feat(pricing, types, utils): Soft delete pricing entities (#5858)

This commit is contained in:
Philip Korsholm authored and GitHub committed 2024-01-04 09:02:49 +01:00
1 parent 1468646b99
commit 3550750975
30 files changed
+795 -159

No files matched your search

+8
View File
@@ -0,0 +1,8 @@
---
"@medusajs/pricing": patch
"@medusajs/types": patch
"@medusajs/utils": patch
---
feat(pricing, types): add soft deletion for money-amounts
feat(utils): cascade soft delete across 1:1 relationships
@@ -6,6 +6,11 @@ import { initialize } from "../../../../src"
import { createCurrencies } from "../../../__fixtures__/currency" import { createCurrencies } from "../../../__fixtures__/currency"
import { createMoneyAmounts } from "../../../__fixtures__/money-amount" import { createMoneyAmounts } from "../../../__fixtures__/money-amount"
import { DB_URL, MikroOrmWrapper } from "../../../utils" import { DB_URL, MikroOrmWrapper } from "../../../utils"
import { createPriceSetMoneyAmounts } from "../../../__fixtures__/price-set-money-amount"
import { createPriceSets } from "../../../__fixtures__/price-set"
import { createRuleTypes } from "../../../__fixtures__/rule-type"
import { createPriceRules } from "../../../__fixtures__/price-rule"
import { createPriceSetMoneyAmountRules } from "../../../__fixtures__/price-set-money-amount-rules"
jest.setTimeout(30000) jest.setTimeout(30000)
@@ -264,6 +269,94 @@ describe("PricingModule Service - MoneyAmount", () => {
}) })
}) })
describe("softDeleteMoneyAmounts", () => {
const id = "money-amount-USD"
it("should softDelete priceSetMoneyAmount and PriceRule when soft-deleting money amount", async () => {
await createPriceSets(testManager)
await createRuleTypes(testManager)
await createPriceSetMoneyAmounts(testManager)
await createPriceRules(testManager)
await createPriceSetMoneyAmountRules(testManager)
await service.softDeleteMoneyAmounts([id])
const [moneyAmount] = await service.listMoneyAmounts(
{
id: [id],
},
{
relations: [
"price_set_money_amount",
"price_set_money_amount.price_rules",
],
withDeleted: true,
}
)
expect(moneyAmount).toBeTruthy()
const deletedAt = moneyAmount.deleted_at
expect(moneyAmount).toEqual(
expect.objectContaining({
deleted_at: deletedAt,
price_set_money_amount: expect.objectContaining({
deleted_at: deletedAt,
price_rules: [
expect.objectContaining({
deleted_at: deletedAt,
}),
],
}),
})
)
})
})
describe("restoreDeletedMoneyAmounts", () => {
const id = "money-amount-USD"
it("should restore softDeleted priceSetMoneyAmount and PriceRule when restoring soft-deleting money amount", async () => {
await createPriceSets(testManager)
await createRuleTypes(testManager)
await createPriceSetMoneyAmounts(testManager)
await createPriceRules(testManager)
await createPriceSetMoneyAmountRules(testManager)
await service.softDeleteMoneyAmounts([id])
await service.restoreDeletedMoneyAmounts([id])
const [moneyAmount] = await service.listMoneyAmounts(
{
id: [id],
},
{
relations: [
"price_set_money_amount",
"price_set_money_amount.price_rules",
],
}
)
expect(moneyAmount).toBeTruthy()
const deletedAt = null
expect(moneyAmount).toEqual(
expect.objectContaining({
deleted_at: deletedAt,
price_set_money_amount: expect.objectContaining({
deleted_at: deletedAt,
price_rules: [
expect.objectContaining({
deleted_at: deletedAt,
}),
],
}),
})
)
})
})
describe("updateMoneyAmounts", () => { describe("updateMoneyAmounts", () => {
const id = "money-amount-USD" const id = "money-amount-USD"
+1
View File
@@ -16,6 +16,7 @@ export const LinkableKeys = {
price_list_id: PriceList.name, price_list_id: PriceList.name,
price_set_money_amount_id: PriceSetMoneyAmount.name, price_set_money_amount_id: PriceSetMoneyAmount.name,
} }
const entityLinkableKeysMap: MapToConfig = {} const entityLinkableKeysMap: MapToConfig = {}
Object.entries(LinkableKeys).forEach(([key, value]) => { Object.entries(LinkableKeys).forEach(([key, value]) => {
entityLinkableKeysMap[value] ??= [] entityLinkableKeysMap[value] ??= []
@@ -1,5 +1,7 @@
{ {
"namespaces": ["public"], "namespaces": [
"public"
],
"name": "public", "name": "public",
"tables": [ "tables": [
{ {
@@ -46,7 +48,9 @@
"indexes": [ "indexes": [
{ {
"keyName": "currency_pkey", "keyName": "currency_pkey",
"columnNames": ["code"], "columnNames": [
"code"
],
"composite": false, "composite": false,
"primary": true, "primary": true,
"unique": true "unique": true
@@ -139,14 +143,18 @@
"schema": "public", "schema": "public",
"indexes": [ "indexes": [
{ {
"columnNames": ["currency_code"], "columnNames": [
"currency_code"
],
"composite": false, "composite": false,
"keyName": "IDX_money_amount_currency_code", "keyName": "IDX_money_amount_currency_code",
"primary": false, "primary": false,
"unique": false "unique": false
}, },
{ {
"columnNames": ["deleted_at"], "columnNames": [
"deleted_at"
],
"composite": false, "composite": false,
"keyName": "IDX_money_amount_deleted_at", "keyName": "IDX_money_amount_deleted_at",
"primary": false, "primary": false,
@@ -154,7 +162,9 @@
}, },
{ {
"keyName": "money_amount_pkey", "keyName": "money_amount_pkey",
"columnNames": ["id"], "columnNames": [
"id"
],
"composite": false, "composite": false,
"primary": true, "primary": true,
"unique": true "unique": true
@@ -164,9 +174,13 @@
"foreignKeys": { "foreignKeys": {
"money_amount_currency_code_foreign": { "money_amount_currency_code_foreign": {
"constraintName": "money_amount_currency_code_foreign", "constraintName": "money_amount_currency_code_foreign",
"columnNames": ["currency_code"], "columnNames": [
"currency_code"
],
"localTableName": "public.money_amount", "localTableName": "public.money_amount",
"referencedColumnNames": ["code"], "referencedColumnNames": [
"code"
],
"referencedTableName": "public.currency", "referencedTableName": "public.currency",
"deleteRule": "set null", "deleteRule": "set null",
"updateRule": "cascade" "updateRule": "cascade"
@@ -210,7 +224,10 @@
"primary": false, "primary": false,
"nullable": false, "nullable": false,
"default": "'draft'", "default": "'draft'",
"enumItems": ["active", "draft"], "enumItems": [
"active",
"draft"
],
"mappedType": "enum" "mappedType": "enum"
}, },
"type": { "type": {
@@ -221,7 +238,10 @@
"primary": false, "primary": false,
"nullable": false, "nullable": false,
"default": "'sale'", "default": "'sale'",
"enumItems": ["sale", "override"], "enumItems": [
"sale",
"override"
],
"mappedType": "enum" "mappedType": "enum"
}, },
"starts_at": { "starts_at": {
@@ -291,7 +311,9 @@
"schema": "public", "schema": "public",
"indexes": [ "indexes": [
{ {
"columnNames": ["deleted_at"], "columnNames": [
"deleted_at"
],
"composite": false, "composite": false,
"keyName": "IDX_price_list_deleted_at", "keyName": "IDX_price_list_deleted_at",
"primary": false, "primary": false,
@@ -299,7 +321,9 @@
}, },
{ {
"keyName": "price_list_pkey", "keyName": "price_list_pkey",
"columnNames": ["id"], "columnNames": [
"id"
],
"composite": false, "composite": false,
"primary": true, "primary": true,
"unique": true "unique": true
@@ -325,7 +349,9 @@
"indexes": [ "indexes": [
{ {
"keyName": "price_set_pkey", "keyName": "price_set_pkey",
"columnNames": ["id"], "columnNames": [
"id"
],
"composite": false, "composite": false,
"primary": true, "primary": true,
"unique": true "unique": true
@@ -390,42 +416,93 @@
"primary": false, "primary": false,
"nullable": true, "nullable": true,
"mappedType": "text" "mappedType": "text"
},
"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": "price_set_money_amount", "name": "price_set_money_amount",
"schema": "public", "schema": "public",
"indexes": [ "indexes": [
{ {
"columnNames": ["price_set_id"], "columnNames": [
"price_set_id"
],
"composite": false, "composite": false,
"keyName": "IDX_price_set_money_amount_price_set_id", "keyName": "IDX_price_set_money_amount_price_set_id",
"primary": false, "primary": false,
"unique": false "unique": false
}, },
{ {
"columnNames": ["money_amount_id"], "columnNames": [
"money_amount_id"
],
"composite": false, "composite": false,
"keyName": "IDX_price_set_money_amount_money_amount_id", "keyName": "IDX_price_set_money_amount_money_amount_id",
"primary": false, "primary": false,
"unique": false "unique": false
}, },
{ {
"columnNames": ["money_amount_id"], "columnNames": [
"money_amount_id"
],
"composite": false, "composite": false,
"keyName": "price_set_money_amount_money_amount_id_unique", "keyName": "price_set_money_amount_money_amount_id_unique",
"primary": false, "primary": false,
"unique": true "unique": true
}, },
{ {
"columnNames": ["price_list_id"], "columnNames": [
"price_list_id"
],
"composite": false, "composite": false,
"keyName": "IDX_price_rule_price_list_id", "keyName": "IDX_price_rule_price_list_id",
"primary": false, "primary": false,
"unique": false "unique": false
}, },
{
"columnNames": [
"deleted_at"
],
"composite": false,
"keyName": "IDX_price_set_money_amount_deleted_at",
"primary": false,
"unique": false
},
{ {
"keyName": "price_set_money_amount_pkey", "keyName": "price_set_money_amount_pkey",
"columnNames": ["id"], "columnNames": [
"id"
],
"composite": false, "composite": false,
"primary": true, "primary": true,
"unique": true "unique": true
@@ -435,30 +512,41 @@
"foreignKeys": { "foreignKeys": {
"price_set_money_amount_price_set_id_foreign": { "price_set_money_amount_price_set_id_foreign": {
"constraintName": "price_set_money_amount_price_set_id_foreign", "constraintName": "price_set_money_amount_price_set_id_foreign",
"columnNames": ["price_set_id"], "columnNames": [
"price_set_id"
],
"localTableName": "public.price_set_money_amount", "localTableName": "public.price_set_money_amount",
"referencedColumnNames": ["id"], "referencedColumnNames": [
"id"
],
"referencedTableName": "public.price_set", "referencedTableName": "public.price_set",
"deleteRule": "cascade", "deleteRule": "cascade",
"updateRule": "cascade" "updateRule": "cascade"
}, },
"price_set_money_amount_money_amount_id_foreign": { "price_set_money_amount_money_amount_id_foreign": {
"constraintName": "price_set_money_amount_money_amount_id_foreign", "constraintName": "price_set_money_amount_money_amount_id_foreign",
"columnNames": ["money_amount_id"], "columnNames": [
"money_amount_id"
],
"localTableName": "public.price_set_money_amount", "localTableName": "public.price_set_money_amount",
"referencedColumnNames": ["id"], "referencedColumnNames": [
"id"
],
"referencedTableName": "public.money_amount", "referencedTableName": "public.money_amount",
"deleteRule": "cascade", "deleteRule": "cascade",
"updateRule": "cascade" "updateRule": "cascade"
}, },
"price_set_money_amount_price_list_id_foreign": { "price_set_money_amount_price_list_id_foreign": {
"constraintName": "price_set_money_amount_price_list_id_foreign", "constraintName": "price_set_money_amount_price_list_id_foreign",
"columnNames": ["price_list_id"], "columnNames": [
"price_list_id"
],
"localTableName": "public.price_set_money_amount", "localTableName": "public.price_set_money_amount",
"referencedColumnNames": ["id"], "referencedColumnNames": [
"id"
],
"referencedTableName": "public.price_list", "referencedTableName": "public.price_list",
"deleteRule": "cascade", "deleteRule": "cascade"
"updateRule": "cascade"
} }
} }
}, },
@@ -506,7 +594,9 @@
"schema": "public", "schema": "public",
"indexes": [ "indexes": [
{ {
"columnNames": ["rule_attribute"], "columnNames": [
"rule_attribute"
],
"composite": false, "composite": false,
"keyName": "IDX_rule_type_rule_attribute", "keyName": "IDX_rule_type_rule_attribute",
"primary": false, "primary": false,
@@ -514,7 +604,9 @@
}, },
{ {
"keyName": "rule_type_pkey", "keyName": "rule_type_pkey",
"columnNames": ["id"], "columnNames": [
"id"
],
"composite": false, "composite": false,
"primary": true, "primary": true,
"unique": true "unique": true
@@ -557,14 +649,18 @@
"schema": "public", "schema": "public",
"indexes": [ "indexes": [
{ {
"columnNames": ["price_set_id"], "columnNames": [
"price_set_id"
],
"composite": false, "composite": false,
"keyName": "IDX_price_set_rule_type_price_set_id", "keyName": "IDX_price_set_rule_type_price_set_id",
"primary": false, "primary": false,
"unique": false "unique": false
}, },
{ {
"columnNames": ["rule_type_id"], "columnNames": [
"rule_type_id"
],
"composite": false, "composite": false,
"keyName": "IDX_price_set_rule_type_rule_type_id", "keyName": "IDX_price_set_rule_type_rule_type_id",
"primary": false, "primary": false,
@@ -572,7 +668,9 @@
}, },
{ {
"keyName": "price_set_rule_type_pkey", "keyName": "price_set_rule_type_pkey",
"columnNames": ["id"], "columnNames": [
"id"
],
"composite": false, "composite": false,
"primary": true, "primary": true,
"unique": true "unique": true
@@ -582,18 +680,26 @@
"foreignKeys": { "foreignKeys": {
"price_set_rule_type_price_set_id_foreign": { "price_set_rule_type_price_set_id_foreign": {
"constraintName": "price_set_rule_type_price_set_id_foreign", "constraintName": "price_set_rule_type_price_set_id_foreign",
"columnNames": ["price_set_id"], "columnNames": [
"price_set_id"
],
"localTableName": "public.price_set_rule_type", "localTableName": "public.price_set_rule_type",
"referencedColumnNames": ["id"], "referencedColumnNames": [
"id"
],
"referencedTableName": "public.price_set", "referencedTableName": "public.price_set",
"deleteRule": "cascade", "deleteRule": "cascade",
"updateRule": "cascade" "updateRule": "cascade"
}, },
"price_set_rule_type_rule_type_id_foreign": { "price_set_rule_type_rule_type_id_foreign": {
"constraintName": "price_set_rule_type_rule_type_id_foreign", "constraintName": "price_set_rule_type_rule_type_id_foreign",
"columnNames": ["rule_type_id"], "columnNames": [
"rule_type_id"
],
"localTableName": "public.price_set_rule_type", "localTableName": "public.price_set_rule_type",
"referencedColumnNames": ["id"], "referencedColumnNames": [
"id"
],
"referencedTableName": "public.rule_type", "referencedTableName": "public.rule_type",
"updateRule": "cascade" "updateRule": "cascade"
} }
@@ -642,14 +748,18 @@
"schema": "public", "schema": "public",
"indexes": [ "indexes": [
{ {
"columnNames": ["price_set_money_amount_id"], "columnNames": [
"price_set_money_amount_id"
],
"composite": false, "composite": false,
"keyName": "IDX_price_set_money_amount_rules_price_set_money_amount_id", "keyName": "IDX_price_set_money_amount_rules_price_set_money_amount_id",
"primary": false, "primary": false,
"unique": false "unique": false
}, },
{ {
"columnNames": ["rule_type_id"], "columnNames": [
"rule_type_id"
],
"composite": false, "composite": false,
"keyName": "IDX_price_set_money_amount_rules_rule_type_id", "keyName": "IDX_price_set_money_amount_rules_rule_type_id",
"primary": false, "primary": false,
@@ -657,7 +767,9 @@
}, },
{ {
"keyName": "price_set_money_amount_rules_pkey", "keyName": "price_set_money_amount_rules_pkey",
"columnNames": ["id"], "columnNames": [
"id"
],
"composite": false, "composite": false,
"primary": true, "primary": true,
"unique": true "unique": true
@@ -667,18 +779,26 @@
"foreignKeys": { "foreignKeys": {
"price_set_money_amount_rules_price_set_money_amount_id_foreign": { "price_set_money_amount_rules_price_set_money_amount_id_foreign": {
"constraintName": "price_set_money_amount_rules_price_set_money_amount_id_foreign", "constraintName": "price_set_money_amount_rules_price_set_money_amount_id_foreign",
"columnNames": ["price_set_money_amount_id"], "columnNames": [
"price_set_money_amount_id"
],
"localTableName": "public.price_set_money_amount_rules", "localTableName": "public.price_set_money_amount_rules",
"referencedColumnNames": ["id"], "referencedColumnNames": [
"id"
],
"referencedTableName": "public.price_set_money_amount", "referencedTableName": "public.price_set_money_amount",
"deleteRule": "cascade", "deleteRule": "cascade",
"updateRule": "cascade" "updateRule": "cascade"
}, },
"price_set_money_amount_rules_rule_type_id_foreign": { "price_set_money_amount_rules_rule_type_id_foreign": {
"constraintName": "price_set_money_amount_rules_rule_type_id_foreign", "constraintName": "price_set_money_amount_rules_rule_type_id_foreign",
"columnNames": ["rule_type_id"], "columnNames": [
"rule_type_id"
],
"localTableName": "public.price_set_money_amount_rules", "localTableName": "public.price_set_money_amount_rules",
"referencedColumnNames": ["id"], "referencedColumnNames": [
"id"
],
"referencedTableName": "public.rule_type", "referencedTableName": "public.rule_type",
"updateRule": "cascade" "updateRule": "cascade"
} }
@@ -713,16 +833,6 @@
"nullable": false, "nullable": false,
"mappedType": "text" "mappedType": "text"
}, },
"is_dynamic": {
"name": "is_dynamic",
"type": "boolean",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"default": "false",
"mappedType": "boolean"
},
"value": { "value": {
"name": "value", "name": "value",
"type": "text", "type": "text",
@@ -750,35 +860,84 @@
"primary": false, "primary": false,
"nullable": false, "nullable": false,
"mappedType": "text" "mappedType": "text"
},
"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": "price_rule", "name": "price_rule",
"schema": "public", "schema": "public",
"indexes": [ "indexes": [
{ {
"columnNames": ["price_set_id"], "columnNames": [
"price_set_id"
],
"composite": false, "composite": false,
"keyName": "IDX_price_rule_price_set_id", "keyName": "IDX_price_rule_price_set_id",
"primary": false, "primary": false,
"unique": false "unique": false
}, },
{ {
"columnNames": ["rule_type_id"], "columnNames": [
"rule_type_id"
],
"composite": false, "composite": false,
"keyName": "IDX_price_rule_rule_type_id", "keyName": "IDX_price_rule_rule_type_id",
"primary": false, "primary": false,
"unique": false "unique": false
}, },
{ {
"columnNames": ["price_set_money_amount_id"], "columnNames": [
"price_set_money_amount_id"
],
"composite": false, "composite": false,
"keyName": "IDX_price_rule_price_set_money_amount_id", "keyName": "IDX_price_rule_price_set_money_amount_id",
"primary": false, "primary": false,
"unique": false "unique": false
}, },
{
"columnNames": [
"deleted_at"
],
"composite": false,
"keyName": "IDX_price_rule_deleted_at",
"primary": false,
"unique": false
},
{ {
"keyName": "price_rule_pkey", "keyName": "price_rule_pkey",
"columnNames": ["id"], "columnNames": [
"id"
],
"composite": false, "composite": false,
"primary": true, "primary": true,
"unique": true "unique": true
@@ -788,26 +947,38 @@
"foreignKeys": { "foreignKeys": {
"price_rule_price_set_id_foreign": { "price_rule_price_set_id_foreign": {
"constraintName": "price_rule_price_set_id_foreign", "constraintName": "price_rule_price_set_id_foreign",
"columnNames": ["price_set_id"], "columnNames": [
"price_set_id"
],
"localTableName": "public.price_rule", "localTableName": "public.price_rule",
"referencedColumnNames": ["id"], "referencedColumnNames": [
"id"
],
"referencedTableName": "public.price_set", "referencedTableName": "public.price_set",
"deleteRule": "cascade", "deleteRule": "cascade",
"updateRule": "cascade" "updateRule": "cascade"
}, },
"price_rule_rule_type_id_foreign": { "price_rule_rule_type_id_foreign": {
"constraintName": "price_rule_rule_type_id_foreign", "constraintName": "price_rule_rule_type_id_foreign",
"columnNames": ["rule_type_id"], "columnNames": [
"rule_type_id"
],
"localTableName": "public.price_rule", "localTableName": "public.price_rule",
"referencedColumnNames": ["id"], "referencedColumnNames": [
"id"
],
"referencedTableName": "public.rule_type", "referencedTableName": "public.rule_type",
"updateRule": "cascade" "updateRule": "cascade"
}, },
"price_rule_price_set_money_amount_id_foreign": { "price_rule_price_set_money_amount_id_foreign": {
"constraintName": "price_rule_price_set_money_amount_id_foreign", "constraintName": "price_rule_price_set_money_amount_id_foreign",
"columnNames": ["price_set_money_amount_id"], "columnNames": [
"price_set_money_amount_id"
],
"localTableName": "public.price_rule", "localTableName": "public.price_rule",
"referencedColumnNames": ["id"], "referencedColumnNames": [
"id"
],
"referencedTableName": "public.price_set_money_amount", "referencedTableName": "public.price_set_money_amount",
"deleteRule": "cascade", "deleteRule": "cascade",
"updateRule": "cascade" "updateRule": "cascade"
@@ -825,8 +996,8 @@
"nullable": false, "nullable": false,
"mappedType": "text" "mappedType": "text"
}, },
"rule_type_id": { "price_list_id": {
"name": "rule_type_id", "name": "price_list_id",
"type": "text", "type": "text",
"unsigned": false, "unsigned": false,
"autoincrement": false, "autoincrement": false,
@@ -834,8 +1005,8 @@
"nullable": false, "nullable": false,
"mappedType": "text" "mappedType": "text"
}, },
"price_list_id": { "rule_type_id": {
"name": "price_list_id", "name": "rule_type_id",
"type": "text", "type": "text",
"unsigned": false, "unsigned": false,
"autoincrement": false, "autoincrement": false,
@@ -848,29 +1019,38 @@
"schema": "public", "schema": "public",
"indexes": [ "indexes": [
{ {
"columnNames": ["rule_type_id"], "columnNames": [
"composite": false, "price_list_id"
"keyName": "IDX_price_list_rule_rule_type_id", ],
"primary": false,
"unique": false
},
{
"columnNames": ["price_list_id"],
"composite": false, "composite": false,
"keyName": "IDX_price_list_rule_price_list_id", "keyName": "IDX_price_list_rule_price_list_id",
"primary": false, "primary": false,
"unique": false "unique": false
}, },
{
"columnNames": [
"rule_type_id"
],
"composite": false,
"keyName": "IDX_price_list_rule_rule_type_id",
"primary": false,
"unique": false
},
{ {
"keyName": "IDX_price_list_rule_rule_type_id_price_list_id_unique", "keyName": "IDX_price_list_rule_rule_type_id_price_list_id_unique",
"columnNames": ["price_list_id", "rule_type_id"], "columnNames": [
"price_list_id",
"rule_type_id"
],
"composite": true, "composite": true,
"primary": false, "primary": false,
"unique": true "unique": true
}, },
{ {
"keyName": "price_list_rule_pkey", "keyName": "price_list_rule_pkey",
"columnNames": ["id"], "columnNames": [
"id"
],
"composite": false, "composite": false,
"primary": true, "primary": true,
"unique": true "unique": true
@@ -878,21 +1058,29 @@
], ],
"checks": [], "checks": [],
"foreignKeys": { "foreignKeys": {
"price_list_rule_rule_type_id_foreign": {
"constraintName": "price_list_rule_rule_type_id_foreign",
"columnNames": ["rule_type_id"],
"localTableName": "public.price_list_rule",
"referencedColumnNames": ["id"],
"referencedTableName": "public.rule_type",
"updateRule": "cascade"
},
"price_list_rule_price_list_id_foreign": { "price_list_rule_price_list_id_foreign": {
"constraintName": "price_list_rule_price_list_id_foreign", "constraintName": "price_list_rule_price_list_id_foreign",
"columnNames": ["price_list_id"], "columnNames": [
"price_list_id"
],
"localTableName": "public.price_list_rule", "localTableName": "public.price_list_rule",
"referencedColumnNames": ["id"], "referencedColumnNames": [
"id"
],
"referencedTableName": "public.price_list", "referencedTableName": "public.price_list",
"updateRule": "cascade" "updateRule": "cascade"
},
"price_list_rule_rule_type_id_foreign": {
"constraintName": "price_list_rule_rule_type_id_foreign",
"columnNames": [
"rule_type_id"
],
"localTableName": "public.price_list_rule",
"referencedColumnNames": [
"id"
],
"referencedTableName": "public.rule_type",
"updateRule": "cascade"
} }
} }
}, },
@@ -930,7 +1118,9 @@
"schema": "public", "schema": "public",
"indexes": [ "indexes": [
{ {
"columnNames": ["price_list_rule_id"], "columnNames": [
"price_list_rule_id"
],
"composite": false, "composite": false,
"keyName": "IDX_price_list_rule_price_list_rule_value_id", "keyName": "IDX_price_list_rule_price_list_rule_value_id",
"primary": false, "primary": false,
@@ -938,7 +1128,9 @@
}, },
{ {
"keyName": "price_list_rule_value_pkey", "keyName": "price_list_rule_value_pkey",
"columnNames": ["id"], "columnNames": [
"id"
],
"composite": false, "composite": false,
"primary": true, "primary": true,
"unique": true "unique": true
@@ -948,9 +1140,13 @@
"foreignKeys": { "foreignKeys": {
"price_list_rule_value_price_list_rule_id_foreign": { "price_list_rule_value_price_list_rule_id_foreign": {
"constraintName": "price_list_rule_value_price_list_rule_id_foreign", "constraintName": "price_list_rule_value_price_list_rule_id_foreign",
"columnNames": ["price_list_rule_id"], "columnNames": [
"price_list_rule_id"
],
"localTableName": "public.price_list_rule_value", "localTableName": "public.price_list_rule_value",
"referencedColumnNames": ["id"], "referencedColumnNames": [
"id"
],
"referencedTableName": "public.price_list_rule", "referencedTableName": "public.price_list_rule",
"deleteRule": "cascade", "deleteRule": "cascade",
"updateRule": "cascade" "updateRule": "cascade"
@@ -0,0 +1,55 @@
import { Migration } from "@mikro-orm/migrations"
export class Migration20240103140327 extends Migration {
async up(): Promise<void> {
this.addSql(
'alter table "price_set_money_amount" drop constraint "price_set_money_amount_price_list_id_foreign";'
)
this.addSql(
'alter table "price_set_money_amount" add column "created_at" timestamptz not null default now(), add column "updated_at" timestamptz not null default now(), add column "deleted_at" timestamptz null;'
)
this.addSql(
'alter table "price_set_money_amount" add constraint "price_set_money_amount_price_list_id_foreign" foreign key ("price_list_id") references "price_list" ("id") on delete cascade;'
)
this.addSql(
'create index "IDX_price_set_money_amount_deleted_at" on "price_set_money_amount" ("deleted_at");'
)
this.addSql(
'alter table "price_rule" add column "created_at" timestamptz not null default now(), add column "updated_at" timestamptz not null default now(), add column "deleted_at" timestamptz null;'
)
this.addSql('alter table "price_rule" drop column "is_dynamic";')
this.addSql(
'create index "IDX_price_rule_deleted_at" on "price_rule" ("deleted_at");'
)
}
async down(): Promise<void> {
this.addSql(
'alter table "price_set_money_amount" drop constraint "price_set_money_amount_price_list_id_foreign";'
)
this.addSql('drop index "IDX_price_set_money_amount_deleted_at";')
this.addSql(
'alter table "price_set_money_amount" drop column "created_at";'
)
this.addSql(
'alter table "price_set_money_amount" drop column "updated_at";'
)
this.addSql(
'alter table "price_set_money_amount" drop column "deleted_at";'
)
this.addSql(
'alter table "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;'
)
this.addSql(
'alter table "price_rule" add column "is_dynamic" boolean not null default false;'
)
this.addSql('drop index "IDX_price_rule_deleted_at";')
this.addSql('alter table "price_rule" drop column "created_at";')
this.addSql('alter table "price_rule" drop column "updated_at";')
this.addSql('alter table "price_rule" drop column "deleted_at";')
}
}
+22 -8
View File
@@ -1,12 +1,14 @@
import { generateEntityId } from "@medusajs/utils" import { DALUtils, generateEntityId } from "@medusajs/utils"
import { import {
BeforeCreate, BeforeCreate,
Collection, Collection,
Entity, Entity,
Filter,
Index, Index,
ManyToMany, ManyToMany,
ManyToOne, ManyToOne,
OneToOne, OneToOne,
OnInit,
OptionalProps, OptionalProps,
PrimaryKey, PrimaryKey,
Property, Property,
@@ -17,18 +19,20 @@ import { PriceSetMoneyAmount } from "./index"
import PriceSet from "./price-set" import PriceSet from "./price-set"
@Entity() @Entity()
@Filter(DALUtils.mikroOrmSoftDeletableFilterOptions)
class MoneyAmount { class MoneyAmount {
[OptionalProps]?: [OptionalProps]?:
| "created_at" | "created_at"
| "updated_at" | "updated_at"
| "deleted_at" | "deleted_at"
| "price_set_money_amount" | "price_set_money_amount"
| "amount"
@PrimaryKey({ columnType: "text" }) @PrimaryKey({ columnType: "text" })
id!: string id!: string
@Property({ columnType: "text", nullable: true }) @Property({ columnType: "text", nullable: true })
currency_code?: string currency_code: string | null
@ManyToMany({ @ManyToMany({
entity: () => PriceSet, entity: () => PriceSet,
@@ -39,6 +43,7 @@ class MoneyAmount {
@OneToOne({ @OneToOne({
entity: () => PriceSetMoneyAmount, entity: () => PriceSetMoneyAmount,
mappedBy: (psma) => psma.money_amount, mappedBy: (psma) => psma.money_amount,
cascade: ["soft-remove"] as any,
}) })
price_set_money_amount: PriceSetMoneyAmount price_set_money_amount: PriceSetMoneyAmount
@@ -47,16 +52,20 @@ class MoneyAmount {
index: "IDX_money_amount_currency_code", index: "IDX_money_amount_currency_code",
fieldName: "currency_code", fieldName: "currency_code",
}) })
currency?: Currency currency: Currency
@Property({ columnType: "numeric", nullable: true, serializer: Number }) @Property({
amount?: number columnType: "numeric",
nullable: true,
serializer: Number,
})
amount: number | null
@Property({ columnType: "numeric", nullable: true }) @Property({ columnType: "numeric", nullable: true })
min_quantity?: number | null min_quantity: number | null
@Property({ columnType: "numeric", nullable: true }) @Property({ columnType: "numeric", nullable: true })
max_quantity?: number | null max_quantity: number | null
@Property({ @Property({
onCreate: () => new Date(), onCreate: () => new Date(),
@@ -75,12 +84,17 @@ class MoneyAmount {
@Index({ name: "IDX_money_amount_deleted_at" }) @Index({ name: "IDX_money_amount_deleted_at" })
@Property({ columnType: "timestamptz", nullable: true }) @Property({ columnType: "timestamptz", nullable: true })
deleted_at: Date deleted_at: Date | null
@BeforeCreate() @BeforeCreate()
onCreate() { onCreate() {
this.id = generateEntityId(this.id, "ma") this.id = generateEntityId(this.id, "ma")
} }
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "ma")
}
} }
export default MoneyAmount export default MoneyAmount
@@ -2,6 +2,7 @@ import {
BeforeCreate, BeforeCreate,
Entity, Entity,
ManyToOne, ManyToOne,
OnInit,
PrimaryKey, PrimaryKey,
Property, Property,
} from "@mikro-orm/core" } from "@mikro-orm/core"
@@ -16,7 +17,7 @@ export default class PriceListRuleValue {
@ManyToOne(() => PriceListRule, { @ManyToOne(() => PriceListRule, {
onDelete: "cascade", onDelete: "cascade",
fieldName: 'price_list_rule_id', fieldName: "price_list_rule_id",
index: "IDX_price_list_rule_price_list_rule_value_id", index: "IDX_price_list_rule_price_list_rule_value_id",
}) })
price_list_rule: PriceListRule price_list_rule: PriceListRule
@@ -28,4 +29,9 @@ export default class PriceListRuleValue {
onCreate() { onCreate() {
this.id = generateEntityId(this.id, "plrv") this.id = generateEntityId(this.id, "plrv")
} }
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "plrv")
}
} }
@@ -5,6 +5,7 @@ import {
Entity, Entity,
ManyToOne, ManyToOne,
OneToMany, OneToMany,
OnInit,
OptionalProps, OptionalProps,
PrimaryKey, PrimaryKey,
Unique, Unique,
@@ -54,4 +55,9 @@ export default class PriceListRule {
beforeCreate() { beforeCreate() {
this.id = generateEntityId(this.id, "plrule") this.id = generateEntityId(this.id, "plrule")
} }
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "plrule")
}
} }
+18 -10
View File
@@ -1,4 +1,8 @@
import { generateEntityId } from "@medusajs/utils" import {
generateEntityId,
PriceListStatus,
PriceListType,
} from "@medusajs/utils"
import { import {
BeforeCreate, BeforeCreate,
Cascade, Cascade,
@@ -8,12 +12,11 @@ import {
Index, Index,
ManyToMany, ManyToMany,
OneToMany, OneToMany,
OnInit,
OptionalProps, OptionalProps,
PrimaryKey, PrimaryKey,
Property, Property,
} from "@mikro-orm/core" } from "@mikro-orm/core"
import { PriceListStatus, PriceListType } from "@medusajs/utils"
import PriceListRule from "./price-list-rule" import PriceListRule from "./price-list-rule"
import PriceSetMoneyAmount from "./price-set-money-amount" import PriceSetMoneyAmount from "./price-set-money-amount"
import RuleType from "./rule-type" import RuleType from "./rule-type"
@@ -47,22 +50,22 @@ export default class PriceList {
description: string description: string
@Enum({ items: () => PriceListStatus, default: PriceListStatus.DRAFT }) @Enum({ items: () => PriceListStatus, default: PriceListStatus.DRAFT })
status?: PriceListStatus status: PriceListStatus
@Enum({ items: () => PriceListType, default: PriceListType.SALE }) @Enum({ items: () => PriceListType, default: PriceListType.SALE })
type?: PriceListType type: PriceListType
@Property({ @Property({
columnType: "timestamptz", columnType: "timestamptz",
nullable: true, nullable: true,
}) })
starts_at?: Date | null starts_at: Date | null
@Property({ @Property({
columnType: "timestamptz", columnType: "timestamptz",
nullable: true, nullable: true,
}) })
ends_at?: Date | null ends_at: Date | null
@OneToMany(() => PriceSetMoneyAmount, (psma) => psma.price_list, { @OneToMany(() => PriceSetMoneyAmount, (psma) => psma.price_list, {
cascade: [Cascade.REMOVE], cascade: [Cascade.REMOVE],
@@ -89,7 +92,7 @@ export default class PriceList {
columnType: "timestamptz", columnType: "timestamptz",
defaultRaw: "now()", defaultRaw: "now()",
}) })
created_at?: Date created_at: Date
@Property({ @Property({
onCreate: () => new Date(), onCreate: () => new Date(),
@@ -97,14 +100,19 @@ export default class PriceList {
columnType: "timestamptz", columnType: "timestamptz",
defaultRaw: "now()", defaultRaw: "now()",
}) })
updated_at?: Date updated_at: Date
@Index({ name: "IDX_price_list_deleted_at" }) @Index({ name: "IDX_price_list_deleted_at" })
@Property({ columnType: "timestamptz", nullable: true }) @Property({ columnType: "timestamptz", nullable: true })
deleted_at?: Date deleted_at: Date | null
@BeforeCreate() @BeforeCreate()
onCreate() { onCreate() {
this.id = generateEntityId(this.id, "plist") this.id = generateEntityId(this.id, "plist")
} }
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "plist")
}
} }
+36 -2
View File
@@ -1,21 +1,31 @@
import { import {
BeforeCreate, BeforeCreate,
Entity, Entity,
Filter,
Index,
ManyToOne, ManyToOne,
OnInit,
OptionalProps, OptionalProps,
PrimaryKey, PrimaryKey,
Property, Property,
} from "@mikro-orm/core" } from "@mikro-orm/core"
import { DALUtils, generateEntityId } from "@medusajs/utils"
import { generateEntityId } from "@medusajs/utils"
import PriceSet from "./price-set" import PriceSet from "./price-set"
import PriceSetMoneyAmount from "./price-set-money-amount" import PriceSetMoneyAmount from "./price-set-money-amount"
import RuleType from "./rule-type" import RuleType from "./rule-type"
type OptionalFields = "id" | "is_dynamic" | "priority" type OptionalFields =
| "id"
| "is_dynamic"
| "priority"
| "created_at"
| "updated_at"
| "deleted_at"
type OptionalRelations = "price_set" | "rule_type" | "price_set_money_amount" type OptionalRelations = "price_set" | "rule_type" | "price_set_money_amount"
@Entity() @Entity()
@Filter(DALUtils.mikroOrmSoftDeletableFilterOptions)
export default class PriceRule { export default class PriceRule {
[OptionalProps]: OptionalFields | OptionalRelations [OptionalProps]: OptionalFields | OptionalRelations
@@ -54,8 +64,32 @@ export default class PriceRule {
}) })
price_set_money_amount: PriceSetMoneyAmount price_set_money_amount: PriceSetMoneyAmount
@Property({
onCreate: () => new Date(),
columnType: "timestamptz",
defaultRaw: "now()",
})
created_at: Date
@Property({
onCreate: () => new Date(),
onUpdate: () => new Date(),
columnType: "timestamptz",
defaultRaw: "now()",
})
updated_at: Date
@Index({ name: "IDX_price_rule_deleted_at" })
@Property({ columnType: "timestamptz", nullable: true })
deleted_at: Date | null
@BeforeCreate() @BeforeCreate()
beforeCreate() { beforeCreate() {
this.id = generateEntityId(this.id, "prule") this.id = generateEntityId(this.id, "prule")
} }
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "prule")
}
} }
@@ -3,6 +3,7 @@ import {
BeforeCreate, BeforeCreate,
Entity, Entity,
ManyToOne, ManyToOne,
OnInit,
PrimaryKey, PrimaryKey,
Property, Property,
} from "@mikro-orm/core" } from "@mikro-orm/core"
@@ -19,12 +20,12 @@ export default class PriceSetMoneyAmountRules {
onDelete: "cascade", onDelete: "cascade",
index: "IDX_price_set_money_amount_rules_price_set_money_amount_id", index: "IDX_price_set_money_amount_rules_price_set_money_amount_id",
}) })
price_set_money_amount?: PriceSetMoneyAmount | string price_set_money_amount: PriceSetMoneyAmount
@ManyToOne(() => RuleType, { @ManyToOne(() => RuleType, {
index: "IDX_price_set_money_amount_rules_rule_type_id", index: "IDX_price_set_money_amount_rules_rule_type_id",
}) })
rule_type?: RuleType | string rule_type: RuleType
@Property({ columnType: "text" }) @Property({ columnType: "text" })
value: string value: string
@@ -33,4 +34,9 @@ export default class PriceSetMoneyAmountRules {
onCreate() { onCreate() {
this.id = generateEntityId(this.id, "psmar") this.id = generateEntityId(this.id, "psmar")
} }
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "psmar")
}
} }
@@ -1,15 +1,20 @@
import { generateEntityId } from "@medusajs/utils"
import { import {
BeforeCreate, BeforeCreate,
Cascade,
Collection, Collection,
Entity, Entity,
Filter,
Index,
ManyToOne, ManyToOne,
OnInit,
OneToMany, OneToMany,
OneToOne, OneToOne,
OptionalProps,
PrimaryKey, PrimaryKey,
PrimaryKeyType, PrimaryKeyType,
Property, Property,
} from "@mikro-orm/core" } from "@mikro-orm/core"
import { DALUtils, generateEntityId } from "@medusajs/utils"
import MoneyAmount from "./money-amount" import MoneyAmount from "./money-amount"
import PriceList from "./price-list" import PriceList from "./price-list"
@@ -18,7 +23,10 @@ import PriceSet from "./price-set"
import PriceSetMoneyAmountRules from "./price-set-money-amount-rules" import PriceSetMoneyAmountRules from "./price-set-money-amount-rules"
@Entity() @Entity()
@Filter(DALUtils.mikroOrmSoftDeletableFilterOptions)
export default class PriceSetMoneyAmount { export default class PriceSetMoneyAmount {
[OptionalProps]?: "created_at" | "updated_at" | "deleted_at"
@PrimaryKey({ columnType: "text" }) @PrimaryKey({ columnType: "text" })
id!: string id!: string
@@ -29,20 +37,21 @@ export default class PriceSetMoneyAmount {
onDelete: "cascade", onDelete: "cascade",
index: "IDX_price_set_money_amount_price_set_id", index: "IDX_price_set_money_amount_price_set_id",
}) })
price_set?: PriceSet price_set: PriceSet
@OneToOne(() => MoneyAmount, { @OneToOne(() => MoneyAmount, {
onDelete: "cascade", onDelete: "cascade",
index: "IDX_price_set_money_amount_money_amount_id", index: "IDX_price_set_money_amount_money_amount_id",
}) })
money_amount?: MoneyAmount money_amount: MoneyAmount
@Property({ columnType: "integer", default: 0 }) @Property({ columnType: "integer", default: 0 })
rules_count?: number rules_count: number
@OneToMany({ @OneToMany({
entity: () => PriceRule, entity: () => PriceRule,
mappedBy: (pr) => pr.price_set_money_amount, mappedBy: (pr) => pr.price_set_money_amount,
cascade: ["soft-remove"] as any,
}) })
price_rules = new Collection<PriceRule>(this) price_rules = new Collection<PriceRule>(this)
@@ -55,15 +64,39 @@ export default class PriceSetMoneyAmount {
@ManyToOne(() => PriceList, { @ManyToOne(() => PriceList, {
index: "IDX_price_rule_price_list_id", index: "IDX_price_rule_price_list_id",
onDelete: "cascade", onDelete: "cascade",
cascade: [Cascade.REMOVE, "soft-remove"] as any,
nullable: true, nullable: true,
}) })
price_list?: PriceList price_list: PriceList | null
@Property({
onCreate: () => new Date(),
columnType: "timestamptz",
defaultRaw: "now()",
})
created_at: Date
@Property({
onCreate: () => new Date(),
onUpdate: () => new Date(),
columnType: "timestamptz",
defaultRaw: "now()",
})
updated_at: Date
@Property({ columnType: "timestamptz", nullable: true , index: "IDX_price_set_money_amount_deleted_at"})
deleted_at: Date | null
@BeforeCreate() @BeforeCreate()
onCreate() { onCreate() {
this.id = generateEntityId(this.id, "psma") this.id = generateEntityId(this.id, "psma")
} }
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "psma")
}
[PrimaryKeyType]?: [string, string] [PrimaryKeyType]?: [string, string]
constructor(money_amount: MoneyAmount, price_set: PriceSet) { constructor(money_amount: MoneyAmount, price_set: PriceSet) {
@@ -2,8 +2,8 @@ import {
BeforeCreate, BeforeCreate,
Entity, Entity,
ManyToOne, ManyToOne,
OnInit,
PrimaryKey, PrimaryKey,
PrimaryKeyType,
} from "@mikro-orm/core" } from "@mikro-orm/core"
import PriceSet from "./price-set" import PriceSet from "./price-set"
@@ -30,4 +30,9 @@ export default class PriceSetRuleType {
onCreate() { onCreate() {
this.id = generateEntityId(this.id, "psrt") this.id = generateEntityId(this.id, "psrt")
} }
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "psrt")
}
} }
+6
View File
@@ -6,6 +6,7 @@ import {
Entity, Entity,
ManyToMany, ManyToMany,
OneToMany, OneToMany,
OnInit,
OptionalProps, OptionalProps,
PrimaryKey, PrimaryKey,
} from "@mikro-orm/core" } from "@mikro-orm/core"
@@ -50,4 +51,9 @@ export default class PriceSet {
onCreate() { onCreate() {
this.id = generateEntityId(this.id, "pset") this.id = generateEntityId(this.id, "pset")
} }
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "pset")
}
} }
+8 -2
View File
@@ -4,6 +4,7 @@ import {
Collection, Collection,
Entity, Entity,
ManyToMany, ManyToMany,
OnInit,
OptionalProps, OptionalProps,
PrimaryKey, PrimaryKey,
Property, Property,
@@ -28,13 +29,18 @@ class RuleType {
@Property({ columnType: "integer", default: 0 }) @Property({ columnType: "integer", default: 0 })
default_priority: number default_priority: number
@ManyToMany(() => PriceSet, priceSet => priceSet.rule_types) @ManyToMany(() => PriceSet, (priceSet) => priceSet.rule_types)
price_sets = new Collection<PriceSet>(this); price_sets = new Collection<PriceSet>(this)
@BeforeCreate() @BeforeCreate()
onCreate() { onCreate() {
this.id = generateEntityId(this.id, "rul-typ") this.id = generateEntityId(this.id, "rul-typ")
} }
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "rul-typ")
}
} }
export default RuleType export default RuleType
@@ -1,9 +1,9 @@
import { Context, DAL } from "@medusajs/types" import { Context, DAL } from "@medusajs/types"
import { DALUtils, MedusaError } from "@medusajs/utils" import { DALUtils, MedusaError } from "@medusajs/utils"
import { import {
LoadStrategy,
FilterQuery as MikroFilterQuery, FilterQuery as MikroFilterQuery,
FindOptions as MikroOptions, FindOptions as MikroOptions,
LoadStrategy,
} from "@mikro-orm/core" } from "@mikro-orm/core"
import { MoneyAmount } from "@models" import { MoneyAmount } from "@models"
@@ -72,7 +72,7 @@ export class MoneyAmountRepository extends DALUtils.MikroOrmBaseRepository {
const manager = this.getActiveManager<SqlEntityManager>(context) const manager = this.getActiveManager<SqlEntityManager>(context)
const moneyAmounts = data.map((moneyAmountData) => { const moneyAmounts = data.map((moneyAmountData) => {
return manager.create(MoneyAmount, moneyAmountData) return manager.create(MoneyAmount, moneyAmountData as any)
}) })
manager.persist(moneyAmounts) manager.persist(moneyAmounts)
@@ -1,9 +1,9 @@
import { Context, DAL } from "@medusajs/types" import { Context, DAL } from "@medusajs/types"
import { DALUtils, MedusaError } from "@medusajs/utils" import { DALUtils, MedusaError } from "@medusajs/utils"
import { import {
LoadStrategy,
FilterQuery as MikroFilterQuery, FilterQuery as MikroFilterQuery,
FindOptions as MikroOptions, FindOptions as MikroOptions,
LoadStrategy,
} from "@mikro-orm/core" } from "@mikro-orm/core"
import { PriceSetMoneyAmountRules } from "@models" import { PriceSetMoneyAmountRules } from "@models"
@@ -72,7 +72,7 @@ export class PriceSetMoneyAmountRulesRepository extends DALUtils.MikroOrmBaseRep
const manager = this.getActiveManager<SqlEntityManager>(context) const manager = this.getActiveManager<SqlEntityManager>(context)
const psmar = data.map((psmarData) => { const psmar = data.map((psmarData) => {
return manager.create(PriceSetMoneyAmountRules, psmarData) return manager.create(PriceSetMoneyAmountRules, psmarData as any)
}) })
manager.persist(psmar) manager.persist(psmar)
@@ -114,7 +114,7 @@ export class PriceSetMoneyAmountRulesRepository extends DALUtils.MikroOrmBaseRep
) )
} }
return manager.assign(existingRecord, psmarData) return manager.assign(existingRecord, psmarData as any)
}) })
manager.persist(psmar) manager.persist(psmar)
+9 -9
View File
@@ -1,7 +1,7 @@
import { LoaderOptions, Logger, ModulesSdkTypes } from "@medusajs/types" import { LoaderOptions, Logger, ModulesSdkTypes } from "@medusajs/types"
import { DALUtils, ModulesSdkUtils } from "@medusajs/utils" import { DALUtils, ModulesSdkUtils } from "@medusajs/utils"
import { EntitySchema, RequiredEntityData } from "@mikro-orm/core" import { EntitySchema, RequiredEntityData } from "@mikro-orm/core"
import { SqlEntityManager } from "@mikro-orm/postgresql" import { PostgreSqlDriver, SqlEntityManager } from "@mikro-orm/postgresql"
import * as PricingModels from "@models" import * as PricingModels from "@models"
import { EOL } from "os" import { EOL } from "os"
import { resolve } from "path" import { resolve } from "path"
@@ -49,10 +49,10 @@ export async function run({
try { try {
logger.info("Inserting price_sets, currencies & money_amounts") logger.info("Inserting price_sets, currencies & money_amounts")
await createCurrencies(manager, currenciesData) await createCurrencies(manager as any, currenciesData)
await createMoneyAmounts(manager, moneyAmountsData) await createMoneyAmounts(manager as any, moneyAmountsData)
await createPriceSets(manager, priceSetsData) await createPriceSets(manager as any, priceSetsData)
await createPriceSetMoneyAmounts(manager, priceSetMoneyAmountsData) await createPriceSetMoneyAmounts(manager as any, priceSetMoneyAmountsData)
} catch (e) { } catch (e) {
logger.error( logger.error(
`Failed to insert the seed data in the PostgreSQL database ${dbData.clientUrl}.${EOL}${e}` `Failed to insert the seed data in the PostgreSQL database ${dbData.clientUrl}.${EOL}${e}`
@@ -63,7 +63,7 @@ export async function run({
} }
async function createCurrencies( async function createCurrencies(
manager: SqlEntityManager, manager: SqlEntityManager<PostgreSqlDriver>,
data: RequiredEntityData<PricingModels.Currency>[] data: RequiredEntityData<PricingModels.Currency>[]
) { ) {
const currencies = data.map((currencyData) => { const currencies = data.map((currencyData) => {
@@ -76,7 +76,7 @@ async function createCurrencies(
} }
async function createMoneyAmounts( async function createMoneyAmounts(
manager: SqlEntityManager, manager: SqlEntityManager<PostgreSqlDriver>,
data: RequiredEntityData<PricingModels.MoneyAmount>[] data: RequiredEntityData<PricingModels.MoneyAmount>[]
) { ) {
const moneyAmounts = data.map((moneyAmountData) => { const moneyAmounts = data.map((moneyAmountData) => {
@@ -89,7 +89,7 @@ async function createMoneyAmounts(
} }
async function createPriceSets( async function createPriceSets(
manager: SqlEntityManager, manager: SqlEntityManager<PostgreSqlDriver>,
data: RequiredEntityData<PricingModels.PriceSet>[] data: RequiredEntityData<PricingModels.PriceSet>[]
) { ) {
const priceSets = data.map((priceSetData) => { const priceSets = data.map((priceSetData) => {
@@ -102,7 +102,7 @@ async function createPriceSets(
} }
async function createPriceSetMoneyAmounts( async function createPriceSetMoneyAmounts(
manager: SqlEntityManager, manager: SqlEntityManager<PostgreSqlDriver>,
data: RequiredEntityData<PricingModels.PriceSetMoneyAmount>[] data: RequiredEntityData<PricingModels.PriceSetMoneyAmount>[]
) { ) {
const priceSetMoneyAmounts = data.map((priceSetMoneyAmountData) => { const priceSetMoneyAmounts = data.map((priceSetMoneyAmountData) => {
@@ -101,4 +101,20 @@ export default class MoneyAmountService<
): Promise<void> { ): Promise<void> {
await this.moneyAmountRepository_.delete(ids, sharedContext) await this.moneyAmountRepository_.delete(ids, sharedContext)
} }
@InjectTransactionManager("moneyAmountRepository_")
async softDelete(
ids: string[],
@MedusaContext() sharedContext: Context = {}
): Promise<void> {
await this.moneyAmountRepository_.softDelete(ids, sharedContext)
}
@InjectTransactionManager("moneyAmountRepository_")
async restore(
ids: string[],
@MedusaContext() sharedContext: Context = {}
): Promise<[TEntity[], Record<string, unknown[]>]> {
return await this.moneyAmountRepository_.restore(ids, sharedContext)
}
} }
@@ -44,7 +44,7 @@ export default class PriceSetMoneyAmountService<
@InjectManager("priceSetMoneyAmountRepository_") @InjectManager("priceSetMoneyAmountRepository_")
async list( async list(
filters: ServiceTypes.FilterablePriceSetMoneyAmountProps = {}, filters: ServiceTypes.FilterablePriceSetMoneyAmountProps = {},
config: FindConfig<ServiceTypes.PriceSetDTO> = {}, config: FindConfig<ServiceTypes.PriceSetMoneyAmountDTO> = {},
@MedusaContext() sharedContext: Context = {} @MedusaContext() sharedContext: Context = {}
): Promise<TEntity[]> { ): Promise<TEntity[]> {
return (await this.priceSetMoneyAmountRepository_.find( return (await this.priceSetMoneyAmountRepository_.find(
@@ -56,7 +56,7 @@ export default class PriceSetMoneyAmountService<
@InjectManager("priceSetMoneyAmountRepository_") @InjectManager("priceSetMoneyAmountRepository_")
async listAndCount( async listAndCount(
filters: ServiceTypes.FilterablePriceSetMoneyAmountProps = {}, filters: ServiceTypes.FilterablePriceSetMoneyAmountProps = {},
config: FindConfig<ServiceTypes.PriceSetDTO> = {}, config: FindConfig<ServiceTypes.PriceSetMoneyAmountDTO> = {},
@MedusaContext() sharedContext: Context = {} @MedusaContext() sharedContext: Context = {}
): Promise<[TEntity[], number]> { ): Promise<[TEntity[], number]> {
return (await this.priceSetMoneyAmountRepository_.findAndCount( return (await this.priceSetMoneyAmountRepository_.findAndCount(
@@ -67,7 +67,7 @@ export default class PriceSetMoneyAmountService<
private buildQueryForList( private buildQueryForList(
filters: ServiceTypes.FilterablePriceSetMoneyAmountProps = {}, filters: ServiceTypes.FilterablePriceSetMoneyAmountProps = {},
config: FindConfig<ServiceTypes.PriceSetDTO> = {} config: FindConfig<ServiceTypes.PriceSetMoneyAmountDTO> = {}
) { ) {
const queryOptions = ModulesSdkUtils.buildQuery<PriceSet>(filters, config) const queryOptions = ModulesSdkUtils.buildQuery<PriceSet>(filters, config)
@@ -13,6 +13,7 @@ import {
PricingFilters, PricingFilters,
PricingRepositoryService, PricingRepositoryService,
PricingTypes, PricingTypes,
RestoreReturn,
RuleTypeDTO, RuleTypeDTO,
} from "@medusajs/types" } from "@medusajs/types"
import { import {
@@ -24,6 +25,7 @@ import {
arrayDifference, arrayDifference,
deduplicate, deduplicate,
groupBy, groupBy,
mapObjectTo,
removeNullish, removeNullish,
} from "@medusajs/utils" } from "@medusajs/utils"
@@ -54,7 +56,11 @@ import {
PriceSetService, PriceSetService,
RuleTypeService, RuleTypeService,
} from "@services" } from "@services"
import { joinerConfig } from "../joiner-config" import {
LinkableKeys,
entityNameToLinkableKeysMap,
joinerConfig,
} from "../joiner-config"
import { validatePriceListDates } from "@utils" import { validatePriceListDates } from "@utils"
import { ServiceTypes } from "@types" import { ServiceTypes } from "@types"
import { CreatePriceListRuleValueDTO } from "src/types/services" import { CreatePriceListRuleValueDTO } from "src/types/services"
@@ -861,6 +867,41 @@ export default class PricingModuleService<
await this.moneyAmountService_.delete(ids, sharedContext) await this.moneyAmountService_.delete(ids, sharedContext)
} }
@InjectTransactionManager("baseRepository_")
async softDeleteMoneyAmounts(
ids: string[],
@MedusaContext() sharedContext: Context = {}
): Promise<void> {
await this.moneyAmountService_.softDelete(ids, sharedContext)
}
@InjectTransactionManager("baseRepository_")
async restoreDeletedMoneyAmounts<
TReturnableLinkableKeys extends string = Lowercase<
keyof typeof LinkableKeys
>
>(
ids: string[],
{ returnLinkableKeys }: RestoreReturn<TReturnableLinkableKeys> = {},
@MedusaContext() sharedContext: Context = {}
): Promise<Record<Lowercase<keyof typeof LinkableKeys>, string[]> | void> {
const [_, cascadedEntitiesMap] = await this.moneyAmountService_.restore(
ids,
sharedContext
)
let mappedCascadedEntitiesMap
if (returnLinkableKeys) {
mappedCascadedEntitiesMap = mapObjectTo<
Record<Lowercase<keyof typeof LinkableKeys>, string[]>
>(cascadedEntitiesMap, entityNameToLinkableKeysMap, {
pick: returnLinkableKeys,
})
}
return mappedCascadedEntitiesMap ? mappedCascadedEntitiesMap : void 0
}
@InjectManager("baseRepository_") @InjectManager("baseRepository_")
async retrieveCurrency( async retrieveCurrency(
code: string, code: string,
@@ -1132,7 +1173,7 @@ export default class PricingModuleService<
) )
return this.baseRepository_.serialize< return this.baseRepository_.serialize<
PricingTypes.PriceSetMoneyAmountRulesDTO[] PricingTypes.PriceSetMoneyAmountDTO[]
>(records, { >(records, {
populate: true, populate: true,
}) })
@@ -1153,7 +1194,7 @@ export default class PricingModuleService<
return [ return [
await this.baseRepository_.serialize< await this.baseRepository_.serialize<
PricingTypes.PriceSetMoneyAmountRulesDTO[] PricingTypes.PriceSetMoneyAmountDTO[]
>(records, { >(records, {
populate: true, populate: true,
}), }),
@@ -30,6 +30,9 @@ export interface MoneyAmountDTO {
min_quantity?: number min_quantity?: number
max_quantity?: number max_quantity?: number
price_set_money_amount?: PriceSetMoneyAmountDTO price_set_money_amount?: PriceSetMoneyAmountDTO
created_at: Date
updated_at: Date
deleted_at: Date | null
} }
export interface FilterableMoneyAmountProps export interface FilterableMoneyAmountProps
@@ -33,6 +33,9 @@ export interface PriceRuleDTO {
priority: number priority: number
price_set_money_amount_id: string price_set_money_amount_id: string
price_list_id: string price_list_id: string
created_at: Date
updated_at: Date
deleted_at: Date | null
} }
export interface FilterablePriceRuleProps export interface FilterablePriceRuleProps
@@ -36,4 +36,7 @@ export interface PriceSetMoneyAmountDTO {
price_set_id?: string price_set_id?: string
price_rules?: PriceRuleDTO[] price_rules?: PriceRuleDTO[]
money_amount?: MoneyAmountDTO money_amount?: MoneyAmountDTO
created_at: Date
updated_at: Date
deleted_at: Date | null
} }
@@ -18,7 +18,7 @@ export interface MoneyAmountDTO {
currency_code?: string currency_code?: string
/** /**
* The money amount's currency. * The money amount's currency.
* *
* @expandable * @expandable
*/ */
currency?: CurrencyDTO currency?: CurrencyDTO
@@ -38,6 +38,18 @@ export interface MoneyAmountDTO {
* The details of the relation between the money amount and its associated price set. * The details of the relation between the money amount and its associated price set.
*/ */
price_set_money_amount?: PriceSetMoneyAmountDTO price_set_money_amount?: PriceSetMoneyAmountDTO
/**
* When the money_amount was created.
*/
created_at: Date
/**
* When the money_amount was updated.
*/
updated_at: Date
/**
* When the money_amount was deleted.
*/
deleted_at: null | Date
} }
/** /**
@@ -48,6 +48,18 @@ export interface PriceRuleDTO {
* The ID of the associated price list. * The ID of the associated price list.
*/ */
price_list_id: string price_list_id: string
/**
* When the price_rule was created.
*/
created_at: Date
/**
* When the price_rule was updated.
*/
updated_at: Date
/**
* When the price_rule was deleted.
*/
deleted_at: null | Date
} }
/** /**
@@ -1,8 +1,8 @@
import { BaseFilterable } from "../../dal" import { BaseFilterable } from "../../dal";
import { MoneyAmountDTO } from "./money-amount" import { MoneyAmountDTO } from "./money-amount";
import { PriceListDTO } from "./price-list" import { PriceListDTO } from "./price-list";
import { PriceRuleDTO } from "./price-rule" import { PriceRuleDTO } from "./price-rule";
import { PriceSetDTO } from "./price-set" import { PriceSetDTO } from "./price-set";
/** /**
* @interface * @interface
@@ -46,6 +46,18 @@ export interface PriceSetMoneyAmountDTO {
* @expandable * @expandable
*/ */
money_amount?: MoneyAmountDTO 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 { export interface UpdatePriceSetMoneyAmountDTO {
+53
View File
@@ -47,6 +47,7 @@ import {
import { FindConfig } from "../common" import { FindConfig } from "../common"
import { ModuleJoinerConfig } from "../modules-sdk" import { ModuleJoinerConfig } from "../modules-sdk"
import { Context } from "../shared-context" import { Context } from "../shared-context"
import { RestoreReturn } from "../dal"
export interface IPricingModuleService { export interface IPricingModuleService {
/** /**
@@ -1274,6 +1275,58 @@ export interface IPricingModuleService {
*/ */
deleteMoneyAmounts(ids: string[], sharedContext?: Context): Promise<void> deleteMoneyAmounts(ids: string[], sharedContext?: Context): Promise<void>
/**
* This method soft deletes money amounts by their IDs.
*
* @param {string[]} ids - The IDs of the money amounts to delete.
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<void>} Resolves when the money amounts are successfully deleted.
*
* @example
* import {
* initialize as initializePricingModule,
* } from "@medusajs/pricing"
*
* async function softDeleteMoneyAmounts (moneyAmountIds: string[]) {
* const pricingService = await initializePricingModule()
*
* await pricingService.softDeleteMoneyAmounts(
* moneyAmountIds
* )
* }
*/
softDeleteMoneyAmounts(ids: string[], sharedContext?: Context): Promise<void>
/**
* This method restores soft deleted money amounts by their IDs.
*
* @param {string[]} ids - The IDs of the money amounts to delete.
* @param {RestoreReturn<TReturnableLinkableKeys>} config -
* Configurations determining which relations to restore along with each of the money amounts. You can pass to its `returnLinkableKeys`
* property any of the money_amount's relation attribute names, such as `price_set_money_amount_id`.
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<Record<string, string[]> | void>}
* An object that includes the IDs of related records that were restored, such as the ID of associated product variants. The object's keys are the ID attribute names of the product entity's relations, such as `variant_id`, and its value is an array of strings, each being the ID of the record associated with the product through this relation, such as the IDs of associated product variants.
*
* @example
* import {
* initialize as initializePricingModule,
* } from "@medusajs/pricing"
*
* async function softDeleteMoneyAmounts (moneyAmountIds: string[]) {
* const pricingService = await initializePricingModule()
*
* await pricingService.softDeleteMoneyAmounts(
* moneyAmountIds
* )
* }
*/
restoreDeletedMoneyAmounts<TReturnableLinkableKeys extends string = string>(
ids: string[],
config?: RestoreReturn<TReturnableLinkableKeys>,
sharedContext?: Context
): Promise<Record<string, string[]> | void>
/** /**
* This method retrieves a currency by its code and and optionally based on the provided configurations. * This method retrieves a currency by its code and and optionally based on the provided configurations.
* *
@@ -6,7 +6,7 @@ import {
} from "@medusajs/types" } from "@medusajs/types"
import { isString } from "../../common" import { isString } from "../../common"
import { MedusaContext } from "../../decorators" import { MedusaContext } from "../../decorators"
import { InjectTransactionManager, buildQuery } from "../../modules-sdk" import { buildQuery, InjectTransactionManager } from "../../modules-sdk"
import { import {
getSoftDeletedCascadedEntitiesIdsMappedBy, getSoftDeletedCascadedEntitiesIdsMappedBy,
transactionWrapper, transactionWrapper,
+16 -12
View File
@@ -1,5 +1,3 @@
import { SoftDeletableFilterKey } from "./mikro-orm-soft-deletable-filter"
export const mikroOrmUpdateDeletedAtRecursively = async < export const mikroOrmUpdateDeletedAtRecursively = async <
T extends object = any T extends object = any
>( >(
@@ -22,19 +20,25 @@ export const mikroOrmUpdateDeletedAtRecursively = async <
) )
for (const relation of relationsToCascade) { for (const relation of relationsToCascade) {
let collectionRelation = entity[relation.name] let entityRelation = entity[relation.name]
if (!collectionRelation.isInitialized()) { // Handle optional relationships
await collectionRelation.init() if (relation.nullable && !entityRelation) {
continue
} }
const relationEntities = await collectionRelation.getItems({ const isCollection = "toArray" in entityRelation
filters: { let relationEntities: any[] = []
[SoftDeletableFilterKey]: {
withDeleted: true, if (isCollection) {
}, if (!entityRelation.isInitialized()) {
}, entityRelation = await entityRelation.init({ populate: true })
}) }
relationEntities = entityRelation.getItems()
} else {
const initializedEntityRelation = await entityRelation.__helper?.init()
relationEntities = [initializedEntityRelation]
}
await mikroOrmUpdateDeletedAtRecursively(manager, relationEntities, value) await mikroOrmUpdateDeletedAtRecursively(manager, relationEntities, value)
} }