cloudcommerce 0.0.109 → 0.0.110

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 (117) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/package.json +1 -1
  3. package/packages/api/lib/api.d.ts +4 -4940
  4. package/packages/api/lib/types.d.ts +17 -3
  5. package/packages/api/package.json +1 -1
  6. package/packages/api/src/types.ts +45 -23
  7. package/packages/apps/correios/package.json +1 -1
  8. package/packages/apps/custom-shipping/package.json +1 -1
  9. package/packages/apps/discounts/package.json +1 -1
  10. package/packages/apps/frenet/lib-mjs/calculate-frenet.mjs +26 -23
  11. package/packages/apps/frenet/package.json +1 -1
  12. package/packages/apps/tiny-erp/lib/event-to-tiny.js +94 -94
  13. package/packages/apps/tiny-erp/lib/index.js +1 -1
  14. package/packages/apps/tiny-erp/lib/integration/after-tiny-queue.js +71 -74
  15. package/packages/apps/tiny-erp/lib/integration/export-order-to-tiny.js +70 -73
  16. package/packages/apps/tiny-erp/lib/integration/export-product-to-tiny.js +49 -53
  17. package/packages/apps/tiny-erp/lib/integration/helpers/format-tiny-date.js +3 -3
  18. package/packages/apps/tiny-erp/lib/integration/import-order-from-tiny.js +76 -75
  19. package/packages/apps/tiny-erp/lib/integration/import-product-from-tiny.js +137 -140
  20. package/packages/apps/tiny-erp/lib/integration/parsers/order-from-tiny.js +40 -39
  21. package/packages/apps/tiny-erp/lib/integration/parsers/order-to-tiny.js +173 -178
  22. package/packages/apps/tiny-erp/lib/integration/parsers/product-from-tiny.js +173 -171
  23. package/packages/apps/tiny-erp/lib/integration/parsers/product-to-tiny.js +123 -127
  24. package/packages/apps/tiny-erp/lib/integration/parsers/status-from-tiny.js +32 -32
  25. package/packages/apps/tiny-erp/lib/integration/parsers/status-to-tiny.js +37 -37
  26. package/packages/apps/tiny-erp/lib/integration/post-tiny-erp.js +42 -43
  27. package/packages/apps/tiny-erp/lib/tiny-erp.js +8 -6
  28. package/packages/apps/tiny-erp/lib/tiny-webhook.js +76 -73
  29. package/packages/apps/tiny-erp/package.json +1 -1
  30. package/packages/cli/package.json +1 -1
  31. package/packages/config/package.json +1 -1
  32. package/packages/events/package.json +1 -1
  33. package/packages/firebase/package.json +1 -1
  34. package/packages/i18n/lib/en_us.d.ts +1 -0
  35. package/packages/i18n/lib/en_us.js +1 -0
  36. package/packages/i18n/lib/en_us.js.map +1 -1
  37. package/packages/i18n/lib/pt_br.d.ts +1 -0
  38. package/packages/i18n/lib/pt_br.js +1 -0
  39. package/packages/i18n/lib/pt_br.js.map +1 -1
  40. package/packages/i18n/package.json +1 -1
  41. package/packages/i18n/src/en_us.ts +1 -0
  42. package/packages/i18n/src/pt_br.ts +1 -0
  43. package/packages/modules/lib/firebase/ajv.js +24 -19
  44. package/packages/modules/lib/firebase/call-app-module.js +110 -116
  45. package/packages/modules/lib/firebase/checkout.js +149 -154
  46. package/packages/modules/lib/firebase/checkout.js.map +1 -1
  47. package/packages/modules/lib/firebase/functions-checkout/fix-items.js +187 -194
  48. package/packages/modules/lib/firebase/functions-checkout/get-custumerId.js +33 -27
  49. package/packages/modules/lib/firebase/functions-checkout/get-custumerId.js.map +1 -1
  50. package/packages/modules/lib/firebase/functions-checkout/handle-order-transaction.js +111 -125
  51. package/packages/modules/lib/firebase/functions-checkout/handle-order-transaction.js.map +1 -1
  52. package/packages/modules/lib/firebase/functions-checkout/new-order.js +178 -178
  53. package/packages/modules/lib/firebase/functions-checkout/new-order.js.map +1 -1
  54. package/packages/modules/lib/firebase/functions-checkout/request-to-module.js +53 -60
  55. package/packages/modules/lib/firebase/functions-checkout/request-to-module.js.map +1 -1
  56. package/packages/modules/lib/firebase/functions-checkout/utils.js +197 -195
  57. package/packages/modules/lib/firebase/handle-module.js +146 -144
  58. package/packages/modules/lib/firebase/handle-module.js.map +1 -1
  59. package/packages/modules/lib/firebase/proxy-apps.js +1 -2
  60. package/packages/modules/lib/firebase/serve-modules-api.js +53 -52
  61. package/packages/modules/lib/firebase/serve-modules-api.js.map +1 -1
  62. package/packages/modules/lib/firebase.js +6 -4
  63. package/packages/modules/lib/index.js +17 -12
  64. package/packages/modules/lib/index.js.map +1 -1
  65. package/packages/modules/package.json +2 -1
  66. package/packages/modules/schemas/@checkout.cjs +13 -1
  67. package/packages/modules/schemas/list_payments.cjs +6 -0
  68. package/packages/modules/src/firebase/checkout.ts +22 -49
  69. package/packages/modules/src/firebase/functions-checkout/get-custumerId.ts +23 -17
  70. package/packages/modules/src/firebase/functions-checkout/handle-order-transaction.ts +8 -45
  71. package/packages/modules/src/firebase/functions-checkout/new-order.ts +4 -9
  72. package/packages/modules/src/firebase/functions-checkout/request-to-module.ts +2 -11
  73. package/packages/modules/src/firebase/handle-module.ts +1 -1
  74. package/packages/modules/src/firebase/serve-modules-api.ts +1 -1
  75. package/packages/modules/src/index.ts +2 -0
  76. package/packages/passport/lib/firebase/authenticate-customer.js +81 -0
  77. package/packages/passport/lib/firebase/authenticate-customer.js.map +1 -0
  78. package/packages/passport/lib/firebase/serve-passport-api.js +20 -30
  79. package/packages/passport/lib/firebase/serve-passport-api.js.map +1 -1
  80. package/packages/passport/lib/firebase.js +1 -13
  81. package/packages/passport/lib/firebase.js.map +1 -1
  82. package/packages/passport/lib/index.js +1 -1
  83. package/packages/passport/lib/index.js.map +1 -1
  84. package/packages/passport/package.json +1 -1
  85. package/packages/passport/src/firebase/authenticate-customer.ts +94 -0
  86. package/packages/passport/src/firebase/serve-passport-api.ts +21 -49
  87. package/packages/passport/src/firebase.ts +1 -21
  88. package/packages/passport/src/index.ts +4 -1
  89. package/packages/ssr/package.json +1 -1
  90. package/packages/storefront/content/header.json +6 -0
  91. package/packages/storefront/dist/client/LoginDrawer.e69d1c74.js +1 -0
  92. package/packages/storefront/dist/client/assets/_...d5980663.css +4 -0
  93. package/packages/storefront/dist/client/chunks/LoginDrawer.0c26574f.js +1 -0
  94. package/packages/storefront/dist/client/chunks/{LoginForm.c995d3d4.js → LoginForm.892d64a5.js} +109 -109
  95. package/packages/storefront/dist/client/chunks/runtime-dom.esm-bundler.7f8f570f.js +1 -0
  96. package/packages/storefront/dist/client/{client.6736232b.js → client.246ab4a4.js} +1 -1
  97. package/packages/storefront/dist/client/sw.js +1 -1
  98. package/packages/storefront/dist/server/entry.mjs +2204 -26
  99. package/packages/storefront/package.json +1 -1
  100. package/packages/storefront/src/assets/pico.css +3 -400
  101. package/packages/storefront/src/lib/components/{AOffcanvas.vue → ADrawer.vue} +3 -3
  102. package/packages/storefront/src/lib/components/LoginDrawer.vue +80 -0
  103. package/packages/storefront/src/lib/components/LoginForm.vue +31 -14
  104. package/packages/storefront/src/lib/layouts/PagesHeader.astro +18 -7
  105. package/packages/storefront/src/lib/state/customer-session.ts +137 -0
  106. package/packages/types/index.ts +22 -0
  107. package/packages/types/modules/@checkout:params.d.ts +9 -1
  108. package/packages/types/modules/list_payments:params.d.ts +4 -0
  109. package/packages/types/package.json +1 -1
  110. package/packages/passport/lib/firebase/handle-passport.js +0 -112
  111. package/packages/passport/lib/firebase/handle-passport.js.map +0 -1
  112. package/packages/passport/src/firebase/handle-passport.ts +0 -142
  113. package/packages/storefront/dist/client/LoginOffcanvas.28d2f50c.js +0 -1
  114. package/packages/storefront/dist/client/assets/_...41f686e3.css +0 -4
  115. package/packages/storefront/dist/client/chunks/LoginOffcanvas.a1f3fe3b.js +0 -1
  116. package/packages/storefront/dist/client/chunks/runtime-dom.esm-bundler.62d623e7.js +0 -1
  117. package/packages/storefront/src/lib/components/LoginOffcanvas.vue +0 -41
@@ -1,82 +1,79 @@
1
1
  import logger from 'firebase-functions/lib/logger';
2
2
  import updateAppData from '@cloudcommerce/firebase/lib/helpers/update-app-data';
3
+
3
4
  export default async (queueEntry, appData, application, payload) => {
4
- const isError = payload instanceof Error;
5
- const isImportation = queueEntry.action.endsWith('importation');
6
- const logs = appData.logs || [];
7
- const logEntry = {
8
- resource: /order/i.test(queueEntry.queue) ? 'orders' : 'products',
9
- [(isImportation ? 'tiny_id' : 'resource_id')]: queueEntry.nextId,
10
- success: !isError,
11
- imestamp: new Date().toISOString(),
12
- };
13
- let notes;
14
- if (payload) {
15
- if (!isError) {
16
- // payload = response
17
- const { data, status, config } = payload;
18
- if (data && data._id) {
19
- logEntry.resource_id = data._id;
20
- }
21
- notes = `Status ${status}`;
22
- if (config) {
23
- notes += ` [${config.url}]`;
24
- }
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
+ let notes;
15
+ if (payload) {
16
+ if (!isError) {
17
+ // payload = response
18
+ const { data, status, config } = payload;
19
+ if (data && data._id) {
20
+ logEntry.resource_id = data._id;
21
+ }
22
+ notes = `Status ${status}`;
23
+ if (config) {
24
+ notes += ` [${config.url}]`;
25
+ }
26
+ } else {
27
+ const { config, response } = payload;
28
+ if (response) {
29
+ const { data, status } = response;
30
+ notes = `Error: Status ${status} \n${JSON.stringify(data)}`;
31
+ if (!status || status === 429 || status >= 500) {
32
+ return setTimeout(() => {
33
+ throw payload;
34
+ }, 2000);
25
35
  }
26
- else {
27
- const { config, response } = payload;
28
- if (response) {
29
- const { data, status } = response;
30
- notes = `Error: Status ${status} \n${JSON.stringify(data)}`;
31
- if (!status || status === 429 || status >= 500) {
32
- return setTimeout(() => {
33
- throw payload;
34
- }, 2000);
35
- }
36
- if (config) {
37
- const { url, method, data } = config;
38
- notes += `\n\n-- Request -- \n${method} ${url} \n${JSON.stringify(data)}`;
39
- }
40
- // @ts-ignore
41
- }
42
- else if (payload.isConfigError === true) {
43
- notes = payload.message;
44
- }
45
- else {
46
- notes = payload.stack;
47
- }
36
+ if (config) {
37
+ const { url, method, data } = config;
38
+ notes += `\n\n-- Request -- \n${method} ${url} \n${JSON.stringify(data)}`;
48
39
  }
40
+ // @ts-ignore
41
+ } else if (payload.isConfigError === true) {
42
+ notes = payload.message;
43
+ } else {
44
+ notes = payload.stack;
45
+ }
49
46
  }
50
- if (notes) {
51
- logEntry.notes = notes.substring(0, 5000);
47
+ }
48
+ if (notes) {
49
+ logEntry.notes = notes.substring(0, 5000);
50
+ }
51
+ if (isError || !isImportation) {
52
+ logs.unshift(logEntry);
53
+ await updateAppData(application, {
54
+ logs: logs.slice(0, 200),
55
+ }, {
56
+ isHiddenData: true,
57
+ canSendPubSub: false,
58
+ });
59
+ }
60
+ const { action, queue, nextId } = queueEntry;
61
+ let queueList = appData[action][queue];
62
+ if (Array.isArray(queueList)) {
63
+ const idIndex = queueList.indexOf(nextId);
64
+ if (idIndex > -1) {
65
+ queueList.splice(idIndex, 1);
52
66
  }
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
- }
70
- else {
71
- queueList = [];
72
- }
73
- const data = {
74
- [action]: {
75
- ...appData[action],
76
- [queue]: queueList,
77
- },
78
- };
79
- logger.info(JSON.stringify(data));
80
- return updateAppData(application, data);
67
+ } else {
68
+ queueList = [];
69
+ }
70
+ const data = {
71
+ [action]: {
72
+ ...appData[action],
73
+ [queue]: queueList,
74
+ },
75
+ };
76
+ logger.info(JSON.stringify(data));
77
+ return updateAppData(application, data);
81
78
  };
82
- //# sourceMappingURL=after-tiny-queue.js.map
79
+ // # sourceMappingURL=after-tiny-queue.js.map
@@ -3,85 +3,82 @@ import api from '@cloudcommerce/api';
3
3
  import postTiny from './post-tiny-erp.js';
4
4
  import parseStatus from './parsers/status-to-tiny.js';
5
5
  import parseOrder from './parsers/order-to-tiny.js';
6
+
6
7
  export default async (apiDoc, queueEntry, appData, canCreateNew) => {
7
- const orderId = queueEntry.nextId;
8
- let order;
9
- if (orderId === apiDoc._id) {
10
- order = apiDoc;
11
- }
12
- else {
13
- try {
14
- order = (await api.get(`orders/${orderId}`)).data;
15
- }
16
- catch (err) {
17
- if (err.statusCode === 404) {
18
- const msg = `O pedido ${orderId} não existe (:${err.statusCode})`;
19
- const error = new Error(msg);
20
- error.isConfigError = true;
21
- return error;
22
- }
23
- throw err;
24
- }
25
- }
26
- if (!order.financial_status) {
27
- logger.info(`${orderId} skipped with no financial status`);
28
- return null;
29
- }
30
- logger.info(`${orderId} searching order ${order.number}`);
31
- let tinyData;
8
+ const orderId = queueEntry.nextId;
9
+ let order;
10
+ if (orderId === apiDoc._id) {
11
+ order = apiDoc;
12
+ } else {
32
13
  try {
33
- tinyData = await postTiny('/pedidos.pesquisa.php', {
34
- numeroEcommerce: String(order.number),
35
- });
14
+ order = (await api.get(`orders/${orderId}`)).data;
15
+ } catch (err) {
16
+ if (err.statusCode === 404) {
17
+ const msg = `O pedido ${orderId} não existe (:${err.statusCode})`;
18
+ const error = new Error(msg);
19
+ error.isConfigError = true;
20
+ return error;
21
+ }
22
+ throw err;
23
+ }
24
+ }
25
+ if (!order.financial_status) {
26
+ logger.info(`${orderId} skipped with no financial status`);
27
+ return null;
28
+ }
29
+ logger.info(`${orderId} searching order ${order.number}`);
30
+ let tinyData;
31
+ try {
32
+ tinyData = await postTiny('/pedidos.pesquisa.php', {
33
+ numeroEcommerce: String(order.number),
34
+ });
35
+ } catch (err) {
36
+ const status = err.response && err.response.status;
37
+ if (status === 404) {
38
+ tinyData = {};
39
+ } else {
40
+ logger.info(`${orderId} search on tiny ends with status ${status}`);
41
+ throw err;
36
42
  }
37
- catch (err) {
38
- const status = err.response && err.response.status;
39
- if (status === 404) {
40
- tinyData = {};
41
- }
42
- else {
43
- logger.info(`${orderId} search on tiny ends with status ${status}`);
44
- throw err;
45
- }
43
+ }
44
+ const { pedidos } = tinyData;
45
+ const tinyStatus = parseStatus(order);
46
+ let originalTinyOrder;
47
+ if (Array.isArray(pedidos)) {
48
+ originalTinyOrder = pedidos.find(({ pedido }) => {
49
+ return order.number === Number(pedido.numero_ecommerce);
50
+ });
51
+ if (originalTinyOrder) {
52
+ originalTinyOrder = originalTinyOrder.pedido;
46
53
  }
47
- const { pedidos } = tinyData;
48
- const tinyStatus = parseStatus(order);
49
- let originalTinyOrder;
50
- if (Array.isArray(pedidos)) {
51
- originalTinyOrder = pedidos.find(({ pedido }) => {
52
- return order.number === Number(pedido.numero_ecommerce);
53
- });
54
- if (originalTinyOrder) {
55
- originalTinyOrder = originalTinyOrder.pedido;
56
- }
54
+ }
55
+ if (!originalTinyOrder) {
56
+ if (!canCreateNew) {
57
+ return null;
57
58
  }
58
- if (!originalTinyOrder) {
59
- if (!canCreateNew) {
60
- return null;
61
- }
62
- if (appData.approved_orders_only
59
+ if (appData.approved_orders_only
63
60
  && (tinyStatus === 'aberto' || tinyStatus === 'cancelado')) {
64
- logger.info(`${orderId} skipped with status "${tinyStatus}"`);
65
- return null;
66
- }
67
- const tinyOrder = parseOrder(order, appData);
68
- logger.info(`${orderId} ${JSON.stringify(tinyOrder)}`);
69
- return postTiny('/pedido.incluir.php', {
70
- pedido: {
71
- pedido: tinyOrder,
72
- },
73
- });
61
+ logger.info(`${orderId} skipped with status "${tinyStatus}"`);
62
+ return null;
74
63
  }
75
- if (originalTinyOrder) {
76
- const { id, situacao } = originalTinyOrder;
77
- logger.info(`${orderId} found with tiny status ${situacao} => ${tinyStatus}`);
78
- if (tinyStatus && tinyStatus !== situacao) {
79
- return postTiny('/pedido.alterar.situacao', {
80
- id,
81
- situacao: tinyStatus,
82
- });
83
- }
64
+ const tinyOrder = parseOrder(order, appData);
65
+ logger.info(`${orderId} ${JSON.stringify(tinyOrder)}`);
66
+ return postTiny('/pedido.incluir.php', {
67
+ pedido: {
68
+ pedido: tinyOrder,
69
+ },
70
+ });
71
+ }
72
+ if (originalTinyOrder) {
73
+ const { id, situacao } = originalTinyOrder;
74
+ logger.info(`${orderId} found with tiny status ${situacao} => ${tinyStatus}`);
75
+ if (tinyStatus && tinyStatus !== situacao) {
76
+ return postTiny('/pedido.alterar.situacao', {
77
+ id,
78
+ situacao: tinyStatus,
79
+ });
84
80
  }
85
- return null;
81
+ }
82
+ return null;
86
83
  };
87
- //# sourceMappingURL=export-order-to-tiny.js.map
84
+ // # sourceMappingURL=export-order-to-tiny.js.map
@@ -1,62 +1,58 @@
1
1
  import api from '@cloudcommerce/api';
2
2
  import postTiny from './post-tiny-erp.js';
3
3
  import parseProduct from './parsers/product-to-tiny.js';
4
+
4
5
  export default async (apiDoc, queueEntry, appData, canCreateNew) => {
5
- const productId = queueEntry.nextId;
6
- let product;
7
- if (productId === apiDoc._id) {
8
- product = apiDoc;
9
- }
10
- else {
11
- try {
12
- product = (await api.get(`products/${productId}`)).data;
13
- }
14
- catch (err) {
15
- if (err.statusCode === 404) {
16
- const msg = `O produto ${productId} não existe (:${err.statusCode})`;
17
- const error = new Error(msg);
18
- error.isConfigError = true;
19
- return error;
20
- }
21
- throw err;
22
- }
23
- }
24
- let tinyData;
6
+ const productId = queueEntry.nextId;
7
+ let product;
8
+ if (productId === apiDoc._id) {
9
+ product = apiDoc;
10
+ } else {
25
11
  try {
26
- tinyData = await postTiny('/produtos.pesquisa.php', {
27
- pesquisa: product.sku,
28
- });
12
+ product = (await api.get(`products/${productId}`)).data;
13
+ } catch (err) {
14
+ if (err.statusCode === 404) {
15
+ const msg = `O produto ${productId} não existe (:${err.statusCode})`;
16
+ const error = new Error(msg);
17
+ error.isConfigError = true;
18
+ return error;
19
+ }
20
+ throw err;
29
21
  }
30
- catch (err) {
31
- if (err.response && err.response.status === 404) {
32
- tinyData = {};
33
- }
34
- else {
35
- throw err;
36
- }
22
+ }
23
+ let tinyData;
24
+ try {
25
+ tinyData = await postTiny('/produtos.pesquisa.php', {
26
+ pesquisa: product.sku,
27
+ });
28
+ } catch (err) {
29
+ if (err.response && err.response.status === 404) {
30
+ tinyData = {};
31
+ } else {
32
+ throw err;
37
33
  }
38
- const { produtos } = tinyData;
39
- let originalTinyProduct;
40
- if (Array.isArray(produtos)) {
41
- originalTinyProduct = produtos.find(({ produto }) => {
42
- return product.sku === String(produto.codigo);
43
- });
44
- if (originalTinyProduct) {
45
- originalTinyProduct = originalTinyProduct.produto;
46
- }
47
- else if (!canCreateNew) {
48
- return null;
49
- }
34
+ }
35
+ const { produtos } = tinyData;
36
+ let originalTinyProduct;
37
+ if (Array.isArray(produtos)) {
38
+ originalTinyProduct = produtos.find(({ produto }) => {
39
+ return product.sku === String(produto.codigo);
40
+ });
41
+ if (originalTinyProduct) {
42
+ originalTinyProduct = originalTinyProduct.produto;
43
+ } else if (!canCreateNew) {
44
+ return null;
50
45
  }
51
- const tinyProduct = parseProduct(product, originalTinyProduct, appData);
52
- return tinyProduct
53
- ? postTiny(originalTinyProduct ? '/produto.alterar.php' : '/produto.incluir.php', {
54
- produto: {
55
- produtos: [{
56
- produto: tinyProduct,
57
- }],
58
- },
59
- })
60
- : null;
46
+ }
47
+ const tinyProduct = parseProduct(product, originalTinyProduct, appData);
48
+ return tinyProduct
49
+ ? postTiny(originalTinyProduct ? '/produto.alterar.php' : '/produto.incluir.php', {
50
+ produto: {
51
+ produtos: [{
52
+ produto: tinyProduct,
53
+ }],
54
+ },
55
+ })
56
+ : null;
61
57
  };
62
- //# sourceMappingURL=export-product-to-tiny.js.map
58
+ // # sourceMappingURL=export-product-to-tiny.js.map
@@ -1,7 +1,7 @@
1
1
  export default (d) => {
2
- /* eslint-disable prefer-template */
3
- return d.getDate().toString().padStart(2, '0') + '/'
2
+ /* eslint-disable prefer-template */
3
+ return d.getDate().toString().padStart(2, '0') + '/'
4
4
  + (d.getMonth() + 1).toString().padStart(2, '0') + '/'
5
5
  + d.getFullYear();
6
6
  };
7
- //# sourceMappingURL=format-tiny-date.js.map
7
+ // # sourceMappingURL=format-tiny-date.js.map
@@ -5,87 +5,88 @@ import api from '@cloudcommerce/api';
5
5
  import postTiny from './post-tiny-erp.js';
6
6
  import parseOrder from './parsers/order-from-tiny.js';
7
7
  import parseStatus from './parsers/status-from-tiny.js';
8
+
8
9
  const getLastStatus = (records) => {
9
- let statusRecord;
10
- records.forEach((record) => {
11
- if (record
10
+ let statusRecord;
11
+ records.forEach((record) => {
12
+ if (record
12
13
  && (!statusRecord || !record.date_time || record.date_time >= statusRecord.date_time)) {
13
- statusRecord = record;
14
- }
15
- });
16
- return statusRecord && statusRecord.status;
14
+ statusRecord = record;
15
+ }
16
+ });
17
+ return statusRecord && statusRecord.status;
17
18
  };
19
+
18
20
  export default async (apiDoc, queueEntry) => {
19
- const getTinyOrder = async (tinyOrderId) => {
20
- const { pedido } = await postTiny('/pedido.obter.php', {
21
- id: Number(tinyOrderId),
22
- });
23
- const situacao = typeof pedido.situacao === 'string'
24
- ? pedido.situacao.toLowerCase()
25
- : null;
26
- const orderNumber = pedido.numero_ecommerce;
27
- logger.info(`Import order n${orderNumber} ${tinyOrderId} => ${situacao}`);
28
- const documentRef = getFirestore().doc(`tinyErpOrders/${tinyOrderId}`);
29
- const documentSnapshot = await documentRef.get();
30
- if (documentSnapshot.exists
21
+ const getTinyOrder = async (tinyOrderId) => {
22
+ const { pedido } = await postTiny('/pedido.obter.php', {
23
+ id: Number(tinyOrderId),
24
+ });
25
+ const situacao = typeof pedido.situacao === 'string'
26
+ ? pedido.situacao.toLowerCase()
27
+ : null;
28
+ const orderNumber = pedido.numero_ecommerce;
29
+ logger.info(`Import order n${orderNumber} ${tinyOrderId} => ${situacao}`);
30
+ const documentRef = getFirestore().doc(`tinyErpOrders/${tinyOrderId}`);
31
+ const documentSnapshot = await documentRef.get();
32
+ if (documentSnapshot.exists
31
33
  && documentSnapshot.get('situacao') === situacao) {
32
- logger.info(`>> Ignoring Tiny order n${orderNumber} ${tinyOrderId} with same status`);
33
- return null;
34
- }
35
- let listEndpoint = 'orders?limit=1&fields=_id,payments_history,fulfillments,shipping_lines';
36
- if (orderNumber) {
37
- listEndpoint += `&number=${orderNumber}`;
38
- }
39
- else {
40
- listEndpoint += `&hidden_metafields.value=${tinyOrderId}_tiny`;
41
- }
42
- const { data: { result } } = await api.get(listEndpoint);
43
- if (!result.length) {
44
- return null;
45
- }
46
- const order = result[0];
47
- const partialOrder = await parseOrder(pedido, order.shipping_lines);
48
- const promises = [];
49
- if (partialOrder && Object.keys(partialOrder).length) {
50
- promises.push(api.patch(`orders/${order._id}`, partialOrder));
51
- }
52
- const { fulfillmentStatus, financialStatus } = parseStatus(situacao);
53
- const data = {
54
- date_time: new Date().toISOString(),
55
- flags: ['from-tiny'],
56
- };
57
- [
58
- [financialStatus, 'payments_history'],
59
- [fulfillmentStatus, 'fulfillments'],
60
- ].forEach(([newStatus, subresource]) => {
61
- if (newStatus
34
+ logger.info(`>> Ignoring Tiny order n${orderNumber} ${tinyOrderId} with same status`);
35
+ return null;
36
+ }
37
+ let listEndpoint = 'orders?limit=1&fields=_id,payments_history,fulfillments,shipping_lines';
38
+ if (orderNumber) {
39
+ listEndpoint += `&number=${orderNumber}`;
40
+ } else {
41
+ listEndpoint += `&hidden_metafields.value=${tinyOrderId}_tiny`;
42
+ }
43
+ const { data: { result } } = await api.get(listEndpoint);
44
+ if (!result.length) {
45
+ return null;
46
+ }
47
+ const order = result[0];
48
+ const partialOrder = await parseOrder(pedido, order.shipping_lines);
49
+ const promises = [];
50
+ if (partialOrder && Object.keys(partialOrder).length) {
51
+ promises.push(api.patch(`orders/${order._id}`, partialOrder));
52
+ }
53
+ const { fulfillmentStatus, financialStatus } = parseStatus(situacao);
54
+ const data = {
55
+ date_time: new Date().toISOString(),
56
+ flags: ['from-tiny'],
57
+ };
58
+ [
59
+ [financialStatus, 'payments_history'],
60
+ [fulfillmentStatus, 'fulfillments'],
61
+ ].forEach(([newStatus, subresource]) => {
62
+ if (newStatus
62
63
  // @ts-ignore
63
64
  && (!order[subresource] || getLastStatus(order[subresource]) !== newStatus)) {
64
- data.status = newStatus;
65
- promises.push(api.post(`orders/${order._id}/${subresource}`, data));
66
- logger.info(`${order._id} updated to ${newStatus} from Tiny ${tinyOrderId}`);
67
- }
68
- });
69
- return Promise.all(promises)
70
- .then(([firstResult]) => {
71
- documentRef.set({ situacao }).catch(logger.error);
72
- return (firstResult && firstResult.response) || firstResult;
73
- });
74
- };
75
- const tinyOrderNumber = queueEntry.nextId;
76
- if (typeof tinyOrderNumber === 'string' && tinyOrderNumber.startsWith('id:')) {
77
- return getTinyOrder(tinyOrderNumber.substring(3));
78
- }
79
- return postTiny('/pedidos.pesquisa.php', {
80
- numero: tinyOrderNumber,
81
- }).then(({ pedidos }) => {
82
- const tinyOrder = pedidos.find(({ pedido }) => {
83
- return Number(tinyOrderNumber) === Number(pedido.numero);
84
- });
85
- if (tinyOrder) {
86
- return getTinyOrder(tinyOrder.pedido.id);
87
- }
88
- return null;
65
+ data.status = newStatus;
66
+ promises.push(api.post(`orders/${order._id}/${subresource}`, data));
67
+ logger.info(`${order._id} updated to ${newStatus} from Tiny ${tinyOrderId}`);
68
+ }
69
+ });
70
+ return Promise.all(promises)
71
+ .then(([firstResult]) => {
72
+ documentRef.set({ situacao }).catch(logger.error);
73
+ return (firstResult && firstResult.response) || firstResult;
74
+ });
75
+ };
76
+ const tinyOrderNumber = queueEntry.nextId;
77
+ if (typeof tinyOrderNumber === 'string' && tinyOrderNumber.startsWith('id:')) {
78
+ return getTinyOrder(tinyOrderNumber.substring(3));
79
+ }
80
+ return postTiny('/pedidos.pesquisa.php', {
81
+ numero: tinyOrderNumber,
82
+ }).then(({ pedidos }) => {
83
+ const tinyOrder = pedidos.find(({ pedido }) => {
84
+ return Number(tinyOrderNumber) === Number(pedido.numero);
89
85
  });
86
+ if (tinyOrder) {
87
+ return getTinyOrder(tinyOrder.pedido.id);
88
+ }
89
+ return null;
90
+ });
90
91
  };
91
- //# sourceMappingURL=import-order-from-tiny.js.map
92
+ // # sourceMappingURL=import-order-from-tiny.js.map