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 Thamir
2024-03-25 14:15:25 +01:00
committed by GitHub
parent fbc369705d
commit 9073d7aba3
80 changed files with 1056 additions and 2276 deletions

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

View File

@@ -4,10 +4,10 @@ import {
} from "../../../../factories"
import { IPricingModuleService } from "@medusajs/types"
import { medusaIntegrationTestRunner } from "medusa-test-utils"
import adminSeeder from "../../../../helpers/admin-seeder"
import { createDefaultRuleTypes } from "../../../helpers/create-default-rule-types"
import { createVariantPriceSet } from "../../../helpers/create-variant-price-set"
import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000)
@@ -100,11 +100,10 @@ medusaIntegrationTestRunner({
})
it("should delete prices in batch based on product ids", async () => {
let priceSetMoneyAmounts =
await pricingModuleService.listPriceSetMoneyAmounts({
price_set_id: [priceSet.id],
})
expect(priceSetMoneyAmounts.length).toEqual(2)
let prices = await pricingModuleService.listPrices({
price_set_id: [priceSet.id],
})
expect(prices.length).toEqual(2)
const deleteRes = await api.delete(
`/admin/price-lists/${priceListId}/products/prices/batch`,
@@ -117,13 +116,12 @@ medusaIntegrationTestRunner({
)
expect(deleteRes.status).toEqual(200)
priceSetMoneyAmounts =
await pricingModuleService.listPriceSetMoneyAmounts({
price_set_id: [priceSet.id],
})
prices = await pricingModuleService.listPrices({
price_set_id: [priceSet.id],
})
expect(priceSetMoneyAmounts.length).toEqual(1)
expect(priceSetMoneyAmounts).toEqual([
expect(prices.length).toEqual(1)
expect(prices).toEqual([
expect.objectContaining({
price_list: null,
}),
@@ -131,11 +129,10 @@ medusaIntegrationTestRunner({
})
it("should delete prices based on single product id", async () => {
let priceSetMoneyAmounts =
await pricingModuleService.listPriceSetMoneyAmounts({
price_set_id: [priceSet.id],
})
expect(priceSetMoneyAmounts.length).toEqual(2)
let prices = await pricingModuleService.listPrices({
price_set_id: [priceSet.id],
})
expect(prices.length).toEqual(2)
const deleteRes = await api.delete(
`/admin/price-lists/${priceListId}/products/${product.id}/prices`,
@@ -143,13 +140,12 @@ medusaIntegrationTestRunner({
)
expect(deleteRes.status).toEqual(200)
priceSetMoneyAmounts =
await pricingModuleService.listPriceSetMoneyAmounts({
price_set_id: [priceSet.id],
})
prices = await pricingModuleService.listPrices({
price_set_id: [priceSet.id],
})
expect(priceSetMoneyAmounts.length).toEqual(1)
expect(priceSetMoneyAmounts).toEqual([
expect(prices.length).toEqual(1)
expect(prices).toEqual([
expect.objectContaining({
price_list: null,
}),

View File

@@ -4,10 +4,10 @@ import {
} from "../../../../factories"
import { IPricingModuleService } from "@medusajs/types"
import { medusaIntegrationTestRunner } from "medusa-test-utils"
import adminSeeder from "../../../../helpers/admin-seeder"
import { createDefaultRuleTypes } from "../../../helpers/create-default-rule-types"
import { createVariantPriceSet } from "../../../helpers/create-variant-price-set"
import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000)
@@ -94,10 +94,10 @@ medusaIntegrationTestRunner({
const result = await api.post(`admin/price-lists`, data, adminHeaders)
const priceListId = result.data.price_list.id
let psmas = await pricingModuleService.listPriceSetMoneyAmounts({
let prices = await pricingModuleService.listPrices({
price_list_id: [priceListId],
})
expect(psmas.length).toEqual(1)
expect(prices.length).toEqual(1)
const deleteRes = await api.delete(
`/admin/price-lists/${priceListId}/variants/${variant.id}/prices`,
@@ -105,10 +105,10 @@ medusaIntegrationTestRunner({
)
expect(deleteRes.status).toEqual(200)
psmas = await pricingModuleService.listPriceSetMoneyAmounts({
prices = await pricingModuleService.listPrices({
price_list_id: [priceListId],
})
expect(psmas.length).toEqual(0)
expect(prices.length).toEqual(0)
})
})
},

View File

@@ -4,10 +4,10 @@ import {
} from "../../../../factories"
import { IPricingModuleService } from "@medusajs/types"
import { medusaIntegrationTestRunner } from "medusa-test-utils"
import adminSeeder from "../../../../helpers/admin-seeder"
import { createDefaultRuleTypes } from "../../../helpers/create-default-rule-types"
import { createVariantPriceSet } from "../../../helpers/create-variant-price-set"
import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000)
@@ -98,16 +98,16 @@ medusaIntegrationTestRunner({
const res = await api.post(`admin/price-lists`, data, adminHeaders)
const priceListId = res.data.price_list.id
let psmas = await pricingModuleService.listPriceSetMoneyAmounts(
let prices = await pricingModuleService.listPrices(
{
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(
`/admin/price-lists/${priceListId}/prices/batch`,
{
@@ -119,10 +119,10 @@ medusaIntegrationTestRunner({
)
expect(deleteRes.status).toEqual(200)
psmas = await pricingModuleService.listPriceSetMoneyAmounts({
prices = await pricingModuleService.listPrices({
price_list_id: [priceListId],
})
expect(psmas.length).toEqual(1)
expect(prices.length).toEqual(1)
})
})
},

View File

@@ -366,11 +366,11 @@ medusaIntegrationTestRunner({
const result = await api.post(`admin/price-lists`, data, adminHeaders)
const priceListId = result.data.price_list.id
let psmas = await pricingModule.listPriceSetMoneyAmounts({
let prices = await pricingModule.listPrices({
price_list_id: [priceListId],
})
expect(psmas.length).toEqual(1)
expect(prices.length).toEqual(1)
const deleteRes = await api.delete(
`/admin/price-lists/${priceListId}`,
@@ -385,10 +385,10 @@ medusaIntegrationTestRunner({
expect(afterDelete.response.status).toEqual(404)
psmas = await pricingModule.listPriceSetMoneyAmounts({
prices = await pricingModule.listPrices({
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 () => {
@@ -609,13 +609,13 @@ medusaIntegrationTestRunner({
const [priceList] = await pricingModule.listPriceLists(
{ 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(
`/admin/price-lists/${priceList.id}/prices/batch/remove`,
{ ids: [psmaIdToDelete] },
{ ids: [priceIdToDelete] },
adminHeaders
)

View File

@@ -19,7 +19,8 @@ const env = {
medusaIntegrationTestRunner({
env,
testSuite: ({ dbConnection, getContainer, api }) => {
describe("/admin/products", () => {
// TODO: unskip this when there is a module compatible productSeeder
describe.skip("/admin/products", () => {
let medusaContainer
beforeAll(async () => {

View File

@@ -41,6 +41,6 @@ export const createVariantPriceSet = async ({
})
return await pricingModuleService.retrieve(priceSet.id, {
relations: ["price_set_money_amounts"],
relations: ["prices"],
})
}

View File

@@ -14,7 +14,7 @@ export const getExistingPriceListsPriceIdsStep = createStep(
)
const existingPrices = priceListIds.length
? await pricingModule.listPriceSetMoneyAmounts(
? await pricingModule.listPrices(
{ price_list_id: priceListIds },
{ relations: ["price_list"] }
)

View File

@@ -14,18 +14,16 @@ export const removePriceListPricesStep = createStep(
ModuleRegistrationName.PRICING
)
const psmas = await pricingModule.listPriceSetMoneyAmounts(
const prices = await pricingModule.listPrices(
{ id: ids },
{ relations: ["price_list"] }
)
await pricingModule.softDeletePriceSetMoneyAmounts(
psmas.map((psma) => psma.id)
)
await pricingModule.softDeletePrices(prices.map((price) => price.id))
return new StepResponse(
null,
psmas.map((psma) => psma.id)
prices.map((price) => price.id)
)
},
async (ids, { container }) => {
@@ -37,6 +35,6 @@ export const removePriceListPricesStep = createStep(
ModuleRegistrationName.PRICING
)
await pricingModule.restorePriceSetMoneyAmounts(ids)
await pricingModule.restorePrices(ids)
}
)

View File

@@ -1,7 +1,7 @@
import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import {
IPricingModuleService,
PriceSetMoneyAmountDTO,
PriceDTO,
UpdatePriceListPriceDTO,
UpdatePriceListPricesDTO,
UpdatePriceListPriceWorkflowStepDTO,
@@ -42,26 +42,26 @@ export const updatePriceListPricesStep = createStep(
}
const existingPrices = priceIds.length
? await pricingModule.listPriceSetMoneyAmounts(
? await pricingModule.listPrices(
{ id: priceIds },
{ relations: ["price_list"] }
)
: []
const priceListPsmaMap = new Map<string, PriceSetMoneyAmountDTO[]>()
const priceListPricesMap = new Map<string, PriceDTO[]>()
const dataBeforePriceUpdate: UpdatePriceListPricesDTO[] = []
for (const price of existingPrices) {
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({
price_list_id: priceListId,
prices: buildPriceSetPricesForModule(psmas),
prices: buildPriceSetPricesForModule(prices),
})
}

View File

@@ -4,7 +4,7 @@ import {
CreatePriceListPriceDTO,
CreatePriceListPriceWorkflowDTO,
IPricingModuleService,
PriceSetMoneyAmountDTO,
PriceDTO,
UpdatePriceListPriceDTO,
UpdatePriceListPriceWorkflowDTO,
UpdatePriceListPricesDTO,
@@ -56,33 +56,30 @@ export const upsertPriceListPricesStep = createStep(
}
}
const updatedPriceSetMoneyAmounts =
await pricingModule.listPriceSetMoneyAmounts(
{
id: priceListPricesToUpdate
.map((priceListData) =>
priceListData.prices.map((price) => price.id)
)
.filter(Boolean)
.flat(1),
},
{ relations: ["price_list"] }
)
const updatedPrices = await pricingModule.listPrices(
{
id: priceListPricesToUpdate
.map((priceListData) => priceListData.prices.map((price) => price.id))
.filter(Boolean)
.flat(1),
},
{ relations: ["price_list"] }
)
const priceListPsmaMap = new Map<string, PriceSetMoneyAmountDTO[]>()
const priceListPricesMap = new Map<string, PriceDTO[]>()
const dataBeforePriceUpdate: UpdatePriceListPricesDTO[] = []
for (const priceSetMoneyAmount of updatedPriceSetMoneyAmounts) {
const priceListId = priceSetMoneyAmount.price_list!.id
const psmas = priceListPsmaMap.get(priceListId) || []
for (const updatedPrice of updatedPrices) {
const priceListId = updatedPrice.price_list!.id
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({
price_list_id: priceListId,
prices: buildPriceSetPricesForModule(psmas),
prices: buildPriceSetPricesForModule(prices),
})
}

View File

@@ -14,9 +14,7 @@ export function buildPriceListResponse(
): AdminPriceListRemoteQueryDTO[] {
for (const priceList of priceLists) {
priceList.rules = buildPriceListRules(priceList.price_list_rules || [])
priceList.prices = buildPriceSetPricesForCore(
priceList.price_set_money_amounts || []
)
priceList.prices = buildPriceSetPricesForCore(priceList.prices || [])
}
return priceLists.map((priceList) => cleanResponseData(priceList, apiFields))

View File

@@ -13,17 +13,17 @@ export const adminPriceListRemoteQueryFields = [
"created_at",
"updated_at",
"deleted_at",
"price_set_money_amounts.id",
"price_set_money_amounts.currency_code",
"price_set_money_amounts.amount",
"price_set_money_amounts.min_quantity",
"price_set_money_amounts.max_quantity",
"price_set_money_amounts.created_at",
"price_set_money_amounts.deleted_at",
"price_set_money_amounts.updated_at",
"price_set_money_amounts.price_set.variant.id",
"price_set_money_amounts.price_rules.value",
"price_set_money_amounts.price_rules.rule_type.rule_attribute",
"prices.id",
"prices.currency_code",
"prices.amount",
"prices.min_quantity",
"prices.max_quantity",
"prices.created_at",
"prices.deleted_at",
"prices.updated_at",
"prices.price_set.variant.id",
"prices.price_rules.value",
"prices.price_rules.rule_type.rule_attribute",
"price_list_rules.price_list_rule_values.value",
"price_list_rules.rule_type.rule_attribute",
]
@@ -50,7 +50,6 @@ export const defaultAdminPriceListFields = [
]
export const defaultAdminPriceListRelations = []
export const allowedAdminPriceListRelations = [PriceListRelations.PRICES]
export const adminListTransformQueryConfig = {

View File

@@ -15,10 +15,7 @@ export const remapKeysForProduct = (selectFields: string[]) => {
const pricingFields = selectFields
.filter((fieldName: string) => isPricing(fieldName))
.map((fieldName: string) =>
fieldName.replace(
"variants.prices.",
"variants.price_set.price_set_money_amounts."
)
fieldName.replace("variants.prices.", "variants.price_set.prices.")
)
return [...productFields, ...pricingFields]
@@ -31,7 +28,7 @@ export const remapKeysForVariant = (selectFields: string[]) => {
const pricingFields = selectFields
.filter((fieldName: string) => isPricing(fieldName))
.map((fieldName: string) =>
fieldName.replace("prices.", "price_set.price_set_money_amounts.")
fieldName.replace("prices.", "price_set.prices.")
)
return [...variantFields, ...pricingFields]
@@ -47,8 +44,8 @@ export const remapProduct = (p: ProductDTO) => {
export const remapVariant = (v: ProductVariantDTO) => {
return {
...v,
prices: (v as any).price_set?.price_set_money_amounts?.map((psma) => ({
...psma,
prices: (v as any).price_set?.prices?.map((price) => ({
...price,
variant_id: v.id,
})),
price_set: undefined,

View File

@@ -19,7 +19,7 @@ export function maybeApplyPriceListsFilter() {
const queryObject = remoteQueryObjectFromString({
entryPoint: "price_list",
fields: ["price_set_money_amounts.price_set.variant.id"],
fields: ["prices.price_set.variant.id"],
variables: {
id: priceListIds,
},
@@ -33,8 +33,9 @@ export function maybeApplyPriceListsFilter() {
const priceLists = await remoteQuery(queryObject)
priceLists.forEach((priceList) => {
priceList.price_set_money_amounts?.forEach((psma) => {
const variantId = psma.price_set?.variant?.id
priceList.prices?.forEach((price) => {
const variantId = price.price_set?.variant?.id
if (variantId) {
variantIds.push(variantId)
}

View File

@@ -9,7 +9,6 @@ import middlewares, {
import {
defaultAdminProductFields,
defaultAdminProductRelations,
defaultAdminProductRemoteQueryObject,
} from "../products"
import { FlagRouter } from "@medusajs/utils"
@@ -87,56 +86,6 @@ export default (app, featureFlagRouter: FlagRouter) => {
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 = [
"id",
"name",

View File

@@ -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]
}

View File

@@ -1,2 +0,0 @@
export * from "./get-price-list"
export * from "./list-and-count-price-lists"

View File

@@ -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]
}

View File

@@ -1,15 +1,5 @@
import {
CalculatedPriceSet,
IPricingModuleService,
PriceSetMoneyAmountDTO,
RemoteQueryFunction,
} from "@medusajs/types"
import {
FlagRouter,
MedusaV2Flag,
promiseAll,
removeNullish,
} from "@medusajs/utils"
import { IPricingModuleService, RemoteQueryFunction } from "@medusajs/types"
import { FlagRouter, promiseAll } from "@medusajs/utils"
import {
CustomerService,
ProductVariantService,
@@ -20,13 +10,7 @@ import {
IPriceSelectionStrategy,
PriceSelectionContext,
} from "../interfaces/price-selection-strategy"
import {
MoneyAmount,
Product,
ProductVariant,
Region,
ShippingOption,
} from "../models"
import { Product, ProductVariant, Region, ShippingOption } from "../models"
import {
PricedProduct,
PricedShippingOption,
@@ -197,128 +181,6 @@ class PricingService extends TransactionBaseService {
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_(
data: {
variantId: string
@@ -326,10 +188,6 @@ class PricingService extends TransactionBaseService {
}[],
context: PricingContext
): Promise<Map<string, ProductVariantPricing>> {
if (this.featureFlagRouter.isFeatureEnabled(MedusaV2Flag.key)) {
return await this.getProductVariantPricingModulePricing_(data, context)
}
const variantsPricing = await this.priceSelectionStrategy
.withTransaction(this.activeManager_)
.calculateVariantPrice(data, context.price_selection)
@@ -681,163 +539,17 @@ 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(
variants: ProductVariant[],
context: PriceSelectionContext = {}
): Promise<PricedVariant[]> {
if (!this.featureFlagRouter.isFeatureEnabled(MedusaV2Flag.key)) {
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
})
return await this.setVariantPrices(variants, context)
}
async setAdminProductPricing(
products: Product[]
): Promise<(Product | PricedProduct)[]> {
if (!this.featureFlagRouter.isFeatureEnabled(MedusaV2Flag.key)) {
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
})
return await this.setProductPrices(products)
}
/**

View File

@@ -5,11 +5,10 @@ export async function getVariantsFromPriceList(
priceListId: string
) {
const remoteQuery = container.resolve("remoteQuery")
const query = {
price_list: {
__args: { id: [priceListId] },
price_set_money_amounts: {
prices: {
price_set: {
variant_link: { variant: { fields: ["id", "product_id"] } },
},
@@ -21,8 +20,8 @@ export async function getVariantsFromPriceList(
const variants: ProductVariantDTO[] = []
priceLists.forEach((priceList) => {
priceList.price_set_money_amounts?.forEach((psma) => {
const variant = psma.price_set?.variant_link?.variant
priceList.prices?.forEach((price) => {
const variant = price.price_set?.variant_link?.variant
if (variant) {
variants.push(variant)

View File

@@ -9,7 +9,7 @@ export const defaultPriceRuleData = [
rule_type_id: "rule-type-1",
value: "USD",
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",
@@ -17,6 +17,6 @@ export const defaultPriceRuleData = [
rule_type_id: "rule-type-2",
value: "region_1",
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[]

View File

@@ -13,17 +13,11 @@ export async function createPriceRules(
const priceRules: PriceRule[] = []
for (let priceRuleData of pricesRulesData) {
const priceRuleDataClone: any = { ...priceRuleData }
const priceRuleDataClone: CreatePriceRuleDTO = { ...priceRuleData }
priceRuleDataClone.price_set = priceRuleDataClone.price_set_id
priceRuleDataClone.rule_type = priceRuleDataClone.rule_type_id
const priceSetMoneyAmountId =
priceRuleDataClone.price_set_money_amount_id ||
priceRuleDataClone.price_set_money_amount?.id
priceRuleDataClone.price_set_money_amount = priceSetMoneyAmountId
priceRuleDataClone.price_set_id = priceRuleDataClone.price_set_id
priceRuleDataClone.rule_type_id = priceRuleDataClone.rule_type_id
priceRuleDataClone.price_id = priceRuleDataClone.price_id
const priceRule = manager.create(PriceRule, priceRuleDataClone)

View File

@@ -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
}

View File

@@ -1,6 +1,6 @@
import { CreatePriceSetDTO } from "@medusajs/types"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { PriceSet, PriceSetMoneyAmount } from "@models"
import { Price, PriceSet } from "@models"
import { defaultPriceSetsData } from "./data"
export * from "./data"
@@ -13,21 +13,21 @@ export async function createPriceSets(
for (let priceSetData of priceSetsData) {
const priceSetDataClone = { ...priceSetData }
const psmas = priceSetDataClone.prices || []
const prices = priceSetDataClone.prices || []
delete priceSetDataClone.prices
let priceSet = manager.create(PriceSet, priceSetDataClone) as PriceSet
manager.persist(priceSet)
for (let psmaData of psmas) {
const psma = manager.create(PriceSetMoneyAmount, {
...psmaData,
for (let priceData of prices) {
const price = manager.create(Price, {
...priceData,
price_set_id: priceSet.id,
title: "test",
})
manager.persist(psma)
manager.persist(price)
}
await manager.flush()

View File

@@ -1,4 +1,4 @@
export const defaultPriceSetMoneyAmountsData = [
export const defaultPricesData = [
{
id: "price-set-money-amount-USD",
currency_code: "USD",

View File

@@ -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
}

View File

@@ -1,10 +1,7 @@
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { createPrices, defaultPricesData } from "./price"
import { createPriceRules, defaultPriceRuleData } from "./price-rule"
import { createPriceSets, defaultPriceSetsData } from "./price-set"
import {
createPriceSetMoneyAmounts,
defaultPriceSetMoneyAmountsData,
} from "./price-set-money-amount"
import { createRuleTypes, defaultRuleTypesData } from "./rule-type"
jest.setTimeout(30000)
@@ -14,12 +11,12 @@ export async function seedPriceData(
{
priceSetsData = defaultPriceSetsData,
priceRuleData = defaultPriceRuleData,
priceSetMoneyAmountsData = defaultPriceSetMoneyAmountsData,
pricesData = defaultPricesData,
ruleTypesData = defaultRuleTypesData,
} = {}
) {
await createPriceSets(testManager, priceSetsData)
await createPriceSetMoneyAmounts(testManager, priceSetMoneyAmountsData)
await createPrices(testManager, pricesData)
await createRuleTypes(testManager, ruleTypesData)
await createPriceRules(testManager, priceRuleData)
}

View File

@@ -57,85 +57,15 @@ moduleIntegrationTestRunner({
describe("PricingModule Service - Calculate Price", () => {
describe("calculatePrices", () => {
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 = [
{
id: "price-set-EUR",
},
{
id: "price-set-PLN",
},
{ id: "price-set-EUR" },
{ id: "price-set-PLN" },
] as unknown as CreatePriceSetDTO[]
const priceSetMoneyAmountsData = [
const pricesData = [
{
id: "psma-PLN",
title: "psma PLN",
id: "price-PLN",
title: "price PLN",
price_set_id: "price-set-PLN",
currency_code: "PLN",
amount: 1000,
@@ -144,8 +74,8 @@ moduleIntegrationTestRunner({
rules_count: 0,
},
{
id: "psma-company_id-EUR",
title: "psma EUR - company_id",
id: "price-company_id-EUR",
title: "price EUR - company_id",
price_set_id: "price-set-EUR",
currency_code: "EUR",
amount: 500,
@@ -154,8 +84,8 @@ moduleIntegrationTestRunner({
rules_count: 1,
},
{
id: "psma-company_id-PLN",
title: "psma PLN - company_id",
id: "price-company_id-PLN",
title: "price PLN - company_id",
price_set_id: "price-set-PLN",
currency_code: "PLN",
amount: 400,
@@ -164,8 +94,8 @@ moduleIntegrationTestRunner({
rules_count: 1,
},
{
id: "psma-region_id-PLN",
title: "psma PLN - region_id",
id: "price-region_id-PLN",
title: "price PLN - region_id",
price_set_id: "price-set-PLN",
currency_code: "PLN",
amount: 300,
@@ -174,8 +104,8 @@ moduleIntegrationTestRunner({
rules_count: 1,
},
{
id: "psma-region_id+company_id-PLN",
title: "psma region_id + company_id",
id: "price-region_id+company_id-PLN",
title: "price region_id + company_id",
price_set_id: "price-set-PLN",
currency_code: "PLN",
amount: 999,
@@ -184,8 +114,8 @@ moduleIntegrationTestRunner({
rules_count: 2,
},
{
id: "psma-region_id-PLN-5-qty",
title: "psma PLN - region_id 5 qty",
id: "price-region_id-PLN-5-qty",
title: "price PLN - region_id 5 qty",
price_set_id: "price-set-PLN",
currency_code: "PLN",
amount: 250,
@@ -194,8 +124,8 @@ moduleIntegrationTestRunner({
rules_count: 1,
},
{
id: "psma-region_id_company_id-PL-EUR",
title: "psma PLN - region_id PL with EUR currency",
id: "price-region_id_company_id-PL-EUR",
title: "price PLN - region_id PL with EUR currency",
price_set_id: "price-set-PLN",
currency_code: "EUR",
amount: 200,
@@ -204,8 +134,9 @@ moduleIntegrationTestRunner({
rules_count: 2,
},
{
id: "psma-region_id_company_id-PL-EUR-4-qty",
title: "psma PLN - region_id PL with EUR currency for quantity 4",
id: "price-region_id_company_id-PL-EUR-4-qty",
title:
"price PLN - region_id PL with EUR currency for quantity 4",
price_set_id: "price-set-PLN",
currency_code: "EUR",
amount: 50,
@@ -214,9 +145,9 @@ moduleIntegrationTestRunner({
rules_count: 2,
},
{
id: "psma-region_id_company_id-PL-EUR-customer-group",
id: "price-region_id_company_id-PL-EUR-customer-group",
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",
currency_code: "EUR",
amount: 100,
@@ -254,7 +185,7 @@ moduleIntegrationTestRunner({
rule_type_id: "rule-type-company_id",
value: "EUR",
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",
@@ -262,7 +193,7 @@ moduleIntegrationTestRunner({
rule_type_id: "rule-type-company_id",
value: "medusa-company-id",
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",
@@ -270,7 +201,7 @@ moduleIntegrationTestRunner({
rule_type_id: "rule-type-region_id",
value: "PL",
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",
@@ -278,7 +209,7 @@ moduleIntegrationTestRunner({
rule_type_id: "rule-type-region_id",
value: "PL",
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",
@@ -286,7 +217,7 @@ moduleIntegrationTestRunner({
rule_type_id: "rule-type-company_id",
value: "medusa-company-id",
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",
@@ -294,7 +225,7 @@ moduleIntegrationTestRunner({
rule_type_id: "rule-type-region_id",
value: "PL",
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",
@@ -302,7 +233,7 @@ moduleIntegrationTestRunner({
rule_type_id: "rule-type-region_id",
value: "PL",
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",
@@ -310,7 +241,7 @@ moduleIntegrationTestRunner({
rule_type_id: "rule-type-company_id",
value: "medusa-company-id",
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",
@@ -318,8 +249,7 @@ moduleIntegrationTestRunner({
rule_type_id: "rule-type-region_id",
value: "PL",
price_list_id: "test",
price_set_money_amount_id:
"psma-region_id_company_id-PL-EUR-4-qty",
price_id: "price-region_id_company_id-PL-EUR-4-qty",
},
{
id: "price-rule-region_id-company_id-PLN-4-qty",
@@ -327,8 +257,7 @@ moduleIntegrationTestRunner({
rule_type_id: "rule-type-company_id",
value: "medusa-company-id",
price_list_id: "test",
price_set_money_amount_id:
"psma-region_id_company_id-PL-EUR-4-qty",
price_id: "price-region_id_company_id-PL-EUR-4-qty",
},
{
id: "price-rule-region_id-currency_customer_group_code-PL",
@@ -336,8 +265,7 @@ moduleIntegrationTestRunner({
rule_type_id: "rule-type-region_id",
value: "PL",
price_list_id: "test",
price_set_money_amount_id:
"psma-region_id_company_id-PL-EUR-customer-group",
price_id: "price-region_id_company_id-PL-EUR-customer-group",
},
{
id: "price-rule-region_id-currency_customer_group_code-PLN",
@@ -345,8 +273,7 @@ moduleIntegrationTestRunner({
rule_type_id: "rule-type-company_id",
value: "medusa-company-id",
price_list_id: "test",
price_set_money_amount_id:
"psma-region_id_company_id-PL-EUR-customer-group",
price_id: "price-region_id_company_id-PL-EUR-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",
value: "test-customer-group",
price_list_id: "test",
price_set_money_amount_id:
"psma-region_id_company_id-PL-EUR-customer-group",
price_id: "price-region_id_company_id-PL-EUR-customer-group",
},
] as unknown as CreatePriceRuleDTO[]
await seedPriceData(MikroOrmWrapper.forkManager(), {
moneyAmountsData,
priceSetsData,
priceSetMoneyAmountsData,
pricesData,
priceRuleData,
ruleTypesData,
})
@@ -427,14 +352,14 @@ moduleIntegrationTestRunner({
original_amount: 1000,
currency_code: "PLN",
calculated_price: {
id: "psma-PLN",
id: "price-PLN",
price_list_id: null,
price_list_type: null,
min_quantity: 1,
max_quantity: 10,
},
original_price: {
id: "psma-PLN",
id: "price-PLN",
price_list_id: null,
price_list_type: null,
min_quantity: 1,
@@ -483,14 +408,14 @@ moduleIntegrationTestRunner({
original_amount: 300,
currency_code: "PLN",
calculated_price: {
id: "psma-region_id-PLN",
id: "price-region_id-PLN",
price_list_id: null,
price_list_type: null,
min_quantity: 1,
max_quantity: 4,
},
original_price: {
id: "psma-region_id-PLN",
id: "price-region_id-PLN",
price_list_id: null,
price_list_type: null,
min_quantity: 1,
@@ -539,14 +464,14 @@ moduleIntegrationTestRunner({
original_amount: 1000,
currency_code: "PLN",
calculated_price: {
id: "psma-PLN",
id: "price-PLN",
price_list_id: null,
price_list_type: null,
min_quantity: 1,
max_quantity: 10,
},
original_price: {
id: "psma-PLN",
id: "price-PLN",
price_list_id: null,
price_list_type: null,
min_quantity: 1,
@@ -651,14 +576,14 @@ moduleIntegrationTestRunner({
original_amount: 300,
currency_code: "PLN",
calculated_price: {
id: "psma-region_id-PLN",
id: "price-region_id-PLN",
price_list_id: null,
price_list_type: null,
min_quantity: 1,
max_quantity: 4,
},
original_price: {
id: "psma-region_id-PLN",
id: "price-region_id-PLN",
price_list_id: null,
price_list_type: null,
min_quantity: 1,
@@ -707,14 +632,14 @@ moduleIntegrationTestRunner({
original_amount: 1000,
currency_code: "PLN",
calculated_price: {
id: "psma-PLN",
id: "price-PLN",
price_list_id: null,
price_list_type: null,
min_quantity: 1,
max_quantity: 10,
},
original_price: {
id: "psma-PLN",
id: "price-PLN",
price_list_id: null,
price_list_type: null,
min_quantity: 1,
@@ -741,14 +666,14 @@ moduleIntegrationTestRunner({
original_amount: 250,
currency_code: "PLN",
calculated_price: {
id: "psma-region_id-PLN-5-qty",
id: "price-region_id-PLN-5-qty",
price_list_id: null,
price_list_type: null,
min_quantity: 4,
max_quantity: 10,
},
original_price: {
id: "psma-region_id-PLN-5-qty",
id: "price-region_id-PLN-5-qty",
price_list_id: null,
price_list_type: null,
min_quantity: 4,
@@ -802,14 +727,14 @@ moduleIntegrationTestRunner({
original_amount: 300,
currency_code: "PLN",
calculated_price: {
id: "psma-region_id-PLN",
id: "price-region_id-PLN",
price_list_id: null,
price_list_type: null,
min_quantity: 1,
max_quantity: 4,
},
original_price: {
id: "psma-region_id-PLN",
id: "price-region_id-PLN",
price_list_id: null,
price_list_type: null,
min_quantity: 1,
@@ -864,14 +789,14 @@ moduleIntegrationTestRunner({
original_amount: 100,
currency_code: "EUR",
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_type: null,
min_quantity: 1,
max_quantity: 3,
},
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_type: null,
min_quantity: 1,
@@ -926,14 +851,14 @@ moduleIntegrationTestRunner({
original_amount: 300,
currency_code: "PLN",
calculated_price: {
id: "psma-region_id-PLN",
id: "price-region_id-PLN",
price_list_id: null,
price_list_type: null,
min_quantity: 1,
max_quantity: 4,
},
original_price: {
id: "psma-region_id-PLN",
id: "price-region_id-PLN",
price_list_id: null,
price_list_type: null,
min_quantity: 1,
@@ -988,14 +913,14 @@ moduleIntegrationTestRunner({
original_amount: 1000,
currency_code: "PLN",
calculated_price: {
id: "psma-PLN",
id: "price-PLN",
price_list_id: null,
price_list_type: null,
min_quantity: 1,
max_quantity: 10,
},
original_price: {
id: "psma-PLN",
id: "price-PLN",
price_list_id: null,
price_list_type: null,
min_quantity: 1,
@@ -1104,14 +1029,14 @@ moduleIntegrationTestRunner({
original_amount: 300,
currency_code: "PLN",
calculated_price: {
id: "psma-region_id-PLN",
id: "price-region_id-PLN",
price_list_id: null,
price_list_type: null,
min_quantity: 1,
max_quantity: 4,
},
original_price: {
id: "psma-region_id-PLN",
id: "price-region_id-PLN",
price_list_id: null,
price_list_type: null,
min_quantity: 1,
@@ -1487,14 +1412,14 @@ moduleIntegrationTestRunner({
original_amount: 300,
currency_code: "PLN",
calculated_price: {
id: "psma-region_id-PLN",
id: "price-region_id-PLN",
price_list_id: null,
price_list_type: null,
min_quantity: 1,
max_quantity: 4,
},
original_price: {
id: "psma-region_id-PLN",
id: "price-region_id-PLN",
price_list_id: null,
price_list_type: null,
min_quantity: 1,
@@ -1700,14 +1625,14 @@ moduleIntegrationTestRunner({
original_amount: 400,
currency_code: "PLN",
calculated_price: {
id: "psma-company_id-PLN",
id: "price-company_id-PLN",
price_list_id: null,
price_list_type: null,
min_quantity: 1,
max_quantity: 5,
},
original_price: {
id: "psma-company_id-PLN",
id: "price-company_id-PLN",
price_list_id: null,
price_list_type: null,
min_quantity: 1,
@@ -1775,14 +1700,14 @@ moduleIntegrationTestRunner({
original_amount: 400,
currency_code: "PLN",
calculated_price: {
id: "psma-company_id-PLN",
id: "price-company_id-PLN",
price_list_id: null,
price_list_type: null,
min_quantity: 1,
max_quantity: 5,
},
original_price: {
id: "psma-company_id-PLN",
id: "price-company_id-PLN",
price_list_id: null,
price_list_type: null,
min_quantity: 1,

View File

@@ -273,17 +273,17 @@ moduleIntegrationTestRunner({
{ id: [createdId] },
{
relations: [
"price_set_money_amounts",
"price_set_money_amounts.price_set",
"prices",
"prices.price_set",
"price_list_rules.price_list_rule_values",
"price_list_rules.rule_type",
],
select: [
"id",
"starts_at",
"price_set_money_amounts.amount",
"price_set_money_amounts.currency_code",
"price_set_money_amounts.price_list_id",
"prices.amount",
"prices.currency_code",
"prices.price_list_id",
"price_list_rules.price_list_rule_values.value",
"price_list_rules.rule_type.rule_attribute",
],
@@ -294,7 +294,7 @@ moduleIntegrationTestRunner({
expect.objectContaining({
id: expect.any(String),
starts_at: updateDate,
price_set_money_amounts: expect.arrayContaining([
prices: expect.arrayContaining([
expect.objectContaining({
price_list: expect.objectContaining({
id: expect.any(String),
@@ -428,16 +428,16 @@ moduleIntegrationTestRunner({
},
{
relations: [
"price_set_money_amounts",
"price_set_money_amounts.price_set",
"prices",
"prices.price_set",
"price_list_rules.price_list_rule_values",
"price_list_rules.rule_type",
],
select: [
"id",
"price_set_money_amounts.amount",
"price_set_money_amounts.currency_code",
"price_set_money_amounts.price_list_id",
"prices.amount",
"prices.currency_code",
"prices.price_list_id",
"price_list_rules.price_list_rule_values.value",
"price_list_rules.rule_type.rule_attribute",
],
@@ -447,7 +447,7 @@ moduleIntegrationTestRunner({
expect(priceList).toEqual(
expect.objectContaining({
id: expect.any(String),
price_set_money_amounts: expect.arrayContaining([
prices: expect.arrayContaining([
expect.objectContaining({
price_list: expect.objectContaining({
id: expect.any(String),
@@ -534,19 +534,19 @@ moduleIntegrationTestRunner({
},
{
relations: [
"price_set_money_amounts",
"price_set_money_amounts.price_set",
"price_set_money_amounts.price_rules",
"prices",
"prices.price_set",
"prices.price_rules",
"price_list_rules.price_list_rule_values",
"price_list_rules.rule_type",
],
select: [
"id",
"price_set_money_amounts.price_rules.value",
"price_set_money_amounts.rules_count",
"price_set_money_amounts.amount",
"price_set_money_amounts.currency_code",
"price_set_money_amounts.price_list_id",
"prices.price_rules.value",
"prices.rules_count",
"prices.amount",
"prices.currency_code",
"prices.price_list_id",
"price_list_rules.price_list_rule_values.value",
"price_list_rules.rule_type.rule_attribute",
],
@@ -556,7 +556,7 @@ moduleIntegrationTestRunner({
expect(priceList).toEqual(
expect.objectContaining({
id: expect.any(String),
price_set_money_amounts: expect.arrayContaining([
prices: expect.arrayContaining([
expect.objectContaining({
rules_count: 1,
price_rules: expect.arrayContaining([
@@ -673,19 +673,19 @@ moduleIntegrationTestRunner({
},
{
relations: [
"price_set_money_amounts",
"price_set_money_amounts.price_set",
"price_set_money_amounts.price_rules",
"prices",
"prices.price_set",
"prices.price_rules",
"price_list_rules.price_list_rule_values",
"price_list_rules.rule_type",
],
select: [
"id",
"price_set_money_amounts.price_rules.value",
"price_set_money_amounts.rules_count",
"price_set_money_amounts.amount",
"price_set_money_amounts.currency_code",
"price_set_money_amounts.price_list_id",
"prices.price_rules.value",
"prices.rules_count",
"prices.amount",
"prices.currency_code",
"prices.price_list_id",
"price_list_rules.price_list_rule_values.value",
"price_list_rules.rule_type.rule_attribute",
],
@@ -695,7 +695,7 @@ moduleIntegrationTestRunner({
expect(priceList).toEqual(
expect.objectContaining({
id: expect.any(String),
price_set_money_amounts: expect.arrayContaining([
prices: expect.arrayContaining([
expect.objectContaining({
rules_count: 0,
price_list: expect.objectContaining({
@@ -782,21 +782,21 @@ moduleIntegrationTestRunner({
},
{
relations: [
"price_set_money_amounts",
"price_set_money_amounts.price_set",
"price_set_money_amounts.price_rules",
"price_set_money_amounts.price_rules.rule_type",
"prices",
"prices.price_set",
"prices.price_rules",
"prices.price_rules.rule_type",
"price_list_rules.price_list_rule_values",
"price_list_rules.rule_type",
],
select: [
"id",
"price_set_money_amounts.price_rules.value",
"price_set_money_amounts.price_rules.rule_type.rule_attribute",
"price_set_money_amounts.rules_count",
"price_set_money_amounts.amount",
"price_set_money_amounts.currency_code",
"price_set_money_amounts.price_list_id",
"prices.price_rules.value",
"prices.price_rules.rule_type.rule_attribute",
"prices.rules_count",
"prices.amount",
"prices.currency_code",
"prices.price_list_id",
"price_list_rules.price_list_rule_values.value",
"price_list_rules.rule_type.rule_attribute",
],
@@ -806,7 +806,7 @@ moduleIntegrationTestRunner({
expect(priceList).toEqual(
expect.objectContaining({
id: expect.any(String),
price_set_money_amounts: expect.arrayContaining([
prices: expect.arrayContaining([
expect.objectContaining({
rules_count: 1,
price_list: expect.objectContaining({
@@ -878,21 +878,21 @@ moduleIntegrationTestRunner({
{ id: ["price-list-1"] },
{
relations: [
"price_set_money_amounts",
"price_set_money_amounts.price_set",
"price_set_money_amounts.price_rules",
"price_set_money_amounts.price_rules.rule_type",
"prices",
"prices.price_set",
"prices.price_rules",
"prices.price_rules.rule_type",
"price_list_rules.price_list_rule_values",
"price_list_rules.rule_type",
],
select: [
"id",
"price_set_money_amounts.price_rules.value",
"price_set_money_amounts.price_rules.rule_type.rule_attribute",
"price_set_money_amounts.rules_count",
"price_set_money_amounts.amount",
"price_set_money_amounts.currency_code",
"price_set_money_amounts.price_list_id",
"prices.price_rules.value",
"prices.price_rules.rule_type.rule_attribute",
"prices.rules_count",
"prices.amount",
"prices.currency_code",
"prices.price_list_id",
"price_list_rules.price_list_rule_values.value",
"price_list_rules.rule_type.rule_attribute",
],
@@ -902,7 +902,7 @@ moduleIntegrationTestRunner({
expect(priceList).toEqual(
expect.objectContaining({
id: expect.any(String),
price_set_money_amounts: expect.arrayContaining([
prices: expect.arrayContaining([
expect.objectContaining({
rules_count: 2,
price_rules: expect.arrayContaining([
@@ -1000,26 +1000,24 @@ moduleIntegrationTestRunner({
let [priceList] = await service.listPriceLists(
{ id: ["price-list-1"] },
{
relations: ["price_set_money_amounts"],
select: ["price_set_money_amounts.id"],
relations: ["prices"],
select: ["prices.id"],
}
)
await service.removePrices(
priceList.price_set_money_amounts!.map((psma) => psma.id)
)
await service.removePrices(priceList.prices!.map((price) => price.id))
;[priceList] = await service.listPriceLists(
{ id: ["price-list-1"] },
{
relations: ["price_set_money_amounts"],
select: ["id", "price_set_money_amounts.id"],
relations: ["prices"],
select: ["id", "prices.id"],
}
)
expect(priceList).toEqual(
expect.objectContaining({
id: expect.any(String),
price_set_money_amounts: [],
prices: [],
})
)
})

View File

@@ -1,11 +1,11 @@
import { Modules } from "@medusajs/modules-sdk"
import { CreatePriceRuleDTO, IPricingModuleService } from "@medusajs/types"
import { IPricingModuleService } from "@medusajs/types"
import { SqlEntityManager } from "@mikro-orm/postgresql"
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 { createPriceSets } from "../../../__fixtures__/price-set"
import { createPriceSetMoneyAmounts } from "../../../__fixtures__/price-set-money-amount"
import { createRuleTypes } from "../../../__fixtures__/rule-type"
jest.setTimeout(30000)
@@ -23,7 +23,7 @@ moduleIntegrationTestRunner({
await createPriceSets(testManager)
await createRuleTypes(testManager)
await createPriceSetMoneyAmounts(testManager)
await createPrices(testManager)
await createPriceRules(testManager)
})
@@ -73,6 +73,7 @@ moduleIntegrationTestRunner({
price_set: {
id: "price-set-1",
},
price_set_id: "price-set-1",
},
])
})
@@ -272,38 +273,33 @@ moduleIntegrationTestRunner({
})
it("should create a PriceRule successfully", async () => {
const psma: PriceSetMoneyAmount = testManager.create(
PriceSetMoneyAmount,
{
currency_code: "EUR",
amount: 100,
price_set_id: "price-set-1",
title: "test",
rules_count: 0,
}
)
const price: Price = testManager.create(Price, {
currency_code: "EUR",
amount: 100,
price_set_id: "price-set-1",
title: "test",
rules_count: 0,
})
await testManager.persist(psma).flush()
await testManager.persist(price).flush()
await service.createPriceRules([
{
id: "price-rule-new",
price_set_id: "price-set-1",
rule_type_id: "rule-type-1",
value: "region_1",
price_list_id: "test",
price_set_money_amount_id: psma.id,
} as unknown as CreatePriceRuleDTO,
])
await service.createPriceRules({
id: "price-rule-new",
price_set_id: "price-set-1",
rule_type_id: "rule-type-1",
value: "region_1",
price_list_id: "test",
price_id: price.id,
})
const [pricerule] = await service.listPriceRules({
const [priceRule] = await service.listPriceRules({
id: ["price-rule-new"],
})
expect(pricerule).toEqual(
expect(priceRule).toEqual(
expect.objectContaining({
id: "price-rule-new",
} as unknown as CreatePriceRuleDTO)
})
)
})
})

View File

@@ -1,11 +1,10 @@
import { Modules } from "@medusajs/modules-sdk"
import {
CreatePriceSetDTO,
CreatePriceSetRuleTypeDTO,
IPricingModuleService,
} from "@medusajs/types"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { Modules } from "@medusajs/modules-sdk"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
import { PriceSetRuleType } from "../../../../src"
import { seedPriceData } from "../../../__fixtures__/seed-price-data"
@@ -39,14 +38,14 @@ moduleIntegrationTestRunner({
await seedPriceData(testManager)
await createPriceSetPriceRules(testManager, [
{
price_set: "price-set-1",
rule_type: "rule-type-1",
price_set_id: "price-set-1",
rule_type_id: "rule-type-1",
},
{
price_set: "price-set-2",
rule_type: "rule-type-2",
price_set_id: "price-set-2",
rule_type_id: "rule-type-2",
},
] as unknown as CreatePriceSetRuleTypeDTO[])
])
})
describe("list", () => {
@@ -84,12 +83,8 @@ moduleIntegrationTestRunner({
id: ["price-set-1"],
},
{
select: [
"id",
"price_set_money_amounts.id",
"price_set_money_amounts.amount",
],
relations: ["price_set_money_amounts"],
select: ["id", "prices.id", "prices.amount"],
relations: ["prices"],
}
)
@@ -98,7 +93,7 @@ moduleIntegrationTestRunner({
expect(serialized).toEqual([
{
id: "price-set-1",
price_set_money_amounts: [
prices: [
expect.objectContaining({
id: "price-set-money-amount-USD",
amount: 500,
@@ -146,12 +141,8 @@ moduleIntegrationTestRunner({
id: ["price-set-1"],
},
{
select: [
"id",
"price_set_money_amounts.amount",
"price_set_money_amounts.id",
],
relations: ["price_set_money_amounts"],
select: ["id", "prices.amount", "prices.id"],
relations: ["prices"],
}
)
@@ -161,7 +152,7 @@ moduleIntegrationTestRunner({
expect(serialized).toEqual([
{
id: "price-set-1",
price_set_money_amounts: [
prices: [
expect.objectContaining({
id: "price-set-money-amount-USD",
amount: 500,
@@ -379,7 +370,7 @@ moduleIntegrationTestRunner({
rule_attribute: "region_id",
}),
],
price_set_money_amounts: [
prices: [
expect.objectContaining({
amount: 100,
currency_code: "USD",
@@ -417,7 +408,7 @@ moduleIntegrationTestRunner({
rule_attribute: "region_id",
}),
],
price_set_money_amounts: expect.arrayContaining([
prices: expect.arrayContaining([
expect.objectContaining({
amount: 100,
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([
{
rules: [{ rule_attribute: "region_id" }],
@@ -454,7 +445,7 @@ moduleIntegrationTestRunner({
rule_attribute: "region_id",
}),
],
price_set_money_amounts: [
prices: [
expect.objectContaining({
amount: 100,
currency_code: "USD",
@@ -493,12 +484,8 @@ moduleIntegrationTestRunner({
const createdPriceSet = await service.create([
{
rules: [
{
rule_attribute: "region_id",
},
{
rule_attribute: "currency_code",
},
{ rule_attribute: "region_id" },
{ rule_attribute: "currency_code" },
],
prices: [
{
@@ -521,23 +508,12 @@ moduleIntegrationTestRunner({
])
await service.removeRules([
{
id: createdPriceSet[0].id,
rules: ["region_id"],
},
{ id: createdPriceSet[0].id, rules: ["region_id"] },
])
let priceSet = await service.list(
{
id: [createdPriceSet[0].id],
},
{
relations: [
"rule_types",
"price_set_money_amounts",
"price_rules",
],
}
{ id: [createdPriceSet[0].id] },
{ relations: ["rule_types", "prices", "price_rules"] }
)
expect(
@@ -552,7 +528,7 @@ moduleIntegrationTestRunner({
}),
},
],
price_set_money_amounts: [
prices: [
expect.objectContaining({
amount: 500,
currency_code: "EUR",
@@ -568,29 +544,18 @@ moduleIntegrationTestRunner({
)
await service.removeRules([
{
id: createdPriceSet[0].id,
rules: ["currency_code"],
},
{ id: createdPriceSet[0].id, rules: ["currency_code"] },
])
priceSet = await service.list(
{
id: [createdPriceSet[0].id],
},
{
relations: [
"rule_types",
"price_set_money_amounts",
"price_rules",
],
}
{ id: [createdPriceSet[0].id] },
{ relations: ["rule_types", "prices", "price_rules"] }
)
expect(priceSet).toEqual([
{
id: expect.any(String),
price_rules: [],
price_set_money_amounts: [],
prices: [],
rule_types: [],
created_at: expect.any(Date),
updated_at: expect.any(Date),
@@ -617,13 +582,13 @@ moduleIntegrationTestRunner({
const [priceSet] = await service.list(
{ id: ["price-set-1"] },
{ relations: ["price_set_money_amounts"] }
{ relations: ["prices"] }
)
expect(priceSet).toEqual(
expect.objectContaining({
id: "price-set-1",
price_set_money_amounts: expect.arrayContaining([
prices: expect.arrayContaining([
expect.objectContaining({
amount: 100,
currency_code: "USD",
@@ -659,13 +624,13 @@ moduleIntegrationTestRunner({
const priceSets = await service.list(
{ id: ["price-set-1", "price-set-2"] },
{ relations: ["price_set_money_amounts"] }
{ relations: ["prices"] }
)
expect(priceSets).toEqual([
expect.objectContaining({
id: "price-set-1",
price_set_money_amounts: expect.arrayContaining([
prices: expect.arrayContaining([
expect.objectContaining({
amount: 100,
currency_code: "USD",
@@ -674,7 +639,7 @@ moduleIntegrationTestRunner({
}),
expect.objectContaining({
id: "price-set-2",
price_set_money_amounts: expect.arrayContaining([
prices: expect.arrayContaining([
expect.objectContaining({
amount: 150,
currency_code: "EUR",
@@ -707,17 +672,14 @@ moduleIntegrationTestRunner({
describe("addRules", () => {
it("should add rules to existing price set", async () => {
console.log("1")
await service.addRules([
{
priceSetId: "price-set-1",
rules: [
{
attribute: "region_id",
},
],
rules: [{ attribute: "region_id" }],
},
])
console.log("2")
const [priceSet] = await service.list(
{ id: ["price-set-1"] },
{ relations: ["rule_types"] }
@@ -745,11 +707,7 @@ moduleIntegrationTestRunner({
await service.addRules([
{
priceSetId: "price-set-doesn't-exist",
rules: [
{
attribute: "region_id",
},
],
rules: [{ attribute: "region_id" }],
},
])
} catch (e) {
@@ -766,14 +724,7 @@ moduleIntegrationTestRunner({
try {
await service.addRules([
{
priceSetId: "price-set-1",
rules: [
{
attribute: "city",
},
],
},
{ priceSetId: "price-set-1", rules: [{ attribute: "city" }] },
])
} catch (e) {
error = e

View File

@@ -1,13 +1,13 @@
import { Modules } from "@medusajs/modules-sdk"
import { ModuleJoinerConfig } from "@medusajs/types"
import { MapToConfig } from "@medusajs/utils"
import { PriceList, PriceSet, PriceSetMoneyAmount } from "@models"
import { Price, PriceList, PriceSet } from "@models"
import schema from "./schema"
export const LinkableKeys = {
price_set_id: PriceSet.name,
price_list_id: PriceList.name,
price_set_money_amount_id: PriceSetMoneyAmount.name,
price_id: Price.name,
}
const entityLinkableKeysMap: MapToConfig = {}

View File

@@ -1,125 +1,7 @@
{
"namespaces": [
"public"
],
"namespaces": ["public"],
"name": "public",
"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": {
"id": {
@@ -157,10 +39,7 @@
"primary": false,
"nullable": false,
"default": "'draft'",
"enumItems": [
"active",
"draft"
],
"enumItems": ["active", "draft"],
"mappedType": "enum"
},
"type": {
@@ -171,10 +50,7 @@
"primary": false,
"nullable": false,
"default": "'sale'",
"enumItems": [
"sale",
"override"
],
"enumItems": ["sale", "override"],
"mappedType": "enum"
},
"starts_at": {
@@ -245,9 +121,7 @@
"indexes": [
{
"keyName": "IDX_price_list_deleted_at",
"columnNames": [
"deleted_at"
],
"columnNames": ["deleted_at"],
"composite": false,
"primary": false,
"unique": false,
@@ -255,9 +129,7 @@
},
{
"keyName": "price_list_pkey",
"columnNames": [
"id"
],
"columnNames": ["id"],
"composite": false,
"primary": true,
"unique": true
@@ -315,9 +187,7 @@
"indexes": [
{
"keyName": "IDX_price_set_deleted_at",
"columnNames": [
"deleted_at"
],
"columnNames": ["deleted_at"],
"composite": false,
"primary": false,
"unique": false,
@@ -325,9 +195,7 @@
},
{
"keyName": "price_set_pkey",
"columnNames": [
"id"
],
"columnNames": ["id"],
"composite": false,
"primary": true,
"unique": true
@@ -453,54 +321,44 @@
"mappedType": "datetime"
}
},
"name": "price_set_money_amount",
"name": "price",
"schema": "public",
"indexes": [
{
"keyName": "IDX_price_set_money_amount_currency_code",
"columnNames": [
"currency_code"
],
"keyName": "IDX_price_currency_code",
"columnNames": ["currency_code"],
"composite": false,
"primary": 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",
"columnNames": [
"price_set_id"
],
"keyName": "IDX_price_price_set_id",
"columnNames": ["price_set_id"],
"composite": false,
"primary": 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",
"columnNames": [
"price_list_id"
],
"keyName": "IDX_price_price_list_id",
"columnNames": ["price_list_id"],
"composite": false,
"primary": 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",
"columnNames": [
"deleted_at"
],
"keyName": "IDX_price_deleted_at",
"columnNames": ["deleted_at"],
"composite": false,
"primary": 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",
"columnNames": [
"id"
],
"keyName": "price_pkey",
"columnNames": ["id"],
"composite": false,
"primary": true,
"unique": true
@@ -508,28 +366,20 @@
],
"checks": [],
"foreignKeys": {
"price_set_money_amount_price_set_id_foreign": {
"constraintName": "price_set_money_amount_price_set_id_foreign",
"columnNames": [
"price_set_id"
],
"localTableName": "public.price_set_money_amount",
"referencedColumnNames": [
"id"
],
"price_price_set_id_foreign": {
"constraintName": "price_price_set_id_foreign",
"columnNames": ["price_set_id"],
"localTableName": "public.price",
"referencedColumnNames": ["id"],
"referencedTableName": "public.price_set",
"deleteRule": "cascade",
"updateRule": "cascade"
},
"price_set_money_amount_price_list_id_foreign": {
"constraintName": "price_set_money_amount_price_list_id_foreign",
"columnNames": [
"price_list_id"
],
"localTableName": "public.price_set_money_amount",
"referencedColumnNames": [
"id"
],
"price_price_list_id_foreign": {
"constraintName": "price_price_list_id_foreign",
"columnNames": ["price_list_id"],
"localTableName": "public.price",
"referencedColumnNames": ["id"],
"referencedTableName": "public.price_list",
"deleteRule": "cascade",
"updateRule": "cascade"
@@ -613,9 +463,7 @@
"indexes": [
{
"keyName": "IDX_rule_type_rule_attribute",
"columnNames": [
"rule_attribute"
],
"columnNames": ["rule_attribute"],
"composite": false,
"primary": false,
"unique": false,
@@ -623,9 +471,7 @@
},
{
"keyName": "IDX_rule_type_deleted_at",
"columnNames": [
"deleted_at"
],
"columnNames": ["deleted_at"],
"composite": false,
"primary": false,
"unique": false,
@@ -633,9 +479,7 @@
},
{
"keyName": "rule_type_pkey",
"columnNames": [
"id"
],
"columnNames": ["id"],
"composite": false,
"primary": true,
"unique": true
@@ -711,9 +555,7 @@
"indexes": [
{
"keyName": "IDX_price_set_rule_type_price_set_id",
"columnNames": [
"price_set_id"
],
"columnNames": ["price_set_id"],
"composite": false,
"primary": false,
"unique": false,
@@ -721,9 +563,7 @@
},
{
"keyName": "IDX_price_set_rule_type_rule_type_id",
"columnNames": [
"rule_type_id"
],
"columnNames": ["rule_type_id"],
"composite": false,
"primary": false,
"unique": false,
@@ -731,9 +571,7 @@
},
{
"keyName": "IDX_price_set_rule_type_deleted_at",
"columnNames": [
"deleted_at"
],
"columnNames": ["deleted_at"],
"composite": false,
"primary": false,
"unique": false,
@@ -741,9 +579,7 @@
},
{
"keyName": "price_set_rule_type_pkey",
"columnNames": [
"id"
],
"columnNames": ["id"],
"composite": false,
"primary": true,
"unique": true
@@ -753,26 +589,18 @@
"foreignKeys": {
"price_set_rule_type_price_set_id_foreign": {
"constraintName": "price_set_rule_type_price_set_id_foreign",
"columnNames": [
"price_set_id"
],
"columnNames": ["price_set_id"],
"localTableName": "public.price_set_rule_type",
"referencedColumnNames": [
"id"
],
"referencedColumnNames": ["id"],
"referencedTableName": "public.price_set",
"deleteRule": "cascade",
"updateRule": "cascade"
},
"price_set_rule_type_rule_type_id_foreign": {
"constraintName": "price_set_rule_type_rule_type_id_foreign",
"columnNames": [
"rule_type_id"
],
"columnNames": ["rule_type_id"],
"localTableName": "public.price_set_rule_type",
"referencedColumnNames": [
"id"
],
"referencedColumnNames": ["id"],
"referencedTableName": "public.rule_type",
"deleteRule": "cascade",
"updateRule": "cascade"
@@ -827,8 +655,8 @@
"default": "0",
"mappedType": "integer"
},
"price_set_money_amount_id": {
"name": "price_set_money_amount_id",
"price_id": {
"name": "price_id",
"type": "text",
"unsigned": false,
"autoincrement": false,
@@ -874,9 +702,7 @@
"indexes": [
{
"keyName": "IDX_price_rule_price_set_id",
"columnNames": [
"price_set_id"
],
"columnNames": ["price_set_id"],
"composite": false,
"primary": false,
"unique": false,
@@ -884,29 +710,23 @@
},
{
"keyName": "IDX_price_rule_rule_type_id",
"columnNames": [
"rule_type_id"
],
"columnNames": ["rule_type_id"],
"composite": false,
"primary": 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"
},
{
"keyName": "IDX_price_rule_price_set_money_amount_id_unique",
"columnNames": [
"price_set_money_amount_id"
],
"keyName": "IDX_price_rule_price_id_rule_type_id_unique",
"columnNames": ["price_id"],
"composite": false,
"primary": 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",
"columnNames": [
"deleted_at"
],
"columnNames": ["deleted_at"],
"composite": false,
"primary": false,
"unique": false,
@@ -914,9 +734,7 @@
},
{
"keyName": "price_rule_pkey",
"columnNames": [
"id"
],
"columnNames": ["id"],
"composite": false,
"primary": true,
"unique": true
@@ -926,39 +744,27 @@
"foreignKeys": {
"price_rule_price_set_id_foreign": {
"constraintName": "price_rule_price_set_id_foreign",
"columnNames": [
"price_set_id"
],
"columnNames": ["price_set_id"],
"localTableName": "public.price_rule",
"referencedColumnNames": [
"id"
],
"referencedColumnNames": ["id"],
"referencedTableName": "public.price_set",
"deleteRule": "cascade",
"updateRule": "cascade"
},
"price_rule_rule_type_id_foreign": {
"constraintName": "price_rule_rule_type_id_foreign",
"columnNames": [
"rule_type_id"
],
"columnNames": ["rule_type_id"],
"localTableName": "public.price_rule",
"referencedColumnNames": [
"id"
],
"referencedColumnNames": ["id"],
"referencedTableName": "public.rule_type",
"updateRule": "cascade"
},
"price_rule_price_set_money_amount_id_foreign": {
"constraintName": "price_rule_price_set_money_amount_id_foreign",
"columnNames": [
"price_set_money_amount_id"
],
"price_rule_price_id_foreign": {
"constraintName": "price_rule_price_id_foreign",
"columnNames": ["price_id"],
"localTableName": "public.price_rule",
"referencedColumnNames": [
"id"
],
"referencedTableName": "public.price_set_money_amount",
"referencedColumnNames": ["id"],
"referencedTableName": "public.price",
"deleteRule": "cascade",
"updateRule": "cascade"
}
@@ -1031,9 +837,7 @@
"indexes": [
{
"keyName": "IDX_price_list_rule_rule_type_id_unique",
"columnNames": [
"rule_type_id"
],
"columnNames": ["rule_type_id"],
"composite": false,
"primary": false,
"unique": false,
@@ -1041,9 +845,7 @@
},
{
"keyName": "IDX_price_list_rule_price_list_id",
"columnNames": [
"price_list_id"
],
"columnNames": ["price_list_id"],
"composite": false,
"primary": false,
"unique": false,
@@ -1051,9 +853,7 @@
},
{
"keyName": "IDX_price_list_rule_deleted_at",
"columnNames": [
"deleted_at"
],
"columnNames": ["deleted_at"],
"composite": false,
"primary": false,
"unique": false,
@@ -1061,9 +861,7 @@
},
{
"keyName": "price_list_rule_pkey",
"columnNames": [
"id"
],
"columnNames": ["id"],
"composite": false,
"primary": true,
"unique": true
@@ -1073,25 +871,17 @@
"foreignKeys": {
"price_list_rule_rule_type_id_foreign": {
"constraintName": "price_list_rule_rule_type_id_foreign",
"columnNames": [
"rule_type_id"
],
"columnNames": ["rule_type_id"],
"localTableName": "public.price_list_rule",
"referencedColumnNames": [
"id"
],
"referencedColumnNames": ["id"],
"referencedTableName": "public.rule_type",
"updateRule": "cascade"
},
"price_list_rule_price_list_id_foreign": {
"constraintName": "price_list_rule_price_list_id_foreign",
"columnNames": [
"price_list_id"
],
"columnNames": ["price_list_id"],
"localTableName": "public.price_list_rule",
"referencedColumnNames": [
"id"
],
"referencedColumnNames": ["id"],
"referencedTableName": "public.price_list",
"deleteRule": "cascade",
"updateRule": "cascade"
@@ -1165,9 +955,7 @@
"indexes": [
{
"keyName": "IDX_price_list_rule_value_price_list_rule_id",
"columnNames": [
"price_list_rule_id"
],
"columnNames": ["price_list_rule_id"],
"composite": false,
"primary": false,
"unique": false,
@@ -1175,9 +963,7 @@
},
{
"keyName": "IDX_price_list_rule_value_deleted_at",
"columnNames": [
"deleted_at"
],
"columnNames": ["deleted_at"],
"composite": false,
"primary": false,
"unique": false,
@@ -1185,9 +971,7 @@
},
{
"keyName": "price_list_rule_value_pkey",
"columnNames": [
"id"
],
"columnNames": ["id"],
"composite": false,
"primary": true,
"unique": true
@@ -1197,13 +981,9 @@
"foreignKeys": {
"price_list_rule_value_price_list_rule_id_foreign": {
"constraintName": "price_list_rule_value_price_list_rule_id_foreign",
"columnNames": [
"price_list_rule_id"
],
"columnNames": ["price_list_rule_id"],
"localTableName": "public.price_list_rule_value",
"referencedColumnNames": [
"id"
],
"referencedColumnNames": ["id"],
"referencedTableName": "public.price_list_rule",
"deleteRule": "cascade",
"updateRule": "cascade"

View File

@@ -11,11 +11,11 @@ export class Migration20230929122253 extends Migration {
)
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(
'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(
@@ -27,14 +27,14 @@ export class Migration20230929122253 extends Migration {
)
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(
'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(
'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(
@@ -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;'
)
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(
@@ -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;'
)
this.addSql(
'alter table "price_set_money_amount" add column "price_list_id" text null;'
)
this.addSql('alter table "price" add column "price_list_id" text null;')
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;'
)
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(
'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(
'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(
'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(
'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;'
)
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(
'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(
'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(
@@ -208,27 +206,25 @@ export class Migration20230929122253 extends Migration {
)
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(
'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(
'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(
'drop index if exists "IDX_price_set_money_amount_money_amount_id";'
)
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;'
'CREATE INDEX IF NOT EXISTS "IDX_price_currency_code" ON "price" (currency_code) WHERE deleted_at IS NULL;'
)
}
}

View File

@@ -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;');
}
}

View File

@@ -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;'
)
}
}

View File

@@ -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;'
)
}
}

View File

@@ -1,8 +1,8 @@
export { default as Price } from "./price"
export { default as PriceList } from "./price-list"
export { default as PriceListRule } from "./price-list-rule"
export { default as PriceListRuleValue } from "./price-list-rule-value"
export { default as PriceRule } from "./price-rule"
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 RuleType } from "./rule-type"

View File

@@ -20,8 +20,8 @@ import {
PrimaryKey,
Property,
} from "@mikro-orm/core"
import Price from "./price"
import PriceListRule from "./price-list-rule"
import PriceSetMoneyAmount from "./price-set-money-amount"
import RuleType from "./rule-type"
type OptionalFields =
@@ -68,10 +68,10 @@ export default class PriceList {
})
ends_at: Date | null = null
@OneToMany(() => PriceSetMoneyAmount, (psma) => psma.price_list, {
@OneToMany(() => Price, (price) => price.price_list, {
cascade: ["soft-remove" as Cascade],
})
price_set_money_amounts = new Collection<PriceSetMoneyAmount>(this)
prices = new Collection<Price>(this)
@OneToMany(() => PriceListRule, (pr) => pr.price_list, {
cascade: ["soft-remove" as Cascade],

View File

@@ -1,7 +1,7 @@
import { DAL } from "@medusajs/types"
import {
DALUtils,
createPsqlIndexStatementHelper,
DALUtils,
generateEntityId,
} from "@medusajs/utils"
import {
@@ -14,8 +14,8 @@ import {
PrimaryKey,
Property,
} from "@mikro-orm/core"
import Price from "./price"
import PriceSet from "./price-set"
import PriceSetMoneyAmount from "./price-set-money-amount"
import RuleType from "./rule-type"
type OptionalFields = DAL.SoftDeletableEntityDateColumns
@@ -39,9 +39,9 @@ const PriceRuleRuleTypeIdIndex = createPsqlIndexStatementHelper({
where: "deleted_at IS NULL",
})
const PriceRulePriceSetMoneyAmountIdIndex = createPsqlIndexStatementHelper({
const PriceRulePriceIdIndex = createPsqlIndexStatementHelper({
tableName: tableName,
columns: "price_set_money_amount_id",
columns: ["price_id", "rule_type_id"],
where: "deleted_at IS NULL",
unique: true,
})
@@ -83,17 +83,17 @@ export default class PriceRule {
@Property({ columnType: "integer", default: 0 })
priority: number = 0
@PriceRulePriceSetMoneyAmountIdIndex.MikroORMIndex()
@ManyToOne(() => PriceSetMoneyAmount, {
@PriceRulePriceIdIndex.MikroORMIndex()
@ManyToOne(() => Price, {
columnType: "text",
mapToPk: true,
fieldName: "price_set_money_amount_id",
fieldName: "price_id",
onDelete: "cascade",
})
price_set_money_amount_id: string
price_id: string
@ManyToOne(() => PriceSetMoneyAmount, { persist: false })
price_set_money_amount: PriceSetMoneyAmount
@ManyToOne(() => Price, { persist: false })
price: Price
@Property({
onCreate: () => new Date(),
@@ -117,10 +117,16 @@ export default class PriceRule {
@BeforeCreate()
beforeCreate() {
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() {
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!
}
}

View File

@@ -41,12 +41,22 @@ export default class PriceSetRuleType {
id!: string
@PriceSetRuleTypePriceSetIdIndex.MikroORMIndex()
@ManyToOne(() => PriceSet, { onDelete: "cascade" })
price_set: PriceSet
@ManyToOne(() => PriceSet, {
columnType: "text",
mapToPk: true,
fieldName: "price_set_id",
onDelete: "cascade",
})
price_set_id: string
@PriceSetRuleTypeRuleTypeIdIndex.MikroORMIndex()
@ManyToOne(() => RuleType, { onDelete: "cascade" })
rule_type: RuleType
@ManyToOne(() => RuleType, {
columnType: "text",
mapToPk: true,
fieldName: "rule_type_id",
onDelete: "cascade",
})
rule_type_id: string
@Property({
onCreate: () => new Date(),

View File

@@ -15,8 +15,8 @@ import {
PrimaryKey,
Property,
} from "@mikro-orm/core"
import Price from "./price"
import PriceRule from "./price-rule"
import PriceSetMoneyAmount from "./price-set-money-amount"
import PriceSetRuleType from "./price-set-rule-type"
import RuleType from "./rule-type"
@@ -33,13 +33,13 @@ export default class PriceSet {
@PrimaryKey({ columnType: "text" })
id!: string
@OneToMany(() => PriceSetMoneyAmount, (psma) => psma.price_set, {
cascade: ["soft-remove" as Cascade],
@OneToMany(() => Price, (price) => price.price_set, {
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, {
cascade: ["soft-remove" as Cascade],
cascade: [Cascade.PERSIST, "soft-remove" as Cascade],
})
price_rules = new Collection<PriceRule>(this)

View File

@@ -1,7 +1,7 @@
import { DAL } from "@medusajs/types"
import {
DALUtils,
createPsqlIndexStatementHelper,
DALUtils,
generateEntityId,
} from "@medusajs/utils"
import {
@@ -11,8 +11,8 @@ import {
Entity,
Filter,
ManyToOne,
OnInit,
OneToMany,
OnInit,
OptionalProps,
PrimaryKey,
Property,
@@ -23,32 +23,26 @@ import PriceSet from "./price-set"
type OptionalFields = DAL.SoftDeletableEntityDateColumns
const tableName = "price_set_money_amount"
const PriceSetMoneyAmountDeletedAtIndex = createPsqlIndexStatementHelper({
const tableName = "price"
const PriceDeletedAtIndex = createPsqlIndexStatementHelper({
tableName: tableName,
columns: "deleted_at",
where: "deleted_at IS NOT NULL",
})
const PriceSetMoneyAmountPriceSetIdIndex = createPsqlIndexStatementHelper({
const PricePriceSetIdIndex = createPsqlIndexStatementHelper({
tableName: tableName,
columns: "price_set_id",
where: "deleted_at IS NULL",
})
const PriceSetMoneyAmountMoneyAmountIdIndex = createPsqlIndexStatementHelper({
tableName: tableName,
columns: "money_amount_id",
where: "deleted_at IS NULL",
})
const PriceSetMoneyAmountPriceListIdIndex = createPsqlIndexStatementHelper({
const PricePriceListIdIndex = createPsqlIndexStatementHelper({
tableName: tableName,
columns: "price_list_id",
where: "deleted_at IS NULL",
})
const PriceSetMoneyAmountCurrencyCodeIndex = createPsqlIndexStatementHelper({
const PriceCurrencyCodeIndex = createPsqlIndexStatementHelper({
tableName: tableName,
columns: "currency_code",
where: "deleted_at IS NULL",
@@ -56,7 +50,7 @@ const PriceSetMoneyAmountCurrencyCodeIndex = createPsqlIndexStatementHelper({
@Entity({ tableName })
@Filter(DALUtils.mikroOrmSoftDeletableFilterOptions)
export default class PriceSetMoneyAmount {
export default class Price {
[OptionalProps]?: OptionalFields
@PrimaryKey({ columnType: "text" })
@@ -65,7 +59,7 @@ export default class PriceSetMoneyAmount {
@Property({ columnType: "text", nullable: true })
title: string | null = null
@PriceSetMoneyAmountCurrencyCodeIndex.MikroORMIndex()
@PriceCurrencyCodeIndex.MikroORMIndex()
@Property({ columnType: "text" })
currency_code: string
@@ -78,7 +72,7 @@ export default class PriceSetMoneyAmount {
@Property({ columnType: "numeric", nullable: true })
max_quantity: number | null = null
@PriceSetMoneyAmountPriceSetIdIndex.MikroORMIndex()
@PricePriceSetIdIndex.MikroORMIndex()
@ManyToOne(() => PriceSet, {
columnType: "text",
mapToPk: true,
@@ -95,12 +89,12 @@ export default class PriceSetMoneyAmount {
@OneToMany({
entity: () => PriceRule,
mappedBy: (pr) => pr.price_set_money_amount,
cascade: ["soft-remove" as Cascade],
mappedBy: (pr) => pr.price,
cascade: [Cascade.PERSIST, "soft-remove" as Cascade],
})
price_rules = new Collection<PriceRule>(this)
@PriceSetMoneyAmountPriceListIdIndex.MikroORMIndex()
@PricePriceListIdIndex.MikroORMIndex()
@ManyToOne(() => PriceList, {
columnType: "text",
mapToPk: true,
@@ -128,17 +122,21 @@ export default class PriceSetMoneyAmount {
})
updated_at: Date
@PriceSetMoneyAmountDeletedAtIndex.MikroORMIndex()
@PriceDeletedAtIndex.MikroORMIndex()
@Property({ columnType: "timestamptz", nullable: true })
deleted_at: Date | null = null
@BeforeCreate()
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() {
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!
}
}

View File

@@ -57,27 +57,27 @@ export class PricingRepository
const date = new Date().toISOString()
// Gets all the price set money amounts where rules match for each of the contexts
// that the price set is configured for
const psmaSubQueryKnex = knex({
psma: "price_set_money_amount",
const priceSubQueryKnex = knex({
price: "price",
})
.select({
id: "psma1.id",
amount: "psma1.amount",
min_quantity: "psma1.min_quantity",
max_quantity: "psma1.max_quantity",
currency_code: "psma1.currency_code",
price_set_id: "psma1.price_set_id",
rules_count: "psma1.rules_count",
price_list_id: "psma1.price_list_id",
id: "price1.id",
amount: "price1.amount",
min_quantity: "price1.min_quantity",
max_quantity: "price1.max_quantity",
currency_code: "price1.currency_code",
price_set_id: "price1.price_set_id",
rules_count: "price1.rules_count",
price_list_id: "price1.price_list_id",
pl_rules_count: "pl.rules_count",
pl_type: "pl.type",
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_rule as pr", "pr.price_set_money_amount_id", "psma1.id")
.leftJoin("price_list as pl", "pl.id", "psma1.price_list_id")
.leftJoin("price as price1", "price1.id", "price1.id")
.leftJoin("price_rule as pr", "pr.price_id", "price1.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_value as plrv",
@@ -90,31 +90,31 @@ export class PricingRepository
{ column: "rules_count", order: "desc" },
{ column: "pl.rules_count", order: "desc" },
])
.groupBy("psma1.id", "pl.id")
.groupBy("price1.id", "pl.id")
.having(
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(
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)) {
q.orWhere({
"rt.rule_attribute": key,
"pr.value": value,
})
}
q.orWhere("psma1.rules_count", "=", 0)
q.whereNull("psma1.price_list_id")
q.orWhere("price1.rules_count", "=", 0)
q.whereNull("price1.price_list_id")
})
psmaSubQueryKnex.orWhere((q) => {
q.whereNotNull("psma1.price_list_id")
priceSubQueryKnex.orWhere((q) => {
q.whereNotNull("price1.price_list_id")
.andWhere(function () {
this.whereNull("pl.starts_at").orWhere("pl.starts_at", "<=", date)
})
@@ -141,9 +141,9 @@ export class PricingRepository
"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",
})
.select({
id: "psma.id",
id: "price.id",
price_set_id: "ps.id",
amount: "psma.amount",
min_quantity: "psma.min_quantity",
max_quantity: "psma.max_quantity",
currency_code: "psma.currency_code",
amount: "price.amount",
min_quantity: "price.min_quantity",
max_quantity: "price.max_quantity",
currency_code: "price.currency_code",
default_priority: "rt.default_priority",
rules_count: "psma.rules_count",
pl_rules_count: "psma.pl_rules_count",
price_list_type: "psma.pl_type",
price_list_id: "psma.price_list_id",
rules_count: "price.rules_count",
pl_rules_count: "price.pl_rules_count",
price_list_type: "price.pl_type",
price_list_id: "price.price_list_id",
})
.join(psmaSubQueryKnex.as("psma"), "psma.price_set_id", "ps.id")
.leftJoin("price_rule as pr", "pr.price_set_money_amount_id", "psma.id")
.join(priceSubQueryKnex.as("price"), "price.price_set_id", "ps.id")
.leftJoin("price_rule as pr", "pr.price_id", "price.id")
.leftJoin("rule_type as rt", "rt.id", "pr.rule_type_id")
.whereIn("ps.id", pricingFilters.id)
.andWhere("psma.currency_code", "=", currencyCode)
.andWhere("price.currency_code", "=", currencyCode)
.orderBy([
{ column: "psma.has_price_list", order: "asc" },
{ column: "price.has_price_list", order: "asc" },
{ column: "amount", order: "asc" },
{ column: "rules_count", order: "desc" },
{ column: "default_priority", order: "desc" },
])
if (quantity) {
priceSetQueryKnex.where("psma.min_quantity", "<=", quantity)
priceSetQueryKnex.andWhere("psma.max_quantity", ">=", quantity)
priceSetQueryKnex.where("price.min_quantity", "<=", quantity)
priceSetQueryKnex.andWhere("price.max_quantity", ">=", quantity)
} else {
priceSetQueryKnex.andWhere(function () {
this.andWhere("psma.min_quantity", "<=", "1").orWhereNull(
"psma.min_quantity"
this.andWhere("price.min_quantity", "<=", "1").orWhereNull(
"price.min_quantity"
)
})
}

View File

@@ -22,11 +22,11 @@ export async function run({
logger.info(`Loading seed data from ${path}...`)
const { priceSetsData, priceSetMoneyAmountsData } = await import(
const { priceSetsData, pricesData } = await import(
resolve(process.cwd(), path)
).catch((e) => {
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
})
@@ -44,10 +44,10 @@ export async function run({
const manager = orm.em.fork()
try {
logger.info("Inserting price_set & price_set_money_amount")
logger.info("Inserting price_sets & prices")
await createPriceSets(manager as any, priceSetsData)
await createPriceSetMoneyAmounts(manager as any, priceSetMoneyAmountsData)
await createPriceSets(manager, priceSetsData)
await createPrices(manager, pricesData)
} catch (e) {
logger.error(
`Failed to insert the seed data in the PostgreSQL database ${dbData.clientUrl}.${EOL}${e}`
@@ -70,18 +70,15 @@ async function createPriceSets(
return priceSets
}
async function createPriceSetMoneyAmounts(
async function createPrices(
manager: SqlEntityManager<PostgreSqlDriver>,
data: RequiredEntityData<PricingModels.PriceSetMoneyAmount>[]
data: RequiredEntityData<PricingModels.Price>[]
) {
const priceSetMoneyAmounts = data.map((priceSetMoneyAmountData) => {
return manager.create(
PricingModels.PriceSetMoneyAmount,
priceSetMoneyAmountData
)
const prices = data.map((priceData) => {
return manager.create(PricingModels.Price, priceData)
})
await manager.persistAndFlush(priceSetMoneyAmounts)
await manager.persistAndFlush(prices)
return priceSetMoneyAmounts
return prices
}

View File

@@ -2,6 +2,7 @@ import {
AddPricesDTO,
Context,
CreatePriceListRuleDTO,
CreatePricesDTO,
DAL,
InternalModuleDeclaration,
ModuleJoinerConfig,
@@ -14,33 +15,33 @@ import {
RuleTypeDTO,
} from "@medusajs/types"
import {
arrayDifference,
deduplicate,
generateEntityId,
groupBy,
InjectManager,
InjectTransactionManager,
MedusaContext,
MedusaError,
ModulesSdkUtils,
PriceListType,
arrayDifference,
deduplicate,
groupBy,
removeNullish,
} from "@medusajs/utils"
import {
Price,
PriceList,
PriceListRule,
PriceListRuleValue,
PriceRule,
PriceSet,
PriceSetMoneyAmount,
PriceSetRuleType,
RuleType,
} from "@models"
import { PriceListService, RuleTypeService } from "@services"
import { ServiceTypes } from "@types"
import { validatePriceListDates } from "@utils"
import { entityNameToLinkableKeysMap, joinerConfig } from "../joiner-config"
import {PriceListService, RuleTypeService} from "@services"
import {validatePriceListDates} from "@utils"
import {entityNameToLinkableKeysMap, joinerConfig} from "../joiner-config"
type InjectedDependencies = {
baseRepository: DAL.RepositoryService
@@ -49,7 +50,7 @@ type InjectedDependencies = {
ruleTypeService: RuleTypeService<any>
priceRuleService: ModulesSdkTypes.InternalModuleService<any>
priceSetRuleTypeService: ModulesSdkTypes.InternalModuleService<any>
priceSetMoneyAmountService: ModulesSdkTypes.InternalModuleService<any>
priceService: ModulesSdkTypes.InternalModuleService<any>
priceListService: PriceListService<any>
priceListRuleService: ModulesSdkTypes.InternalModuleService<any>
priceListRuleValueService: ModulesSdkTypes.InternalModuleService<any>
@@ -60,7 +61,7 @@ const generateMethodForModels = [
PriceListRule,
PriceListRuleValue,
PriceRule,
PriceSetMoneyAmount,
Price,
PriceSetRuleType,
RuleType,
]
@@ -70,7 +71,7 @@ export default class PricingModuleService<
TRuleType extends RuleType = RuleType,
TPriceRule extends PriceRule = PriceRule,
TPriceSetRuleType extends PriceSetRuleType = PriceSetRuleType,
TPriceSetMoneyAmount extends PriceSetMoneyAmount = PriceSetMoneyAmount,
TPrice extends Price = Price,
TPriceList extends PriceList = PriceList,
TPriceListRule extends PriceListRule = PriceListRule,
TPriceListRuleValue extends PriceListRuleValue = PriceListRuleValue
@@ -79,7 +80,7 @@ export default class PricingModuleService<
InjectedDependencies,
PricingTypes.PriceSetDTO,
{
PriceSetMoneyAmount: { dto: PricingTypes.PriceSetMoneyAmountDTO }
Price: { dto: PricingTypes.PriceDTO }
PriceRule: {
dto: PricingTypes.PriceRuleDTO
create: PricingTypes.CreatePriceRuleDTO
@@ -102,7 +103,7 @@ export default class PricingModuleService<
protected readonly priceSetService_: ModulesSdkTypes.InternalModuleService<TPriceSet>
protected readonly priceRuleService_: ModulesSdkTypes.InternalModuleService<TPriceRule>
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 priceListRuleService_: ModulesSdkTypes.InternalModuleService<TPriceListRule>
protected readonly priceListRuleValueService_: ModulesSdkTypes.InternalModuleService<TPriceListRuleValue>
@@ -115,7 +116,7 @@ export default class PricingModuleService<
priceSetService,
priceRuleService,
priceSetRuleTypeService,
priceSetMoneyAmountService,
priceService,
priceListService,
priceListRuleService,
priceListRuleValueService,
@@ -132,7 +133,7 @@ export default class PricingModuleService<
this.ruleTypeService_ = ruleTypeService
this.priceRuleService_ = priceRuleService
this.priceSetRuleTypeService_ = priceSetRuleTypeService
this.priceSetMoneyAmountService_ = priceSetMoneyAmountService
this.priceService_ = priceService
this.priceListService_ = priceListService
this.priceListRuleService_ = priceListRuleService
this.priceListRuleValueService_ = priceListRuleValueService
@@ -228,20 +229,20 @@ export default class PricingModuleService<
@MedusaContext() sharedContext: Context = {}
): Promise<PriceSetDTO | PriceSetDTO[]> {
const input = Array.isArray(data) ? data : [data]
const priceSets = await this.create_(input, sharedContext)
const dbPriceSets = await this.list(
{ id: priceSets.filter((p) => !!p).map((p) => p!.id) },
{
relations: ["rule_types", "price_set_money_amounts", "price_rules"],
},
{ id: priceSets.map((p) => p.id) },
{ relations: ["rule_types", "prices", "price_rules"] },
sharedContext
)
return (Array.isArray(data) ? dbPriceSets : dbPriceSets[0]) as unknown as
| PriceSetDTO
| PriceSetDTO[]
// Ensure the output to be in the same order as the input
const results = priceSets.map((priceSet) => {
return dbPriceSets.find((p) => p.id === priceSet.id)!
})
return Array.isArray(data) ? results : results[0]
}
@InjectTransactionManager("baseRepository_")
@@ -249,14 +250,14 @@ export default class PricingModuleService<
data: PricingTypes.CreatePriceSetDTO[],
@MedusaContext() sharedContext: Context = {}
) {
const input = Array.isArray(data) ? data : [data]
const ruleAttributes = data
.map((d) => d.rules?.map((r) => r.rule_attribute) ?? [])
.flat()
const ruleTypes = await this.ruleTypeService_.list(
{
rule_attribute: ruleAttributes,
},
{ rule_attribute: ruleAttributes },
{ take: null },
sharedContext
)
@@ -293,77 +294,82 @@ export default class PricingModuleService<
)
}
const ruleSetRuleTypeToCreateMap: Map<string, TPriceSetRuleType> = new Map()
const toCreate = input.map((inputData) => {
const id = generateEntityId(
(inputData as unknown as TPriceSet).id,
"pset"
)
const { prices, rules = [], ...rest } = inputData
let pricesData: CreatePricesDTO[] = []
rules.forEach((rule) => {
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 priceSetRuleType = {
rule_type_id: ruleTypeMap.get(attribute).id,
price_set_id: id,
} as TPriceSetRuleType
ruleSetRuleTypeToCreateMap.set(
JSON.stringify(priceSetRuleType),
priceSetRuleType
)
})
return {
...rest,
title: "test", // TODO: accept title
rules_count: numberOfRules,
price_rules: Array.from(rulesDataMap.values()),
}
})
}
return {
...rest,
id,
prices: pricesData,
}
})
// Bulk create price sets
const priceSetData = data.map(({ rules, prices, ...rest }) => rest)
const createdPriceSets = await this.priceSetService_.create(
priceSetData,
toCreate,
sharedContext
)
// Price set rule types
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) {
if (ruleSetRuleTypeToCreateMap.size) {
await this.priceSetRuleTypeService_.create(
ruleTypeData as unknown as PricingTypes.CreatePriceSetRuleTypeDTO[],
sharedContext
)
}
const priceSetMoneyAmountData: unknown[] = []
const priceRulesData: unknown[] = []
for (const [index, item] of data.entries()) {
for (const price of item.prices || []) {
const cleanRules = price.rules ? removeNullish(price.rules) : {}
const numberOfRules = Object.entries(cleanRules).length
const priceSetMoneyAmount = {
...price,
price_set_id: createdPriceSets[index].id,
title: "test", // TODO: accept title
rules_count: numberOfRules,
}
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
const createdPriceSetMoneyAmounts =
await this.priceSetMoneyAmountService_.create(
priceSetMoneyAmountData as PricingTypes.CreatePriceSetMoneyAmountDTO[],
sharedContext
)
// Update price set money amount references
for (let i = 0, j = 0; i < priceSetMoneyAmountData.length; i++) {
const rulesCount = (priceSetMoneyAmountData[i] as any).rules_count
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[],
Array.from(ruleSetRuleTypeToCreateMap.values()),
sharedContext
)
}
@@ -392,9 +398,7 @@ export default class PricingModuleService<
return await this.list(
{ 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 invalidPriceSetInputs = inputs.filter(
(d) => !priceSetMap.has(d.priceSetId)
)
@@ -434,7 +437,7 @@ export default class PricingModuleService<
const ruleTypes = await this.ruleTypeService_.list(
{
rule_attribute: inputs
.map((d) => d.rules.map((r) => r.attribute))
.map((data) => data.rules.map((r) => r.attribute))
.flat(),
},
{ take: null },
@@ -461,23 +464,21 @@ export default class PricingModuleService<
const priceSetRuleTypesCreate: PricingTypes.CreatePriceSetRuleTypeDTO[] = []
inputs.forEach((d) => {
const priceSet = priceSetMap.get(d.priceSetId)
for (const r of d.rules) {
if (priceSetRuleTypeMap.get(d.priceSetId)!.has(r.attribute)) {
inputs.forEach((data) => {
for (const rule of data.rules) {
if (priceSetRuleTypeMap.get(data.priceSetId)!.has(rule.attribute)) {
continue
}
priceSetRuleTypesCreate.push({
rule_type: ruleTypeMap.get(r.attribute) as RuleTypeDTO,
price_set: priceSet as unknown as PriceSetDTO,
rule_type_id: ruleTypeMap.get(rule.attribute)!.id,
price_set_id: priceSetMap.get(data.priceSetId)!.id,
})
}
})
await this.priceSetRuleTypeService_.create(
priceSetRuleTypesCreate as unknown as PricingTypes.CreatePriceSetRuleTypeDTO[],
priceSetRuleTypesCreate,
sharedContext
)
@@ -503,11 +504,11 @@ export default class PricingModuleService<
await this.addPrices_(input, sharedContext)
return (await this.list(
return await this.list(
{ id: input.map((d) => d.priceSetId) },
{ relations: ["price_set_money_amounts"] },
{ relations: ["prices"] },
sharedContext
)) as unknown as PricingTypes.PriceSetDTO[] | PricingTypes.PriceSetDTO
)
}
@InjectTransactionManager("baseRepository_")
@@ -558,7 +559,7 @@ export default class PricingModuleService<
}
})
const priceSetMoneyAmountsBulkData: unknown[] = input.flatMap(
const pricesToCreate: PricingTypes.CreatePriceDTO[] = input.flatMap(
({ priceSetId, prices }) =>
prices.map((price) => {
const numberOfRules = Object.entries(price?.rules ?? {}).length
@@ -572,21 +573,21 @@ export default class PricingModuleService<
})
)
const createdPriceSetMoneyAmounts =
await this.priceSetMoneyAmountService_.create(
priceSetMoneyAmountsBulkData as ServiceTypes.CreatePriceSetMoneyAmountDTO[],
sharedContext
)
const createdPrices = await this.priceService_.create(
pricesToCreate,
sharedContext
)
// Price rules
let rulesCursor = 0
const priceRulesBulkData = input.flatMap(({ priceSetId, prices }) =>
prices.flatMap((ma) => {
const rules = ma.rules ?? {}
const priceSetMoneyAmount = createdPriceSetMoneyAmounts[rulesCursor]
const price = createdPrices[rulesCursor]
rulesCursor++
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,
price_set_id: priceSetId,
value: v,
@@ -605,14 +606,12 @@ export default class PricingModuleService<
@MedusaContext() sharedContext: Context = {}
): Promise<void> {
const priceSets = await this.priceSetService_.list(
{
id: data.map((d) => d.id),
},
{ id: data.map((d) => d.id) },
{},
sharedContext
)
const priceSetIds = priceSets.map((ps) => ps.id)
const priceSetIds = priceSets.map((ps) => ps.id)
const ruleTypes = await this.ruleTypeService_.list(
{
rule_attribute: data.map((d) => d.rules || []).flat(),
@@ -620,26 +619,17 @@ export default class PricingModuleService<
{ take: null },
sharedContext
)
const ruleTypeIds = ruleTypes.map((rt) => rt.id)
const ruleTypeIds = ruleTypes.map((rt) => rt.id)
const priceSetRuleTypes = await this.priceSetRuleTypeService_.list(
{
price_set_id: priceSetIds,
rule_type_id: ruleTypeIds,
},
{ price_set_id: priceSetIds, rule_type_id: ruleTypeIds },
{ take: null },
sharedContext
)
const priceRules = await this.priceRuleService_.list(
{
price_set_id: priceSetIds,
rule_type_id: ruleTypeIds,
},
{
select: ["price_set_money_amount"],
take: null,
},
{ price_set_id: priceSetIds, rule_type_id: ruleTypeIds },
{ select: ["price"], take: null },
sharedContext
)
@@ -648,8 +638,8 @@ export default class PricingModuleService<
sharedContext
)
await this.priceSetMoneyAmountService_.delete(
priceRules.map((pr) => pr.price_set_money_amount.id),
await this.priceService_.delete(
priceRules.map((pr) => pr.price.id),
sharedContext
)
}
@@ -663,9 +653,7 @@ export default class PricingModuleService<
return await this.baseRepository_.serialize<PricingTypes.PriceSetDTO[]>(
priceSets,
{
populate: true,
}
{ populate: true }
)
}
@@ -678,9 +666,7 @@ export default class PricingModuleService<
return await this.baseRepository_.serialize<PricingTypes.PriceListDTO[]>(
priceLists,
{
populate: true,
}
{ populate: true }
)
}
@@ -759,7 +745,7 @@ export default class PricingModuleService<
)
// Create the values for the rule
for (const ruleValue of ruleValues as string[]) {
for (const ruleValue of ruleValues) {
await this.priceListRuleValueService_.create(
[{ price_list_rule_id: priceListRule.id, value: ruleValue }],
sharedContext
@@ -767,26 +753,23 @@ export default class PricingModuleService<
}
}
for (const price of prices) {
for (const priceData of prices) {
const {
price_set_id: priceSetId,
rules: priceRules = {},
...psmaData
} = price
...rest
} = priceData
const [priceSetMoneyAmount] =
await this.priceSetMoneyAmountService_.create(
[
{
price_set_id: priceSetId,
price_list_id: priceList.id,
title: "test",
rules_count: Object.keys(priceRules).length,
...psmaData,
},
],
sharedContext
)
const createdPrice = await this.priceService_.create(
{
price_set_id: priceSetId,
price_list_id: priceList.id,
title: "test",
rules_count: Object.keys(priceRules).length,
...rest,
},
sharedContext
)
await this.priceRuleService_.create(
Object.entries(priceRules).map(([ruleAttribute, ruleValue]) => {
@@ -794,7 +777,7 @@ export default class PricingModuleService<
price_set_id: priceSetId,
rule_type_id: ruleTypeMap.get(ruleAttribute)!?.id,
value: ruleValue,
price_set_money_amount_id: priceSetMoneyAmount.id,
price_id: createdPrice.id,
}
}),
sharedContext
@@ -814,9 +797,7 @@ export default class PricingModuleService<
return await this.baseRepository_.serialize<PricingTypes.PriceListDTO[]>(
priceLists,
{
populate: true,
}
{ populate: true }
)
}
@@ -913,7 +894,7 @@ export default class PricingModuleService<
sharedContext
)
for (const ruleValue of ruleValues as string[]) {
for (const ruleValue of ruleValues) {
await this.priceListRuleValueService_.create(
[{ price_list_rule_id: priceListRule.id, value: ruleValue }],
sharedContext
@@ -979,7 +960,7 @@ export default class PricingModuleService<
): Promise<PricingTypes.PriceListDTO[]> {
const ruleTypeAttributes: string[] = []
const priceListIds: string[] = []
const psmaIds: string[] = []
const priceIds: string[] = []
const priceSetIds = data
.map((d) => d.prices.map((price) => price.price_set_id))
.flat()
@@ -988,22 +969,19 @@ export default class PricingModuleService<
priceListIds.push(priceListData.price_list_id)
for (const price of priceListData.prices) {
psmaIds.push(price.id)
priceIds.push(price.id)
ruleTypeAttributes.push(...Object.keys(price.rules || {}))
}
}
const psmas = await this.listPriceSetMoneyAmounts(
{ id: psmaIds },
{
take: null,
relations: ["price_rules"],
},
const prices = await this.listPrices(
{ id: priceIds },
{ take: null, relations: ["price_rules"] },
sharedContext
)
const psmaMap: Map<string, PricingTypes.PriceSetMoneyAmountDTO> = new Map(
psmas.map((psma) => [psma.id, psma])
const priceMap: Map<string, PricingTypes.PriceDTO> = new Map(
prices.map((price) => [price.id, price])
)
const ruleTypes = await this.listRuleTypes(
@@ -1032,6 +1010,7 @@ export default class PricingModuleService<
}
acc.set(curr.id, priceSetRuleAttributeSet)
return acc
},
new Map()
@@ -1080,40 +1059,41 @@ export default class PricingModuleService<
)
}
const moneyAmountsToUpdate: PricingTypes.UpdateMoneyAmountDTO[] = []
const priceRulesToDelete: string[] = []
const priceRuleIdsToDelete: string[] = []
const priceRulesToCreate: PricingTypes.CreatePriceRuleDTO[] = []
const psmaToUpdate: ServiceTypes.UpdatePriceSetMoneyAmountDTO[] = []
const pricesToUpdate: (PricingTypes.UpdatePriceDTO & {
rules_count: number
})[] = []
for (const price of prices) {
const { rules, price_set_id, ...priceData } = price
const priceSetMoneyAmount = psmaMap.get(price.id)!
const priceRules = priceSetMoneyAmount.price_rules!
for (const priceData of prices) {
const { rules, price_set_id, ...rest } = priceData
const price = priceMap.get(rest.id)!
const priceRules = price.price_rules!
if (typeof rules === "undefined") {
continue
}
psmaToUpdate.push({
...priceData,
pricesToUpdate.push({
...rest,
rules_count: Object.keys(rules).length,
})
priceRulesToDelete.push(...priceRules.map((pr) => pr.id))
priceRuleIdsToDelete.push(...priceRules.map((pr) => pr.id))
priceRulesToCreate.push(
...Object.entries(rules).map(([ruleAttribute, ruleValue]) => ({
price_set_id: price.price_set_id,
price_set_id,
rule_type_id: ruleTypeMap.get(ruleAttribute)!.id,
value: ruleValue,
price_set_money_amount_id: priceSetMoneyAmount.id,
price_id: price.id,
}))
)
}
await Promise.all([
this.priceRuleService_.delete(priceRulesToDelete),
this.priceRuleService_.delete(priceRuleIdsToDelete),
this.priceRuleService_.create(priceRulesToCreate),
this.priceSetMoneyAmountService_.update(psmaToUpdate),
this.priceService_.update(pricesToUpdate),
])
}
@@ -1133,7 +1113,7 @@ export default class PricingModuleService<
ids: string[],
sharedContext: Context = {}
): Promise<void> {
await this.priceSetMoneyAmountService_.delete(ids, sharedContext)
await this.priceService_.delete(ids, sharedContext)
}
@InjectManager("baseRepository_")
@@ -1237,15 +1217,15 @@ export default class PricingModuleService<
}
await Promise.all(
prices.map(async (price) => {
const priceRules = price.rules || {}
prices.map(async (priceData) => {
const priceRules = priceData.rules || {}
const noOfRules = Object.keys(priceRules).length
const [psma] = await this.priceSetMoneyAmountService_.create(
const [price] = await this.priceService_.create(
[
{
...price,
price_set_id: price.price_set_id,
...priceData,
price_set_id: priceData.price_set_id,
title: "test",
price_list_id: priceList.id,
rules_count: noOfRules,
@@ -1257,16 +1237,16 @@ export default class PricingModuleService<
await this.priceRuleService_.create(
Object.entries(priceRules).map(([ruleAttribute, ruleValue]) => {
return {
price_set_id: price.price_set_id,
price_set_id: priceData.price_set_id,
rule_type_id: ruleTypeMap.get(ruleAttribute)!?.id,
value: ruleValue,
price_set_money_amount_id: psma.id,
price_id: price.id,
}
}),
sharedContext
)
return psma
return price
})
)
}
@@ -1291,27 +1271,19 @@ export default class PricingModuleService<
): Promise<PricingTypes.PriceListDTO[]> {
const priceLists = await this.priceListService_.list(
{ 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
)
const priceListMap = new Map(priceLists.map((p) => [p.id, p]))
const ruleTypes = await this.listRuleTypes(
{
rule_attribute: data.map((d) => Object.keys(d.rules)).flat(),
},
{
take: null,
}
{ rule_attribute: data.map((d) => Object.keys(d.rules)).flat() },
{ take: null }
)
const ruleTypeMap = new Map(ruleTypes.map((rt) => [rt.rule_attribute, rt]))
const ruleIdsToUpdate: string[] = []
const rulesToCreate: CreatePriceListRuleDTO[] = []
const priceRuleValues = new Map<string, Map<string, string[]>>()
for (const { price_list_id: priceListId, rules } of data) {
@@ -1325,9 +1297,7 @@ export default class PricingModuleService<
}
const priceListRulesMap: Map<string, PriceListRule> = new Map(
priceList.price_list_rules
.getItems()
.map((p) => [p.rule_type.rule_attribute, p])
priceList.price_list_rules.map((p) => [p.rule_type.rule_attribute, p])
)
const priceListRuleValues = new Map<string, string[]>()
@@ -1365,9 +1335,7 @@ export default class PricingModuleService<
const [createdRules, priceListValuesToDelete] = await Promise.all([
this.priceListRuleService_.create(rulesToCreate),
this.priceListRuleValueService_.list(
{
price_list_rule_id: ruleIdsToUpdate,
},
{ price_list_rule_id: ruleIdsToUpdate },
{ take: null }
),
])
@@ -1382,6 +1350,7 @@ export default class PricingModuleService<
}
const values = ruleValues.get(rule_type_id)
if (!values) {
continue
}
@@ -1400,16 +1369,14 @@ export default class PricingModuleService<
sharedContext
),
this.priceListRuleValueService_.create(
priceListRuleValuesToCreate as ServiceTypes.CreatePriceListRuleValueDTO[],
priceListRuleValuesToCreate,
sharedContext
),
])
return await this.baseRepository_.serialize<PricingTypes.PriceListDTO[]>(
priceLists,
{
populate: true,
}
{ populate: true }
)
}
@@ -1430,15 +1397,13 @@ export default class PricingModuleService<
): Promise<PricingTypes.PriceListDTO[]> {
const priceLists = await this.priceListService_.list(
{ 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
)
const priceListMap = new Map(priceLists.map((p) => [p.id, p]))
const idsToDelete: string[] = []
for (const { price_list_id: priceListId, rules } of data) {
const priceList = priceListMap.get(priceListId)
@@ -1450,14 +1415,13 @@ export default class PricingModuleService<
}
const priceListRulesMap: Map<string, PriceListRule> = new Map(
priceList.price_list_rules
.getItems()
.map((p) => [p.rule_type.rule_attribute, p])
priceList.price_list_rules.map((p) => [p.rule_type.rule_attribute, p])
)
await Promise.all(
rules.map(async (rule_attribute) => {
const rule = priceListRulesMap.get(rule_attribute)
if (rule) {
idsToDelete.push(rule.id)
}
@@ -1469,9 +1433,7 @@ export default class PricingModuleService<
return await this.baseRepository_.serialize<PricingTypes.PriceListDTO[]>(
priceLists,
{
populate: true,
}
{ populate: true }
)
}
}

View File

@@ -1,4 +1,4 @@
import { Context, DAL } from "@medusajs/types"
import { Context, DAL, PricingTypes } from "@medusajs/types"
import {
InjectTransactionManager,
MedusaContext,
@@ -6,7 +6,6 @@ import {
validateRuleAttributes,
} from "@medusajs/utils"
import { RuleType } from "@models"
import { ServiceTypes } from "@types"
type InjectedDependencies = {
ruleTypeRepository: DAL.RepositoryService
@@ -26,17 +25,17 @@ export default class RuleTypeService<
}
create(
data: ServiceTypes.CreateRuleTypeDTO,
data: PricingTypes.CreateRuleTypeDTO,
sharedContext: Context
): Promise<TEntity>
create(
data: ServiceTypes.CreateRuleTypeDTO[],
data: PricingTypes.CreateRuleTypeDTO[],
sharedContext: Context
): Promise<TEntity[]>
@InjectTransactionManager("ruleTypeRepository_")
async create(
data: ServiceTypes.CreateRuleTypeDTO | ServiceTypes.CreateRuleTypeDTO[],
data: PricingTypes.CreateRuleTypeDTO | PricingTypes.CreateRuleTypeDTO[],
@MedusaContext() sharedContext: Context = {}
): Promise<TEntity | TEntity[]> {
const data_ = Array.isArray(data) ? data : [data]
@@ -46,12 +45,12 @@ export default class RuleTypeService<
// @ts-ignore
update(
data: ServiceTypes.UpdateRuleTypeDTO[],
data: PricingTypes.UpdateRuleTypeDTO[],
sharedContext: Context
): Promise<TEntity[]>
// @ts-ignore
update(
data: ServiceTypes.UpdateRuleTypeDTO,
data: PricingTypes.UpdateRuleTypeDTO,
sharedContext: Context
): Promise<TEntity>
@@ -59,7 +58,7 @@ export default class RuleTypeService<
// TODO: add support for selector? and then rm ts ignore
// @ts-ignore
async update(
data: ServiceTypes.UpdateRuleTypeDTO | ServiceTypes.UpdateRuleTypeDTO[],
data: PricingTypes.UpdateRuleTypeDTO | PricingTypes.UpdateRuleTypeDTO[],
@MedusaContext() sharedContext: Context = {}
): Promise<TEntity | TEntity[]> {
const data_ = Array.isArray(data) ? data : [data]

View File

@@ -4,5 +4,4 @@ export type InitializeModuleInjectableDependencies = {
logger?: Logger
}
export * as RepositoryTypes from "./repositories"
export * as ServiceTypes from "./services"

View File

@@ -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"

View File

@@ -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
}

View File

@@ -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
}

View File

@@ -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
}

View File

@@ -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
}

View File

@@ -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
}

View File

@@ -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
}

View File

@@ -1,5 +0,0 @@
export interface CreatePriceSetDTO {}
export interface UpdatePriceSetDTO {
id: string
}

View File

@@ -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
}

View File

@@ -1,10 +1 @@
export * from "./money-amount"
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"

View File

@@ -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[]
}

View File

@@ -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[]
}

View File

@@ -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[]
}

View File

@@ -1,10 +1,3 @@
import {
BaseFilterable,
MoneyAmountDTO,
PriceListRuleDTO,
PriceSetMoneyAmountDTO,
RuleTypeDTO,
} from "@medusajs/types"
import { PriceListStatus, PriceListType } from "@medusajs/utils"
export interface CreatePriceListDTO {
@@ -25,26 +18,3 @@ export interface UpdatePriceListDTO {
status?: PriceListStatus
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[]
}

View File

@@ -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[]
}

View File

@@ -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
}

View File

@@ -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[]
}

View File

@@ -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
}

View File

@@ -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
}

View File

@@ -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[]
}

View File

@@ -1,7 +1,7 @@
export * from "./money-amount"
export * from "./price"
export * from "./price-list"
export * from "./price-rule"
export * from "./price-set"
export * from "./price-set-money-amount"
export * from "./price-set-rule-type"
export * from "./rule-type"

View File

@@ -1,5 +1,4 @@
import { BaseFilterable } from "../../dal"
import { PriceSetMoneyAmountDTO } from "./price-set-money-amount"
/**
* @interface
@@ -27,10 +26,6 @@ export interface MoneyAmountDTO {
* The maximum quantity required to be purchased for this price to be applied.
*/
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.
*/

View File

@@ -4,7 +4,7 @@ import {
MoneyAmountDTO,
UpdateMoneyAmountDTO,
} from "./money-amount"
import { PriceSetMoneyAmountDTO } from "./price-set-money-amount"
import { PriceDTO } from "./price"
import { RuleTypeDTO } from "./rule-type"
/**
@@ -74,7 +74,7 @@ export interface PriceListDTO {
*
* @expandable
*/
price_set_money_amounts?: PriceSetMoneyAmountDTO[]
prices?: PriceDTO[]
/**
* The associated money amounts.
*

View File

@@ -40,9 +40,9 @@ export interface PriceRuleDTO {
*/
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.
*/
@@ -85,16 +85,16 @@ export interface CreatePriceRuleDTO {
*/
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
*
* 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 {
id: string
@@ -109,9 +109,9 @@ export interface UpdatePriceRuleDTO {
*/
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.
*/

View File

@@ -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[]
}

View File

@@ -10,8 +10,8 @@ export interface PriceSetRuleTypeDTO {
}
export interface CreatePriceSetRuleTypeDTO {
price_set: PriceSetDTO
rule_type: RuleTypeDTO
price_set_id: string
rule_type_id: string
}
export interface UpdatePriceSetRuleTypeDTO {

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[]
}

View File

@@ -10,15 +10,15 @@ import {
CreateRuleTypeDTO,
FilterablePriceListProps,
FilterablePriceListRuleProps,
FilterablePriceProps,
FilterablePriceRuleProps,
FilterablePriceSetMoneyAmountProps,
FilterablePriceSetProps,
FilterableRuleTypeProps,
PriceDTO,
PriceListDTO,
PriceListRuleDTO,
PriceRuleDTO,
PriceSetDTO,
PriceSetMoneyAmountDTO,
PricingContext,
PricingFilters,
RemovePriceListRulesDTO,
@@ -169,7 +169,7 @@ export interface IPricingModuleService extends IModuleService {
* const priceSet = await pricingService.retrieve(
* priceSetId,
* {
* relations: ["money_amounts"]
* relations: ["prices"]
* }
* )
*
@@ -230,7 +230,7 @@ export interface IPricingModuleService extends IModuleService {
* id: priceSetIds
* },
* {
* relations: ["money_amounts"]
* relations: ["prices"]
* }
* )
*
@@ -253,7 +253,7 @@ export interface IPricingModuleService extends IModuleService {
* id: priceSetIds
* },
* {
* relations: ["money_amounts"],
* relations: ["prices"],
* skip,
* take
* }
@@ -270,7 +270,7 @@ export interface IPricingModuleService extends IModuleService {
* initialize as initializePricingModule,
* } 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 priceSets = await pricingService.list(
@@ -280,14 +280,14 @@ export interface IPricingModuleService extends IModuleService {
* id: priceSetIds
* },
* {
* money_amounts: {
* id: moneyAmountIds
* prices: {
* id: priceIds
* }
* }
* ]
* },
* {
* relations: ["money_amounts"],
* relations: ["prices"],
* skip,
* take
* }
@@ -350,7 +350,7 @@ export interface IPricingModuleService extends IModuleService {
* id: priceSetIds
* },
* {
* relations: ["money_amounts"]
* relations: ["prices"]
* }
* )
*
@@ -373,7 +373,7 @@ export interface IPricingModuleService extends IModuleService {
* id: priceSetIds
* },
* {
* relations: ["money_amounts"],
* relations: ["prices"],
* skip,
* take
* }
@@ -390,7 +390,7 @@ export interface IPricingModuleService extends IModuleService {
* initialize as initializePricingModule,
* } 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 [priceSets, count] = await pricingService.listAndCount(
@@ -400,14 +400,14 @@ export interface IPricingModuleService extends IModuleService {
* id: priceSetIds
* },
* {
* money_amounts: {
* id: moneyAmountIds
* prices: {
* id: priceIds
* }
* }
* ]
* },
* {
* relations: ["money_amounts"],
* relations: ["prices"],
* skip,
* take
* }
@@ -1240,52 +1240,52 @@ export interface IPricingModuleService extends IModuleService {
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 {FindConfig<PriceSetMoneyAmountDTO>} config -
* The configurations determining how the price set money amounts are retrieved. Its properties, such as `select` or `relations`, accept the
* attributes or relations associated with a price set money amount.
* @param {FilterablePriceProps} filters - The filters to apply on the retrieved prices.
* @param {FindConfig<PriceDTO>} config -
* The configurations determining how the prices are retrieved. Its properties, such as `select` or `relations`, accept the
* 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.
* @returns {Promise<PriceSetMoneyAmountDTO[]>} The list of price set money amounts.
* @returns {Promise<PriceDTO[]>} The list of prices.
*
* @example
*
* To retrieve a list of price set money amounts using their IDs:
* To retrieve a list of prices using their IDs:
*
* ```ts
* import {
* initialize as initializePricingModule,
* } from "@medusajs/pricing"
*
* async function retrievePriceSetMoneyAmounts (id: string) {
* async function retrievePrices (id: string) {
* const pricingService = await initializePricingModule()
*
* const priceSetMoneyAmounts = await pricingService.listPriceSetMoneyAmounts({
* const prices = await pricingService.listPrices({
* 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
* import {
* initialize as initializePricingModule,
* } from "@medusajs/pricing"
*
* async function retrievePriceSetMoneyAmounts (id: string) {
* async function retrievePrices (id: string) {
* const pricingService = await initializePricingModule()
*
* const priceSetMoneyAmounts = await pricingService.listPriceSetMoneyAmounts({
* const prices = await pricingService.listPrices({
* id: [id]
* }, {
* 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,
* } 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 priceSetMoneyAmounts = await pricingService.listPriceSetMoneyAmounts({
* const prices = await pricingService.listPrices({
* id: [id]
* }, {
* relations: ["price_rules"],
@@ -1307,7 +1307,7 @@ export interface IPricingModuleService extends IModuleService {
* 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,
* } 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 priceSetMoneyAmounts = await pricingService.listPriceSetMoneyAmounts({
* const prices = await pricingService.listPrices({
* $and: [
* {
* id: ids
@@ -1336,78 +1336,76 @@ export interface IPricingModuleService extends IModuleService {
* take
* })
*
* // do something with the price set money amounts or return them
* // do something with the prices or return them
* }
* ```
*/
listPriceSetMoneyAmounts(
filters?: FilterablePriceSetMoneyAmountProps,
config?: FindConfig<PriceSetMoneyAmountDTO>,
listPrices(
filters?: FilterablePriceProps,
config?: FindConfig<PriceDTO>,
sharedContext?: Context
): Promise<PriceSetMoneyAmountDTO[]>
): Promise<PriceDTO[]>
softDeletePriceSetMoneyAmounts<
TReturnableLinkableKeys extends string = string
>(
psmaIds: string[],
softDeletePrices<TReturnableLinkableKeys extends string = string>(
priceIds: string[],
config?: SoftDeleteReturn<TReturnableLinkableKeys>,
sharedContext?: Context
): Promise<Record<string, string[]> | void>
restorePriceSetMoneyAmounts<TReturnableLinkableKeys extends string = string>(
psmaIds: string[],
restorePrices<TReturnableLinkableKeys extends string = string>(
priceIds: string[],
config?: RestoreReturn<TReturnableLinkableKeys>,
sharedContext?: Context
): 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
* available price set money amounts satisfying the provided filters.
* This method is used to retrieve a paginated list of prices along with the total count of
* available prices satisfying the provided filters.
*
* @param {FilterablePriceSetMoneyAmountProps} filters - The filters to apply on the retrieved price set money amounts.
* @param {FindConfig<PriceSetMoneyAmountDTO>} config -
* The configurations determining how the price set money amounts are retrieved. Its properties, such as `select` or `relations`, accept the
* attributes or relations associated with a price set money amount.
* @param {FilterablePriceProps} filters - The filters to apply on the retrieved prices.
* @param {FindConfig<PriceDTO>} config -
* The configurations determining how the prices are retrieved. Its properties, such as `select` or `relations`, accept the
* 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.
* @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
*
* To retrieve a list of price set money amounts using their IDs:
* To retrieve a list of prices using their IDs:
*
* ```ts
* import {
* initialize as initializePricingModule,
* } from "@medusajs/pricing"
*
* async function retrievePriceSetMoneyAmounts (id: string) {
* async function retrievePrices (id: string) {
* const pricingService = await initializePricingModule()
*
* const [priceSetMoneyAmounts, count] = await pricingService.listAndCountPriceSetMoneyAmounts({
* const [prices, count] = await pricingService.listAndCountPrices({
* 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
* import {
* initialize as initializePricingModule,
* } from "@medusajs/pricing"
*
* async function retrievePriceSetMoneyAmounts (id: string) {
* async function retrievePrices (id: string) {
* const pricingService = await initializePricingModule()
*
* const [priceSetMoneyAmounts, count] = await pricingService.listAndCountPriceSetMoneyAmounts({
* const [prices, count] = await pricingService.listAndCountPrices({
* id: [id]
* }, {
* 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,
* } 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 [priceSetMoneyAmounts, count] = await pricingService.listAndCountPriceSetMoneyAmounts({
* const [prices, count] = await pricingService.listAndCountPrices({
* id: [id]
* }, {
* relations: ["price_rules"],
@@ -1429,7 +1427,7 @@ export interface IPricingModuleService extends IModuleService {
* 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,
* } 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 [priceSetMoneyAmounts, count] = await pricingService.listAndCountPriceSetMoneyAmounts({
* const [prices, count] = await pricingService.listAndCountPrices({
* $and: [
* {
* id: ids
@@ -1458,15 +1456,15 @@ export interface IPricingModuleService extends IModuleService {
* take
* })
*
* // do something with the price set money amounts or return them
* // do something with the prices or return them
* }
* ```
*/
listAndCountPriceSetMoneyAmounts(
filters?: FilterablePriceSetMoneyAmountProps,
config?: FindConfig<PriceSetMoneyAmountDTO>,
listAndCountPrices(
filters?: FilterablePriceProps,
config?: FindConfig<PriceDTO>,
sharedContext?: Context
): Promise<[PriceSetMoneyAmountDTO[], number]>
): Promise<[PriceDTO[], number]>
/**
* This method is used to retrieve a price rule by its ID.
@@ -1750,7 +1748,7 @@ export interface IPricingModuleService extends IModuleService {
* priceSetId: string,
* ruleTypeId: string,
* value: string,
* priceSetMoneyAmountId: string,
* priceId: string,
* priceListId: string
* ) {
* const pricingService = await initializePricingModule()
@@ -1761,7 +1759,7 @@ export interface IPricingModuleService extends IModuleService {
* price_set_id: priceSetId,
* rule_type_id: ruleTypeId,
* value,
* price_set_money_amount_id: priceSetMoneyAmountId,
* price_id: priceId,
* price_list_id: priceListId
* }
* ])
@@ -1874,7 +1872,7 @@ export interface IPricingModuleService extends IModuleService {
* const priceList = await pricingService.retrievePriceList(
* priceListId,
* {
* relations: ["price_set_money_amounts"]
* relations: ["prices"]
* }
* )
*
@@ -1935,7 +1933,7 @@ export interface IPricingModuleService extends IModuleService {
* id: priceListIds
* },
* {
* relations: ["price_set_money_amounts"]
* relations: ["prices"]
* }
* )
*
@@ -1958,7 +1956,7 @@ export interface IPricingModuleService extends IModuleService {
* id: priceListIds
* },
* {
* relations: ["price_set_money_amounts"],
* relations: ["prices"],
* skip,
* take
* }
@@ -1990,7 +1988,7 @@ export interface IPricingModuleService extends IModuleService {
* ]
* },
* {
* relations: ["price_set_money_amounts"],
* relations: ["prices"],
* skip,
* take
* }
@@ -2053,7 +2051,7 @@ export interface IPricingModuleService extends IModuleService {
* id: priceListIds
* },
* {
* relations: ["price_set_money_amounts"]
* relations: ["prices"]
* }
* )
*
@@ -2076,7 +2074,7 @@ export interface IPricingModuleService extends IModuleService {
* id: priceListIds
* },
* {
* relations: ["price_set_money_amounts"],
* relations: ["prices"],
* skip,
* take
* }
@@ -2108,7 +2106,7 @@ export interface IPricingModuleService extends IModuleService {
* ]
* },
* {
* relations: ["price_set_money_amounts"],
* relations: ["prices"],
* skip,
* take
* }

View File

@@ -1,14 +1,18 @@
import { isDefined } from "./is-defined"
export const removeNullish = (
obj: Record<string, unknown>
): Record<string, unknown> =>
Object.entries(obj).reduce((resultObject, [currentKey, currentValue]) => {
if (!isDefined(currentValue) || currentValue === null) {
export function removeNullish<T = unknown>(
obj: Record<string, T>
): Record<string, T> {
return Object.entries(obj).reduce(
(resultObject, [currentKey, currentValue]) => {
if (!isDefined(currentValue) || currentValue === null) {
return resultObject
}
resultObject[currentKey] = currentValue
return resultObject
}
resultObject[currentKey] = currentValue
return resultObject
}, {})
},
{}
)
}

View File

@@ -248,13 +248,11 @@ export type AbstractModuleService<
*
* const otherModels = new Set([
* Currency,
* MoneyAmount,
* Price,
* PriceList,
* PriceListRule,
* PriceListRuleValue,
* PriceRule,
* PriceSetMoneyAmount,
* PriceSetMoneyAmountRules,
* PriceSetRuleType,
* 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
* {
* Currency: { dto: PricingTypes.CurrencyDTO }
* MoneyAmount: { dto: PricingTypes.MoneyAmountDTO }
* PriceSetMoneyAmount: { dto: PricingTypes.PriceSetMoneyAmountDTO }
* PriceSetMoneyAmountRules: {
* dto: PricingTypes.PriceSetMoneyAmountRulesDTO
* }
* Price: { dto: PricingTypes.PriceDTO }
* PriceRule: { dto: PricingTypes.PriceRuleDTO }
* RuleType: { dto: PricingTypes.RuleTypeDTO }
* PriceList: { dto: PricingTypes.PriceListDTO }

View File

@@ -1,7 +1,7 @@
import {
PriceDTO,
PriceListRuleDTO,
PriceRuleDTO,
PriceSetMoneyAmountDTO,
ProductVariantDTO,
UpdatePriceListPriceDTO,
} from "@medusajs/types"
@@ -33,20 +33,20 @@ export function buildPriceSetRules(
}
export function buildPriceSetPricesForCore(
priceSetMoneyAmounts: (PriceSetMoneyAmountDTO & {
price_set: PriceSetMoneyAmountDTO["price_set"] & {
prices: (PriceDTO & {
price_set: PriceDTO["price_set"] & {
variant?: ProductVariantDTO
}
})[]
): Record<string, any>[] {
return priceSetMoneyAmounts.map((priceSetMoneyAmount) => {
const productVariant = (priceSetMoneyAmount.price_set as any).variant
const rules: Record<string, string> = priceSetMoneyAmount.price_rules
? buildPriceSetRules(priceSetMoneyAmount.price_rules)
return prices.map((price) => {
const productVariant = (price.price_set as any).variant
const rules: Record<string, string> = price.price_rules
? buildPriceSetRules(price.price_rules)
: {}
return {
...priceSetMoneyAmount,
...price,
variant_id: productVariant?.id ?? null,
rules,
}
@@ -54,16 +54,16 @@ export function buildPriceSetPricesForCore(
}
export function buildPriceSetPricesForModule(
priceSetMoneyAmounts: PriceSetMoneyAmountDTO[]
prices: PriceDTO[]
): UpdatePriceListPriceDTO[] {
return priceSetMoneyAmounts.map((priceSetMoneyAmount) => {
const rules: Record<string, string> = priceSetMoneyAmount.price_rules
? buildPriceSetRules(priceSetMoneyAmount.price_rules)
return prices.map((price) => {
const rules: Record<string, string> = price.price_rules
? buildPriceSetRules(price.price_rules)
: {}
return {
...priceSetMoneyAmount,
price_set_id: priceSetMoneyAmount.price_set!?.id!,
...price,
price_set_id: price.price_set!?.id!,
rules,
}
})