HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux spn-python 5.15.0-89-generic #99-Ubuntu SMP Mon Oct 30 20:42:41 UTC 2023 x86_64
User: arjun (1000)
PHP: 8.1.2-1ubuntu2.20
Disabled: NONE
Upload Files
File: //home/arjun/projects/good-life-be/helper/eventUpdation.js
import { Op, Sequelize } from 'sequelize';
import moment from 'moment-timezone';
import User from '../models/User.js';
import Event from '../models/Event.js';
import EventCount from '../models/eventsCount.js';
import FormData from '../models/formDataModel.js';

const usersEventsFailureCron = async () => {
  try {
    const pendingUsers = await User.findAll({
      attributes: ['id'],
      where: { status: 'active', eventStatus: 'pending' },
      raw: true,
    });

    if (pendingUsers.length === 0) {
      console.log('No pending users found.');
      return;
    }

    const userIds = pendingUsers.map((user) => user.id);

    // Check EventCount table where eventStatus is 'pending'
    const eventCounts = await EventCount.findAll({
      attributes: ['user_id'],
      where: {
        user_id: { [Op.in]: userIds },
        eventStatus: 'pending',
      },
      raw: true,
    });

    if (eventCounts.length === 0) {
      console.log('No matching event counts found.');
      return;
    }

    const matchingUserIds = eventCounts.map((event) => event.user_id);

    const processingFormData = await FormData.findAll({
      attributes: ['user_id'],
      where: {
        user_id: { [Op.in]: matchingUserIds },
        status: 'processing',
      },
      raw: true,
    });

    if (processingFormData.length === 0) {
      console.log('No processing form data found.');
      return;
    }

    const processingUserIds = processingFormData.map((form) => form.user_id);

    // Check Event table where createdAt is older than 15 minutes
    const fifteenMinutesAgo = moment()
      .utc()
      .subtract(15, 'minutes')
      .toISOString();

    const oldEvents = await Event.findAll({
      attributes: [
        'user_id',
        [Sequelize.fn('MAX', Sequelize.col('createdAt')), 'latestEvent'],
      ],
      where: {
        user_id: { [Op.in]: processingUserIds },
      },
      group: ['user_id'],
      having: Sequelize.literal(`MAX("createdAt") < '${fifteenMinutesAgo}'`),
      raw: true,
    });

    if (oldEvents.length === 0) {
      console.log('No matching old events found.');
      return;
    }

    const finalUserIds = oldEvents.map((event) => event.user_id);

    console.log('finalUserIds', finalUserIds);

    await Event.destroy({
      where: { user_id: { [Op.in]: finalUserIds } },
    });

    await FormData.update(
      { status: 'pending' },
      { where: { user_id: { [Op.in]: finalUserIds } } }
    );

    console.log(
      `Updated FormData status to 'pending' for users: ${finalUserIds.length}`
    );

    await EventCount.update(
      { eventStatus: 'pending', count: 0 },
      { where: { user_id: { [Op.in]: finalUserIds } } }
    );

    console.log(`Deleted all events for users: ${finalUserIds.length}`);
  } catch (error) {
    console.error('Error in cron job:', error);
  }
};

export default usersEventsFailureCron;