@cloudcommerce/app-tiny-erp 0.0.59 → 0.0.60

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 +32 -6
  2. package/lib/event-to-tiny.js +111 -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 +94 -0
  15. package/lib/integration/import-order-from-tiny.js.map +1 -0
  16. package/lib/integration/import-product-from-tiny.js +169 -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 +135 -0
  35. package/lib/tiny-webhook.js.map +1 -0
  36. package/package.json +13 -6
  37. package/src/event-to-tiny.ts +129 -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 +104 -0
  44. package/src/integration/import-product-from-tiny.ts +174 -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 +143 -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,135 @@
1
+ import { firestore } from 'firebase-admin';
2
+ import logger from 'firebase-functions/lib/logger';
3
+ import api from '@cloudcommerce/api';
4
+ import config from '@cloudcommerce/firebase/lib/config';
5
+ import updateAppData from '@cloudcommerce/firebase/lib/helpers/update-app-data';
6
+ import importProduct from './integration/import-product-from-tiny.js';
7
+ import importOrder from './integration/import-order-from-tiny.js';
8
+ import afterQueue from './integration/after-tiny-queue.js';
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 { apps: { tinyErp: { appId } } } = config.get();
20
+ const applicationId = req.query._id;
21
+ const appEndpoint = applicationId && typeof applicationId === 'string'
22
+ ? `applications/${applicationId}`
23
+ : `applications/app_id:${appId}`;
24
+ const application = (await api.get(appEndpoint)).data;
25
+ const appData = {
26
+ ...application.data,
27
+ ...application.hidden_data,
28
+ };
29
+ if (appData.tiny_api_token !== tinyToken) {
30
+ return res.sendStatus(401);
31
+ }
32
+ if (dados.idVendaTiny) {
33
+ let orderNumbers = appData.___importation?.order_numbers;
34
+ if (!Array.isArray(orderNumbers)) {
35
+ orderNumbers = [];
36
+ }
37
+ const orderNumber = `id:${dados.idVendaTiny}`;
38
+ if (!orderNumbers.includes(orderNumber)) {
39
+ logger.info(`> Tiny webhook: order ${orderNumber}`);
40
+ const saveToQueue = () => {
41
+ orderNumbers.push(orderNumber);
42
+ logger.info(`> Order numbers: ${JSON.stringify(orderNumbers)}`);
43
+ return updateAppData(application, {
44
+ ___importation: {
45
+ ...appData.___importation,
46
+ order_numbers: orderNumbers,
47
+ },
48
+ });
49
+ };
50
+ const queueEntry = {
51
+ nextId: orderNumber,
52
+ isNotQueued: true,
53
+ };
54
+ try {
55
+ const payload = await importOrder({}, queueEntry);
56
+ await afterQueue(queueEntry, appData, application, payload);
57
+ } catch (e) {
58
+ await saveToQueue();
59
+ }
60
+ }
61
+ }
62
+ if (tipo === 'produto' || tipo === 'estoque') {
63
+ if ((dados.id || dados.idProduto) && (dados.codigo || dados.sku)) {
64
+ const nextId = String(dados.skuMapeamento || dados.sku || dados.codigo);
65
+ const tinyStockUpdate = {
66
+ ref: `${nextId}`,
67
+ tipo,
68
+ produto: {
69
+ id: dados.idProduto,
70
+ codigo: dados.sku,
71
+ ...dados,
72
+ },
73
+ updatedAt: firestore.Timestamp.fromDate(new Date()),
74
+ };
75
+ logger.info(`> Tiny webhook: ${nextId} => ${tinyStockUpdate.produto.saldo}`);
76
+ const saveToQueue = () => {
77
+ let skus = appData.___importation && appData.___importation.skus;
78
+ if (!Array.isArray(skus)) {
79
+ skus = [];
80
+ }
81
+ if (!skus.includes(nextId)) {
82
+ return firestore().collection('tinyErpStockUpdates').add(tinyStockUpdate)
83
+ .then(() => {
84
+ skus.push(nextId);
85
+ logger.info(`> SKUs: ${JSON.stringify(skus)}`);
86
+ return updateAppData(application, {
87
+ ___importation: {
88
+ ...appData.___importation,
89
+ skus,
90
+ },
91
+ });
92
+ });
93
+ }
94
+ return Promise.resolve(null);
95
+ };
96
+ const queueEntry = {
97
+ nextId,
98
+ tinyStockUpdate,
99
+ isNotQueued: true,
100
+ };
101
+ try {
102
+ const payload = await importProduct({}, queueEntry, appData, false, true);
103
+ await afterQueue(queueEntry, appData, application, payload);
104
+ } catch (e) {
105
+ await saveToQueue();
106
+ }
107
+ }
108
+ }
109
+ if (tipo === 'produto') {
110
+ const mapeamentos = [];
111
+ const parseTinyItem = (tinyItem) => {
112
+ if (tinyItem) {
113
+ const {
114
+ idMapeamento, id, codigo, sku,
115
+ } = tinyItem;
116
+ mapeamentos.push({
117
+ idMapeamento: idMapeamento || id,
118
+ skuMapeamento: codigo || sku,
119
+ });
120
+ }
121
+ };
122
+ parseTinyItem(dados);
123
+ if (Array.isArray(dados.variacoes)) {
124
+ dados.variacoes.forEach((variacao) => {
125
+ parseTinyItem(variacao.id ? variacao : variacao.variacao);
126
+ });
127
+ }
128
+ return res.status(200).send(mapeamentos);
129
+ }
130
+ return res.sendStatus(200);
131
+ }
132
+ }
133
+ return res.sendStatus(403);
134
+ };
135
+ // # sourceMappingURL=tiny-webhook.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tiny-webhook.js","sourceRoot":"","sources":["../src/tiny-webhook.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,MAAM,MAAM,+BAA+B,CAAC;AACnD,OAAO,GAAG,MAAM,oBAAoB,CAAC;AACrC,OAAO,MAAM,MAAM,oCAAoC,CAAC;AACxD,OAAO,aAAa,MAAM,qDAAqD,CAAC;AAChF,OAAO,aAAa,MAAM,wCAAwC,CAAC;AACnE,OAAO,WAAW,MAAM,sCAAsC,CAAC;AAC/D,OAAO,UAAU,MAAM,gCAAgC,CAAC;AAExD,eAAe,KAAK,EAAE,GAAY,EAAE,GAAa,EAAE,EAAE;IACnD,MAAM,SAAS,GAAG,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC;IAClC,IAAI,OAAO,SAAS,KAAK,QAAQ,IAAI,SAAS,IAAI,GAAG,CAAC,IAAI,EAAE;QAC1D,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,GAAG,CAA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AE;oBACjC,IAAI,QAAQ,EAAE;wBACZ,MAAM,EACJ,YAAY,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;KACF;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.60",
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.60",
20
+ "@cloudcommerce/firebase": "0.0.60",
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.60",
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,129 @@
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
+ const tinyToken = appData.tiny_api_token;
41
+ if (typeof tinyToken === 'string' && tinyToken) {
42
+ process.env.TINY_ERP_TOKEN = tinyToken;
43
+ let integrationConfig;
44
+ let canCreateNew = false;
45
+ if (evName === 'applications-dataSet') {
46
+ integrationConfig = appData;
47
+ canCreateNew = true;
48
+ } else if (evName === 'orders-anyStatusSet') {
49
+ canCreateNew = Boolean(appData.new_orders);
50
+ integrationConfig = {
51
+ _exportation: {
52
+ order_ids: [resourceId],
53
+ },
54
+ };
55
+ } else {
56
+ if (evName === 'products-new') {
57
+ if (!appData.new_products) {
58
+ return null;
59
+ }
60
+ } else if (!appData.update_price) {
61
+ return null;
62
+ }
63
+ integrationConfig = {
64
+ _exportation: {
65
+ product_ids: [resourceId],
66
+ },
67
+ };
68
+ }
69
+
70
+ if (integrationConfig) {
71
+ const actions = Object.keys(integrationHandlers);
72
+ actions.forEach((action) => {
73
+ for (let i = 1; i <= 3; i++) {
74
+ actions.push(`${('_'.repeat(i))}${action}`);
75
+ }
76
+ });
77
+ for (let i = 0; i < actions.length; i++) {
78
+ const action = actions[i];
79
+ const actionQueues = integrationConfig[action];
80
+
81
+ if (typeof actionQueues === 'object' && actionQueues) {
82
+ // eslint-disable-next-line guard-for-in, no-restricted-syntax
83
+ for (const queue in actionQueues) {
84
+ const ids = actionQueues[queue];
85
+ if (Array.isArray(ids) && ids.length) {
86
+ const isHiddenQueue = action.charAt(0) === '_';
87
+ const mustUpdateAppQueue = evName === 'applications-dataSet';
88
+ const handlerName = action.replace(/^_+/, '');
89
+ const handler = integrationHandlers[handlerName][queue.toLowerCase()];
90
+ const nextId = ids[0];
91
+
92
+ if (
93
+ typeof nextId === 'string'
94
+ && nextId.length
95
+ && handler
96
+ ) {
97
+ const debugFlag = `#${action}/${queue}/${nextId}`;
98
+ logger.info(`> Starting ${debugFlag}`);
99
+ const queueEntry = {
100
+ action,
101
+ queue,
102
+ nextId,
103
+ key,
104
+ mustUpdateAppQueue,
105
+ app,
106
+ };
107
+ return handler(
108
+ apiDoc,
109
+ queueEntry,
110
+ appData,
111
+ canCreateNew,
112
+ isHiddenQueue,
113
+ ).then((payload) => {
114
+ return afterQueue(queueEntry, appData, app, payload);
115
+ }).catch((err) => {
116
+ return afterQueue(queueEntry, appData, app, err);
117
+ });
118
+ }
119
+ }
120
+ }
121
+ }
122
+ }
123
+ }
124
+ }
125
+ // Nothing to do
126
+ return null;
127
+ };
128
+
129
+ export default handleApiEvent;
package/src/index.ts CHANGED
@@ -0,0 +1 @@
1
+ export * from './tiny-erp';