All files / crons index.js

20.53% Statements 23/112
0% Branches 0/57
0% Functions 0/25
22.77% Lines 23/101

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261            1x 1x 1x 1x 1x 1x   1x 1x 1x 1x           1x                                                                                             1x   1x                                                                     1x                                                                                                                           1x                                                           1x                             1x           1x 1x 1x 1x                   1x                                     1x                  
/* eslint-disable no-use-before-define */
/* eslint-disable no-throw-literal */
/* eslint-disable no-plusplus */
/* eslint-disable no-empty */
// CRON JOBS - DOCUMENTATION: https://github.com/breejs/bree
 
const Bree = require('bree');
const path = require('path');
const winston = require('winston');
const { Worker } = require('worker_threads');
const { default: config } = require('../../config/config');
const { default: I18n } = require('../helpers/i18n');
 
const pathJobs = path.resolve(__dirname, 'jobs');
const logFile = path.resolve(__dirname, 'logs/logs.txt');
let cronsModel = null;
let bree = null;
 
// ######## JOBS DEVERAO SER CADASTRADOS AQUI ############################################
// ######## NAME DEVERA SER UNICO ASSIM COMO CADA ARQUIVO JS #############################
// AGENDAMENTOS DE JOBS ESTARAO NO BANCO DE DADOS OS JOBS EM SI ESTARAO CADASTRADOS AQUI
// TABELA DE CRONS (bee_crons)
const jobs = [
  // Exemplo
  // {
  //   name: 'example', // Script do job, esta na pasta /server/crons/jobs
  //   timeout: false, // timeout: false = desabilitado
  //   description: 'Example job for print' or I18n.t() // Descricao do job
  // },
  {
    name: 'reportDelete',
    timeout: false,
    description: () =>
      I18n.t(
        'BEE2561' /* Deleta relatórios que foram baixados através do segundo plano. Para manutenção de espaço em disco do servidor. */
      ),
  },
  {
    name: 'checkExpirationDate',
    timeout: false,
    description: () => I18n.t('BEE2231' /* Bloqueia itens vencidos */),
  },
  {
    name: 'pendingQueues',
    timeout: false,
    description: () => I18n.t('BEE3225' /* Integração de Fila de Integração */),
  },
  {
    name: 'getStockBalanceErp',
    timeout: false,
    description: () => I18n.t('BEE3226' /* Busca Saldo de Estoque no ERP */),
  },
  {
    name: 'generateResupply',
    timeout: false,
    description: () => I18n.t('BEE2714' /* Regra de ressuprimento */),
  },
  {
    name: 'automaticAllocation',
    timeout: false,
    description: () => I18n.t('BEE2956' /* Alocação automática */),
  },
  {
    name: 'finishUsersTimeTrack',
    timeout: false,
    description: () => I18n.t('BEE4299' /* Encerra apontamentos em aberto */),
  },
];
// #######################################################################################
const jobsDefined = [...jobs]; // usado para gravacao de estado inicial dos jobs
 
const WinstonLoggerJobs = winston.createLogger({
  transports: [
    new winston.transports.Console({
      format: winston.format.combine(
        winston.format.timestamp(),
        winston.format.align(),
        winston.format.errors(),
        winston.format.printf((info) => {
          const { timestamp, level, message = '', stack } = info;
 
          return `${timestamp} ${level}: ${message.trim()} ${
            stack ? `\n${stack}` : ''
          }`;
        }),
        winston.format.colorize({ all: true })
      ),
    }),
    new winston.transports.File({
      filename: logFile,
      format: winston.format.combine(
        winston.format.timestamp(),
        winston.format.align(),
        winston.format.errors(),
        winston.format.printf((info) => {
          const { timestamp, level, message = '', stack } = info;
 
          return `${timestamp} ${level}: ${message.trim()} ${
            stack ? `\n${stack}` : ''
          }`;
        })
      ),
    }),
  ],
});
 
const updateCronsToJob = (crons = []) => {
  let jobDisabled = false;
  for (let index = 0; index < jobs.length; index++) {
    if (typeof jobs[index].description === 'function') {
      jobs[index].description = jobs[index].description();
    }
    const findedCronIndex = crons.findIndex(
      (cron) => cron.name === jobs[index].name
    );
    jobDisabled = false;
 
    if (findedCronIndex !== -1) {
      const jobUpdate = {};
      let hasTimers = false;
 
      if (crons[findedCronIndex].id) jobUpdate.id = crons[findedCronIndex].id;
      if (crons[findedCronIndex].cron) {
        jobUpdate.cron = crons[findedCronIndex].cron;
        hasTimers = true;
      } else {
        if (crons[findedCronIndex].date) {
          jobUpdate.date = crons[findedCronIndex].date;
          hasTimers = true;
        }
        if (crons[findedCronIndex].interval) {
          jobUpdate.interval = crons[findedCronIndex].interval;
          hasTimers = true;
        }
      }
      if (crons[findedCronIndex].jsonParams)
        jobUpdate.jsonParams = crons[findedCronIndex].jsonParams;
      if (crons[findedCronIndex].updatedUser)
        jobUpdate.updatedUser = crons[findedCronIndex].updatedUser;
      if (crons[findedCronIndex].updatedAt)
        jobUpdate.updatedAt = crons[findedCronIndex].updatedAt;
 
      // Habilitada para iniciar
      if (Object.keys(jobUpdate) && hasTimers) {
        jobs[index] = {
          ...jobUpdate,
          name: jobs[index].name,
          timezone: config.timezone || 'America/Sao_Paulo',
        };
      } else {
        jobDisabled = true;
      }
    } else {
      jobDisabled = true;
    }
 
    if (jobDisabled) {
      // Job Default atribuido caso nao exista cron a ser atualizada
      const jbDef = jobsDefined.find(
        (jobDef) => jobDef.name === jobs[index].name
      );
      jobs[index] = jbDef
        ? { ...jbDef }
        : { name: jobs[index].name, timeout: false };
    }
  }
};
 
const initJobs = async (models = {}) => {
  if (!cronsModel) cronsModel = models.Crons;
 
  if (cronsModel) {
    const crons = await cronsModel.findAll({
      where: { enabled: true },
      raw: true,
    });
    updateCronsToJob(crons);
  } else {
    throw 'Failed Init JOBS';
  }
 
  try {
    if (bree) removeJobs();
 
    bree = new Bree({
      logger: WinstonLoggerJobs,
      root: pathJobs,
      jobs,
      workerMessageHandler: workerMessage,
    });
 
    if (config.env === 'development') return; // Em desenv nao inicia os jobs
    bree.start();
  } catch (e) {
    WinstonLoggerJobs.error(e.message);
  }
};
 
const workerMessage = (workerMessageParam) => {
  try {
    if (workerMessageParam.message === 'done') {
      WinstonLoggerJobs.info(
        `Worker for job ${workerMessageParam.name} signaled completion done`
      );
 
      if (workerMessageParam.resolve) workerMessageParam.resolve(true);
    } else {
      WinstonLoggerJobs.warn(
        `Worker [${workerMessageParam.name}]: ${workerMessageParam.message}`
      );
    }
  } catch (e) {}
};
const removeJobs = () =>
  jobsDefined.forEach((it) => {
    try {
      if (bree) bree.remove(it.name);
    } catch (e) {}
  });
const reloadJobs = (models) => initJobs(models);
const getJobs = () => jobs;
const getJobsDefined = () => jobsDefined;
const runJob = async (name = '') => {
  const jobFinded = jobsDefined.find((it) => it.name === name);
  if (jobFinded && bree) {
    try {
      await bree.stop(name);
    } catch (e) {}
    bree.run(name);
  }
};
 
const runReportAsBackground = (workerData) => {
  return new Promise((resolve, reject) => {
    const worker = new Worker(path.resolve(pathJobs, 'reports.js'), {
      workerData,
    });
    worker.on('message', (message) =>
      workerMessage({ name: 'REPORTS', message, resolve })
    );
    worker.on('error', reject);
    worker.on('exit', (code) => {
      if (code !== 0) {
        reject(new Error(`Worker stopped with exit code ${code}`));
      } else {
        resolve(true);
      }
    });
  });
};
 
module.exports = {
  runJob,
  getJobs,
  initJobs,
  reloadJobs,
  WinstonLoggerJobs,
  getJobsDefined,
  runReportAsBackground,
};