backfillErpProtocoloSup.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import "dotenv/config";
  2. import { config } from "../src/config/index.js";
  3. import { Atendimento } from "../src/models/Atendimento.model.js";
  4. import { importarProtocolo } from "../src/services/atendimentosService.js";
  5. const limiteIdx = process.argv.indexOf("--limite");
  6. const LIMITE = limiteIdx > -1 ? Number(process.argv[limiteIdx + 1]) : null;
  7. const CONCORRENCIA = 4;
  8. async function main() {
  9. let query = Atendimento.query()
  10. .where("Setor", "SUP")
  11. .withGraphFetched("cliente")
  12. .orderBy("Abertura", "desc");
  13. if (LIMITE) query = query.limit(LIMITE);
  14. const atendimentos = await query;
  15. const total = atendimentos.length;
  16. console.log(`[backfill-erp-sup] iniciando: ${total} atendimentos SUP`);
  17. const baseUrl = config.ifbot.baseUrl.replace(/\/+$/, "");
  18. let processados = 0;
  19. let comVinculo = 0;
  20. let erros = 0;
  21. const t0 = Date.now();
  22. async function processar(a) {
  23. try {
  24. const item = {
  25. Id: a.Id,
  26. Codigo: a.Codigo,
  27. Abertura: a.Abertura,
  28. Cliente: { Id: a.cliente?.Id, Nome: a.cliente?.Nome, Telefone: a.cliente?.Telefone }
  29. };
  30. await importarProtocolo(item, baseUrl);
  31. const atualizado = await Atendimento.query()
  32. .findById(a.Id)
  33. .withGraphFetched("cliente(soVinculo)")
  34. .modifiers({ soVinculo: (q) => q.select("ErpVinculoConfirmadoEm") });
  35. if (atualizado?.cliente?.ErpVinculoConfirmadoEm) comVinculo += 1;
  36. } catch (err) {
  37. erros += 1;
  38. console.warn(`[backfill-erp-sup] erro em ${a.Codigo}: ${err.message}`);
  39. } finally {
  40. processados += 1;
  41. if (processados % 50 === 0 || processados === total) {
  42. const decorridoS = Math.round((Date.now() - t0) / 1000);
  43. console.log(
  44. `[backfill-erp-sup] progresso: ${processados}/${total} | com vínculo: ${comVinculo} | erros: ${erros} | ${decorridoS}s decorridos`
  45. );
  46. }
  47. }
  48. }
  49. let idx = 0;
  50. async function worker() {
  51. while (idx < atendimentos.length) {
  52. const a = atendimentos[idx++];
  53. await processar(a);
  54. }
  55. }
  56. await Promise.all(Array.from({ length: CONCORRENCIA }, worker));
  57. const totalS = Math.round((Date.now() - t0) / 1000);
  58. console.log(
  59. `[backfill-erp-sup] concluído: ${processados}/${total} | com vínculo: ${comVinculo} | erros: ${erros} | ${totalS}s total`
  60. );
  61. process.exit(0);
  62. }
  63. main().catch((err) => {
  64. console.error("[backfill-erp-sup] falha fatal:", err);
  65. process.exit(1);
  66. });