cloudcommerce 0.0.97 → 0.0.98

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 (114) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/package.json +1 -1
  3. package/packages/api/package.json +1 -1
  4. package/packages/apps/correios/package.json +1 -1
  5. package/packages/apps/custom-shipping/package.json +1 -1
  6. package/packages/apps/discounts/package.json +1 -1
  7. package/packages/apps/frenet/package.json +1 -1
  8. package/packages/apps/tiny-erp/lib/event-to-tiny.js +94 -94
  9. package/packages/apps/tiny-erp/lib/index.js +1 -1
  10. package/packages/apps/tiny-erp/lib/integration/after-tiny-queue.js +74 -71
  11. package/packages/apps/tiny-erp/lib/integration/export-order-to-tiny.js +73 -70
  12. package/packages/apps/tiny-erp/lib/integration/export-product-to-tiny.js +53 -49
  13. package/packages/apps/tiny-erp/lib/integration/helpers/format-tiny-date.js +3 -3
  14. package/packages/apps/tiny-erp/lib/integration/import-order-from-tiny.js +75 -76
  15. package/packages/apps/tiny-erp/lib/integration/import-product-from-tiny.js +140 -137
  16. package/packages/apps/tiny-erp/lib/integration/parsers/order-from-tiny.js +39 -40
  17. package/packages/apps/tiny-erp/lib/integration/parsers/order-to-tiny.js +178 -173
  18. package/packages/apps/tiny-erp/lib/integration/parsers/product-from-tiny.js +171 -173
  19. package/packages/apps/tiny-erp/lib/integration/parsers/product-to-tiny.js +127 -123
  20. package/packages/apps/tiny-erp/lib/integration/parsers/status-from-tiny.js +32 -32
  21. package/packages/apps/tiny-erp/lib/integration/parsers/status-to-tiny.js +37 -37
  22. package/packages/apps/tiny-erp/lib/integration/post-tiny-erp.js +43 -42
  23. package/packages/apps/tiny-erp/lib/tiny-erp.js +6 -8
  24. package/packages/apps/tiny-erp/lib/tiny-webhook.js +73 -76
  25. package/packages/apps/tiny-erp/package.json +1 -1
  26. package/packages/cli/package.json +1 -1
  27. package/packages/config/package.json +1 -1
  28. package/packages/events/package.json +1 -1
  29. package/packages/firebase/lib/config.js +27 -25
  30. package/packages/firebase/lib/const.js +3 -2
  31. package/packages/firebase/lib/env.js +2 -1
  32. package/packages/firebase/lib/handlers/check-store-events.js +146 -145
  33. package/packages/firebase/lib/helpers/pubsub.js +20 -18
  34. package/packages/firebase/lib/helpers/update-app-data.js +38 -38
  35. package/packages/firebase/lib/index.js +9 -7
  36. package/packages/firebase/lib/init.js +2 -1
  37. package/packages/firebase/package.json +1 -1
  38. package/packages/modules/lib/firebase/ajv.js +19 -24
  39. package/packages/modules/lib/firebase/call-app-module.js +116 -110
  40. package/packages/modules/lib/firebase/checkout.js +151 -152
  41. package/packages/modules/lib/firebase/functions-checkout/fix-items.js +194 -187
  42. package/packages/modules/lib/firebase/functions-checkout/get-custumerId.js +25 -26
  43. package/packages/modules/lib/firebase/functions-checkout/handle-order-transaction.js +110 -109
  44. package/packages/modules/lib/firebase/functions-checkout/new-order.js +177 -177
  45. package/packages/modules/lib/firebase/functions-checkout/request-to-module.js +59 -59
  46. package/packages/modules/lib/firebase/functions-checkout/utils.js +195 -197
  47. package/packages/modules/lib/firebase/handle-module.js +144 -146
  48. package/packages/modules/lib/firebase/proxy-apps.js +2 -1
  49. package/packages/modules/lib/firebase/serve-modules-api.js +52 -53
  50. package/packages/modules/lib/firebase.js +4 -6
  51. package/packages/modules/lib/index.js +12 -15
  52. package/packages/modules/package.json +1 -1
  53. package/packages/passport/package.json +1 -1
  54. package/packages/ssr/package.json +1 -1
  55. package/packages/storefront/dist/client/LoginOffcanvas.daf3f717.js +1 -0
  56. package/packages/storefront/dist/client/admin/config.json +1 -0
  57. package/packages/storefront/dist/client/assets/_...522e6bf2.css +4 -0
  58. package/packages/storefront/dist/client/assets/_...a48b75c7.css +1 -0
  59. package/packages/storefront/dist/client/assets/cms-preview.css +274 -0
  60. package/packages/storefront/dist/client/assets/cms.css +114 -0
  61. package/packages/storefront/dist/client/assets/cvv.png +0 -0
  62. package/packages/storefront/dist/client/assets/icons/bootstrap-icons/font/storefront-icons.woff2 +0 -0
  63. package/packages/storefront/dist/client/assets/icons/feather-icons/font/storefront-icons.woff2 +0 -0
  64. package/packages/storefront/dist/client/assets/icons/font-awesome/font/storefront-icons.woff2 +0 -0
  65. package/packages/storefront/dist/client/assets/icons/line-awesome/font/storefront-icons.woff2 +0 -0
  66. package/packages/storefront/dist/client/assets/icons/tabler-icons/font/storefront-icons.woff2 +0 -0
  67. package/packages/storefront/dist/client/assets/img-placeholder.png +0 -0
  68. package/packages/storefront/dist/client/assets/payments.png +0 -0
  69. package/packages/storefront/dist/client/assets/ssl-safe.png +0 -0
  70. package/packages/storefront/dist/client/chunks/LoginForm.d9251274.js +1066 -0
  71. package/packages/storefront/dist/client/chunks/LoginOffcanvas.07fe6492.js +1 -0
  72. package/packages/storefront/dist/client/chunks/index.esm.84a649c7.js +331 -0
  73. package/packages/storefront/dist/client/chunks/preload-helper.f15ab524.js +1 -0
  74. package/packages/storefront/dist/client/chunks/runtime-dom.esm-bundler.738639ee.js +1 -0
  75. package/packages/storefront/dist/client/chunks/workbox-window.prod.es5.4b654ae6.js +2 -0
  76. package/packages/storefront/dist/client/client.b552d86a.js +1 -0
  77. package/packages/storefront/dist/client/hoisted.054c36ac.js +1 -0
  78. package/packages/storefront/dist/client/img/icon.png +0 -0
  79. package/packages/storefront/dist/client/img/large-icon.png +0 -0
  80. package/packages/storefront/dist/client/img/uploads/banner1.png +0 -0
  81. package/packages/storefront/dist/client/img/uploads/banner2.png +0 -0
  82. package/packages/storefront/dist/client/img/uploads/banner2.webp +0 -0
  83. package/packages/storefront/dist/client/img/uploads/favicon.png +0 -0
  84. package/packages/storefront/dist/client/img/uploads/headless.png +0 -0
  85. package/packages/storefront/dist/client/img/uploads/headphone.png +0 -0
  86. package/packages/storefront/dist/client/img/uploads/headphone.webp +0 -0
  87. package/packages/storefront/dist/client/img/uploads/icon.png +0 -0
  88. package/packages/storefront/dist/client/img/uploads/large-icon.png +0 -0
  89. package/packages/storefront/dist/client/img/uploads/logo.png +0 -0
  90. package/packages/storefront/dist/client/img/uploads/logo.webp +0 -0
  91. package/packages/storefront/dist/client/img/uploads/og-image.png +0 -0
  92. package/packages/storefront/dist/client/img/uploads/passion.png +0 -0
  93. package/packages/storefront/dist/client/img/uploads/passion.webp +0 -0
  94. package/packages/storefront/dist/client/img/uploads/pwa-reliable.png +0 -0
  95. package/packages/storefront/dist/client/img/uploads/rect8589.png +0 -0
  96. package/packages/storefront/dist/client/img/uploads/rect859.png +0 -0
  97. package/packages/storefront/dist/client/img/uploads/rect89.png +0 -0
  98. package/packages/storefront/dist/client/img/uploads/rect89.webp +0 -0
  99. package/packages/storefront/dist/client/img/uploads/ssl-safe.png +0 -0
  100. package/packages/storefront/dist/client/manifest.webmanifest +1 -0
  101. package/packages/storefront/dist/client/page.3aa82516.js +1 -0
  102. package/packages/storefront/dist/client/robots.txt +8 -0
  103. package/packages/storefront/dist/client/sw.js +1 -0
  104. package/packages/storefront/dist/client/workbox-6f0d1f78.js +1 -0
  105. package/packages/storefront/dist/client/~partytown/partytown-atomics.js +2 -0
  106. package/packages/storefront/dist/client/~partytown/partytown-media.js +2 -0
  107. package/packages/storefront/dist/client/~partytown/partytown-sw.js +2 -0
  108. package/packages/storefront/dist/client/~partytown/partytown.js +2 -0
  109. package/packages/storefront/dist/server/entry.mjs +2852 -0
  110. package/packages/storefront/dist/server/manifest.webmanifest +1 -0
  111. package/packages/storefront/dist/server/registerSW.js +1 -0
  112. package/packages/storefront/package.json +1 -1
  113. package/packages/storefront/src/lib/layouts/PagesHeader.astro +2 -1
  114. package/packages/types/package.json +1 -1
@@ -1,75 +1,79 @@
1
1
  import { logger } from 'firebase-functions';
2
2
  import axios from 'axios';
3
3
  import config from '@cloudcommerce/firebase/lib/config';
4
-
5
4
  // Blacklist urls to prevent consecultive errors
6
5
  const blacklist = {};
7
-
8
6
  export default async (appId, modName, url, data, isBigTimeout) => {
9
- if (blacklist[url] > 2) {
10
- logger.log(`> Skipping blacklisted ${url}`);
11
- const err = new Error('Blacklited endpoint URL');
12
- return Promise.reject(err);
13
- }
14
- const { storeId, apps } = config.get();
15
- const checkErrorResponse = (logHead, resData) => {
16
- if (typeof resData === 'object' && resData !== null) {
17
- const { error, message } = resData;
18
- if (typeof error === 'string' && error.length && typeof message === 'string') {
19
- logger.warn(logHead, JSON.stringify({ error, message }));
20
- }
7
+ if (blacklist[url] > 2) {
8
+ logger.log(`> Skipping blacklisted ${url}`);
9
+ const err = new Error('Blacklited endpoint URL');
10
+ return Promise.reject(err);
21
11
  }
22
- };
23
- const debugAndBlacklist = (response) => {
24
- const status = response ? response.status : 0;
25
- if (!blacklist[url]) {
26
- blacklist[url] = 1;
27
- } else {
28
- blacklist[url] += 1;
29
- }
30
- setTimeout(() => {
31
- if (blacklist[url] > 1) {
32
- blacklist[url] -= 1;
33
- } else {
34
- delete blacklist[url];
35
- }
36
- }, !status ? 180000 : 6000);
37
- const logHead = `${url} : ${status}`;
38
- if (status >= 400 && status < 500) {
39
- checkErrorResponse(logHead, response.data);
40
- } else {
41
- logger.info(logHead);
42
- }
43
- };
12
+ const { storeId, apps } = config.get();
13
+ const checkErrorResponse = (logHead, resData) => {
14
+ if (typeof resData === 'object' && resData !== null) {
15
+ const { error, message } = resData;
16
+ if (typeof error === 'string' && error.length && typeof message === 'string') {
17
+ logger.warn(logHead, JSON.stringify({ error, message }));
18
+ }
19
+ }
20
+ };
21
+ const debugAndBlacklist = (response) => {
22
+ const status = response ? response.status : 0;
23
+ if (!blacklist[url]) {
24
+ blacklist[url] = 1;
25
+ }
26
+ else {
27
+ blacklist[url] += 1;
28
+ }
29
+ setTimeout(() => {
30
+ if (blacklist[url] > 1) {
31
+ blacklist[url] -= 1;
32
+ }
33
+ else {
34
+ delete blacklist[url];
35
+ }
36
+ }, !status ? 180000 : 6000);
37
+ const logHead = `${url} : ${status}`;
38
+ if (status >= 400 && status < 500) {
39
+ checkErrorResponse(logHead, response.data);
40
+ }
41
+ else {
42
+ logger.info(logHead);
43
+ }
44
+ };
44
45
  // eslint-disable-next-line no-unused-vars
45
- let internalModuleFn;
46
- if (modName === 'apply_discount') {
47
- if (appId === apps.discounts.appId) {
48
- internalModuleFn = async (_data = data) => {
49
- return import('@cloudcommerce/app-discounts')
50
- .then(({ applyDiscount }) => applyDiscount(_data));
51
- };
46
+ let internalModuleFn;
47
+ if (modName === 'apply_discount') {
48
+ if (appId === apps.discounts.appId) {
49
+ internalModuleFn = async (_data = data) => {
50
+ return import('@cloudcommerce/app-discounts')
51
+ .then(({ applyDiscount }) => applyDiscount(_data));
52
+ };
53
+ }
52
54
  }
53
- } else if (modName === 'calculate_shipping') {
54
- if (appId === apps.correios.appId) {
55
- internalModuleFn = async (_data = data) => {
56
- return import('@cloudcommerce/app-correios')
57
- .then(({ calculateShipping }) => calculateShipping(_data));
58
- };
59
- } else if (appId === apps.customShipping.appId) {
60
- internalModuleFn = async (_data = data) => {
61
- return import('@cloudcommerce/app-custom-shipping')
62
- .then(({ calculateShipping }) => calculateShipping(_data));
63
- };
64
- } else if (appId === apps.frenet.appId) {
65
- internalModuleFn = async (_data = data) => {
66
- return import('@cloudcommerce/app-frenet')
67
- .then(({ calculateShipping }) => calculateShipping(_data));
68
- };
55
+ else if (modName === 'calculate_shipping') {
56
+ if (appId === apps.correios.appId) {
57
+ internalModuleFn = async (_data = data) => {
58
+ return import('@cloudcommerce/app-correios')
59
+ .then(({ calculateShipping }) => calculateShipping(_data));
60
+ };
61
+ }
62
+ else if (appId === apps.customShipping.appId) {
63
+ internalModuleFn = async (_data = data) => {
64
+ return import('@cloudcommerce/app-custom-shipping')
65
+ .then(({ calculateShipping }) => calculateShipping(_data));
66
+ };
67
+ }
68
+ else if (appId === apps.frenet.appId) {
69
+ internalModuleFn = async (_data = data) => {
70
+ return import('@cloudcommerce/app-frenet')
71
+ .then(({ calculateShipping }) => calculateShipping(_data));
72
+ };
73
+ }
69
74
  }
70
- }
71
- if (internalModuleFn) {
72
- /*
75
+ if (internalModuleFn) {
76
+ /*
73
77
  global.app1_apply_discount_middleware = async (
74
78
  data: any,
75
79
  next: () => Promise<any>,
@@ -80,56 +84,58 @@ export default async (appId, modName, url, data, isBigTimeout) => {
80
84
  return next(data);
81
85
  };
82
86
  */
83
- const middleware = global[`app${appId}_${modName}_middleware`];
84
- try {
85
- let appResponse;
86
- if (typeof middleware === 'function') {
87
- appResponse = await middleware(data, internalModuleFn);
88
- } else {
89
- appResponse = await internalModuleFn(data);
90
- }
91
- checkErrorResponse(`${appId}_${modName}`, appResponse);
92
- return appResponse;
93
- } catch (err) {
94
- logger.error(err);
95
- let message = 'Failed to execute module function';
96
- if (typeof middleware === 'function') {
97
- message += ' (has middleware)';
98
- }
99
- return {
100
- error: 'INTERNAL_MODULE_ERROR',
101
- message,
102
- };
87
+ const middleware = global[`app${appId}_${modName}_middleware`];
88
+ try {
89
+ let appResponse;
90
+ if (typeof middleware === 'function') {
91
+ appResponse = await middleware(data, internalModuleFn);
92
+ }
93
+ else {
94
+ appResponse = await internalModuleFn(data);
95
+ }
96
+ checkErrorResponse(`${appId}_${modName}`, appResponse);
97
+ return appResponse;
98
+ }
99
+ catch (err) {
100
+ logger.error(err);
101
+ let message = 'Failed to execute module function';
102
+ if (typeof middleware === 'function') {
103
+ message += ' (has middleware)';
104
+ }
105
+ return {
106
+ error: 'INTERNAL_MODULE_ERROR',
107
+ message,
108
+ };
109
+ }
103
110
  }
104
- }
105
- return axios({
106
- method: 'POST',
107
- maxRedirects: 2,
108
- responseType: 'json',
109
- maxContentLength: 1000000,
110
- url,
111
- data,
112
- headers: {
113
- 'X-Store-ID': storeId.toString(),
114
- },
115
- // Wait 10s by default and 30s in specific cases
116
- timeout: isBigTimeout ? 30000 : 10000,
117
- })
118
- .then((response) => {
119
- debugAndBlacklist(response);
120
- return response.data;
111
+ return axios({
112
+ method: 'POST',
113
+ maxRedirects: 2,
114
+ responseType: 'json',
115
+ maxContentLength: 1000000,
116
+ url,
117
+ data,
118
+ headers: {
119
+ 'X-Store-ID': storeId.toString(),
120
+ },
121
+ // Wait 10s by default and 30s in specific cases
122
+ timeout: isBigTimeout ? 30000 : 10000,
123
+ })
124
+ .then((response) => {
125
+ debugAndBlacklist(response);
126
+ return response.data;
121
127
  })
122
- .catch((err) => {
123
- const { response } = err;
124
- debugAndBlacklist(response);
125
- if (err.message || err.code) {
126
- let msg = `Axios error ${err.code}: ${err.message}`;
127
- if (data) {
128
- msg += `\n\n${JSON.stringify(data)}`;
128
+ .catch((err) => {
129
+ const { response } = err;
130
+ debugAndBlacklist(response);
131
+ if (err.message || err.code) {
132
+ let msg = `Axios error ${err.code}: ${err.message}`;
133
+ if (data) {
134
+ msg += `\n\n${JSON.stringify(data)}`;
135
+ }
136
+ logger.warn(msg);
129
137
  }
130
- logger.warn(msg);
131
- }
132
- throw err;
138
+ throw err;
133
139
  });
134
140
  };
135
- // # sourceMappingURL=call-app-module.js.map
141
+ //# sourceMappingURL=call-app-module.js.map
@@ -1,163 +1,162 @@
1
- import { ajv, sendRequestError } from './ajv.js';
1
+ import { ajv, sendRequestError, } from './ajv.js';
2
2
  import fixItems from './functions-checkout/fix-items.js';
3
3
  import getCustomerId from './functions-checkout/get-custumerId.js';
4
4
  import requestModule from './functions-checkout/request-to-module.js';
5
- import {
6
- sendError, fixAmount, getValidResults, handleShippingServices, handleApplyDiscount, handleListPayments,
7
- } from './functions-checkout/utils.js';
5
+ import { sendError, fixAmount, getValidResults, handleShippingServices, handleApplyDiscount, handleListPayments, } from './functions-checkout/utils.js';
8
6
  import createOrder from './functions-checkout/new-order.js';
9
-
10
7
  const runCheckout = async (checkoutBody, accessToken, res, validate, hostname) => {
11
- if (!validate(checkoutBody)) {
12
- return sendRequestError(res, '@checkout', validate.errors);
13
- }
14
- const { items, ...newBody } = checkoutBody;
15
- const newItems = await fixItems(items);
16
- const amount = {
17
- subtotal: 0,
18
- discount: 0,
19
- freight: 0,
20
- total: 0,
21
- };
22
- const body = {
23
- ...newBody,
24
- items: [...newItems],
25
- subtotal: 0,
26
- amount,
27
- };
28
- const countCheckoutItems = body.items.length;
29
- const { customer } = body;
30
- const customerId = await getCustomerId(accessToken, customer);
31
- if (customerId && customer) {
32
- if (newItems.length) {
33
- const { _id, ...newCustomer } = customer;
34
- // start mounting order body
35
- // https://developers.e-com.plus/docs/api/#/store/orders/orders
36
- const dateTime = new Date().toISOString();
37
- const orderBody = {
38
- opened_at: dateTime,
39
- buyers: [
40
- // received customer info
41
- {
42
- _id: customerId,
43
- ...newCustomer,
44
- },
45
- ],
46
- items: [],
47
- amount: {
48
- total: 0,
49
- },
50
- };
51
- // bypass some order fields
52
- const fields = [
53
- 'utm',
54
- 'affiliate_code',
55
- 'browser_ip',
56
- 'channel_id',
57
- 'channel_type',
58
- 'domain',
59
- 'notes',
60
- ];
61
- fields.forEach((field) => {
62
- if (body[field]) {
63
- orderBody[field] = body[field];
64
- }
65
- });
66
- if (orderBody.domain) {
67
- // consider default Storefront app routes
68
- if (!orderBody.checkout_link) {
69
- orderBody.checkout_link = `https://${orderBody.domain}/app/#/checkout/(_id)`;
70
- }
71
- if (!orderBody.status_link) {
72
- orderBody.status_link = `https://${orderBody.domain}/app/#/order/(_id)`;
73
- }
74
- }
75
- // count subtotal value
76
- let subtotal = 0;
77
- newItems.forEach((item) => {
78
- subtotal += (item.final_price || item.price * item.quantity);
79
- // pass each item to prevent object overwrite
80
- if (orderBody.items) {
81
- orderBody.items.push({ ...item });
8
+ if (!validate(checkoutBody)) {
9
+ return sendRequestError(res, '@checkout', validate.errors);
10
+ }
11
+ const { items, ...newBody } = checkoutBody;
12
+ const newItems = await fixItems(items);
13
+ const amount = {
14
+ subtotal: 0,
15
+ discount: 0,
16
+ freight: 0,
17
+ total: 0,
18
+ };
19
+ const body = {
20
+ ...newBody,
21
+ items: [...newItems],
22
+ subtotal: 0,
23
+ amount,
24
+ };
25
+ const countCheckoutItems = body.items.length;
26
+ const { customer } = body;
27
+ const customerId = await getCustomerId(accessToken, customer);
28
+ if (customerId && customer) {
29
+ if (newItems.length) {
30
+ const { _id, ...newCustomer } = customer;
31
+ // start mounting order body
32
+ // https://developers.e-com.plus/docs/api/#/store/orders/orders
33
+ const dateTime = new Date().toISOString();
34
+ const orderBody = {
35
+ opened_at: dateTime,
36
+ buyers: [
37
+ // received customer info
38
+ {
39
+ _id: customerId,
40
+ ...newCustomer,
41
+ },
42
+ ],
43
+ items: [],
44
+ amount: {
45
+ total: 0,
46
+ },
47
+ };
48
+ // bypass some order fields
49
+ const fields = [
50
+ 'utm',
51
+ 'affiliate_code',
52
+ 'browser_ip',
53
+ 'channel_id',
54
+ 'channel_type',
55
+ 'domain',
56
+ 'notes',
57
+ ];
58
+ fields.forEach((field) => {
59
+ if (body[field]) {
60
+ orderBody[field] = body[field];
61
+ }
62
+ });
63
+ if (orderBody.domain) {
64
+ // consider default Storefront app routes
65
+ if (!orderBody.checkout_link) {
66
+ orderBody.checkout_link = `https://${orderBody.domain}/app/#/checkout/(_id)`;
67
+ }
68
+ if (!orderBody.status_link) {
69
+ orderBody.status_link = `https://${orderBody.domain}/app/#/order/(_id)`;
70
+ }
71
+ }
72
+ // count subtotal value
73
+ let subtotal = 0;
74
+ newItems.forEach((item) => {
75
+ subtotal += (item.final_price || item.price * item.quantity);
76
+ // pass each item to prevent object overwrite
77
+ if (orderBody.items) {
78
+ orderBody.items.push({ ...item });
79
+ }
80
+ });
81
+ if (subtotal <= 0 && items.length < countCheckoutItems) {
82
+ return sendError(res, 400, 'CKT801', 'Cannot handle checkout, any valid cart item');
83
+ }
84
+ amount.subtotal = subtotal;
85
+ body.subtotal = subtotal;
86
+ fixAmount(amount, body, orderBody);
87
+ const transactions = Array.isArray(body.transaction) ? body.transaction : [body.transaction];
88
+ // add customer ID to order and transaction
89
+ customer._id = customerId;
90
+ transactions.forEach(({ buyer }) => {
91
+ if (buyer) {
92
+ buyer.customer_id = customerId;
93
+ }
94
+ });
95
+ let listShipping = await requestModule(body, hostname, 'shipping');
96
+ if (listShipping) {
97
+ listShipping = getValidResults(listShipping, 'shipping_services');
98
+ handleShippingServices(body, listShipping, amount, orderBody);
99
+ }
100
+ else {
101
+ // problem with shipping response object
102
+ return sendError(res, 400, 'CKT901', 'Any valid shipping service from /calculate_shipping module', {
103
+ en_us: 'Shipping method not available, please choose another',
104
+ pt_br: 'Forma de envio indisponível, por favor escolha outra',
105
+ });
106
+ }
107
+ let discounts = await requestModule(body, hostname, 'discount');
108
+ if (discounts) {
109
+ discounts = getValidResults(discounts);
110
+ handleApplyDiscount(body, discounts, amount, orderBody);
111
+ }
112
+ const { transaction, ...bodyPayment } = body;
113
+ let paymentsBody;
114
+ if (Array.isArray(transaction)) {
115
+ paymentsBody = {
116
+ ...bodyPayment,
117
+ transaction: transaction[0],
118
+ };
119
+ }
120
+ else {
121
+ paymentsBody = {
122
+ ...bodyPayment,
123
+ transaction,
124
+ };
125
+ }
126
+ let listPaymentGateways = await requestModule(paymentsBody, hostname, 'payment');
127
+ if (listPaymentGateways) {
128
+ listPaymentGateways = getValidResults(listPaymentGateways, 'payment_gateways');
129
+ handleListPayments(body, listPaymentGateways, paymentsBody, amount, orderBody);
130
+ }
131
+ else {
132
+ return sendError(res, 409, 'CKT902', 'Any valid payment gateway from /list_payments module', {
133
+ en_us: 'Payment method not available, please choose another',
134
+ pt_br: 'Forma de pagamento indisponível, por favor escolha outra',
135
+ });
136
+ }
137
+ return createOrder(res, accessToken, hostname, amount, checkoutBody, orderBody, transactions, dateTime);
82
138
  }
83
- });
84
- if (subtotal <= 0 && items.length < countCheckoutItems) {
85
139
  return sendError(res, 400, 'CKT801', 'Cannot handle checkout, any valid cart item');
86
- }
87
- amount.subtotal = subtotal;
88
- body.subtotal = subtotal;
89
- fixAmount(amount, body, orderBody);
90
- const transactions = Array.isArray(body.transaction) ? body.transaction : [body.transaction];
91
- // add customer ID to order and transaction
92
- customer._id = customerId;
93
- transactions.forEach(({ buyer }) => {
94
- if (buyer) {
95
- buyer.customer_id = customerId;
96
- }
97
- });
98
- let listShipping = await requestModule(body, hostname, 'shipping');
99
- if (listShipping) {
100
- listShipping = getValidResults(listShipping, 'shipping_services');
101
- handleShippingServices(body, listShipping, amount, orderBody);
102
- } else {
103
- // problem with shipping response object
104
- return sendError(res, 400, 'CKT901', 'Any valid shipping service from /calculate_shipping module', {
105
- en_us: 'Shipping method not available, please choose another',
106
- pt_br: 'Forma de envio indisponível, por favor escolha outra',
107
- });
108
- }
109
- let discounts = await requestModule(body, hostname, 'discount');
110
- if (discounts) {
111
- discounts = getValidResults(discounts);
112
- handleApplyDiscount(body, discounts, amount, orderBody);
113
- }
114
- const { transaction, ...bodyPayment } = body;
115
- let paymentsBody;
116
- if (Array.isArray(transaction)) {
117
- paymentsBody = {
118
- ...bodyPayment,
119
- transaction: transaction[0],
120
- };
121
- } else {
122
- paymentsBody = {
123
- ...bodyPayment,
124
- transaction,
125
- };
126
- }
127
- let listPaymentGateways = await requestModule(paymentsBody, hostname, 'payment');
128
- if (listPaymentGateways) {
129
- listPaymentGateways = getValidResults(listPaymentGateways, 'payment_gateways');
130
- handleListPayments(body, listPaymentGateways, paymentsBody, amount, orderBody);
131
- } else {
132
- return sendError(res, 409, 'CKT902', 'Any valid payment gateway from /list_payments module', {
133
- en_us: 'Payment method not available, please choose another',
134
- pt_br: 'Forma de pagamento indisponível, por favor escolha outra',
135
- });
136
- }
137
- return createOrder(res, accessToken, hostname, amount, checkoutBody, orderBody, transactions, dateTime);
138
140
  }
139
- return sendError(res, 400, 'CKT801', 'Cannot handle checkout, any valid cart item');
140
- }
141
- return sendError(res, 404, -404, 'Not found', {
142
- en_us: 'No customers found with ID or email provided',
143
- pt_br: 'Nenhum cliente encontrado com ID ou e-mail fornecido',
144
- });
141
+ return sendError(res, 404, -404, 'Not found', {
142
+ en_us: 'No customers found with ID or email provided',
143
+ pt_br: 'Nenhum cliente encontrado com ID ou e-mail fornecido',
144
+ });
145
145
  };
146
-
147
146
  export default (schema, req, res, hostname) => {
148
- const validate = ajv.compile(schema);
149
- const ip = req.headers['x-real-ip'];
150
- if (!req.body.browser_ip && ip) {
151
- req.body.browser_ip = ip;
152
- }
153
- let acessToken = req.headers.authorization;
154
- if (acessToken) {
155
- acessToken = acessToken.replace(/Bearer /i, '');
156
- return runCheckout(req.body, acessToken, res, validate, hostname);
157
- }
158
- return sendError(res, 401, 109, "Token is required on 'Authorization'", {
159
- en_us: 'No authorization for the requested method and resource',
160
- pt_br: 'Sem autorização para o método e recurso solicitado',
161
- });
147
+ const validate = ajv.compile(schema);
148
+ const ip = req.headers['x-real-ip'];
149
+ if (!req.body.browser_ip && ip) {
150
+ req.body.browser_ip = ip;
151
+ }
152
+ let acessToken = req.headers.authorization;
153
+ if (acessToken) {
154
+ acessToken = acessToken.replace(/Bearer /i, '');
155
+ return runCheckout(req.body, acessToken, res, validate, hostname);
156
+ }
157
+ return sendError(res, 401, 109, "Token is required on 'Authorization'", {
158
+ en_us: 'No authorization for the requested method and resource',
159
+ pt_br: 'Sem autorização para o método e recurso solicitado',
160
+ });
162
161
  };
163
- // # sourceMappingURL=checkout.js.map
162
+ //# sourceMappingURL=checkout.js.map