-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathcheckout.ts
More file actions
240 lines (228 loc) · 7.32 KB
/
checkout.ts
File metadata and controls
240 lines (228 loc) · 7.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
import type { Request, Response } from 'firebase-functions';
import type { OrderSet, CheckoutBody } from '@cloudcommerce/types';
import type {
CheckoutBodyWithItems,
Amount,
Payment,
} from '../types/index';
import { info } from 'firebase-functions/logger';
import { fullName as getFullname } from '@ecomplus/utils';
import { checkoutSchema } from '../index';
import { ajv, sendRequestError } from './ajv';
import fixItems from './functions-checkout/fix-items';
import readOrSaveCustomer from './functions-checkout/read-or-save-customer';
import requestModule from './functions-checkout/request-to-module';
import {
sendError,
fixAmount,
getValidResults,
handleShippingServices,
handleApplyDiscount,
handleListPayments,
} from './functions-checkout/checkout-utils';
import createOrder from './functions-checkout/new-order';
type Item = Exclude<OrderSet['items'], undefined>[number]
export default async (req: Request, res: Response) => {
const host = req.hostname !== 'localhost' && req.hostname !== '127.0.0.1'
? `https://${req.hostname}`
: 'http://127.0.0.1:5000/_api/modules';
console.log('>> debug ', host);
const modulesBaseURL = `${host}${req.url.replace(/\/@?checkout[^/]*$/i, '')}`;
const validate = ajv.compile(checkoutSchema.params);
req.body.client_ip = req.ip;
const userAgent = req.get('user-agent');
req.body.client_user_agent = userAgent === 'string'
? userAgent.substring(0, 255)
: '';
const checkoutBody = req.body as CheckoutBody;
if (checkoutBody.shipping.to.number! < 1) {
delete checkoutBody.shipping.to.number;
}
if (!validate(checkoutBody)) {
return sendRequestError(res, '@checkout', validate.errors);
}
const { items, ...newBody } = checkoutBody;
info(`Checkout by ${checkoutBody.customer.main_email}`, { checkoutBody });
const newItems = await fixItems(items) as Exclude<OrderSet['items'], undefined>;
const amount: Amount = {
subtotal: 0,
discount: 0,
freight: 0,
total: 0,
};
const body: CheckoutBodyWithItems = {
...newBody,
items: [...newItems],
subtotal: 0,
amount,
};
if (!newItems.length) {
return sendError(res, 400, 'CKT801', 'Cannot handle checkout, any valid cart item');
}
const countCheckoutItems = body.items.length;
const { customer } = body;
const savedCustomer = await readOrSaveCustomer({
...customer,
addresses: !body.shipping.to.line_address?.includes('***')
? [body.shipping.to]
: undefined,
});
const customerId = savedCustomer._id;
if (customerId === customer._id) {
Object.keys(savedCustomer).forEach((field) => {
if (customer[field] === undefined) {
customer[field] = savedCustomer[field];
}
});
if (customer.name.family_name?.includes('***') && savedCustomer.name) {
customer.name = savedCustomer.name;
}
if (customer.phones?.[0].number.match(/^0{3,}\d{1,4}$/)) {
customer.phones = savedCustomer.phones;
}
}
customer._id = customerId;
const fixMaskedAddr = (bodyAddr: typeof body.shipping.to) => {
if (bodyAddr.line_address?.includes('***') || bodyAddr.name?.includes('***')) {
const savedAddr = savedCustomer.addresses?.find(({ zip }) => zip === bodyAddr.zip);
if (savedAddr) {
Object.assign(bodyAddr, savedAddr);
delete bodyAddr.line_address;
}
}
};
fixMaskedAddr(body.shipping.to);
// start mounting order body
// https://developers.e-com.plus/docs/api/#/store/orders/orders
const dateTime = new Date().toISOString();
const orderBody: OrderSet = {
opened_at: dateTime,
buyers: [{
...customer,
_id: customerId,
}],
items: [],
amount: {
total: 0,
},
};
// bypass some order fields
const fields = [
'utm',
'affiliate_code',
'client_ip',
'client_user_agent',
'channel_id',
'channel_type',
'domain',
'notes',
];
fields.forEach((field) => {
if (body[field]) {
orderBody[field] = body[field];
}
});
if (orderBody.domain) {
// consider default Storefront app routes
if (!orderBody.checkout_link) {
orderBody.checkout_link = `https://${orderBody.domain}/app/#/checkout/(_id)`;
}
if (!orderBody.status_link) {
orderBody.status_link = `https://${orderBody.domain}/app/#/order/(_id)`;
}
}
let subtotal = 0;
newItems.forEach(
(item: Item) => {
subtotal += ((item.final_price || item.price) * item.quantity);
if (orderBody.items) {
orderBody.items.push({ ...item });
}
},
);
if (subtotal <= 0 && items.length < countCheckoutItems) {
return sendError(res, 400, 'CKT801', 'Cannot handle checkout, any valid cart item');
}
amount.subtotal = subtotal;
body.subtotal = subtotal;
fixAmount(amount, body, orderBody);
const transactions = Array.isArray(body.transaction) ? body.transaction : [body.transaction];
transactions.forEach((transaction) => {
transaction.buyer.customer_id = customerId;
(['buyer', 'payer'] as const).forEach((field) => {
const buyerOrPayer = transaction[field];
if (buyerOrPayer?.fullname?.includes('***')) {
buyerOrPayer.fullname = getFullname(customer);
if (customer.phones?.[0]) buyerOrPayer.phone = customer.phones[0];
}
});
(['billing_address', 'to'] as const).forEach((field) => {
const addr = transaction[field];
if (addr) fixMaskedAddr(addr);
});
});
let shippingOptions = await requestModule(body, modulesBaseURL, 'shipping');
let { msgErr } = shippingOptions;
if (shippingOptions && !msgErr) {
shippingOptions = getValidResults(shippingOptions, 'shipping_services');
handleShippingServices(body, shippingOptions, amount, orderBody);
} else {
// problem with shipping response object
return sendError(
res,
msgErr?.status || 400,
msgErr?.code || 'CKT901',
'Any valid shipping service from /calculate_shipping module',
{
en_us: 'Shipping method not available, please choose another',
pt_br: 'Forma de envio indisponível, por favor escolha outra',
},
msgErr?.moreInfo,
);
}
let discounts = await requestModule(body, modulesBaseURL, 'discount');
if (discounts) {
discounts = getValidResults(discounts);
handleApplyDiscount(body, discounts, amount, orderBody);
}
const { transaction, ...bodyPayment } = body;
let paymentsBody: Payment;
if (Array.isArray(transaction)) {
paymentsBody = {
...bodyPayment,
transaction: transaction[0],
};
} else {
paymentsBody = {
...bodyPayment,
transaction,
};
}
let listPaymentGateways = await requestModule(paymentsBody, modulesBaseURL, 'payment');
msgErr = listPaymentGateways.msgErr;
if (listPaymentGateways && !msgErr) {
listPaymentGateways = getValidResults(listPaymentGateways, 'payment_gateways');
handleListPayments(body, listPaymentGateways, paymentsBody, amount, orderBody);
} else {
return sendError(
res,
msgErr?.status || 409,
msgErr?.code || 'CKT902',
'Any valid payment gateway from /list_payments module',
{
en_us: 'Payment method not available, please choose another',
pt_br: 'Forma de pagamento indisponível, por favor escolha outra',
},
msgErr?.moreInfo,
);
}
return createOrder(
res,
modulesBaseURL,
amount,
checkoutBody,
orderBody,
transactions,
dateTime,
);
};