magaya-cai-number-honduras 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/.github/workflows/release.yaml +37 -0
  2. package/.vscode/launch.json +18 -0
  3. package/.whitesource +30 -0
  4. package/LICENSE +21 -0
  5. package/README.md +1 -0
  6. package/combined.log +0 -0
  7. package/error.log +0 -0
  8. package/extension.config.json +58 -0
  9. package/index.js +220 -0
  10. package/package.json +56 -0
  11. package/src/integration/helpers/dbHelper.js +12 -0
  12. package/src/integration/helpers/initilize.js +111 -0
  13. package/src/integration/index.js +1053 -0
  14. package/src/integration/jobs/creditmemo.js +155 -0
  15. package/src/integration/jobs/debitnote.js +155 -0
  16. package/src/integration/jobs/invoices.js +176 -0
  17. package/src/integration/jobs/transactionlog.js +65 -0
  18. package/src/util/db/db.js +62 -0
  19. package/src/util/email/email.js +75 -0
  20. package/src/util/email/index.js +124 -0
  21. package/src/util/email/logo/logo.jpg +0 -0
  22. package/src/util/email/settingsEmail.js +33 -0
  23. package/src/util/files/uploadHelper.js +11 -0
  24. package/src/util/gateway.js +23 -0
  25. package/src/util/setting.js +25 -0
  26. package/static/assets/img/honduras-flag-icon.svg +214 -0
  27. package/static/fa-brands-400.eot +0 -0
  28. package/static/fa-brands-400.svg +1100 -0
  29. package/static/fa-brands-400.ttf +0 -0
  30. package/static/fa-brands-400.woff +0 -0
  31. package/static/fa-brands-400.woff2 +0 -0
  32. package/static/fa-regular-400.eot +0 -0
  33. package/static/fa-regular-400.svg +368 -0
  34. package/static/fa-regular-400.ttf +0 -0
  35. package/static/fa-regular-400.woff +0 -0
  36. package/static/fa-regular-400.woff2 +0 -0
  37. package/static/fa-solid-900.eot +0 -0
  38. package/static/fa-solid-900.svg +1892 -0
  39. package/static/fa-solid-900.ttf +0 -0
  40. package/static/fa-solid-900.woff +0 -0
  41. package/static/fa-solid-900.woff2 +0 -0
  42. package/static/favicon.ico +0 -0
  43. package/static/index.html +21 -0
  44. package/static/main.js +2436 -0
  45. package/static/main.js.map +1 -0
  46. package/static/polyfills.js +5793 -0
  47. package/static/polyfills.js.map +1 -0
  48. package/static/runtime.js +154 -0
  49. package/static/runtime.js.map +1 -0
  50. package/static/scripts.js +18 -0
  51. package/static/scripts.js.map +1 -0
  52. package/static/styles.js +776 -0
  53. package/static/styles.js.map +1 -0
  54. package/static/vendor.js +98718 -0
  55. package/static/vendor.js.map +1 -0
@@ -0,0 +1,155 @@
1
+ const dbhelper = require('../helpers/dbHelper');
2
+ const cm = dbhelper.common;
3
+ const hyperion = cm.getHyperionObject();
4
+ const moment = require('moment');
5
+ const email = require('../../util/email/email');
6
+ const sqliteDB = require('../../util/db/db');
7
+ const transactionLog = require('./transactionlog');
8
+
9
+ var db;
10
+ let isRunning = false;
11
+ let timeoutHandle = null;
12
+
13
+ async function setNumber(startDate) {
14
+ try {
15
+
16
+ var todayFormatted = moment(Date.now()).format("YYYY-MM-DD");
17
+ var today = moment(todayFormatted).add(23, 'hours').add(59, 'minutes').add(59, 'seconds').add(999, 'milliseconds');
18
+
19
+ // console.log("Start set number CDM");
20
+
21
+ let query = `SELECT * FROM cdm_settings
22
+ WHERE cdm_settings.active = 1`;
23
+
24
+ var queryResult = await sqliteDB.queryDBAll(db, query);
25
+ let endDate;
26
+
27
+ if (queryResult.length === 1) {
28
+
29
+ if (moment(queryResult[0].packageExpirationDate).add(23, 'hours').add(59, 'minutes').add(59, 'seconds').add(999, 'milliseconds').isBefore(moment())) {
30
+
31
+ subject = 'Notificación de Magaya: Paquete de números CAI de Nota de Crédito';
32
+ body = `El paquete de números CAI para las notas de crédito expiró en la fecha ${moment(queryResult[0].packageExpirationDate).format("DD/MM/YYYY")}. Debe proceder a comprar un paquete CAI nuevo para\r\tcontinuar con la asignación de números CAI en las Nota de Crédito.`;
33
+ if (!queryResult[0].emailNotifiedDate || queryResult[0].emailNotifiedDate === "" || (moment(queryResult[0].emailNotifiedDate).add(23, 'hours').add(59, 'minutes').add(59, 'seconds').add(999, 'milliseconds').isBefore(today))) {
34
+ let emailQuery = `SELECT * FROM email_settings
35
+ WHERE email_settings.active = 1`;
36
+ //console.log("Query para consultar email setting");
37
+ var emailResult = await sqliteDB.queryDBAll(db, emailQuery);
38
+ if (emailResult.length === 1) {
39
+ console.log("Enviando correo");
40
+ let updateQuery = `UPDATE cdm_settings
41
+ SET emailNotifiedDate = '${todayFormatted}',
42
+ emailNotified = 1
43
+ WHERE cai = '${queryResult[0].cai}'`;
44
+ await db.run(updateQuery);
45
+ await email.sendEmail(emailResult[0], subject, body);
46
+ }
47
+ }
48
+ } else if (parseInt((queryResult[0].current) ? queryResult[0].current : queryResult[0].startNumber) >= parseInt(queryResult[0].startNumber) && parseInt((queryResult[0].current) ? queryResult[0].current : queryResult[0].startNumber) < parseInt(queryResult[0].endNumber)) {
49
+ if (moment(queryResult[0].packageExpirationDate).add(23, 'hours').add(59, 'minutes').add(59, 'seconds').add(999, 'milliseconds').isSame(today)) {
50
+
51
+ subject = 'Notificación de Magaya: Paquete de números CAI de Nota de Crédito';
52
+ body = `El paquete de números CAI para las notas de crédito expira hoy ${moment(queryResult[0].packageExpirationDate).format("DD/MM/YYYY")}. Debe proceder a comprar un paquete CAI nuevo para\r\tcontinuar con la asignación de números CAI en las Nota de Crédito.`;
53
+ if (!queryResult[0].emailNotifiedDate || queryResult[0].emailNotifiedDate === "" || (moment(queryResult[0].emailNotifiedDate).add(23, 'hours').add(59, 'minutes').add(59, 'seconds').add(999, 'milliseconds').isBefore(today))) {
54
+ let emailQuery = `SELECT * FROM email_settings
55
+ WHERE email_settings.active = 1`;
56
+ //console.log("Query para consultar email setting");
57
+ var emailResult = await sqliteDB.queryDBAll(db, emailQuery);
58
+ if (emailResult.length === 1) {
59
+ console.log("Enviando correo");
60
+ let updateQuery = `UPDATE cdm_settings
61
+ SET emailNotifiedDate = '${todayFormatted}',
62
+ emailNotified = 1
63
+ WHERE cai = '${queryResult[0].cai}'`;
64
+ await db.run(updateQuery);
65
+ await email.sendEmail(emailResult[0], subject, body);
66
+ }
67
+ }
68
+ }
69
+
70
+ endDate = (moment().toDate()).setMilliseconds(0);
71
+ let transactionList = await transactionLog.getTransactionsModified(
72
+ startDate,
73
+ endDate,
74
+ hyperion,
75
+ 'Nota de Crédito'
76
+ );
77
+ if (transactionList.size > 0) {
78
+ invoiceList = Array.from(transactionList.values()).map(item => item.transObject);
79
+ for (let i = 0; i < invoiceList.length; i++) {
80
+ const invoice = invoiceList[i];
81
+ if (parseInt((queryResult[0].current) ? queryResult[0].current : queryResult[0].startNumber) <= parseInt(queryResult[0].endNumber)) {
82
+ let result = await sqliteDB.queryDBAll(db, `
83
+ SELECT current FROM cdm_settings
84
+ WHERE cai = '${queryResult[0].cai}'
85
+ LIMIT 1
86
+ `);
87
+ let current = parseInt(result[0].current);
88
+
89
+
90
+ await db.run(`
91
+ UPDATE cdm_settings
92
+ SET current = '${current + 1}'
93
+ WHERE cai = '${queryResult[0].cai}'
94
+ `);
95
+
96
+
97
+ await transactionLog.saveCF(invoice, queryResult[0], current, hyperion);
98
+ console.log('Current number Credit Memo', current);
99
+ }
100
+ }
101
+ }
102
+ }
103
+ } else {
104
+ console.log('No se puede procesar, configuracion incorrecta');
105
+ }
106
+ return endDate || startDate;
107
+ } catch (error) {
108
+ let d = new Date();
109
+ console.log(moment(d).format(), error);
110
+ return startDate;
111
+ }
112
+ }
113
+
114
+ async function enqueueWork(startDate) {
115
+ if (!isRunning) {
116
+ console.log("Invoice job stopped, not scheduling new cycle");
117
+ return;
118
+ }
119
+
120
+ if (!db)
121
+ db = await sqliteDB.createConnection();
122
+
123
+ timeoutHandle = setTimeout(async () => {
124
+ try {
125
+ if (!isRunning) return;
126
+
127
+ const newStartDate = await setNumber(startDate);
128
+
129
+ // Schedule next run
130
+ enqueueWork(newStartDate);
131
+ } catch (err) {
132
+ console.error("Invoice job error:", err);
133
+ }
134
+ }, 30000);
135
+ }
136
+
137
+
138
+ async function startCreditMemoJob() {
139
+ if (isRunning) return;
140
+ isRunning = true;
141
+ if (!db) db = await sqliteDB.createConnection();
142
+ enqueueWork(moment().subtract(7, 'days').toDate());
143
+ }
144
+
145
+ function stopCreditMemoJob() {
146
+ isRunning = false;
147
+ if (timeoutHandle) clearTimeout(timeoutHandle);
148
+ }
149
+
150
+ module.exports = {
151
+ startCreditMemoJob,
152
+ stopCreditMemoJob,
153
+ isCreditMemoJobRunning: () => isRunning
154
+ };
155
+
@@ -0,0 +1,155 @@
1
+ const dbhelper = require('../helpers/dbHelper');
2
+ const cm = dbhelper.common;
3
+ const hyperion = cm.getHyperionObject();
4
+ const moment = require('moment');
5
+ const email = require('../../util/email/email');
6
+ const sqliteDB = require('../../util/db/db');
7
+ const transactionLog = require('./transactionlog');
8
+
9
+ var db;
10
+ let isRunning = false;
11
+ let timeoutHandle = null;
12
+
13
+ async function setNumber(startDate) {
14
+ try {
15
+
16
+ var todayFormatted = moment(Date.now()).format("YYYY-MM-DD");
17
+ var today = moment(todayFormatted).add(23, 'hours').add(59, 'minutes').add(59, 'seconds').add(999, 'milliseconds');
18
+
19
+ // console.log("Start set number DBN");
20
+
21
+ let query = `SELECT * FROM dbn_settings
22
+ WHERE dbn_settings.active = 1`;
23
+
24
+ var queryResult = await sqliteDB.queryDBAll(db, query);
25
+ let endDate;
26
+
27
+ if (queryResult.length === 1) {
28
+ if (moment(queryResult[0].packageExpirationDate).add(23, 'hours').add(59, 'minutes').add(59, 'seconds').add(999, 'milliseconds').isBefore(moment())) {
29
+
30
+ subject = 'Notificación de Magaya: Paquete de números CAI de Nota de Débito';
31
+ body = `El paquete de números CAI para las notas de débito expiró en la fecha ${moment(queryResult[0].packageExpirationDate).format("DD/MM/YYYY")}. Debe proceder a comprar un paquete CAI nuevo para\r\tcontinuar con la asignación de números CAI en las Nota de Débito.`;
32
+ if (!queryResult[0].emailNotifiedDate || queryResult[0].emailNotifiedDate === "" || (moment(queryResult[0].emailNotifiedDate).add(23, 'hours').add(59, 'minutes').add(59, 'seconds').add(999, 'milliseconds').isBefore(today))) {
33
+ let emailQuery = `SELECT * FROM email_settings
34
+ WHERE email_settings.active = 1`;
35
+ //console.log("Query para consultar email setting");
36
+ var emailResult = await sqliteDB.queryDBAll(db, emailQuery);
37
+ if (emailResult.length === 1) {
38
+ console.log("Enviando correo");
39
+ let updateQuery = `UPDATE dbn_settings
40
+ SET emailNotifiedDate = '${todayFormatted}',
41
+ emailNotified = 1
42
+ WHERE cai = '${queryResult[0].cai}'`;
43
+ await db.run(updateQuery);
44
+ await email.sendEmail(emailResult[0], subject, body);
45
+ }
46
+ }
47
+ } else if (parseInt((queryResult[0].current) ? queryResult[0].current : queryResult[0].startNumber) >= parseInt(queryResult[0].startNumber) && parseInt((queryResult[0].current) ? queryResult[0].current : queryResult[0].startNumber) < parseInt(queryResult[0].endNumber)) {
48
+ if (moment(queryResult[0].packageExpirationDate).add(23, 'hours').add(59, 'minutes').add(59, 'seconds').add(999, 'milliseconds').isSame(today)) {
49
+
50
+ subject = 'Notificación de Magaya: Paquete de números CAI de Nota de Débito';
51
+ body = `El paquete de números CAI para las notas de débito expira hoy ${moment(queryResult[0].packageExpirationDate).format("DD/MM/YYYY")}. Debe proceder a comprar un paquete CAI nuevo para\r\tcontinuar con la asignación de números CAI en las Nota de Débito.`;
52
+ if (!queryResult[0].emailNotifiedDate || queryResult[0].emailNotifiedDate === "" || (moment(queryResult[0].emailNotifiedDate).add(23, 'hours').add(59, 'minutes').add(59, 'seconds').add(999, 'milliseconds').isBefore(today))) {
53
+ let emailQuery = `SELECT * FROM email_settings
54
+ WHERE email_settings.active = 1`;
55
+ //console.log("Query para consultar email setting");
56
+ var emailResult = await sqliteDB.queryDBAll(db, emailQuery);
57
+ if (emailResult.length === 1) {
58
+ console.log("Enviando correo");
59
+ let updateQuery = `UPDATE dbn_settings
60
+ SET emailNotifiedDate = '${todayFormatted}',
61
+ emailNotified = 1
62
+ WHERE cai = '${queryResult[0].cai}'`;
63
+ await db.run(updateQuery);
64
+ await email.sendEmail(emailResult[0], subject, body);
65
+ }
66
+ }
67
+ }
68
+
69
+ endDate = (moment().toDate()).setMilliseconds(0);
70
+ let transactionList = await transactionLog.getTransactionsModified(
71
+ startDate,
72
+ endDate,
73
+ hyperion,
74
+ 'Nota de Débito'
75
+ );
76
+ if (transactionList.size > 0) {
77
+ invoiceList = Array.from(transactionList.values()).map(item => item.transObject);
78
+ for (let i = 0; i < invoiceList.length; i++) {
79
+ const invoice = invoiceList[i];
80
+ if (parseInt((queryResult[0].current) ? queryResult[0].current : queryResult[0].startNumber) <= parseInt(queryResult[0].endNumber)) {
81
+ let result = await sqliteDB.queryDBAll(db, `
82
+ SELECT current FROM dbn_settings
83
+ WHERE cai = '${queryResult[0].cai}'
84
+ LIMIT 1
85
+ `);
86
+ let current = parseInt(result[0].current);
87
+
88
+
89
+ await db.run(`
90
+ UPDATE dbn_settings
91
+ SET current = '${current + 1}'
92
+ WHERE cai = '${queryResult[0].cai}'
93
+ `);
94
+
95
+
96
+ await transactionLog.saveCF(invoice, queryResult[0], current, hyperion);
97
+ console.log('Current number Debit Note', current);
98
+ }
99
+ }
100
+ }
101
+
102
+ }
103
+ } else {
104
+ console.log('No se puede procesar, configuracion incorrecta');
105
+ }
106
+ return endDate || startDate;
107
+ } catch (error) {
108
+ let d = new Date();
109
+ console.log(moment(d).format(), error);
110
+ return startDate
111
+ }
112
+ }
113
+
114
+
115
+ async function enqueueWork(startDate) {
116
+ if (!isRunning) {
117
+ console.log("Invoice job stopped, not scheduling new cycle");
118
+ return;
119
+ }
120
+
121
+ if (!db)
122
+ db = await sqliteDB.createConnection();
123
+
124
+ timeoutHandle = setTimeout(async () => {
125
+ try {
126
+ if (!isRunning) return;
127
+
128
+ const newStartDate = await setNumber(startDate);
129
+
130
+ // Schedule next run
131
+ enqueueWork(newStartDate);
132
+ } catch (err) {
133
+ console.error("Invoice job error:", err);
134
+ }
135
+ }, 30000);
136
+ }
137
+
138
+ async function startDebitNoteJob() {
139
+ if (isRunning) return;
140
+ isRunning = true;
141
+ if (!db) db = await sqliteDB.createConnection();
142
+ enqueueWork(moment().subtract(7, 'days').toDate());
143
+ }
144
+
145
+ function stopDebitNoteJob() {
146
+ isRunning = false;
147
+ if (timeoutHandle) clearTimeout(timeoutHandle);
148
+ }
149
+
150
+ module.exports = {
151
+ startDebitNoteJob,
152
+ stopDebitNoteJob,
153
+ isDebitNoteJobRunning: () => isRunning
154
+ };
155
+
@@ -0,0 +1,176 @@
1
+ const dbhelper = require('../helpers/dbHelper');
2
+ const cm = dbhelper.common;
3
+ const hyperion = cm.getHyperionObject();
4
+ const moment = require('moment');
5
+ const email = require('../../util/email/email');
6
+ const sqliteDB = require('../../util/db/db');
7
+ const transactionLog = require('./transactionlog');
8
+
9
+ var db;
10
+ let isRunning = false;
11
+ let timeoutHandle = null;
12
+
13
+ async function setNumber(startDate) {
14
+ try {
15
+
16
+ var todayFormatted = moment(Date.now()).format("YYYY-MM-DD");
17
+ var today = moment(todayFormatted).add(23, 'hours').add(59, 'minutes').add(59, 'seconds').add(999, 'milliseconds');
18
+
19
+ // console.log("Start set number INV");
20
+
21
+ let query = `SELECT * FROM invoice_settings
22
+ WHERE invoice_settings.active = 1`;
23
+
24
+ var queryResult = await sqliteDB.queryDBAll(db, query);
25
+ let endDate;
26
+
27
+ if (queryResult.length === 1) {
28
+ if (moment(queryResult[0].packageExpirationDate).add(23, 'hours').add(59, 'minutes').add(59, 'seconds').add(999, 'milliseconds').isBefore(moment())) {
29
+
30
+ subject = 'Notificación de Magaya: Paquete de números CAI de Facturas';
31
+ body = `El paquete de números CAI para las facturas de cobro expiró en la fecha ${moment(queryResult[0].packageExpirationDate).format("DD/MM/YYYY")}. Debe proceder a comprar un paquete CAI nuevo para\r\tcontinuar con la asignación de números CAI en las facturas.`;
32
+ if (!queryResult[0].emailNotifiedDate || queryResult[0].emailNotifiedDate === "" || (moment(queryResult[0].emailNotifiedDate).add(23, 'hours').add(59, 'minutes').add(59, 'seconds').add(999, 'milliseconds').isBefore(today))) {
33
+ let emailQuery = `SELECT * FROM email_settings
34
+ WHERE email_settings.active = 1`;
35
+ //console.log("Query para consultar email setting");
36
+ var emailResult = await sqliteDB.queryDBAll(db, emailQuery);
37
+ if (emailResult.length === 1) {
38
+ console.log("Enviando correo");
39
+ let updateQuery = `UPDATE invoice_settings
40
+ SET emailNotifiedDate = '${todayFormatted}',
41
+ emailNotified = 1
42
+ WHERE cai = '${queryResult[0].cai}'`;
43
+ await db.run(updateQuery);
44
+ await email.sendEmail(emailResult[0], subject, body);
45
+ }
46
+ }
47
+ } else if (parseInt((queryResult[0].current) ? queryResult[0].current : queryResult[0].startNumber) >= parseInt(queryResult[0].startNumber) && parseInt((queryResult[0].current) ? queryResult[0].current : queryResult[0].startNumber) < parseInt(queryResult[0].endNumber)) {
48
+ if (moment(queryResult[0].packageExpirationDate).add(23, 'hours').add(59, 'minutes').add(59, 'seconds').add(999, 'milliseconds').isSame(today)) {
49
+
50
+ subject = 'Notificación de Magaya: Paquete de números CAI de Facturas';
51
+ body = `El paquete de números CAI para las factura expira hoy ${moment(queryResult[0].packageExpirationDate).format("DD/MM/YYYY")}. Debe proceder a comprar un paquete CAI nuevo para\r\tcontinuar con la asignación de números CAI en las facturas.`;
52
+ if (!queryResult[0].emailNotifiedDate || queryResult[0].emailNotifiedDate === "" || (moment(queryResult[0].emailNotifiedDate).add(23, 'hours').add(59, 'minutes').add(59, 'seconds').add(999, 'milliseconds').isBefore(today))) {
53
+ let emailQuery = `SELECT * FROM email_settings
54
+ WHERE email_settings.active = 1`;
55
+ //console.log("Query para consultar email setting");
56
+ var emailResult = await sqliteDB.queryDBAll(db, emailQuery);
57
+ if (emailResult.length === 1) {
58
+ console.log("Enviando correo");
59
+ let updateQuery = `UPDATE invoice_settings
60
+ SET emailNotifiedDate = '${todayFormatted}',
61
+ emailNotified = 1
62
+ WHERE cai = '${queryResult[0].cai}'`;
63
+ await db.run(updateQuery);
64
+ await email.sendEmail(emailResult[0], subject, body);
65
+ }
66
+ }
67
+ }
68
+
69
+ if (queryResult[0].emailNotified === 0 && (queryResult[0].endNumber - queryResult[0].current) <= queryResult[0].packageEmailNotificationNumber) {
70
+
71
+ subject = 'Notificación de Magaya: Paquete de números CAI de Facturas';
72
+ body = `El paquete de números CAI para las factura está próximo a agotarse. El valor actual es ${queryResult[0].current} y el número final\tes ${queryResult[0].endNumber}, debe proceder a comprar un paquete CAI nuevo.`;
73
+ if (!queryResult[0].emailNotifiedDate || queryResult[0].emailNotifiedDate === "" || (moment(queryResult[0].emailNotifiedDate).add(23, 'hours').add(59, 'minutes').add(59, 'seconds').add(999, 'milliseconds').isBefore(today))) {
74
+ let emailQuery = `SELECT * FROM email_settings WHERE email_settings.active = 1`;
75
+ //console.log("Query para consultar email setting");
76
+ var emailResult = await sqliteDB.queryDBAll(db, emailQuery);
77
+ if (emailResult.length === 1) {
78
+ console.log("Enviando correo");
79
+ let updateQuery = `UPDATE invoice_settings SET emailNotifiedDate = '${todayFormatted}',emailNotified = 1 WHERE cai = '${queryResult[0].cai}'`;
80
+ await db.run(updateQuery);
81
+ await email.sendEmail(emailResult[0], subject, body);
82
+ }
83
+ }
84
+ }
85
+
86
+ endDate = (moment().toDate()).setMilliseconds(0);
87
+ let transactionList = await transactionLog.getTransactionsModified(
88
+ startDate,
89
+ endDate,
90
+ hyperion,
91
+ 'Factura de Cobro'
92
+ );
93
+ if (transactionList.size > 0) {
94
+ invoiceList = Array.from(transactionList.values()).map(item => item.transObject);
95
+ for (let i = 0; i < invoiceList.length; i++) {
96
+ const invoice = invoiceList[i];
97
+ if (parseInt((queryResult[0].current) ? queryResult[0].current : queryResult[0].startNumber) <= parseInt(queryResult[0].endNumber)) {
98
+ let result = await sqliteDB.queryDBAll(db, `
99
+ SELECT current FROM invoice_settings
100
+ WHERE cai = '${queryResult[0].cai}'
101
+ LIMIT 1
102
+ `);
103
+ let current = parseInt(result[0].current);
104
+
105
+
106
+ await db.run(`
107
+ UPDATE invoice_settings
108
+ SET current = '${current + 1}'
109
+ WHERE cai = '${queryResult[0].cai}'
110
+ `);
111
+
112
+
113
+ await transactionLog.saveCF(invoice, queryResult[0], current, hyperion);
114
+ console.log('Current number Invoice', current);
115
+ }
116
+ }
117
+ }
118
+
119
+
120
+ }
121
+ } else {
122
+ console.log('No se puede procesar, configuracion incorrecta');
123
+ }
124
+ return endDate || startDate;
125
+ } catch (error) {
126
+ let d = new Date();
127
+ console.log(moment(d).format(), error);
128
+ return startDate;
129
+ }
130
+ }
131
+ async function enqueueWork(startDate) {
132
+ if (!isRunning) {
133
+ console.log("Invoice job stopped, not scheduling new cycle");
134
+ return;
135
+ }
136
+
137
+ if (!db)
138
+ db = await sqliteDB.createConnection();
139
+
140
+ timeoutHandle = setTimeout(async () => {
141
+ try {
142
+ if (!isRunning) return;
143
+
144
+ const newStartDate = await setNumber(startDate);
145
+
146
+ // Schedule next run
147
+ enqueueWork(newStartDate);
148
+ } catch (err) {
149
+ console.error("Invoice job error:", err);
150
+ }
151
+ }, 30000);
152
+ }
153
+
154
+
155
+ async function startInvoiceJob() {
156
+ if (isRunning) return;
157
+ isRunning = true;
158
+ if (!db) db = await sqliteDB.createConnection();
159
+ enqueueWork(moment().subtract(7, 'days').toDate());
160
+ }
161
+
162
+ function stopInvoiceJob() {
163
+ console.log("Stopping invoice job...");
164
+ isRunning = false;
165
+ if (timeoutHandle) {
166
+ clearTimeout(timeoutHandle);
167
+ timeoutHandle = null;
168
+ }
169
+ }
170
+
171
+
172
+ module.exports = {
173
+ startInvoiceJob,
174
+ stopInvoiceJob,
175
+ isInvoiceJobRunning: () => isRunning
176
+ };
@@ -0,0 +1,65 @@
1
+ const moment = require('moment');
2
+
3
+ // 🧩 Fetch transactions modified in a time window (creation or edition)
4
+ async function getTransactionsModified(start, end, hyperion, desiredTransactionType) {
5
+ const { dbx, algorithm } = hyperion;
6
+ const results = new Map();
7
+
8
+ try {
9
+ const logListByTime = dbx.Log.ListByTime;
10
+
11
+ await algorithm.forEach(dbx.using(logListByTime).from(start).to(end))
12
+ .callback(record => {
13
+ const isCreateOrEdit =
14
+ record.EntryType & (dbx.Log.EntryType.Creation | dbx.Log.EntryType.Edition);
15
+ const obj = record.Object;
16
+ if (!isCreateOrEdit || !obj || obj.DbClassType !== dbx.Common.DbClassType.Invoice) return;
17
+
18
+ if (!(obj.CustomFields.numero_cai) && obj.CustomFields.numero_cai === '' && obj.CustomFields.tipo_documento === desiredTransactionType)
19
+ results.set(obj.GUID, {
20
+ transObject: obj
21
+ });
22
+ });
23
+
24
+ return results;
25
+ } catch (error) {
26
+ console.error('❌ Error in getTransactionsModified:', error);
27
+ LOGGER?.addLogEntry('ERROR', `${error}`, 'ERROR');
28
+ return new Map();
29
+ }
30
+ }
31
+ async function saveCF(invoice, cursorObject, current, hyperion) {
32
+ let interface = await hyperion.dbw.edit(invoice);
33
+ interface.CustomFields['rango'] = cursorObject.range;
34
+ interface.CustomFields['fecha_limite'] = moment(cursorObject.packageExpirationDate).format("DD/MM/YYYY");
35
+ interface.CustomFields['numero_documento'] = `${cursorObject.firstPartDocumentNumber}-${completeSequence(current)}`;
36
+ interface.CustomFields['numero_cai'] = cursorObject.cai;
37
+ await hyperion.dbw.save(interface);
38
+ }
39
+
40
+ function completeSequence(value) {
41
+
42
+ var seq = value.toString();
43
+ var count = seq.length;
44
+
45
+ if (count === 1)
46
+ return `0000000${value}`;
47
+ if (count === 2)
48
+ return `000000${value}`;
49
+ if (count === 3)
50
+ return `00000${value}`;
51
+ if (count === 4)
52
+ return `0000${value}`;
53
+ if (count === 5)
54
+ return `000${value}`;
55
+ if (count === 6)
56
+ return `00${value}`;
57
+ if (count === 7)
58
+ return `0${value}`;
59
+ if (count === 8)
60
+ return value;
61
+ }
62
+ module.exports = {
63
+ getTransactionsModified,
64
+ saveCF
65
+ };
@@ -0,0 +1,62 @@
1
+ const path = require('path');
2
+ const fsHelper = require('@magaya/extension-fs-helper');
3
+ const extConfigJson = require('../../../extension.config.json');
4
+ // const program = require('commander');
5
+ const { program } = require('commander');
6
+ const packageJson = require('../../../package.json');
7
+
8
+ // const configFolder = fsHelper.GetExtensionDataFolder({
9
+ // "company": "magaya",
10
+ // "name": "cai"
11
+ // }, (process.networkId) ? process.networkId : process.argv[process.argv.length - 2]);
12
+
13
+ //Require databa sqlite
14
+ const sqlite = require('sqlite');
15
+ const sqlite3 = require('sqlite3');
16
+
17
+ const Promise = require('bluebird');
18
+
19
+ if (!program._version) {
20
+ program
21
+ .version(packageJson.version)
22
+ .option("-p, --port <n>", "running port", parseInt)
23
+ .option("-r, --root <value>", "startup root for api")
24
+ .option("-s, --service-name <value>", "name for service")
25
+ .option("-g, --gateway", "dictates if we should be through gateway")
26
+ .option("-i, --network-id <n>", "magaya network id", parseInt)
27
+ .option("--connection-string <value>", "connection endpoint for database")
28
+ .option("--no-daemon", "pm2 no daemon option")
29
+ .parse(process.argv);
30
+ }
31
+
32
+ const options = program.opts();
33
+ const configFolder = fsHelper.GetExtensionDataFolder(extConfigJson.id, options.networkId);
34
+
35
+ const dbPromise = sqlite.open({
36
+ filename: path.join(configFolder, 'setting.db'),
37
+ driver: sqlite3.Database
38
+ });
39
+
40
+ module.exports = {
41
+ createConnection: async function () {
42
+ return await dbPromise;
43
+ },
44
+ queryDBAll: async function (db, query) {
45
+ var dbInstance;
46
+ if (!db)
47
+ dbInstance = await this.createConnection();
48
+ else
49
+ dbInstance = db;
50
+
51
+ return await Promise.all(dbInstance.all(query));
52
+ },
53
+ queryDBGet: async function (db, query) {
54
+ var dbInstance;
55
+ if (!db)
56
+ dbInstance = await this.createConnection();
57
+ else
58
+ dbInstance = db;
59
+
60
+ return await Promise.all(db.get(query));
61
+ }
62
+ }