chore(medusa): Remove intepestive services re instanciation in loop (#2036)

* chore(medusa): Renove intepestive services re instanciation in loop

* test(medusa): Fix missing deps

* fix(medusa): Missing await
This commit is contained in:
Adrien de Peretti
2022-08-11 22:18:11 +02:00
committed by GitHub
parent c31290c911
commit cbe2b7f687
12 changed files with 240 additions and 193 deletions
@@ -1,6 +1,7 @@
import { IdMap, MockManager, MockRepository } from "medusa-test-utils" import { IdMap, MockManager, MockRepository } from "medusa-test-utils"
import OrderService from "../order" import OrderService from "../order"
import { InventoryServiceMock } from "../__mocks__/inventory" import { InventoryServiceMock } from "../__mocks__/inventory"
import { LineItemServiceMock } from "../__mocks__/line-item";
describe("OrderService", () => { describe("OrderService", () => {
const totalsService = { const totalsService = {
@@ -520,6 +521,7 @@ describe("OrderService", () => {
manager: MockManager, manager: MockManager,
orderRepository: orderRepo, orderRepository: orderRepo,
eventBusService, eventBusService,
lineItemService: LineItemServiceMock
}) })
beforeEach(async () => { beforeEach(async () => {
@@ -2,6 +2,7 @@ import { MedusaError } from "medusa-core-utils"
import { IdMap, MockManager, MockRepository } from "medusa-test-utils" import { IdMap, MockManager, MockRepository } from "medusa-test-utils"
import PriceListService from "../price-list" import PriceListService from "../price-list"
import { MoneyAmountRepository } from "../../repositories/money-amount" import { MoneyAmountRepository } from "../../repositories/money-amount"
import { RegionServiceMock } from "../__mocks__/region";
const priceListRepository = MockRepository({ const priceListRepository = MockRepository({
findOne: (q) => { findOne: (q) => {
@@ -129,6 +130,7 @@ describe("PriceListService", () => {
customerGroupService, customerGroupService,
priceListRepository, priceListRepository,
moneyAmountRepository: updateRelatedMoneyAmountRepository, moneyAmountRepository: updateRelatedMoneyAmountRepository,
regionService: RegionServiceMock
}) })
it("update only existing price lists and related money amount", async () => { it("update only existing price lists and related money amount", async () => {
+12 -8
View File
@@ -1736,14 +1736,17 @@ class CartService extends TransactionBaseService<CartService> {
const methods = [newShippingMethod] const methods = [newShippingMethod]
if (shipping_methods?.length) { if (shipping_methods?.length) {
const shippingOptionServiceTx =
this.shippingOptionService_.withTransaction(transactionManager)
for (const shippingMethod of shipping_methods) { for (const shippingMethod of shipping_methods) {
if ( if (
shippingMethod.shipping_option.profile_id === shippingMethod.shipping_option.profile_id ===
newShippingMethod.shipping_option.profile_id newShippingMethod.shipping_option.profile_id
) { ) {
await this.shippingOptionService_ await shippingOptionServiceTx.deleteShippingMethods(
.withTransaction(transactionManager) shippingMethod
.deleteShippingMethods(shippingMethod) )
} else { } else {
methods.push(shippingMethod) methods.push(shippingMethod)
} }
@@ -1751,13 +1754,14 @@ class CartService extends TransactionBaseService<CartService> {
} }
if (cart.items?.length) { if (cart.items?.length) {
const lineItemServiceTx =
this.lineItemService_.withTransaction(transactionManager)
await Promise.all( await Promise.all(
cart.items.map(async (item) => { cart.items.map(async (item) => {
return this.lineItemService_ return lineItemServiceTx.update(item.id, {
.withTransaction(transactionManager) has_shipping: this.validateLineItemShipping_(methods, item),
.update(item.id, { })
has_shipping: this.validateLineItemShipping_(methods, item),
})
}) })
) )
} }
+80 -75
View File
@@ -150,32 +150,29 @@ export default class ClaimService extends TransactionBaseService<
} }
if (shipping_methods) { if (shipping_methods) {
const shippingOptionServiceTx =
this.shippingOptionService_.withTransaction(transactionManager)
for (const m of claim.shipping_methods) { for (const m of claim.shipping_methods) {
await this.shippingOptionService_ await shippingOptionServiceTx.updateShippingMethod(m.id, {
.withTransaction(transactionManager) claim_order_id: null,
.updateShippingMethod(m.id, { })
claim_order_id: null,
})
} }
for (const method of shipping_methods) { for (const method of shipping_methods) {
if (method.id) { if (method.id) {
await this.shippingOptionService_ await shippingOptionServiceTx.updateShippingMethod(method.id, {
.withTransaction(transactionManager) claim_order_id: claim.id,
.updateShippingMethod(method.id, { })
claim_order_id: claim.id,
})
} else { } else {
await this.shippingOptionService_ await shippingOptionServiceTx.createShippingMethod(
.withTransaction(transactionManager) method.option_id as string,
.createShippingMethod( (method as any).data,
method.option_id as string, {
(method as any).data, claim_order_id: claim.id,
{ price: method.price,
claim_order_id: claim.id, }
price: method.price, )
}
)
} }
} }
} }
@@ -186,11 +183,12 @@ export default class ClaimService extends TransactionBaseService<
} }
if (claim_items) { if (claim_items) {
const claimItemServiceTx =
this.claimItemService_.withTransaction(transactionManager)
for (const i of claim_items) { for (const i of claim_items) {
if (i.id) { if (i.id) {
await this.claimItemService_ await claimItemServiceTx.update(i.id, i)
.withTransaction(transactionManager)
.update(i.id, i)
} }
} }
} }
@@ -235,12 +233,13 @@ export default class ClaimService extends TransactionBaseService<
...rest ...rest
} = data } = data
const lineItemServiceTx =
this.lineItemService_.withTransaction(transactionManager)
for (const item of claim_items) { for (const item of claim_items) {
const line = await this.lineItemService_ const line = await lineItemServiceTx.retrieve(item.item_id, {
.withTransaction(transactionManager) relations: ["order", "swap", "claim_order", "tax_lines"],
.retrieve(item.item_id, { })
relations: ["order", "swap", "claim_order", "tax_lines"],
})
if ( if (
line.order?.canceled_at || line.order?.canceled_at ||
@@ -337,24 +336,31 @@ export default class ClaimService extends TransactionBaseService<
let newItems: LineItem[] = [] let newItems: LineItem[] = []
if (isDefined(additional_items)) { if (isDefined(additional_items)) {
const inventoryServiceTx =
this.inventoryService_.withTransaction(transactionManager)
for (const item of additional_items) { for (const item of additional_items) {
await this.inventoryService_ await inventoryServiceTx.confirmInventory(
.withTransaction(transactionManager) item.variant_id,
.confirmInventory(item.variant_id, item.quantity) item.quantity
)
} }
newItems = await Promise.all( newItems = await Promise.all(
additional_items.map((i) => additional_items.map((i) =>
this.lineItemService_ lineItemServiceTx.generate(
.withTransaction(transactionManager) i.variant_id,
.generate(i.variant_id, order.region_id, i.quantity) order.region_id,
i.quantity
)
) )
) )
for (const newItem of newItems) { for (const newItem of newItems) {
await this.inventoryService_ await inventoryServiceTx.adjustInventory(
.withTransaction(transactionManager) newItem.variant_id,
.adjustInventory(newItem.variant_id, -newItem.quantity) -newItem.quantity
)
} }
} }
@@ -378,46 +384,44 @@ export default class ClaimService extends TransactionBaseService<
if (result.additional_items && result.additional_items.length) { if (result.additional_items && result.additional_items.length) {
const calcContext = this.totalsService_.getCalculationContext(order) const calcContext = this.totalsService_.getCalculationContext(order)
const lineItems = await this.lineItemService_ const lineItems = await lineItemServiceTx.list({
.withTransaction(transactionManager) id: result.additional_items.map((i) => i.id),
.list({ })
id: result.additional_items.map((i) => i.id),
})
await this.taxProviderService_ await this.taxProviderService_
.withTransaction(transactionManager) .withTransaction(transactionManager)
.createTaxLines(lineItems, calcContext) .createTaxLines(lineItems, calcContext)
} }
if (shipping_methods) { if (shipping_methods) {
const shippingOptionServiceTx =
this.shippingOptionService_.withTransaction(transactionManager)
for (const method of shipping_methods) { for (const method of shipping_methods) {
if (method.id) { if (method.id) {
await this.shippingOptionService_ await shippingOptionServiceTx.updateShippingMethod(method.id, {
.withTransaction(transactionManager) claim_order_id: result.id,
.updateShippingMethod(method.id, { })
claim_order_id: result.id,
})
} else { } else {
await this.shippingOptionService_ await shippingOptionServiceTx.createShippingMethod(
.withTransaction(transactionManager) method.option_id as string,
.createShippingMethod( (method as any).data,
method.option_id as string, {
(method as any).data, claim_order_id: result.id,
{ price: method.price,
claim_order_id: result.id, }
price: method.price, )
}
)
} }
} }
} }
const claimItemServiceTx =
this.claimItemService_.withTransaction(transactionManager)
for (const ci of claim_items) { for (const ci of claim_items) {
await this.claimItemService_ await claimItemServiceTx.create({
.withTransaction(transactionManager) ...ci,
.create({ claim_order_id: result.id,
...ci, })
claim_order_id: result.id,
})
} }
if (return_shipping) { if (return_shipping) {
@@ -584,14 +588,14 @@ export default class ClaimService extends TransactionBaseService<
) )
const claimOrder = await claimRepo.save(claim) const claimOrder = await claimRepo.save(claim)
const eventBusTx = this.eventBus_.withTransaction(transactionManager)
for (const fulfillment of fulfillments) { for (const fulfillment of fulfillments) {
await this.eventBus_ await eventBusTx.emit(ClaimService.Events.FULFILLMENT_CREATED, {
.withTransaction(transactionManager) id: id,
.emit(ClaimService.Events.FULFILLMENT_CREATED, { fulfillment_id: fulfillment.id,
id: id, no_notification: claim.no_notification,
fulfillment_id: fulfillment.id, })
no_notification: claim.no_notification,
})
} }
return claimOrder return claimOrder
@@ -708,6 +712,9 @@ export default class ClaimService extends TransactionBaseService<
claim.fulfillment_status = ClaimFulfillmentStatus.SHIPPED claim.fulfillment_status = ClaimFulfillmentStatus.SHIPPED
const lineItemServiceTx =
this.lineItemService_.withTransaction(transactionManager)
for (const additionalItem of claim.additional_items) { for (const additionalItem of claim.additional_items) {
const shipped = shipment.items.find( const shipped = shipment.items.find(
(si) => si.item_id === additionalItem.id (si) => si.item_id === additionalItem.id
@@ -715,11 +722,9 @@ export default class ClaimService extends TransactionBaseService<
if (shipped) { if (shipped) {
const shippedQty = const shippedQty =
(additionalItem.shipped_quantity || 0) + shipped.quantity (additionalItem.shipped_quantity || 0) + shipped.quantity
await this.lineItemService_ await lineItemServiceTx.update(additionalItem.id, {
.withTransaction(transactionManager) shipped_quantity: shippedQty,
.update(additionalItem.id, { })
shipped_quantity: shippedQty,
})
if (shippedQty !== additionalItem.quantity) { if (shippedQty !== additionalItem.quantity) {
claim.fulfillment_status = claim.fulfillment_status =
+35 -29
View File
@@ -266,20 +266,22 @@ class DraftOrderService extends TransactionBaseService<DraftOrderService> {
const { shipping_methods, no_notification_order, items, ...rawCart } = const { shipping_methods, no_notification_order, items, ...rawCart } =
data data
const cartServiceTx =
this.cartService_.withTransaction(transactionManager)
if (rawCart.discounts) { if (rawCart.discounts) {
const { discounts } = rawCart const { discounts } = rawCart
rawCart.discounts = [] rawCart.discounts = []
for (const { code } of discounts) { for (const { code } of discounts) {
await this.cartService_ await cartServiceTx.applyDiscount(rawCart as Cart, code)
.withTransaction(transactionManager)
.applyDiscount(rawCart as Cart, code)
} }
} }
const createdCart = await this.cartService_ const createdCart = await cartServiceTx.create({
.withTransaction(transactionManager) type: CartType.DRAFT_ORDER,
.create({ type: CartType.DRAFT_ORDER, ...rawCart }) ...rawCart,
})
const draftOrder = draftOrderRepo.create({ const draftOrder = draftOrderRepo.create({
cart_id: createdCart.id, cart_id: createdCart.id,
@@ -293,22 +295,26 @@ class DraftOrderService extends TransactionBaseService<DraftOrderService> {
id: result.id, id: result.id,
}) })
const lineItemServiceTx =
this.lineItemService_.withTransaction(transactionManager)
for (const item of items) { for (const item of items) {
if (item.variant_id) { if (item.variant_id) {
const line = await this.lineItemService_ const line = await lineItemServiceTx.generate(
.withTransaction(transactionManager) item.variant_id,
.generate(item.variant_id, data.region_id, item.quantity, { data.region_id,
item.quantity,
{
metadata: item?.metadata || {}, metadata: item?.metadata || {},
unit_price: item.unit_price, unit_price: item.unit_price,
cart: createdCart, cart: createdCart,
}) }
)
await this.lineItemService_ await lineItemServiceTx.create({
.withTransaction(transactionManager) ...line,
.create({ cart_id: createdCart.id,
...line, })
cart_id: createdCart.id,
})
} else { } else {
let price let price
if (typeof item.unit_price === `undefined` || item.unit_price < 0) { if (typeof item.unit_price === `undefined` || item.unit_price < 0) {
@@ -318,23 +324,23 @@ class DraftOrderService extends TransactionBaseService<DraftOrderService> {
} }
// custom line items can be added to a draft order // custom line items can be added to a draft order
await this.lineItemService_ await lineItemServiceTx.create({
.withTransaction(transactionManager) cart_id: createdCart.id,
.create({ has_shipping: true,
cart_id: createdCart.id, title: item.title || "Custom item",
has_shipping: true, allow_discounts: false,
title: item.title || "Custom item", unit_price: price,
allow_discounts: false, quantity: item.quantity,
unit_price: price, })
quantity: item.quantity,
})
} }
} }
for (const method of shipping_methods) { for (const method of shipping_methods) {
await this.cartService_ await cartServiceTx.addShippingMethod(
.withTransaction(transactionManager) createdCart.id,
.addShippingMethod(createdCart.id, method.option_id, method.data) method.option_id,
method.data
)
} }
return result return result
+3 -3
View File
@@ -274,12 +274,12 @@ class FulfillmentService extends TransactionBaseService<FulfillmentService> {
fulfillment.canceled_at = new Date() fulfillment.canceled_at = new Date()
const lineItemService = this.lineItemService_.withTransaction(manager) const lineItemServiceTx = this.lineItemService_.withTransaction(manager)
for (const fItem of fulfillment.items) { for (const fItem of fulfillment.items) {
const item = await lineItemService.retrieve(fItem.item_id) const item = await lineItemServiceTx.retrieve(fItem.item_id)
const fulfilledQuantity = item.fulfilled_quantity - fItem.quantity const fulfilledQuantity = item.fulfilled_quantity - fItem.quantity
await lineItemService.update(item.id, { await lineItemServiceTx.update(item.id, {
fulfilled_quantity: fulfilledQuantity, fulfilled_quantity: fulfilledQuantity,
}) })
} }
+36 -29
View File
@@ -479,10 +479,10 @@ class OrderService extends TransactionBaseService<OrderService> {
*/ */
async createFromCart(cartId: string): Promise<Order | never> { async createFromCart(cartId: string): Promise<Order | never> {
return await this.atomicPhase_(async (manager) => { return await this.atomicPhase_(async (manager) => {
const cartService = this.cartService_.withTransaction(manager) const cartServiceTx = this.cartService_.withTransaction(manager)
const inventoryService = this.inventoryService_.withTransaction(manager) const inventoryServiceTx = this.inventoryService_.withTransaction(manager)
const cart = await cartService.retrieve(cartId, { const cart = await cartServiceTx.retrieve(cartId, {
select: ["subtotal", "total"], select: ["subtotal", "total"],
relations: [ relations: [
"region", "region",
@@ -506,7 +506,7 @@ class OrderService extends TransactionBaseService<OrderService> {
for (const item of cart.items) { for (const item of cart.items) {
try { try {
await inventoryService.confirmInventory( await inventoryServiceTx.confirmInventory(
item.variant_id, item.variant_id,
item.quantity item.quantity
) )
@@ -516,7 +516,7 @@ class OrderService extends TransactionBaseService<OrderService> {
.withTransaction(manager) .withTransaction(manager)
.cancelPayment(payment) .cancelPayment(payment)
} }
await cartService.update(cart.id, { payment_authorized_at: null }) await cartServiceTx.update(cart.id, { payment_authorized_at: null })
throw err throw err
} }
} }
@@ -618,13 +618,16 @@ class OrderService extends TransactionBaseService<OrderService> {
.updateShippingMethod(method.id, { order_id: result.id }) .updateShippingMethod(method.id, { order_id: result.id })
} }
const lineItemService = this.lineItemService_.withTransaction(manager) const lineItemServiceTx = this.lineItemService_.withTransaction(manager)
for (const item of cart.items) { for (const item of cart.items) {
await lineItemService.update(item.id, { order_id: result.id }) await lineItemServiceTx.update(item.id, { order_id: result.id })
} }
for (const item of cart.items) { for (const item of cart.items) {
await inventoryService.adjustInventory(item.variant_id, -item.quantity) await inventoryServiceTx.adjustInventory(
item.variant_id,
-item.quantity
)
} }
await this.eventBus_ await this.eventBus_
@@ -634,7 +637,7 @@ class OrderService extends TransactionBaseService<OrderService> {
no_notification: result.no_notification, no_notification: result.no_notification,
}) })
await cartService.update(cart.id, { completed_at: new Date() }) await cartServiceTx.update(cart.id, { completed_at: new Date() })
return result return result
}) })
@@ -697,6 +700,8 @@ class OrderService extends TransactionBaseService<OrderService> {
no_notification: evaluatedNoNotification, no_notification: evaluatedNoNotification,
}) })
const lineItemServiceTx = this.lineItemService_.withTransaction(manager)
order.fulfillment_status = FulfillmentStatus.SHIPPED order.fulfillment_status = FulfillmentStatus.SHIPPED
for (const item of order.items) { for (const item of order.items) {
const shipped = shipmentRes.items.find((si) => si.item_id === item.id) const shipped = shipmentRes.items.find((si) => si.item_id === item.id)
@@ -706,7 +711,7 @@ class OrderService extends TransactionBaseService<OrderService> {
order.fulfillment_status = FulfillmentStatus.PARTIALLY_SHIPPED order.fulfillment_status = FulfillmentStatus.PARTIALLY_SHIPPED
} }
await this.lineItemService_.withTransaction(manager).update(item.id, { await lineItemServiceTx.update(item.id, {
shipped_quantity: shippedQty, shipped_quantity: shippedQty,
}) })
} else { } else {
@@ -839,6 +844,9 @@ class OrderService extends TransactionBaseService<OrderService> {
.withTransaction(manager) .withTransaction(manager)
.createShippingMethod(optionId, data ?? {}, { order, ...config }) .createShippingMethod(optionId, data ?? {}, { order, ...config })
const shippingOptionServiceTx =
this.shippingOptionService_.withTransaction(manager)
const methods = [newMethod] const methods = [newMethod]
if (shipping_methods.length) { if (shipping_methods.length) {
for (const sm of shipping_methods) { for (const sm of shipping_methods) {
@@ -846,9 +854,7 @@ class OrderService extends TransactionBaseService<OrderService> {
sm.shipping_option.profile_id === sm.shipping_option.profile_id ===
newMethod.shipping_option.profile_id newMethod.shipping_option.profile_id
) { ) {
await this.shippingOptionService_ await shippingOptionServiceTx.deleteShippingMethods(sm)
.withTransaction(manager)
.deleteShippingMethods(sm)
} else { } else {
methods.push(sm) methods.push(sm)
} }
@@ -927,9 +933,10 @@ class OrderService extends TransactionBaseService<OrderService> {
order.no_notification = no_notification ?? false order.no_notification = no_notification ?? false
} }
const lineItemServiceTx = this.lineItemService_.withTransaction(manager)
if (update.items) { if (update.items) {
for (const item of items as LineItem[]) { for (const item of items as LineItem[]) {
await this.lineItemService_.withTransaction(manager).create({ await lineItemServiceTx.create({
...item, ...item,
order_id: orderId, order_id: orderId,
}) })
@@ -1004,16 +1011,15 @@ class OrderService extends TransactionBaseService<OrderService> {
throwErrorIf(order.swaps, notCanceled, "swaps") throwErrorIf(order.swaps, notCanceled, "swaps")
throwErrorIf(order.claims, notCanceled, "claims") throwErrorIf(order.claims, notCanceled, "claims")
const inventoryServiceTx = this.inventoryService_.withTransaction(manager)
for (const item of order.items) { for (const item of order.items) {
await this.inventoryService_ await inventoryServiceTx.adjustInventory(item.variant_id, item.quantity)
.withTransaction(manager)
.adjustInventory(item.variant_id, item.quantity)
} }
const paymentProviderServiceTx =
this.paymentProviderService_.withTransaction(manager)
for (const p of order.payments) { for (const p of order.payments) {
await this.paymentProviderService_ await paymentProviderServiceTx.cancelPayment(p)
.withTransaction(manager)
.cancelPayment(p)
} }
order.status = OrderStatus.CANCELED order.status = OrderStatus.CANCELED
@@ -1051,11 +1057,13 @@ class OrderService extends TransactionBaseService<OrderService> {
) )
} }
const paymentProviderServiceTx =
this.paymentProviderService_.withTransaction(manager)
const payments: Payment[] = [] const payments: Payment[] = []
for (const p of order.payments) { for (const p of order.payments) {
if (p.captured_at === null) { if (p.captured_at === null) {
const result = await this.paymentProviderService_ const result = await paymentProviderServiceTx
.withTransaction(manager)
.capturePayment(p) .capturePayment(p)
.catch((err) => { .catch((err) => {
this.eventBus_ this.eventBus_
@@ -1251,14 +1259,13 @@ class OrderService extends TransactionBaseService<OrderService> {
const evaluatedNoNotification = const evaluatedNoNotification =
no_notification !== undefined ? no_notification : order.no_notification no_notification !== undefined ? no_notification : order.no_notification
const eventBusTx = this.eventBus_.withTransaction(manager)
for (const fulfillment of fulfillments) { for (const fulfillment of fulfillments) {
await this.eventBus_ await eventBusTx.emit(OrderService.Events.FULFILLMENT_CREATED, {
.withTransaction(manager) id: orderId,
.emit(OrderService.Events.FULFILLMENT_CREATED, { fulfillment_id: fulfillment.id,
id: orderId, no_notification: evaluatedNoNotification,
fulfillment_id: fulfillment.id, })
no_notification: evaluatedNoNotification,
})
} }
return result return result
+2 -3
View File
@@ -476,11 +476,10 @@ class PriceListService extends TransactionBaseService<PriceListService> {
>(prices: T[]): Promise<T[]> { >(prices: T[]): Promise<T[]> {
const prices_: typeof prices = [] const prices_: typeof prices = []
const regionServiceTx = this.regionService_.withTransaction(this.manager_)
for (const p of prices) { for (const p of prices) {
if (p.region_id) { if (p.region_id) {
const region = await this.regionService_ const region = await regionServiceTx.retrieve(p.region_id)
.withTransaction(this.manager_)
.retrieve(p.region_id)
p.currency_code = region.currency_code p.currency_code = region.currency_code
} }
+7 -3
View File
@@ -658,10 +658,14 @@ class ProductService extends TransactionBaseService<
await productOptionRepo.save(option) await productOptionRepo.save(option)
const productVariantServiceTx =
this.productVariantService_.withTransaction(manager)
for (const variant of product.variants) { for (const variant of product.variants) {
this.productVariantService_ await productVariantServiceTx.addOptionValue(
.withTransaction(manager) variant.id,
.addOptionValue(variant.id, option.id, "Default Value") option.id,
"Default Value"
)
} }
const result = await this.retrieve(productId) const result = await this.retrieve(productId)
+8 -7
View File
@@ -625,22 +625,23 @@ class ReturnService extends BaseService {
const result = await returnRepository.save(updateObj) const result = await returnRepository.save(updateObj)
const lineItemServiceTx = this.lineItemService_.withTransaction(manager)
for (const i of returnObj.items) { for (const i of returnObj.items) {
const lineItem = await this.lineItemService_ const lineItem = await lineItemServiceTx.retrieve(i.item_id)
.withTransaction(manager)
.retrieve(i.item_id)
const returnedQuantity = (lineItem.returned_quantity || 0) + i.quantity const returnedQuantity = (lineItem.returned_quantity || 0) + i.quantity
await this.lineItemService_.withTransaction(manager).update(i.item_id, { await lineItemServiceTx.update(i.item_id, {
returned_quantity: returnedQuantity, returned_quantity: returnedQuantity,
}) })
} }
const inventoryServiceTx = this.inventoryService_.withTransaction(manager)
for (const line of newLines) { for (const line of newLines) {
const orderItem = order.items.find((i) => i.id === line.item_id) const orderItem = order.items.find((i) => i.id === line.item_id)
if (orderItem) { if (orderItem) {
await this.inventoryService_ await inventoryServiceTx.adjustInventory(
.withTransaction(manager) orderItem.variant_id,
.adjustInventory(orderItem.variant_id, line.received_quantity) line.received_quantity
)
} }
} }
@@ -297,20 +297,21 @@ class ShippingProfileService extends TransactionBaseService<ShippingProfileServi
} }
if (products) { if (products) {
const productServiceTx = this.productService_.withTransaction(manager)
for (const pId of products) { for (const pId of products) {
await this.productService_.withTransaction(manager).update(pId, { await productServiceTx.update(pId, {
profile_id: profile.id, profile_id: profile.id,
}) })
} }
} }
if (shipping_options) { if (shipping_options) {
const shippingOptionServiceTx =
this.shippingOptionService_.withTransaction(manager)
for (const oId of shipping_options) { for (const oId of shipping_options) {
await this.shippingOptionService_ await shippingOptionServiceTx.update(oId, {
.withTransaction(manager) profile_id: profile.id,
.update(oId, { })
profile_id: profile.id,
})
} }
} }
+46 -30
View File
@@ -600,24 +600,28 @@ class SwapService extends BaseService {
}, },
}) })
const customShippingOptionServiceTx =
this.customShippingOptionService_.withTransaction(manager)
for (const customShippingOption of customShippingOptions) { for (const customShippingOption of customShippingOptions) {
await this.customShippingOptionService_ await customShippingOptionServiceTx.create({
.withTransaction(manager) cart_id: cart.id,
.create({ shipping_option_id: customShippingOption.option_id,
cart_id: cart.id, price: customShippingOption.price,
shipping_option_id: customShippingOption.option_id, })
price: customShippingOption.price,
})
} }
const lineItemServiceTx = this.lineItemService_.withTransaction(manager)
const lineItemAdjustmentServiceTx =
this.lineItemAdjustmentService_.withTransaction(manager)
for (const item of swap.additional_items) { for (const item of swap.additional_items) {
await this.lineItemService_.withTransaction(manager).update(item.id, { await lineItemServiceTx.update(item.id, {
cart_id: cart.id, cart_id: cart.id,
}) })
// we generate adjustments in case the cart has any discounts that should be applied to the additional items // we generate adjustments in case the cart has any discounts that should be applied to the additional items
await this.lineItemAdjustmentService_ await lineItemAdjustmentServiceTx.createAdjustmentForLineItem(
.withTransaction(manager) cart,
.createAdjustmentForLineItem(cart, item) item
)
} }
// If the swap has a return shipping method the price has to be added to // If the swap has a return shipping method the price has to be added to
@@ -695,20 +699,23 @@ class SwapService extends BaseService {
const items = cart.items const items = cart.items
if (!swap.allow_backorder) { if (!swap.allow_backorder) {
const inventoryServiceTx =
this.inventoryService_.withTransaction(manager)
const paymentProviderServiceTx =
this.paymentProviderService_.withTransaction(manager)
const cartServiceTx = this.cartService_.withTransaction(manager)
for (const item of items) { for (const item of items) {
try { try {
await this.inventoryService_ await inventoryServiceTx.confirmInventory(
.withTransaction(manager) item.variant_id,
.confirmInventory(item.variant_id, item.quantity) item.quantity
)
} catch (err) { } catch (err) {
if (payment) { if (payment) {
await this.paymentProviderService_ await paymentProviderServiceTx.cancelPayment(payment)
.withTransaction(manager)
.cancelPayment(payment)
} }
await this.cartService_ await cartServiceTx.update(cart.id, { payment_authorized_at: null })
.withTransaction(manager)
.update(cart.id, { payment_authorized_at: null })
throw err throw err
} }
} }
@@ -743,10 +750,14 @@ class SwapService extends BaseService {
order_id: swap.order_id, order_id: swap.order_id,
}) })
const inventoryServiceTx =
this.inventoryService_.withTransaction(manager)
for (const item of items) { for (const item of items) {
await this.inventoryService_ await inventoryServiceTx.adjustInventory(
.withTransaction(manager) item.variant_id,
.adjustInventory(item.variant_id, -item.quantity) -item.quantity
)
} }
} }
@@ -760,12 +771,13 @@ class SwapService extends BaseService {
const swapRepo = manager.getCustomRepository(this.swapRepository_) const swapRepo = manager.getCustomRepository(this.swapRepository_)
const result = await swapRepo.save(swap) const result = await swapRepo.save(swap)
const shippingOptionServiceTx =
this.shippingOptionService_.withTransaction(manager)
for (const method of cart.shipping_methods) { for (const method of cart.shipping_methods) {
await this.shippingOptionService_ await shippingOptionServiceTx.updateShippingMethod(method.id, {
.withTransaction(manager) swap_id: result.id,
.updateShippingMethod(method.id, { })
swap_id: result.id,
})
} }
this.eventBus_ this.eventBus_
@@ -936,6 +948,8 @@ class SwapService extends BaseService {
swap.fulfillment_status = "fulfilled" swap.fulfillment_status = "fulfilled"
const lineItemServiceTx = this.lineItemService_.withTransaction(manager)
// Update all line items to reflect fulfillment // Update all line items to reflect fulfillment
for (const item of swap.additional_items) { for (const item of swap.additional_items) {
const fulfillmentItem = successfullyFulfilled.find( const fulfillmentItem = successfullyFulfilled.find(
@@ -947,7 +961,7 @@ class SwapService extends BaseService {
(item.fulfilled_quantity || 0) + fulfillmentItem.quantity (item.fulfilled_quantity || 0) + fulfillmentItem.quantity
// Update the fulfilled quantity // Update the fulfilled quantity
await this.lineItemService_.withTransaction(manager).update(item.id, { await lineItemServiceTx.update(item.id, {
fulfilled_quantity: fulfilledQuantity, fulfilled_quantity: fulfilledQuantity,
}) })
@@ -1051,12 +1065,14 @@ class SwapService extends BaseService {
swap.fulfillment_status = "shipped" swap.fulfillment_status = "shipped"
const lineItemServiceTx = this.lineItemService_.withTransaction(manager)
// Go through all the additional items in the swap // Go through all the additional items in the swap
for (const i of swap.additional_items) { for (const i of swap.additional_items) {
const shipped = shipment.items.find((si) => si.item_id === i.id) const shipped = shipment.items.find((si) => si.item_id === i.id)
if (shipped) { if (shipped) {
const shippedQty = (i.shipped_quantity || 0) + shipped.quantity const shippedQty = (i.shipped_quantity || 0) + shipped.quantity
await this.lineItemService_.withTransaction(manager).update(i.id, { await lineItemServiceTx.update(i.id, {
shipped_quantity: shippedQty, shipped_quantity: shippedQty,
}) })