cloudcommerce 0.0.62 → 0.0.65

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 (96) hide show
  1. package/.eslintrc.cjs +1 -1
  2. package/CHANGELOG.md +34 -0
  3. package/package.json +1 -1
  4. package/packages/api/lib/api.d.ts +8 -8
  5. package/packages/api/lib/types/applications.d.ts +2 -2
  6. package/packages/api/package.json +1 -1
  7. package/packages/api/src/types/applications.d.ts +2 -2
  8. package/packages/apps/correios/CHANGELOG.md +1 -0
  9. package/packages/apps/correios/README.md +1 -0
  10. package/packages/apps/correios/lib/correios.d.ts +2 -0
  11. package/packages/apps/correios/lib/correios.js +6 -0
  12. package/packages/apps/correios/lib/correios.js.map +1 -0
  13. package/packages/apps/correios/lib/index.d.ts +1 -0
  14. package/packages/apps/correios/lib/index.js +2 -0
  15. package/packages/apps/correios/lib/index.js.map +1 -0
  16. package/packages/apps/correios/lib-mjs/calculate-correios.mjs +470 -0
  17. package/packages/apps/correios/lib-mjs/correios-ws.mjs +154 -0
  18. package/packages/apps/correios/package.json +29 -0
  19. package/packages/apps/correios/src/correios.ts +7 -0
  20. package/packages/apps/correios/src/index.ts +1 -0
  21. package/packages/apps/correios/tsconfig.json +6 -0
  22. package/packages/apps/custom-shipping/CHANGELOG.md +1 -0
  23. package/packages/apps/custom-shipping/README.md +1 -0
  24. package/packages/apps/custom-shipping/lib/custom-shipping.d.ts +2 -0
  25. package/packages/apps/custom-shipping/lib/custom-shipping.js +6 -0
  26. package/packages/apps/custom-shipping/lib/custom-shipping.js.map +1 -0
  27. package/packages/apps/custom-shipping/lib/index.d.ts +1 -0
  28. package/packages/apps/custom-shipping/lib/index.js +2 -0
  29. package/packages/apps/custom-shipping/lib/index.js.map +1 -0
  30. package/packages/apps/custom-shipping/lib-mjs/calculate-custom-shipping.mjs +251 -0
  31. package/packages/apps/custom-shipping/package.json +27 -0
  32. package/packages/apps/custom-shipping/src/custom-shipping.ts +7 -0
  33. package/packages/apps/custom-shipping/src/index.ts +1 -0
  34. package/packages/apps/custom-shipping/tsconfig.json +6 -0
  35. package/packages/apps/discounts/lib/index.js +1 -1
  36. package/packages/apps/discounts/package.json +3 -7
  37. package/packages/apps/tiny-erp/README.md +1 -1
  38. package/packages/apps/tiny-erp/lib/event-to-tiny.js +0 -2
  39. package/packages/apps/tiny-erp/lib/event-to-tiny.js.map +1 -1
  40. package/packages/apps/tiny-erp/lib/index.js +1 -1
  41. package/packages/apps/tiny-erp/lib/integration/export-order-to-tiny.js +9 -6
  42. package/packages/apps/tiny-erp/lib/integration/export-order-to-tiny.js.map +1 -1
  43. package/packages/apps/tiny-erp/lib/tiny-erp.js +6 -5
  44. package/packages/apps/tiny-erp/lib/tiny-erp.js.map +1 -1
  45. package/packages/apps/tiny-erp/package.json +1 -1
  46. package/packages/apps/tiny-erp/src/event-to-tiny.ts +0 -2
  47. package/packages/apps/tiny-erp/src/integration/export-order-to-tiny.ts +9 -6
  48. package/packages/apps/tiny-erp/src/tiny-erp.ts +9 -7
  49. package/packages/cli/package.json +1 -1
  50. package/packages/events/lib/firebase.js.map +1 -1
  51. package/packages/events/package.json +1 -1
  52. package/packages/events/src/firebase.ts +0 -1
  53. package/packages/firebase/lib/config.d.ts +6 -0
  54. package/packages/firebase/lib/config.js +6 -0
  55. package/packages/firebase/lib/config.js.map +1 -1
  56. package/packages/firebase/lib/index.js.map +1 -1
  57. package/packages/firebase/lib/init.js.map +1 -1
  58. package/packages/firebase/package.json +1 -1
  59. package/packages/firebase/src/config.ts +6 -0
  60. package/packages/firebase/src/index.ts +0 -1
  61. package/packages/firebase/src/init.ts +0 -1
  62. package/packages/modules/lib/firebase/call-app-module.js +33 -13
  63. package/packages/modules/lib/firebase/call-app-module.js.map +1 -1
  64. package/packages/modules/lib/firebase.js.map +1 -1
  65. package/packages/modules/package.json +3 -1
  66. package/packages/modules/src/firebase/call-app-module.ts +34 -14
  67. package/packages/modules/src/firebase.ts +0 -1
  68. package/packages/passport/package.json +1 -1
  69. package/packages/ssr/lib/firebase.js.map +1 -1
  70. package/packages/ssr/package.json +1 -1
  71. package/packages/ssr/src/firebase.ts +0 -1
  72. package/packages/storefront/astro.config.mjs +20 -0
  73. package/packages/storefront/dist/client/assets/_...0b5ebd52.css +1 -0
  74. package/packages/storefront/dist/client/assets/_...d4aa8aff.css +1 -0
  75. package/packages/storefront/dist/client/assets/index.5608ba47.css +1 -0
  76. package/packages/storefront/dist/client/client.dbac84dd.js +1 -0
  77. package/packages/storefront/dist/client/favicon.ico +0 -0
  78. package/packages/storefront/dist/client/page.3aa82516.js +1 -0
  79. package/packages/storefront/dist/client/~partytown/partytown-atomics.js +2 -0
  80. package/packages/storefront/dist/client/~partytown/partytown-media.js +2 -0
  81. package/packages/storefront/dist/client/~partytown/partytown-sw.js +2 -0
  82. package/packages/storefront/dist/client/~partytown/partytown.js +2 -0
  83. package/packages/storefront/dist/server/entry.mjs +1674 -0
  84. package/packages/storefront/package.json +7 -3
  85. package/packages/storefront/public/favicon.ico +0 -0
  86. package/packages/storefront/src/components/Card.astro +74 -0
  87. package/packages/storefront/src/layouts/Layout.astro +56 -0
  88. package/packages/storefront/src/pages/[...slug].astro +76 -0
  89. package/packages/storefront/src/pages/index.astro +82 -0
  90. package/packages/storefront/tsconfig.json +3 -0
  91. package/packages/types/package.json +1 -1
  92. package/packages/apps/_app.config.js +0 -80
  93. package/packages/apps/discounts/lib/discounts.config.d.ts +0 -14
  94. package/packages/apps/discounts/lib/discounts.config.js +0 -19
  95. package/packages/apps/discounts/lib/discounts.config.js.map +0 -1
  96. package/packages/apps/discounts/src/discounts.config.ts +0 -25
package/.eslintrc.cjs CHANGED
@@ -26,7 +26,7 @@ module.exports = {
26
26
  'no-nested-ternary': 'warn',
27
27
  'no-await-in-loop': 'warn',
28
28
  'no-shadow': 'warn',
29
- 'no-param-reassign': 'warn',
29
+ 'no-param-reassign': 'off',
30
30
  'no-underscore-dangle': 'off',
31
31
  'no-continue': 'off',
32
32
  'lines-between-class-members': 'off',
package/CHANGELOG.md CHANGED
@@ -2,6 +2,40 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4
4
 
5
+ ### [0.0.65](https://github.com/ecomplus/cloud-commerce/compare/v0.0.64...v0.0.65) (2022-09-03)
6
+
7
+
8
+ ### Features
9
+
10
+ * **custom-shipping:** Setup custom shipping app from github.com/ecomplus/app-custom-shipping/ ([78818ea](https://github.com/ecomplus/cloud-commerce/commit/78818ead244741bea2a2c02becb465863b087461))
11
+ * **modules:** Handle custom shipping calculation with internal package ([b555a12](https://github.com/ecomplus/cloud-commerce/commit/b555a12dc8e2d7b6b11a5993d0ba846e645ced9e))
12
+
13
+
14
+ ### Bug Fixes
15
+
16
+ * **tiny-erp:** Prevent exporting order with same Tiny status ([8b22e1b](https://github.com/ecomplus/cloud-commerce/commit/8b22e1b18a6b0494c794bd21f4bf38dcf9f92dc4))
17
+
18
+ ### [0.0.64](https://github.com/ecomplus/cloud-commerce/compare/v0.0.63...v0.0.64) (2022-09-02)
19
+
20
+
21
+ ### Features
22
+
23
+ * **correios:** Setup Correios app from https://github.com/ecomplus/app-correios ([aa18bed](https://github.com/ecomplus/cloud-commerce/commit/aa18bed5193bfbcf7075614c5b41b7e84497efca))
24
+ * **modules:** Handle Correios calculate shipping with internal package ([88e6f7f](https://github.com/ecomplus/cloud-commerce/commit/88e6f7f30cedf35c9a05f0f4d24637946c21b3cf))
25
+
26
+
27
+ ### Bug Fixes
28
+
29
+ * **api:** Update applications interface with `data?: { [k: string]: any }` instead of unknow ([a44a6c9](https://github.com/ecomplus/cloud-commerce/commit/a44a6c9d93a5550843115cad3cbcb2a231691b1b))
30
+ * **modules:** Also debug internal modules error responses ([9c89962](https://github.com/ecomplus/cloud-commerce/commit/9c89962924984b48cd52f308bc173c18a4a90939))
31
+
32
+ ### [0.0.63](https://github.com/ecomplus/cloud-commerce/compare/v0.0.62...v0.0.63) (2022-08-31)
33
+
34
+
35
+ ### Bug Fixes
36
+
37
+ * Group app (Tiny ERP) functions and fix name for CLoud Functions v2 limits ([a059056](https://github.com/ecomplus/cloud-commerce/commit/a0590564ce8e376c000ba02ccb3b2a94d31e3c0d))
38
+
5
39
  ### [0.0.62](https://github.com/ecomplus/cloud-commerce/compare/v0.0.61...v0.0.62) (2022-08-31)
6
40
 
7
41
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "cloudcommerce",
3
3
  "type": "module",
4
- "version": "0.0.62",
4
+ "version": "0.0.65",
5
5
  "description": "Open fair-code headless commerce platform: API-first, microservices based, event driven and cloud native",
6
6
  "main": "packages/api/lib/index.js",
7
7
  "author": "E-Com Club Softwares para E-commerce <ti@e-com.club>",
@@ -1235,10 +1235,10 @@ declare const api: {
1235
1235
  };
1236
1236
  } | undefined;
1237
1237
  data?: {
1238
- [k: string]: unknown;
1238
+ [k: string]: any;
1239
1239
  } | undefined;
1240
1240
  hidden_data?: {
1241
- [k: string]: unknown;
1241
+ [k: string]: any;
1242
1242
  } | undefined;
1243
1243
  } : E_1 extends "authentications" | `authentications/${string}` ? {
1244
1244
  name?: string | undefined;
@@ -2483,10 +2483,10 @@ declare const api: {
2483
2483
  };
2484
2484
  } | undefined;
2485
2485
  data?: {
2486
- [k: string]: unknown;
2486
+ [k: string]: any;
2487
2487
  } | undefined;
2488
2488
  hidden_data?: {
2489
- [k: string]: unknown;
2489
+ [k: string]: any;
2490
2490
  } | undefined;
2491
2491
  } : E_2 extends "authentications" | `authentications/${string}` ? {
2492
2492
  name?: string | undefined;
@@ -3739,10 +3739,10 @@ declare const post: <E extends Endpoint, C extends AbstractedConfig>(endpoint: E
3739
3739
  };
3740
3740
  } | undefined;
3741
3741
  data?: {
3742
- [k: string]: unknown;
3742
+ [k: string]: any;
3743
3743
  } | undefined;
3744
3744
  hidden_data?: {
3745
- [k: string]: unknown;
3745
+ [k: string]: any;
3746
3746
  } | undefined;
3747
3747
  } : E extends "authentications" | `authentications/${string}` ? {
3748
3748
  name?: string | undefined;
@@ -4987,10 +4987,10 @@ declare const put: <E extends `products/${string}` | `categories/${string}` | `b
4987
4987
  };
4988
4988
  } | undefined;
4989
4989
  data?: {
4990
- [k: string]: unknown;
4990
+ [k: string]: any;
4991
4991
  } | undefined;
4992
4992
  hidden_data?: {
4993
- [k: string]: unknown;
4993
+ [k: string]: any;
4994
4994
  } | undefined;
4995
4995
  } : E extends "authentications" | `authentications/${string}` ? {
4996
4996
  name?: string | undefined;
@@ -79,13 +79,13 @@ export interface Applications {
79
79
  * Application object data, schema free
80
80
  */
81
81
  data?: {
82
- [k: string]: unknown;
82
+ [k: string]: any;
83
83
  };
84
84
  /**
85
85
  * Application private data, available only with authentication
86
86
  */
87
87
  hidden_data?: {
88
- [k: string]: unknown;
88
+ [k: string]: any;
89
89
  };
90
90
  /**
91
91
  * Flags to associate additional info
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@cloudcommerce/api",
3
3
  "type": "module",
4
- "version": "0.0.62",
4
+ "version": "0.0.65",
5
5
  "description": "E-Com Plus Cloud Commerce APIs client/adapter",
6
6
  "main": "lib/api.js",
7
7
  "types": "lib/api.d.ts",
@@ -79,13 +79,13 @@ export interface Applications {
79
79
  * Application object data, schema free
80
80
  */
81
81
  data?: {
82
- [k: string]: unknown;
82
+ [k: string]: any;
83
83
  };
84
84
  /**
85
85
  * Application private data, available only with authentication
86
86
  */
87
87
  hidden_data?: {
88
- [k: string]: unknown;
88
+ [k: string]: any;
89
89
  };
90
90
  /**
91
91
  * Flags to associate additional info
@@ -0,0 +1 @@
1
+ Please refer to GitHub [repository releases](https://github.com/ecomplus/cloud-commerce/releases) or monorepo unified [CHANGELOG.md](https://github.com/ecomplus/cloud-commerce/blob/main/CHANGELOG.md).
@@ -0,0 +1 @@
1
+ # `@cloudcommerce/app-correios`
@@ -0,0 +1,2 @@
1
+ import type { AppModuleBody } from '@cloudcommerce/types';
2
+ export declare const calculateShipping: (modBody: AppModuleBody) => Promise<any>;
@@ -0,0 +1,6 @@
1
+ import handleCalculateShipping from '../lib-mjs/calculate-correios.mjs';
2
+
3
+ export const calculateShipping = async (modBody) => {
4
+ return handleCalculateShipping(modBody);
5
+ };
6
+ // # sourceMappingURL=correios.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"correios.js","sourceRoot":"","sources":["../src/correios.ts"],"names":[],"mappings":"AAEA,OAAO,uBAAuB,MAAM,mCAAmC,CAAC;AAExE,MAAM,CAAC,MAAM,iBAAiB,GAAG,KAAK,EAAE,OAAsB,EAAE,EAAE;IAChE,OAAO,uBAAuB,CAAC,OAAO,CAAC,CAAC;AAC1C,CAAC,CAAC"}
@@ -0,0 +1 @@
1
+ export * from './correios';
@@ -0,0 +1,2 @@
1
+ export * from './correios.js';
2
+ // # sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,YAAY,CAAC"}
@@ -0,0 +1,470 @@
1
+ import correiosCalculate from './correios-ws.mjs';
2
+
3
+ export default async ({ params, application }) => {
4
+ const config = {
5
+ ...application.data,
6
+ ...application.hidden_data,
7
+ };
8
+
9
+ // Correios calculate params
10
+ let nCdServico;
11
+ let sCdMaoPropria;
12
+ let sCdAvisoRecebimento;
13
+ let nVlPeso = 0;
14
+ let nVlValorDeclarado = 0;
15
+ let nCdEmpresa = '';
16
+ let sDsSenha = '';
17
+ const contract = config.correios_contract;
18
+ if (contract) {
19
+ const code = typeof contract.code === 'string' && contract.code.trim();
20
+ if (code) {
21
+ nCdEmpresa = code;
22
+ const password = typeof contract.password === 'string' && contract.password.trim();
23
+ if (password) {
24
+ sDsSenha = password;
25
+ }
26
+ }
27
+ }
28
+ const sCepDestino = params.to?.zip.replace(/\D/g, '') || '';
29
+ const sCepOrigem = params.from?.zip.replace(/\D/g, '')
30
+ || config.zip?.replace(/\D/g, '')
31
+ || '';
32
+
33
+ const checkZipCode = (rule) => {
34
+ // validate rule zip range
35
+ if (sCepDestino && rule.zip_range) {
36
+ const { min, max } = rule.zip_range;
37
+ return Boolean((!min || sCepDestino >= min) && (!max || sCepDestino <= max));
38
+ }
39
+ return true;
40
+ };
41
+
42
+ // https://apx-mods.e-com.plus/api/v1/calculate_shipping/response_schema.json?store_id=100
43
+ const response = {
44
+ shipping_services: [],
45
+ };
46
+ // search for configured free shipping rule
47
+ if (Array.isArray(config.shipping_rules)) {
48
+ for (let i = 0; i < config.shipping_rules.length; i++) {
49
+ const rule = config.shipping_rules[i];
50
+ if (rule.free_shipping && checkZipCode(rule)) {
51
+ if (!rule.min_amount) {
52
+ response.free_shipping_from_value = 0;
53
+ break;
54
+ } else if (!(response.free_shipping_from_value <= rule.min_amount)) {
55
+ response.free_shipping_from_value = rule.min_amount;
56
+ }
57
+ }
58
+ }
59
+ }
60
+
61
+ // params object follows calculate shipping request schema:
62
+ // https://apx-mods.e-com.plus/api/v1/calculate_shipping/schema.json?store_id=100
63
+ if (!params.to) {
64
+ // respond only with free shipping option
65
+ return response;
66
+ }
67
+
68
+ if (!sCepOrigem) {
69
+ // must have configured origin zip code to continue
70
+ return {
71
+ error: 'CALCULATE_ERR',
72
+ message: 'Zip code is unset on app hidden data (merchant must configure the app)',
73
+ };
74
+ }
75
+
76
+ // optinal predefined or configured service codes
77
+ if (params.service_code) {
78
+ nCdServico = params.service_code;
79
+ } else if (Array.isArray(config.services) && config.services[0]) {
80
+ const firstServiceCode = config.services[0].service_code;
81
+ if (firstServiceCode) {
82
+ nCdServico = firstServiceCode;
83
+ for (let i = 1; i < config.services.length; i++) {
84
+ nCdServico += `,${config.services[i].service_code}`;
85
+ }
86
+ }
87
+ }
88
+
89
+ // optional params to Correios services
90
+ if (params.subtotal && !config.no_declare_value) {
91
+ nVlValorDeclarado = params.subtotal;
92
+ }
93
+ if (params.own_hand) {
94
+ sCdMaoPropria = 's';
95
+ }
96
+ if (params.receipt) {
97
+ sCdAvisoRecebimento = 's';
98
+ }
99
+
100
+ // calculate weight and pkg value from items list
101
+ if (params.items) {
102
+ const pkg = {
103
+ dimensions: {
104
+ width: {
105
+ value: 0,
106
+ unit: 'cm',
107
+ },
108
+ height: {
109
+ value: 0,
110
+ unit: 'cm',
111
+ },
112
+ length: {
113
+ value: 0,
114
+ unit: 'cm',
115
+ },
116
+ },
117
+ weight: {
118
+ value: 0,
119
+ unit: 'kg',
120
+ },
121
+ };
122
+
123
+ params.items.forEach(({
124
+ price,
125
+ quantity,
126
+ dimensions,
127
+ weight,
128
+ }) => {
129
+ let physicalWeight = 0;
130
+ let cubicWeight = 0;
131
+ if (!params.subtotal && !config.no_declare_value) {
132
+ nVlValorDeclarado += price * quantity;
133
+ }
134
+
135
+ // sum physical weight
136
+ if (weight && weight.value) {
137
+ switch (weight.unit) {
138
+ case 'kg':
139
+ physicalWeight = weight.value;
140
+ break;
141
+ case 'g':
142
+ physicalWeight = weight.value / 1000;
143
+ break;
144
+ case 'mg':
145
+ physicalWeight = weight.value / 1000000;
146
+ break;
147
+ default:
148
+ }
149
+ pkg.weight.value += physicalWeight * quantity;
150
+ }
151
+
152
+ // sum total items dimensions to calculate cubic weight
153
+ if (dimensions) {
154
+ const sumDimensions = {};
155
+ Object.keys(dimensions).forEach((side) => {
156
+ const dimension = dimensions[side];
157
+ if (dimension && dimension.value) {
158
+ let dimensionValue;
159
+ switch (dimension.unit) {
160
+ case 'cm':
161
+ dimensionValue = dimension.value;
162
+ break;
163
+ case 'm':
164
+ dimensionValue = dimension.value * 100;
165
+ break;
166
+ case 'mm':
167
+ dimensionValue = dimension.value / 10;
168
+ break;
169
+ default:
170
+ }
171
+ // add/sum current side to final dimensions object
172
+ if (dimensionValue) {
173
+ sumDimensions[side] = sumDimensions[side]
174
+ ? sumDimensions[side] + dimensionValue
175
+ : dimensionValue;
176
+ }
177
+ }
178
+ });
179
+
180
+ // calculate cubic weight
181
+ // https://suporte.boxloja.pro/article/82-correios-calculo-frete
182
+ // (C x L x A) / 6.000
183
+ Object.keys(sumDimensions).forEach((side) => {
184
+ if (sumDimensions[side]) {
185
+ cubicWeight = cubicWeight > 0
186
+ ? cubicWeight * sumDimensions[side]
187
+ : sumDimensions[side];
188
+ pkg.dimensions[side].value += sumDimensions[side] * quantity;
189
+ }
190
+ });
191
+ if (cubicWeight > 0) {
192
+ cubicWeight /= 6000;
193
+ }
194
+ }
195
+ if (!config.free_no_weight_shipping || physicalWeight > 0) {
196
+ const unitWeight = cubicWeight < 5 || physicalWeight > cubicWeight
197
+ ? physicalWeight : cubicWeight;
198
+ nVlPeso += (quantity * unitWeight);
199
+ }
200
+ });
201
+
202
+ // pre check for maximum allowed declared value
203
+ if (nVlValorDeclarado > 10000) {
204
+ nVlValorDeclarado = 10000;
205
+ }
206
+
207
+ let result;
208
+ try {
209
+ result = await correiosCalculate({
210
+ sCepOrigem,
211
+ sCepDestino,
212
+ nCdEmpresa,
213
+ sDsSenha,
214
+ nCdServico,
215
+ sCdMaoPropria,
216
+ sCdAvisoRecebimento,
217
+ nVlPeso,
218
+ nVlValorDeclarado,
219
+ });
220
+ } catch (err) {
221
+ return {
222
+ error: 'CALCULATE_FAILED',
223
+ message: err.message,
224
+ };
225
+ }
226
+
227
+ const { Servicos, cServico } = result;
228
+ // set services array from `Servicos` or `cServico`
229
+ let services;
230
+ if (Servicos) {
231
+ if (Array.isArray(Servicos)) {
232
+ services = Servicos;
233
+ } else if (Servicos.cServico) {
234
+ services = Array.isArray(Servicos.cServico) ? Servicos.cServico : [Servicos.cServico];
235
+ }
236
+ }
237
+ if (!services) {
238
+ services = Array.isArray(cServico) ? cServico : [cServico];
239
+ }
240
+
241
+ if (services[0] && services[0].Codigo) {
242
+ let errorMsg;
243
+ services.forEach((service) => {
244
+ // check error first
245
+ let { Erro, PrazoEntrega } = service;
246
+ const { MsgErro, url } = service;
247
+ let notes;
248
+ PrazoEntrega = parseInt(PrazoEntrega, 10);
249
+ // known Correios errors
250
+ switch (Erro) {
251
+ case '010':
252
+ case 10:
253
+ Erro = false;
254
+ notes = MsgErro;
255
+ break;
256
+ case '011':
257
+ case 11:
258
+ Erro = false;
259
+ PrazoEntrega += 7;
260
+ break;
261
+ default:
262
+ }
263
+
264
+ if ((!Erro || Erro === '0') && PrazoEntrega >= 0) {
265
+ // fix price strings to number
266
+ [
267
+ 'Valor',
268
+ 'ValorSemAdicionais',
269
+ 'ValorMaoPropria',
270
+ 'ValorAvisoRecebimento',
271
+ 'ValorValorDeclarado',
272
+ ].forEach((field) => {
273
+ switch (typeof service[field]) {
274
+ case 'number':
275
+ break;
276
+ case 'string':
277
+ service[field] = parseFloat(service[field].replace('.', '').replace(',', '.'));
278
+ break;
279
+ default:
280
+ service[field] = 0;
281
+ }
282
+ });
283
+ const {
284
+ Codigo,
285
+ Valor,
286
+ ValorSemAdicionais,
287
+ ValorMaoPropria,
288
+ ValorAvisoRecebimento,
289
+ ValorValorDeclarado,
290
+ } = service;
291
+
292
+ // find respective configured service label
293
+ let serviceName;
294
+ switch (Codigo) {
295
+ case '04014':
296
+ serviceName = 'SEDEX';
297
+ break;
298
+ case '04510':
299
+ serviceName = 'PAC';
300
+ break;
301
+ default:
302
+ }
303
+ let label = serviceName || `Correios ${Codigo}`;
304
+ if (Array.isArray(config.services)) {
305
+ for (let i = 0; i < config.services.length; i++) {
306
+ const service = config.services[i];
307
+ if (service && service.service_code === Codigo && service.label) {
308
+ label = service.label;
309
+ }
310
+ }
311
+ }
312
+
313
+ // parse to E-Com Plus shipping line object
314
+ const shippingLine = {
315
+ from: {
316
+ ...params.from,
317
+ zip: sCepOrigem,
318
+ },
319
+ to: params.to,
320
+ package: pkg,
321
+ price: ValorSemAdicionais || Valor,
322
+ declared_value: nVlValorDeclarado,
323
+ declared_value_price: ValorValorDeclarado > 0 ? ValorValorDeclarado : 0,
324
+ own_hand: Boolean(sCdMaoPropria),
325
+ own_hand_price: ValorMaoPropria,
326
+ receipt: Boolean(sCdAvisoRecebimento),
327
+ receipt_price: ValorAvisoRecebimento,
328
+ discount: 0,
329
+ total_price: Valor,
330
+ delivery_time: {
331
+ days: PrazoEntrega,
332
+ working_days: true,
333
+ },
334
+ posting_deadline: {
335
+ days: 3,
336
+ ...config.posting_deadline,
337
+ },
338
+ flags: ['correios-ws'],
339
+ notes,
340
+ };
341
+
342
+ // check for default configured additional/discount price
343
+ if (typeof config.additional_price === 'number' && config.additional_price) {
344
+ if (config.additional_price > 0) {
345
+ shippingLine.other_additionals = [{
346
+ tag: 'additional_price',
347
+ label: 'Adicional padrão',
348
+ price: config.additional_price,
349
+ }];
350
+ } else {
351
+ // negative additional price to apply discount
352
+ shippingLine.discount -= config.additional_price;
353
+ }
354
+ // update total price
355
+ shippingLine.total_price += config.additional_price;
356
+ }
357
+
358
+ // search for discount by shipping rule
359
+ if (Array.isArray(config.shipping_rules)) {
360
+ for (let i = 0; i < config.shipping_rules.length; i++) {
361
+ const rule = config.shipping_rules[i];
362
+ if (
363
+ rule
364
+ && (!rule.service_code || rule.service_code === Codigo)
365
+ && checkZipCode(rule)
366
+ && !(rule.min_amount > params.subtotal)
367
+ ) {
368
+ // valid shipping rule
369
+ if (rule.free_shipping) {
370
+ shippingLine.discount += shippingLine.total_price;
371
+ shippingLine.total_price = 0;
372
+ break;
373
+ } else if (rule.discount) {
374
+ let discountValue = rule.discount.value;
375
+ if (rule.discount.percentage) {
376
+ discountValue *= (shippingLine.total_price / 100);
377
+ }
378
+ if (discountValue) {
379
+ shippingLine.discount += discountValue;
380
+ shippingLine.total_price -= discountValue;
381
+ if (shippingLine.total_price < 0) {
382
+ shippingLine.total_price = 0;
383
+ }
384
+ }
385
+ break;
386
+ }
387
+ }
388
+ }
389
+ }
390
+
391
+ if (typeof url === 'string') {
392
+ // add WS URL to custom fields to facilitate debugging
393
+ shippingLine.custom_fields = [{
394
+ field: 'correios_ws_params',
395
+ value: (nCdEmpresa ? url.replace(nCdEmpresa, 'c').replace(sDsSenha, 's') : url)
396
+ .replace(/[^?]+\?(.*)/, '$1')
397
+ .replace(/(StrRetorno|nIndicaCalculo|nCdFormato|nVlDiametro)=[^&]+&?/g, '')
398
+ .slice(0, 255),
399
+ }];
400
+ }
401
+
402
+ // push shipping service object to response
403
+ response.shipping_services.push({
404
+ label,
405
+ carrier: 'Correios',
406
+ // https://informederendimentos.com/consulta/cnpj-correios/
407
+ carrier_doc_number: '34028316000103',
408
+ service_code: Codigo,
409
+ service_name: serviceName || label,
410
+ shipping_line: shippingLine,
411
+ });
412
+ } else {
413
+ errorMsg = `Correios erro ${Erro}`;
414
+ if (typeof MsgErro === 'string') {
415
+ errorMsg += `: ${MsgErro}`;
416
+ }
417
+ if (typeof url === 'string') {
418
+ errorMsg += `\n${url}`;
419
+ }
420
+ }
421
+ });
422
+
423
+ if (response.shipping_services.length) {
424
+ // free shipping if all items has no weigth
425
+ const freeNoWeightShipping = nVlPeso <= 0 && config.free_no_weight_shipping;
426
+ if (freeNoWeightShipping) {
427
+ let cheapestShippingLine;
428
+ for (let i = 0; i < response.shipping_services.length; i++) {
429
+ const shippingLine = response.shipping_services[i].shipping_line;
430
+ if (!shippingLine.total_price) {
431
+ // already free
432
+ break;
433
+ }
434
+ if (
435
+ !cheapestShippingLine
436
+ || cheapestShippingLine.total_price > shippingLine.total_price
437
+ ) {
438
+ cheapestShippingLine = shippingLine;
439
+ }
440
+ }
441
+ if (cheapestShippingLine) {
442
+ // set the cheapest shipping line free
443
+ cheapestShippingLine.discount = cheapestShippingLine.total_price;
444
+ cheapestShippingLine.total_price = 0;
445
+ cheapestShippingLine.flags.push('free_no_weight');
446
+ }
447
+ }
448
+ } else if (errorMsg) {
449
+ // pass Correios error message
450
+ return {
451
+ error: 'CALCULATE_ERR_MSG',
452
+ message: errorMsg,
453
+ };
454
+ }
455
+
456
+ // success response with available shipping services
457
+ return response;
458
+ }
459
+
460
+ // unexpected result object
461
+ return {
462
+ error: 'CALCULATE_UNEXPECTED_RSP',
463
+ message: 'Unexpected object from Correios response, please try again later',
464
+ };
465
+ }
466
+ return {
467
+ error: 'CALCULATE_EMPTY_CART',
468
+ message: 'Cannot calculate shipping without cart items',
469
+ };
470
+ };