feat(core-flows,medusa,types,utils): rename psma to prices (#6796)

What:

Renames pricesetmoneyamount to prices

Co-authored-by: Adrien de Peretti <25098370+adrien2p@users.noreply.github.com>
This commit is contained in:
Riqwan ThamirandAdrien de Peretti authored and GitHub committed 2024-03-25 13:15:25 +00:00
1 parent fbc369705d
commit 9073d7aba3
80 files changed
+1002 -2222

No files matched your search

+8
View File
@@ -0,0 +1,8 @@
---
"@medusajs/core-flows": patch
"@medusajs/medusa": patch
"@medusajs/types": patch
"@medusajs/utils": patch
---
feat(core-flows,medusa,types,utils): rename psma to prices
@@ -4,10 +4,10 @@ import {
} from "../../../../factories" } from "../../../../factories"
import { IPricingModuleService } from "@medusajs/types" import { IPricingModuleService } from "@medusajs/types"
import { medusaIntegrationTestRunner } from "medusa-test-utils"
import adminSeeder from "../../../../helpers/admin-seeder" import adminSeeder from "../../../../helpers/admin-seeder"
import { createDefaultRuleTypes } from "../../../helpers/create-default-rule-types" import { createDefaultRuleTypes } from "../../../helpers/create-default-rule-types"
import { createVariantPriceSet } from "../../../helpers/create-variant-price-set" import { createVariantPriceSet } from "../../../helpers/create-variant-price-set"
import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -100,11 +100,10 @@ medusaIntegrationTestRunner({
}) })
it("should delete prices in batch based on product ids", async () => { it("should delete prices in batch based on product ids", async () => {
let priceSetMoneyAmounts = let prices = await pricingModuleService.listPrices({
await pricingModuleService.listPriceSetMoneyAmounts({
price_set_id: [priceSet.id], price_set_id: [priceSet.id],
}) })
expect(priceSetMoneyAmounts.length).toEqual(2) expect(prices.length).toEqual(2)
const deleteRes = await api.delete( const deleteRes = await api.delete(
`/admin/price-lists/${priceListId}/products/prices/batch`, `/admin/price-lists/${priceListId}/products/prices/batch`,
@@ -117,13 +116,12 @@ medusaIntegrationTestRunner({
) )
expect(deleteRes.status).toEqual(200) expect(deleteRes.status).toEqual(200)
priceSetMoneyAmounts = prices = await pricingModuleService.listPrices({
await pricingModuleService.listPriceSetMoneyAmounts({
price_set_id: [priceSet.id], price_set_id: [priceSet.id],
}) })
expect(priceSetMoneyAmounts.length).toEqual(1) expect(prices.length).toEqual(1)
expect(priceSetMoneyAmounts).toEqual([ expect(prices).toEqual([
expect.objectContaining({ expect.objectContaining({
price_list: null, price_list: null,
}), }),
@@ -131,11 +129,10 @@ medusaIntegrationTestRunner({
}) })
it("should delete prices based on single product id", async () => { it("should delete prices based on single product id", async () => {
let priceSetMoneyAmounts = let prices = await pricingModuleService.listPrices({
await pricingModuleService.listPriceSetMoneyAmounts({
price_set_id: [priceSet.id], price_set_id: [priceSet.id],
}) })
expect(priceSetMoneyAmounts.length).toEqual(2) expect(prices.length).toEqual(2)
const deleteRes = await api.delete( const deleteRes = await api.delete(
`/admin/price-lists/${priceListId}/products/${product.id}/prices`, `/admin/price-lists/${priceListId}/products/${product.id}/prices`,
@@ -143,13 +140,12 @@ medusaIntegrationTestRunner({
) )
expect(deleteRes.status).toEqual(200) expect(deleteRes.status).toEqual(200)
priceSetMoneyAmounts = prices = await pricingModuleService.listPrices({
await pricingModuleService.listPriceSetMoneyAmounts({
price_set_id: [priceSet.id], price_set_id: [priceSet.id],
}) })
expect(priceSetMoneyAmounts.length).toEqual(1) expect(prices.length).toEqual(1)
expect(priceSetMoneyAmounts).toEqual([ expect(prices).toEqual([
expect.objectContaining({ expect.objectContaining({
price_list: null, price_list: null,
}), }),
@@ -4,10 +4,10 @@ import {
} from "../../../../factories" } from "../../../../factories"
import { IPricingModuleService } from "@medusajs/types" import { IPricingModuleService } from "@medusajs/types"
import { medusaIntegrationTestRunner } from "medusa-test-utils"
import adminSeeder from "../../../../helpers/admin-seeder" import adminSeeder from "../../../../helpers/admin-seeder"
import { createDefaultRuleTypes } from "../../../helpers/create-default-rule-types" import { createDefaultRuleTypes } from "../../../helpers/create-default-rule-types"
import { createVariantPriceSet } from "../../../helpers/create-variant-price-set" import { createVariantPriceSet } from "../../../helpers/create-variant-price-set"
import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -94,10 +94,10 @@ medusaIntegrationTestRunner({
const result = await api.post(`admin/price-lists`, data, adminHeaders) const result = await api.post(`admin/price-lists`, data, adminHeaders)
const priceListId = result.data.price_list.id const priceListId = result.data.price_list.id
let psmas = await pricingModuleService.listPriceSetMoneyAmounts({ let prices = await pricingModuleService.listPrices({
price_list_id: [priceListId], price_list_id: [priceListId],
}) })
expect(psmas.length).toEqual(1) expect(prices.length).toEqual(1)
const deleteRes = await api.delete( const deleteRes = await api.delete(
`/admin/price-lists/${priceListId}/variants/${variant.id}/prices`, `/admin/price-lists/${priceListId}/variants/${variant.id}/prices`,
@@ -105,10 +105,10 @@ medusaIntegrationTestRunner({
) )
expect(deleteRes.status).toEqual(200) expect(deleteRes.status).toEqual(200)
psmas = await pricingModuleService.listPriceSetMoneyAmounts({ prices = await pricingModuleService.listPrices({
price_list_id: [priceListId], price_list_id: [priceListId],
}) })
expect(psmas.length).toEqual(0) expect(prices.length).toEqual(0)
}) })
}) })
}, },
@@ -4,10 +4,10 @@ import {
} from "../../../../factories" } from "../../../../factories"
import { IPricingModuleService } from "@medusajs/types" import { IPricingModuleService } from "@medusajs/types"
import { medusaIntegrationTestRunner } from "medusa-test-utils"
import adminSeeder from "../../../../helpers/admin-seeder" import adminSeeder from "../../../../helpers/admin-seeder"
import { createDefaultRuleTypes } from "../../../helpers/create-default-rule-types" import { createDefaultRuleTypes } from "../../../helpers/create-default-rule-types"
import { createVariantPriceSet } from "../../../helpers/create-variant-price-set" import { createVariantPriceSet } from "../../../helpers/create-variant-price-set"
import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -98,16 +98,16 @@ medusaIntegrationTestRunner({
const res = await api.post(`admin/price-lists`, data, adminHeaders) const res = await api.post(`admin/price-lists`, data, adminHeaders)
const priceListId = res.data.price_list.id const priceListId = res.data.price_list.id
let psmas = await pricingModuleService.listPriceSetMoneyAmounts( let prices = await pricingModuleService.listPrices(
{ {
price_list_id: [priceListId], price_list_id: [priceListId],
}, },
{ relations: ["money_amount"] } {}
) )
expect(psmas.length).toEqual(2) expect(prices.length).toEqual(2)
const deletePrice = psmas[0].money_amount const deletePrice = prices[0]
const deleteRes = await api.delete( const deleteRes = await api.delete(
`/admin/price-lists/${priceListId}/prices/batch`, `/admin/price-lists/${priceListId}/prices/batch`,
{ {
@@ -119,10 +119,10 @@ medusaIntegrationTestRunner({
) )
expect(deleteRes.status).toEqual(200) expect(deleteRes.status).toEqual(200)
psmas = await pricingModuleService.listPriceSetMoneyAmounts({ prices = await pricingModuleService.listPrices({
price_list_id: [priceListId], price_list_id: [priceListId],
}) })
expect(psmas.length).toEqual(1) expect(prices.length).toEqual(1)
}) })
}) })
}, },
@@ -366,11 +366,11 @@ medusaIntegrationTestRunner({
const result = await api.post(`admin/price-lists`, data, adminHeaders) const result = await api.post(`admin/price-lists`, data, adminHeaders)
const priceListId = result.data.price_list.id const priceListId = result.data.price_list.id
let psmas = await pricingModule.listPriceSetMoneyAmounts({ let prices = await pricingModule.listPrices({
price_list_id: [priceListId], price_list_id: [priceListId],
}) })
expect(psmas.length).toEqual(1) expect(prices.length).toEqual(1)
const deleteRes = await api.delete( const deleteRes = await api.delete(
`/admin/price-lists/${priceListId}`, `/admin/price-lists/${priceListId}`,
@@ -385,10 +385,10 @@ medusaIntegrationTestRunner({
expect(afterDelete.response.status).toEqual(404) expect(afterDelete.response.status).toEqual(404)
psmas = await pricingModule.listPriceSetMoneyAmounts({ prices = await pricingModule.listPrices({
price_list_id: [priceListId], price_list_id: [priceListId],
}) })
expect(psmas.length).toEqual(0) expect(prices.length).toEqual(0)
}) })
it("should idempotently return a success even if price lists dont exist", async () => { it("should idempotently return a success even if price lists dont exist", async () => {
@@ -609,13 +609,13 @@ medusaIntegrationTestRunner({
const [priceList] = await pricingModule.listPriceLists( const [priceList] = await pricingModule.listPriceLists(
{ id: [createdPriceList.id] }, { id: [createdPriceList.id] },
{ relations: ["price_set_money_amounts"] } { relations: ["prices"] }
) )
const psmaIdToDelete = priceList.price_set_money_amounts![0].id const priceIdToDelete = priceList.prices![0].id
const response = await api.post( const response = await api.post(
`/admin/price-lists/${priceList.id}/prices/batch/remove`, `/admin/price-lists/${priceList.id}/prices/batch/remove`,
{ ids: [psmaIdToDelete] }, { ids: [priceIdToDelete] },
adminHeaders adminHeaders
) )
@@ -19,7 +19,8 @@ const env = {
medusaIntegrationTestRunner({ medusaIntegrationTestRunner({
env, env,
testSuite: ({ dbConnection, getContainer, api }) => { testSuite: ({ dbConnection, getContainer, api }) => {
describe("/admin/products", () => { // TODO: unskip this when there is a module compatible productSeeder
describe.skip("/admin/products", () => {
let medusaContainer let medusaContainer
beforeAll(async () => { beforeAll(async () => {
@@ -41,6 +41,6 @@ export const createVariantPriceSet = async ({
}) })
return await pricingModuleService.retrieve(priceSet.id, { return await pricingModuleService.retrieve(priceSet.id, {
relations: ["price_set_money_amounts"], relations: ["prices"],
}) })
} }
@@ -14,7 +14,7 @@ export const getExistingPriceListsPriceIdsStep = createStep(
) )
const existingPrices = priceListIds.length const existingPrices = priceListIds.length
? await pricingModule.listPriceSetMoneyAmounts( ? await pricingModule.listPrices(
{ price_list_id: priceListIds }, { price_list_id: priceListIds },
{ relations: ["price_list"] } { relations: ["price_list"] }
) )
@@ -14,18 +14,16 @@ export const removePriceListPricesStep = createStep(
ModuleRegistrationName.PRICING ModuleRegistrationName.PRICING
) )
const psmas = await pricingModule.listPriceSetMoneyAmounts( const prices = await pricingModule.listPrices(
{ id: ids }, { id: ids },
{ relations: ["price_list"] } { relations: ["price_list"] }
) )
await pricingModule.softDeletePriceSetMoneyAmounts( await pricingModule.softDeletePrices(prices.map((price) => price.id))
psmas.map((psma) => psma.id)
)
return new StepResponse( return new StepResponse(
null, null,
psmas.map((psma) => psma.id) prices.map((price) => price.id)
) )
}, },
async (ids, { container }) => { async (ids, { container }) => {
@@ -37,6 +35,6 @@ export const removePriceListPricesStep = createStep(
ModuleRegistrationName.PRICING ModuleRegistrationName.PRICING
) )
await pricingModule.restorePriceSetMoneyAmounts(ids) await pricingModule.restorePrices(ids)
} }
) )
@@ -1,7 +1,7 @@
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { import {
IPricingModuleService, IPricingModuleService,
PriceSetMoneyAmountDTO, PriceDTO,
UpdatePriceListPriceDTO, UpdatePriceListPriceDTO,
UpdatePriceListPricesDTO, UpdatePriceListPricesDTO,
UpdatePriceListPriceWorkflowStepDTO, UpdatePriceListPriceWorkflowStepDTO,
@@ -42,26 +42,26 @@ export const updatePriceListPricesStep = createStep(
} }
const existingPrices = priceIds.length const existingPrices = priceIds.length
? await pricingModule.listPriceSetMoneyAmounts( ? await pricingModule.listPrices(
{ id: priceIds }, { id: priceIds },
{ relations: ["price_list"] } { relations: ["price_list"] }
) )
: [] : []
const priceListPsmaMap = new Map<string, PriceSetMoneyAmountDTO[]>() const priceListPricesMap = new Map<string, PriceDTO[]>()
const dataBeforePriceUpdate: UpdatePriceListPricesDTO[] = [] const dataBeforePriceUpdate: UpdatePriceListPricesDTO[] = []
for (const price of existingPrices) { for (const price of existingPrices) {
const priceListId = price.price_list!.id const priceListId = price.price_list!.id
const psmas = priceListPsmaMap.get(priceListId) || [] const prices = priceListPricesMap.get(priceListId) || []
priceListPsmaMap.set(priceListId, psmas) priceListPricesMap.set(priceListId, prices)
} }
for (const [priceListId, psmas] of Object.entries(priceListPsmaMap)) { for (const [priceListId, prices] of Object.entries(priceListPricesMap)) {
dataBeforePriceUpdate.push({ dataBeforePriceUpdate.push({
price_list_id: priceListId, price_list_id: priceListId,
prices: buildPriceSetPricesForModule(psmas), prices: buildPriceSetPricesForModule(prices),
}) })
} }
@@ -4,7 +4,7 @@ import {
CreatePriceListPriceDTO, CreatePriceListPriceDTO,
CreatePriceListPriceWorkflowDTO, CreatePriceListPriceWorkflowDTO,
IPricingModuleService, IPricingModuleService,
PriceSetMoneyAmountDTO, PriceDTO,
UpdatePriceListPriceDTO, UpdatePriceListPriceDTO,
UpdatePriceListPriceWorkflowDTO, UpdatePriceListPriceWorkflowDTO,
UpdatePriceListPricesDTO, UpdatePriceListPricesDTO,
@@ -56,33 +56,30 @@ export const upsertPriceListPricesStep = createStep(
} }
} }
const updatedPriceSetMoneyAmounts = const updatedPrices = await pricingModule.listPrices(
await pricingModule.listPriceSetMoneyAmounts(
{ {
id: priceListPricesToUpdate id: priceListPricesToUpdate
.map((priceListData) => .map((priceListData) => priceListData.prices.map((price) => price.id))
priceListData.prices.map((price) => price.id)
)
.filter(Boolean) .filter(Boolean)
.flat(1), .flat(1),
}, },
{ relations: ["price_list"] } { relations: ["price_list"] }
) )
const priceListPsmaMap = new Map<string, PriceSetMoneyAmountDTO[]>() const priceListPricesMap = new Map<string, PriceDTO[]>()
const dataBeforePriceUpdate: UpdatePriceListPricesDTO[] = [] const dataBeforePriceUpdate: UpdatePriceListPricesDTO[] = []
for (const priceSetMoneyAmount of updatedPriceSetMoneyAmounts) { for (const updatedPrice of updatedPrices) {
const priceListId = priceSetMoneyAmount.price_list!.id const priceListId = updatedPrice.price_list!.id
const psmas = priceListPsmaMap.get(priceListId) || [] const prices = priceListPricesMap.get(priceListId) || []
priceListPsmaMap.set(priceListId, psmas) priceListPricesMap.set(priceListId, prices)
} }
for (const [priceListId, psmas] of Object.entries(priceListPsmaMap)) { for (const [priceListId, prices] of Object.entries(priceListPricesMap)) {
dataBeforePriceUpdate.push({ dataBeforePriceUpdate.push({
price_list_id: priceListId, price_list_id: priceListId,
prices: buildPriceSetPricesForModule(psmas), prices: buildPriceSetPricesForModule(prices),
}) })
} }
@@ -14,9 +14,7 @@ export function buildPriceListResponse(
): AdminPriceListRemoteQueryDTO[] { ): AdminPriceListRemoteQueryDTO[] {
for (const priceList of priceLists) { for (const priceList of priceLists) {
priceList.rules = buildPriceListRules(priceList.price_list_rules || []) priceList.rules = buildPriceListRules(priceList.price_list_rules || [])
priceList.prices = buildPriceSetPricesForCore( priceList.prices = buildPriceSetPricesForCore(priceList.prices || [])
priceList.price_set_money_amounts || []
)
} }
return priceLists.map((priceList) => cleanResponseData(priceList, apiFields)) return priceLists.map((priceList) => cleanResponseData(priceList, apiFields))
@@ -13,17 +13,17 @@ export const adminPriceListRemoteQueryFields = [
"created_at", "created_at",
"updated_at", "updated_at",
"deleted_at", "deleted_at",
"price_set_money_amounts.id", "prices.id",
"price_set_money_amounts.currency_code", "prices.currency_code",
"price_set_money_amounts.amount", "prices.amount",
"price_set_money_amounts.min_quantity", "prices.min_quantity",
"price_set_money_amounts.max_quantity", "prices.max_quantity",
"price_set_money_amounts.created_at", "prices.created_at",
"price_set_money_amounts.deleted_at", "prices.deleted_at",
"price_set_money_amounts.updated_at", "prices.updated_at",
"price_set_money_amounts.price_set.variant.id", "prices.price_set.variant.id",
"price_set_money_amounts.price_rules.value", "prices.price_rules.value",
"price_set_money_amounts.price_rules.rule_type.rule_attribute", "prices.price_rules.rule_type.rule_attribute",
"price_list_rules.price_list_rule_values.value", "price_list_rules.price_list_rule_values.value",
"price_list_rules.rule_type.rule_attribute", "price_list_rules.rule_type.rule_attribute",
] ]
@@ -50,7 +50,6 @@ export const defaultAdminPriceListFields = [
] ]
export const defaultAdminPriceListRelations = [] export const defaultAdminPriceListRelations = []
export const allowedAdminPriceListRelations = [PriceListRelations.PRICES] export const allowedAdminPriceListRelations = [PriceListRelations.PRICES]
export const adminListTransformQueryConfig = { export const adminListTransformQueryConfig = {
@@ -15,10 +15,7 @@ export const remapKeysForProduct = (selectFields: string[]) => {
const pricingFields = selectFields const pricingFields = selectFields
.filter((fieldName: string) => isPricing(fieldName)) .filter((fieldName: string) => isPricing(fieldName))
.map((fieldName: string) => .map((fieldName: string) =>
fieldName.replace( fieldName.replace("variants.prices.", "variants.price_set.prices.")
"variants.prices.",
"variants.price_set.price_set_money_amounts."
)
) )
return [...productFields, ...pricingFields] return [...productFields, ...pricingFields]
@@ -31,7 +28,7 @@ export const remapKeysForVariant = (selectFields: string[]) => {
const pricingFields = selectFields const pricingFields = selectFields
.filter((fieldName: string) => isPricing(fieldName)) .filter((fieldName: string) => isPricing(fieldName))
.map((fieldName: string) => .map((fieldName: string) =>
fieldName.replace("prices.", "price_set.price_set_money_amounts.") fieldName.replace("prices.", "price_set.prices.")
) )
return [...variantFields, ...pricingFields] return [...variantFields, ...pricingFields]
@@ -47,8 +44,8 @@ export const remapProduct = (p: ProductDTO) => {
export const remapVariant = (v: ProductVariantDTO) => { export const remapVariant = (v: ProductVariantDTO) => {
return { return {
...v, ...v,
prices: (v as any).price_set?.price_set_money_amounts?.map((psma) => ({ prices: (v as any).price_set?.prices?.map((price) => ({
...psma, ...price,
variant_id: v.id, variant_id: v.id,
})), })),
price_set: undefined, price_set: undefined,
@@ -19,7 +19,7 @@ export function maybeApplyPriceListsFilter() {
const queryObject = remoteQueryObjectFromString({ const queryObject = remoteQueryObjectFromString({
entryPoint: "price_list", entryPoint: "price_list",
fields: ["price_set_money_amounts.price_set.variant.id"], fields: ["prices.price_set.variant.id"],
variables: { variables: {
id: priceListIds, id: priceListIds,
}, },
@@ -33,8 +33,9 @@ export function maybeApplyPriceListsFilter() {
const priceLists = await remoteQuery(queryObject) const priceLists = await remoteQuery(queryObject)
priceLists.forEach((priceList) => { priceLists.forEach((priceList) => {
priceList.price_set_money_amounts?.forEach((psma) => { priceList.prices?.forEach((price) => {
const variantId = psma.price_set?.variant?.id const variantId = price.price_set?.variant?.id
if (variantId) { if (variantId) {
variantIds.push(variantId) variantIds.push(variantId)
} }
@@ -9,7 +9,6 @@ import middlewares, {
import { import {
defaultAdminProductFields, defaultAdminProductFields,
defaultAdminProductRelations, defaultAdminProductRelations,
defaultAdminProductRemoteQueryObject,
} from "../products" } from "../products"
import { FlagRouter } from "@medusajs/utils" import { FlagRouter } from "@medusajs/utils"
@@ -87,56 +86,6 @@ export default (app, featureFlagRouter: FlagRouter) => {
return app return app
} }
export const defaultAdminPriceListRemoteQueryObject = {
fields: [
"created_at",
"deleted_at",
"description",
"ends_at",
"id",
"title",
"starts_at",
"status",
"type",
"updated_at",
],
price_list_rules: {
price_list_rule_values: {
fields: ["value"],
},
rule_type: {
fields: ["rule_attribute"],
},
},
price_set_money_amounts: {
money_amount: {
fields: [
"id",
"currency_code",
"amount",
"min_quantity",
"max_quantity",
"created_at",
"deleted_at",
"updated_at",
],
},
price_rules: {
fields: ["value"],
rule_type: {
fields: ["rule_attribute"],
},
},
price_set: {
variant_link: {
variant: {
fields: defaultAdminProductRemoteQueryObject.variants.fields,
},
},
},
},
}
export const defaultAdminPriceListFields = [ export const defaultAdminPriceListFields = [
"id", "id",
"name", "name",
@@ -1,27 +0,0 @@
import { MedusaContainer } from "@medusajs/types"
import { MedusaError } from "medusa-core-utils"
import { PriceList } from "../../../../../models"
import { listAndCountPriceListPricingModule } from "./list-and-count-price-lists"
export async function getPriceListPricingModule(
id: string,
{
container,
}: {
container: MedusaContainer
}
): Promise<PriceList> {
const [priceLists, count] = await listAndCountPriceListPricingModule({
filters: { id: [id] },
container,
})
if (count === 0) {
throw new MedusaError(
MedusaError.Types.NOT_FOUND,
`Price list with id: ${id} was not found`
)
}
return priceLists[0]
}
@@ -1,2 +0,0 @@
export * from "./get-price-list"
export * from "./list-and-count-price-lists"
@@ -1,86 +0,0 @@
import { LinkModuleUtils, ModuleRegistrationName } from "@medusajs/modules-sdk"
import { FilterablePriceListProps, MedusaContainer } from "@medusajs/types"
import { CustomerGroup, MoneyAmount, PriceList } from "../../../../../models"
import { FindConfig } from "../../../../../types/common"
import { defaultAdminPriceListRemoteQueryObject } from "../index"
export async function listAndCountPriceListPricingModule({
filters,
listConfig = { skip: 0 },
container,
}: {
container: MedusaContainer
filters?: FilterablePriceListProps
listConfig?: FindConfig<PriceList>
}): Promise<[PriceList[], number]> {
const remoteQuery = container.resolve(LinkModuleUtils.REMOTE_QUERY)
const customerModule = container.resolve(ModuleRegistrationName.CUSTOMER)
const query = {
price_list: {
__args: { filters, ...listConfig },
...defaultAdminPriceListRemoteQueryObject,
},
}
const {
rows: priceLists,
metadata: { count },
} = await remoteQuery(query)
if (!count) {
return [[], 0]
}
const customerGroupIds: string[] = priceLists
.map((priceList) =>
priceList.price_list_rules
.filter((rule) => rule.rule_type.rule_attribute === "customer_group_id")
.map((rule) =>
rule.price_list_rule_values.map((rule_value) => rule_value.value)
)
)
.flat(2)
const customerGroups = await customerModule.list({ id: customerGroupIds }, {})
const customerGroupIdMap = new Map(customerGroups.map((cg) => [cg.id, cg]))
for (const priceList of priceLists) {
const priceSetMoneyAmounts = priceList.price_set_money_amounts || []
const priceListRulesData = priceList.price_list_rules || []
delete priceList.price_set_money_amounts
delete priceList.price_list_rules
priceList.prices = priceSetMoneyAmounts.map((priceSetMoneyAmount) => {
const productVariant = priceSetMoneyAmount.price_set.variant_link.variant
const rules = priceSetMoneyAmount.price_rules.reduce((acc, curr) => {
acc[curr.rule_type.rule_attribute] = curr.value
return acc
}, {})
return {
...(priceSetMoneyAmount.money_amount as MoneyAmount),
price_list_id: priceList.id,
variant_id: productVariant?.id ?? null,
variant: productVariant ?? null,
region_id: rules["region_id"] ?? null,
rules,
}
})
priceList.name = priceList.title
delete priceList.title
const customerGroupRule = priceListRulesData.find(
(plr) => plr.rule_type.rule_attribute === "customer_group_id"
)
priceList.customer_groups =
customerGroupRule?.price_list_rule_values
.map((cgr) => customerGroupIdMap.get(cgr.value))
.filter((cg): cg is CustomerGroup => !!cg) || []
}
return [priceLists, count]
}
+3 -291
View File
@@ -1,15 +1,5 @@
import { import { IPricingModuleService, RemoteQueryFunction } from "@medusajs/types"
CalculatedPriceSet, import { FlagRouter, promiseAll } from "@medusajs/utils"
IPricingModuleService,
PriceSetMoneyAmountDTO,
RemoteQueryFunction,
} from "@medusajs/types"
import {
FlagRouter,
MedusaV2Flag,
promiseAll,
removeNullish,
} from "@medusajs/utils"
import { import {
CustomerService, CustomerService,
ProductVariantService, ProductVariantService,
@@ -20,13 +10,7 @@ import {
IPriceSelectionStrategy, IPriceSelectionStrategy,
PriceSelectionContext, PriceSelectionContext,
} from "../interfaces/price-selection-strategy" } from "../interfaces/price-selection-strategy"
import { import { Product, ProductVariant, Region, ShippingOption } from "../models"
MoneyAmount,
Product,
ProductVariant,
Region,
ShippingOption,
} from "../models"
import { import {
PricedProduct, PricedProduct,
PricedShippingOption, PricedShippingOption,
@@ -197,128 +181,6 @@ class PricingService extends TransactionBaseService {
return taxedPricing return taxedPricing
} }
private async getProductVariantPricingModulePricing_(
variantPriceData: {
variantId: string
quantity?: number
}[],
context: PricingContext
) {
const variables = {
variant_id: variantPriceData.map((pricedata) => pricedata.variantId),
take: null,
}
const query = {
product_variant_price_set: {
__args: variables,
fields: ["variant_id", "price_set_id"],
},
}
const variantPriceSets = await this.remoteQuery(query)
const variantIdToPriceSetIdMap: Map<string, string> = new Map(
variantPriceSets.map((variantPriceSet) => [
variantPriceSet.variant_id,
variantPriceSet.price_set_id,
])
)
const priceSetIds: string[] = variantPriceSets.map(
(variantPriceSet) => variantPriceSet.price_set_id
)
const queryContext: PriceSelectionContext & {
customer_group_id?: string[]
} = removeNullish(context.price_selection)
if (queryContext.customer_id) {
const { groups } = await this.customerService_.retrieve(
queryContext.customer_id,
{ relations: ["groups"] }
)
if (groups?.length) {
queryContext.customer_group_id = groups.map((group) => group.id)
}
}
let calculatedPrices: CalculatedPriceSet[] = []
if (queryContext.currency_code) {
calculatedPrices = (await this.pricingModuleService.calculatePrices(
{ id: priceSetIds },
{
context: queryContext as any,
}
)) as unknown as CalculatedPriceSet[]
}
const calculatedPriceMap = new Map<string, CalculatedPriceSet>(
calculatedPrices.map((priceSet) => [priceSet.id, priceSet])
)
const pricingResultMap = new Map()
variantPriceData.forEach(({ variantId }) => {
const priceSetId = variantIdToPriceSetIdMap.get(variantId)
const pricingResult: ProductVariantPricing = {
prices: [] as MoneyAmount[],
original_price: null,
calculated_price: null,
calculated_price_type: null,
original_price_includes_tax: null,
calculated_price_includes_tax: null,
original_price_incl_tax: null,
calculated_price_incl_tax: null,
original_tax: null,
calculated_tax: null,
tax_rates: null,
}
if (priceSetId) {
const calculatedPrices: CalculatedPriceSet | undefined =
calculatedPriceMap.get(priceSetId)
if (calculatedPrices) {
pricingResult.prices.push({
id: calculatedPrices?.original_price?.id,
currency_code: calculatedPrices.currency_code,
amount: calculatedPrices.original_amount,
min_quantity: calculatedPrices.original_price?.min_quantity,
max_quantity: calculatedPrices.original_price?.max_quantity,
price_list_id: calculatedPrices.original_price?.price_list_id,
} as MoneyAmount)
if (
calculatedPrices.calculated_price?.id !==
calculatedPrices.original_price?.id
) {
pricingResult.prices.push({
id: calculatedPrices.calculated_price?.id,
currency_code: calculatedPrices.currency_code,
amount: calculatedPrices.calculated_amount,
min_quantity: calculatedPrices.calculated_price?.min_quantity,
max_quantity: calculatedPrices.calculated_price?.max_quantity,
price_list_id: calculatedPrices.calculated_price?.price_list_id,
} as MoneyAmount)
}
pricingResult.original_price = calculatedPrices?.original_amount
pricingResult.calculated_price = calculatedPrices?.calculated_amount
pricingResult.calculated_price_type =
calculatedPrices?.calculated_price?.price_list_type
}
}
pricingResultMap.set(variantId, pricingResult)
})
return pricingResultMap
}
private async getProductVariantPricing_( private async getProductVariantPricing_(
data: { data: {
variantId: string variantId: string
@@ -326,10 +188,6 @@ class PricingService extends TransactionBaseService {
}[], }[],
context: PricingContext context: PricingContext
): Promise<Map<string, ProductVariantPricing>> { ): Promise<Map<string, ProductVariantPricing>> {
if (this.featureFlagRouter.isFeatureEnabled(MedusaV2Flag.key)) {
return await this.getProductVariantPricingModulePricing_(data, context)
}
const variantsPricing = await this.priceSelectionStrategy const variantsPricing = await this.priceSelectionStrategy
.withTransaction(this.activeManager_) .withTransaction(this.activeManager_)
.calculateVariantPrice(data, context.price_selection) .calculateVariantPrice(data, context.price_selection)
@@ -681,165 +539,19 @@ class PricingService extends TransactionBaseService {
}) })
} }
private async getPricingModuleVariantMoneyAmounts(
variantIds: string[]
): Promise<Map<string, MoneyAmount[]>> {
const variables = {
variant_id: variantIds,
take: null,
}
const query = {
product_variant_price_set: {
__args: variables,
fields: ["variant_id", "price_set_id"],
},
}
const variantPriceSets = await this.remoteQuery(query)
const priceSetIdToVariantIdMap: Map<string, string> = new Map(
variantPriceSets.map((variantPriceSet) => [
variantPriceSet.price_set_id,
variantPriceSet.variant_id,
])
)
const priceSetIds: string[] = variantPriceSets.map(
(variantPriceSet) => variantPriceSet.price_set_id
)
const priceSetMoneyAmounts: PriceSetMoneyAmountDTO[] =
await this.pricingModuleService.listPriceSetMoneyAmounts(
{
price_set_id: priceSetIds,
},
{
take: null,
relations: [
"money_amount",
"price_list",
"price_set",
"price_rules",
"price_rules.rule_type",
],
}
)
const variantIdMoneyAmountMap = priceSetMoneyAmounts.reduce(
(map, priceSetMoneyAmount) => {
const variantId = priceSetIdToVariantIdMap.get(
priceSetMoneyAmount.price_set!.id
)
if (!variantId) {
return map
}
const regionId = priceSetMoneyAmount.price_rules!.find(
(pr) => pr.rule_type.rule_attribute === "region_id"
)?.value
delete priceSetMoneyAmount.money_amount?.price_set_money_amount
const moneyAmount = {
...priceSetMoneyAmount.money_amount,
region_id: null as null | string,
price_list_id: priceSetMoneyAmount.price_list?.id ?? null,
price_list: priceSetMoneyAmount.price_list ?? null,
}
if (regionId) {
moneyAmount.region_id = regionId
}
if (map.has(variantId)) {
map.get(variantId).push(moneyAmount)
} else {
map.set(variantId, [moneyAmount])
}
return map
},
new Map()
)
return variantIdMoneyAmountMap
}
async setAdminVariantPricing( async setAdminVariantPricing(
variants: ProductVariant[], variants: ProductVariant[],
context: PriceSelectionContext = {} context: PriceSelectionContext = {}
): Promise<PricedVariant[]> { ): Promise<PricedVariant[]> {
if (!this.featureFlagRouter.isFeatureEnabled(MedusaV2Flag.key)) {
return await this.setVariantPrices(variants, context) return await this.setVariantPrices(variants, context)
} }
const variantIds = variants.map((variant) => variant.id)
const variantIdMoneyAmountMap =
await this.getPricingModuleVariantMoneyAmounts(variantIds)
return variants.map((variant) => {
const pricing: ProductVariantPricing = {
prices: variantIdMoneyAmountMap.get(variant.id) ?? [],
original_price: null,
calculated_price: null,
calculated_price_type: null,
original_price_includes_tax: null,
calculated_price_includes_tax: null,
original_price_incl_tax: null,
calculated_price_incl_tax: null,
original_tax: null,
calculated_tax: null,
tax_rates: null,
}
Object.assign(variant, pricing)
return variant as unknown as PricedVariant
})
}
async setAdminProductPricing( async setAdminProductPricing(
products: Product[] products: Product[]
): Promise<(Product | PricedProduct)[]> { ): Promise<(Product | PricedProduct)[]> {
if (!this.featureFlagRouter.isFeatureEnabled(MedusaV2Flag.key)) {
return await this.setProductPrices(products) return await this.setProductPrices(products)
} }
const variantIds = products
.map((product) => product.variants.map((variant) => variant.id).flat())
.flat()
const variantIdMoneyAmountMap =
await this.getPricingModuleVariantMoneyAmounts(variantIds)
return products.map((product) => {
if (!product?.variants?.length) {
return product
}
product.variants.map((productVariant): PricedVariant => {
const pricing: ProductVariantPricing = {
prices: variantIdMoneyAmountMap.get(productVariant.id) ?? [],
original_price: null,
calculated_price: null,
calculated_price_type: null,
original_price_includes_tax: null,
calculated_price_includes_tax: null,
original_price_incl_tax: null,
calculated_price_incl_tax: null,
original_tax: null,
calculated_tax: null,
tax_rates: null,
}
Object.assign(productVariant, pricing)
return productVariant as unknown as PricedVariant
})
return product
})
}
/** /**
* Gets the prices for a shipping option. * Gets the prices for a shipping option.
* @param shippingOption - the shipping option to get prices for * @param shippingOption - the shipping option to get prices for
@@ -5,11 +5,10 @@ export async function getVariantsFromPriceList(
priceListId: string priceListId: string
) { ) {
const remoteQuery = container.resolve("remoteQuery") const remoteQuery = container.resolve("remoteQuery")
const query = { const query = {
price_list: { price_list: {
__args: { id: [priceListId] }, __args: { id: [priceListId] },
price_set_money_amounts: { prices: {
price_set: { price_set: {
variant_link: { variant: { fields: ["id", "product_id"] } }, variant_link: { variant: { fields: ["id", "product_id"] } },
}, },
@@ -21,8 +20,8 @@ export async function getVariantsFromPriceList(
const variants: ProductVariantDTO[] = [] const variants: ProductVariantDTO[] = []
priceLists.forEach((priceList) => { priceLists.forEach((priceList) => {
priceList.price_set_money_amounts?.forEach((psma) => { priceList.prices?.forEach((price) => {
const variant = psma.price_set?.variant_link?.variant const variant = price.price_set?.variant_link?.variant
if (variant) { if (variant) {
variants.push(variant) variants.push(variant)
@@ -9,7 +9,7 @@ export const defaultPriceRuleData = [
rule_type_id: "rule-type-1", rule_type_id: "rule-type-1",
value: "USD", value: "USD",
price_list_id: "test", price_list_id: "test",
price_set_money_amount_id: "price-set-money-amount-USD", price_id: "price-set-money-amount-USD",
}, },
{ {
id: "price-rule-2", id: "price-rule-2",
@@ -17,6 +17,6 @@ export const defaultPriceRuleData = [
rule_type_id: "rule-type-2", rule_type_id: "rule-type-2",
value: "region_1", value: "region_1",
price_list_id: "test", price_list_id: "test",
price_set_money_amount_id: "price-set-money-amount-EUR", price_id: "price-set-money-amount-EUR",
}, },
] as unknown as CreatePriceRuleDTO[] ] as unknown as CreatePriceRuleDTO[]
@@ -13,17 +13,11 @@ export async function createPriceRules(
const priceRules: PriceRule[] = [] const priceRules: PriceRule[] = []
for (let priceRuleData of pricesRulesData) { for (let priceRuleData of pricesRulesData) {
const priceRuleDataClone: any = { ...priceRuleData } const priceRuleDataClone: CreatePriceRuleDTO = { ...priceRuleData }
priceRuleDataClone.price_set = priceRuleDataClone.price_set_id priceRuleDataClone.price_set_id = priceRuleDataClone.price_set_id
priceRuleDataClone.rule_type_id = priceRuleDataClone.rule_type_id
priceRuleDataClone.rule_type = priceRuleDataClone.rule_type_id priceRuleDataClone.price_id = priceRuleDataClone.price_id
const priceSetMoneyAmountId =
priceRuleDataClone.price_set_money_amount_id ||
priceRuleDataClone.price_set_money_amount?.id
priceRuleDataClone.price_set_money_amount = priceSetMoneyAmountId
const priceRule = manager.create(PriceRule, priceRuleDataClone) const priceRule = manager.create(PriceRule, priceRuleDataClone)
@@ -1,22 +0,0 @@
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { PriceSetMoneyAmount } from "@models"
import { defaultPriceSetMoneyAmountsData } from "./data"
export * from "./data"
export async function createPriceSetMoneyAmounts(
manager: SqlEntityManager,
psmaData: any[] = defaultPriceSetMoneyAmountsData
): Promise<PriceSetMoneyAmount[]> {
const priceSetMoneyAmount: PriceSetMoneyAmount[] = []
for (let data of psmaData) {
const psmar = manager.create(PriceSetMoneyAmount, data)
priceSetMoneyAmount.push(psmar)
}
await manager.persistAndFlush(priceSetMoneyAmount)
return priceSetMoneyAmount
}
@@ -1,6 +1,6 @@
import { CreatePriceSetDTO } from "@medusajs/types" import { CreatePriceSetDTO } from "@medusajs/types"
import { SqlEntityManager } from "@mikro-orm/postgresql" import { SqlEntityManager } from "@mikro-orm/postgresql"
import { PriceSet, PriceSetMoneyAmount } from "@models" import { Price, PriceSet } from "@models"
import { defaultPriceSetsData } from "./data" import { defaultPriceSetsData } from "./data"
export * from "./data" export * from "./data"
@@ -13,21 +13,21 @@ export async function createPriceSets(
for (let priceSetData of priceSetsData) { for (let priceSetData of priceSetsData) {
const priceSetDataClone = { ...priceSetData } const priceSetDataClone = { ...priceSetData }
const psmas = priceSetDataClone.prices || [] const prices = priceSetDataClone.prices || []
delete priceSetDataClone.prices delete priceSetDataClone.prices
let priceSet = manager.create(PriceSet, priceSetDataClone) as PriceSet let priceSet = manager.create(PriceSet, priceSetDataClone) as PriceSet
manager.persist(priceSet) manager.persist(priceSet)
for (let psmaData of psmas) { for (let priceData of prices) {
const psma = manager.create(PriceSetMoneyAmount, { const price = manager.create(Price, {
...psmaData, ...priceData,
price_set_id: priceSet.id, price_set_id: priceSet.id,
title: "test", title: "test",
}) })
manager.persist(psma) manager.persist(price)
} }
await manager.flush() await manager.flush()
@@ -1,4 +1,4 @@
export const defaultPriceSetMoneyAmountsData = [ export const defaultPricesData = [
{ {
id: "price-set-money-amount-USD", id: "price-set-money-amount-USD",
currency_code: "USD", currency_code: "USD",
@@ -0,0 +1,21 @@
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { Price } from "@models"
import { defaultPricesData } from "./data"
export * from "./data"
export async function createPrices(
manager: SqlEntityManager,
pricesData: any[] = defaultPricesData
): Promise<Price[]> {
const prices: Price[] = []
for (let data of pricesData) {
const price = manager.create(Price, data)
prices.push(price)
}
await manager.persistAndFlush(prices)
return prices
}
@@ -1,10 +1,7 @@
import { SqlEntityManager } from "@mikro-orm/postgresql" import { SqlEntityManager } from "@mikro-orm/postgresql"
import { createPrices, defaultPricesData } from "./price"
import { createPriceRules, defaultPriceRuleData } from "./price-rule" import { createPriceRules, defaultPriceRuleData } from "./price-rule"
import { createPriceSets, defaultPriceSetsData } from "./price-set" import { createPriceSets, defaultPriceSetsData } from "./price-set"
import {
createPriceSetMoneyAmounts,
defaultPriceSetMoneyAmountsData,
} from "./price-set-money-amount"
import { createRuleTypes, defaultRuleTypesData } from "./rule-type" import { createRuleTypes, defaultRuleTypesData } from "./rule-type"
jest.setTimeout(30000) jest.setTimeout(30000)
@@ -14,12 +11,12 @@ export async function seedPriceData(
{ {
priceSetsData = defaultPriceSetsData, priceSetsData = defaultPriceSetsData,
priceRuleData = defaultPriceRuleData, priceRuleData = defaultPriceRuleData,
priceSetMoneyAmountsData = defaultPriceSetMoneyAmountsData, pricesData = defaultPricesData,
ruleTypesData = defaultRuleTypesData, ruleTypesData = defaultRuleTypesData,
} = {} } = {}
) { ) {
await createPriceSets(testManager, priceSetsData) await createPriceSets(testManager, priceSetsData)
await createPriceSetMoneyAmounts(testManager, priceSetMoneyAmountsData) await createPrices(testManager, pricesData)
await createRuleTypes(testManager, ruleTypesData) await createRuleTypes(testManager, ruleTypesData)
await createPriceRules(testManager, priceRuleData) await createPriceRules(testManager, priceRuleData)
} }
@@ -57,85 +57,15 @@ moduleIntegrationTestRunner({
describe("PricingModule Service - Calculate Price", () => { describe("PricingModule Service - Calculate Price", () => {
describe("calculatePrices", () => { describe("calculatePrices", () => {
beforeEach(async () => { beforeEach(async () => {
const moneyAmountsData = [
{
id: "psma-PLN",
currency_code: "PLN",
amount: 1000,
min_quantity: 1,
max_quantity: 10,
},
{
id: "psma-company_id-EUR",
currency_code: "EUR",
amount: 500,
min_quantity: 1,
max_quantity: 10,
},
{
id: "psma-company_id-PLN",
currency_code: "PLN",
amount: 400,
min_quantity: 1,
max_quantity: 5,
},
{
id: "psma-region_id-PLN",
currency_code: "PLN",
amount: 300,
min_quantity: 1,
max_quantity: 4,
},
{
id: "psma-region_id+company_id-PLN",
currency_code: "PLN",
amount: 999,
min_quantity: 1,
max_quantity: 10,
},
{
id: "psma-region_id-PLN-5-qty",
currency_code: "PLN",
amount: 250,
min_quantity: 4,
max_quantity: 10,
},
{
id: "psma-region_id_company_id-PL-EUR",
currency_code: "EUR",
amount: 200,
min_quantity: 1,
max_quantity: 3,
},
{
id: "psma-region_id_company_id-PL-EUR-4-qty",
currency_code: "EUR",
amount: 50,
min_quantity: 4,
max_quantity: 10,
},
{
id: "psma-region_id_company_id-PL-EUR-customer-group",
currency_code: "EUR",
amount: 100,
min_quantity: 1,
max_quantity: 3,
},
]
const priceSetsData = [ const priceSetsData = [
{ { id: "price-set-EUR" },
id: "price-set-EUR", { id: "price-set-PLN" },
},
{
id: "price-set-PLN",
},
] as unknown as CreatePriceSetDTO[] ] as unknown as CreatePriceSetDTO[]
const priceSetMoneyAmountsData = [ const pricesData = [
{ {
id: "psma-PLN", id: "price-PLN",
title: "psma PLN", title: "price PLN",
price_set_id: "price-set-PLN", price_set_id: "price-set-PLN",
currency_code: "PLN", currency_code: "PLN",
amount: 1000, amount: 1000,
@@ -144,8 +74,8 @@ moduleIntegrationTestRunner({
rules_count: 0, rules_count: 0,
}, },
{ {
id: "psma-company_id-EUR", id: "price-company_id-EUR",
title: "psma EUR - company_id", title: "price EUR - company_id",
price_set_id: "price-set-EUR", price_set_id: "price-set-EUR",
currency_code: "EUR", currency_code: "EUR",
amount: 500, amount: 500,
@@ -154,8 +84,8 @@ moduleIntegrationTestRunner({
rules_count: 1, rules_count: 1,
}, },
{ {
id: "psma-company_id-PLN", id: "price-company_id-PLN",
title: "psma PLN - company_id", title: "price PLN - company_id",
price_set_id: "price-set-PLN", price_set_id: "price-set-PLN",
currency_code: "PLN", currency_code: "PLN",
amount: 400, amount: 400,
@@ -164,8 +94,8 @@ moduleIntegrationTestRunner({
rules_count: 1, rules_count: 1,
}, },
{ {
id: "psma-region_id-PLN", id: "price-region_id-PLN",
title: "psma PLN - region_id", title: "price PLN - region_id",
price_set_id: "price-set-PLN", price_set_id: "price-set-PLN",
currency_code: "PLN", currency_code: "PLN",
amount: 300, amount: 300,
@@ -174,8 +104,8 @@ moduleIntegrationTestRunner({
rules_count: 1, rules_count: 1,
}, },
{ {
id: "psma-region_id+company_id-PLN", id: "price-region_id+company_id-PLN",
title: "psma region_id + company_id", title: "price region_id + company_id",
price_set_id: "price-set-PLN", price_set_id: "price-set-PLN",
currency_code: "PLN", currency_code: "PLN",
amount: 999, amount: 999,
@@ -184,8 +114,8 @@ moduleIntegrationTestRunner({
rules_count: 2, rules_count: 2,
}, },
{ {
id: "psma-region_id-PLN-5-qty", id: "price-region_id-PLN-5-qty",
title: "psma PLN - region_id 5 qty", title: "price PLN - region_id 5 qty",
price_set_id: "price-set-PLN", price_set_id: "price-set-PLN",
currency_code: "PLN", currency_code: "PLN",
amount: 250, amount: 250,
@@ -194,8 +124,8 @@ moduleIntegrationTestRunner({
rules_count: 1, rules_count: 1,
}, },
{ {
id: "psma-region_id_company_id-PL-EUR", id: "price-region_id_company_id-PL-EUR",
title: "psma PLN - region_id PL with EUR currency", title: "price PLN - region_id PL with EUR currency",
price_set_id: "price-set-PLN", price_set_id: "price-set-PLN",
currency_code: "EUR", currency_code: "EUR",
amount: 200, amount: 200,
@@ -204,8 +134,9 @@ moduleIntegrationTestRunner({
rules_count: 2, rules_count: 2,
}, },
{ {
id: "psma-region_id_company_id-PL-EUR-4-qty", id: "price-region_id_company_id-PL-EUR-4-qty",
title: "psma PLN - region_id PL with EUR currency for quantity 4", title:
"price PLN - region_id PL with EUR currency for quantity 4",
price_set_id: "price-set-PLN", price_set_id: "price-set-PLN",
currency_code: "EUR", currency_code: "EUR",
amount: 50, amount: 50,
@@ -214,9 +145,9 @@ moduleIntegrationTestRunner({
rules_count: 2, rules_count: 2,
}, },
{ {
id: "psma-region_id_company_id-PL-EUR-customer-group", id: "price-region_id_company_id-PL-EUR-customer-group",
title: title:
"psma PLN - region_id PL with EUR currency for customer group", "price PLN - region_id PL with EUR currency for customer group",
price_set_id: "price-set-PLN", price_set_id: "price-set-PLN",
currency_code: "EUR", currency_code: "EUR",
amount: 100, amount: 100,
@@ -254,7 +185,7 @@ moduleIntegrationTestRunner({
rule_type_id: "rule-type-company_id", rule_type_id: "rule-type-company_id",
value: "EUR", value: "EUR",
price_list_id: "test", price_list_id: "test",
price_set_money_amount_id: "psma-company_id-EUR", price_id: "price-company_id-EUR",
}, },
{ {
id: "price-rule-company_id-PLN", id: "price-rule-company_id-PLN",
@@ -262,7 +193,7 @@ moduleIntegrationTestRunner({
rule_type_id: "rule-type-company_id", rule_type_id: "rule-type-company_id",
value: "medusa-company-id", value: "medusa-company-id",
price_list_id: "test", price_list_id: "test",
price_set_money_amount_id: "psma-company_id-PLN", price_id: "price-company_id-PLN",
}, },
{ {
id: "price-rule-region_id-PLN", id: "price-rule-region_id-PLN",
@@ -270,7 +201,7 @@ moduleIntegrationTestRunner({
rule_type_id: "rule-type-region_id", rule_type_id: "rule-type-region_id",
value: "PL", value: "PL",
price_list_id: "test", price_list_id: "test",
price_set_money_amount_id: "psma-region_id-PLN", price_id: "price-region_id-PLN",
}, },
{ {
id: "price-rule-region_id+company_id-PL", id: "price-rule-region_id+company_id-PL",
@@ -278,7 +209,7 @@ moduleIntegrationTestRunner({
rule_type_id: "rule-type-region_id", rule_type_id: "rule-type-region_id",
value: "PL", value: "PL",
price_list_id: "test", price_list_id: "test",
price_set_money_amount_id: "psma-region_id+company_id-PLN", price_id: "price-region_id+company_id-PLN",
}, },
{ {
id: "price-rule-region_id+company_id-medusa-company-id", id: "price-rule-region_id+company_id-medusa-company-id",
@@ -286,7 +217,7 @@ moduleIntegrationTestRunner({
rule_type_id: "rule-type-company_id", rule_type_id: "rule-type-company_id",
value: "medusa-company-id", value: "medusa-company-id",
price_list_id: "test", price_list_id: "test",
price_set_money_amount_id: "psma-region_id+company_id-PLN", price_id: "price-region_id+company_id-PLN",
}, },
{ {
id: "price-rule-region_id-PLN-5-qty", id: "price-rule-region_id-PLN-5-qty",
@@ -294,7 +225,7 @@ moduleIntegrationTestRunner({
rule_type_id: "rule-type-region_id", rule_type_id: "rule-type-region_id",
value: "PL", value: "PL",
price_list_id: "test", price_list_id: "test",
price_set_money_amount_id: "psma-region_id-PLN-5-qty", price_id: "price-region_id-PLN-5-qty",
}, },
{ {
id: "price-rule-region_id-company_id-PL", id: "price-rule-region_id-company_id-PL",
@@ -302,7 +233,7 @@ moduleIntegrationTestRunner({
rule_type_id: "rule-type-region_id", rule_type_id: "rule-type-region_id",
value: "PL", value: "PL",
price_list_id: "test", price_list_id: "test",
price_set_money_amount_id: "psma-region_id_company_id-PL-EUR", price_id: "price-region_id_company_id-PL-EUR",
}, },
{ {
id: "price-rule-region_id-company_id-PLN", id: "price-rule-region_id-company_id-PLN",
@@ -310,7 +241,7 @@ moduleIntegrationTestRunner({
rule_type_id: "rule-type-company_id", rule_type_id: "rule-type-company_id",
value: "medusa-company-id", value: "medusa-company-id",
price_list_id: "test", price_list_id: "test",
price_set_money_amount_id: "psma-region_id_company_id-PL-EUR", price_id: "price-region_id_company_id-PL-EUR",
}, },
{ {
id: "price-rule-region_id-company_id-PL-4-qty", id: "price-rule-region_id-company_id-PL-4-qty",
@@ -318,8 +249,7 @@ moduleIntegrationTestRunner({
rule_type_id: "rule-type-region_id", rule_type_id: "rule-type-region_id",
value: "PL", value: "PL",
price_list_id: "test", price_list_id: "test",
price_set_money_amount_id: price_id: "price-region_id_company_id-PL-EUR-4-qty",
"psma-region_id_company_id-PL-EUR-4-qty",
}, },
{ {
id: "price-rule-region_id-company_id-PLN-4-qty", id: "price-rule-region_id-company_id-PLN-4-qty",
@@ -327,8 +257,7 @@ moduleIntegrationTestRunner({
rule_type_id: "rule-type-company_id", rule_type_id: "rule-type-company_id",
value: "medusa-company-id", value: "medusa-company-id",
price_list_id: "test", price_list_id: "test",
price_set_money_amount_id: price_id: "price-region_id_company_id-PL-EUR-4-qty",
"psma-region_id_company_id-PL-EUR-4-qty",
}, },
{ {
id: "price-rule-region_id-currency_customer_group_code-PL", id: "price-rule-region_id-currency_customer_group_code-PL",
@@ -336,8 +265,7 @@ moduleIntegrationTestRunner({
rule_type_id: "rule-type-region_id", rule_type_id: "rule-type-region_id",
value: "PL", value: "PL",
price_list_id: "test", price_list_id: "test",
price_set_money_amount_id: price_id: "price-region_id_company_id-PL-EUR-customer-group",
"psma-region_id_company_id-PL-EUR-customer-group",
}, },
{ {
id: "price-rule-region_id-currency_customer_group_code-PLN", id: "price-rule-region_id-currency_customer_group_code-PLN",
@@ -345,8 +273,7 @@ moduleIntegrationTestRunner({
rule_type_id: "rule-type-company_id", rule_type_id: "rule-type-company_id",
value: "medusa-company-id", value: "medusa-company-id",
price_list_id: "test", price_list_id: "test",
price_set_money_amount_id: price_id: "price-region_id_company_id-PL-EUR-customer-group",
"psma-region_id_company_id-PL-EUR-customer-group",
}, },
{ {
id: "price-rule-region_id-currency_customer_group_code-test_customer_group", id: "price-rule-region_id-currency_customer_group_code-test_customer_group",
@@ -354,15 +281,13 @@ moduleIntegrationTestRunner({
rule_type_id: "rule-type-customer_group_id", rule_type_id: "rule-type-customer_group_id",
value: "test-customer-group", value: "test-customer-group",
price_list_id: "test", price_list_id: "test",
price_set_money_amount_id: price_id: "price-region_id_company_id-PL-EUR-customer-group",
"psma-region_id_company_id-PL-EUR-customer-group",
}, },
] as unknown as CreatePriceRuleDTO[] ] as unknown as CreatePriceRuleDTO[]
await seedPriceData(MikroOrmWrapper.forkManager(), { await seedPriceData(MikroOrmWrapper.forkManager(), {
moneyAmountsData,
priceSetsData, priceSetsData,
priceSetMoneyAmountsData, pricesData,
priceRuleData, priceRuleData,
ruleTypesData, ruleTypesData,
}) })
@@ -427,14 +352,14 @@ moduleIntegrationTestRunner({
original_amount: 1000, original_amount: 1000,
currency_code: "PLN", currency_code: "PLN",
calculated_price: { calculated_price: {
id: "psma-PLN", id: "price-PLN",
price_list_id: null, price_list_id: null,
price_list_type: null, price_list_type: null,
min_quantity: 1, min_quantity: 1,
max_quantity: 10, max_quantity: 10,
}, },
original_price: { original_price: {
id: "psma-PLN", id: "price-PLN",
price_list_id: null, price_list_id: null,
price_list_type: null, price_list_type: null,
min_quantity: 1, min_quantity: 1,
@@ -483,14 +408,14 @@ moduleIntegrationTestRunner({
original_amount: 300, original_amount: 300,
currency_code: "PLN", currency_code: "PLN",
calculated_price: { calculated_price: {
id: "psma-region_id-PLN", id: "price-region_id-PLN",
price_list_id: null, price_list_id: null,
price_list_type: null, price_list_type: null,
min_quantity: 1, min_quantity: 1,
max_quantity: 4, max_quantity: 4,
}, },
original_price: { original_price: {
id: "psma-region_id-PLN", id: "price-region_id-PLN",
price_list_id: null, price_list_id: null,
price_list_type: null, price_list_type: null,
min_quantity: 1, min_quantity: 1,
@@ -539,14 +464,14 @@ moduleIntegrationTestRunner({
original_amount: 1000, original_amount: 1000,
currency_code: "PLN", currency_code: "PLN",
calculated_price: { calculated_price: {
id: "psma-PLN", id: "price-PLN",
price_list_id: null, price_list_id: null,
price_list_type: null, price_list_type: null,
min_quantity: 1, min_quantity: 1,
max_quantity: 10, max_quantity: 10,
}, },
original_price: { original_price: {
id: "psma-PLN", id: "price-PLN",
price_list_id: null, price_list_id: null,
price_list_type: null, price_list_type: null,
min_quantity: 1, min_quantity: 1,
@@ -651,14 +576,14 @@ moduleIntegrationTestRunner({
original_amount: 300, original_amount: 300,
currency_code: "PLN", currency_code: "PLN",
calculated_price: { calculated_price: {
id: "psma-region_id-PLN", id: "price-region_id-PLN",
price_list_id: null, price_list_id: null,
price_list_type: null, price_list_type: null,
min_quantity: 1, min_quantity: 1,
max_quantity: 4, max_quantity: 4,
}, },
original_price: { original_price: {
id: "psma-region_id-PLN", id: "price-region_id-PLN",
price_list_id: null, price_list_id: null,
price_list_type: null, price_list_type: null,
min_quantity: 1, min_quantity: 1,
@@ -707,14 +632,14 @@ moduleIntegrationTestRunner({
original_amount: 1000, original_amount: 1000,
currency_code: "PLN", currency_code: "PLN",
calculated_price: { calculated_price: {
id: "psma-PLN", id: "price-PLN",
price_list_id: null, price_list_id: null,
price_list_type: null, price_list_type: null,
min_quantity: 1, min_quantity: 1,
max_quantity: 10, max_quantity: 10,
}, },
original_price: { original_price: {
id: "psma-PLN", id: "price-PLN",
price_list_id: null, price_list_id: null,
price_list_type: null, price_list_type: null,
min_quantity: 1, min_quantity: 1,
@@ -741,14 +666,14 @@ moduleIntegrationTestRunner({
original_amount: 250, original_amount: 250,
currency_code: "PLN", currency_code: "PLN",
calculated_price: { calculated_price: {
id: "psma-region_id-PLN-5-qty", id: "price-region_id-PLN-5-qty",
price_list_id: null, price_list_id: null,
price_list_type: null, price_list_type: null,
min_quantity: 4, min_quantity: 4,
max_quantity: 10, max_quantity: 10,
}, },
original_price: { original_price: {
id: "psma-region_id-PLN-5-qty", id: "price-region_id-PLN-5-qty",
price_list_id: null, price_list_id: null,
price_list_type: null, price_list_type: null,
min_quantity: 4, min_quantity: 4,
@@ -802,14 +727,14 @@ moduleIntegrationTestRunner({
original_amount: 300, original_amount: 300,
currency_code: "PLN", currency_code: "PLN",
calculated_price: { calculated_price: {
id: "psma-region_id-PLN", id: "price-region_id-PLN",
price_list_id: null, price_list_id: null,
price_list_type: null, price_list_type: null,
min_quantity: 1, min_quantity: 1,
max_quantity: 4, max_quantity: 4,
}, },
original_price: { original_price: {
id: "psma-region_id-PLN", id: "price-region_id-PLN",
price_list_id: null, price_list_id: null,
price_list_type: null, price_list_type: null,
min_quantity: 1, min_quantity: 1,
@@ -864,14 +789,14 @@ moduleIntegrationTestRunner({
original_amount: 100, original_amount: 100,
currency_code: "EUR", currency_code: "EUR",
calculated_price: { calculated_price: {
id: "psma-region_id_company_id-PL-EUR-customer-group", id: "price-region_id_company_id-PL-EUR-customer-group",
price_list_id: null, price_list_id: null,
price_list_type: null, price_list_type: null,
min_quantity: 1, min_quantity: 1,
max_quantity: 3, max_quantity: 3,
}, },
original_price: { original_price: {
id: "psma-region_id_company_id-PL-EUR-customer-group", id: "price-region_id_company_id-PL-EUR-customer-group",
price_list_id: null, price_list_id: null,
price_list_type: null, price_list_type: null,
min_quantity: 1, min_quantity: 1,
@@ -926,14 +851,14 @@ moduleIntegrationTestRunner({
original_amount: 300, original_amount: 300,
currency_code: "PLN", currency_code: "PLN",
calculated_price: { calculated_price: {
id: "psma-region_id-PLN", id: "price-region_id-PLN",
price_list_id: null, price_list_id: null,
price_list_type: null, price_list_type: null,
min_quantity: 1, min_quantity: 1,
max_quantity: 4, max_quantity: 4,
}, },
original_price: { original_price: {
id: "psma-region_id-PLN", id: "price-region_id-PLN",
price_list_id: null, price_list_id: null,
price_list_type: null, price_list_type: null,
min_quantity: 1, min_quantity: 1,
@@ -988,14 +913,14 @@ moduleIntegrationTestRunner({
original_amount: 1000, original_amount: 1000,
currency_code: "PLN", currency_code: "PLN",
calculated_price: { calculated_price: {
id: "psma-PLN", id: "price-PLN",
price_list_id: null, price_list_id: null,
price_list_type: null, price_list_type: null,
min_quantity: 1, min_quantity: 1,
max_quantity: 10, max_quantity: 10,
}, },
original_price: { original_price: {
id: "psma-PLN", id: "price-PLN",
price_list_id: null, price_list_id: null,
price_list_type: null, price_list_type: null,
min_quantity: 1, min_quantity: 1,
@@ -1104,14 +1029,14 @@ moduleIntegrationTestRunner({
original_amount: 300, original_amount: 300,
currency_code: "PLN", currency_code: "PLN",
calculated_price: { calculated_price: {
id: "psma-region_id-PLN", id: "price-region_id-PLN",
price_list_id: null, price_list_id: null,
price_list_type: null, price_list_type: null,
min_quantity: 1, min_quantity: 1,
max_quantity: 4, max_quantity: 4,
}, },
original_price: { original_price: {
id: "psma-region_id-PLN", id: "price-region_id-PLN",
price_list_id: null, price_list_id: null,
price_list_type: null, price_list_type: null,
min_quantity: 1, min_quantity: 1,
@@ -1487,14 +1412,14 @@ moduleIntegrationTestRunner({
original_amount: 300, original_amount: 300,
currency_code: "PLN", currency_code: "PLN",
calculated_price: { calculated_price: {
id: "psma-region_id-PLN", id: "price-region_id-PLN",
price_list_id: null, price_list_id: null,
price_list_type: null, price_list_type: null,
min_quantity: 1, min_quantity: 1,
max_quantity: 4, max_quantity: 4,
}, },
original_price: { original_price: {
id: "psma-region_id-PLN", id: "price-region_id-PLN",
price_list_id: null, price_list_id: null,
price_list_type: null, price_list_type: null,
min_quantity: 1, min_quantity: 1,
@@ -1700,14 +1625,14 @@ moduleIntegrationTestRunner({
original_amount: 400, original_amount: 400,
currency_code: "PLN", currency_code: "PLN",
calculated_price: { calculated_price: {
id: "psma-company_id-PLN", id: "price-company_id-PLN",
price_list_id: null, price_list_id: null,
price_list_type: null, price_list_type: null,
min_quantity: 1, min_quantity: 1,
max_quantity: 5, max_quantity: 5,
}, },
original_price: { original_price: {
id: "psma-company_id-PLN", id: "price-company_id-PLN",
price_list_id: null, price_list_id: null,
price_list_type: null, price_list_type: null,
min_quantity: 1, min_quantity: 1,
@@ -1775,14 +1700,14 @@ moduleIntegrationTestRunner({
original_amount: 400, original_amount: 400,
currency_code: "PLN", currency_code: "PLN",
calculated_price: { calculated_price: {
id: "psma-company_id-PLN", id: "price-company_id-PLN",
price_list_id: null, price_list_id: null,
price_list_type: null, price_list_type: null,
min_quantity: 1, min_quantity: 1,
max_quantity: 5, max_quantity: 5,
}, },
original_price: { original_price: {
id: "psma-company_id-PLN", id: "price-company_id-PLN",
price_list_id: null, price_list_id: null,
price_list_type: null, price_list_type: null,
min_quantity: 1, min_quantity: 1,
@@ -273,17 +273,17 @@ moduleIntegrationTestRunner({
{ id: [createdId] }, { id: [createdId] },
{ {
relations: [ relations: [
"price_set_money_amounts", "prices",
"price_set_money_amounts.price_set", "prices.price_set",
"price_list_rules.price_list_rule_values", "price_list_rules.price_list_rule_values",
"price_list_rules.rule_type", "price_list_rules.rule_type",
], ],
select: [ select: [
"id", "id",
"starts_at", "starts_at",
"price_set_money_amounts.amount", "prices.amount",
"price_set_money_amounts.currency_code", "prices.currency_code",
"price_set_money_amounts.price_list_id", "prices.price_list_id",
"price_list_rules.price_list_rule_values.value", "price_list_rules.price_list_rule_values.value",
"price_list_rules.rule_type.rule_attribute", "price_list_rules.rule_type.rule_attribute",
], ],
@@ -294,7 +294,7 @@ moduleIntegrationTestRunner({
expect.objectContaining({ expect.objectContaining({
id: expect.any(String), id: expect.any(String),
starts_at: updateDate, starts_at: updateDate,
price_set_money_amounts: expect.arrayContaining([ prices: expect.arrayContaining([
expect.objectContaining({ expect.objectContaining({
price_list: expect.objectContaining({ price_list: expect.objectContaining({
id: expect.any(String), id: expect.any(String),
@@ -428,16 +428,16 @@ moduleIntegrationTestRunner({
}, },
{ {
relations: [ relations: [
"price_set_money_amounts", "prices",
"price_set_money_amounts.price_set", "prices.price_set",
"price_list_rules.price_list_rule_values", "price_list_rules.price_list_rule_values",
"price_list_rules.rule_type", "price_list_rules.rule_type",
], ],
select: [ select: [
"id", "id",
"price_set_money_amounts.amount", "prices.amount",
"price_set_money_amounts.currency_code", "prices.currency_code",
"price_set_money_amounts.price_list_id", "prices.price_list_id",
"price_list_rules.price_list_rule_values.value", "price_list_rules.price_list_rule_values.value",
"price_list_rules.rule_type.rule_attribute", "price_list_rules.rule_type.rule_attribute",
], ],
@@ -447,7 +447,7 @@ moduleIntegrationTestRunner({
expect(priceList).toEqual( expect(priceList).toEqual(
expect.objectContaining({ expect.objectContaining({
id: expect.any(String), id: expect.any(String),
price_set_money_amounts: expect.arrayContaining([ prices: expect.arrayContaining([
expect.objectContaining({ expect.objectContaining({
price_list: expect.objectContaining({ price_list: expect.objectContaining({
id: expect.any(String), id: expect.any(String),
@@ -534,19 +534,19 @@ moduleIntegrationTestRunner({
}, },
{ {
relations: [ relations: [
"price_set_money_amounts", "prices",
"price_set_money_amounts.price_set", "prices.price_set",
"price_set_money_amounts.price_rules", "prices.price_rules",
"price_list_rules.price_list_rule_values", "price_list_rules.price_list_rule_values",
"price_list_rules.rule_type", "price_list_rules.rule_type",
], ],
select: [ select: [
"id", "id",
"price_set_money_amounts.price_rules.value", "prices.price_rules.value",
"price_set_money_amounts.rules_count", "prices.rules_count",
"price_set_money_amounts.amount", "prices.amount",
"price_set_money_amounts.currency_code", "prices.currency_code",
"price_set_money_amounts.price_list_id", "prices.price_list_id",
"price_list_rules.price_list_rule_values.value", "price_list_rules.price_list_rule_values.value",
"price_list_rules.rule_type.rule_attribute", "price_list_rules.rule_type.rule_attribute",
], ],
@@ -556,7 +556,7 @@ moduleIntegrationTestRunner({
expect(priceList).toEqual( expect(priceList).toEqual(
expect.objectContaining({ expect.objectContaining({
id: expect.any(String), id: expect.any(String),
price_set_money_amounts: expect.arrayContaining([ prices: expect.arrayContaining([
expect.objectContaining({ expect.objectContaining({
rules_count: 1, rules_count: 1,
price_rules: expect.arrayContaining([ price_rules: expect.arrayContaining([
@@ -673,19 +673,19 @@ moduleIntegrationTestRunner({
}, },
{ {
relations: [ relations: [
"price_set_money_amounts", "prices",
"price_set_money_amounts.price_set", "prices.price_set",
"price_set_money_amounts.price_rules", "prices.price_rules",
"price_list_rules.price_list_rule_values", "price_list_rules.price_list_rule_values",
"price_list_rules.rule_type", "price_list_rules.rule_type",
], ],
select: [ select: [
"id", "id",
"price_set_money_amounts.price_rules.value", "prices.price_rules.value",
"price_set_money_amounts.rules_count", "prices.rules_count",
"price_set_money_amounts.amount", "prices.amount",
"price_set_money_amounts.currency_code", "prices.currency_code",
"price_set_money_amounts.price_list_id", "prices.price_list_id",
"price_list_rules.price_list_rule_values.value", "price_list_rules.price_list_rule_values.value",
"price_list_rules.rule_type.rule_attribute", "price_list_rules.rule_type.rule_attribute",
], ],
@@ -695,7 +695,7 @@ moduleIntegrationTestRunner({
expect(priceList).toEqual( expect(priceList).toEqual(
expect.objectContaining({ expect.objectContaining({
id: expect.any(String), id: expect.any(String),
price_set_money_amounts: expect.arrayContaining([ prices: expect.arrayContaining([
expect.objectContaining({ expect.objectContaining({
rules_count: 0, rules_count: 0,
price_list: expect.objectContaining({ price_list: expect.objectContaining({
@@ -782,21 +782,21 @@ moduleIntegrationTestRunner({
}, },
{ {
relations: [ relations: [
"price_set_money_amounts", "prices",
"price_set_money_amounts.price_set", "prices.price_set",
"price_set_money_amounts.price_rules", "prices.price_rules",
"price_set_money_amounts.price_rules.rule_type", "prices.price_rules.rule_type",
"price_list_rules.price_list_rule_values", "price_list_rules.price_list_rule_values",
"price_list_rules.rule_type", "price_list_rules.rule_type",
], ],
select: [ select: [
"id", "id",
"price_set_money_amounts.price_rules.value", "prices.price_rules.value",
"price_set_money_amounts.price_rules.rule_type.rule_attribute", "prices.price_rules.rule_type.rule_attribute",
"price_set_money_amounts.rules_count", "prices.rules_count",
"price_set_money_amounts.amount", "prices.amount",
"price_set_money_amounts.currency_code", "prices.currency_code",
"price_set_money_amounts.price_list_id", "prices.price_list_id",
"price_list_rules.price_list_rule_values.value", "price_list_rules.price_list_rule_values.value",
"price_list_rules.rule_type.rule_attribute", "price_list_rules.rule_type.rule_attribute",
], ],
@@ -806,7 +806,7 @@ moduleIntegrationTestRunner({
expect(priceList).toEqual( expect(priceList).toEqual(
expect.objectContaining({ expect.objectContaining({
id: expect.any(String), id: expect.any(String),
price_set_money_amounts: expect.arrayContaining([ prices: expect.arrayContaining([
expect.objectContaining({ expect.objectContaining({
rules_count: 1, rules_count: 1,
price_list: expect.objectContaining({ price_list: expect.objectContaining({
@@ -878,21 +878,21 @@ moduleIntegrationTestRunner({
{ id: ["price-list-1"] }, { id: ["price-list-1"] },
{ {
relations: [ relations: [
"price_set_money_amounts", "prices",
"price_set_money_amounts.price_set", "prices.price_set",
"price_set_money_amounts.price_rules", "prices.price_rules",
"price_set_money_amounts.price_rules.rule_type", "prices.price_rules.rule_type",
"price_list_rules.price_list_rule_values", "price_list_rules.price_list_rule_values",
"price_list_rules.rule_type", "price_list_rules.rule_type",
], ],
select: [ select: [
"id", "id",
"price_set_money_amounts.price_rules.value", "prices.price_rules.value",
"price_set_money_amounts.price_rules.rule_type.rule_attribute", "prices.price_rules.rule_type.rule_attribute",
"price_set_money_amounts.rules_count", "prices.rules_count",
"price_set_money_amounts.amount", "prices.amount",
"price_set_money_amounts.currency_code", "prices.currency_code",
"price_set_money_amounts.price_list_id", "prices.price_list_id",
"price_list_rules.price_list_rule_values.value", "price_list_rules.price_list_rule_values.value",
"price_list_rules.rule_type.rule_attribute", "price_list_rules.rule_type.rule_attribute",
], ],
@@ -902,7 +902,7 @@ moduleIntegrationTestRunner({
expect(priceList).toEqual( expect(priceList).toEqual(
expect.objectContaining({ expect.objectContaining({
id: expect.any(String), id: expect.any(String),
price_set_money_amounts: expect.arrayContaining([ prices: expect.arrayContaining([
expect.objectContaining({ expect.objectContaining({
rules_count: 2, rules_count: 2,
price_rules: expect.arrayContaining([ price_rules: expect.arrayContaining([
@@ -1000,26 +1000,24 @@ moduleIntegrationTestRunner({
let [priceList] = await service.listPriceLists( let [priceList] = await service.listPriceLists(
{ id: ["price-list-1"] }, { id: ["price-list-1"] },
{ {
relations: ["price_set_money_amounts"], relations: ["prices"],
select: ["price_set_money_amounts.id"], select: ["prices.id"],
} }
) )
await service.removePrices( await service.removePrices(priceList.prices!.map((price) => price.id))
priceList.price_set_money_amounts!.map((psma) => psma.id)
)
;[priceList] = await service.listPriceLists( ;[priceList] = await service.listPriceLists(
{ id: ["price-list-1"] }, { id: ["price-list-1"] },
{ {
relations: ["price_set_money_amounts"], relations: ["prices"],
select: ["id", "price_set_money_amounts.id"], select: ["id", "prices.id"],
} }
) )
expect(priceList).toEqual( expect(priceList).toEqual(
expect.objectContaining({ expect.objectContaining({
id: expect.any(String), id: expect.any(String),
price_set_money_amounts: [], prices: [],
}) })
) )
}) })
@@ -1,11 +1,11 @@
import { Modules } from "@medusajs/modules-sdk" import { Modules } from "@medusajs/modules-sdk"
import { CreatePriceRuleDTO, IPricingModuleService } from "@medusajs/types" import { IPricingModuleService } from "@medusajs/types"
import { SqlEntityManager } from "@mikro-orm/postgresql" import { SqlEntityManager } from "@mikro-orm/postgresql"
import { SuiteOptions, moduleIntegrationTestRunner } from "medusa-test-utils" import { SuiteOptions, moduleIntegrationTestRunner } from "medusa-test-utils"
import { PriceSetMoneyAmount } from "../../../../src" import { Price } from "../../../../src"
import { createPrices } from "../../../__fixtures__/price"
import { createPriceRules } from "../../../__fixtures__/price-rule" import { createPriceRules } from "../../../__fixtures__/price-rule"
import { createPriceSets } from "../../../__fixtures__/price-set" import { createPriceSets } from "../../../__fixtures__/price-set"
import { createPriceSetMoneyAmounts } from "../../../__fixtures__/price-set-money-amount"
import { createRuleTypes } from "../../../__fixtures__/rule-type" import { createRuleTypes } from "../../../__fixtures__/rule-type"
jest.setTimeout(30000) jest.setTimeout(30000)
@@ -23,7 +23,7 @@ moduleIntegrationTestRunner({
await createPriceSets(testManager) await createPriceSets(testManager)
await createRuleTypes(testManager) await createRuleTypes(testManager)
await createPriceSetMoneyAmounts(testManager) await createPrices(testManager)
await createPriceRules(testManager) await createPriceRules(testManager)
}) })
@@ -73,6 +73,7 @@ moduleIntegrationTestRunner({
price_set: { price_set: {
id: "price-set-1", id: "price-set-1",
}, },
price_set_id: "price-set-1",
}, },
]) ])
}) })
@@ -272,38 +273,33 @@ moduleIntegrationTestRunner({
}) })
it("should create a PriceRule successfully", async () => { it("should create a PriceRule successfully", async () => {
const psma: PriceSetMoneyAmount = testManager.create( const price: Price = testManager.create(Price, {
PriceSetMoneyAmount,
{
currency_code: "EUR", currency_code: "EUR",
amount: 100, amount: 100,
price_set_id: "price-set-1", price_set_id: "price-set-1",
title: "test", title: "test",
rules_count: 0, rules_count: 0,
} })
)
await testManager.persist(psma).flush() await testManager.persist(price).flush()
await service.createPriceRules([ await service.createPriceRules({
{
id: "price-rule-new", id: "price-rule-new",
price_set_id: "price-set-1", price_set_id: "price-set-1",
rule_type_id: "rule-type-1", rule_type_id: "rule-type-1",
value: "region_1", value: "region_1",
price_list_id: "test", price_list_id: "test",
price_set_money_amount_id: psma.id, price_id: price.id,
} as unknown as CreatePriceRuleDTO, })
])
const [pricerule] = await service.listPriceRules({ const [priceRule] = await service.listPriceRules({
id: ["price-rule-new"], id: ["price-rule-new"],
}) })
expect(pricerule).toEqual( expect(priceRule).toEqual(
expect.objectContaining({ expect.objectContaining({
id: "price-rule-new", id: "price-rule-new",
} as unknown as CreatePriceRuleDTO) })
) )
}) })
}) })
@@ -1,11 +1,10 @@
import { Modules } from "@medusajs/modules-sdk"
import { import {
CreatePriceSetDTO, CreatePriceSetDTO,
CreatePriceSetRuleTypeDTO, CreatePriceSetRuleTypeDTO,
IPricingModuleService, IPricingModuleService,
} from "@medusajs/types" } from "@medusajs/types"
import { SqlEntityManager } from "@mikro-orm/postgresql" import { SqlEntityManager } from "@mikro-orm/postgresql"
import { Modules } from "@medusajs/modules-sdk"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils" import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
import { PriceSetRuleType } from "../../../../src" import { PriceSetRuleType } from "../../../../src"
import { seedPriceData } from "../../../__fixtures__/seed-price-data" import { seedPriceData } from "../../../__fixtures__/seed-price-data"
@@ -39,14 +38,14 @@ moduleIntegrationTestRunner({
await seedPriceData(testManager) await seedPriceData(testManager)
await createPriceSetPriceRules(testManager, [ await createPriceSetPriceRules(testManager, [
{ {
price_set: "price-set-1", price_set_id: "price-set-1",
rule_type: "rule-type-1", rule_type_id: "rule-type-1",
}, },
{ {
price_set: "price-set-2", price_set_id: "price-set-2",
rule_type: "rule-type-2", rule_type_id: "rule-type-2",
}, },
] as unknown as CreatePriceSetRuleTypeDTO[]) ])
}) })
describe("list", () => { describe("list", () => {
@@ -84,12 +83,8 @@ moduleIntegrationTestRunner({
id: ["price-set-1"], id: ["price-set-1"],
}, },
{ {
select: [ select: ["id", "prices.id", "prices.amount"],
"id", relations: ["prices"],
"price_set_money_amounts.id",
"price_set_money_amounts.amount",
],
relations: ["price_set_money_amounts"],
} }
) )
@@ -98,7 +93,7 @@ moduleIntegrationTestRunner({
expect(serialized).toEqual([ expect(serialized).toEqual([
{ {
id: "price-set-1", id: "price-set-1",
price_set_money_amounts: [ prices: [
expect.objectContaining({ expect.objectContaining({
id: "price-set-money-amount-USD", id: "price-set-money-amount-USD",
amount: 500, amount: 500,
@@ -146,12 +141,8 @@ moduleIntegrationTestRunner({
id: ["price-set-1"], id: ["price-set-1"],
}, },
{ {
select: [ select: ["id", "prices.amount", "prices.id"],
"id", relations: ["prices"],
"price_set_money_amounts.amount",
"price_set_money_amounts.id",
],
relations: ["price_set_money_amounts"],
} }
) )
@@ -161,7 +152,7 @@ moduleIntegrationTestRunner({
expect(serialized).toEqual([ expect(serialized).toEqual([
{ {
id: "price-set-1", id: "price-set-1",
price_set_money_amounts: [ prices: [
expect.objectContaining({ expect.objectContaining({
id: "price-set-money-amount-USD", id: "price-set-money-amount-USD",
amount: 500, amount: 500,
@@ -379,7 +370,7 @@ moduleIntegrationTestRunner({
rule_attribute: "region_id", rule_attribute: "region_id",
}), }),
], ],
price_set_money_amounts: [ prices: [
expect.objectContaining({ expect.objectContaining({
amount: 100, amount: 100,
currency_code: "USD", currency_code: "USD",
@@ -417,7 +408,7 @@ moduleIntegrationTestRunner({
rule_attribute: "region_id", rule_attribute: "region_id",
}), }),
], ],
price_set_money_amounts: expect.arrayContaining([ prices: expect.arrayContaining([
expect.objectContaining({ expect.objectContaining({
amount: 100, amount: 100,
currency_code: "USD", currency_code: "USD",
@@ -431,7 +422,7 @@ moduleIntegrationTestRunner({
) )
}) })
it("should create a price set with rule types and money amountss", async () => { it("should create a price set with rule types and money amounts", async () => {
const [priceSet] = await service.create([ const [priceSet] = await service.create([
{ {
rules: [{ rule_attribute: "region_id" }], rules: [{ rule_attribute: "region_id" }],
@@ -454,7 +445,7 @@ moduleIntegrationTestRunner({
rule_attribute: "region_id", rule_attribute: "region_id",
}), }),
], ],
price_set_money_amounts: [ prices: [
expect.objectContaining({ expect.objectContaining({
amount: 100, amount: 100,
currency_code: "USD", currency_code: "USD",
@@ -493,12 +484,8 @@ moduleIntegrationTestRunner({
const createdPriceSet = await service.create([ const createdPriceSet = await service.create([
{ {
rules: [ rules: [
{ { rule_attribute: "region_id" },
rule_attribute: "region_id", { rule_attribute: "currency_code" },
},
{
rule_attribute: "currency_code",
},
], ],
prices: [ prices: [
{ {
@@ -521,23 +508,12 @@ moduleIntegrationTestRunner({
]) ])
await service.removeRules([ await service.removeRules([
{ { id: createdPriceSet[0].id, rules: ["region_id"] },
id: createdPriceSet[0].id,
rules: ["region_id"],
},
]) ])
let priceSet = await service.list( let priceSet = await service.list(
{ { id: [createdPriceSet[0].id] },
id: [createdPriceSet[0].id], { relations: ["rule_types", "prices", "price_rules"] }
},
{
relations: [
"rule_types",
"price_set_money_amounts",
"price_rules",
],
}
) )
expect( expect(
@@ -552,7 +528,7 @@ moduleIntegrationTestRunner({
}), }),
}, },
], ],
price_set_money_amounts: [ prices: [
expect.objectContaining({ expect.objectContaining({
amount: 500, amount: 500,
currency_code: "EUR", currency_code: "EUR",
@@ -568,29 +544,18 @@ moduleIntegrationTestRunner({
) )
await service.removeRules([ await service.removeRules([
{ { id: createdPriceSet[0].id, rules: ["currency_code"] },
id: createdPriceSet[0].id,
rules: ["currency_code"],
},
]) ])
priceSet = await service.list( priceSet = await service.list(
{ { id: [createdPriceSet[0].id] },
id: [createdPriceSet[0].id], { relations: ["rule_types", "prices", "price_rules"] }
},
{
relations: [
"rule_types",
"price_set_money_amounts",
"price_rules",
],
}
) )
expect(priceSet).toEqual([ expect(priceSet).toEqual([
{ {
id: expect.any(String), id: expect.any(String),
price_rules: [], price_rules: [],
price_set_money_amounts: [], prices: [],
rule_types: [], rule_types: [],
created_at: expect.any(Date), created_at: expect.any(Date),
updated_at: expect.any(Date), updated_at: expect.any(Date),
@@ -617,13 +582,13 @@ moduleIntegrationTestRunner({
const [priceSet] = await service.list( const [priceSet] = await service.list(
{ id: ["price-set-1"] }, { id: ["price-set-1"] },
{ relations: ["price_set_money_amounts"] } { relations: ["prices"] }
) )
expect(priceSet).toEqual( expect(priceSet).toEqual(
expect.objectContaining({ expect.objectContaining({
id: "price-set-1", id: "price-set-1",
price_set_money_amounts: expect.arrayContaining([ prices: expect.arrayContaining([
expect.objectContaining({ expect.objectContaining({
amount: 100, amount: 100,
currency_code: "USD", currency_code: "USD",
@@ -659,13 +624,13 @@ moduleIntegrationTestRunner({
const priceSets = await service.list( const priceSets = await service.list(
{ id: ["price-set-1", "price-set-2"] }, { id: ["price-set-1", "price-set-2"] },
{ relations: ["price_set_money_amounts"] } { relations: ["prices"] }
) )
expect(priceSets).toEqual([ expect(priceSets).toEqual([
expect.objectContaining({ expect.objectContaining({
id: "price-set-1", id: "price-set-1",
price_set_money_amounts: expect.arrayContaining([ prices: expect.arrayContaining([
expect.objectContaining({ expect.objectContaining({
amount: 100, amount: 100,
currency_code: "USD", currency_code: "USD",
@@ -674,7 +639,7 @@ moduleIntegrationTestRunner({
}), }),
expect.objectContaining({ expect.objectContaining({
id: "price-set-2", id: "price-set-2",
price_set_money_amounts: expect.arrayContaining([ prices: expect.arrayContaining([
expect.objectContaining({ expect.objectContaining({
amount: 150, amount: 150,
currency_code: "EUR", currency_code: "EUR",
@@ -707,17 +672,14 @@ moduleIntegrationTestRunner({
describe("addRules", () => { describe("addRules", () => {
it("should add rules to existing price set", async () => { it("should add rules to existing price set", async () => {
console.log("1")
await service.addRules([ await service.addRules([
{ {
priceSetId: "price-set-1", priceSetId: "price-set-1",
rules: [ rules: [{ attribute: "region_id" }],
{
attribute: "region_id",
},
],
}, },
]) ])
console.log("2")
const [priceSet] = await service.list( const [priceSet] = await service.list(
{ id: ["price-set-1"] }, { id: ["price-set-1"] },
{ relations: ["rule_types"] } { relations: ["rule_types"] }
@@ -745,11 +707,7 @@ moduleIntegrationTestRunner({
await service.addRules([ await service.addRules([
{ {
priceSetId: "price-set-doesn't-exist", priceSetId: "price-set-doesn't-exist",
rules: [ rules: [{ attribute: "region_id" }],
{
attribute: "region_id",
},
],
}, },
]) ])
} catch (e) { } catch (e) {
@@ -766,14 +724,7 @@ moduleIntegrationTestRunner({
try { try {
await service.addRules([ await service.addRules([
{ { priceSetId: "price-set-1", rules: [{ attribute: "city" }] },
priceSetId: "price-set-1",
rules: [
{
attribute: "city",
},
],
},
]) ])
} catch (e) { } catch (e) {
error = e error = e
+2 -2
View File
@@ -1,13 +1,13 @@
import { Modules } from "@medusajs/modules-sdk" import { Modules } from "@medusajs/modules-sdk"
import { ModuleJoinerConfig } from "@medusajs/types" import { ModuleJoinerConfig } from "@medusajs/types"
import { MapToConfig } from "@medusajs/utils" import { MapToConfig } from "@medusajs/utils"
import { PriceList, PriceSet, PriceSetMoneyAmount } from "@models" import { Price, PriceList, PriceSet } from "@models"
import schema from "./schema" import schema from "./schema"
export const LinkableKeys = { export const LinkableKeys = {
price_set_id: PriceSet.name, price_set_id: PriceSet.name,
price_list_id: PriceList.name, price_list_id: PriceList.name,
price_set_money_amount_id: PriceSetMoneyAmount.name, price_id: Price.name,
} }
const entityLinkableKeysMap: MapToConfig = {} const entityLinkableKeysMap: MapToConfig = {}
@@ -1,125 +1,7 @@
{ {
"namespaces": [ "namespaces": ["public"],
"public"
],
"name": "public", "name": "public",
"tables": [ "tables": [
{
"columns": {
"id": {
"name": "id",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "text"
},
"currency_code": {
"name": "currency_code",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "text"
},
"amount": {
"name": "amount",
"type": "numeric",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "decimal"
},
"min_quantity": {
"name": "min_quantity",
"type": "numeric",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"mappedType": "decimal"
},
"max_quantity": {
"name": "max_quantity",
"type": "numeric",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"mappedType": "decimal"
},
"created_at": {
"name": "created_at",
"type": "timestamptz",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"length": 6,
"default": "now()",
"mappedType": "datetime"
},
"updated_at": {
"name": "updated_at",
"type": "timestamptz",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"length": 6,
"default": "now()",
"mappedType": "datetime"
},
"deleted_at": {
"name": "deleted_at",
"type": "timestamptz",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"length": 6,
"mappedType": "datetime"
}
},
"name": "money_amount",
"schema": "public",
"indexes": [
{
"keyName": "IDX_money_amount_currency_code",
"columnNames": [
"currency_code"
],
"composite": false,
"primary": false,
"unique": false,
"expression": "CREATE INDEX IF NOT EXISTS \"IDX_money_amount_currency_code\" ON \"money_amount\" (currency_code) WHERE deleted_at IS NULL"
},
{
"keyName": "IDX_money_amount_deleted_at",
"columnNames": [
"deleted_at"
],
"composite": false,
"primary": false,
"unique": false,
"expression": "CREATE INDEX IF NOT EXISTS \"IDX_money_amount_deleted_at\" ON \"money_amount\" (deleted_at) WHERE deleted_at IS NOT NULL"
},
{
"keyName": "money_amount_pkey",
"columnNames": [
"id"
],
"composite": false,
"primary": true,
"unique": true
}
],
"checks": [],
"foreignKeys": {}
},
{ {
"columns": { "columns": {
"id": { "id": {
@@ -157,10 +39,7 @@
"primary": false, "primary": false,
"nullable": false, "nullable": false,
"default": "'draft'", "default": "'draft'",
"enumItems": [ "enumItems": ["active", "draft"],
"active",
"draft"
],
"mappedType": "enum" "mappedType": "enum"
}, },
"type": { "type": {
@@ -171,10 +50,7 @@
"primary": false, "primary": false,
"nullable": false, "nullable": false,
"default": "'sale'", "default": "'sale'",
"enumItems": [ "enumItems": ["sale", "override"],
"sale",
"override"
],
"mappedType": "enum" "mappedType": "enum"
}, },
"starts_at": { "starts_at": {
@@ -245,9 +121,7 @@
"indexes": [ "indexes": [
{ {
"keyName": "IDX_price_list_deleted_at", "keyName": "IDX_price_list_deleted_at",
"columnNames": [ "columnNames": ["deleted_at"],
"deleted_at"
],
"composite": false, "composite": false,
"primary": false, "primary": false,
"unique": false, "unique": false,
@@ -255,9 +129,7 @@
}, },
{ {
"keyName": "price_list_pkey", "keyName": "price_list_pkey",
"columnNames": [ "columnNames": ["id"],
"id"
],
"composite": false, "composite": false,
"primary": true, "primary": true,
"unique": true "unique": true
@@ -315,9 +187,7 @@
"indexes": [ "indexes": [
{ {
"keyName": "IDX_price_set_deleted_at", "keyName": "IDX_price_set_deleted_at",
"columnNames": [ "columnNames": ["deleted_at"],
"deleted_at"
],
"composite": false, "composite": false,
"primary": false, "primary": false,
"unique": false, "unique": false,
@@ -325,9 +195,7 @@
}, },
{ {
"keyName": "price_set_pkey", "keyName": "price_set_pkey",
"columnNames": [ "columnNames": ["id"],
"id"
],
"composite": false, "composite": false,
"primary": true, "primary": true,
"unique": true "unique": true
@@ -453,54 +321,44 @@
"mappedType": "datetime" "mappedType": "datetime"
} }
}, },
"name": "price_set_money_amount", "name": "price",
"schema": "public", "schema": "public",
"indexes": [ "indexes": [
{ {
"keyName": "IDX_price_set_money_amount_currency_code", "keyName": "IDX_price_currency_code",
"columnNames": [ "columnNames": ["currency_code"],
"currency_code"
],
"composite": false, "composite": false,
"primary": false, "primary": false,
"unique": false, "unique": false,
"expression": "CREATE INDEX IF NOT EXISTS \"IDX_price_set_money_amount_currency_code\" ON \"price_set_money_amount\" (currency_code) WHERE deleted_at IS NULL" "expression": "CREATE INDEX IF NOT EXISTS \"IDX_price_currency_code\" ON \"price\" (currency_code) WHERE deleted_at IS NULL"
}, },
{ {
"keyName": "IDX_price_set_money_amount_price_set_id", "keyName": "IDX_price_price_set_id",
"columnNames": [ "columnNames": ["price_set_id"],
"price_set_id"
],
"composite": false, "composite": false,
"primary": false, "primary": false,
"unique": false, "unique": false,
"expression": "CREATE INDEX IF NOT EXISTS \"IDX_price_set_money_amount_price_set_id\" ON \"price_set_money_amount\" (price_set_id) WHERE deleted_at IS NULL" "expression": "CREATE INDEX IF NOT EXISTS \"IDX_price_price_set_id\" ON \"price\" (price_set_id) WHERE deleted_at IS NULL"
}, },
{ {
"keyName": "IDX_price_set_money_amount_price_list_id", "keyName": "IDX_price_price_list_id",
"columnNames": [ "columnNames": ["price_list_id"],
"price_list_id"
],
"composite": false, "composite": false,
"primary": false, "primary": false,
"unique": false, "unique": false,
"expression": "CREATE INDEX IF NOT EXISTS \"IDX_price_set_money_amount_price_list_id\" ON \"price_set_money_amount\" (price_list_id) WHERE deleted_at IS NULL" "expression": "CREATE INDEX IF NOT EXISTS \"IDX_price_price_list_id\" ON \"price\" (price_list_id) WHERE deleted_at IS NULL"
}, },
{ {
"keyName": "IDX_price_set_money_amount_deleted_at", "keyName": "IDX_price_deleted_at",
"columnNames": [ "columnNames": ["deleted_at"],
"deleted_at"
],
"composite": false, "composite": false,
"primary": false, "primary": false,
"unique": false, "unique": false,
"expression": "CREATE INDEX IF NOT EXISTS \"IDX_price_set_money_amount_deleted_at\" ON \"price_set_money_amount\" (deleted_at) WHERE deleted_at IS NOT NULL" "expression": "CREATE INDEX IF NOT EXISTS \"IDX_price_deleted_at\" ON \"price\" (deleted_at) WHERE deleted_at IS NOT NULL"
}, },
{ {
"keyName": "price_set_money_amount_pkey", "keyName": "price_pkey",
"columnNames": [ "columnNames": ["id"],
"id"
],
"composite": false, "composite": false,
"primary": true, "primary": true,
"unique": true "unique": true
@@ -508,28 +366,20 @@
], ],
"checks": [], "checks": [],
"foreignKeys": { "foreignKeys": {
"price_set_money_amount_price_set_id_foreign": { "price_price_set_id_foreign": {
"constraintName": "price_set_money_amount_price_set_id_foreign", "constraintName": "price_price_set_id_foreign",
"columnNames": [ "columnNames": ["price_set_id"],
"price_set_id" "localTableName": "public.price",
], "referencedColumnNames": ["id"],
"localTableName": "public.price_set_money_amount",
"referencedColumnNames": [
"id"
],
"referencedTableName": "public.price_set", "referencedTableName": "public.price_set",
"deleteRule": "cascade", "deleteRule": "cascade",
"updateRule": "cascade" "updateRule": "cascade"
}, },
"price_set_money_amount_price_list_id_foreign": { "price_price_list_id_foreign": {
"constraintName": "price_set_money_amount_price_list_id_foreign", "constraintName": "price_price_list_id_foreign",
"columnNames": [ "columnNames": ["price_list_id"],
"price_list_id" "localTableName": "public.price",
], "referencedColumnNames": ["id"],
"localTableName": "public.price_set_money_amount",
"referencedColumnNames": [
"id"
],
"referencedTableName": "public.price_list", "referencedTableName": "public.price_list",
"deleteRule": "cascade", "deleteRule": "cascade",
"updateRule": "cascade" "updateRule": "cascade"
@@ -613,9 +463,7 @@
"indexes": [ "indexes": [
{ {
"keyName": "IDX_rule_type_rule_attribute", "keyName": "IDX_rule_type_rule_attribute",
"columnNames": [ "columnNames": ["rule_attribute"],
"rule_attribute"
],
"composite": false, "composite": false,
"primary": false, "primary": false,
"unique": false, "unique": false,
@@ -623,9 +471,7 @@
}, },
{ {
"keyName": "IDX_rule_type_deleted_at", "keyName": "IDX_rule_type_deleted_at",
"columnNames": [ "columnNames": ["deleted_at"],
"deleted_at"
],
"composite": false, "composite": false,
"primary": false, "primary": false,
"unique": false, "unique": false,
@@ -633,9 +479,7 @@
}, },
{ {
"keyName": "rule_type_pkey", "keyName": "rule_type_pkey",
"columnNames": [ "columnNames": ["id"],
"id"
],
"composite": false, "composite": false,
"primary": true, "primary": true,
"unique": true "unique": true
@@ -711,9 +555,7 @@
"indexes": [ "indexes": [
{ {
"keyName": "IDX_price_set_rule_type_price_set_id", "keyName": "IDX_price_set_rule_type_price_set_id",
"columnNames": [ "columnNames": ["price_set_id"],
"price_set_id"
],
"composite": false, "composite": false,
"primary": false, "primary": false,
"unique": false, "unique": false,
@@ -721,9 +563,7 @@
}, },
{ {
"keyName": "IDX_price_set_rule_type_rule_type_id", "keyName": "IDX_price_set_rule_type_rule_type_id",
"columnNames": [ "columnNames": ["rule_type_id"],
"rule_type_id"
],
"composite": false, "composite": false,
"primary": false, "primary": false,
"unique": false, "unique": false,
@@ -731,9 +571,7 @@
}, },
{ {
"keyName": "IDX_price_set_rule_type_deleted_at", "keyName": "IDX_price_set_rule_type_deleted_at",
"columnNames": [ "columnNames": ["deleted_at"],
"deleted_at"
],
"composite": false, "composite": false,
"primary": false, "primary": false,
"unique": false, "unique": false,
@@ -741,9 +579,7 @@
}, },
{ {
"keyName": "price_set_rule_type_pkey", "keyName": "price_set_rule_type_pkey",
"columnNames": [ "columnNames": ["id"],
"id"
],
"composite": false, "composite": false,
"primary": true, "primary": true,
"unique": true "unique": true
@@ -753,26 +589,18 @@
"foreignKeys": { "foreignKeys": {
"price_set_rule_type_price_set_id_foreign": { "price_set_rule_type_price_set_id_foreign": {
"constraintName": "price_set_rule_type_price_set_id_foreign", "constraintName": "price_set_rule_type_price_set_id_foreign",
"columnNames": [ "columnNames": ["price_set_id"],
"price_set_id"
],
"localTableName": "public.price_set_rule_type", "localTableName": "public.price_set_rule_type",
"referencedColumnNames": [ "referencedColumnNames": ["id"],
"id"
],
"referencedTableName": "public.price_set", "referencedTableName": "public.price_set",
"deleteRule": "cascade", "deleteRule": "cascade",
"updateRule": "cascade" "updateRule": "cascade"
}, },
"price_set_rule_type_rule_type_id_foreign": { "price_set_rule_type_rule_type_id_foreign": {
"constraintName": "price_set_rule_type_rule_type_id_foreign", "constraintName": "price_set_rule_type_rule_type_id_foreign",
"columnNames": [ "columnNames": ["rule_type_id"],
"rule_type_id"
],
"localTableName": "public.price_set_rule_type", "localTableName": "public.price_set_rule_type",
"referencedColumnNames": [ "referencedColumnNames": ["id"],
"id"
],
"referencedTableName": "public.rule_type", "referencedTableName": "public.rule_type",
"deleteRule": "cascade", "deleteRule": "cascade",
"updateRule": "cascade" "updateRule": "cascade"
@@ -827,8 +655,8 @@
"default": "0", "default": "0",
"mappedType": "integer" "mappedType": "integer"
}, },
"price_set_money_amount_id": { "price_id": {
"name": "price_set_money_amount_id", "name": "price_id",
"type": "text", "type": "text",
"unsigned": false, "unsigned": false,
"autoincrement": false, "autoincrement": false,
@@ -874,9 +702,7 @@
"indexes": [ "indexes": [
{ {
"keyName": "IDX_price_rule_price_set_id", "keyName": "IDX_price_rule_price_set_id",
"columnNames": [ "columnNames": ["price_set_id"],
"price_set_id"
],
"composite": false, "composite": false,
"primary": false, "primary": false,
"unique": false, "unique": false,
@@ -884,29 +710,23 @@
}, },
{ {
"keyName": "IDX_price_rule_rule_type_id", "keyName": "IDX_price_rule_rule_type_id",
"columnNames": [ "columnNames": ["rule_type_id"],
"rule_type_id"
],
"composite": false, "composite": false,
"primary": false, "primary": false,
"unique": false, "unique": false,
"expression": "CREATE INDEX IF NOT EXISTS \"IDX_price_rule_rule_type_id\" ON \"price_rule\" (rule_type_id) WHERE deleted_at IS NULL" "expression": "CREATE INDEX IF NOT EXISTS \"IDX_price_rule_rule_type_id\" ON \"price_rule\" (rule_type_id) WHERE deleted_at IS NULL"
}, },
{ {
"keyName": "IDX_price_rule_price_set_money_amount_id_unique", "keyName": "IDX_price_rule_price_id_rule_type_id_unique",
"columnNames": [ "columnNames": ["price_id"],
"price_set_money_amount_id"
],
"composite": false, "composite": false,
"primary": false, "primary": false,
"unique": false, "unique": false,
"expression": "CREATE UNIQUE INDEX IF NOT EXISTS \"IDX_price_rule_price_set_money_amount_id_unique\" ON \"price_rule\" (price_set_money_amount_id) WHERE deleted_at IS NULL" "expression": "CREATE UNIQUE INDEX IF NOT EXISTS \"IDX_price_rule_price_id_rule_type_id_unique\" ON \"price_rule\" (price_id, rule_type_id) WHERE deleted_at IS NULL"
}, },
{ {
"keyName": "IDX_price_rule_deleted_at", "keyName": "IDX_price_rule_deleted_at",
"columnNames": [ "columnNames": ["deleted_at"],
"deleted_at"
],
"composite": false, "composite": false,
"primary": false, "primary": false,
"unique": false, "unique": false,
@@ -914,9 +734,7 @@
}, },
{ {
"keyName": "price_rule_pkey", "keyName": "price_rule_pkey",
"columnNames": [ "columnNames": ["id"],
"id"
],
"composite": false, "composite": false,
"primary": true, "primary": true,
"unique": true "unique": true
@@ -926,39 +744,27 @@
"foreignKeys": { "foreignKeys": {
"price_rule_price_set_id_foreign": { "price_rule_price_set_id_foreign": {
"constraintName": "price_rule_price_set_id_foreign", "constraintName": "price_rule_price_set_id_foreign",
"columnNames": [ "columnNames": ["price_set_id"],
"price_set_id"
],
"localTableName": "public.price_rule", "localTableName": "public.price_rule",
"referencedColumnNames": [ "referencedColumnNames": ["id"],
"id"
],
"referencedTableName": "public.price_set", "referencedTableName": "public.price_set",
"deleteRule": "cascade", "deleteRule": "cascade",
"updateRule": "cascade" "updateRule": "cascade"
}, },
"price_rule_rule_type_id_foreign": { "price_rule_rule_type_id_foreign": {
"constraintName": "price_rule_rule_type_id_foreign", "constraintName": "price_rule_rule_type_id_foreign",
"columnNames": [ "columnNames": ["rule_type_id"],
"rule_type_id"
],
"localTableName": "public.price_rule", "localTableName": "public.price_rule",
"referencedColumnNames": [ "referencedColumnNames": ["id"],
"id"
],
"referencedTableName": "public.rule_type", "referencedTableName": "public.rule_type",
"updateRule": "cascade" "updateRule": "cascade"
}, },
"price_rule_price_set_money_amount_id_foreign": { "price_rule_price_id_foreign": {
"constraintName": "price_rule_price_set_money_amount_id_foreign", "constraintName": "price_rule_price_id_foreign",
"columnNames": [ "columnNames": ["price_id"],
"price_set_money_amount_id"
],
"localTableName": "public.price_rule", "localTableName": "public.price_rule",
"referencedColumnNames": [ "referencedColumnNames": ["id"],
"id" "referencedTableName": "public.price",
],
"referencedTableName": "public.price_set_money_amount",
"deleteRule": "cascade", "deleteRule": "cascade",
"updateRule": "cascade" "updateRule": "cascade"
} }
@@ -1031,9 +837,7 @@
"indexes": [ "indexes": [
{ {
"keyName": "IDX_price_list_rule_rule_type_id_unique", "keyName": "IDX_price_list_rule_rule_type_id_unique",
"columnNames": [ "columnNames": ["rule_type_id"],
"rule_type_id"
],
"composite": false, "composite": false,
"primary": false, "primary": false,
"unique": false, "unique": false,
@@ -1041,9 +845,7 @@
}, },
{ {
"keyName": "IDX_price_list_rule_price_list_id", "keyName": "IDX_price_list_rule_price_list_id",
"columnNames": [ "columnNames": ["price_list_id"],
"price_list_id"
],
"composite": false, "composite": false,
"primary": false, "primary": false,
"unique": false, "unique": false,
@@ -1051,9 +853,7 @@
}, },
{ {
"keyName": "IDX_price_list_rule_deleted_at", "keyName": "IDX_price_list_rule_deleted_at",
"columnNames": [ "columnNames": ["deleted_at"],
"deleted_at"
],
"composite": false, "composite": false,
"primary": false, "primary": false,
"unique": false, "unique": false,
@@ -1061,9 +861,7 @@
}, },
{ {
"keyName": "price_list_rule_pkey", "keyName": "price_list_rule_pkey",
"columnNames": [ "columnNames": ["id"],
"id"
],
"composite": false, "composite": false,
"primary": true, "primary": true,
"unique": true "unique": true
@@ -1073,25 +871,17 @@
"foreignKeys": { "foreignKeys": {
"price_list_rule_rule_type_id_foreign": { "price_list_rule_rule_type_id_foreign": {
"constraintName": "price_list_rule_rule_type_id_foreign", "constraintName": "price_list_rule_rule_type_id_foreign",
"columnNames": [ "columnNames": ["rule_type_id"],
"rule_type_id"
],
"localTableName": "public.price_list_rule", "localTableName": "public.price_list_rule",
"referencedColumnNames": [ "referencedColumnNames": ["id"],
"id"
],
"referencedTableName": "public.rule_type", "referencedTableName": "public.rule_type",
"updateRule": "cascade" "updateRule": "cascade"
}, },
"price_list_rule_price_list_id_foreign": { "price_list_rule_price_list_id_foreign": {
"constraintName": "price_list_rule_price_list_id_foreign", "constraintName": "price_list_rule_price_list_id_foreign",
"columnNames": [ "columnNames": ["price_list_id"],
"price_list_id"
],
"localTableName": "public.price_list_rule", "localTableName": "public.price_list_rule",
"referencedColumnNames": [ "referencedColumnNames": ["id"],
"id"
],
"referencedTableName": "public.price_list", "referencedTableName": "public.price_list",
"deleteRule": "cascade", "deleteRule": "cascade",
"updateRule": "cascade" "updateRule": "cascade"
@@ -1165,9 +955,7 @@
"indexes": [ "indexes": [
{ {
"keyName": "IDX_price_list_rule_value_price_list_rule_id", "keyName": "IDX_price_list_rule_value_price_list_rule_id",
"columnNames": [ "columnNames": ["price_list_rule_id"],
"price_list_rule_id"
],
"composite": false, "composite": false,
"primary": false, "primary": false,
"unique": false, "unique": false,
@@ -1175,9 +963,7 @@
}, },
{ {
"keyName": "IDX_price_list_rule_value_deleted_at", "keyName": "IDX_price_list_rule_value_deleted_at",
"columnNames": [ "columnNames": ["deleted_at"],
"deleted_at"
],
"composite": false, "composite": false,
"primary": false, "primary": false,
"unique": false, "unique": false,
@@ -1185,9 +971,7 @@
}, },
{ {
"keyName": "price_list_rule_value_pkey", "keyName": "price_list_rule_value_pkey",
"columnNames": [ "columnNames": ["id"],
"id"
],
"composite": false, "composite": false,
"primary": true, "primary": true,
"unique": true "unique": true
@@ -1197,13 +981,9 @@
"foreignKeys": { "foreignKeys": {
"price_list_rule_value_price_list_rule_id_foreign": { "price_list_rule_value_price_list_rule_id_foreign": {
"constraintName": "price_list_rule_value_price_list_rule_id_foreign", "constraintName": "price_list_rule_value_price_list_rule_id_foreign",
"columnNames": [ "columnNames": ["price_list_rule_id"],
"price_list_rule_id"
],
"localTableName": "public.price_list_rule_value", "localTableName": "public.price_list_rule_value",
"referencedColumnNames": [ "referencedColumnNames": ["id"],
"id"
],
"referencedTableName": "public.price_list_rule", "referencedTableName": "public.price_list_rule",
"deleteRule": "cascade", "deleteRule": "cascade",
"updateRule": "cascade" "updateRule": "cascade"
@@ -11,11 +11,11 @@ export class Migration20230929122253 extends Migration {
) )
this.addSql( this.addSql(
'create table "price_set_money_amount" ("id" text not null, "title" text, "price_set_id" text not null, "money_amount_id" text not null, "rules_count" integer not null default 0, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "price_set_money_amount_pkey" primary key ("id"));' 'create table "price" ("id" text not null, "title" text, "price_set_id" text not null, "money_amount_id" text not null, "rules_count" integer not null default 0, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "price_pkey" primary key ("id"));'
) )
this.addSql( this.addSql(
'alter table "price_set_money_amount" add constraint "price_set_money_amount_money_amount_id_unique" unique ("money_amount_id");' 'alter table "price" add constraint "price_money_amount_id_unique" unique ("money_amount_id");'
) )
this.addSql( this.addSql(
@@ -27,14 +27,14 @@ export class Migration20230929122253 extends Migration {
) )
this.addSql( this.addSql(
'create table "price_rule" ("id" text not null, "price_set_id" text not null, "rule_type_id" text not null, "value" text not null, "priority" integer not null default 0, "price_set_money_amount_id" text not null, "price_list_id" text not null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "price_rule_pkey" primary key ("id"));' 'create table "price_rule" ("id" text not null, "price_set_id" text not null, "rule_type_id" text not null, "value" text not null, "priority" integer not null default 0, "price_id" text not null, "price_list_id" text not null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "price_rule_pkey" primary key ("id"));'
) )
this.addSql( this.addSql(
'alter table "price_set_money_amount" add constraint "price_set_money_amount_price_set_id_foreign" foreign key ("price_set_id") references "price_set" ("id") on update cascade on delete cascade;' 'alter table "price" add constraint "price_price_set_id_foreign" foreign key ("price_set_id") references "price_set" ("id") on update cascade on delete cascade;'
) )
this.addSql( this.addSql(
'alter table "price_set_money_amount" add constraint "price_set_money_amount_money_amount_id_foreign" foreign key ("money_amount_id") references "money_amount" ("id") on update cascade on delete cascade;' 'alter table "price" add constraint "price_money_amount_id_foreign" foreign key ("money_amount_id") references "money_amount" ("id") on update cascade on delete cascade;'
) )
this.addSql( this.addSql(
@@ -51,7 +51,7 @@ export class Migration20230929122253 extends Migration {
'alter table "price_rule" add constraint "price_rule_rule_type_id_foreign" foreign key ("rule_type_id") references "rule_type" ("id") on update cascade;' 'alter table "price_rule" add constraint "price_rule_rule_type_id_foreign" foreign key ("rule_type_id") references "rule_type" ("id") on update cascade;'
) )
this.addSql( this.addSql(
'alter table "price_rule" add constraint "price_rule_price_set_money_amount_id_foreign" foreign key ("price_set_money_amount_id") references "price_set_money_amount" ("id") on update cascade on delete cascade;' 'alter table "price_rule" add constraint "price_rule_price_id_foreign" foreign key ("price_id") references "price" ("id") on update cascade on delete cascade;'
) )
this.addSql( this.addSql(
@@ -69,9 +69,7 @@ export class Migration20230929122253 extends Migration {
'alter table "price_list_rule" add constraint "price_list_rule_price_list_id_foreign" foreign key ("price_list_id") references "price_list" ("id") on update cascade;' 'alter table "price_list_rule" add constraint "price_list_rule_price_list_id_foreign" foreign key ("price_list_id") references "price_list" ("id") on update cascade;'
) )
this.addSql( this.addSql('alter table "price" add column "price_list_id" text null;')
'alter table "price_set_money_amount" add column "price_list_id" text null;'
)
this.addSql('alter table "price_rule" drop column "price_list_id";') this.addSql('alter table "price_rule" drop column "price_list_id";')
@@ -112,16 +110,16 @@ export class Migration20230929122253 extends Migration {
'CREATE INDEX IF NOT EXISTS "IDX_price_set_deleted_at" ON "price_set" (deleted_at) WHERE deleted_at IS NOT NULL;' 'CREATE INDEX IF NOT EXISTS "IDX_price_set_deleted_at" ON "price_set" (deleted_at) WHERE deleted_at IS NOT NULL;'
) )
this.addSql( this.addSql(
'CREATE INDEX IF NOT EXISTS "IDX_price_set_money_amount_price_set_id" ON "price_set_money_amount" (price_set_id) WHERE deleted_at IS NULL;' 'CREATE INDEX IF NOT EXISTS "IDX_price_price_set_id" ON "price" (price_set_id) WHERE deleted_at IS NULL;'
) )
this.addSql( this.addSql(
'CREATE INDEX IF NOT EXISTS "IDX_price_set_money_amount_money_amount_id" ON "price_set_money_amount" (money_amount_id) WHERE deleted_at IS NULL;' 'CREATE INDEX IF NOT EXISTS "IDX_price_money_amount_id" ON "price" (money_amount_id) WHERE deleted_at IS NULL;'
) )
this.addSql( this.addSql(
'CREATE INDEX IF NOT EXISTS "IDX_price_set_money_amount_price_list_id" ON "price_set_money_amount" (price_list_id) WHERE deleted_at IS NULL;' 'CREATE INDEX IF NOT EXISTS "IDX_price_price_list_id" ON "price" (price_list_id) WHERE deleted_at IS NULL;'
) )
this.addSql( this.addSql(
'CREATE INDEX IF NOT EXISTS "IDX_price_set_money_amount_deleted_at" ON "price_set_money_amount" (deleted_at) WHERE deleted_at IS NOT NULL;' 'CREATE INDEX IF NOT EXISTS "IDX_price_deleted_at" ON "price" (deleted_at) WHERE deleted_at IS NOT NULL;'
) )
this.addSql( this.addSql(
'CREATE INDEX IF NOT EXISTS "IDX_rule_type_rule_attribute" ON "rule_type" (rule_attribute) WHERE deleted_at IS NOT NULL;' 'CREATE INDEX IF NOT EXISTS "IDX_rule_type_rule_attribute" ON "rule_type" (rule_attribute) WHERE deleted_at IS NOT NULL;'
@@ -146,7 +144,7 @@ export class Migration20230929122253 extends Migration {
'CREATE INDEX IF NOT EXISTS "IDX_price_rule_rule_type_id" ON "price_rule" (rule_type_id) WHERE deleted_at IS NOT NULL;' 'CREATE INDEX IF NOT EXISTS "IDX_price_rule_rule_type_id" ON "price_rule" (rule_type_id) WHERE deleted_at IS NOT NULL;'
) )
this.addSql( this.addSql(
'CREATE UNIQUE INDEX IF NOT EXISTS "IDX_price_rule_price_set_money_amount_id_unique" ON "price_rule" (price_set_money_amount_id) WHERE deleted_at IS NOT NULL;' 'CREATE UNIQUE INDEX IF NOT EXISTS "IDX_price_rule_price_id_unique" ON "price_rule" (price_id) WHERE deleted_at IS NOT NULL;'
) )
this.addSql( this.addSql(
'CREATE INDEX IF NOT EXISTS "IDX_price_rule_deleted_at" ON "price_rule" (deleted_at) WHERE deleted_at IS NOT NULL;' 'CREATE INDEX IF NOT EXISTS "IDX_price_rule_deleted_at" ON "price_rule" (deleted_at) WHERE deleted_at IS NOT NULL;'
@@ -172,7 +170,7 @@ export class Migration20230929122253 extends Migration {
) )
this.addSql( this.addSql(
'alter table if exists "price_set_money_amount" add constraint "price_set_money_amount_price_list_id_foreign" foreign key ("price_list_id") references "price_list" ("id") on update cascade on delete cascade;' 'alter table if exists "price" add constraint "price_price_list_id_foreign" foreign key ("price_list_id") references "price_list" ("id") on update cascade on delete cascade;'
) )
this.addSql( this.addSql(
@@ -208,27 +206,25 @@ export class Migration20230929122253 extends Migration {
) )
this.addSql( this.addSql(
'alter table if exists "price_set_money_amount" drop constraint if exists "price_set_money_amount_money_amount_id_foreign";' 'alter table if exists "price" drop constraint if exists "price_money_amount_id_foreign";'
) )
this.addSql( this.addSql(
'alter table if exists "price_set_money_amount" add column if not exists "amount" numeric not null, add column "min_quantity" numeric null, add column "max_quantity" numeric null;' 'alter table if exists "price" add column if not exists "amount" numeric not null, add column "min_quantity" numeric null, add column "max_quantity" numeric null;'
) )
this.addSql( this.addSql(
'alter table if exists "price_set_money_amount" drop constraint if exists "price_set_money_amount_money_amount_id_unique";' 'alter table if exists "price" drop constraint if exists "price_money_amount_id_unique";'
)
this.addSql('drop index if exists "IDX_price_money_amount_id";')
this.addSql(
'alter table if exists "price" rename column "money_amount_id" to "currency_code";'
) )
this.addSql( this.addSql(
'drop index if exists "IDX_price_set_money_amount_money_amount_id";' 'CREATE INDEX IF NOT EXISTS "IDX_price_currency_code" ON "price" (currency_code) WHERE deleted_at IS NULL;'
)
this.addSql(
'alter table if exists "price_set_money_amount" rename column "money_amount_id" to "currency_code";'
)
this.addSql(
'CREATE INDEX IF NOT EXISTS "IDX_price_set_money_amount_currency_code" ON "price_set_money_amount" (currency_code) WHERE deleted_at IS NULL;'
) )
} }
} }
@@ -0,0 +1,15 @@
import { Migration } from '@mikro-orm/migrations';
export class Migration20240322094407 extends Migration {
async up(): Promise<void> {
this.addSql('drop table if exists "money_amount" cascade;');
}
async down(): Promise<void> {
this.addSql('create table if not exists "money_amount" ("id" text not null, "currency_code" text not null, "amount" numeric not null, "min_quantity" numeric null, "max_quantity" numeric null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "money_amount_pkey" primary key ("id"));');
this.addSql('CREATE INDEX IF NOT EXISTS "IDX_money_amount_currency_code" ON "money_amount" (currency_code) WHERE deleted_at IS NULL;');
this.addSql('CREATE INDEX IF NOT EXISTS "IDX_money_amount_deleted_at" ON "money_amount" (deleted_at) WHERE deleted_at IS NOT NULL;');
}
}
@@ -0,0 +1,31 @@
import { Migration } from "@mikro-orm/migrations"
export class Migration20240322113359 extends Migration {
async up(): Promise<void> {
this.addSql(
'alter table if exists "price_rule" drop constraint if exists "price_rule_price_id_foreign";'
)
this.addSql('drop index if exists "IDX_price_rule_price_id_unique";')
this.addSql(
'alter table if exists "price_rule" add constraint "price_rule_price_id_foreign" foreign key ("price_id") references "price" ("id") on update cascade on delete cascade;'
)
this.addSql(
'CREATE UNIQUE INDEX IF NOT EXISTS "IDX_price_rule_price_id_unique" ON "price_rule" (price_id) WHERE deleted_at IS NULL;'
)
}
async down(): Promise<void> {
this.addSql(
'alter table if exists "price_rule" drop constraint if exists "price_rule_price_id_foreign";'
)
this.addSql('drop index if exists "IDX_price_rule_price_id_unique";')
this.addSql(
'alter table if exists "price_rule" add constraint "price_rule_price_id_foreign" foreign key ("price_id") references "price" ("id") on update cascade on delete cascade;'
)
this.addSql(
'CREATE UNIQUE INDEX IF NOT EXISTS "IDX_price_rule_price_id_unique" ON "price_rule" (price_id) WHERE deleted_at IS NULL;'
)
}
}
@@ -0,0 +1,19 @@
import { Migration } from "@mikro-orm/migrations"
export class Migration20240322120125 extends Migration {
async up(): Promise<void> {
this.addSql('drop index if exists "IDX_price_rule_price_id_unique";')
this.addSql(
'CREATE UNIQUE INDEX IF NOT EXISTS "IDX_price_rule_price_id_rule_type_id_unique" ON "price_rule" (price_id, rule_type_id) WHERE deleted_at IS NULL;'
)
}
async down(): Promise<void> {
this.addSql(
'drop index if exists "IDX_price_rule_price_id_rule_type_id_unique";'
)
this.addSql(
'CREATE UNIQUE INDEX IF NOT EXISTS "IDX_price_rule_price_id_unique" ON "price_rule" (price_id) WHERE deleted_at IS NULL;'
)
}
}
+1 -1
View File
@@ -1,8 +1,8 @@
export { default as Price } from "./price"
export { default as PriceList } from "./price-list" export { default as PriceList } from "./price-list"
export { default as PriceListRule } from "./price-list-rule" export { default as PriceListRule } from "./price-list-rule"
export { default as PriceListRuleValue } from "./price-list-rule-value" export { default as PriceListRuleValue } from "./price-list-rule-value"
export { default as PriceRule } from "./price-rule" export { default as PriceRule } from "./price-rule"
export { default as PriceSet } from "./price-set" export { default as PriceSet } from "./price-set"
export { default as PriceSetMoneyAmount } from "./price-set-money-amount"
export { default as PriceSetRuleType } from "./price-set-rule-type" export { default as PriceSetRuleType } from "./price-set-rule-type"
export { default as RuleType } from "./rule-type" export { default as RuleType } from "./rule-type"
+3 -3
View File
@@ -20,8 +20,8 @@ import {
PrimaryKey, PrimaryKey,
Property, Property,
} from "@mikro-orm/core" } from "@mikro-orm/core"
import Price from "./price"
import PriceListRule from "./price-list-rule" import PriceListRule from "./price-list-rule"
import PriceSetMoneyAmount from "./price-set-money-amount"
import RuleType from "./rule-type" import RuleType from "./rule-type"
type OptionalFields = type OptionalFields =
@@ -68,10 +68,10 @@ export default class PriceList {
}) })
ends_at: Date | null = null ends_at: Date | null = null
@OneToMany(() => PriceSetMoneyAmount, (psma) => psma.price_list, { @OneToMany(() => Price, (price) => price.price_list, {
cascade: ["soft-remove" as Cascade], cascade: ["soft-remove" as Cascade],
}) })
price_set_money_amounts = new Collection<PriceSetMoneyAmount>(this) prices = new Collection<Price>(this)
@OneToMany(() => PriceListRule, (pr) => pr.price_list, { @OneToMany(() => PriceListRule, (pr) => pr.price_list, {
cascade: ["soft-remove" as Cascade], cascade: ["soft-remove" as Cascade],
+16 -10
View File
@@ -1,7 +1,7 @@
import { DAL } from "@medusajs/types" import { DAL } from "@medusajs/types"
import { import {
DALUtils,
createPsqlIndexStatementHelper, createPsqlIndexStatementHelper,
DALUtils,
generateEntityId, generateEntityId,
} from "@medusajs/utils" } from "@medusajs/utils"
import { import {
@@ -14,8 +14,8 @@ import {
PrimaryKey, PrimaryKey,
Property, Property,
} from "@mikro-orm/core" } from "@mikro-orm/core"
import Price from "./price"
import PriceSet from "./price-set" import PriceSet from "./price-set"
import PriceSetMoneyAmount from "./price-set-money-amount"
import RuleType from "./rule-type" import RuleType from "./rule-type"
type OptionalFields = DAL.SoftDeletableEntityDateColumns type OptionalFields = DAL.SoftDeletableEntityDateColumns
@@ -39,9 +39,9 @@ const PriceRuleRuleTypeIdIndex = createPsqlIndexStatementHelper({
where: "deleted_at IS NULL", where: "deleted_at IS NULL",
}) })
const PriceRulePriceSetMoneyAmountIdIndex = createPsqlIndexStatementHelper({ const PriceRulePriceIdIndex = createPsqlIndexStatementHelper({
tableName: tableName, tableName: tableName,
columns: "price_set_money_amount_id", columns: ["price_id", "rule_type_id"],
where: "deleted_at IS NULL", where: "deleted_at IS NULL",
unique: true, unique: true,
}) })
@@ -83,17 +83,17 @@ export default class PriceRule {
@Property({ columnType: "integer", default: 0 }) @Property({ columnType: "integer", default: 0 })
priority: number = 0 priority: number = 0
@PriceRulePriceSetMoneyAmountIdIndex.MikroORMIndex() @PriceRulePriceIdIndex.MikroORMIndex()
@ManyToOne(() => PriceSetMoneyAmount, { @ManyToOne(() => Price, {
columnType: "text", columnType: "text",
mapToPk: true, mapToPk: true,
fieldName: "price_set_money_amount_id", fieldName: "price_id",
onDelete: "cascade", onDelete: "cascade",
}) })
price_set_money_amount_id: string price_id: string
@ManyToOne(() => PriceSetMoneyAmount, { persist: false }) @ManyToOne(() => Price, { persist: false })
price_set_money_amount: PriceSetMoneyAmount price: Price
@Property({ @Property({
onCreate: () => new Date(), onCreate: () => new Date(),
@@ -117,10 +117,16 @@ export default class PriceRule {
@BeforeCreate() @BeforeCreate()
beforeCreate() { beforeCreate() {
this.id = generateEntityId(this.id, "prule") this.id = generateEntityId(this.id, "prule")
this.rule_type_id ??= this.rule_type?.id!
this.price_set_id ??= this.price_set?.id!
this.price_id ??= this.price?.id!
} }
@OnInit() @OnInit()
onInit() { onInit() {
this.id = generateEntityId(this.id, "prule") this.id = generateEntityId(this.id, "prule")
this.rule_type_id ??= this.rule_type?.id!
this.price_set_id ??= this.price_set?.id!
this.price_id ??= this.price?.id!
} }
} }
@@ -41,12 +41,22 @@ export default class PriceSetRuleType {
id!: string id!: string
@PriceSetRuleTypePriceSetIdIndex.MikroORMIndex() @PriceSetRuleTypePriceSetIdIndex.MikroORMIndex()
@ManyToOne(() => PriceSet, { onDelete: "cascade" }) @ManyToOne(() => PriceSet, {
price_set: PriceSet columnType: "text",
mapToPk: true,
fieldName: "price_set_id",
onDelete: "cascade",
})
price_set_id: string
@PriceSetRuleTypeRuleTypeIdIndex.MikroORMIndex() @PriceSetRuleTypeRuleTypeIdIndex.MikroORMIndex()
@ManyToOne(() => RuleType, { onDelete: "cascade" }) @ManyToOne(() => RuleType, {
rule_type: RuleType columnType: "text",
mapToPk: true,
fieldName: "rule_type_id",
onDelete: "cascade",
})
rule_type_id: string
@Property({ @Property({
onCreate: () => new Date(), onCreate: () => new Date(),
+5 -5
View File
@@ -15,8 +15,8 @@ import {
PrimaryKey, PrimaryKey,
Property, Property,
} from "@mikro-orm/core" } from "@mikro-orm/core"
import Price from "./price"
import PriceRule from "./price-rule" import PriceRule from "./price-rule"
import PriceSetMoneyAmount from "./price-set-money-amount"
import PriceSetRuleType from "./price-set-rule-type" import PriceSetRuleType from "./price-set-rule-type"
import RuleType from "./rule-type" import RuleType from "./rule-type"
@@ -33,13 +33,13 @@ export default class PriceSet {
@PrimaryKey({ columnType: "text" }) @PrimaryKey({ columnType: "text" })
id!: string id!: string
@OneToMany(() => PriceSetMoneyAmount, (psma) => psma.price_set, { @OneToMany(() => Price, (price) => price.price_set, {
cascade: ["soft-remove" as Cascade], cascade: [Cascade.PERSIST, "soft-remove" as Cascade],
}) })
price_set_money_amounts = new Collection<PriceSetMoneyAmount>(this) prices = new Collection<Price>(this)
@OneToMany(() => PriceRule, (pr) => pr.price_set, { @OneToMany(() => PriceRule, (pr) => pr.price_set, {
cascade: ["soft-remove" as Cascade], cascade: [Cascade.PERSIST, "soft-remove" as Cascade],
}) })
price_rules = new Collection<PriceRule>(this) price_rules = new Collection<PriceRule>(this)
@@ -1,7 +1,7 @@
import { DAL } from "@medusajs/types" import { DAL } from "@medusajs/types"
import { import {
DALUtils,
createPsqlIndexStatementHelper, createPsqlIndexStatementHelper,
DALUtils,
generateEntityId, generateEntityId,
} from "@medusajs/utils" } from "@medusajs/utils"
import { import {
@@ -11,8 +11,8 @@ import {
Entity, Entity,
Filter, Filter,
ManyToOne, ManyToOne,
OnInit,
OneToMany, OneToMany,
OnInit,
OptionalProps, OptionalProps,
PrimaryKey, PrimaryKey,
Property, Property,
@@ -23,32 +23,26 @@ import PriceSet from "./price-set"
type OptionalFields = DAL.SoftDeletableEntityDateColumns type OptionalFields = DAL.SoftDeletableEntityDateColumns
const tableName = "price_set_money_amount" const tableName = "price"
const PriceSetMoneyAmountDeletedAtIndex = createPsqlIndexStatementHelper({ const PriceDeletedAtIndex = createPsqlIndexStatementHelper({
tableName: tableName, tableName: tableName,
columns: "deleted_at", columns: "deleted_at",
where: "deleted_at IS NOT NULL", where: "deleted_at IS NOT NULL",
}) })
const PriceSetMoneyAmountPriceSetIdIndex = createPsqlIndexStatementHelper({ const PricePriceSetIdIndex = createPsqlIndexStatementHelper({
tableName: tableName, tableName: tableName,
columns: "price_set_id", columns: "price_set_id",
where: "deleted_at IS NULL", where: "deleted_at IS NULL",
}) })
const PriceSetMoneyAmountMoneyAmountIdIndex = createPsqlIndexStatementHelper({ const PricePriceListIdIndex = createPsqlIndexStatementHelper({
tableName: tableName,
columns: "money_amount_id",
where: "deleted_at IS NULL",
})
const PriceSetMoneyAmountPriceListIdIndex = createPsqlIndexStatementHelper({
tableName: tableName, tableName: tableName,
columns: "price_list_id", columns: "price_list_id",
where: "deleted_at IS NULL", where: "deleted_at IS NULL",
}) })
const PriceSetMoneyAmountCurrencyCodeIndex = createPsqlIndexStatementHelper({ const PriceCurrencyCodeIndex = createPsqlIndexStatementHelper({
tableName: tableName, tableName: tableName,
columns: "currency_code", columns: "currency_code",
where: "deleted_at IS NULL", where: "deleted_at IS NULL",
@@ -56,7 +50,7 @@ const PriceSetMoneyAmountCurrencyCodeIndex = createPsqlIndexStatementHelper({
@Entity({ tableName }) @Entity({ tableName })
@Filter(DALUtils.mikroOrmSoftDeletableFilterOptions) @Filter(DALUtils.mikroOrmSoftDeletableFilterOptions)
export default class PriceSetMoneyAmount { export default class Price {
[OptionalProps]?: OptionalFields [OptionalProps]?: OptionalFields
@PrimaryKey({ columnType: "text" }) @PrimaryKey({ columnType: "text" })
@@ -65,7 +59,7 @@ export default class PriceSetMoneyAmount {
@Property({ columnType: "text", nullable: true }) @Property({ columnType: "text", nullable: true })
title: string | null = null title: string | null = null
@PriceSetMoneyAmountCurrencyCodeIndex.MikroORMIndex() @PriceCurrencyCodeIndex.MikroORMIndex()
@Property({ columnType: "text" }) @Property({ columnType: "text" })
currency_code: string currency_code: string
@@ -78,7 +72,7 @@ export default class PriceSetMoneyAmount {
@Property({ columnType: "numeric", nullable: true }) @Property({ columnType: "numeric", nullable: true })
max_quantity: number | null = null max_quantity: number | null = null
@PriceSetMoneyAmountPriceSetIdIndex.MikroORMIndex() @PricePriceSetIdIndex.MikroORMIndex()
@ManyToOne(() => PriceSet, { @ManyToOne(() => PriceSet, {
columnType: "text", columnType: "text",
mapToPk: true, mapToPk: true,
@@ -95,12 +89,12 @@ export default class PriceSetMoneyAmount {
@OneToMany({ @OneToMany({
entity: () => PriceRule, entity: () => PriceRule,
mappedBy: (pr) => pr.price_set_money_amount, mappedBy: (pr) => pr.price,
cascade: ["soft-remove" as Cascade], cascade: [Cascade.PERSIST, "soft-remove" as Cascade],
}) })
price_rules = new Collection<PriceRule>(this) price_rules = new Collection<PriceRule>(this)
@PriceSetMoneyAmountPriceListIdIndex.MikroORMIndex() @PricePriceListIdIndex.MikroORMIndex()
@ManyToOne(() => PriceList, { @ManyToOne(() => PriceList, {
columnType: "text", columnType: "text",
mapToPk: true, mapToPk: true,
@@ -128,17 +122,21 @@ export default class PriceSetMoneyAmount {
}) })
updated_at: Date updated_at: Date
@PriceSetMoneyAmountDeletedAtIndex.MikroORMIndex() @PriceDeletedAtIndex.MikroORMIndex()
@Property({ columnType: "timestamptz", nullable: true }) @Property({ columnType: "timestamptz", nullable: true })
deleted_at: Date | null = null deleted_at: Date | null = null
@BeforeCreate() @BeforeCreate()
onCreate() { onCreate() {
this.id = generateEntityId(this.id, "psma") this.id = generateEntityId(this.id, "price")
this.price_set_id ??= this.price_set?.id!
this.price_list_id ??= this.price_list?.id!
} }
@OnInit() @OnInit()
onInit() { onInit() {
this.id = generateEntityId(this.id, "psma") this.id = generateEntityId(this.id, "price")
this.price_set_id ??= this.price_set?.id!
this.price_list_id ??= this.price_list?.id!
} }
} }
+41 -41
View File
@@ -57,27 +57,27 @@ export class PricingRepository
const date = new Date().toISOString() const date = new Date().toISOString()
// Gets all the price set money amounts where rules match for each of the contexts // Gets all the price set money amounts where rules match for each of the contexts
// that the price set is configured for // that the price set is configured for
const psmaSubQueryKnex = knex({ const priceSubQueryKnex = knex({
psma: "price_set_money_amount", price: "price",
}) })
.select({ .select({
id: "psma1.id", id: "price1.id",
amount: "psma1.amount", amount: "price1.amount",
min_quantity: "psma1.min_quantity", min_quantity: "price1.min_quantity",
max_quantity: "psma1.max_quantity", max_quantity: "price1.max_quantity",
currency_code: "psma1.currency_code", currency_code: "price1.currency_code",
price_set_id: "psma1.price_set_id", price_set_id: "price1.price_set_id",
rules_count: "psma1.rules_count", rules_count: "price1.rules_count",
price_list_id: "psma1.price_list_id", price_list_id: "price1.price_list_id",
pl_rules_count: "pl.rules_count", pl_rules_count: "pl.rules_count",
pl_type: "pl.type", pl_type: "pl.type",
has_price_list: knex.raw( has_price_list: knex.raw(
"case when psma1.price_list_id IS NULL then False else True end" "case when price1.price_list_id IS NULL then False else True end"
), ),
}) })
.leftJoin("price_set_money_amount as psma1", "psma1.id", "psma1.id") .leftJoin("price as price1", "price1.id", "price1.id")
.leftJoin("price_rule as pr", "pr.price_set_money_amount_id", "psma1.id") .leftJoin("price_rule as pr", "pr.price_id", "price1.id")
.leftJoin("price_list as pl", "pl.id", "psma1.price_list_id") .leftJoin("price_list as pl", "pl.id", "price1.price_list_id")
.leftJoin("price_list_rule as plr", "plr.price_list_id", "pl.id") .leftJoin("price_list_rule as plr", "plr.price_list_id", "pl.id")
.leftJoin( .leftJoin(
"price_list_rule_value as plrv", "price_list_rule_value as plrv",
@@ -90,31 +90,31 @@ export class PricingRepository
{ column: "rules_count", order: "desc" }, { column: "rules_count", order: "desc" },
{ column: "pl.rules_count", order: "desc" }, { column: "pl.rules_count", order: "desc" },
]) ])
.groupBy("psma1.id", "pl.id") .groupBy("price1.id", "pl.id")
.having( .having(
knex.raw( knex.raw(
"count(DISTINCT rt.rule_attribute) = psma1.rules_count AND psma1.price_list_id IS NULL" "count(DISTINCT rt.rule_attribute) = price1.rules_count AND price1.price_list_id IS NULL"
) )
) )
.orHaving( .orHaving(
knex.raw( knex.raw(
"count(DISTINCT plrt.rule_attribute) = pl.rules_count AND psma1.price_list_id IS NOT NULL" "count(DISTINCT plrt.rule_attribute) = pl.rules_count AND price1.price_list_id IS NOT NULL"
) )
) )
psmaSubQueryKnex.orWhere((q) => { priceSubQueryKnex.orWhere((q) => {
for (const [key, value] of Object.entries(context)) { for (const [key, value] of Object.entries(context)) {
q.orWhere({ q.orWhere({
"rt.rule_attribute": key, "rt.rule_attribute": key,
"pr.value": value, "pr.value": value,
}) })
} }
q.orWhere("psma1.rules_count", "=", 0) q.orWhere("price1.rules_count", "=", 0)
q.whereNull("psma1.price_list_id") q.whereNull("price1.price_list_id")
}) })
psmaSubQueryKnex.orWhere((q) => { priceSubQueryKnex.orWhere((q) => {
q.whereNotNull("psma1.price_list_id") q.whereNotNull("price1.price_list_id")
.andWhere(function () { .andWhere(function () {
this.whereNull("pl.starts_at").orWhere("pl.starts_at", "<=", date) this.whereNull("pl.starts_at").orWhere("pl.starts_at", "<=", date)
}) })
@@ -141,9 +141,9 @@ export class PricingRepository
"pr.value": value, "pr.value": value,
}) })
} }
this.andWhere("psma1.rules_count", ">", 0) this.andWhere("price1.rules_count", ">", 0)
}) })
this.orWhere("psma1.rules_count", "=", 0) this.orWhere("price1.rules_count", "=", 0)
}) })
}) })
}) })
@@ -152,38 +152,38 @@ export class PricingRepository
ps: "price_set", ps: "price_set",
}) })
.select({ .select({
id: "psma.id", id: "price.id",
price_set_id: "ps.id", price_set_id: "ps.id",
amount: "psma.amount", amount: "price.amount",
min_quantity: "psma.min_quantity", min_quantity: "price.min_quantity",
max_quantity: "psma.max_quantity", max_quantity: "price.max_quantity",
currency_code: "psma.currency_code", currency_code: "price.currency_code",
default_priority: "rt.default_priority", default_priority: "rt.default_priority",
rules_count: "psma.rules_count", rules_count: "price.rules_count",
pl_rules_count: "psma.pl_rules_count", pl_rules_count: "price.pl_rules_count",
price_list_type: "psma.pl_type", price_list_type: "price.pl_type",
price_list_id: "psma.price_list_id", price_list_id: "price.price_list_id",
}) })
.join(psmaSubQueryKnex.as("psma"), "psma.price_set_id", "ps.id") .join(priceSubQueryKnex.as("price"), "price.price_set_id", "ps.id")
.leftJoin("price_rule as pr", "pr.price_set_money_amount_id", "psma.id") .leftJoin("price_rule as pr", "pr.price_id", "price.id")
.leftJoin("rule_type as rt", "rt.id", "pr.rule_type_id") .leftJoin("rule_type as rt", "rt.id", "pr.rule_type_id")
.whereIn("ps.id", pricingFilters.id) .whereIn("ps.id", pricingFilters.id)
.andWhere("psma.currency_code", "=", currencyCode) .andWhere("price.currency_code", "=", currencyCode)
.orderBy([ .orderBy([
{ column: "psma.has_price_list", order: "asc" }, { column: "price.has_price_list", order: "asc" },
{ column: "amount", order: "asc" }, { column: "amount", order: "asc" },
{ column: "rules_count", order: "desc" }, { column: "rules_count", order: "desc" },
{ column: "default_priority", order: "desc" }, { column: "default_priority", order: "desc" },
]) ])
if (quantity) { if (quantity) {
priceSetQueryKnex.where("psma.min_quantity", "<=", quantity) priceSetQueryKnex.where("price.min_quantity", "<=", quantity)
priceSetQueryKnex.andWhere("psma.max_quantity", ">=", quantity) priceSetQueryKnex.andWhere("price.max_quantity", ">=", quantity)
} else { } else {
priceSetQueryKnex.andWhere(function () { priceSetQueryKnex.andWhere(function () {
this.andWhere("psma.min_quantity", "<=", "1").orWhereNull( this.andWhere("price.min_quantity", "<=", "1").orWhereNull(
"psma.min_quantity" "price.min_quantity"
) )
}) })
} }
+11 -14
View File
@@ -22,11 +22,11 @@ export async function run({
logger.info(`Loading seed data from ${path}...`) logger.info(`Loading seed data from ${path}...`)
const { priceSetsData, priceSetMoneyAmountsData } = await import( const { priceSetsData, pricesData } = await import(
resolve(process.cwd(), path) resolve(process.cwd(), path)
).catch((e) => { ).catch((e) => {
logger?.error( logger?.error(
`Failed to load seed data from ${path}. Please, provide a relative path and check that you export the following: priceSetsData and priceSetMoneyAmountsData.${EOL}${e}` `Failed to load seed data from ${path}. Please, provide a relative path and check that you export the following: priceSetsData and pricesData.${EOL}${e}`
) )
throw e throw e
}) })
@@ -44,10 +44,10 @@ export async function run({
const manager = orm.em.fork() const manager = orm.em.fork()
try { try {
logger.info("Inserting price_set & price_set_money_amount") logger.info("Inserting price_sets & prices")
await createPriceSets(manager as any, priceSetsData) await createPriceSets(manager, priceSetsData)
await createPriceSetMoneyAmounts(manager as any, priceSetMoneyAmountsData) await createPrices(manager, pricesData)
} catch (e) { } catch (e) {
logger.error( logger.error(
`Failed to insert the seed data in the PostgreSQL database ${dbData.clientUrl}.${EOL}${e}` `Failed to insert the seed data in the PostgreSQL database ${dbData.clientUrl}.${EOL}${e}`
@@ -70,18 +70,15 @@ async function createPriceSets(
return priceSets return priceSets
} }
async function createPriceSetMoneyAmounts( async function createPrices(
manager: SqlEntityManager<PostgreSqlDriver>, manager: SqlEntityManager<PostgreSqlDriver>,
data: RequiredEntityData<PricingModels.PriceSetMoneyAmount>[] data: RequiredEntityData<PricingModels.Price>[]
) { ) {
const priceSetMoneyAmounts = data.map((priceSetMoneyAmountData) => { const prices = data.map((priceData) => {
return manager.create( return manager.create(PricingModels.Price, priceData)
PricingModels.PriceSetMoneyAmount,
priceSetMoneyAmountData
)
}) })
await manager.persistAndFlush(priceSetMoneyAmounts) await manager.persistAndFlush(prices)
return priceSetMoneyAmounts return prices
} }
+167 -205
View File
@@ -2,6 +2,7 @@ import {
AddPricesDTO, AddPricesDTO,
Context, Context,
CreatePriceListRuleDTO, CreatePriceListRuleDTO,
CreatePricesDTO,
DAL, DAL,
InternalModuleDeclaration, InternalModuleDeclaration,
ModuleJoinerConfig, ModuleJoinerConfig,
@@ -14,33 +15,33 @@ import {
RuleTypeDTO, RuleTypeDTO,
} from "@medusajs/types" } from "@medusajs/types"
import { import {
arrayDifference,
deduplicate,
generateEntityId,
groupBy,
InjectManager, InjectManager,
InjectTransactionManager, InjectTransactionManager,
MedusaContext, MedusaContext,
MedusaError, MedusaError,
ModulesSdkUtils, ModulesSdkUtils,
PriceListType, PriceListType,
arrayDifference,
deduplicate,
groupBy,
removeNullish, removeNullish,
} from "@medusajs/utils" } from "@medusajs/utils"
import { import {
Price,
PriceList, PriceList,
PriceListRule, PriceListRule,
PriceListRuleValue, PriceListRuleValue,
PriceRule, PriceRule,
PriceSet, PriceSet,
PriceSetMoneyAmount,
PriceSetRuleType, PriceSetRuleType,
RuleType, RuleType,
} from "@models" } from "@models"
import { PriceListService, RuleTypeService } from "@services" import {PriceListService, RuleTypeService} from "@services"
import { ServiceTypes } from "@types" import {validatePriceListDates} from "@utils"
import { validatePriceListDates } from "@utils" import {entityNameToLinkableKeysMap, joinerConfig} from "../joiner-config"
import { entityNameToLinkableKeysMap, joinerConfig } from "../joiner-config"
type InjectedDependencies = { type InjectedDependencies = {
baseRepository: DAL.RepositoryService baseRepository: DAL.RepositoryService
@@ -49,7 +50,7 @@ type InjectedDependencies = {
ruleTypeService: RuleTypeService<any> ruleTypeService: RuleTypeService<any>
priceRuleService: ModulesSdkTypes.InternalModuleService<any> priceRuleService: ModulesSdkTypes.InternalModuleService<any>
priceSetRuleTypeService: ModulesSdkTypes.InternalModuleService<any> priceSetRuleTypeService: ModulesSdkTypes.InternalModuleService<any>
priceSetMoneyAmountService: ModulesSdkTypes.InternalModuleService<any> priceService: ModulesSdkTypes.InternalModuleService<any>
priceListService: PriceListService<any> priceListService: PriceListService<any>
priceListRuleService: ModulesSdkTypes.InternalModuleService<any> priceListRuleService: ModulesSdkTypes.InternalModuleService<any>
priceListRuleValueService: ModulesSdkTypes.InternalModuleService<any> priceListRuleValueService: ModulesSdkTypes.InternalModuleService<any>
@@ -60,7 +61,7 @@ const generateMethodForModels = [
PriceListRule, PriceListRule,
PriceListRuleValue, PriceListRuleValue,
PriceRule, PriceRule,
PriceSetMoneyAmount, Price,
PriceSetRuleType, PriceSetRuleType,
RuleType, RuleType,
] ]
@@ -70,7 +71,7 @@ export default class PricingModuleService<
TRuleType extends RuleType = RuleType, TRuleType extends RuleType = RuleType,
TPriceRule extends PriceRule = PriceRule, TPriceRule extends PriceRule = PriceRule,
TPriceSetRuleType extends PriceSetRuleType = PriceSetRuleType, TPriceSetRuleType extends PriceSetRuleType = PriceSetRuleType,
TPriceSetMoneyAmount extends PriceSetMoneyAmount = PriceSetMoneyAmount, TPrice extends Price = Price,
TPriceList extends PriceList = PriceList, TPriceList extends PriceList = PriceList,
TPriceListRule extends PriceListRule = PriceListRule, TPriceListRule extends PriceListRule = PriceListRule,
TPriceListRuleValue extends PriceListRuleValue = PriceListRuleValue TPriceListRuleValue extends PriceListRuleValue = PriceListRuleValue
@@ -79,7 +80,7 @@ export default class PricingModuleService<
InjectedDependencies, InjectedDependencies,
PricingTypes.PriceSetDTO, PricingTypes.PriceSetDTO,
{ {
PriceSetMoneyAmount: { dto: PricingTypes.PriceSetMoneyAmountDTO } Price: { dto: PricingTypes.PriceDTO }
PriceRule: { PriceRule: {
dto: PricingTypes.PriceRuleDTO dto: PricingTypes.PriceRuleDTO
create: PricingTypes.CreatePriceRuleDTO create: PricingTypes.CreatePriceRuleDTO
@@ -102,7 +103,7 @@ export default class PricingModuleService<
protected readonly priceSetService_: ModulesSdkTypes.InternalModuleService<TPriceSet> protected readonly priceSetService_: ModulesSdkTypes.InternalModuleService<TPriceSet>
protected readonly priceRuleService_: ModulesSdkTypes.InternalModuleService<TPriceRule> protected readonly priceRuleService_: ModulesSdkTypes.InternalModuleService<TPriceRule>
protected readonly priceSetRuleTypeService_: ModulesSdkTypes.InternalModuleService<TPriceSetRuleType> protected readonly priceSetRuleTypeService_: ModulesSdkTypes.InternalModuleService<TPriceSetRuleType>
protected readonly priceSetMoneyAmountService_: ModulesSdkTypes.InternalModuleService<TPriceSetMoneyAmount> protected readonly priceService_: ModulesSdkTypes.InternalModuleService<TPrice>
protected readonly priceListService_: PriceListService<TPriceList> protected readonly priceListService_: PriceListService<TPriceList>
protected readonly priceListRuleService_: ModulesSdkTypes.InternalModuleService<TPriceListRule> protected readonly priceListRuleService_: ModulesSdkTypes.InternalModuleService<TPriceListRule>
protected readonly priceListRuleValueService_: ModulesSdkTypes.InternalModuleService<TPriceListRuleValue> protected readonly priceListRuleValueService_: ModulesSdkTypes.InternalModuleService<TPriceListRuleValue>
@@ -115,7 +116,7 @@ export default class PricingModuleService<
priceSetService, priceSetService,
priceRuleService, priceRuleService,
priceSetRuleTypeService, priceSetRuleTypeService,
priceSetMoneyAmountService, priceService,
priceListService, priceListService,
priceListRuleService, priceListRuleService,
priceListRuleValueService, priceListRuleValueService,
@@ -132,7 +133,7 @@ export default class PricingModuleService<
this.ruleTypeService_ = ruleTypeService this.ruleTypeService_ = ruleTypeService
this.priceRuleService_ = priceRuleService this.priceRuleService_ = priceRuleService
this.priceSetRuleTypeService_ = priceSetRuleTypeService this.priceSetRuleTypeService_ = priceSetRuleTypeService
this.priceSetMoneyAmountService_ = priceSetMoneyAmountService this.priceService_ = priceService
this.priceListService_ = priceListService this.priceListService_ = priceListService
this.priceListRuleService_ = priceListRuleService this.priceListRuleService_ = priceListRuleService
this.priceListRuleValueService_ = priceListRuleValueService this.priceListRuleValueService_ = priceListRuleValueService
@@ -228,20 +229,20 @@ export default class PricingModuleService<
@MedusaContext() sharedContext: Context = {} @MedusaContext() sharedContext: Context = {}
): Promise<PriceSetDTO | PriceSetDTO[]> { ): Promise<PriceSetDTO | PriceSetDTO[]> {
const input = Array.isArray(data) ? data : [data] const input = Array.isArray(data) ? data : [data]
const priceSets = await this.create_(input, sharedContext) const priceSets = await this.create_(input, sharedContext)
const dbPriceSets = await this.list( const dbPriceSets = await this.list(
{ id: priceSets.filter((p) => !!p).map((p) => p!.id) }, { id: priceSets.map((p) => p.id) },
{ { relations: ["rule_types", "prices", "price_rules"] },
relations: ["rule_types", "price_set_money_amounts", "price_rules"],
},
sharedContext sharedContext
) )
return (Array.isArray(data) ? dbPriceSets : dbPriceSets[0]) as unknown as // Ensure the output to be in the same order as the input
| PriceSetDTO const results = priceSets.map((priceSet) => {
| PriceSetDTO[] return dbPriceSets.find((p) => p.id === priceSet.id)!
})
return Array.isArray(data) ? results : results[0]
} }
@InjectTransactionManager("baseRepository_") @InjectTransactionManager("baseRepository_")
@@ -249,14 +250,14 @@ export default class PricingModuleService<
data: PricingTypes.CreatePriceSetDTO[], data: PricingTypes.CreatePriceSetDTO[],
@MedusaContext() sharedContext: Context = {} @MedusaContext() sharedContext: Context = {}
) { ) {
const input = Array.isArray(data) ? data : [data]
const ruleAttributes = data const ruleAttributes = data
.map((d) => d.rules?.map((r) => r.rule_attribute) ?? []) .map((d) => d.rules?.map((r) => r.rule_attribute) ?? [])
.flat() .flat()
const ruleTypes = await this.ruleTypeService_.list( const ruleTypes = await this.ruleTypeService_.list(
{ { rule_attribute: ruleAttributes },
rule_attribute: ruleAttributes,
},
{ take: null }, { take: null },
sharedContext sharedContext
) )
@@ -293,77 +294,82 @@ export default class PricingModuleService<
) )
} }
// Bulk create price sets const ruleSetRuleTypeToCreateMap: Map<string, TPriceSetRuleType> = new Map()
const priceSetData = data.map(({ rules, prices, ...rest }) => rest)
const createdPriceSets = await this.priceSetService_.create( const toCreate = input.map((inputData) => {
priceSetData, const id = generateEntityId(
sharedContext (inputData as unknown as TPriceSet).id,
"pset"
) )
// Price set rule types const { prices, rules = [], ...rest } = inputData
const ruleTypeData = data.flatMap(
(item, index) =>
item.rules?.map((rule) => ({
rule_type: ruleTypeMap.get(rule.rule_attribute),
price_set: createdPriceSets[index],
})) || []
)
if (ruleTypeData.length > 0) { let pricesData: CreatePricesDTO[] = []
await this.priceSetRuleTypeService_.create(
ruleTypeData as unknown as PricingTypes.CreatePriceSetRuleTypeDTO[], rules.forEach((rule) => {
sharedContext const priceSetRuleType = {
rule_type_id: ruleTypeMap.get(rule.rule_attribute).id,
price_set_id: id,
} as TPriceSetRuleType
ruleSetRuleTypeToCreateMap.set(
JSON.stringify(priceSetRuleType),
priceSetRuleType
) )
})
if (inputData.prices) {
pricesData = inputData.prices.map((price) => {
let { rules: priceRules = {}, ...rest } = price
const cleanRules = priceRules ? removeNullish(priceRules) : {}
const numberOfRules = Object.keys(cleanRules).length
const rulesDataMap = new Map()
Object.entries(priceRules).map(([attribute, value]) => {
const rule = {
price_set_id: id,
rule_type_id: ruleTypeMap.get(attribute).id,
value,
} }
rulesDataMap.set(JSON.stringify(rule), rule)
const priceSetMoneyAmountData: unknown[] = [] const priceSetRuleType = {
const priceRulesData: unknown[] = [] rule_type_id: ruleTypeMap.get(attribute).id,
price_set_id: id,
} as TPriceSetRuleType
for (const [index, item] of data.entries()) { ruleSetRuleTypeToCreateMap.set(
for (const price of item.prices || []) { JSON.stringify(priceSetRuleType),
const cleanRules = price.rules ? removeNullish(price.rules) : {} priceSetRuleType
const numberOfRules = Object.entries(cleanRules).length )
})
const priceSetMoneyAmount = { return {
...price, ...rest,
price_set_id: createdPriceSets[index].id,
title: "test", // TODO: accept title title: "test", // TODO: accept title
rules_count: numberOfRules, rules_count: numberOfRules,
price_rules: Array.from(rulesDataMap.values()),
} }
priceSetMoneyAmountData.push(priceSetMoneyAmount)
for (const [k, v] of Object.entries(cleanRules)) {
priceRulesData.push({
price_set_money_amount_id: null, // Updated later
rule_type_id: ruleTypeMap.get(k).id,
price_set_id: createdPriceSets[index].id,
value: v,
price_list_id: "test",
}) })
} }
}
}
// Bulk create price set money amounts return {
const createdPriceSetMoneyAmounts = ...rest,
await this.priceSetMoneyAmountService_.create( id,
priceSetMoneyAmountData as PricingTypes.CreatePriceSetMoneyAmountDTO[], prices: pricesData,
}
})
// Bulk create price sets
const createdPriceSets = await this.priceSetService_.create(
toCreate,
sharedContext sharedContext
) )
// Update price set money amount references if (ruleSetRuleTypeToCreateMap.size) {
for (let i = 0, j = 0; i < priceSetMoneyAmountData.length; i++) { await this.priceSetRuleTypeService_.create(
const rulesCount = (priceSetMoneyAmountData[i] as any).rules_count Array.from(ruleSetRuleTypeToCreateMap.values()),
for (let k = 0; k < rulesCount; k++, j++) {
;(priceRulesData[j] as any).price_set_money_amount_id =
createdPriceSetMoneyAmounts[i].id
}
}
// Price rules
if (priceRulesData.length > 0) {
await this.priceRuleService_.create(
priceRulesData as ServiceTypes.CreatePriceRuleDTO[],
sharedContext sharedContext
) )
} }
@@ -392,9 +398,7 @@ export default class PricingModuleService<
return await this.list( return await this.list(
{ id: priceSets.map(({ id }) => id) }, { id: priceSets.map(({ id }) => id) },
{ { relations: ["rule_types"] }
relations: ["rule_types"],
}
) )
} }
@@ -417,7 +421,6 @@ export default class PricingModuleService<
) )
const priceSetMap = new Map(priceSets.map((p) => [p.id, p])) const priceSetMap = new Map(priceSets.map((p) => [p.id, p]))
const invalidPriceSetInputs = inputs.filter( const invalidPriceSetInputs = inputs.filter(
(d) => !priceSetMap.has(d.priceSetId) (d) => !priceSetMap.has(d.priceSetId)
) )
@@ -434,7 +437,7 @@ export default class PricingModuleService<
const ruleTypes = await this.ruleTypeService_.list( const ruleTypes = await this.ruleTypeService_.list(
{ {
rule_attribute: inputs rule_attribute: inputs
.map((d) => d.rules.map((r) => r.attribute)) .map((data) => data.rules.map((r) => r.attribute))
.flat(), .flat(),
}, },
{ take: null }, { take: null },
@@ -461,23 +464,21 @@ export default class PricingModuleService<
const priceSetRuleTypesCreate: PricingTypes.CreatePriceSetRuleTypeDTO[] = [] const priceSetRuleTypesCreate: PricingTypes.CreatePriceSetRuleTypeDTO[] = []
inputs.forEach((d) => { inputs.forEach((data) => {
const priceSet = priceSetMap.get(d.priceSetId) for (const rule of data.rules) {
if (priceSetRuleTypeMap.get(data.priceSetId)!.has(rule.attribute)) {
for (const r of d.rules) {
if (priceSetRuleTypeMap.get(d.priceSetId)!.has(r.attribute)) {
continue continue
} }
priceSetRuleTypesCreate.push({ priceSetRuleTypesCreate.push({
rule_type: ruleTypeMap.get(r.attribute) as RuleTypeDTO, rule_type_id: ruleTypeMap.get(rule.attribute)!.id,
price_set: priceSet as unknown as PriceSetDTO, price_set_id: priceSetMap.get(data.priceSetId)!.id,
}) })
} }
}) })
await this.priceSetRuleTypeService_.create( await this.priceSetRuleTypeService_.create(
priceSetRuleTypesCreate as unknown as PricingTypes.CreatePriceSetRuleTypeDTO[], priceSetRuleTypesCreate,
sharedContext sharedContext
) )
@@ -503,11 +504,11 @@ export default class PricingModuleService<
await this.addPrices_(input, sharedContext) await this.addPrices_(input, sharedContext)
return (await this.list( return await this.list(
{ id: input.map((d) => d.priceSetId) }, { id: input.map((d) => d.priceSetId) },
{ relations: ["price_set_money_amounts"] }, { relations: ["prices"] },
sharedContext sharedContext
)) as unknown as PricingTypes.PriceSetDTO[] | PricingTypes.PriceSetDTO )
} }
@InjectTransactionManager("baseRepository_") @InjectTransactionManager("baseRepository_")
@@ -558,7 +559,7 @@ export default class PricingModuleService<
} }
}) })
const priceSetMoneyAmountsBulkData: unknown[] = input.flatMap( const pricesToCreate: PricingTypes.CreatePriceDTO[] = input.flatMap(
({ priceSetId, prices }) => ({ priceSetId, prices }) =>
prices.map((price) => { prices.map((price) => {
const numberOfRules = Object.entries(price?.rules ?? {}).length const numberOfRules = Object.entries(price?.rules ?? {}).length
@@ -572,9 +573,8 @@ export default class PricingModuleService<
}) })
) )
const createdPriceSetMoneyAmounts = const createdPrices = await this.priceService_.create(
await this.priceSetMoneyAmountService_.create( pricesToCreate,
priceSetMoneyAmountsBulkData as ServiceTypes.CreatePriceSetMoneyAmountDTO[],
sharedContext sharedContext
) )
@@ -583,10 +583,11 @@ export default class PricingModuleService<
const priceRulesBulkData = input.flatMap(({ priceSetId, prices }) => const priceRulesBulkData = input.flatMap(({ priceSetId, prices }) =>
prices.flatMap((ma) => { prices.flatMap((ma) => {
const rules = ma.rules ?? {} const rules = ma.rules ?? {}
const priceSetMoneyAmount = createdPriceSetMoneyAmounts[rulesCursor] const price = createdPrices[rulesCursor]
rulesCursor++ rulesCursor++
return Object.entries(rules).map(([k, v]) => ({ return Object.entries(rules).map(([k, v]) => ({
price_set_money_amount_id: priceSetMoneyAmount.id, price_id: price.id,
rule_type_id: ruleTypeMap.get(priceSetId)!.get(k)!.id, rule_type_id: ruleTypeMap.get(priceSetId)!.get(k)!.id,
price_set_id: priceSetId, price_set_id: priceSetId,
value: v, value: v,
@@ -605,14 +606,12 @@ export default class PricingModuleService<
@MedusaContext() sharedContext: Context = {} @MedusaContext() sharedContext: Context = {}
): Promise<void> { ): Promise<void> {
const priceSets = await this.priceSetService_.list( const priceSets = await this.priceSetService_.list(
{ { id: data.map((d) => d.id) },
id: data.map((d) => d.id),
},
{}, {},
sharedContext sharedContext
) )
const priceSetIds = priceSets.map((ps) => ps.id)
const priceSetIds = priceSets.map((ps) => ps.id)
const ruleTypes = await this.ruleTypeService_.list( const ruleTypes = await this.ruleTypeService_.list(
{ {
rule_attribute: data.map((d) => d.rules || []).flat(), rule_attribute: data.map((d) => d.rules || []).flat(),
@@ -620,26 +619,17 @@ export default class PricingModuleService<
{ take: null }, { take: null },
sharedContext sharedContext
) )
const ruleTypeIds = ruleTypes.map((rt) => rt.id)
const ruleTypeIds = ruleTypes.map((rt) => rt.id)
const priceSetRuleTypes = await this.priceSetRuleTypeService_.list( const priceSetRuleTypes = await this.priceSetRuleTypeService_.list(
{ { price_set_id: priceSetIds, rule_type_id: ruleTypeIds },
price_set_id: priceSetIds,
rule_type_id: ruleTypeIds,
},
{ take: null }, { take: null },
sharedContext sharedContext
) )
const priceRules = await this.priceRuleService_.list( const priceRules = await this.priceRuleService_.list(
{ { price_set_id: priceSetIds, rule_type_id: ruleTypeIds },
price_set_id: priceSetIds, { select: ["price"], take: null },
rule_type_id: ruleTypeIds,
},
{
select: ["price_set_money_amount"],
take: null,
},
sharedContext sharedContext
) )
@@ -648,8 +638,8 @@ export default class PricingModuleService<
sharedContext sharedContext
) )
await this.priceSetMoneyAmountService_.delete( await this.priceService_.delete(
priceRules.map((pr) => pr.price_set_money_amount.id), priceRules.map((pr) => pr.price.id),
sharedContext sharedContext
) )
} }
@@ -663,9 +653,7 @@ export default class PricingModuleService<
return await this.baseRepository_.serialize<PricingTypes.PriceSetDTO[]>( return await this.baseRepository_.serialize<PricingTypes.PriceSetDTO[]>(
priceSets, priceSets,
{ { populate: true }
populate: true,
}
) )
} }
@@ -678,9 +666,7 @@ export default class PricingModuleService<
return await this.baseRepository_.serialize<PricingTypes.PriceListDTO[]>( return await this.baseRepository_.serialize<PricingTypes.PriceListDTO[]>(
priceLists, priceLists,
{ { populate: true }
populate: true,
}
) )
} }
@@ -759,7 +745,7 @@ export default class PricingModuleService<
) )
// Create the values for the rule // Create the values for the rule
for (const ruleValue of ruleValues as string[]) { for (const ruleValue of ruleValues) {
await this.priceListRuleValueService_.create( await this.priceListRuleValueService_.create(
[{ price_list_rule_id: priceListRule.id, value: ruleValue }], [{ price_list_rule_id: priceListRule.id, value: ruleValue }],
sharedContext sharedContext
@@ -767,24 +753,21 @@ export default class PricingModuleService<
} }
} }
for (const price of prices) { for (const priceData of prices) {
const { const {
price_set_id: priceSetId, price_set_id: priceSetId,
rules: priceRules = {}, rules: priceRules = {},
...psmaData ...rest
} = price } = priceData
const [priceSetMoneyAmount] = const createdPrice = await this.priceService_.create(
await this.priceSetMoneyAmountService_.create(
[
{ {
price_set_id: priceSetId, price_set_id: priceSetId,
price_list_id: priceList.id, price_list_id: priceList.id,
title: "test", title: "test",
rules_count: Object.keys(priceRules).length, rules_count: Object.keys(priceRules).length,
...psmaData, ...rest,
}, },
],
sharedContext sharedContext
) )
@@ -794,7 +777,7 @@ export default class PricingModuleService<
price_set_id: priceSetId, price_set_id: priceSetId,
rule_type_id: ruleTypeMap.get(ruleAttribute)!?.id, rule_type_id: ruleTypeMap.get(ruleAttribute)!?.id,
value: ruleValue, value: ruleValue,
price_set_money_amount_id: priceSetMoneyAmount.id, price_id: createdPrice.id,
} }
}), }),
sharedContext sharedContext
@@ -814,9 +797,7 @@ export default class PricingModuleService<
return await this.baseRepository_.serialize<PricingTypes.PriceListDTO[]>( return await this.baseRepository_.serialize<PricingTypes.PriceListDTO[]>(
priceLists, priceLists,
{ { populate: true }
populate: true,
}
) )
} }
@@ -913,7 +894,7 @@ export default class PricingModuleService<
sharedContext sharedContext
) )
for (const ruleValue of ruleValues as string[]) { for (const ruleValue of ruleValues) {
await this.priceListRuleValueService_.create( await this.priceListRuleValueService_.create(
[{ price_list_rule_id: priceListRule.id, value: ruleValue }], [{ price_list_rule_id: priceListRule.id, value: ruleValue }],
sharedContext sharedContext
@@ -979,7 +960,7 @@ export default class PricingModuleService<
): Promise<PricingTypes.PriceListDTO[]> { ): Promise<PricingTypes.PriceListDTO[]> {
const ruleTypeAttributes: string[] = [] const ruleTypeAttributes: string[] = []
const priceListIds: string[] = [] const priceListIds: string[] = []
const psmaIds: string[] = [] const priceIds: string[] = []
const priceSetIds = data const priceSetIds = data
.map((d) => d.prices.map((price) => price.price_set_id)) .map((d) => d.prices.map((price) => price.price_set_id))
.flat() .flat()
@@ -988,22 +969,19 @@ export default class PricingModuleService<
priceListIds.push(priceListData.price_list_id) priceListIds.push(priceListData.price_list_id)
for (const price of priceListData.prices) { for (const price of priceListData.prices) {
psmaIds.push(price.id) priceIds.push(price.id)
ruleTypeAttributes.push(...Object.keys(price.rules || {})) ruleTypeAttributes.push(...Object.keys(price.rules || {}))
} }
} }
const psmas = await this.listPriceSetMoneyAmounts( const prices = await this.listPrices(
{ id: psmaIds }, { id: priceIds },
{ { take: null, relations: ["price_rules"] },
take: null,
relations: ["price_rules"],
},
sharedContext sharedContext
) )
const psmaMap: Map<string, PricingTypes.PriceSetMoneyAmountDTO> = new Map( const priceMap: Map<string, PricingTypes.PriceDTO> = new Map(
psmas.map((psma) => [psma.id, psma]) prices.map((price) => [price.id, price])
) )
const ruleTypes = await this.listRuleTypes( const ruleTypes = await this.listRuleTypes(
@@ -1032,6 +1010,7 @@ export default class PricingModuleService<
} }
acc.set(curr.id, priceSetRuleAttributeSet) acc.set(curr.id, priceSetRuleAttributeSet)
return acc return acc
}, },
new Map() new Map()
@@ -1080,40 +1059,41 @@ export default class PricingModuleService<
) )
} }
const moneyAmountsToUpdate: PricingTypes.UpdateMoneyAmountDTO[] = [] const priceRuleIdsToDelete: string[] = []
const priceRulesToDelete: string[] = []
const priceRulesToCreate: PricingTypes.CreatePriceRuleDTO[] = [] const priceRulesToCreate: PricingTypes.CreatePriceRuleDTO[] = []
const psmaToUpdate: ServiceTypes.UpdatePriceSetMoneyAmountDTO[] = [] const pricesToUpdate: (PricingTypes.UpdatePriceDTO & {
rules_count: number
})[] = []
for (const price of prices) { for (const priceData of prices) {
const { rules, price_set_id, ...priceData } = price const { rules, price_set_id, ...rest } = priceData
const priceSetMoneyAmount = psmaMap.get(price.id)! const price = priceMap.get(rest.id)!
const priceRules = priceSetMoneyAmount.price_rules! const priceRules = price.price_rules!
if (typeof rules === "undefined") { if (typeof rules === "undefined") {
continue continue
} }
psmaToUpdate.push({ pricesToUpdate.push({
...priceData, ...rest,
rules_count: Object.keys(rules).length, rules_count: Object.keys(rules).length,
}) })
priceRulesToDelete.push(...priceRules.map((pr) => pr.id)) priceRuleIdsToDelete.push(...priceRules.map((pr) => pr.id))
priceRulesToCreate.push( priceRulesToCreate.push(
...Object.entries(rules).map(([ruleAttribute, ruleValue]) => ({ ...Object.entries(rules).map(([ruleAttribute, ruleValue]) => ({
price_set_id: price.price_set_id, price_set_id,
rule_type_id: ruleTypeMap.get(ruleAttribute)!.id, rule_type_id: ruleTypeMap.get(ruleAttribute)!.id,
value: ruleValue, value: ruleValue,
price_set_money_amount_id: priceSetMoneyAmount.id, price_id: price.id,
})) }))
) )
} }
await Promise.all([ await Promise.all([
this.priceRuleService_.delete(priceRulesToDelete), this.priceRuleService_.delete(priceRuleIdsToDelete),
this.priceRuleService_.create(priceRulesToCreate), this.priceRuleService_.create(priceRulesToCreate),
this.priceSetMoneyAmountService_.update(psmaToUpdate), this.priceService_.update(pricesToUpdate),
]) ])
} }
@@ -1133,7 +1113,7 @@ export default class PricingModuleService<
ids: string[], ids: string[],
sharedContext: Context = {} sharedContext: Context = {}
): Promise<void> { ): Promise<void> {
await this.priceSetMoneyAmountService_.delete(ids, sharedContext) await this.priceService_.delete(ids, sharedContext)
} }
@InjectManager("baseRepository_") @InjectManager("baseRepository_")
@@ -1237,15 +1217,15 @@ export default class PricingModuleService<
} }
await Promise.all( await Promise.all(
prices.map(async (price) => { prices.map(async (priceData) => {
const priceRules = price.rules || {} const priceRules = priceData.rules || {}
const noOfRules = Object.keys(priceRules).length const noOfRules = Object.keys(priceRules).length
const [psma] = await this.priceSetMoneyAmountService_.create( const [price] = await this.priceService_.create(
[ [
{ {
...price, ...priceData,
price_set_id: price.price_set_id, price_set_id: priceData.price_set_id,
title: "test", title: "test",
price_list_id: priceList.id, price_list_id: priceList.id,
rules_count: noOfRules, rules_count: noOfRules,
@@ -1257,16 +1237,16 @@ export default class PricingModuleService<
await this.priceRuleService_.create( await this.priceRuleService_.create(
Object.entries(priceRules).map(([ruleAttribute, ruleValue]) => { Object.entries(priceRules).map(([ruleAttribute, ruleValue]) => {
return { return {
price_set_id: price.price_set_id, price_set_id: priceData.price_set_id,
rule_type_id: ruleTypeMap.get(ruleAttribute)!?.id, rule_type_id: ruleTypeMap.get(ruleAttribute)!?.id,
value: ruleValue, value: ruleValue,
price_set_money_amount_id: psma.id, price_id: price.id,
} }
}), }),
sharedContext sharedContext
) )
return psma return price
}) })
) )
} }
@@ -1291,27 +1271,19 @@ export default class PricingModuleService<
): Promise<PricingTypes.PriceListDTO[]> { ): Promise<PricingTypes.PriceListDTO[]> {
const priceLists = await this.priceListService_.list( const priceLists = await this.priceListService_.list(
{ id: data.map((d) => d.price_list_id) }, { id: data.map((d) => d.price_list_id) },
{ { relations: ["price_list_rules", "price_list_rules.rule_type"] },
relations: ["price_list_rules", "price_list_rules.rule_type"],
},
sharedContext sharedContext
) )
const priceListMap = new Map(priceLists.map((p) => [p.id, p])) const priceListMap = new Map(priceLists.map((p) => [p.id, p]))
const ruleTypes = await this.listRuleTypes( const ruleTypes = await this.listRuleTypes(
{ { rule_attribute: data.map((d) => Object.keys(d.rules)).flat() },
rule_attribute: data.map((d) => Object.keys(d.rules)).flat(), { take: null }
},
{
take: null,
}
) )
const ruleTypeMap = new Map(ruleTypes.map((rt) => [rt.rule_attribute, rt])) const ruleTypeMap = new Map(ruleTypes.map((rt) => [rt.rule_attribute, rt]))
const ruleIdsToUpdate: string[] = [] const ruleIdsToUpdate: string[] = []
const rulesToCreate: CreatePriceListRuleDTO[] = [] const rulesToCreate: CreatePriceListRuleDTO[] = []
const priceRuleValues = new Map<string, Map<string, string[]>>() const priceRuleValues = new Map<string, Map<string, string[]>>()
for (const { price_list_id: priceListId, rules } of data) { for (const { price_list_id: priceListId, rules } of data) {
@@ -1325,9 +1297,7 @@ export default class PricingModuleService<
} }
const priceListRulesMap: Map<string, PriceListRule> = new Map( const priceListRulesMap: Map<string, PriceListRule> = new Map(
priceList.price_list_rules priceList.price_list_rules.map((p) => [p.rule_type.rule_attribute, p])
.getItems()
.map((p) => [p.rule_type.rule_attribute, p])
) )
const priceListRuleValues = new Map<string, string[]>() const priceListRuleValues = new Map<string, string[]>()
@@ -1365,9 +1335,7 @@ export default class PricingModuleService<
const [createdRules, priceListValuesToDelete] = await Promise.all([ const [createdRules, priceListValuesToDelete] = await Promise.all([
this.priceListRuleService_.create(rulesToCreate), this.priceListRuleService_.create(rulesToCreate),
this.priceListRuleValueService_.list( this.priceListRuleValueService_.list(
{ { price_list_rule_id: ruleIdsToUpdate },
price_list_rule_id: ruleIdsToUpdate,
},
{ take: null } { take: null }
), ),
]) ])
@@ -1382,6 +1350,7 @@ export default class PricingModuleService<
} }
const values = ruleValues.get(rule_type_id) const values = ruleValues.get(rule_type_id)
if (!values) { if (!values) {
continue continue
} }
@@ -1400,16 +1369,14 @@ export default class PricingModuleService<
sharedContext sharedContext
), ),
this.priceListRuleValueService_.create( this.priceListRuleValueService_.create(
priceListRuleValuesToCreate as ServiceTypes.CreatePriceListRuleValueDTO[], priceListRuleValuesToCreate,
sharedContext sharedContext
), ),
]) ])
return await this.baseRepository_.serialize<PricingTypes.PriceListDTO[]>( return await this.baseRepository_.serialize<PricingTypes.PriceListDTO[]>(
priceLists, priceLists,
{ { populate: true }
populate: true,
}
) )
} }
@@ -1430,15 +1397,13 @@ export default class PricingModuleService<
): Promise<PricingTypes.PriceListDTO[]> { ): Promise<PricingTypes.PriceListDTO[]> {
const priceLists = await this.priceListService_.list( const priceLists = await this.priceListService_.list(
{ id: data.map((d) => d.price_list_id) }, { id: data.map((d) => d.price_list_id) },
{ { relations: ["price_list_rules", "price_list_rules.rule_type"] },
relations: ["price_list_rules", "price_list_rules.rule_type"],
},
sharedContext sharedContext
) )
const priceListMap = new Map(priceLists.map((p) => [p.id, p])) const priceListMap = new Map(priceLists.map((p) => [p.id, p]))
const idsToDelete: string[] = [] const idsToDelete: string[] = []
for (const { price_list_id: priceListId, rules } of data) { for (const { price_list_id: priceListId, rules } of data) {
const priceList = priceListMap.get(priceListId) const priceList = priceListMap.get(priceListId)
@@ -1450,14 +1415,13 @@ export default class PricingModuleService<
} }
const priceListRulesMap: Map<string, PriceListRule> = new Map( const priceListRulesMap: Map<string, PriceListRule> = new Map(
priceList.price_list_rules priceList.price_list_rules.map((p) => [p.rule_type.rule_attribute, p])
.getItems()
.map((p) => [p.rule_type.rule_attribute, p])
) )
await Promise.all( await Promise.all(
rules.map(async (rule_attribute) => { rules.map(async (rule_attribute) => {
const rule = priceListRulesMap.get(rule_attribute) const rule = priceListRulesMap.get(rule_attribute)
if (rule) { if (rule) {
idsToDelete.push(rule.id) idsToDelete.push(rule.id)
} }
@@ -1469,9 +1433,7 @@ export default class PricingModuleService<
return await this.baseRepository_.serialize<PricingTypes.PriceListDTO[]>( return await this.baseRepository_.serialize<PricingTypes.PriceListDTO[]>(
priceLists, priceLists,
{ { populate: true }
populate: true,
}
) )
} }
} }
+7 -8
View File
@@ -1,4 +1,4 @@
import { Context, DAL } from "@medusajs/types" import { Context, DAL, PricingTypes } from "@medusajs/types"
import { import {
InjectTransactionManager, InjectTransactionManager,
MedusaContext, MedusaContext,
@@ -6,7 +6,6 @@ import {
validateRuleAttributes, validateRuleAttributes,
} from "@medusajs/utils" } from "@medusajs/utils"
import { RuleType } from "@models" import { RuleType } from "@models"
import { ServiceTypes } from "@types"
type InjectedDependencies = { type InjectedDependencies = {
ruleTypeRepository: DAL.RepositoryService ruleTypeRepository: DAL.RepositoryService
@@ -26,17 +25,17 @@ export default class RuleTypeService<
} }
create( create(
data: ServiceTypes.CreateRuleTypeDTO, data: PricingTypes.CreateRuleTypeDTO,
sharedContext: Context sharedContext: Context
): Promise<TEntity> ): Promise<TEntity>
create( create(
data: ServiceTypes.CreateRuleTypeDTO[], data: PricingTypes.CreateRuleTypeDTO[],
sharedContext: Context sharedContext: Context
): Promise<TEntity[]> ): Promise<TEntity[]>
@InjectTransactionManager("ruleTypeRepository_") @InjectTransactionManager("ruleTypeRepository_")
async create( async create(
data: ServiceTypes.CreateRuleTypeDTO | ServiceTypes.CreateRuleTypeDTO[], data: PricingTypes.CreateRuleTypeDTO | PricingTypes.CreateRuleTypeDTO[],
@MedusaContext() sharedContext: Context = {} @MedusaContext() sharedContext: Context = {}
): Promise<TEntity | TEntity[]> { ): Promise<TEntity | TEntity[]> {
const data_ = Array.isArray(data) ? data : [data] const data_ = Array.isArray(data) ? data : [data]
@@ -46,12 +45,12 @@ export default class RuleTypeService<
// @ts-ignore // @ts-ignore
update( update(
data: ServiceTypes.UpdateRuleTypeDTO[], data: PricingTypes.UpdateRuleTypeDTO[],
sharedContext: Context sharedContext: Context
): Promise<TEntity[]> ): Promise<TEntity[]>
// @ts-ignore // @ts-ignore
update( update(
data: ServiceTypes.UpdateRuleTypeDTO, data: PricingTypes.UpdateRuleTypeDTO,
sharedContext: Context sharedContext: Context
): Promise<TEntity> ): Promise<TEntity>
@@ -59,7 +58,7 @@ export default class RuleTypeService<
// TODO: add support for selector? and then rm ts ignore // TODO: add support for selector? and then rm ts ignore
// @ts-ignore // @ts-ignore
async update( async update(
data: ServiceTypes.UpdateRuleTypeDTO | ServiceTypes.UpdateRuleTypeDTO[], data: PricingTypes.UpdateRuleTypeDTO | PricingTypes.UpdateRuleTypeDTO[],
@MedusaContext() sharedContext: Context = {} @MedusaContext() sharedContext: Context = {}
): Promise<TEntity | TEntity[]> { ): Promise<TEntity | TEntity[]> {
const data_ = Array.isArray(data) ? data : [data] const data_ = Array.isArray(data) ? data : [data]
-1
View File
@@ -4,5 +4,4 @@ export type InitializeModuleInjectableDependencies = {
logger?: Logger logger?: Logger
} }
export * as RepositoryTypes from "./repositories"
export * as ServiceTypes from "./services" export * as ServiceTypes from "./services"
@@ -1,8 +0,0 @@
export * from "./price-list"
export * from "./price-list-rule"
export * from "./price-list-rule-value"
export * from "./price-rule"
export * from "./price-set"
export * from "./price-set-money-amount"
export * from "./price-set-rule-type"
export * from "./rule-type"
@@ -1,12 +0,0 @@
import { PriceListRule } from "@models"
export interface CreatePriceListRuleValueDTO {
price_list_rule_id?: string
price_list_rule: PriceListRule | string
value: string
}
export interface UpdatePriceListRuleValueDTO {
id: string
value: string
}
@@ -1,16 +0,0 @@
import { PriceListDTO, RuleTypeDTO } from "../services"
export interface CreatePriceListRuleDTO {
rule_type_id?: string
rule_type?: string | RuleTypeDTO
price_list_id?: string
price_list?: string | PriceListDTO
}
export interface UpdatePriceListRuleDTO {
id: string
price_list_id?: string
rule_type_id?: string
price_list?: string
rule_type?: string
}
@@ -1,20 +0,0 @@
import { PriceListStatus, PriceListType } from "@medusajs/utils"
export interface CreatePriceListDTO {
title: string
description: string
starts_at?: string | null
ends_at?: string | null
status?: PriceListStatus
type?: PriceListType
rules_count?: number
}
export interface UpdatePriceListDTO {
id: string
title?: string
starts_at?: string | null
ends_at?: string | null
status?: PriceListStatus
number_rules?: number
}
@@ -1,23 +0,0 @@
import { PriceSet, PriceSetMoneyAmount, RuleType } from "@models"
export interface CreatePriceRuleDTO {
id?: string
price_set_id?: string
price_set?: PriceSet | string
rule_type_id?: string
rule_type?: RuleType | string
value: string
priority?: number
price_set_money_amount_id?: string
price_set_money_amount?: PriceSetMoneyAmount | string
}
export interface UpdatePriceRuleDTO {
id: string
price_set_id?: string
rule_type_id?: string
value?: string
priority?: number
price_set_money_amount_id?: string
price_list_id?: string
}
@@ -1,15 +0,0 @@
import { MoneyAmountDTO, PriceListDTO, PriceSetDTO } from "../services"
export interface UpdatePriceSetMoneyAmountDTO {
id: string
title?: string
price_set?: PriceSetDTO
money_amount?: MoneyAmountDTO
}
export interface CreatePriceSetMoneyAmountDTO {
title?: string
price_set?: PriceSetDTO | string
price_list?: PriceListDTO | string
money_amount?: MoneyAmountDTO | string
}
@@ -1,12 +0,0 @@
import { PriceSetDTO, RuleTypeDTO } from "../services"
export interface CreatePriceSetRuleTypeDTO {
price_set: PriceSetDTO | string
rule_type: RuleTypeDTO | string
}
export interface UpdatePriceSetRuleTypeDTO {
id: string
price_set?: string
rule_type?: string
}
@@ -1,5 +0,0 @@
export interface CreatePriceSetDTO {}
export interface UpdatePriceSetDTO {
id: string
}
@@ -1,13 +0,0 @@
export interface CreateRuleTypeDTO {
id?: string
name: string
rule_attribute: string
default_priority?: number
}
export interface UpdateRuleTypeDTO {
id: string
name?: string
rule_attribute?: string
default_priority?: number
}
@@ -1,10 +1 @@
export * from "./money-amount"
export * from "./price-list" export * from "./price-list"
export * from "./price-list-rule"
export * from "./price-list-rule-value"
export * from "./price-rule"
export * from "./price-set"
export * from "./price-set-money-amount"
export * from "./price-set-rule-type"
export * from "./pricing"
export * from "./rule-type"
@@ -1,35 +0,0 @@
import { BaseFilterable, PriceSetMoneyAmountDTO } from "@medusajs/types"
export interface CreateMoneyAmountDTO {
id?: string
currency_code: string
amount: number
min_quantity?: number | null
max_quantity?: number | null
}
export interface UpdateMoneyAmountDTO {
id: string
currency_code?: string
amount?: number
min_quantity?: number
max_quantity?: number
}
export interface MoneyAmountDTO {
id: string
currency_code?: string | null
amount?: number | null
min_quantity?: number | null
max_quantity?: number | null
price_set_money_amount?: PriceSetMoneyAmountDTO
created_at: Date
updated_at: Date
deleted_at: Date | null
}
export interface FilterableMoneyAmountProps
extends BaseFilterable<FilterableMoneyAmountProps> {
id?: string[]
currency_code?: string | string[]
}
@@ -1,26 +0,0 @@
import { BaseFilterable } from "@medusajs/types"
import { PriceListRule } from "@models"
export interface CreatePriceListRuleValueDTO {
price_list_rule_id?: string
price_list_rule: PriceListRule | string
value: string
}
export interface UpdatePriceListRuleValueDTO {
id: string
value: string
}
export interface PriceListRuleValueDTO {
id: string
value: string
price_list_rule: PriceListRule
}
export interface FilterablePriceListRuleValueProps
extends BaseFilterable<FilterablePriceListRuleValueProps> {
id?: string[]
value?: string[]
price_list_rule_id?: string[]
}
@@ -1,37 +0,0 @@
import {
BaseFilterable,
PriceListDTO,
PriceListRuleValueDTO,
RuleTypeDTO,
} from "@medusajs/types"
export interface CreatePriceListRuleDTO {
rule_type_id?: string
rule_type?: string | RuleTypeDTO
price_list_id?: string
price_list?: string | PriceListDTO
}
export interface UpdatePriceListRuleDTO {
id: string
price_list_id?: string
rule_type_id?: string
price_list?: string
rule_type?: string
}
export interface PriceListRuleDTO {
id: string
value: string
rule_type: RuleTypeDTO
price_list: PriceListDTO
price_list_rule_values?: PriceListRuleValueDTO[]
}
export interface FilterablePriceListRuleProps
extends BaseFilterable<FilterablePriceListRuleProps> {
id?: string[]
value?: string[]
rule_type?: string[]
price_list_id?: string[]
}
@@ -1,10 +1,3 @@
import {
BaseFilterable,
MoneyAmountDTO,
PriceListRuleDTO,
PriceSetMoneyAmountDTO,
RuleTypeDTO,
} from "@medusajs/types"
import { PriceListStatus, PriceListType } from "@medusajs/utils" import { PriceListStatus, PriceListType } from "@medusajs/utils"
export interface CreatePriceListDTO { export interface CreatePriceListDTO {
@@ -25,26 +18,3 @@ export interface UpdatePriceListDTO {
status?: PriceListStatus status?: PriceListStatus
number_rules?: number number_rules?: number
} }
export interface PriceListDTO {
id: string
title?: string
starts_at?: string | null
status?: PriceListStatus
ends_at?: string | null
number_rules?: number
price_set_money_amounts?: PriceSetMoneyAmountDTO[]
money_amounts?: MoneyAmountDTO[]
rule_types?: RuleTypeDTO[]
rules?: PriceListRuleDTO[]
price_list_rules?: PriceListRuleDTO[]
}
export interface FilterablePriceListProps
extends BaseFilterable<FilterablePriceListProps> {
id?: string[]
starts_at?: string[]
ends_at?: string[]
status?: PriceListStatus[]
number_rules?: number[]
}
@@ -1,47 +0,0 @@
import { BaseFilterable, PriceSetDTO, RuleTypeDTO } from "@medusajs/types"
import { PriceSet, PriceSetMoneyAmount, RuleType } from "@models"
export interface CreatePriceRuleDTO {
id?: string
price_set_id?: string
price_set?: PriceSet | string
rule_type_id?: string
rule_type?: RuleType | string
value: string
priority?: number
price_set_money_amount_id?: string
price_set_money_amount?: PriceSetMoneyAmount | string
}
export interface UpdatePriceRuleDTO {
id: string
price_set_id?: string
rule_type_id?: string
value?: string
priority?: number
price_set_money_amount_id?: string
price_list_id?: string
}
export interface PriceRuleDTO {
id: string
price_set_id: string
price_set: PriceSetDTO
rule_type_id: string
rule_type: RuleTypeDTO
value: string
priority: number
price_set_money_amount_id: string
price_list_id: string
created_at: Date
updated_at: Date
deleted_at: Date | null
}
export interface FilterablePriceRuleProps
extends BaseFilterable<FilterablePriceRuleProps> {
id?: string[]
name?: string[]
price_set_id?: string[]
rule_type_id?: string[]
}
@@ -1,43 +0,0 @@
import {
BaseFilterable,
MoneyAmountDTO,
PriceListDTO,
PriceRuleDTO,
PriceSetDTO,
} from "@medusajs/types"
export interface UpdatePriceSetMoneyAmountDTO {
id: string
title?: string
price_set?: PriceSetDTO
money_amount?: MoneyAmountDTO
rules_count?: number
}
export interface CreatePriceSetMoneyAmountDTO {
title?: string
price_set?: PriceSetDTO | string
price_list?: PriceListDTO | string
money_amount?: MoneyAmountDTO | string
rules_count?: number
}
export interface FilterablePriceSetMoneyAmountProps
extends BaseFilterable<FilterablePriceSetMoneyAmountProps> {
id?: string[]
price_set_id?: string[]
price_list_id?: string[]
}
export interface PriceSetMoneyAmountDTO {
id: string
title?: string
price_set?: PriceSetDTO
price_list?: PriceListDTO
price_set_id?: string
price_rules?: PriceRuleDTO[]
money_amount?: MoneyAmountDTO
created_at: Date
updated_at: Date
deleted_at: Date | null
}
@@ -1,26 +0,0 @@
import { BaseFilterable, PriceSetDTO, RuleTypeDTO } from "@medusajs/types"
export interface CreatePriceSetRuleTypeDTO {
price_set: PriceSetDTO | string
rule_type: RuleTypeDTO | string
}
export interface UpdatePriceSetRuleTypeDTO {
id: string
price_set?: string
rule_type?: string
}
export interface PriceSetRuleTypeDTO {
id: string
price_set: PriceSetDTO
rule_type: RuleTypeDTO
value: string
}
export interface FilterablePriceSetRuleTypeProps
extends BaseFilterable<FilterablePriceSetRuleTypeProps> {
id?: string[]
rule_type_id?: string[]
price_set_id?: string[]
}
@@ -1,24 +0,0 @@
import {
BaseFilterable,
FilterableMoneyAmountProps,
MoneyAmountDTO,
RuleTypeDTO,
} from "@medusajs/types"
export interface CreatePriceSetDTO {}
export interface UpdatePriceSetDTO {
id: string
}
export interface PriceSetDTO {
id: string
money_amounts?: MoneyAmountDTO[]
rule_types?: RuleTypeDTO[]
}
export interface FilterablePriceSetProps
extends BaseFilterable<FilterablePriceSetProps> {
id?: string[]
money_amounts?: FilterableMoneyAmountProps
}
@@ -1,28 +0,0 @@
import { Context } from "@medusajs/types"
export interface PricingRepositoryService {
calculatePrices(
pricingFilters: PricingFilters,
pricingContext: PricingContext,
context: Context
): Promise<CalculatedPriceSetDTO[]>
}
export interface PricingFilters {
id: string[]
}
export interface PricingContext {
context?: Record<string, string | number>
}
export interface CalculatedPriceSetDTO {
id: string
price_set_id: string
amount: string | null
currency_code: string | null
min_quantity: string | null
max_quantity: string | null
price_list_type: string | null
price_list_id: string | null
}
@@ -1,38 +0,0 @@
import { BaseFilterable } from "@medusajs/types"
export interface CreateRuleTypeDTO {
id?: string
name: string
rule_attribute: string
default_priority?: number
}
export interface UpdateRuleTypeDTO {
id: string
name?: string
rule_attribute?: string
default_priority?: number
}
export interface RuleTypeDTO {
id: string
name: string
rule_attribute: string
default_priority: number
/**
* The creation date of the rule type.
*/
created_at?: Date | string
/**
* The update date of the rule type.
*/
updated_at?: Date | string
}
export interface FilterableRuleTypeProps
extends BaseFilterable<FilterableRuleTypeProps> {
id?: string[]
name?: string[]
rule_attribute?: string[]
}
+1 -1
View File
@@ -1,7 +1,7 @@
export * from "./money-amount" export * from "./money-amount"
export * from "./price"
export * from "./price-list" export * from "./price-list"
export * from "./price-rule" export * from "./price-rule"
export * from "./price-set" export * from "./price-set"
export * from "./price-set-money-amount"
export * from "./price-set-rule-type" export * from "./price-set-rule-type"
export * from "./rule-type" export * from "./rule-type"
@@ -1,5 +1,4 @@
import { BaseFilterable } from "../../dal" import { BaseFilterable } from "../../dal"
import { PriceSetMoneyAmountDTO } from "./price-set-money-amount"
/** /**
* @interface * @interface
@@ -27,10 +26,6 @@ export interface MoneyAmountDTO {
* The maximum quantity required to be purchased for this price to be applied. * The maximum quantity required to be purchased for this price to be applied.
*/ */
max_quantity?: number max_quantity?: number
/**
* The details of the relation between the money amount and its associated price set.
*/
price_set_money_amount?: PriceSetMoneyAmountDTO
/** /**
* When the money_amount was created. * When the money_amount was created.
*/ */
@@ -4,7 +4,7 @@ import {
MoneyAmountDTO, MoneyAmountDTO,
UpdateMoneyAmountDTO, UpdateMoneyAmountDTO,
} from "./money-amount" } from "./money-amount"
import { PriceSetMoneyAmountDTO } from "./price-set-money-amount" import { PriceDTO } from "./price"
import { RuleTypeDTO } from "./rule-type" import { RuleTypeDTO } from "./rule-type"
/** /**
@@ -74,7 +74,7 @@ export interface PriceListDTO {
* *
* @expandable * @expandable
*/ */
price_set_money_amounts?: PriceSetMoneyAmountDTO[] prices?: PriceDTO[]
/** /**
* The associated money amounts. * The associated money amounts.
* *
@@ -40,9 +40,9 @@ export interface PriceRuleDTO {
*/ */
priority: number priority: number
/** /**
* The ID of the associated price set money amount. * The ID of the associated price.
*/ */
price_set_money_amount_id: string price_id: string
/** /**
* The ID of the associated price list. * The ID of the associated price list.
*/ */
@@ -85,16 +85,16 @@ export interface CreatePriceRuleDTO {
*/ */
priority?: number priority?: number
/** /**
* The ID of the associated price set money amount. * The ID of the associated price.
*/ */
price_set_money_amount_id?: string price_id?: string
} }
/** /**
* *
* @interface * @interface
* *
* The data to update in a price rule. The `id` is used to identify which money amount to update. * The data to update in a price rule. The `id` is used to identify which price rule to update.
*/ */
export interface UpdatePriceRuleDTO { export interface UpdatePriceRuleDTO {
id: string id: string
@@ -109,9 +109,9 @@ export interface UpdatePriceRuleDTO {
*/ */
priority?: number priority?: number
/** /**
* The ID of the associated price set money amount. * The ID of the associated price.
*/ */
price_set_money_amount_id?: string price_id?: string
/** /**
* The ID of the associated price list. * The ID of the associated price list.
*/ */
@@ -1,97 +0,0 @@
import { BaseFilterable } from "../../dal"
import { MoneyAmountDTO } from "./money-amount"
import { PriceListDTO } from "./price-list"
import { PriceRuleDTO } from "./price-rule"
import { PriceSetDTO } from "./price-set"
/**
* @interface
*
* A price set money amount's data.
*/
export interface PriceSetMoneyAmountDTO {
/**
* The ID of a price set money amount.
*/
id: string
/**
* The title of the price set money amount.
*/
title?: string
/**
* The price set associated with the price set money amount.
*
* @expandable
*/
price_set?: PriceSetDTO
/**
* The price list associated with the price set money amount.
*
* @expandable
*/
price_list?: PriceListDTO
/**
* The ID of the associated price set.
*/
price_set_id?: string
/**
* The price rules associated with the price set money amount.
*
* @expandable
*/
price_rules?: PriceRuleDTO[]
/**
* The money amount associated with the price set money amount.
*
* @expandable
*/
money_amount?: MoneyAmountDTO
/**
* When the price_set_money_amount was created.
*/
created_at: Date
/**
* When the price_set_money_amount was updated.
*/
updated_at: Date
/**
* When the price_set_money_amount was deleted.
*/
deleted_at: null | Date
}
export interface UpdatePriceSetMoneyAmountDTO {
id: string
title?: string
price_set?: PriceSetDTO
money_amount?: MoneyAmountDTO
}
export interface CreatePriceSetMoneyAmountDTO {
title?: string
price_set?: PriceSetDTO | string
price_list?: PriceListDTO | string
money_amount?: MoneyAmountDTO | string
rules_count?: number
}
/**
* @interface
*
* Filters to apply on price set money amounts.
*/
export interface FilterablePriceSetMoneyAmountProps
extends BaseFilterable<FilterablePriceSetMoneyAmountProps> {
/**
* The IDs to filter the price set money amounts by.
*/
id?: string[]
/**
* The IDs to filter the price set money amount's associated price set.
*/
price_set_id?: string[]
/**
* The IDs to filter the price set money amount's associated price list.
*/
price_list_id?: string[]
}
@@ -10,8 +10,8 @@ export interface PriceSetRuleTypeDTO {
} }
export interface CreatePriceSetRuleTypeDTO { export interface CreatePriceSetRuleTypeDTO {
price_set: PriceSetDTO price_set_id: string
rule_type: RuleTypeDTO rule_type_id: string
} }
export interface UpdatePriceSetRuleTypeDTO { export interface UpdatePriceSetRuleTypeDTO {
+141
View File
@@ -0,0 +1,141 @@
import { BaseFilterable } from "../../dal"
import { PriceListDTO } from "./price-list"
import { PriceRuleDTO } from "./price-rule"
import { PriceSetDTO } from "./price-set"
/**
* @interface
*
* A price's data.
*/
export interface PriceDTO {
/**
* The ID of a price.
*/
id: string
/**
* The title of the price.
*/
title?: string
/**
* The currency code of this price.
*/
currency_code?: string
/**
* The price of this price.
*/
amount?: number
/**
* The minimum quantity required to be purchased for this price to be applied.
*/
min_quantity?: number
/**
* The maximum quantity required to be purchased for this price to be applied.
*/
max_quantity?: number
/**
* The price set associated with the price.
*
* @expandable
*/
price_set?: PriceSetDTO
/**
* The price list associated with the price.
*
* @expandable
*/
price_list?: PriceListDTO
/**
* The ID of the associated price set.
*/
price_set_id?: string
/**
* The price rules associated with the price.
*
* @expandable
*/
price_rules?: PriceRuleDTO[]
/**
* When the price was created.
*/
created_at: Date
/**
* When the price was updated.
*/
updated_at: Date
/**
* When the price was deleted.
*/
deleted_at: null | Date
}
export interface UpdatePriceDTO {
id: string
title?: string
price_set?: PriceSetDTO
/**
* The code of the currency to associate with the price.
*/
currency_code?: string | null
/**
* The amount of this price.
*/
amount?: number
/**
* The minimum quantity required to be purchased for this price to be applied.
*/
min_quantity?: number
/**
* The maximum quantity required to be purchased for this price to be applied.
*/
max_quantity?: number
}
export interface CreatePriceDTO {
title?: string
price_set?: PriceSetDTO | string
price_set_id: string
price_list?: PriceListDTO | string
rules_count?: number
/**
* The currency code of this price.
*/
currency_code: string
/**
* The amount of this price.
*/
amount: number
/**
* The minimum quantity required to be purchased for this price to be applied.
*/
min_quantity?: number | null
/**
* The maximum quantity required to be purchased for this price to be applied.
*/
max_quantity?: number | null
}
/**
* @interface
*
* Filters to apply on prices.
*/
export interface FilterablePriceProps
extends BaseFilterable<FilterablePriceProps> {
/**
* The IDs to filter the prices by.
*/
id?: string[]
/**
* Currency codes to filter price by.
*/
currency_code?: string | string[]
/**
* The IDs to filter the price's associated price set.
*/
price_set_id?: string[]
/**
* The IDs to filter the price's associated price list.
*/
price_list_id?: string[]
}
+77 -79
View File
@@ -10,15 +10,15 @@ import {
CreateRuleTypeDTO, CreateRuleTypeDTO,
FilterablePriceListProps, FilterablePriceListProps,
FilterablePriceListRuleProps, FilterablePriceListRuleProps,
FilterablePriceProps,
FilterablePriceRuleProps, FilterablePriceRuleProps,
FilterablePriceSetMoneyAmountProps,
FilterablePriceSetProps, FilterablePriceSetProps,
FilterableRuleTypeProps, FilterableRuleTypeProps,
PriceDTO,
PriceListDTO, PriceListDTO,
PriceListRuleDTO, PriceListRuleDTO,
PriceRuleDTO, PriceRuleDTO,
PriceSetDTO, PriceSetDTO,
PriceSetMoneyAmountDTO,
PricingContext, PricingContext,
PricingFilters, PricingFilters,
RemovePriceListRulesDTO, RemovePriceListRulesDTO,
@@ -169,7 +169,7 @@ export interface IPricingModuleService extends IModuleService {
* const priceSet = await pricingService.retrieve( * const priceSet = await pricingService.retrieve(
* priceSetId, * priceSetId,
* { * {
* relations: ["money_amounts"] * relations: ["prices"]
* } * }
* ) * )
* *
@@ -230,7 +230,7 @@ export interface IPricingModuleService extends IModuleService {
* id: priceSetIds * id: priceSetIds
* }, * },
* { * {
* relations: ["money_amounts"] * relations: ["prices"]
* } * }
* ) * )
* *
@@ -253,7 +253,7 @@ export interface IPricingModuleService extends IModuleService {
* id: priceSetIds * id: priceSetIds
* }, * },
* { * {
* relations: ["money_amounts"], * relations: ["prices"],
* skip, * skip,
* take * take
* } * }
@@ -270,7 +270,7 @@ export interface IPricingModuleService extends IModuleService {
* initialize as initializePricingModule, * initialize as initializePricingModule,
* } from "@medusajs/pricing" * } from "@medusajs/pricing"
* *
* async function retrievePriceSets (priceSetIds: string[], moneyAmountIds: string[], skip: number, take: number) { * async function retrievePriceSets (priceSetIds: string[], priceIds: string[], skip: number, take: number) {
* const pricingService = await initializePricingModule() * const pricingService = await initializePricingModule()
* *
* const priceSets = await pricingService.list( * const priceSets = await pricingService.list(
@@ -280,14 +280,14 @@ export interface IPricingModuleService extends IModuleService {
* id: priceSetIds * id: priceSetIds
* }, * },
* { * {
* money_amounts: { * prices: {
* id: moneyAmountIds * id: priceIds
* } * }
* } * }
* ] * ]
* }, * },
* { * {
* relations: ["money_amounts"], * relations: ["prices"],
* skip, * skip,
* take * take
* } * }
@@ -350,7 +350,7 @@ export interface IPricingModuleService extends IModuleService {
* id: priceSetIds * id: priceSetIds
* }, * },
* { * {
* relations: ["money_amounts"] * relations: ["prices"]
* } * }
* ) * )
* *
@@ -373,7 +373,7 @@ export interface IPricingModuleService extends IModuleService {
* id: priceSetIds * id: priceSetIds
* }, * },
* { * {
* relations: ["money_amounts"], * relations: ["prices"],
* skip, * skip,
* take * take
* } * }
@@ -390,7 +390,7 @@ export interface IPricingModuleService extends IModuleService {
* initialize as initializePricingModule, * initialize as initializePricingModule,
* } from "@medusajs/pricing" * } from "@medusajs/pricing"
* *
* async function retrievePriceSets (priceSetIds: string[], moneyAmountIds: string[], skip: number, take: number) { * async function retrievePriceSets (priceSetIds: string[], priceIds: string[], skip: number, take: number) {
* const pricingService = await initializePricingModule() * const pricingService = await initializePricingModule()
* *
* const [priceSets, count] = await pricingService.listAndCount( * const [priceSets, count] = await pricingService.listAndCount(
@@ -400,14 +400,14 @@ export interface IPricingModuleService extends IModuleService {
* id: priceSetIds * id: priceSetIds
* }, * },
* { * {
* money_amounts: { * prices: {
* id: moneyAmountIds * id: priceIds
* } * }
* } * }
* ] * ]
* }, * },
* { * {
* relations: ["money_amounts"], * relations: ["prices"],
* skip, * skip,
* take * take
* } * }
@@ -1240,52 +1240,52 @@ export interface IPricingModuleService extends IModuleService {
deleteRuleTypes(ruleTypeIds: string[], sharedContext?: Context): Promise<void> deleteRuleTypes(ruleTypeIds: string[], sharedContext?: Context): Promise<void>
/** /**
* This method is used to retrieve a paginated list of price set money amounts based on optional filters and configuration. * This method is used to retrieve a paginated list of prices based on optional filters and configuration.
* *
* @param {FilterablePriceSetMoneyAmountProps} filters - The filters to apply on the retrieved price set money amounts. * @param {FilterablePriceProps} filters - The filters to apply on the retrieved prices.
* @param {FindConfig<PriceSetMoneyAmountDTO>} config - * @param {FindConfig<PriceDTO>} config -
* The configurations determining how the price set money amounts are retrieved. Its properties, such as `select` or `relations`, accept the * The configurations determining how the prices are retrieved. Its properties, such as `select` or `relations`, accept the
* attributes or relations associated with a price set money amount. * attributes or relations associated with a price.
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module. * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<PriceSetMoneyAmountDTO[]>} The list of price set money amounts. * @returns {Promise<PriceDTO[]>} The list of prices.
* *
* @example * @example
* *
* To retrieve a list of price set money amounts using their IDs: * To retrieve a list of prices using their IDs:
* *
* ```ts * ```ts
* import { * import {
* initialize as initializePricingModule, * initialize as initializePricingModule,
* } from "@medusajs/pricing" * } from "@medusajs/pricing"
* *
* async function retrievePriceSetMoneyAmounts (id: string) { * async function retrievePrices (id: string) {
* const pricingService = await initializePricingModule() * const pricingService = await initializePricingModule()
* *
* const priceSetMoneyAmounts = await pricingService.listPriceSetMoneyAmounts({ * const prices = await pricingService.listPrices({
* id: [id] * id: [id]
* }) * })
* *
* // do something with the price set money amounts or return them * // do something with the prices or return them
* } * }
* ``` * ```
* *
* To specify relations that should be retrieved within the price set money amounts: * To specify relations that should be retrieved within the prices:
* *
* ```ts * ```ts
* import { * import {
* initialize as initializePricingModule, * initialize as initializePricingModule,
* } from "@medusajs/pricing" * } from "@medusajs/pricing"
* *
* async function retrievePriceSetMoneyAmounts (id: string) { * async function retrievePrices (id: string) {
* const pricingService = await initializePricingModule() * const pricingService = await initializePricingModule()
* *
* const priceSetMoneyAmounts = await pricingService.listPriceSetMoneyAmounts({ * const prices = await pricingService.listPrices({
* id: [id] * id: [id]
* }, { * }, {
* relations: ["price_rules"] * relations: ["price_rules"]
* }) * })
* *
* // do something with the price set money amounts or return them * // do something with the prices or return them
* } * }
* ``` * ```
* *
@@ -1296,10 +1296,10 @@ export interface IPricingModuleService extends IModuleService {
* initialize as initializePricingModule, * initialize as initializePricingModule,
* } from "@medusajs/pricing" * } from "@medusajs/pricing"
* *
* async function retrievePriceSetMoneyAmounts (id: string, skip: number, take: number) { * async function retrievePrices (id: string, skip: number, take: number) {
* const pricingService = await initializePricingModule() * const pricingService = await initializePricingModule()
* *
* const priceSetMoneyAmounts = await pricingService.listPriceSetMoneyAmounts({ * const prices = await pricingService.listPrices({
* id: [id] * id: [id]
* }, { * }, {
* relations: ["price_rules"], * relations: ["price_rules"],
@@ -1307,7 +1307,7 @@ export interface IPricingModuleService extends IModuleService {
* take * take
* }) * })
* *
* // do something with the price set money amounts or return them * // do something with the prices or return them
* } * }
* ``` * ```
* *
@@ -1318,10 +1318,10 @@ export interface IPricingModuleService extends IModuleService {
* initialize as initializePricingModule, * initialize as initializePricingModule,
* } from "@medusajs/pricing" * } from "@medusajs/pricing"
* *
* async function retrievePriceSetMoneyAmounts (ids: string[], titles: string[], skip: number, take: number) { * async function retrievePrices (ids: string[], titles: string[], skip: number, take: number) {
* const pricingService = await initializePricingModule() * const pricingService = await initializePricingModule()
* *
* const priceSetMoneyAmounts = await pricingService.listPriceSetMoneyAmounts({ * const prices = await pricingService.listPrices({
* $and: [ * $and: [
* { * {
* id: ids * id: ids
@@ -1336,78 +1336,76 @@ export interface IPricingModuleService extends IModuleService {
* take * take
* }) * })
* *
* // do something with the price set money amounts or return them * // do something with the prices or return them
* } * }
* ``` * ```
*/ */
listPriceSetMoneyAmounts( listPrices(
filters?: FilterablePriceSetMoneyAmountProps, filters?: FilterablePriceProps,
config?: FindConfig<PriceSetMoneyAmountDTO>, config?: FindConfig<PriceDTO>,
sharedContext?: Context sharedContext?: Context
): Promise<PriceSetMoneyAmountDTO[]> ): Promise<PriceDTO[]>
softDeletePriceSetMoneyAmounts< softDeletePrices<TReturnableLinkableKeys extends string = string>(
TReturnableLinkableKeys extends string = string priceIds: string[],
>(
psmaIds: string[],
config?: SoftDeleteReturn<TReturnableLinkableKeys>, config?: SoftDeleteReturn<TReturnableLinkableKeys>,
sharedContext?: Context sharedContext?: Context
): Promise<Record<string, string[]> | void> ): Promise<Record<string, string[]> | void>
restorePriceSetMoneyAmounts<TReturnableLinkableKeys extends string = string>( restorePrices<TReturnableLinkableKeys extends string = string>(
psmaIds: string[], priceIds: string[],
config?: RestoreReturn<TReturnableLinkableKeys>, config?: RestoreReturn<TReturnableLinkableKeys>,
sharedContext?: Context sharedContext?: Context
): Promise<Record<string, string[]> | void> ): Promise<Record<string, string[]> | void>
/** /**
* This method is used to retrieve a paginated list of price set money amounts along with the total count of * This method is used to retrieve a paginated list of prices along with the total count of
* available price set money amounts satisfying the provided filters. * available prices satisfying the provided filters.
* *
* @param {FilterablePriceSetMoneyAmountProps} filters - The filters to apply on the retrieved price set money amounts. * @param {FilterablePriceProps} filters - The filters to apply on the retrieved prices.
* @param {FindConfig<PriceSetMoneyAmountDTO>} config - * @param {FindConfig<PriceDTO>} config -
* The configurations determining how the price set money amounts are retrieved. Its properties, such as `select` or `relations`, accept the * The configurations determining how the prices are retrieved. Its properties, such as `select` or `relations`, accept the
* attributes or relations associated with a price set money amount. * attributes or relations associated with a price.
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module. * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<[PriceSetMoneyAmountDTO[], number]>} The list of price set money amounts and their total count. * @returns {Promise<[PriceDTO[], number]>} The list of prices and their total count.
* *
* @example * @example
* *
* To retrieve a list of price set money amounts using their IDs: * To retrieve a list of prices using their IDs:
* *
* ```ts * ```ts
* import { * import {
* initialize as initializePricingModule, * initialize as initializePricingModule,
* } from "@medusajs/pricing" * } from "@medusajs/pricing"
* *
* async function retrievePriceSetMoneyAmounts (id: string) { * async function retrievePrices (id: string) {
* const pricingService = await initializePricingModule() * const pricingService = await initializePricingModule()
* *
* const [priceSetMoneyAmounts, count] = await pricingService.listAndCountPriceSetMoneyAmounts({ * const [prices, count] = await pricingService.listAndCountPrices({
* id: [id] * id: [id]
* }) * })
* *
* // do something with the price set money amounts or return them * // do something with the prices or return them
* } * }
* ``` * ```
* *
* To specify relations that should be retrieved within the price set money amounts: * To specify relations that should be retrieved within the prices:
* *
* ```ts * ```ts
* import { * import {
* initialize as initializePricingModule, * initialize as initializePricingModule,
* } from "@medusajs/pricing" * } from "@medusajs/pricing"
* *
* async function retrievePriceSetMoneyAmounts (id: string) { * async function retrievePrices (id: string) {
* const pricingService = await initializePricingModule() * const pricingService = await initializePricingModule()
* *
* const [priceSetMoneyAmounts, count] = await pricingService.listAndCountPriceSetMoneyAmounts({ * const [prices, count] = await pricingService.listAndCountPrices({
* id: [id] * id: [id]
* }, { * }, {
* relations: ["price_rules"], * relations: ["price_rules"],
* }) * })
* *
* // do something with the price set money amounts or return them * // do something with the prices or return them
* } * }
* ``` * ```
* *
@@ -1418,10 +1416,10 @@ export interface IPricingModuleService extends IModuleService {
* initialize as initializePricingModule, * initialize as initializePricingModule,
* } from "@medusajs/pricing" * } from "@medusajs/pricing"
* *
* async function retrievePriceSetMoneyAmounts (id: string, skip: number, take: number) { * async function retrievePrices (id: string, skip: number, take: number) {
* const pricingService = await initializePricingModule() * const pricingService = await initializePricingModule()
* *
* const [priceSetMoneyAmounts, count] = await pricingService.listAndCountPriceSetMoneyAmounts({ * const [prices, count] = await pricingService.listAndCountPrices({
* id: [id] * id: [id]
* }, { * }, {
* relations: ["price_rules"], * relations: ["price_rules"],
@@ -1429,7 +1427,7 @@ export interface IPricingModuleService extends IModuleService {
* take * take
* }) * })
* *
* // do something with the price set money amounts or return them * // do something with the prices or return them
* } * }
* ``` * ```
* *
@@ -1440,10 +1438,10 @@ export interface IPricingModuleService extends IModuleService {
* initialize as initializePricingModule, * initialize as initializePricingModule,
* } from "@medusajs/pricing" * } from "@medusajs/pricing"
* *
* async function retrievePriceSetMoneyAmounts (ids: string[], titles: string[], skip: number, take: number) { * async function retrievePrices (ids: string[], titles: string[], skip: number, take: number) {
* const pricingService = await initializePricingModule() * const pricingService = await initializePricingModule()
* *
* const [priceSetMoneyAmounts, count] = await pricingService.listAndCountPriceSetMoneyAmounts({ * const [prices, count] = await pricingService.listAndCountPrices({
* $and: [ * $and: [
* { * {
* id: ids * id: ids
@@ -1458,15 +1456,15 @@ export interface IPricingModuleService extends IModuleService {
* take * take
* }) * })
* *
* // do something with the price set money amounts or return them * // do something with the prices or return them
* } * }
* ``` * ```
*/ */
listAndCountPriceSetMoneyAmounts( listAndCountPrices(
filters?: FilterablePriceSetMoneyAmountProps, filters?: FilterablePriceProps,
config?: FindConfig<PriceSetMoneyAmountDTO>, config?: FindConfig<PriceDTO>,
sharedContext?: Context sharedContext?: Context
): Promise<[PriceSetMoneyAmountDTO[], number]> ): Promise<[PriceDTO[], number]>
/** /**
* This method is used to retrieve a price rule by its ID. * This method is used to retrieve a price rule by its ID.
@@ -1750,7 +1748,7 @@ export interface IPricingModuleService extends IModuleService {
* priceSetId: string, * priceSetId: string,
* ruleTypeId: string, * ruleTypeId: string,
* value: string, * value: string,
* priceSetMoneyAmountId: string, * priceId: string,
* priceListId: string * priceListId: string
* ) { * ) {
* const pricingService = await initializePricingModule() * const pricingService = await initializePricingModule()
@@ -1761,7 +1759,7 @@ export interface IPricingModuleService extends IModuleService {
* price_set_id: priceSetId, * price_set_id: priceSetId,
* rule_type_id: ruleTypeId, * rule_type_id: ruleTypeId,
* value, * value,
* price_set_money_amount_id: priceSetMoneyAmountId, * price_id: priceId,
* price_list_id: priceListId * price_list_id: priceListId
* } * }
* ]) * ])
@@ -1874,7 +1872,7 @@ export interface IPricingModuleService extends IModuleService {
* const priceList = await pricingService.retrievePriceList( * const priceList = await pricingService.retrievePriceList(
* priceListId, * priceListId,
* { * {
* relations: ["price_set_money_amounts"] * relations: ["prices"]
* } * }
* ) * )
* *
@@ -1935,7 +1933,7 @@ export interface IPricingModuleService extends IModuleService {
* id: priceListIds * id: priceListIds
* }, * },
* { * {
* relations: ["price_set_money_amounts"] * relations: ["prices"]
* } * }
* ) * )
* *
@@ -1958,7 +1956,7 @@ export interface IPricingModuleService extends IModuleService {
* id: priceListIds * id: priceListIds
* }, * },
* { * {
* relations: ["price_set_money_amounts"], * relations: ["prices"],
* skip, * skip,
* take * take
* } * }
@@ -1990,7 +1988,7 @@ export interface IPricingModuleService extends IModuleService {
* ] * ]
* }, * },
* { * {
* relations: ["price_set_money_amounts"], * relations: ["prices"],
* skip, * skip,
* take * take
* } * }
@@ -2053,7 +2051,7 @@ export interface IPricingModuleService extends IModuleService {
* id: priceListIds * id: priceListIds
* }, * },
* { * {
* relations: ["price_set_money_amounts"] * relations: ["prices"]
* } * }
* ) * )
* *
@@ -2076,7 +2074,7 @@ export interface IPricingModuleService extends IModuleService {
* id: priceListIds * id: priceListIds
* }, * },
* { * {
* relations: ["price_set_money_amounts"], * relations: ["prices"],
* skip, * skip,
* take * take
* } * }
@@ -2108,7 +2106,7 @@ export interface IPricingModuleService extends IModuleService {
* ] * ]
* }, * },
* { * {
* relations: ["price_set_money_amounts"], * relations: ["prices"],
* skip, * skip,
* take * take
* } * }
+9 -5
View File
@@ -1,9 +1,10 @@
import { isDefined } from "./is-defined" import { isDefined } from "./is-defined"
export const removeNullish = ( export function removeNullish<T = unknown>(
obj: Record<string, unknown> obj: Record<string, T>
): Record<string, unknown> => ): Record<string, T> {
Object.entries(obj).reduce((resultObject, [currentKey, currentValue]) => { return Object.entries(obj).reduce(
(resultObject, [currentKey, currentValue]) => {
if (!isDefined(currentValue) || currentValue === null) { if (!isDefined(currentValue) || currentValue === null) {
return resultObject return resultObject
} }
@@ -11,4 +12,7 @@ export const removeNullish = (
resultObject[currentKey] = currentValue resultObject[currentKey] = currentValue
return resultObject return resultObject
}, {}) },
{}
)
}
@@ -248,13 +248,11 @@ export type AbstractModuleService<
* *
* const otherModels = new Set([ * const otherModels = new Set([
* Currency, * Currency,
* MoneyAmount, * Price,
* PriceList, * PriceList,
* PriceListRule, * PriceListRule,
* PriceListRuleValue, * PriceListRuleValue,
* PriceRule, * PriceRule,
* PriceSetMoneyAmount,
* PriceSetMoneyAmountRules,
* PriceSetRuleType, * PriceSetRuleType,
* RuleType, * RuleType,
* ]) * ])
@@ -265,11 +263,7 @@ export type AbstractModuleService<
* // The configuration of each entity also accept singular/plural properties, if not provided then it is using english pluralization * // The configuration of each entity also accept singular/plural properties, if not provided then it is using english pluralization
* { * {
* Currency: { dto: PricingTypes.CurrencyDTO } * Currency: { dto: PricingTypes.CurrencyDTO }
* MoneyAmount: { dto: PricingTypes.MoneyAmountDTO } * Price: { dto: PricingTypes.PriceDTO }
* PriceSetMoneyAmount: { dto: PricingTypes.PriceSetMoneyAmountDTO }
* PriceSetMoneyAmountRules: {
* dto: PricingTypes.PriceSetMoneyAmountRulesDTO
* }
* PriceRule: { dto: PricingTypes.PriceRuleDTO } * PriceRule: { dto: PricingTypes.PriceRuleDTO }
* RuleType: { dto: PricingTypes.RuleTypeDTO } * RuleType: { dto: PricingTypes.RuleTypeDTO }
* PriceList: { dto: PricingTypes.PriceListDTO } * PriceList: { dto: PricingTypes.PriceListDTO }
+14 -14
View File
@@ -1,7 +1,7 @@
import { import {
PriceDTO,
PriceListRuleDTO, PriceListRuleDTO,
PriceRuleDTO, PriceRuleDTO,
PriceSetMoneyAmountDTO,
ProductVariantDTO, ProductVariantDTO,
UpdatePriceListPriceDTO, UpdatePriceListPriceDTO,
} from "@medusajs/types" } from "@medusajs/types"
@@ -33,20 +33,20 @@ export function buildPriceSetRules(
} }
export function buildPriceSetPricesForCore( export function buildPriceSetPricesForCore(
priceSetMoneyAmounts: (PriceSetMoneyAmountDTO & { prices: (PriceDTO & {
price_set: PriceSetMoneyAmountDTO["price_set"] & { price_set: PriceDTO["price_set"] & {
variant?: ProductVariantDTO variant?: ProductVariantDTO
} }
})[] })[]
): Record<string, any>[] { ): Record<string, any>[] {
return priceSetMoneyAmounts.map((priceSetMoneyAmount) => { return prices.map((price) => {
const productVariant = (priceSetMoneyAmount.price_set as any).variant const productVariant = (price.price_set as any).variant
const rules: Record<string, string> = priceSetMoneyAmount.price_rules const rules: Record<string, string> = price.price_rules
? buildPriceSetRules(priceSetMoneyAmount.price_rules) ? buildPriceSetRules(price.price_rules)
: {} : {}
return { return {
...priceSetMoneyAmount, ...price,
variant_id: productVariant?.id ?? null, variant_id: productVariant?.id ?? null,
rules, rules,
} }
@@ -54,16 +54,16 @@ export function buildPriceSetPricesForCore(
} }
export function buildPriceSetPricesForModule( export function buildPriceSetPricesForModule(
priceSetMoneyAmounts: PriceSetMoneyAmountDTO[] prices: PriceDTO[]
): UpdatePriceListPriceDTO[] { ): UpdatePriceListPriceDTO[] {
return priceSetMoneyAmounts.map((priceSetMoneyAmount) => { return prices.map((price) => {
const rules: Record<string, string> = priceSetMoneyAmount.price_rules const rules: Record<string, string> = price.price_rules
? buildPriceSetRules(priceSetMoneyAmount.price_rules) ? buildPriceSetRules(price.price_rules)
: {} : {}
return { return {
...priceSetMoneyAmount, ...price,
price_set_id: priceSetMoneyAmount.price_set!?.id!, price_set_id: price.price_set!?.id!,
rules, rules,
} }
}) })