Raw
1 import {
2 BigNumberInput,
3 Context,
4 DAL,
5 IInventoryService,
6 InferEntityType,
7 InternalModuleDeclaration,
8 InventoryTypes,
9 ModuleJoinerConfig,
10 ModulesSdkTypes,
11 ReservationItemDTO,
12 RestoreReturn,
13 SoftDeleteReturn,
14 } from "@medusajs/framework/types"
15 import {
16 arrayDifference,
17 BigNumber,
18 EmitEvents,
19 InjectManager,
20 InjectTransactionManager,
21 isDefined,
22 isString,
23 MathBN,
24 MedusaContext,
25 MedusaError,
26 MedusaService,
27 partitionArray,
28 } from "@medusajs/framework/utils"
29 import { InventoryItem, InventoryLevel, ReservationItem } from "@models"
30 import { joinerConfig } from "../joiner-config"
31 import { applyEntityHooks } from "../utils/apply-decorators"
32 import InventoryLevelService from "./inventory-level"
33
34 type InjectedDependencies = {
35 baseRepository: DAL.RepositoryService
36 inventoryItemService: ModulesSdkTypes.IMedusaInternalService<any>
37 inventoryLevelService: InventoryLevelService
38 reservationItemService: ModulesSdkTypes.IMedusaInternalService<any>
39 }
40
41 type InventoryItemCheckLevel = {
42 id?: string
43 location_id: string
44 inventory_item_id: string
45 quantity?: BigNumberInput
46 allow_backorder?: boolean
47 }
48
49 applyEntityHooks()
50
51 export default class InventoryModuleService
52 extends MedusaService<{
53 InventoryItem: {
54 dto: InventoryTypes.InventoryItemDTO
55 }
56 InventoryLevel: {
57 dto: InventoryTypes.InventoryLevelDTO
58 }
59 ReservationItem: {
60 dto: InventoryTypes.ReservationItemDTO
61 }
62 }>({
63 InventoryItem,
64 InventoryLevel,
65 ReservationItem,
66 })
67 implements IInventoryService
68 {
69 protected baseRepository_: DAL.RepositoryService
70
71 protected readonly inventoryItemService_: ModulesSdkTypes.IMedusaInternalService<
72 typeof InventoryItem
73 >
74 protected readonly reservationItemService_: ModulesSdkTypes.IMedusaInternalService<
75 typeof ReservationItem
76 >
77 protected readonly inventoryLevelService_: InventoryLevelService
78
79 constructor(
80 {
81 baseRepository,
82 inventoryItemService,
83 inventoryLevelService,
84 reservationItemService,
85 }: InjectedDependencies,
86 protected readonly moduleDeclaration?: InternalModuleDeclaration
87 ) {
88 // @ts-ignore
89 // eslint-disable-next-line prefer-rest-params
90 super(...arguments)
91
92 this.baseRepository_ = baseRepository
93 this.inventoryItemService_ = inventoryItemService
94 this.inventoryLevelService_ = inventoryLevelService
95 this.reservationItemService_ = reservationItemService
96 }
97
98 __joinerConfig(): ModuleJoinerConfig {
99 return joinerConfig
100 }
101
102 private async ensureInventoryLevels(
103 data: InventoryItemCheckLevel[],
104 options?: {
105 validateQuantityAtLocation?: boolean
106 },
107 context?: Context
108 ): Promise<InventoryTypes.InventoryLevelDTO[]> {
109 options ??= {}
110 const validateQuantityAtLocation =
111 options.validateQuantityAtLocation ?? false
112
113 const data_ = data.map((dt: any) => ({
114 location_id: dt.location_id,
115 inventory_item_id: dt.inventory_item_id,
116 })) as InventoryItemCheckLevel[]
117
118 const [idData, itemLocationData] = partitionArray(
119 data_,
120 ({ id }) => !!id
121 ) as [
122 { id: string }[],
123 { location_id: string; inventory_item_id: string }[]
124 ]
125
126 const inventoryLevels = await this.inventoryLevelService_.list(
127 {
128 $or: [
129 { id: idData.filter(({ id }) => !!id).map((e) => e.id) },
130 ...itemLocationData,
131 ],
132 },
133 {},
134 context
135 )
136
137 const inventoryLevelIdMap: Map<string, InventoryTypes.InventoryLevelDTO> =
138 new Map(inventoryLevels.map((level) => [level.id, level]))
139
140 const inventoryLevelItemLocationMap: Map<
141 string,
142 Map<string, InventoryTypes.InventoryLevelDTO>
143 > = inventoryLevels.reduce((acc, curr) => {
144 const inventoryLevelMap = acc.get(curr.inventory_item_id) ?? new Map()
145 inventoryLevelMap.set(curr.location_id, curr)
146 acc.set(curr.inventory_item_id, inventoryLevelMap)
147 return acc
148 }, new Map())
149
150 const missing = data.filter((item) => {
151 if (item.id) {
152 return !inventoryLevelIdMap.has(item.id!)
153 }
154
155 return !inventoryLevelItemLocationMap
156 .get(item.inventory_item_id)
157 ?.has(item.location_id)
158 })
159
160 if (missing.length) {
161 const error = missing
162 .map((missing) => {
163 if ("id" in missing) {
164 return `Inventory level with id ${missing.id} does not exist`
165 }
166 return `Item ${missing.inventory_item_id} is not stocked at location ${missing.location_id}`
167 })
168 .join(", ")
169
170 throw new MedusaError(MedusaError.Types.NOT_FOUND, error)
171 }
172
173 if (validateQuantityAtLocation) {
174 for (const item of data) {
175 if (!!item.allow_backorder) {
176 continue
177 }
178
179 const locations = inventoryLevelItemLocationMap.get(
180 item.inventory_item_id
181 )!
182
183 const level = locations?.get(item.location_id)!
184
185 if (MathBN.lt(level.available_quantity, item.quantity!)) {
186 throw new MedusaError(
187 MedusaError.Types.NOT_ALLOWED,
188 `Not enough stock available for item ${item.inventory_item_id} at location ${item.location_id}`
189 )
190 }
191 }
192 }
193
194 return inventoryLevels
195 }
196
197 // reserved_quantity should solely be handled through creating & updating reservation items
198 // We sanitize the inputs here to prevent that from being used to update it
199 private sanitizeInventoryLevelInput<TDTO = unknown>(
200 input: (TDTO & {
201 reserved_quantity?: BigNumberInput
202 })[]
203 ): TDTO[] {
204 return input.map((input) => {
205 const { reserved_quantity, ...validInput } = input
206
207 return validInput as TDTO
208 })
209 }
210
211 private sanitizeInventoryItemInput<TDTO = unknown>(
212 input: (TDTO & {
213 location_levels?: object[]
214 })[]
215 ): TDTO[] {
216 return input.map((input) => {
217 const { location_levels, ...validInput } = input
218
219 return validInput as TDTO
220 })
221 }
222
223 // @ts-expect-error
224 async createReservationItems(
225 input: InventoryTypes.CreateReservationItemInput[],
226 context?: Context
227 ): Promise<InventoryTypes.ReservationItemDTO[]>
228 // @ts-expect-error
229 async createReservationItems(
230 input: InventoryTypes.CreateReservationItemInput,
231 context?: Context
232 ): Promise<InventoryTypes.ReservationItemDTO>
233
234 @InjectManager()
235 @EmitEvents()
236 // @ts-expect-error
237 async createReservationItems(
238 input:
239 | InventoryTypes.CreateReservationItemInput[]
240 | InventoryTypes.CreateReservationItemInput,
241 @MedusaContext() context: Context = {}
242 ): Promise<
243 InventoryTypes.ReservationItemDTO[] | InventoryTypes.ReservationItemDTO
244 > {
245 const toCreate = Array.isArray(input) ? input : [input]
246 const created = await this.createReservationItems_(toCreate, context)
247
248 const serializedReservations = await this.baseRepository_.serialize<
249 InventoryTypes.ReservationItemDTO[] | InventoryTypes.ReservationItemDTO
250 >(created)
251
252 return Array.isArray(input)
253 ? serializedReservations
254 : serializedReservations[0]
255 }
256
257 @InjectTransactionManager()
258 async createReservationItems_(
259 input: InventoryTypes.CreateReservationItemInput[],
260 @MedusaContext() context: Context = {}
261 ): Promise<InferEntityType<typeof ReservationItem>[]> {
262 const inventoryLevels = await this.ensureInventoryLevels(
263 input.map(
264 ({ location_id, inventory_item_id, quantity, allow_backorder }) => ({
265 location_id,
266 inventory_item_id,
267 quantity,
268 allow_backorder,
269 })
270 ),
271 {
272 validateQuantityAtLocation: true,
273 },
274 context
275 )
276
277 const created = await this.reservationItemService_.create(input, context)
278
279 const adjustments: Map<string, Map<string, number>> = input.reduce(
280 (acc, curr) => {
281 const locationMap = acc.get(curr.inventory_item_id) ?? new Map()
282
283 const adjustment = locationMap.get(curr.location_id) ?? 0
284 locationMap.set(curr.location_id, MathBN.add(adjustment, curr.quantity))
285
286 acc.set(curr.inventory_item_id, locationMap)
287 return acc
288 },
289 new Map()
290 )
291
292 const levelAdjustmentUpdates = inventoryLevels.map((level) => {
293 const adjustment = adjustments
294 .get(level.inventory_item_id)
295 ?.get(level.location_id)
296
297 if (!adjustment) {
298 return
299 }
300
301 return {
302 id: level.id,
303 reserved_quantity: MathBN.add(level.reserved_quantity, adjustment),
304 }
305 })
306
307 await this.inventoryLevelService_.update(levelAdjustmentUpdates, context)
308
309 return created
310 }
311
312 // @ts-expect-error
313 createInventoryItems(
314 input: InventoryTypes.CreateInventoryItemInput,
315 context?: Context
316 ): Promise<InventoryTypes.InventoryItemDTO>
317 createInventoryItems(
318 input: InventoryTypes.CreateInventoryItemInput[],
319 context?: Context
320 ): Promise<InventoryTypes.InventoryItemDTO[]>
321
322 @InjectManager()
323 @EmitEvents()
324 async createInventoryItems(
325 input:
326 | InventoryTypes.CreateInventoryItemInput
327 | InventoryTypes.CreateInventoryItemInput[],
328 @MedusaContext() context: Context = {}
329 ): Promise<
330 InventoryTypes.InventoryItemDTO | InventoryTypes.InventoryItemDTO[]
331 > {
332 const toCreate = this.sanitizeInventoryItemInput(
333 Array.isArray(input) ? input : [input]
334 )
335 const result = await this.createInventoryItems_(toCreate, context)
336
337 const serializedItems = await this.baseRepository_.serialize<
338 InventoryTypes.InventoryItemDTO | InventoryTypes.InventoryItemDTO[]
339 >(result)
340
341 return Array.isArray(input) ? serializedItems : serializedItems[0]
342 }
343
344 @InjectTransactionManager()
345 async createInventoryItems_(
346 input: InventoryTypes.CreateInventoryItemInput[],
347 @MedusaContext() context: Context = {}
348 ): Promise<InventoryTypes.InventoryItemDTO[]> {
349 return await this.inventoryItemService_.create(input, context)
350 }
351
352 // @ts-ignore
353 createInventoryLevels(
354 input: InventoryTypes.CreateInventoryLevelInput,
355 context?: Context
356 ): Promise<InventoryTypes.InventoryLevelDTO>
357 // @ts-expect-error
358 createInventoryLevels(
359 input: InventoryTypes.CreateInventoryLevelInput[],
360 context?: Context
361 ): Promise<InventoryTypes.InventoryLevelDTO[]>
362
363 @InjectManager()
364 @EmitEvents()
365 // @ts-expect-error
366 async createInventoryLevels(
367 input:
368 | InventoryTypes.CreateInventoryLevelInput[]
369 | InventoryTypes.CreateInventoryLevelInput,
370 @MedusaContext() context: Context = {}
371 ): Promise<
372 InventoryTypes.InventoryLevelDTO[] | InventoryTypes.InventoryLevelDTO
373 > {
374 const toCreate = this.sanitizeInventoryLevelInput(
375 Array.isArray(input) ? input : [input]
376 )
377
378 const created = await this.createInventoryLevels_(toCreate, context)
379
380 const serialized = await this.baseRepository_.serialize<
381 InventoryTypes.InventoryLevelDTO[] | InventoryTypes.InventoryLevelDTO
382 >(created)
383
384 return Array.isArray(input) ? serialized : serialized[0]
385 }
386
387 @InjectTransactionManager()
388 async createInventoryLevels_(
389 input: InventoryTypes.CreateInventoryLevelInput[],
390 @MedusaContext() context: Context = {}
391 ): Promise<InferEntityType<typeof InventoryLevel>[]> {
392 return await this.inventoryLevelService_.create(input, context)
393 }
394
395 // @ts-expect-error
396 updateInventoryItems(
397 input: InventoryTypes.UpdateInventoryItemInput[],
398 context?: Context
399 ): Promise<InventoryTypes.InventoryItemDTO[]>
400 // @ts-expect-error
401 updateInventoryItems(
402 input: InventoryTypes.UpdateInventoryItemInput,
403 context?: Context
404 ): Promise<InventoryTypes.InventoryItemDTO>
405
406 @InjectManager()
407 @EmitEvents()
408 // @ts-expect-error
409 async updateInventoryItems(
410 input:
411 | InventoryTypes.UpdateInventoryItemInput
412 | InventoryTypes.UpdateInventoryItemInput[],
413 @MedusaContext() context: Context = {}
414 ): Promise<
415 InventoryTypes.InventoryItemDTO | InventoryTypes.InventoryItemDTO[]
416 > {
417 const updates = this.sanitizeInventoryItemInput(
418 Array.isArray(input) ? input : [input]
419 )
420
421 const result = await this.updateInventoryItems_(updates, context)
422
423 const serializedItems = await this.baseRepository_.serialize<
424 InventoryTypes.InventoryItemDTO | InventoryTypes.InventoryItemDTO[]
425 >(result)
426
427 return Array.isArray(input) ? serializedItems : serializedItems[0]
428 }
429
430 @InjectTransactionManager()
431 async updateInventoryItems_(
432 input: (Partial<InventoryTypes.CreateInventoryItemInput> & {
433 id: string
434 })[],
435 @MedusaContext() context: Context = {}
436 ): Promise<InferEntityType<typeof InventoryItem>[]> {
437 return await this.inventoryItemService_.update(input, context)
438 }
439
440 @InjectManager()
441 @EmitEvents()
442 async deleteInventoryItemLevelByLocationId(
443 locationId: string | string[],
444 @MedusaContext() context: Context = {}
445 ): Promise<[object[], Record<string, unknown[]>]> {
446 const result = await this.inventoryLevelService_.softDelete(
447 { location_id: locationId },
448 context
449 )
450
451 return result
452 }
453
454 /**
455 * Deletes an inventory level
456 * @param inventoryItemId - the id of the inventory item associated with the level
457 * @param locationId - the id of the location associated with the level
458 * @param context
459 */
460 @InjectTransactionManager()
461 @EmitEvents()
462 async deleteInventoryLevel(
463 inventoryItemId: string,
464 locationId: string,
465 @MedusaContext() context: Context = {}
466 ): Promise<void> {
467 const [inventoryLevel] = await this.inventoryLevelService_.list(
468 { inventory_item_id: inventoryItemId, location_id: locationId },
469 { take: 1 },
470 context
471 )
472
473 if (!inventoryLevel) {
474 return
475 }
476
477 await this.inventoryLevelService_.delete(inventoryLevel.id, context)
478 }
479
480 // @ts-ignore
481 async updateInventoryLevels(
482 updates: InventoryTypes.UpdateInventoryLevelInput[],
483 context?: Context
484 ): Promise<InventoryTypes.InventoryLevelDTO[]>
485 // @ts-expect-error
486 async updateInventoryLevels(
487 updates: InventoryTypes.UpdateInventoryLevelInput,
488 context?: Context
489 ): Promise<InventoryTypes.InventoryLevelDTO>
490
491 @InjectManager()
492 @EmitEvents()
493 // @ts-expect-error
494 async updateInventoryLevels(
495 updates:
496 | InventoryTypes.UpdateInventoryLevelInput[]
497 | InventoryTypes.UpdateInventoryLevelInput,
498 @MedusaContext() context: Context = {}
499 ): Promise<
500 InventoryTypes.InventoryLevelDTO | InventoryTypes.InventoryLevelDTO[]
501 > {
502 const input = this.sanitizeInventoryLevelInput(
503 Array.isArray(updates) ? updates : [updates]
504 )
505
506 const levels = await this.updateInventoryLevels_(input, context)
507
508 const updatedLevels = await this.baseRepository_.serialize<
509 InventoryTypes.InventoryLevelDTO | InventoryTypes.InventoryLevelDTO[]
510 >(levels)
511
512 return Array.isArray(updates) ? updatedLevels : updatedLevels[0]
513 }
514
515 @InjectTransactionManager()
516 async updateInventoryLevels_(
517 updates: InventoryTypes.UpdateInventoryLevelInput[],
518 @MedusaContext() context: Context = {}
519 ) {
520 const inventoryLevels = await this.ensureInventoryLevels(
521 updates.map(({ location_id, inventory_item_id }) => ({
522 location_id,
523 inventory_item_id,
524 })),
525 undefined,
526 context
527 )
528
529 const levelMap = inventoryLevels.reduce((acc, curr) => {
530 const inventoryLevelMap = acc.get(curr.inventory_item_id) ?? new Map()
531 inventoryLevelMap.set(curr.location_id, curr.id)
532 acc.set(curr.inventory_item_id, inventoryLevelMap)
533 return acc
534 }, new Map())
535
536 const updatesWithIds = updates.map((update) => {
537 const id = levelMap.get(update.inventory_item_id).get(update.location_id)
538
539 return { id, ...update }
540 })
541
542 return await this.inventoryLevelService_.update(updatesWithIds, context)
543 }
544
545 /**
546 * Updates a reservation item
547 * @param reservationItemId
548 * @param input - the input object
549 * @param context
550 * @param context
551 * @return The updated inventory level
552 */
553 // @ts-expect-error
554 async updateReservationItems(
555 input: InventoryTypes.UpdateReservationItemInput[],
556 context?: Context
557 ): Promise<InventoryTypes.ReservationItemDTO[]>
558 // @ts-expect-error
559 async updateReservationItems(
560 input: InventoryTypes.UpdateReservationItemInput,
561 context?: Context
562 ): Promise<InventoryTypes.ReservationItemDTO>
563
564 @InjectManager()
565 @EmitEvents()
566 // @ts-expect-error
567 async updateReservationItems(
568 input:
569 | InventoryTypes.UpdateReservationItemInput
570 | InventoryTypes.UpdateReservationItemInput[],
571 @MedusaContext() context: Context = {}
572 ): Promise<
573 InventoryTypes.ReservationItemDTO | InventoryTypes.ReservationItemDTO[]
574 > {
575 const update = Array.isArray(input) ? input : [input]
576 const result = await this.updateReservationItems_(update, context)
577
578 const serialized = await this.baseRepository_.serialize<
579 InventoryTypes.ReservationItemDTO | InventoryTypes.ReservationItemDTO[]
580 >(result)
581
582 return Array.isArray(input) ? serialized : serialized[0]
583 }
584
585 @InjectTransactionManager()
586 async updateReservationItems_(
587 input: (InventoryTypes.UpdateReservationItemInput & { id: string })[],
588 @MedusaContext() context: Context = {}
589 ): Promise<InferEntityType<typeof ReservationItem>[]> {
590 const ids = input.map((u) => u.id)
591 const reservationItems = await this.reservationItemService_.list(
592 { id: ids },
593 {},
594 context
595 )
596
597 const diff = arrayDifference(
598 ids,
599 reservationItems.map((i) => i.id)
600 )
601
602 if (diff.length) {
603 throw new MedusaError(
604 MedusaError.Types.INVALID_DATA,
605 `Reservation item with id ${diff.join(", ")} not found`
606 )
607 }
608
609 const reservationMap: Map<string, ReservationItemDTO> = new Map(
610 reservationItems.map((r) => [r.id, r])
611 )
612
613 const adjustments: Map<string, Map<string, number>> = input.reduce(
614 (acc, update) => {
615 const reservation = reservationMap.get(update.id)!
616 const locationMap = acc.get(reservation.inventory_item_id) ?? new Map()
617
618 if (
619 isDefined(update.location_id) &&
620 update.location_id !== reservation.location_id
621 ) {
622 const reservationLocationAdjustment =
623 locationMap.get(reservation.location_id) ?? 0
624
625 locationMap.set(
626 reservation.location_id,
627 MathBN.sub(reservationLocationAdjustment, reservation.quantity)
628 )
629
630 const updateLocationAdjustment =
631 locationMap.get(update.location_id) ?? 0
632
633 locationMap.set(
634 update.location_id,
635 MathBN.add(
636 updateLocationAdjustment,
637 update.quantity || reservation.quantity
638 )
639 )
640 } else if (
641 isDefined(update.quantity) &&
642 !MathBN.eq(update.quantity, reservation.quantity)
643 ) {
644 const locationAdjustment =
645 locationMap.get(reservation.location_id) ?? 0
646
647 locationMap.set(
648 reservation.location_id,
649 MathBN.add(
650 locationAdjustment,
651 MathBN.sub(update.quantity!, reservation.quantity)
652 )
653 )
654 }
655
656 acc.set(reservation.inventory_item_id, locationMap)
657
658 return acc
659 },
660 new Map()
661 )
662 const availabilityData = input.map((data) => {
663 const reservation = reservationMap.get(data.id)!
664
665 let adjustment = data.quantity
666 ? MathBN.sub(data.quantity, reservation.quantity)
667 : 0
668
669 if (MathBN.lt(adjustment, 0)) {
670 adjustment = 0
671 }
672
673 return {
674 inventory_item_id: reservation.inventory_item_id,
675 location_id: data.location_id ?? reservation.location_id,
676 quantity: adjustment,
677 allow_backorder:
678 data.allow_backorder || reservation.allow_backorder || false,
679 }
680 })
681
682 const inventoryLevels = await this.ensureInventoryLevels(
683 availabilityData,
684 {
685 validateQuantityAtLocation: true,
686 },
687 context
688 )
689
690 const result = await this.reservationItemService_.update(input, context)
691
692 const levelAdjustmentUpdates = inventoryLevels
693 .map((level) => {
694 const adjustment = adjustments
695 .get(level.inventory_item_id)
696 ?.get(level.location_id)
697
698 if (!adjustment) {
699 return
700 }
701
702 return {
703 id: level.id,
704 reserved_quantity: MathBN.add(level.reserved_quantity, adjustment),
705 }
706 })
707 .filter(Boolean)
708
709 await this.inventoryLevelService_.update(levelAdjustmentUpdates, context)
710
711 return result
712 }
713
714 @InjectManager()
715 @EmitEvents()
716 // @ts-expect-error
717 async deleteReservationItems(
718 ids: string | string[],
719 @MedusaContext() context: Context = {}
720 ): Promise<void> {
721 return await this.deleteReservationItems_(ids, context)
722 }
723
724 @InjectTransactionManager()
725 protected async deleteReservationItems_(
726 ids: string | string[],
727 @MedusaContext() context: Context = {}
728 ): Promise<void> {
729 const reservations: InventoryTypes.ReservationItemDTO[] =
730 await this.reservationItemService_.list({ id: ids }, {}, context)
731
732 await super.deleteReservationItems(ids, context)
733
734 await this.adjustInventoryLevelsForReservationsDeletion(
735 reservations,
736 context
737 )
738 }
739
740 @InjectManager()
741 @EmitEvents()
742 // @ts-expect-error
743 async softDeleteReservationItems(
744 ids: string | string[],
745 config?: SoftDeleteReturn<string>,
746 @MedusaContext() context: Context = {}
747 ): Promise<void> {
748 return await this.softDeleteReservationItems_(ids, config, context)
749 }
750
751 @InjectTransactionManager()
752 protected async softDeleteReservationItems_(
753 ids: string | string[],
754 config?: SoftDeleteReturn<string>,
755 @MedusaContext() context: Context = {}
756 ): Promise<void> {
757 const reservations: InventoryTypes.ReservationItemDTO[] =
758 await this.reservationItemService_.list({ id: ids }, {}, context)
759
760 await super.softDeleteReservationItems(ids, config, context)
761
762 await this.adjustInventoryLevelsForReservationsDeletion(
763 reservations,
764 context
765 )
766 }
767
768 @InjectManager()
769 @EmitEvents()
770 // @ts-expect-error
771 async restoreReservationItems(
772 ids: string | string[],
773 config?: RestoreReturn<string>,
774 @MedusaContext() context: Context = {}
775 ): Promise<void> {
776 return await this.restoreReservationItems_(ids, config, context)
777 }
778
779 @InjectTransactionManager()
780 protected async restoreReservationItems_(
781 ids: string | string[],
782 config?: RestoreReturn<string>,
783 @MedusaContext() context: Context = {}
784 ): Promise<void> {
785 await super.restoreReservationItems({ id: ids }, config, context)
786
787 const reservations: InventoryTypes.ReservationItemDTO[] =
788 await super.listReservationItems({ id: ids }, {}, context)
789
790 await this.adjustInventoryLevelsForReservationsRestore(
791 reservations,
792 context
793 )
794 }
795
796 @InjectManager()
797 @EmitEvents()
798 async deleteReservationItemByLocationId(
799 locationId: string | string[],
800 @MedusaContext() context: Context = {}
801 ): Promise<void> {
802 return await this.deleteReservationItemByLocationId_(locationId, context)
803 }
804
805 @InjectTransactionManager()
806 protected async deleteReservationItemByLocationId_(
807 locationId: string | string[],
808 @MedusaContext() context: Context = {}
809 ): Promise<void> {
810 const reservations: InventoryTypes.ReservationItemDTO[] =
811 await this.reservationItemService_.list(
812 { location_id: locationId },
813 {},
814 context
815 )
816
817 await this.reservationItemService_.softDelete(
818 { location_id: locationId },
819 context
820 )
821
822 await this.adjustInventoryLevelsForReservationsDeletion(
823 reservations,
824 context
825 )
826 }
827
828 /**
829 * Deletes reservation items by line item
830 * @param lineItemId - the id of the line item associated with the reservation item
831 * @param context
832 */
833
834 @InjectManager()
835 @EmitEvents()
836 async deleteReservationItemsByLineItem(
837 lineItemId: string | string[],
838 @MedusaContext() context: Context = {}
839 ): Promise<void> {
840 return await this.deleteReservationItemsByLineItem_(lineItemId, context)
841 }
842
843 @InjectTransactionManager()
844 protected async deleteReservationItemsByLineItem_(
845 lineItemId: string | string[],
846 @MedusaContext() context: Context = {}
847 ): Promise<void> {
848 const reservations: InventoryTypes.ReservationItemDTO[] =
849 await this.reservationItemService_.list(
850 { line_item_id: lineItemId },
851 {},
852 context
853 )
854
855 await this.reservationItemService_.softDelete(
856 { line_item_id: lineItemId },
857 context
858 )
859
860 await this.adjustInventoryLevelsForReservationsDeletion(
861 reservations,
862 context
863 )
864 }
865
866 /**
867 * Deletes reservation items by line item
868 * @param lineItemId - the id of the line item associated with the reservation item
869 * @param context
870 */
871
872 @InjectManager()
873 @EmitEvents()
874 async restoreReservationItemsByLineItem(
875 lineItemId: string | string[],
876 @MedusaContext() context: Context = {}
877 ): Promise<void> {
878 return await this.restoreReservationItemsByLineItem_(lineItemId, context)
879 }
880
881 @InjectTransactionManager()
882 protected async restoreReservationItemsByLineItem_(
883 lineItemId: string | string[],
884 @MedusaContext() context: Context = {}
885 ): Promise<void> {
886 await this.reservationItemService_.restore(
887 { line_item_id: lineItemId },
888 context
889 )
890
891 const reservations: InventoryTypes.ReservationItemDTO[] =
892 await this.reservationItemService_.list(
893 { line_item_id: lineItemId },
894 {},
895 context
896 )
897
898 await this.adjustInventoryLevelsForReservationsRestore(
899 reservations,
900 context
901 )
902 }
903
904 /**
905 * Adjusts the inventory level for a given inventory item and location.
906 * @param inventoryItemId - the id of the inventory item
907 * @param locationId - the id of the location
908 * @param adjustment - the number to adjust the inventory by (can be positive or negative)
909 * @param context
910 * @return The updated inventory level
911 * @throws when the inventory level is not found
912 */
913 adjustInventory(
914 inventoryItemId: string,
915 locationId: string,
916 adjustment: BigNumberInput,
917 context: Context
918 ): Promise<InventoryTypes.InventoryLevelDTO>
919
920 adjustInventory(
921 data: {
922 inventoryItemId: string
923 locationId: string
924 adjustment: BigNumberInput
925 }[],
926 context: Context
927 ): Promise<InventoryTypes.InventoryLevelDTO[]>
928
929 @InjectManager()
930 @EmitEvents()
931 async adjustInventory(
932 inventoryItemIdOrData: string | any,
933 locationId?: string | Context,
934 adjustment?: BigNumberInput,
935 @MedusaContext() context: Context = {}
936 ): Promise<
937 InventoryTypes.InventoryLevelDTO | InventoryTypes.InventoryLevelDTO[]
938 > {
939 let all: any = inventoryItemIdOrData
940
941 if (isString(inventoryItemIdOrData)) {
942 all = [
943 {
944 inventoryItemId: inventoryItemIdOrData,
945 locationId,
946 adjustment,
947 },
948 ]
949 }
950
951 const results: InferEntityType<typeof InventoryLevel>[] = []
952
953 for (const data of all) {
954 const result = await this.adjustInventory_(
955 data.inventoryItemId,
956 data.locationId,
957 data.adjustment,
958 context
959 )
960 results.push(result)
961 }
962
963 return await this.baseRepository_.serialize<InventoryTypes.InventoryLevelDTO>(
964 Array.isArray(inventoryItemIdOrData) ? results : results[0]
965 )
966 }
967
968 @InjectTransactionManager()
969 async adjustInventory_(
970 inventoryItemId: string,
971 locationId: string,
972 adjustment: BigNumberInput,
973 @MedusaContext() context: Context = {}
974 ): Promise<InferEntityType<typeof InventoryLevel>> {
975 const [inventoryLevel] = await this.inventoryLevelService_.list(
976 { inventory_item_id: inventoryItemId, location_id: locationId },
977 {},
978 context
979 )
980
981 if (!inventoryLevel) {
982 throw new MedusaError(
983 MedusaError.Types.NOT_FOUND,
984 `Inventory level for item ${inventoryItemId} and location ${locationId} not found`
985 )
986 }
987
988 const result = await this.inventoryLevelService_.update(
989 {
990 id: inventoryLevel.id,
991 stocked_quantity: MathBN.add(
992 inventoryLevel.stocked_quantity,
993 adjustment
994 ),
995 },
996 context
997 )
998
999 return result
1000 }
1001
1002 @InjectManager()
1003 async retrieveInventoryLevelByItemAndLocation(
1004 inventoryItemId: string,
1005 locationId: string,
1006 @MedusaContext() context: Context = {}
1007 ): Promise<InventoryTypes.InventoryLevelDTO> {
1008 const [inventoryLevel] = await this.listInventoryLevels(
1009 { inventory_item_id: inventoryItemId, location_id: locationId },
1010 {},
1011 context
1012 )
1013
1014 if (!inventoryLevel) {
1015 throw new MedusaError(
1016 MedusaError.Types.NOT_FOUND,
1017 `Inventory level for item ${inventoryItemId} and location ${locationId} not found`
1018 )
1019 }
1020
1021 return inventoryLevel
1022 }
1023
1024 /**
1025 * Retrieves the available quantity of a given inventory item in a given location.
1026 * @param inventoryItemId - the id of the inventory item
1027 * @param locationIds - the ids of the locations to check
1028 * @param context
1029 * @return The available quantity
1030 * @throws when the inventory item is not found
1031 */
1032 @InjectManager()
1033 async retrieveAvailableQuantity(
1034 inventoryItemId: string,
1035 locationIds: string[],
1036 @MedusaContext() context: Context = {}
1037 ): Promise<BigNumber> {
1038 if (locationIds.length === 0) {
1039 return new BigNumber(0)
1040 }
1041
1042 await this.inventoryItemService_.retrieve(
1043 inventoryItemId,
1044 {
1045 select: ["id"],
1046 },
1047 context
1048 )
1049
1050 const availableQuantity =
1051 await this.inventoryLevelService_.getAvailableQuantity(
1052 inventoryItemId,
1053 locationIds,
1054 context
1055 )
1056
1057 return availableQuantity
1058 }
1059
1060 /**
1061 * Retrieves the stocked quantity of a given inventory item in a given location.
1062 * @param inventoryItemId - the id of the inventory item
1063 * @param locationIds - the ids of the locations to check
1064 * @param context
1065 * @return The stocked quantity
1066 * @throws when the inventory item is not found
1067 */
1068 @InjectManager()
1069 async retrieveStockedQuantity(
1070 inventoryItemId: string,
1071 locationIds: string[],
1072 @MedusaContext() context: Context = {}
1073 ): Promise<BigNumber> {
1074 if (locationIds.length === 0) {
1075 return new BigNumber(0)
1076 }
1077
1078 // Throws if item does not exist
1079 await this.inventoryItemService_.retrieve(
1080 inventoryItemId,
1081 {
1082 select: ["id"],
1083 },
1084 context
1085 )
1086
1087 const stockedQuantity =
1088 await this.inventoryLevelService_.retrieveStockedQuantity(
1089 inventoryItemId,
1090 locationIds,
1091 context
1092 )
1093
1094 return stockedQuantity
1095 }
1096
1097 /**
1098 * Retrieves the reserved quantity of a given inventory item in a given location.
1099 * @param inventoryItemId - the id of the inventory item
1100 * @param locationIds - the ids of the locations to check
1101 * @param context
1102 * @return The reserved quantity
1103 * @throws when the inventory item is not found
1104 */
1105 @InjectManager()
1106 async retrieveReservedQuantity(
1107 inventoryItemId: string,
1108 locationIds: string[],
1109 @MedusaContext() context: Context = {}
1110 ): Promise<BigNumber> {
1111 // Throws if item does not exist
1112 await this.inventoryItemService_.retrieve(
1113 inventoryItemId,
1114 {
1115 select: ["id"],
1116 },
1117 context
1118 )
1119
1120 if (locationIds.length === 0) {
1121 return new BigNumber(0)
1122 }
1123
1124 const reservedQuantity =
1125 await this.inventoryLevelService_.getReservedQuantity(
1126 inventoryItemId,
1127 locationIds,
1128 context
1129 )
1130
1131 return reservedQuantity
1132 }
1133
1134 /**
1135 * Confirms whether there is sufficient inventory for a given quantity of a given inventory item in a given location.
1136 * @param inventoryItemId - the id of the inventory item
1137 * @param locationIds - the ids of the locations to check
1138 * @param quantity - the quantity to check
1139 * @param context
1140 * @return Whether there is sufficient inventory
1141 */
1142 @InjectManager()
1143 async confirmInventory(
1144 inventoryItemId: string,
1145 locationIds: string[],
1146 quantity: BigNumberInput,
1147 @MedusaContext() context: Context = {}
1148 ): Promise<boolean> {
1149 const availableQuantity = await this.retrieveAvailableQuantity(
1150 inventoryItemId,
1151 locationIds,
1152 context
1153 )
1154 return MathBN.gte(availableQuantity, quantity)
1155 }
1156
1157 private async adjustInventoryLevelsForReservationsDeletion(
1158 reservations: ReservationItemDTO[],
1159 context: Context
1160 ): Promise<void> {
1161 await this.adjustInventoryLevelsForReservations_(
1162 reservations,
1163 true,
1164 context
1165 )
1166 }
1167
1168 private async adjustInventoryLevelsForReservationsRestore(
1169 reservations: ReservationItemDTO[],
1170 context: Context
1171 ): Promise<void> {
1172 await this.adjustInventoryLevelsForReservations_(
1173 reservations,
1174 false,
1175 context
1176 )
1177 }
1178
1179 private async adjustInventoryLevelsForReservations_(
1180 reservations: ReservationItemDTO[],
1181 isDelete: boolean,
1182 context: Context
1183 ): Promise<void> {
1184 const multiplier = isDelete ? -1 : 1
1185 const inventoryLevels = await this.ensureInventoryLevels(
1186 reservations.map((r) => ({
1187 inventory_item_id: r.inventory_item_id,
1188 location_id: r.location_id,
1189 })),
1190 undefined,
1191 context
1192 )
1193
1194 const inventoryLevelAdjustments: Map<
1195 string,
1196 Map<string, number>
1197 > = reservations.reduce((acc, curr) => {
1198 const inventoryLevelMap = acc.get(curr.inventory_item_id) ?? new Map()
1199
1200 const adjustment = inventoryLevelMap.has(curr.location_id)
1201 ? MathBN.add(
1202 inventoryLevelMap.get(curr.location_id),
1203 MathBN.mult(curr.quantity, multiplier)
1204 )
1205 : MathBN.mult(curr.quantity, multiplier)
1206
1207 inventoryLevelMap.set(curr.location_id, adjustment)
1208 acc.set(curr.inventory_item_id, inventoryLevelMap)
1209 return acc
1210 }, new Map())
1211
1212 const levelAdjustmentUpdates = inventoryLevels.map((level) => {
1213 const adjustment = inventoryLevelAdjustments
1214 .get(level.inventory_item_id)
1215 ?.get(level.location_id)
1216
1217 if (!adjustment) {
1218 return
1219 }
1220
1221 return {
1222 id: level.id,
1223 reserved_quantity: MathBN.add(level.reserved_quantity, adjustment),
1224 }
1225 })
1226
1227 await this.inventoryLevelService_.update(levelAdjustmentUpdates, context)
1228 }
1229 }