fix(medusa): Include items.variant relation in order calculation (#2869)

**What**

When an order require to decorate the totals, the variant relation should be added

FIXES CORE-930
This commit is contained in:
Adrien de Peretti authored and GitHub committed 2022-12-22 09:32:49 +00:00
1 parent b700c6ba5b
commit e27b1940c7
5 files changed
+173 -339

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
"@medusajs/medusa": patch
---
fix: Order with totals should include the variant relation to the items
@@ -28,6 +28,7 @@ const {
simpleOrderFactory, simpleOrderFactory,
simplePaymentFactory, simplePaymentFactory,
simpleProductFactory, simpleProductFactory,
simpleLineItemFactory,
} = require("../../../factories") } = require("../../../factories")
const adminReqConfig = { const adminReqConfig = {
@@ -70,11 +71,7 @@ describe("/admin/orders", () => {
const api = useApi() const api = useApi()
const response = await api const response = await api
.get("/admin/orders", { .get("/admin/orders", adminReqConfig)
headers: {
Authorization: "Bearer test_token",
},
})
.catch((err) => { .catch((err) => {
console.log(err) console.log(err)
}) })
@@ -110,11 +107,7 @@ describe("/admin/orders", () => {
country_code: "us", country_code: "us",
}, },
}, },
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
.catch((err) => { .catch((err) => {
console.log(err.response.data) console.log(err.response.data)
@@ -225,15 +218,7 @@ describe("/admin/orders", () => {
expect(initialInventoryRes.data.variant.inventory_quantity).toEqual(1) expect(initialInventoryRes.data.variant.inventory_quantity).toEqual(1)
const response = await api const response = await api
.post( .post(`/admin/orders/test-order-not-payed/cancel`, {}, adminReqConfig)
`/admin/orders/test-order-not-payed/cancel`,
{},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
.catch((err) => { .catch((err) => {
console.log(err) console.log(err)
}) })
@@ -259,15 +244,7 @@ describe("/admin/orders", () => {
expect(initialInventoryRes.data.variant.inventory_quantity).toEqual(1) expect(initialInventoryRes.data.variant.inventory_quantity).toEqual(1)
const response = await api const response = await api
.post( .post(`/admin/orders/test-order-not-payed/cancel`, {}, adminReqConfig)
`/admin/orders/test-order-not-payed/cancel`,
{},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
.catch((err) => { .catch((err) => {
console.log(err) console.log(err)
}) })
@@ -305,11 +282,7 @@ describe("/admin/orders", () => {
], ],
additional_items: [{ variant_id: "test-variant", quantity: 1 }], additional_items: [{ variant_id: "test-variant", quantity: 1 }],
}, },
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
expect(swapOnSwap.status).toEqual(200) expect(swapOnSwap.status).toEqual(200)
@@ -351,19 +324,11 @@ describe("/admin/orders", () => {
}, },
], ],
}, },
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
expect(response.status).toEqual(200) expect(response.status).toEqual(200)
const variant = await api.get("/admin/products", { const variant = await api.get("/admin/products", adminReqConfig)
headers: {
authorization: "Bearer test_token",
},
})
// find test variant and verify that its inventory quantity has changed // find test variant and verify that its inventory quantity has changed
const toTest = variant.data.products[0].variants.find( const toTest = variant.data.products[0].variants.find(
@@ -430,11 +395,7 @@ describe("/admin/orders", () => {
}, },
], ],
}, },
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
.catch((err) => console.log(err)) .catch((err) => console.log(err))
expect(response.status).toEqual(200) expect(response.status).toEqual(200)
@@ -464,11 +425,7 @@ describe("/admin/orders", () => {
}, },
], ],
}, },
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
.catch((err) => { .catch((err) => {
console.log(err) console.log(err)
@@ -508,11 +465,7 @@ describe("/admin/orders", () => {
}, },
], ],
}, },
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
expect(response.status).toEqual(200) expect(response.status).toEqual(200)
@@ -576,11 +529,7 @@ describe("/admin/orders", () => {
], ],
return_shipping: { option_id: "test-return-option", price: 0 }, return_shipping: { option_id: "test-return-option", price: 0 },
}, },
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
expect(response.status).toEqual(200) expect(response.status).toEqual(200)
@@ -642,11 +591,7 @@ describe("/admin/orders", () => {
}, },
], ],
}, },
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
expect(response.status).toEqual(200) expect(response.status).toEqual(200)
@@ -660,11 +605,7 @@ describe("/admin/orders", () => {
}, },
], ],
}, },
{ adminReqConfig
headers: {
authorization: "bearer test_token",
},
}
) )
expect(status).toEqual(200) expect(status).toEqual(200)
@@ -701,11 +642,7 @@ describe("/admin/orders", () => {
}, },
], ],
}, },
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
expect(response.status).toEqual(200) expect(response.status).toEqual(200)
@@ -728,11 +665,7 @@ describe("/admin/orders", () => {
], ],
})), })),
}, },
{ adminReqConfig
headers: {
authorization: "bearer test_token",
},
}
) )
expect(status).toEqual(200) expect(status).toEqual(200)
@@ -788,11 +721,7 @@ describe("/admin/orders", () => {
}, },
], ],
}, },
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
expect(response.status).toEqual(200) expect(response.status).toEqual(200)
@@ -812,11 +741,7 @@ describe("/admin/orders", () => {
], ],
})), })),
}, },
{ adminReqConfig
headers: {
authorization: "bearer test_token",
},
}
) )
expect(status).toEqual(200) expect(status).toEqual(200)
@@ -871,11 +796,7 @@ describe("/admin/orders", () => {
}, },
], ],
}, },
{ adminReqConfig
headers: {
Authorization: "Bearer test_token",
},
}
) )
.catch((err) => { .catch((err) => {
console.log(err) console.log(err)
@@ -885,11 +806,7 @@ describe("/admin/orders", () => {
const fulRes = await api.post( const fulRes = await api.post(
`/admin/orders/test-order/claims/${cid}/fulfillments`, `/admin/orders/test-order/claims/${cid}/fulfillments`,
{}, {},
{ adminReqConfig
headers: {
Authorization: "Bearer test_token",
},
}
) )
expect(fulRes.status).toEqual(200) expect(fulRes.status).toEqual(200)
expect(fulRes.data.order.claims).toHaveLength(1) expect(fulRes.data.order.claims).toHaveLength(1)
@@ -951,11 +868,7 @@ describe("/admin/orders", () => {
}, },
], ],
}, },
{ adminReqConfig
headers: {
Authorization: "Bearer test_token",
},
}
) )
.catch((err) => { .catch((err) => {
console.log(err) console.log(err)
@@ -965,11 +878,7 @@ describe("/admin/orders", () => {
const fulRes = await api.post( const fulRes = await api.post(
`/admin/orders/test-order/claims/${cid}/fulfillments`, `/admin/orders/test-order/claims/${cid}/fulfillments`,
{}, {},
{ adminReqConfig
headers: {
Authorization: "Bearer test_token",
},
}
) )
const claimItemIdToClaim = const claimItemIdToClaim =
@@ -1001,11 +910,7 @@ describe("/admin/orders", () => {
}, },
], ],
}, },
{ adminReqConfig
headers: {
Authorization: "Bearer test_token",
},
}
) )
.catch((err) => { .catch((err) => {
console.log(err) console.log(err)
@@ -1038,11 +943,7 @@ describe("/admin/orders", () => {
], ],
additional_items: [{ variant_id: "test-variant-2", quantity: 1 }], additional_items: [{ variant_id: "test-variant-2", quantity: 1 }],
}, },
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
.catch((e) => console.log(e)) .catch((e) => console.log(e))
@@ -1065,11 +966,7 @@ describe("/admin/orders", () => {
.post( .post(
`/admin/orders/test-order/swaps/${sid}/fulfillments`, `/admin/orders/test-order/swaps/${sid}/fulfillments`,
{}, {},
{ adminReqConfig
headers: {
Authorization: "Bearer test_token",
},
}
) )
.catch((e) => console.log(e)) .catch((e) => console.log(e))
@@ -1080,11 +977,7 @@ describe("/admin/orders", () => {
{ {
fulfillment_id: fulRes.data.order.swaps[0].fulfillments[0].id, fulfillment_id: fulRes.data.order.swaps[0].fulfillments[0].id,
}, },
{ adminReqConfig
headers: {
Authorization: "Bearer test_token",
},
}
) )
.catch((e) => console.log(e)) .catch((e) => console.log(e))
@@ -1113,11 +1006,7 @@ describe("/admin/orders", () => {
}, },
], ],
}, },
{ adminReqConfig
headers: {
Authorization: "Bearer test_token",
},
}
) )
.catch((err) => { .catch((err) => {
console.log(err) console.log(err)
@@ -1206,11 +1095,7 @@ describe("/admin/orders", () => {
}, },
], ],
}, },
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
} catch (e) { } catch (e) {
expect(e.response.status).toEqual(400) expect(e.response.status).toEqual(400)
@@ -1257,11 +1142,7 @@ describe("/admin/orders", () => {
}, },
], ],
}, },
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
.catch((err) => { .catch((err) => {
console.log(err) console.log(err)
@@ -1306,11 +1187,7 @@ describe("/admin/orders", () => {
}, },
], ],
}, },
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
expect(response.status).toEqual(200) expect(response.status).toEqual(200)
@@ -1342,11 +1219,7 @@ describe("/admin/orders", () => {
], ],
receive_now: true, receive_now: true,
}, },
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
// Find variant that should have its inventory_quantity updated // Find variant that should have its inventory_quantity updated
@@ -1377,11 +1250,7 @@ describe("/admin/orders", () => {
], ],
receive_now: true, receive_now: true,
}, },
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
// Find variant that should have its inventory_quantity updated // Find variant that should have its inventory_quantity updated
@@ -1410,11 +1279,7 @@ describe("/admin/orders", () => {
it("lists all orders", async () => { it("lists all orders", async () => {
const api = useApi() const api = useApi()
const response = await api.get("/admin/orders?fields=id", { const response = await api.get("/admin/orders?fields=id", adminReqConfig)
headers: {
authorization: "Bearer test_token",
},
})
expect(response.status).toEqual(200) expect(response.status).toEqual(200)
expect(response.data.orders).toHaveLength(6) expect(response.data.orders).toHaveLength(6)
@@ -1450,11 +1315,7 @@ describe("/admin/orders", () => {
const response = await api const response = await api
.get( .get(
"/admin/orders?fulfillment_status[]=fulfilled&payment_status[]=captured", "/admin/orders?fulfillment_status[]=fulfilled&payment_status[]=captured",
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
.catch((err) => console.log(err)) .catch((err) => console.log(err))
@@ -1477,11 +1338,7 @@ describe("/admin/orders", () => {
const api = useApi() const api = useApi()
await api await api
.get("/admin/orders?status[]=test", { .get("/admin/orders?status[]=test", adminReqConfig)
headers: {
authorization: "Bearer test_token",
},
})
.catch((err) => { .catch((err) => {
expect(err.response.status).toEqual(400) expect(err.response.status).toEqual(400)
expect(err.response.data.type).toEqual("invalid_data") expect(err.response.data.type).toEqual("invalid_data")
@@ -1496,11 +1353,7 @@ describe("/admin/orders", () => {
const response = await api.get( const response = await api.get(
"/admin/orders?fields=id,email&q=test@email", "/admin/orders?fields=id,email&q=test@email",
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
expect(response.status).toEqual(200) expect(response.status).toEqual(200)
@@ -1519,11 +1372,7 @@ describe("/admin/orders", () => {
it("list all orders with matching shipping_address first name", async () => { it("list all orders with matching shipping_address first name", async () => {
const api = useApi() const api = useApi()
const response = await api.get("/admin/orders?q=lebron", { const response = await api.get("/admin/orders?q=lebron", adminReqConfig)
headers: {
authorization: "Bearer test_token",
},
})
expect(response.status).toEqual(200) expect(response.status).toEqual(200)
expect(response.data.count).toEqual(2) expect(response.data.count).toEqual(2)
@@ -1546,11 +1395,7 @@ describe("/admin/orders", () => {
const response = await api.get( const response = await api.get(
"/admin/orders?fields=id&created_at[gt]=01-26-1990", "/admin/orders?fields=id&created_at[gt]=01-26-1990",
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
expect(response.status).toEqual(200) expect(response.status).toEqual(200)
@@ -1585,11 +1430,7 @@ describe("/admin/orders", () => {
const response = await api.get( const response = await api.get(
"/admin/orders?fields=id&created_at[gt]=01-26-2000", "/admin/orders?fields=id&created_at[gt]=01-26-2000",
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
expect(response.status).toEqual(200) expect(response.status).toEqual(200)
@@ -1601,11 +1442,7 @@ describe("/admin/orders", () => {
const response = await api.get( const response = await api.get(
"/admin/orders?fields=id&created_at[lt]=01-26-2000", "/admin/orders?fields=id&created_at[lt]=01-26-2000",
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
expect(response.status).toEqual(200) expect(response.status).toEqual(200)
@@ -1640,11 +1477,7 @@ describe("/admin/orders", () => {
const response = await api.get( const response = await api.get(
"/admin/orders?fields=id&created_at[lt]=01-26-1990", "/admin/orders?fields=id&created_at[lt]=01-26-1990",
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
expect(response.status).toEqual(200) expect(response.status).toEqual(200)
@@ -1656,11 +1489,7 @@ describe("/admin/orders", () => {
const response = await api.get( const response = await api.get(
"/admin/orders?fields=id&created_at[gt]=633351600", "/admin/orders?fields=id&created_at[gt]=633351600",
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
expect(response.status).toEqual(200) expect(response.status).toEqual(200)
@@ -1778,11 +1607,7 @@ describe("/admin/orders", () => {
price: 400, price: 400,
}, },
}, },
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
expect(response.status).toEqual(200) expect(response.status).toEqual(200)
}) })
@@ -1803,20 +1628,15 @@ describe("/admin/orders", () => {
], ],
additional_items: [{ variant_id: "test-variant-2", quantity: 1 }], additional_items: [{ variant_id: "test-variant-2", quantity: 1 }],
}, },
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
const swapCartId = response.data.order.swaps[0].cart_id const swapCartId = response.data.order.swaps[0].cart_id
const swapCartRes = await api.get(`/store/carts/${swapCartId}`, { const swapCartRes = await api.get(
headers: { `/store/carts/${swapCartId}`,
authorization: "Bearer test_token", adminReqConfig
}, )
})
const cart = swapCartRes.data.cart const cart = swapCartRes.data.cart
expect(response.status).toEqual(200) expect(response.status).toEqual(200)
@@ -1861,11 +1681,7 @@ describe("/admin/orders", () => {
], ],
additional_items: [{ variant_id: "test-variant", quantity: 1 }], additional_items: [{ variant_id: "test-variant", quantity: 1 }],
}, },
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
const swapCartId = createSwapRes.data.order.swaps[0].cart_id const swapCartId = createSwapRes.data.order.swaps[0].cart_id
@@ -1876,11 +1692,7 @@ describe("/admin/orders", () => {
variant_id: "test-variant-2", variant_id: "test-variant-2",
quantity: 1, quantity: 1,
}, },
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
const cart = response.data.cart const cart = response.data.cart
@@ -1915,11 +1727,7 @@ describe("/admin/orders", () => {
additional_items: [{ variant_id: "test-variant-2", quantity: 1 }], additional_items: [{ variant_id: "test-variant-2", quantity: 1 }],
custom_shipping_options: [{ option_id: "test-option", price: 0 }], custom_shipping_options: [{ option_id: "test-option", price: 0 }],
}, },
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
const swap = response.data.order.swaps[0] const swap = response.data.order.swaps[0]
@@ -1955,11 +1763,7 @@ describe("/admin/orders", () => {
], ],
receive_now: true, receive_now: true,
}, },
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
expect(returnedOrderFirst.status).toEqual(200) expect(returnedOrderFirst.status).toEqual(200)
@@ -1975,11 +1779,7 @@ describe("/admin/orders", () => {
], ],
receive_now: true, receive_now: true,
}, },
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
// find item to test returned quantity for // find item to test returned quantity for
@@ -2005,11 +1805,7 @@ describe("/admin/orders", () => {
], ],
additional_items: [{ variant_id: "test-variant-2", quantity: 1 }], additional_items: [{ variant_id: "test-variant-2", quantity: 1 }],
}, },
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
expect(createdSwapOrder.status).toEqual(200) expect(createdSwapOrder.status).toEqual(200)
@@ -2026,11 +1822,7 @@ describe("/admin/orders", () => {
}, },
], ],
}, },
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
expect(receivedSwap.status).toEqual(200) expect(receivedSwap.status).toEqual(200)
@@ -2051,11 +1843,7 @@ describe("/admin/orders", () => {
], ],
additional_items: [{ variant_id: "test-variant", quantity: 1 }], additional_items: [{ variant_id: "test-variant", quantity: 1 }],
}, },
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
expect(swapOnSwap.status).toEqual(200) expect(swapOnSwap.status).toEqual(200)
@@ -2074,11 +1862,7 @@ describe("/admin/orders", () => {
}, },
], ],
}, },
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
expect(received.status).toEqual(200) expect(received.status).toEqual(200)
@@ -2098,11 +1882,7 @@ describe("/admin/orders", () => {
], ],
return_shipping: { option_id: "test-return-option", price: 0 }, return_shipping: { option_id: "test-return-option", price: 0 },
}, },
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
expect(response.status).toEqual(200) expect(response.status).toEqual(200)
@@ -2145,11 +1925,7 @@ describe("/admin/orders", () => {
}, },
], ],
}, },
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
expect(returnOnSwap.status).toEqual(200) expect(returnOnSwap.status).toEqual(200)
@@ -2168,24 +1944,12 @@ describe("/admin/orders", () => {
}, },
], ],
}, },
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
expect(returnOnOrder.status).toEqual(200) expect(returnOnOrder.status).toEqual(200)
await api.post( await api.post("/admin/orders/test-order/capture", {}, adminReqConfig)
"/admin/orders/test-order/capture",
{},
{
headers: {
authorization: "Bearer test_token",
},
}
)
const returnId = returnOnOrder.data.order.returns[0].id const returnId = returnOnOrder.data.order.returns[0].id
@@ -2199,11 +1963,7 @@ describe("/admin/orders", () => {
}, },
], ],
}, },
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
expect(received.status).toEqual(200) expect(received.status).toEqual(200)
@@ -2261,6 +2021,8 @@ describe("/admin/orders", () => {
}) })
describe("GET /admin/orders/:id", () => { describe("GET /admin/orders/:id", () => {
const testOrderId = "test-order"
beforeEach(async () => { beforeEach(async () => {
await adminSeeder(dbConnection) await adminSeeder(dbConnection)
await orderSeeder(dbConnection) await orderSeeder(dbConnection)
@@ -2275,12 +2037,8 @@ describe("/admin/orders", () => {
const api = useApi() const api = useApi()
const order = await api.get( const order = await api.get(
"/admin/orders/test-order?fields=id&expand=region", `/admin/orders/${testOrderId}?fields=id&expand=region`,
{ adminReqConfig
headers: {
authorization: "Bearer test_token",
},
}
) )
expect(order.status).toEqual(200) expect(order.status).toEqual(200)
@@ -2294,11 +2052,10 @@ describe("/admin/orders", () => {
it("retrieves an order should include the items totals", async () => { it("retrieves an order should include the items totals", async () => {
const api = useApi() const api = useApi()
const order = await api.get("/admin/orders/test-order", { const order = await api.get(
headers: { `/admin/orders/${testOrderId}`,
authorization: "Bearer test_token", adminReqConfig
}, )
})
expect(order.status).toEqual(200) expect(order.status).toEqual(200)
expect(order.data.order).toEqual( expect(order.data.order).toEqual(
@@ -2313,6 +2070,52 @@ describe("/admin/orders", () => {
}) })
}) })
it("retrieves an order should include deleted items variants", async () => {
const api = useApi()
const variantTitle = "test variant"
const product = await simpleProductFactory(dbConnection, {
variants: [
{
title: variantTitle,
},
],
})
const lineItem = await simpleLineItemFactory(dbConnection, {
order_id: testOrderId,
variant_id: product.variants[0].id,
})
await dbConnection.manager.query(
`UPDATE product_variant
set deleted_at = NOW()
WHERE id = '${product.variants[0].id}';`
)
const order = await api.get(
`/admin/orders/${testOrderId}`,
adminReqConfig
)
expect(order.status).toEqual(200)
expect(order.data.order).toEqual(
expect.objectContaining({
id: "test-order",
items: expect.arrayContaining([
expect.objectContaining({
id: lineItem.id,
variant: expect.objectContaining({
id: product.variants[0].id,
deleted_at: expect.any(String),
}),
}),
]),
})
)
})
it("retrieves an order should include a deleted region", async () => { it("retrieves an order should include a deleted region", async () => {
const api = useApi() const api = useApi()
@@ -2322,11 +2125,10 @@ describe("/admin/orders", () => {
WHERE id = 'test-region';` WHERE id = 'test-region';`
) )
const order = await api.get("/admin/orders/test-order", { const order = await api.get(
headers: { `/admin/orders/${testOrderId}`,
authorization: "Bearer test_token", adminReqConfig
}, )
})
expect(order.status).toEqual(200) expect(order.status).toEqual(200)
expect(order.data.order).toEqual( expect(order.data.order).toEqual(
+6 -1
View File
@@ -2,6 +2,9 @@ import { flatten, groupBy, map, merge } from "lodash"
import { EntityRepository, FindManyOptions, Repository } from "typeorm" import { EntityRepository, FindManyOptions, Repository } from "typeorm"
import { Order } from "../models" import { Order } from "../models"
const ITEMS_REL_NAME = "items"
const REGION_REL_NAME = "region"
@EntityRepository(Order) @EntityRepository(Order)
export class OrderRepository extends Repository<Order> { export class OrderRepository extends Repository<Order> {
public async findWithRelations( public async findWithRelations(
@@ -23,10 +26,12 @@ export class OrderRepository extends Repository<Order> {
const entitiesIdsWithRelations = await Promise.all( const entitiesIdsWithRelations = await Promise.all(
Object.entries(groupedRelations).map(async ([topLevel, rels]) => { Object.entries(groupedRelations).map(async ([topLevel, rels]) => {
// If top level is region or items then get deleted region as well
return this.findByIds(entitiesIds, { return this.findByIds(entitiesIds, {
select: ["id"], select: ["id"],
relations: rels, relations: rels,
withDeleted: topLevel === "region", withDeleted:
topLevel === ITEMS_REL_NAME || topLevel === REGION_REL_NAME,
}) })
}) })
).then(flatten) ).then(flatten)
+24 -12
View File
@@ -71,6 +71,7 @@ export default class NewTotalsService extends TransactionBaseService {
featureFlagRouter, featureFlagRouter,
taxCalculationStrategy, taxCalculationStrategy,
}: InjectedDependencies) { }: InjectedDependencies) {
// eslint-disable-next-line prefer-rest-params
super(arguments[0]) super(arguments[0])
this.manager_ = manager this.manager_ = manager
@@ -490,23 +491,34 @@ export default class NewTotalsService extends TransactionBaseService {
} }
// If a gift card is not taxable, the tax_rate for the giftcard will be null // If a gift card is not taxable, the tax_rate for the giftcard will be null
const { totalGiftCardBalance, totalTaxFromGiftCards } = giftCards.reduce((acc, giftCard) => { const { totalGiftCardBalance, totalTaxFromGiftCards } = giftCards.reduce(
let taxableAmount = 0 (acc, giftCard) => {
let taxableAmount = 0
acc.totalGiftCardBalance += giftCard.balance acc.totalGiftCardBalance += giftCard.balance
taxableAmount = Math.min(acc.giftCardableBalance, giftCard.balance) taxableAmount = Math.min(acc.giftCardableBalance, giftCard.balance)
// skip tax, if the taxable amount is not a positive number or tax rate is not set // skip tax, if the taxable amount is not a positive number or tax rate is not set
if (taxableAmount <= 0 || !giftCard.tax_rate) return acc if (taxableAmount <= 0 || !giftCard.tax_rate) {
return acc
}
let taxAmountFromGiftCard = Math.round(taxableAmount * (giftCard.tax_rate / 100)) const taxAmountFromGiftCard = Math.round(
taxableAmount * (giftCard.tax_rate / 100)
)
acc.totalTaxFromGiftCards += taxAmountFromGiftCard acc.totalTaxFromGiftCards += taxAmountFromGiftCard
// Update the balance, pass it over to the next gift card (if any) for calculating tax on balance. // Update the balance, pass it over to the next gift card (if any) for calculating tax on balance.
acc.giftCardableBalance -= taxableAmount acc.giftCardableBalance -= taxableAmount
return acc return acc
}, { totalGiftCardBalance: 0, totalTaxFromGiftCards: 0, giftCardableBalance: giftCardableAmount }) },
{
totalGiftCardBalance: 0,
totalTaxFromGiftCards: 0,
giftCardableBalance: giftCardableAmount,
}
)
result.tax_total = Math.round(totalTaxFromGiftCards) result.tax_total = Math.round(totalTaxFromGiftCards)
result.total = Math.min(giftCardableAmount, totalGiftCardBalance) result.total = Math.min(giftCardableAmount, totalGiftCardBalance)
+18 -8
View File
@@ -9,6 +9,7 @@ import {
Fulfillment, Fulfillment,
FulfillmentItem, FulfillmentItem,
FulfillmentStatus, FulfillmentStatus,
GiftCard,
LineItem, LineItem,
Order, Order,
OrderStatus, OrderStatus,
@@ -17,7 +18,6 @@ import {
Return, Return,
Swap, Swap,
TrackingLink, TrackingLink,
GiftCard,
} from "../models" } from "../models"
import { AddressRepository } from "../repositories/address" import { AddressRepository } from "../repositories/address"
import { OrderRepository } from "../repositories/order" import { OrderRepository } from "../repositories/order"
@@ -674,7 +674,10 @@ class OrderService extends TransactionBaseService {
const giftCardService = this.giftCardService_.withTransaction(manager) const giftCardService = this.giftCardService_.withTransaction(manager)
for (const giftCard of cart.gift_cards) { for (const giftCard of cart.gift_cards) {
const newGiftCardBalance = Math.max(0, giftCard.balance - giftCardableAmountBalance) const newGiftCardBalance = Math.max(
0,
giftCard.balance - giftCardableAmountBalance
)
const giftCardBalanceUsed = giftCard.balance - newGiftCardBalance const giftCardBalanceUsed = giftCard.balance - newGiftCardBalance
await giftCardService.update(giftCard.id, { await giftCardService.update(giftCard.id, {
@@ -687,10 +690,11 @@ class OrderService extends TransactionBaseService {
order_id: order.id, order_id: order.id,
amount: giftCardBalanceUsed, amount: giftCardBalanceUsed,
is_taxable: !!giftCard.tax_rate, is_taxable: !!giftCard.tax_rate,
tax_rate: giftCard.tax_rate tax_rate: giftCard.tax_rate,
}) })
giftCardableAmountBalance = giftCardableAmountBalance - giftCardBalanceUsed giftCardableAmountBalance =
giftCardableAmountBalance - giftCardBalanceUsed
} }
const shippingOptionServiceTx = const shippingOptionServiceTx =
@@ -709,7 +713,9 @@ class OrderService extends TransactionBaseService {
] ]
if (lineItem.is_giftcard) { if (lineItem.is_giftcard) {
lineItemPromises.push(this.createGiftCardsFromLineItem_(order, lineItem, manager)) lineItemPromises.push(
this.createGiftCardsFromLineItem_(order, lineItem, manager)
)
} }
return lineItemPromises return lineItemPromises
@@ -748,7 +754,9 @@ class OrderService extends TransactionBaseService {
// LineItem type doesn't promise either the subtotal or quantity. Adding a check here provides // LineItem type doesn't promise either the subtotal or quantity. Adding a check here provides
// additional type safety/strictness // additional type safety/strictness
if (!lineItem.subtotal || !lineItem.quantity) return createGiftCardPromises if (!lineItem.subtotal || !lineItem.quantity) {
return createGiftCardPromises
}
// Subtotal is the pure value of the product/variant excluding tax, discounts, etc. // Subtotal is the pure value of the product/variant excluding tax, discounts, etc.
// We divide here by quantity to get the value of the product/variant as a lineItem // We divide here by quantity to get the value of the product/variant as a lineItem
@@ -758,7 +766,8 @@ class OrderService extends TransactionBaseService {
// On utilizing the gift card, the same set of taxRate will apply to gift card // On utilizing the gift card, the same set of taxRate will apply to gift card
// We calculate the summation of all taxes and add that as a snapshot in the giftcard.tax_rate column // We calculate the summation of all taxes and add that as a snapshot in the giftcard.tax_rate column
const giftCardTaxRate = lineItem.tax_lines.reduce( const giftCardTaxRate = lineItem.tax_lines.reduce(
(sum, taxLine) => sum + taxLine.rate, 0 (sum, taxLine) => sum + taxLine.rate,
0
) )
const giftCardTxnService = this.giftCardService_.withTransaction(manager) const giftCardTxnService = this.giftCardService_.withTransaction(manager)
@@ -770,7 +779,7 @@ class OrderService extends TransactionBaseService {
value: taxExclusivePrice, value: taxExclusivePrice,
balance: taxExclusivePrice, balance: taxExclusivePrice,
metadata: lineItem.metadata, metadata: lineItem.metadata,
tax_rate: giftCardTaxRate || null tax_rate: giftCardTaxRate || null,
}) })
createGiftCardPromises.push(createGiftCardPromise) createGiftCardPromises.push(createGiftCardPromise)
@@ -1933,6 +1942,7 @@ class OrderService extends TransactionBaseService {
relationSet.add("items") relationSet.add("items")
relationSet.add("items.tax_lines") relationSet.add("items.tax_lines")
relationSet.add("items.adjustments") relationSet.add("items.adjustments")
relationSet.add("items.variant")
relationSet.add("swaps") relationSet.add("swaps")
relationSet.add("swaps.additional_items") relationSet.add("swaps.additional_items")
relationSet.add("swaps.additional_items.tax_lines") relationSet.add("swaps.additional_items.tax_lines")