-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Expand file tree
/
Copy pathconfirmOrder.ts
More file actions
230 lines (210 loc) · 6.08 KB
/
confirmOrder.ts
File metadata and controls
230 lines (210 loc) · 6.08 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
import { addDataAndFileToRequest, type DefaultDocumentIDType, type Endpoint } from 'payload'
import type { CurrenciesConfig, PaymentAdapter, ProductsValidation } from '../types/index.js'
type Args = {
/**
* The slug of the carts collection, defaults to 'carts'.
*/
cartsSlug?: string
currenciesConfig: CurrenciesConfig
/**
* The slug of the customers collection, defaults to 'users'.
*/
customersSlug?: string
/**
* The slug of the orders collection, defaults to 'orders'.
*/
ordersSlug?: string
paymentMethod: PaymentAdapter
/**
* The slug of the products collection, defaults to 'products'.
*/
productsSlug?: string
/**
* Customise the validation used for checking products or variants before a transaction is created.
*/
productsValidation?: ProductsValidation
/**
* The slug of the transactions collection, defaults to 'transactions'.
*/
transactionsSlug?: string
/**
* The slug of the variants collection, defaults to 'variants'.
*/
variantsSlug?: string
}
type ConfirmOrderHandler = (args: Args) => Endpoint['handler']
/**
* Handles the endpoint for initiating payments. We will handle checking the amount and product and variant prices here before it is sent to the payment provider.
* This is the first step in the payment process.
*/
export const confirmOrderHandler: ConfirmOrderHandler =
({
cartsSlug = 'carts',
currenciesConfig,
customersSlug = 'users',
ordersSlug = 'orders',
paymentMethod,
productsSlug = 'products',
productsValidation,
transactionsSlug = 'transactions',
variantsSlug = 'variants',
}) =>
async (req) => {
await addDataAndFileToRequest(req)
const data = req.data
const payload = req.payload
const user = req.user?.collection === customersSlug ? req.user : undefined
let currency: string = currenciesConfig.defaultCurrency
let cartID: DefaultDocumentIDType = data?.cartID
let cart = undefined
let customerEmail: string = user?.email ?? ''
const cartSecret = data?.secret
if (user) {
if (user.cart?.docs && Array.isArray(user.cart.docs) && user.cart.docs.length > 0) {
if (!cartID && user.cart.docs[0]) {
// Use the user's cart instead
if (typeof user.cart.docs[0] === 'object') {
cartID = user.cart.docs[0].id
cart = user.cart.docs[0]
} else {
cartID = user.cart.docs[0]
}
}
}
} else {
// Get the email from the data if user is not available
if (data?.customerEmail && typeof data.customerEmail === 'string') {
customerEmail = data.customerEmail
} else {
return Response.json(
{
message: 'A customer email is required to make a purchase.',
},
{
status: 400,
},
)
}
}
if (!cart) {
if (cartID) {
// Add cart secret to query for guest cart access control
if (cartSecret && typeof cartSecret === 'string') {
req.query = req.query || {}
req.query.secret = cartSecret
}
cart = await payload.findByID({
id: cartID,
collection: cartsSlug,
depth: 2,
overrideAccess: false,
req,
select: {
id: true,
currency: true,
customerEmail: true,
items: true,
subtotal: true,
},
})
if (!cart) {
return Response.json(
{
message: `Cart with ID ${cartID} not found.`,
},
{
status: 404,
},
)
}
} else {
return Response.json(
{
message: 'Cart ID is required.',
},
{
status: 400,
},
)
}
}
if (cart.currency && typeof cart.currency === 'string') {
currency = cart.currency
}
// Ensure the currency is provided or inferred in some way
if (!currency) {
return Response.json(
{
message: 'Currency is required.',
},
{
status: 400,
},
)
}
try {
const paymentResponse = await paymentMethod.confirmOrder({
cartsSlug,
customersSlug,
data: {
...data,
customerEmail,
},
ordersSlug,
req,
transactionsSlug,
})
if (paymentResponse.transactionID) {
const transaction = await payload.findByID({
id: paymentResponse.transactionID,
collection: transactionsSlug,
depth: 0,
select: {
id: true,
items: true,
},
})
if (transaction && Array.isArray(transaction.items) && transaction.items.length > 0) {
for (const item of transaction.items) {
if (item.variant) {
const id = typeof item.variant === 'object' ? item.variant.id : item.variant
await payload.db.updateOne({
id,
collection: variantsSlug,
data: {
inventory: {
$inc: item.quantity * -1,
},
},
})
} else if (item.product) {
const id = typeof item.product === 'object' ? item.product.id : item.product
await payload.db.updateOne({
id,
collection: productsSlug,
data: {
inventory: {
$inc: item.quantity * -1,
},
},
})
}
}
}
}
if ('paymentResponse.transactionID' in paymentResponse && paymentResponse.transactionID) {
delete (paymentResponse as Partial<typeof paymentResponse>).transactionID
}
return Response.json(paymentResponse)
} catch (error) {
payload.logger.error(error, 'Error confirming order.')
return Response.json(
{
message: 'Error confirming order.',
},
{
status: 500,
},
)
}
}