fix(medusa): Deleting product prices (#3152)

This commit is contained in:
Kasper Fabricius Kristensen authored and GitHub committed 2023-02-08 13:13:34 +01:00
1 parent 08324355a4
commit 86c87c7b10
5 files changed
+290 -58

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
"@medusajs/medusa": patch
---
fix(medusa): findVariantPricesNotIn now finds obsolete prices to delete
+233 -42
View File
@@ -6,7 +6,7 @@ const { initDb, useDb } = require("../../../helpers/use-db")
const adminSeeder = require("../../helpers/admin-seeder") const adminSeeder = require("../../helpers/admin-seeder")
const productSeeder = require("../../helpers/product-seeder") const productSeeder = require("../../helpers/product-seeder")
const { Product, ProductCategory } = require("@medusajs/medusa") const { ProductCategory } = require("@medusajs/medusa")
const { const {
ProductVariant, ProductVariant,
@@ -20,6 +20,7 @@ const {
simpleProductFactory, simpleProductFactory,
simpleDiscountFactory, simpleDiscountFactory,
simpleProductCategoryFactory, simpleProductCategoryFactory,
simpleRegionFactory,
} = require("../../factories") } = require("../../factories")
const { DiscountRuleType, AllocationType } = require("@medusajs/medusa/dist") const { DiscountRuleType, AllocationType } = require("@medusajs/medusa/dist")
const { IdMap } = require("medusa-test-utils") const { IdMap } = require("medusa-test-utils")
@@ -447,7 +448,10 @@ describe("/admin/products", () => {
}) })
describe("Product Category filtering", () => { describe("Product Category filtering", () => {
let categoryWithProduct, categoryWithoutProduct, nestedCategoryWithProduct, nested2CategoryWithProduct let categoryWithProduct
let categoryWithoutProduct
let nestedCategoryWithProduct
let nested2CategoryWithProduct
const nestedCategoryWithProductId = "nested-category-with-product-id" const nestedCategoryWithProductId = "nested-category-with-product-id"
const nested2CategoryWithProductId = "nested2-category-with-product-id" const nested2CategoryWithProductId = "nested2-category-with-product-id"
const categoryWithProductId = "category-with-product-id" const categoryWithProductId = "category-with-product-id"
@@ -455,14 +459,11 @@ describe("/admin/products", () => {
beforeEach(async () => { beforeEach(async () => {
const manager = dbConnection.manager const manager = dbConnection.manager
categoryWithProduct = await simpleProductCategoryFactory( categoryWithProduct = await simpleProductCategoryFactory(dbConnection, {
dbConnection,
{
id: categoryWithProductId, id: categoryWithProductId,
name: "category with Product", name: "category with Product",
products: [{ id: testProductId }], products: [{ id: testProductId }],
} })
)
nestedCategoryWithProduct = await simpleProductCategoryFactory( nestedCategoryWithProduct = await simpleProductCategoryFactory(
dbConnection, dbConnection,
@@ -496,49 +497,42 @@ describe("/admin/products", () => {
it("returns a list of products in product category without category children", async () => { it("returns a list of products in product category without category children", async () => {
const api = useApi() const api = useApi()
const params = `category_id[]=${categoryWithProductId}` const params = `category_id[]=${categoryWithProductId}`
const response = await api const response = await api.get(
.get(
`/admin/products?${params}`, `/admin/products?${params}`,
adminHeaders adminHeaders
) )
expect(response.status).toEqual(200) expect(response.status).toEqual(200)
expect(response.data.products).toHaveLength(1) expect(response.data.products).toHaveLength(1)
expect(response.data.products).toEqual( expect(response.data.products).toEqual([
[
expect.objectContaining({ expect.objectContaining({
id: testProductId, id: testProductId,
}), }),
] ])
)
}) })
it("returns a list of products in product category without category children explicitly set to false", async () => { it("returns a list of products in product category without category children explicitly set to false", async () => {
const api = useApi() const api = useApi()
const params = `category_id[]=${categoryWithProductId}&include_category_children=false` const params = `category_id[]=${categoryWithProductId}&include_category_children=false`
const response = await api const response = await api.get(
.get(
`/admin/products?${params}`, `/admin/products?${params}`,
adminHeaders adminHeaders
) )
expect(response.status).toEqual(200) expect(response.status).toEqual(200)
expect(response.data.products).toHaveLength(1) expect(response.data.products).toHaveLength(1)
expect(response.data.products).toEqual( expect(response.data.products).toEqual([
[
expect.objectContaining({ expect.objectContaining({
id: testProductId, id: testProductId,
}), }),
] ])
)
}) })
it("returns a list of products in product category with category children", async () => { it("returns a list of products in product category with category children", async () => {
const api = useApi() const api = useApi()
const params = `category_id[]=${categoryWithProductId}&include_category_children=true` const params = `category_id[]=${categoryWithProductId}&include_category_children=true`
const response = await api const response = await api.get(
.get(
`/admin/products?${params}`, `/admin/products?${params}`,
adminHeaders adminHeaders
) )
@@ -555,7 +549,7 @@ describe("/admin/products", () => {
}), }),
expect.objectContaining({ expect.objectContaining({
id: testProductFilteringId1, id: testProductFilteringId1,
}) }),
]) ])
) )
}) })
@@ -564,8 +558,7 @@ describe("/admin/products", () => {
const api = useApi() const api = useApi()
const params = `category_id[]=${categoryWithoutProductId}&include_category_children=true` const params = `category_id[]=${categoryWithoutProductId}&include_category_children=true`
const response = await api const response = await api.get(
.get(
`/admin/products?${params}`, `/admin/products?${params}`,
adminHeaders adminHeaders
) )
@@ -1594,7 +1587,8 @@ describe("/admin/products", () => {
}) })
describe("Categories", () => { describe("Categories", () => {
let categoryWithProduct, categoryWithoutProduct let categoryWithProduct
let categoryWithoutProduct
const categoryWithProductId = "category-with-product-id" const categoryWithProductId = "category-with-product-id"
const categoryWithoutProductId = "category-without-product-id" const categoryWithoutProductId = "category-without-product-id"
@@ -1620,12 +1614,15 @@ describe("/admin/products", () => {
const payload = { const payload = {
title: "Test", title: "Test",
description: "test-product-description", description: "test-product-description",
categories: [{ id: categoryWithProductId }, { id: categoryWithoutProductId }] categories: [
{ id: categoryWithProductId },
{ id: categoryWithoutProductId },
],
} }
const response = await api const response = await api
.post("/admin/products", payload, adminHeaders) .post("/admin/products", payload, adminHeaders)
.catch(e => e) .catch((e) => e)
expect(response.status).toEqual(200) expect(response.status).toEqual(200)
expect(response.data.product).toEqual( expect(response.data.product).toEqual(
@@ -1649,16 +1646,18 @@ describe("/admin/products", () => {
const payload = { const payload = {
title: "Test", title: "Test",
description: "test-product-description", description: "test-product-description",
categories: [{ id: categoryNotFoundId }] categories: [{ id: categoryNotFoundId }],
} }
const error = await api const error = await api
.post("/admin/products", payload, adminHeaders) .post("/admin/products", payload, adminHeaders)
.catch(e => e) .catch((e) => e)
expect(error.response.status).toEqual(404) expect(error.response.status).toEqual(404)
expect(error.response.data.type).toEqual("not_found") expect(error.response.data.type).toEqual("not_found")
expect(error.response.data.message).toEqual(`Product_category with product_category_id ${categoryNotFoundId} does not exist.`) expect(error.response.data.message).toEqual(
`Product_category with product_category_id ${categoryNotFoundId} does not exist.`
)
}) })
it("updates a product's categories", async () => { it("updates a product's categories", async () => {
@@ -1668,8 +1667,11 @@ describe("/admin/products", () => {
categories: [{ id: categoryWithoutProductId }], categories: [{ id: categoryWithoutProductId }],
} }
const response = await api const response = await api.post(
.post(`/admin/products/${testProductId}`, payload, adminHeaders) `/admin/products/${testProductId}`,
payload,
adminHeaders
)
expect(response.status).toEqual(200) expect(response.status).toEqual(200)
expect(response.data.product).toEqual( expect(response.data.product).toEqual(
@@ -1687,21 +1689,21 @@ describe("/admin/products", () => {
it("remove all categories of a product", async () => { it("remove all categories of a product", async () => {
const api = useApi() const api = useApi()
const category = await simpleProductCategoryFactory( const category = await simpleProductCategoryFactory(dbConnection, {
dbConnection,
{
id: "existing-category", id: "existing-category",
name: "existing category", name: "existing category",
products: [{ id: "test-product" }] products: [{ id: "test-product" }],
} })
)
const payload = { const payload = {
categories: [], categories: [],
} }
const response = await api const response = await api.post(
.post("/admin/products/test-product", payload, adminHeaders) "/admin/products/test-product",
payload,
adminHeaders
)
expect(response.status).toEqual(200) expect(response.status).toEqual(200)
expect(response.data.product).toEqual( expect(response.data.product).toEqual(
@@ -1720,11 +1722,13 @@ describe("/admin/products", () => {
const error = await api const error = await api
.post("/admin/products/test-product", payload, adminHeaders) .post("/admin/products/test-product", payload, adminHeaders)
.catch(e => e) .catch((e) => e)
expect(error.response.status).toEqual(400) expect(error.response.status).toEqual(400)
expect(error.response.data.type).toEqual("invalid_data") expect(error.response.data.type).toEqual("invalid_data")
expect(error.response.data.message).toEqual("property incorrect should not exist, id must be a string") expect(error.response.data.message).toEqual(
"property incorrect should not exist, id must be a string"
)
}) })
}) })
}) })
@@ -2126,6 +2130,193 @@ describe("/admin/products", () => {
]) ])
) )
}) })
it("successfully deletes a region price", async () => {
const api = useApi()
const createRegionPricePayload = {
prices: [
{
currency_code: "usd",
amount: 1000,
},
{
region_id: "test-region",
amount: 8000,
},
{
currency_code: "eur",
amount: 900,
},
],
}
const variantId = "test-variant_3"
const createRegionPriceResponse = await api.post(
"/admin/products/test-product1/variants/test-variant_3",
createRegionPricePayload,
adminHeaders
)
const initialPriceArray =
createRegionPriceResponse.data.product.variants.find(
(v) => v.id === variantId
).prices
expect(createRegionPriceResponse.status).toEqual(200)
expect(initialPriceArray).toHaveLength(3)
expect(initialPriceArray).toEqual(
expect.arrayContaining([
expect.objectContaining({
amount: 1000,
currency_code: "usd",
}),
expect.objectContaining({
amount: 8000,
currency_code: "usd",
region_id: "test-region",
}),
expect.objectContaining({
amount: 900,
currency_code: "eur",
}),
])
)
const deleteRegionPricePayload = {
prices: [
{
currency_code: "usd",
amount: 1000,
},
{
currency_code: "eur",
amount: 900,
},
],
}
const deleteRegionPriceResponse = await api.post(
"/admin/products/test-product1/variants/test-variant_3",
deleteRegionPricePayload,
adminHeaders
)
const finalPriceArray =
deleteRegionPriceResponse.data.product.variants.find(
(v) => v.id === variantId
).prices
expect(deleteRegionPriceResponse.status).toEqual(200)
expect(finalPriceArray).toHaveLength(2)
expect(finalPriceArray).toEqual([
expect.objectContaining({
amount: 1000,
currency_code: "usd",
}),
expect.objectContaining({
amount: 900,
currency_code: "eur",
}),
])
})
it("successfully updates a variants prices by deleting both a currency and region price", async () => {
const api = useApi()
await Promise.all(
["reg_1", "reg_2", "reg_3"].map(async (regionId) => {
return await simpleRegionFactory(dbConnection, {
id: regionId,
currency_code: regionId === "reg_1" ? "eur" : "usd",
})
})
)
const createPrices = {
prices: [
{
region_id: "reg_1",
amount: 1,
},
{
region_id: "reg_2",
amount: 2,
},
{
currency_code: "usd",
amount: 3,
},
{
region_id: "reg_3",
amount: 4,
},
{
currency_code: "eur",
amount: 5,
},
],
}
const variantId = "test-variant_3"
await api
.post(
`/admin/products/test-product1/variants/${variantId}`,
createPrices,
adminHeaders
)
.catch((err) => {
console.log(err)
})
const updatePrices = {
prices: [
{
region_id: "reg_1",
amount: 100,
},
{
region_id: "reg_2",
amount: 200,
},
{
currency_code: "usd",
amount: 300,
},
],
}
const response = await api.post(
`/admin/products/test-product1/variants/${variantId}`,
updatePrices,
adminHeaders
)
const finalPriceArray = response.data.product.variants.find(
(v) => v.id === variantId
).prices
expect(response.status).toEqual(200)
expect(finalPriceArray).toHaveLength(3)
expect(finalPriceArray).toEqual(
expect.arrayContaining([
expect.objectContaining({
amount: 100,
region_id: "reg_1",
}),
expect.objectContaining({
amount: 200,
region_id: "reg_2",
}),
expect.objectContaining({
amount: 300,
currency_code: "usd",
}),
])
)
})
}) })
describe("variant creation", () => { describe("variant creation", () => {
@@ -5,15 +5,16 @@ import {
In, In,
IsNull, IsNull,
Not, Not,
ObjectLiteral,
Repository, Repository,
WhereExpressionBuilder, WhereExpressionBuilder,
} from "typeorm" } from "typeorm"
import { QueryDeepPartialEntity } from "typeorm/query-builder/QueryPartialEntity"
import { MoneyAmount } from "../models/money-amount" import { MoneyAmount } from "../models/money-amount"
import { import {
PriceListPriceCreateInput, PriceListPriceCreateInput,
PriceListPriceUpdateInput, PriceListPriceUpdateInput,
} from "../types/price-list" } from "../types/price-list"
import { QueryDeepPartialEntity } from "typeorm/query-builder/QueryPartialEntity"
type Price = Partial< type Price = Partial<
Omit<MoneyAmount, "created_at" | "updated_at" | "deleted_at"> Omit<MoneyAmount, "created_at" | "updated_at" | "deleted_at">
@@ -23,6 +24,11 @@ type Price = Partial<
@EntityRepository(MoneyAmount) @EntityRepository(MoneyAmount)
export class MoneyAmountRepository extends Repository<MoneyAmount> { export class MoneyAmountRepository extends Repository<MoneyAmount> {
/**
* Will be removed in a future release.
* Use `deleteVariantPricesNotIn` instead.
* @deprecated
*/
public async findVariantPricesNotIn( public async findVariantPricesNotIn(
variantId: string, variantId: string,
prices: Price[] prices: Price[]
@@ -43,6 +49,44 @@ export class MoneyAmountRepository extends Repository<MoneyAmount> {
return pricesNotInPricesPayload return pricesNotInPricesPayload
} }
public async deleteVariantPricesNotIn(
variantId: string,
prices: Price[]
): Promise<void> {
const where = {
variant_id: variantId,
price_list_id: IsNull(),
}
const orWhere: ObjectLiteral[] = []
for (const price of prices) {
if (price.currency_code) {
orWhere.push(
{
currency_code: Not(price.currency_code),
},
{
region_id: price.region_id ? Not(price.region_id) : Not(IsNull()),
currency_code: price.currency_code,
}
)
}
if (price.region_id) {
orWhere.push({
region_id: Not(price.region_id),
})
}
}
await this.createQueryBuilder()
.delete()
.where(where)
.andWhere(orWhere)
.execute()
}
public async upsertVariantCurrencyPrice( public async upsertVariantCurrencyPrice(
variantId: string, variantId: string,
price: Price price: Price
@@ -477,7 +477,7 @@ describe("ProductVariantService", () => {
}, },
] ]
moneyAmountRepository.findVariantPricesNotIn = jest moneyAmountRepository.deleteVariantPricesNotIn = jest
.fn() .fn()
.mockImplementation(() => Promise.resolve(oldPrices)) .mockImplementation(() => Promise.resolve(oldPrices))
@@ -641,7 +641,7 @@ describe("ProductVariantService", () => {
}, },
] ]
moneyAmountRepository.findVariantPricesNotIn = jest moneyAmountRepository.deleteVariantPricesNotIn = jest
.fn() .fn()
.mockImplementation(() => Promise.resolve(oldPrices)) .mockImplementation(() => Promise.resolve(oldPrices))
@@ -692,7 +692,7 @@ describe("ProductVariantService", () => {
]) ])
expect( expect(
moneyAmountRepository.findVariantPricesNotIn moneyAmountRepository.deleteVariantPricesNotIn
).toHaveBeenCalledTimes(1) ).toHaveBeenCalledTimes(1)
expect( expect(
@@ -704,9 +704,6 @@ describe("ProductVariantService", () => {
currency_code: "usd", currency_code: "usd",
amount: 4000, amount: 4000,
}) })
expect(moneyAmountRepository.remove).toHaveBeenCalledTimes(1)
expect(moneyAmountRepository.remove).toHaveBeenCalledWith(oldPrices)
}) })
it("successfully creates new a region price", async () => { it("successfully creates new a region price", async () => {
@@ -19,8 +19,6 @@ import {
FindWithRelationsOptions, FindWithRelationsOptions,
ProductVariantRepository, ProductVariantRepository,
} from "../repositories/product-variant" } from "../repositories/product-variant"
import EventBusService from "./event-bus"
import RegionService from "./region"
import { FindConfig } from "../types/common" import { FindConfig } from "../types/common"
import { import {
CreateProductVariantInput, CreateProductVariantInput,
@@ -30,6 +28,8 @@ import {
UpdateProductVariantInput, UpdateProductVariantInput,
} from "../types/product-variant" } from "../types/product-variant"
import { buildQuery, setMetadata } from "../utils" import { buildQuery, setMetadata } from "../utils"
import EventBusService from "./event-bus"
import RegionService from "./region"
class ProductVariantService extends TransactionBaseService { class ProductVariantService extends TransactionBaseService {
static Events = { static Events = {
@@ -341,11 +341,8 @@ class ProductVariantService extends TransactionBaseService {
this.moneyAmountRepository_ this.moneyAmountRepository_
) )
// get prices to be deleted // Delete obsolete prices
const obsoletePrices = await moneyAmountRepo.findVariantPricesNotIn( await moneyAmountRepo.deleteVariantPricesNotIn(variantId, prices)
variantId,
prices
)
const regionsServiceTx = this.regionService_.withTransaction(manager) const regionsServiceTx = this.regionService_.withTransaction(manager)
@@ -362,8 +359,6 @@ class ProductVariantService extends TransactionBaseService {
await this.setCurrencyPrice(variantId, price) await this.setCurrencyPrice(variantId, price)
} }
} }
await moneyAmountRepo.remove(obsoletePrices)
}) })
} }