@cloudcommerce/app-tiny-erp 0.0.59 → 0.0.62

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 (54) hide show
  1. package/.turbo/turbo-build.log +30 -4
  2. package/lib/event-to-tiny.js +117 -0
  3. package/lib/event-to-tiny.js.map +1 -0
  4. package/lib/index.js +2 -0
  5. package/lib/index.js.map +1 -0
  6. package/lib/integration/after-tiny-queue.js +79 -0
  7. package/lib/integration/after-tiny-queue.js.map +1 -0
  8. package/lib/integration/export-order-to-tiny.js +81 -0
  9. package/lib/integration/export-order-to-tiny.js.map +1 -0
  10. package/lib/integration/export-product-to-tiny.js +58 -0
  11. package/lib/integration/export-product-to-tiny.js.map +1 -0
  12. package/lib/integration/helpers/format-tiny-date.js +7 -0
  13. package/lib/integration/helpers/format-tiny-date.js.map +1 -0
  14. package/lib/integration/import-order-from-tiny.js +92 -0
  15. package/lib/integration/import-order-from-tiny.js.map +1 -0
  16. package/lib/integration/import-product-from-tiny.js +158 -0
  17. package/lib/integration/import-product-from-tiny.js.map +1 -0
  18. package/lib/integration/parsers/order-from-tiny.js +46 -0
  19. package/lib/integration/parsers/order-from-tiny.js.map +1 -0
  20. package/lib/integration/parsers/order-to-tiny.js +193 -0
  21. package/lib/integration/parsers/order-to-tiny.js.map +1 -0
  22. package/lib/integration/parsers/product-from-tiny.js +199 -0
  23. package/lib/integration/parsers/product-from-tiny.js.map +1 -0
  24. package/lib/integration/parsers/product-to-tiny.js +129 -0
  25. package/lib/integration/parsers/product-to-tiny.js.map +1 -0
  26. package/lib/integration/parsers/status-from-tiny.js +34 -0
  27. package/lib/integration/parsers/status-from-tiny.js.map +1 -0
  28. package/lib/integration/parsers/status-to-tiny.js +39 -0
  29. package/lib/integration/parsers/status-to-tiny.js.map +1 -0
  30. package/lib/integration/post-tiny-erp.js +47 -0
  31. package/lib/integration/post-tiny-erp.js.map +1 -0
  32. package/lib/tiny-erp.js +17 -0
  33. package/lib/tiny-erp.js.map +1 -0
  34. package/lib/tiny-webhook.js +92 -0
  35. package/lib/tiny-webhook.js.map +1 -0
  36. package/package.json +13 -6
  37. package/src/event-to-tiny.ts +136 -0
  38. package/src/index.ts +1 -0
  39. package/src/integration/after-tiny-queue.ts +80 -0
  40. package/src/integration/export-order-to-tiny.ts +86 -0
  41. package/src/integration/export-product-to-tiny.ts +60 -0
  42. package/src/integration/helpers/format-tiny-date.ts +6 -0
  43. package/src/integration/import-order-from-tiny.ts +102 -0
  44. package/src/integration/import-product-from-tiny.ts +162 -0
  45. package/src/integration/parsers/order-from-tiny.ts +49 -0
  46. package/src/integration/parsers/order-to-tiny.ts +205 -0
  47. package/src/integration/parsers/product-from-tiny.ts +215 -0
  48. package/src/integration/parsers/product-to-tiny.ts +138 -0
  49. package/src/integration/parsers/status-from-tiny.ts +35 -0
  50. package/src/integration/parsers/status-to-tiny.ts +42 -0
  51. package/src/integration/post-tiny-erp.ts +52 -0
  52. package/src/tiny-erp.ts +23 -0
  53. package/src/tiny-webhook.ts +100 -0
  54. package/src/firebase.ts +0 -0
@@ -0,0 +1,129 @@
1
+ import ecomUtils from '@ecomplus/utils';
2
+
3
+ export default async (product, originalTinyProduct, appData) => {
4
+ const hasVariations = product.variations && product.variations.length;
5
+ const tinyProduct = {
6
+ sequencia: 1,
7
+ origem: 0,
8
+ situacao: product.available && product.visible ? 'A' : 'I',
9
+ tipo: 'P',
10
+ classe_produto: hasVariations ? 'V' : 'S',
11
+ codigo: product.sku,
12
+ nome: ecomUtils.name(product, 'pt_br').substring(0, 120),
13
+ unidade: originalTinyProduct && originalTinyProduct.unidade
14
+ ? originalTinyProduct.unidade
15
+ : product.measurement && product.measurement.unit !== 'oz' && product.measurement.unit !== 'ct'
16
+ ? product.measurement.unit.substring(0, 3).toUpperCase()
17
+ : 'UN',
18
+ };
19
+ if (ecomUtils.onPromotion(product)) {
20
+ tinyProduct.preco = product.base_price;
21
+ tinyProduct.preco_promocional = ecomUtils.price(product);
22
+ } else {
23
+ tinyProduct.preco = product.price;
24
+ }
25
+ if (product.cost_price) {
26
+ tinyProduct.preco_custo = product.cost_price;
27
+ }
28
+ if (product.min_quantity) {
29
+ tinyProduct.unidade_por_caixa = product.min_quantity < 1000
30
+ ? String(product.min_quantity) : '999';
31
+ }
32
+ if (product.short_description) {
33
+ tinyProduct.descricao_complementar = product.short_description;
34
+ }
35
+ if (product.warranty) {
36
+ tinyProduct.garantia = product.warranty.substring(0, 20);
37
+ }
38
+ if (product.mpn && product.mpn.length) {
39
+ [tinyProduct.ncm] = product.mpn;
40
+ }
41
+ if (product.gtin && product.gtin.length) {
42
+ [tinyProduct.gtin] = product.gtin;
43
+ if (product.gtin[1]) {
44
+ // eslint-disable-next-line prefer-destructuring
45
+ tinyProduct.gtin_embalagem = product.gtin[1];
46
+ }
47
+ }
48
+ if (product.weight && product.weight.value) {
49
+ tinyProduct.peso_bruto = product.weight.value;
50
+ if (product.weight.unit === 'mg') {
51
+ tinyProduct.peso_bruto /= 1000000;
52
+ } else if (product.weight.unit === 'g') {
53
+ tinyProduct.peso_bruto /= 1000;
54
+ }
55
+ }
56
+ const { dimensions } = product;
57
+ if (dimensions) {
58
+ Object.keys(dimensions).forEach((side) => {
59
+ if (dimensions[side] && dimensions[side].value) {
60
+ let field = side === 'width' ? 'largura'
61
+ : side === 'height' ? 'altura'
62
+ : 'comprimento';
63
+ field += '_embalagem';
64
+ tinyProduct[field] = dimensions[side].value;
65
+ if (dimensions[side].unit === 'mm') {
66
+ tinyProduct[field] *= 0.1;
67
+ } else if (dimensions[side].unit === 'm') {
68
+ tinyProduct[field] *= 100;
69
+ }
70
+ }
71
+ });
72
+ }
73
+ if (product.brands && product.brands.length) {
74
+ tinyProduct.marca = product.brands[0].name;
75
+ }
76
+ if (product.category_tree) {
77
+ tinyProduct.categoria = product.category_tree.replace(/\s?>\s?/g, ' >> ');
78
+ } else if (product.categories && product.categories.length) {
79
+ tinyProduct.categoria = product.categories.map(({ name }) => name).join(' >> ');
80
+ }
81
+ if (product.pictures && product.pictures.length) {
82
+ tinyProduct.anexos = [];
83
+ product.pictures.forEach(({ zoom, big, normal }) => {
84
+ const img = (zoom || big || normal);
85
+ if (img) {
86
+ tinyProduct.anexos.push({
87
+ anexo: img.url,
88
+ });
89
+ }
90
+ });
91
+ }
92
+ if (originalTinyProduct) {
93
+ tinyProduct.id = originalTinyProduct.id;
94
+ if (!appData.update_price) {
95
+ ['preco', 'preco_promocional', 'preco_custo'].forEach((field) => {
96
+ if (typeof originalTinyProduct[field] === 'number') {
97
+ tinyProduct[field] = originalTinyProduct[field];
98
+ }
99
+ });
100
+ }
101
+ } else {
102
+ tinyProduct.estoque_atual = product.quantity || 0;
103
+ }
104
+ if (hasVariations) {
105
+ tinyProduct.variacoes = [];
106
+ product.variations?.forEach((variation, i) => {
107
+ const tinyVariation = {
108
+ codigo: variation.sku || `${product.sku}-${(i + 1)}`,
109
+ grade: {},
110
+ };
111
+ if (!originalTinyProduct) {
112
+ tinyVariation.estoque_atual = variation.quantity || 0;
113
+ }
114
+ Object.keys(variation.specifications).forEach((gridId) => {
115
+ const gridOptions = variation.specifications[gridId];
116
+ if (gridOptions && gridOptions.length) {
117
+ gridOptions.forEach(({ text }, i) => {
118
+ tinyVariation.grade[i === 0 ? gridId : `${gridId}_${(i + 1)}`] = text;
119
+ });
120
+ }
121
+ });
122
+ tinyProduct.variacoes.push({
123
+ variacao: tinyVariation,
124
+ });
125
+ });
126
+ }
127
+ return tinyProduct;
128
+ };
129
+ // # sourceMappingURL=product-to-tiny.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"product-to-tiny.js","sourceRoot":"","sources":["../../../src/integration/parsers/product-to-tiny.ts"],"names":[],"mappings":"AAEA,OAAO,SAAS,MAAM,iBAAiB,CAAC;AAExC,eAAe,KAAK,EAAE,OAAiB,EAAE,mBAAmB,EAAE,OAAO,EAAE,EAAE;IACvE,MAAM,aAAa,GAAG,OAAO,CAAC,UAAU,IAAI,OAAO,CAAC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AAC,EAAE;gBACpD,KAAK,EAAE,EAAE;aACV,CAAC;YACF,IAAI,CAAC,mBAAmB,EAAE;gBACxB,aAAa,CAAC,aAAa,GAAG,SAAS,CAAC,QAAQ,IAAI,CAAC,CAAC;aACvD;YACD,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,cAAc,CAAC,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE;gBACvD,MAAM,WAAW,GAAG,SAAS,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC;gBACrD,IAAI,WAAW,IAAI,WAAW,CAAC,MAAM,EAAE;oBACrC,WAAW,CAAC,OAAO,CAAC,CAAC,EAAE,IAAI,EAAE,EAAE,CAAC,EAAE,EAAE;wBAClC,aAAa,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,MAAM,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC;oBACxE,CAAC,CAAC,CAAC;iBACJ;YACH,CAAC,CAAC,CAAC;YACH,WAAW,CAAC,SAAS,CAAC,IAAI,CAAC;gBACzB,QAAQ,EAAE,aAAa;aACxB,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;KACJ;IACD,OAAO,WAAW,CAAC;AACrB,CAAC,CAAC"}
@@ -0,0 +1,34 @@
1
+ export default (situacao) => {
2
+ let financialStatus;
3
+ let fulfillmentStatus;
4
+ switch (situacao) {
5
+ case 'aprovado':
6
+ financialStatus = 'paid';
7
+ break;
8
+ case 'preparando_envio':
9
+ case 'preparando envio':
10
+ fulfillmentStatus = 'in_separation';
11
+ break;
12
+ case 'faturado':
13
+ case 'faturado (atendido)':
14
+ case 'atendido':
15
+ fulfillmentStatus = 'invoice_issued';
16
+ break;
17
+ case 'pronto_envio':
18
+ case 'pronto para envio':
19
+ fulfillmentStatus = 'ready_for_shipping';
20
+ break;
21
+ case 'enviado':
22
+ fulfillmentStatus = 'shipped';
23
+ break;
24
+ case 'entregue':
25
+ fulfillmentStatus = 'delivered';
26
+ break;
27
+ case 'cancelado':
28
+ financialStatus = 'voided';
29
+ break;
30
+ default:
31
+ }
32
+ return { financialStatus, fulfillmentStatus };
33
+ };
34
+ // # sourceMappingURL=status-from-tiny.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"status-from-tiny.js","sourceRoot":"","sources":["../../../src/integration/parsers/status-from-tiny.ts"],"names":[],"mappings":"AAEA,eAAe,CAAC,QAAgB,EAAE,EAAE;IAClC,IAAI,eAAsF,CAAC;IAC3F,IAAI,iBAA0F,CAAC;IAC/F,QAAQ,QAAQ,EAAE;QAChB,KAAK,UAAU;YACb,eAAe,GAAG,MAAM,CAAC;YACzB,MAAM;QACR,KAAK,kBAAkB,CAAC;QACxB,KAAK,kBAAkB;YACrB,iBAAiB,GAAG,eAAe,CAAC;YACpC,MAAM;QACR,KAAK,UAAU,CAAC;QAChB,KAAK,qBAAqB,CAAC;QAC3B,KAAK,UAAU;YACb,iBAAiB,GAAG,gBAAgB,CAAC;YACrC,MAAM;QACR,KAAK,cAAc,CAAC;QACpB,KAAK,mBAAmB;YACtB,iBAAiB,GAAG,oBAAoB,CAAC;YACzC,MAAM;QACR,KAAK,SAAS;YACZ,iBAAiB,GAAG,SAAS,CAAC;YAC9B,MAAM;QACR,KAAK,UAAU;YACb,iBAAiB,GAAG,WAAW,CAAC;YAChC,MAAM;QACR,KAAK,WAAW;YACd,eAAe,GAAG,QAAQ,CAAC;YAC3B,MAAM;QACR,QAAQ;KACT;IACD,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,CAAC;AAChD,CAAC,CAAC"}
@@ -0,0 +1,39 @@
1
+ export default (order) => {
2
+ const financialStatus = order.financial_status && order.financial_status.current;
3
+ switch (financialStatus) {
4
+ case 'pending':
5
+ case 'under_analysis':
6
+ case 'unknown':
7
+ case 'authorized':
8
+ case 'partially_paid':
9
+ return 'aberto';
10
+ case 'voided':
11
+ case 'refunded':
12
+ case 'in_dispute':
13
+ case 'unauthorized':
14
+ return 'cancelado';
15
+ default:
16
+ }
17
+ switch (order.fulfillment_status && order.fulfillment_status.current) {
18
+ case 'in_production':
19
+ case 'in_separation':
20
+ return 'preparando_envio';
21
+ case 'invoice_issued':
22
+ return 'faturado';
23
+ case 'ready_for_shipping':
24
+ return 'pronto_envio';
25
+ case 'shipped':
26
+ case 'partially_shipped':
27
+ return 'enviado';
28
+ case 'delivered':
29
+ return 'entregue';
30
+ case 'returned':
31
+ return 'cancelado';
32
+ default:
33
+ }
34
+ if (financialStatus === 'paid') {
35
+ return 'aprovado';
36
+ }
37
+ return 'aberto';
38
+ };
39
+ // # sourceMappingURL=status-to-tiny.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"status-to-tiny.js","sourceRoot":"","sources":["../../../src/integration/parsers/status-to-tiny.ts"],"names":[],"mappings":"AAEA,eAAe,CAAC,KAAa,EAAE,EAAE;IAC/B,MAAM,eAAe,GAAG,KAAK,CAAC,gBAAgB,IAAI,KAAK,CAAC,gBAAgB,CAAC,OAAO,CAAC;IACjF,QAAQ,eAAe,EAAE;QACvB,KAAK,SAAS,CAAC;QACf,KAAK,gBAAgB,CAAC;QACtB,KAAK,SAAS,CAAC;QACf,KAAK,YAAY,CAAC;QAClB,KAAK,gBAAgB;YACnB,OAAO,QAAQ,CAAC;QAClB,KAAK,QAAQ,CAAC;QACd,KAAK,UAAU,CAAC;QAChB,KAAK,YAAY,CAAC;QAClB,KAAK,cAAc;YACjB,OAAO,WAAW,CAAC;QACrB,QAAQ;KACT;IAED,QAAQ,KAAK,CAAC,kBAAkB,IAAI,KAAK,CAAC,kBAAkB,CAAC,OAAO,EAAE;QACpE,KAAK,eAAe,CAAC;QACrB,KAAK,eAAe;YAClB,OAAO,kBAAkB,CAAC;QAC5B,KAAK,gBAAgB;YACnB,OAAO,UAAU,CAAC;QACpB,KAAK,oBAAoB;YACvB,OAAO,cAAc,CAAC;QACxB,KAAK,SAAS,CAAC;QACf,KAAK,mBAAmB;YACtB,OAAO,SAAS,CAAC;QACnB,KAAK,WAAW;YACd,OAAO,UAAU,CAAC;QACpB,KAAK,UAAU;YACb,OAAO,WAAW,CAAC;QACrB,QAAQ;KACT;IAED,IAAI,eAAe,KAAK,MAAM,EAAE;QAC9B,OAAO,UAAU,CAAC;KACnB;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC,CAAC"}
@@ -0,0 +1,47 @@
1
+ import axios from 'axios';
2
+
3
+ export default (url, body, token = process.env.TINY_ERP_TOKEN, options = {}) => {
4
+ // https://www.tiny.com.br/ajuda/api/api2
5
+ let data = `token=${token}&formato=JSON`;
6
+ if (body) {
7
+ Object.keys(body).forEach((field) => {
8
+ if (body[field]) {
9
+ switch (typeof body[field]) {
10
+ case 'object':
11
+ data += `&${field}=${JSON.stringify(body[field])}`;
12
+ break;
13
+ case 'string':
14
+ case 'number':
15
+ data += `&${field}=${body[field]}`;
16
+ break;
17
+ default:
18
+ }
19
+ }
20
+ });
21
+ }
22
+ return axios.post(url, data, {
23
+ baseURL: 'https://api.tiny.com.br/api2/',
24
+ timeout: 30000,
25
+ ...options,
26
+ })
27
+ .then((response) => {
28
+ const { retorno } = response.data;
29
+ if (retorno.status === 'Erro') {
30
+ const err = new Error('Tiny error response');
31
+ const tinyErrorCode = parseInt(retorno.codigo_erro, 10);
32
+ if (tinyErrorCode <= 2) {
33
+ response.status = 401;
34
+ } else if (tinyErrorCode === 6) {
35
+ response.status = 503;
36
+ } else if (tinyErrorCode === 20) {
37
+ response.status = 404;
38
+ }
39
+ err.response = response;
40
+ err.config = response.config;
41
+ err.request = response.request;
42
+ throw err;
43
+ }
44
+ return retorno;
45
+ });
46
+ };
47
+ // # sourceMappingURL=post-tiny-erp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"post-tiny-erp.js","sourceRoot":"","sources":["../../src/integration/post-tiny-erp.ts"],"names":[],"mappings":"AAAA,OAAO,KAA6B,MAAM,OAAO,CAAC;AAElD,eAAe,CACb,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AE;gBAC9B,QAAQ,CAAC,MAAM,GAAG,GAAG,CAAC;aACvB;iBAAM,IAAI,aAAa,KAAK,EAAE,EAAE;gBAC/B,QAAQ,CAAC,MAAM,GAAG,GAAG,CAAC;aACvB;YACD,GAAG,CAAC,QAAQ,GAAG,QAAQ,CAAC;YACxB,GAAG,CAAC,MAAM,GAAG,QAAQ,CAAC,MAAM,CAAC;YAC7B,GAAG,CAAC,OAAO,GAAG,QAAQ,CAAC,OAAO,CAAC;YAC/B,MAAM,GAAG,CAAC;SACX;QACD,OAAO,OAAO,CAAC;IACjB,CAAC,CAAC,CAAC;AACP,CAAC,CAAC"}
@@ -0,0 +1,17 @@
1
+ /* eslint-disable import/prefer-default-export */
2
+ import '@cloudcommerce/firebase/lib/init';
3
+ // eslint-disable-next-line import/no-unresolved
4
+ import { onRequest } from 'firebase-functions/v2/https';
5
+ import config from '@cloudcommerce/firebase/lib/config';
6
+ import { createAppEventsFunction } from '@cloudcommerce/firebase/lib/helpers/pubsub';
7
+ import handleApiEvent from './event-to-tiny.js';
8
+ import handleTinyWebhook from './tiny-webhook.js';
9
+
10
+ const { httpsFunctionOptions } = config.get();
11
+
12
+ export const tinyErpOnApiEvent = createAppEventsFunction('tinyErp', handleApiEvent);
13
+
14
+ export const tinyErpWebhook = onRequest(httpsFunctionOptions, (req, res) => {
15
+ handleTinyWebhook(req, res);
16
+ });
17
+ // # sourceMappingURL=tiny-erp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tiny-erp.js","sourceRoot":"","sources":["../src/tiny-erp.ts"],"names":[],"mappings":"AAAA,iDAAiD;AAEjD,OAAO,kCAAkC,CAAC;AAC1C,gDAAgD;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,6BAA6B,CAAC;AACxD,OAAO,MAAM,MAAM,oCAAoC,CAAC;AACxD,OAAO,EACL,uBAAuB,GAExB,MAAM,4CAA4C,CAAC;AACpD,OAAO,cAAc,MAAM,iBAAiB,CAAC;AAC7C,OAAO,iBAAiB,MAAM,gBAAgB,CAAC;AAE/C,MAAM,EAAE,oBAAoB,EAAE,GAAG,MAAM,CAAC,GAAG,EAAE,CAAC;AAE9C,MAAM,CAAC,MAAM,iBAAiB,GAAG,uBAAuB,CACtD,SAAS,EACT,cAAiC,CAClC,CAAC;AAEF,MAAM,CAAC,MAAM,cAAc,GAAG,SAAS,CAAC,oBAAoB,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;IACzE,iBAAiB,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;AAC9B,CAAC,CAAC,CAAC"}
@@ -0,0 +1,92 @@
1
+ import logger from 'firebase-functions/lib/logger';
2
+ import api from '@cloudcommerce/api';
3
+ import config from '@cloudcommerce/firebase/lib/config';
4
+ import importProduct from './integration/import-product-from-tiny.js';
5
+ import importOrder from './integration/import-order-from-tiny.js';
6
+
7
+ let appData = {};
8
+ let application;
9
+
10
+ export default async (req, res) => {
11
+ const tinyToken = req.query.token;
12
+ if (typeof tinyToken === 'string' && tinyToken && req.body) {
13
+ const { dados, tipo } = req.body;
14
+ if (dados) {
15
+ /*
16
+ TODO: Check Tiny server IPs
17
+ const clientIp = req.get('x-forwarded-for') || req.connection.remoteAddress
18
+ */
19
+ const { TINY_ERP_TOKEN } = process.env;
20
+ if (!TINY_ERP_TOKEN || TINY_ERP_TOKEN !== tinyToken) {
21
+ const { apps: { tinyErp: { appId } } } = config.get();
22
+ const applicationId = req.query._id;
23
+ const appEndpoint = applicationId && typeof applicationId === 'string'
24
+ ? `applications/${applicationId}`
25
+ : `applications/app_id:${appId}`;
26
+ application = (await api.get(appEndpoint)).data;
27
+ appData = {
28
+ ...application.data,
29
+ ...application.hidden_data,
30
+ };
31
+ if (appData.tiny_api_token !== tinyToken) {
32
+ return res.sendStatus(401);
33
+ }
34
+ process.env.TINY_ERP_TOKEN = tinyToken;
35
+ }
36
+ if (dados.idVendaTiny) {
37
+ const orderNumber = `id:${dados.idVendaTiny}`;
38
+ const queueEntry = {
39
+ nextId: orderNumber,
40
+ isNotQueued: true,
41
+ };
42
+ await importOrder({}, queueEntry);
43
+ } else if ((tipo === 'produto' || tipo === 'estoque')
44
+ && (dados.id || dados.idProduto)
45
+ && (dados.codigo || dados.sku)) {
46
+ const nextId = String(dados.skuMapeamento || dados.sku || dados.codigo);
47
+ const tinyStockUpdate = {
48
+ ref: `${nextId}`,
49
+ tipo,
50
+ produto: {
51
+ id: dados.idProduto,
52
+ codigo: dados.sku,
53
+ ...dados,
54
+ },
55
+ };
56
+ logger.info(`> Tiny webhook: ${nextId} => ${tinyStockUpdate.produto.saldo}`);
57
+ const queueEntry = {
58
+ nextId,
59
+ tinyStockUpdate,
60
+ isNotQueued: true,
61
+ app: application,
62
+ };
63
+ await importProduct({}, queueEntry, appData, false, true);
64
+ }
65
+ if (tipo === 'produto') {
66
+ const mapeamentos = [];
67
+ const parseTinyItem = (tinyItem) => {
68
+ if (tinyItem) {
69
+ const {
70
+ idMapeamento, id, codigo, sku,
71
+ } = tinyItem;
72
+ mapeamentos.push({
73
+ idMapeamento: idMapeamento || id,
74
+ skuMapeamento: codigo || sku,
75
+ });
76
+ }
77
+ };
78
+ parseTinyItem(dados);
79
+ if (Array.isArray(dados.variacoes)) {
80
+ dados.variacoes.forEach((variacao) => {
81
+ parseTinyItem(variacao.id ? variacao : variacao.variacao);
82
+ });
83
+ }
84
+ return res.status(200).send(mapeamentos);
85
+ }
86
+ return res.sendStatus(200);
87
+ }
88
+ logger.warn('< Invalid Tiny Webhook body', req.body);
89
+ }
90
+ return res.sendStatus(403);
91
+ };
92
+ // # sourceMappingURL=tiny-webhook.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tiny-webhook.js","sourceRoot":"","sources":["../src/tiny-webhook.ts"],"names":[],"mappings":"AAEA,OAAO,MAAM,MAAM,+BAA+B,CAAC;AACnD,OAAO,GAAG,MAAM,oBAAoB,CAAC;AACrC,OAAO,MAAM,MAAM,oCAAoC,CAAC;AACxD,OAAO,aAAa,MAAM,wCA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Y,EACZ,EAAE,EACF,MAAM,EACN,GAAG,GACJ,GAAG,QAAQ,CAAC;wBACb,WAAW,CAAC,IAAI,CAAC;4BACf,YAAY,EAAE,YAAY,IAAI,EAAE;4BAChC,aAAa,EAAE,MAAM,IAAI,GAAG;yBAC7B,CAAC,CAAC;qBACJ;gBACH,CAAC,CAAC;gBACF,aAAa,CAAC,KAAK,CAAC,CAAC;gBACrB,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,SAAS,CAAC,EAAE;oBAClC,KAAK,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,EAAE;wBACnC,aAAa,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;oBAC5D,CAAC,CAAC,CAAC;iBACJ;gBACD,OAAO,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;aAC1C;YACD,OAAO,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;SAC5B;QACD,MAAM,CAAC,IAAI,CAAC,6BAA6B,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;KACtD;IACD,OAAO,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;AAC7B,CAAC,CAAC"}
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@cloudcommerce/app-tiny-erp",
3
3
  "type": "module",
4
- "version": "0.0.59",
5
- "description": "E-Com Plus Cloud Commerce",
6
- "main": "lib/index.js",
4
+ "version": "0.0.62",
5
+ "description": "E-Com Plus Cloud Commerce app for Tiny ERP",
6
+ "main": "lib/tiny-erp.js",
7
7
  "repository": {
8
8
  "type": "git",
9
9
  "url": "git+https://github.com/ecomplus/cloud-commerce.git",
@@ -16,12 +16,19 @@
16
16
  },
17
17
  "homepage": "https://github.com/ecomplus/cloud-commerce/tree/main/packages/apps/tiny-erp#readme",
18
18
  "dependencies": {
19
- "@cloudcommerce/api": "0.0.59"
19
+ "@cloudcommerce/api": "0.0.62",
20
+ "@cloudcommerce/firebase": "0.0.62",
21
+ "@ecomplus/utils": "^1.4.1",
22
+ "axios": "^0.27.2",
23
+ "firebase-admin": "^11.0.1",
24
+ "firebase-functions": "^3.22.0",
25
+ "form-data": "^4.0.0"
20
26
  },
21
27
  "devDependencies": {
22
- "@cloudcommerce/types": "0.0.59"
28
+ "@cloudcommerce/types": "0.0.62",
29
+ "@firebase/app-types": "^0.7.0"
23
30
  },
24
31
  "scripts": {
25
- "build": "echo '@ecomplus/tiny-erp'"
32
+ "build": "sh ../../../scripts/build-lib.sh"
26
33
  }
27
34
  }
@@ -0,0 +1,136 @@
1
+ import type { ApiEventHandler } from '@cloudcommerce/firebase/lib/helpers/pubsub';
2
+ import logger from 'firebase-functions/lib/logger';
3
+ import exportProduct from './integration/export-product-to-tiny';
4
+ import exportOrder from './integration/export-order-to-tiny';
5
+ import importProduct from './integration/import-product-from-tiny';
6
+ import importOrder from './integration/import-order-from-tiny';
7
+ import afterQueue from './integration/after-tiny-queue';
8
+
9
+ // Async integration handlers
10
+ const integrationHandlers = {
11
+ exportation: {
12
+ product_ids: exportProduct,
13
+ order_ids: exportOrder,
14
+ },
15
+ importation: {
16
+ skus: importProduct,
17
+ order_numbers: importOrder,
18
+ },
19
+ };
20
+
21
+ const handleApiEvent: ApiEventHandler = async ({
22
+ evName,
23
+ apiEvent,
24
+ apiDoc,
25
+ app,
26
+ }) => {
27
+ const resourceId = apiEvent.resource_id;
28
+ logger.info('>> ', resourceId, ' - Action: ', apiEvent.action);
29
+ const key = `${evName}_${resourceId}`;
30
+ const appData = { ...app.data, ...app.hidden_data };
31
+ if (
32
+ Array.isArray(appData.ignore_events)
33
+ && appData.ignore_events.includes(evName)
34
+ ) {
35
+ logger.info('>> ', key, ' - Ignored event');
36
+ return null;
37
+ }
38
+ logger.info(`> Webhook ${resourceId} [${evName}]`);
39
+
40
+ if (!process.env.TINY_ERP_TOKEN) {
41
+ const tinyToken = appData.tiny_api_token;
42
+ if (typeof tinyToken === 'string' && tinyToken) {
43
+ process.env.TINY_ERP_TOKEN = tinyToken;
44
+ } else {
45
+ logger.warn('Missing Tiny API token');
46
+ }
47
+ }
48
+
49
+ if (process.env.TINY_ERP_TOKEN) {
50
+ let integrationConfig;
51
+ let canCreateNew = false;
52
+ if (evName === 'applications-dataSet') {
53
+ integrationConfig = appData;
54
+ canCreateNew = true;
55
+ } else if (evName === 'orders-anyStatusSet') {
56
+ canCreateNew = Boolean(appData.new_orders);
57
+ integrationConfig = {
58
+ _exportation: {
59
+ order_ids: [resourceId],
60
+ },
61
+ };
62
+ } else {
63
+ if (evName === 'products-new') {
64
+ if (!appData.new_products) {
65
+ return null;
66
+ }
67
+ } else if (!appData.update_price) {
68
+ return null;
69
+ }
70
+ integrationConfig = {
71
+ _exportation: {
72
+ product_ids: [resourceId],
73
+ },
74
+ };
75
+ }
76
+
77
+ if (integrationConfig) {
78
+ const actions = Object.keys(integrationHandlers);
79
+ actions.forEach((action) => {
80
+ for (let i = 1; i <= 3; i++) {
81
+ actions.push(`${('_'.repeat(i))}${action}`);
82
+ }
83
+ });
84
+ for (let i = 0; i < actions.length; i++) {
85
+ const action = actions[i];
86
+ const actionQueues = integrationConfig[action];
87
+
88
+ if (typeof actionQueues === 'object' && actionQueues) {
89
+ // eslint-disable-next-line guard-for-in, no-restricted-syntax
90
+ for (const queue in actionQueues) {
91
+ const ids = actionQueues[queue];
92
+ if (Array.isArray(ids) && ids.length) {
93
+ const isHiddenQueue = action.charAt(0) === '_';
94
+ const mustUpdateAppQueue = evName === 'applications-dataSet';
95
+ const handlerName = action.replace(/^_+/, '');
96
+ const handler = integrationHandlers[handlerName][queue.toLowerCase()];
97
+ const nextId = ids[0];
98
+
99
+ if (
100
+ typeof nextId === 'string'
101
+ && nextId.length
102
+ && handler
103
+ ) {
104
+ const debugFlag = `#${action}/${queue}/${nextId}`;
105
+ logger.info(`> Starting ${debugFlag}`);
106
+ const queueEntry = {
107
+ action,
108
+ queue,
109
+ nextId,
110
+ key,
111
+ mustUpdateAppQueue,
112
+ app,
113
+ };
114
+ return handler(
115
+ apiDoc,
116
+ queueEntry,
117
+ appData,
118
+ canCreateNew,
119
+ isHiddenQueue,
120
+ ).then((payload) => {
121
+ return afterQueue(queueEntry, appData, app, payload);
122
+ }).catch((err) => {
123
+ return afterQueue(queueEntry, appData, app, err);
124
+ });
125
+ }
126
+ }
127
+ }
128
+ }
129
+ }
130
+ }
131
+ }
132
+ // Nothing to do
133
+ return null;
134
+ };
135
+
136
+ export default handleApiEvent;
package/src/index.ts CHANGED
@@ -0,0 +1 @@
1
+ export * from './tiny-erp';
@@ -0,0 +1,80 @@
1
+ import logger from 'firebase-functions/lib/logger';
2
+ import updateAppData from '@cloudcommerce/firebase/lib/helpers/update-app-data';
3
+
4
+ export default async (queueEntry, appData, application, payload) => {
5
+ const isError = payload instanceof Error;
6
+ const isImportation = queueEntry.action.endsWith('importation');
7
+ const logs = appData.logs || [];
8
+ const logEntry = {
9
+ resource: /order/i.test(queueEntry.queue) ? 'orders' : 'products',
10
+ [(isImportation ? 'tiny_id' : 'resource_id')]: queueEntry.nextId,
11
+ success: !isError,
12
+ imestamp: new Date().toISOString(),
13
+ };
14
+
15
+ let notes;
16
+ if (payload) {
17
+ if (!isError) {
18
+ // payload = response
19
+ const { data, status, config } = payload;
20
+ if (data && data._id) {
21
+ logEntry.resource_id = data._id;
22
+ }
23
+ notes = `Status ${status}`;
24
+ if (config) {
25
+ notes += ` [${config.url}]`;
26
+ }
27
+ } else {
28
+ const { config, response } = payload as any;
29
+ if (response) {
30
+ const { data, status } = response;
31
+ notes = `Error: Status ${status} \n${JSON.stringify(data)}`;
32
+ if (!status || status === 429 || status >= 500) {
33
+ return setTimeout(() => {
34
+ throw payload;
35
+ }, 2000);
36
+ }
37
+ if (config) {
38
+ const { url, method, data } = config;
39
+ notes += `\n\n-- Request -- \n${method} ${url} \n${JSON.stringify(data)}`;
40
+ }
41
+ // @ts-ignore
42
+ } else if (payload.isConfigError === true) {
43
+ notes = payload.message;
44
+ } else {
45
+ notes = payload.stack;
46
+ }
47
+ }
48
+ }
49
+ if (notes) {
50
+ logEntry.notes = notes.substring(0, 5000);
51
+ }
52
+
53
+ if (isError || !isImportation) {
54
+ logs.unshift(logEntry);
55
+ await updateAppData(application, {
56
+ logs: logs.slice(0, 200),
57
+ }, {
58
+ isHiddenData: true,
59
+ canSendPubSub: false,
60
+ });
61
+ }
62
+ const { action, queue, nextId } = queueEntry;
63
+ let queueList = appData[action][queue];
64
+ if (Array.isArray(queueList)) {
65
+ const idIndex = queueList.indexOf(nextId);
66
+ if (idIndex > -1) {
67
+ queueList.splice(idIndex, 1);
68
+ }
69
+ } else {
70
+ queueList = [];
71
+ }
72
+ const data = {
73
+ [action]: {
74
+ ...appData[action],
75
+ [queue]: queueList,
76
+ },
77
+ };
78
+ logger.info(JSON.stringify(data));
79
+ return updateAppData(application, data);
80
+ };