/
OrderItems.tsx
392 lines (337 loc) · 10.3 KB
/
OrderItems.tsx
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
import React, {
createContext,
FC,
useCallback,
useContext,
useMemo,
useRef,
useEffect,
} from 'react'
import { useMutation } from 'react-apollo'
import UpdateItems from 'vtex.checkout-resources/MutationUpdateItems'
import AddToCart from 'vtex.checkout-resources/MutationAddToCard'
import { useOrderForm } from 'vtex.order-manager/OrderForm'
import {
useOrderQueue,
useQueueStatus,
QueueStatus,
} from 'vtex.order-manager/OrderQueue'
import {
LocalOrderTaskType,
getLocalOrderQueue,
popLocalOrderQueue,
pushLocalOrderQueue,
updateLocalQueueItemIds,
} from './modules/localOrderQueue'
import {
adjustForItemInput,
mapItemInputToOrderFormItem,
AVAILABLE,
} from './utils'
interface Context {
addItem: (props: Partial<Item>[]) => void
updateQuantity: (props: Partial<Item>) => void
removeItem: (props: Partial<Item>) => void
}
enum Totalizers {
SUBTOTAL = 'Items',
DISCOUNT = 'Discounts',
}
const updateTotalizersAndValue = ({
totalizers,
currentValue,
newItem,
oldItem,
}: {
totalizers: Totalizer[]
currentValue: number
newItem: Item
oldItem: Item
}) => {
if (oldItem.availability !== AVAILABLE) {
return { totalizers, value: currentValue }
}
const oldPrice = oldItem.price * oldItem.quantity
const newPrice = newItem.price * newItem.quantity
const subtotalDifference = newPrice - oldPrice
const oldDiscount = (oldItem.sellingPrice - oldItem.price) * oldItem.quantity
const newDiscount = (newItem.sellingPrice - newItem.price) * newItem.quantity
const discountDifference = newDiscount - oldDiscount
const newTotalizers = totalizers.map((totalizer: Totalizer) => {
switch (totalizer.id) {
case Totalizers.SUBTOTAL:
return { ...totalizer, value: totalizer.value + subtotalDifference }
case Totalizers.DISCOUNT:
return { ...totalizer, value: totalizer.value + discountDifference }
default:
return totalizer
}
})
return {
totalizers: newTotalizers,
value: currentValue + subtotalDifference - discountDifference,
}
}
const addToTotalizers = (totalizers: Totalizer[], item: Item): Totalizer[] => {
const itemPrice = item.price * item.quantity
const itemDiscount = (item.sellingPrice - item.price) * item.quantity
if (!totalizers.length) {
return [
{
id: Totalizers.SUBTOTAL,
name: 'Items Total',
value: itemPrice,
},
{
id: Totalizers.DISCOUNT,
name: 'Discounts Total',
value: itemDiscount,
},
]
}
return totalizers.map(totalizer => {
switch (totalizer.id) {
case Totalizers.SUBTOTAL:
return {
...totalizer,
value: totalizer.value + itemPrice,
}
case Totalizers.DISCOUNT:
return {
...totalizer,
value: totalizer.value + itemDiscount,
}
default:
return totalizer
}
})
}
const noop = async () => {}
const OrderItemsContext = createContext<Context>({
addItem: noop,
updateQuantity: noop,
removeItem: noop,
})
const useEnqueueTask = () => {
const { enqueue, listen } = useOrderQueue()
const queueStatusRef = useQueueStatus(listen)
const { setOrderForm } = useOrderForm()
const enqueueTask = useCallback<(task: () => Promise<OrderForm>) => void>(
task => {
enqueue(task).then(
(orderForm: OrderForm) => {
popLocalOrderQueue()
if (queueStatusRef.current === QueueStatus.FULFILLED) {
setOrderForm(orderForm)
}
},
(error: any) => {
popLocalOrderQueue()
if (!error || error.code !== 'TASK_CANCELLED') {
throw error
}
}
)
},
[enqueue, queueStatusRef, setOrderForm]
)
return enqueueTask
}
interface UpdateItemsMutation {
updateItems: OrderForm
}
export const OrderItemsProvider: FC = ({ children }) => {
const { orderForm, setOrderForm } = useOrderForm()
const enqueueTask = useEnqueueTask()
const orderFormItemsRef = useRef(orderForm.items)
useEffect(() => {
orderFormItemsRef.current = orderForm.items
}, [orderForm.items])
const [mutateUpdateQuantity] = useMutation<UpdateItemsMutation>(UpdateItems)
const [mutateAddItem] = useMutation<
{ addToCart: OrderForm },
{ items: OrderFormItemInput[] }
>(AddToCart)
const addItem = useCallback(
(items: Partial<Item>[]) => {
const mutationInput = items.map(adjustForItemInput)
const orderFormItems = mutationInput
.map((itemInput, index) =>
mapItemInputToOrderFormItem(itemInput, items[index])
)
.filter(
orderFormItem =>
orderFormItemsRef.current.findIndex(
(item: any) => item.id === orderFormItem.id
) === -1
)
if (orderFormItems.length === 0) {
// all items already exist in the cart
return
}
setOrderForm((prevOrderForm: OrderForm) => ({
...prevOrderForm,
items: [...orderFormItemsRef.current, ...orderFormItems],
totalizers: orderFormItems.reduce(
addToTotalizers,
prevOrderForm.totalizers ?? []
),
value:
prevOrderForm.value +
orderFormItems.reduce(
(total, item) => total + item.sellingPrice * item.quantity,
0
),
}))
pushLocalOrderQueue({
type: LocalOrderTaskType.ADD_MUTATION,
variables: {
items: mutationInput,
},
})
enqueueTask(() => {
return mutateAddItem({ variables: { items: mutationInput } })
.then(({ data }) => data!.addToCart)
.then(orderForm => {
// update the uniqueId of the items that were
// added locally with the value from the server
setOrderForm((prevOrderForm: OrderForm) => ({
...prevOrderForm,
items: prevOrderForm.items.map(item => {
const inputIndex = mutationInput.findIndex(
inputItem => inputItem.id === +item.id
)
if (inputIndex === -1) {
// this item wasn't part of the initial mutation, skip it
return item
}
const updatedItem = orderForm.items.find(
updatedItem => updatedItem.id === item.id
)!
const fakeUniqueId = item.uniqueId
// update all mutations in the queue that referenced
// this item with it's fake `uniqueId`
updateLocalQueueItemIds({
fakeUniqueId,
uniqueId: updatedItem.uniqueId,
})
return {
...item,
uniqueId: updatedItem.uniqueId,
}
}),
}))
return orderForm
})
})
},
[enqueueTask, mutateAddItem, setOrderForm]
)
const updateQuantity = useCallback(
input => {
let index: number
let uniqueId = ''
if (input.id) {
index = orderFormItemsRef.current.findIndex(
(orderItem: any) => orderItem.id === input.id
)
} else if ('uniqueId' in input) {
uniqueId = input.uniqueId
index = orderFormItemsRef.current.findIndex(
(orderItem: any) => orderItem.uniqueId === input.uniqueId
)
} else {
index = input.index ?? -1
}
if (index < 0 || index >= orderFormItemsRef.current.length) {
throw new Error(`Item ${input.id || input.uniqueId} not found`)
}
if (!uniqueId) {
uniqueId = orderFormItemsRef.current[index].uniqueId
}
const quantity = input.quantity ?? 1
setOrderForm((prevOrderForm: OrderForm) => {
const updatedItems = prevOrderForm.items.slice()
const oldItem = updatedItems[index]
const newItem = {
...oldItem,
quantity,
}
if (quantity > 0) {
updatedItems[index] = newItem
} else {
updatedItems.splice(index, 1)
}
return {
...prevOrderForm,
...updateTotalizersAndValue({
totalizers: prevOrderForm.totalizers,
currentValue: prevOrderForm.value,
newItem,
oldItem,
}),
items: updatedItems,
}
})
let mutationVariables = {
orderItems: [{ uniqueId, quantity }],
}
pushLocalOrderQueue({
type: LocalOrderTaskType.UPDATE_MUTATION,
variables: mutationVariables,
})
enqueueTask(() => {
// here we need to update the uniqueId again in the mutation
// because it may have been a "fake" `uniqueId` that were generated
// locally so we could manage the items better.
// so, we will read the value again using the orderFormItemsRef because
// it will contain the latest value, i.e. will have the *actual* uniqueId
// for this item.
uniqueId = orderFormItemsRef.current[index].uniqueId
mutationVariables = {
orderItems: [{ uniqueId, quantity }],
}
return mutateUpdateQuantity({
variables: mutationVariables,
}).then(({ data }) => data!.updateItems)
})
},
[enqueueTask, mutateUpdateQuantity, setOrderForm]
)
const removeItem = useCallback(
(props: Partial<Item>) => updateQuantity({ ...props, quantity: 0 }),
[updateQuantity]
)
const value = useMemo(() => ({ addItem, updateQuantity, removeItem }), [
addItem,
updateQuantity,
removeItem,
])
useEffect(() => {
const localOrderQueue = getLocalOrderQueue()
localOrderQueue.queue.forEach(task => {
if (task.type === LocalOrderTaskType.ADD_MUTATION) {
enqueueTask(() =>
mutateAddItem({ variables: task?.variables }).then(
({ data }) => data!.addToCart
)
)
} else if (task.type === LocalOrderTaskType.UPDATE_MUTATION) {
enqueueTask(() =>
mutateUpdateQuantity({
variables: task?.variables,
}).then(({ data }) => data!.updateItems)
)
}
})
}, [enqueueTask, mutateAddItem, mutateUpdateQuantity])
return (
<OrderItemsContext.Provider value={value}>
{children}
</OrderItemsContext.Provider>
)
}
export const useOrderItems = () => {
return useContext(OrderItemsContext)
}
export default { OrderItemsProvider, useOrderItems }