feat: Add currency module and remove currency models from region and pricing modules (#6536)

What:
- Creates a new currency module
- Removes currency model from the pricing module
- Removes currency model from region module
This commit is contained in:
Stevche Radevski authored and GitHub committed 2024-02-29 15:09:59 +00:00
1 parent 06f706a51a
commit dc025302a1
102 files changed
+1502 -2128

No files matched your search

@@ -1,20 +0,0 @@
export const defaultCurrencyData = [
{
symbol: "$",
name: "US Dollar",
symbol_native: "$",
code: "USD",
},
{
symbol: "CA$",
name: "Canadian Dollar",
symbol_native: "$",
code: "CAD",
},
{
symbol: "€",
name: "Euro",
symbol_native: "€",
code: "EUR",
},
]
@@ -1,22 +0,0 @@
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { Currency } from "@models"
import { defaultCurrencyData } from "./data"
export * from "./data"
export async function createCurrencies(
manager: SqlEntityManager,
currencyData: any[] = defaultCurrencyData
): Promise<Currency[]> {
const currencies: Currency[] = []
for (let curr of currencyData) {
const currency = manager.create(Currency, curr)
currencies.push(currency)
}
await manager.persistAndFlush(currencies)
return currencies
}
@@ -1,6 +1,5 @@
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { createCurrencies, defaultCurrencyData } from "./currency"
import { createMoneyAmounts, defaultMoneyAmountsData } from "./money-amount"
import { createPriceRules, defaultPriceRuleData } from "./price-rule"
import { createPriceSets, defaultPriceSetsData } from "./price-set"
@@ -21,14 +20,12 @@ export async function seedPriceData(
{
moneyAmountsData = defaultMoneyAmountsData,
priceSetsData = defaultPriceSetsData,
currencyData = defaultCurrencyData,
priceRuleData = defaultPriceRuleData,
priceSetMoneyAmountsData = defaultPriceSetMoneyAmountsData,
priceSetMoneyAmountRulesData = defaultPriceSetMoneyAmountRulesData,
ruleTypesData = defaultRuleTypesData,
} = {}
) {
await createCurrencies(testManager, currencyData)
await createMoneyAmounts(testManager, moneyAmountsData)
await createPriceSets(testManager, priceSetsData)
await createPriceSetMoneyAmounts(testManager, priceSetMoneyAmountsData)
@@ -1,278 +0,0 @@
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { Currency } from "@models"
import { createCurrencies } from "../../../__fixtures__/currency"
import { MikroOrmWrapper } from "../../../utils"
import { createMedusaContainer } from "@medusajs/utils"
import { asValue } from "awilix"
import ContainerLoader from "../../../../src/loaders/container"
import { ModulesSdkTypes } from "@medusajs/types"
jest.setTimeout(30000)
describe("Currency Service", () => {
let service: ModulesSdkTypes.InternalModuleService<any>
let testManager: SqlEntityManager
let repositoryManager: SqlEntityManager
let data!: Currency[]
const currencyData = [
{
symbol: "$",
name: "US Dollar",
symbol_native: "$",
code: "USD",
},
{
symbol: "CA$",
name: "Canadian Dollar",
symbol_native: "$",
code: "CAD",
},
]
beforeEach(async () => {
await MikroOrmWrapper.setupDatabase()
repositoryManager = await MikroOrmWrapper.forkManager()
const container = createMedusaContainer()
container.register("manager", asValue(repositoryManager))
await ContainerLoader({ container })
service = container.resolve("currencyService")
testManager = await MikroOrmWrapper.forkManager()
data = await createCurrencies(testManager, currencyData)
})
afterEach(async () => {
await MikroOrmWrapper.clearDatabase()
})
describe("list", () => {
it("list currencies", async () => {
const currenciesResult = await service.list()
expect(currenciesResult).toEqual([
expect.objectContaining({
code: "CAD",
name: "Canadian Dollar",
}),
expect.objectContaining({
code: "USD",
name: "US Dollar",
}),
])
})
it("list currencies by code", async () => {
const currenciesResult = await service.list({ code: ["USD"] })
expect(currenciesResult).toEqual([
expect.objectContaining({
code: "USD",
name: "US Dollar",
}),
])
})
})
describe("listAndCount", () => {
it("should return currencies and count", async () => {
const [currenciesResult, count] = await service.listAndCount()
expect(count).toEqual(2)
expect(currenciesResult).toEqual([
expect.objectContaining({
code: "CAD",
name: "Canadian Dollar",
}),
expect.objectContaining({
code: "USD",
name: "US Dollar",
}),
])
})
it("should return currencies and count when filtered", async () => {
const [currenciesResult, count] = await service.listAndCount({
code: ["USD"],
})
expect(count).toEqual(1)
expect(currenciesResult).toEqual([
expect.objectContaining({
code: "USD",
name: "US Dollar",
}),
])
})
it("should return currencies and count when using skip and take", async () => {
const [currenciesResult, count] = await service.listAndCount(
{},
{ skip: 1, take: 1 }
)
expect(count).toEqual(2)
expect(currenciesResult).toEqual([
expect.objectContaining({
code: "USD",
name: "US Dollar",
}),
])
})
it("should return requested fields", async () => {
const [currenciesResult, count] = await service.listAndCount(
{},
{
take: 1,
select: ["code"],
}
)
const serialized = JSON.parse(JSON.stringify(currenciesResult))
expect(count).toEqual(2)
expect(serialized).toEqual([
{
code: "CAD",
},
])
})
})
describe("retrieve", () => {
const code = "USD"
const name = "US Dollar"
it("should return currency for the given code", async () => {
const currency = await service.retrieve(code)
expect(currency).toEqual(
expect.objectContaining({
code,
})
)
})
it("should throw an error when currency with code does not exist", async () => {
let error
try {
await service.retrieve("does-not-exist")
} catch (e) {
error = e
}
expect(error.message).toEqual(
"Currency with code: does-not-exist was not found"
)
})
it("should throw an error when a code is not provided", async () => {
let error
try {
await service.retrieve(undefined as unknown as string)
} catch (e) {
error = e
}
expect(error.message).toEqual("currency - code must be defined")
})
it("should return currency based on config select param", async () => {
const currency = await service.retrieve(code, {
select: ["code", "name"],
})
const serialized = JSON.parse(JSON.stringify(currency))
expect(serialized).toEqual({
code,
name,
})
})
})
describe("delete", () => {
const code = "USD"
it("should delete the currencies given an code successfully", async () => {
await service.delete([code])
const currencies = await service.list({
code: [code],
})
expect(currencies).toHaveLength(0)
})
})
describe("update", () => {
const code = "USD"
it("should update the name of the currency successfully", async () => {
await service.update([
{
code,
name: "United States Pounds",
},
])
const currency = await service.retrieve(code)
expect(currency.name).toEqual("United States Pounds")
})
it("should throw an error when a code does not exist", async () => {
let error
try {
await service.update([
{
code: "does-not-exist",
name: "UK",
},
])
} catch (e) {
error = e
}
expect(error.message).toEqual(
'Currency with code "does-not-exist" not found'
)
})
})
describe("create", () => {
it("should create a currency successfully", async () => {
await service.create([
{
code: "TES",
name: "Test Dollars",
symbol: "TES1",
symbol_native: "TES2",
},
])
const [currency] = await service.list({
code: ["TES"],
})
expect(currency).toEqual(
expect.objectContaining({
code: "TES",
name: "Test Dollars",
symbol: "TES1",
symbol_native: "TES2",
})
)
})
})
})
@@ -3,7 +3,6 @@ import { SqlEntityManager } from "@mikro-orm/postgresql"
import { Currency, MoneyAmount } from "@models"
import { MoneyAmountService } from "@services"
import { createCurrencies } from "../../../__fixtures__/currency"
import { createMoneyAmounts } from "../../../__fixtures__/money-amount"
import { MikroOrmWrapper } from "../../../utils"
import { createMedusaContainer } from "@medusajs/utils"
@@ -17,7 +16,6 @@ describe("MoneyAmount Service", () => {
let testManager: SqlEntityManager
let repositoryManager: SqlEntityManager
let data!: MoneyAmount[]
let currencyData!: Currency[]
beforeEach(async () => {
await MikroOrmWrapper.setupDatabase()
@@ -31,7 +29,6 @@ describe("MoneyAmount Service", () => {
service = container.resolve("moneyAmountService")
testManager = await MikroOrmWrapper.forkManager()
currencyData = await createCurrencies(testManager)
data = await createMoneyAmounts(testManager)
})
@@ -79,8 +76,7 @@ describe("MoneyAmount Service", () => {
id: ["money-amount-USD"],
},
{
select: ["id", "min_quantity", "currency.code", "amount"],
relations: ["currency"],
select: ["id", "min_quantity", "currency_code", "amount"],
}
)
@@ -92,9 +88,6 @@ describe("MoneyAmount Service", () => {
amount: 500,
min_quantity: "1",
currency_code: "USD",
currency: {
code: "USD",
},
},
])
})
@@ -105,8 +98,7 @@ describe("MoneyAmount Service", () => {
currency_code: ["USD"],
},
{
select: ["id", "min_quantity", "currency.code", "amount"],
relations: ["currency"],
select: ["id", "min_quantity", "currency_code", "amount"],
}
)
@@ -118,9 +110,6 @@ describe("MoneyAmount Service", () => {
min_quantity: "1",
currency_code: "USD",
amount: 500,
currency: {
code: "USD",
},
},
])
})
@@ -165,8 +154,7 @@ describe("MoneyAmount Service", () => {
id: ["money-amount-USD"],
},
{
select: ["id", "min_quantity", "currency.code", "amount"],
relations: ["currency"],
select: ["id", "min_quantity", "currency_code", "amount"],
}
)
@@ -179,9 +167,6 @@ describe("MoneyAmount Service", () => {
amount: 500,
min_quantity: "1",
currency_code: "USD",
currency: {
code: "USD",
},
},
])
})
@@ -316,7 +301,6 @@ describe("MoneyAmount Service", () => {
const moneyAmount = await service.retrieve(id)
expect(moneyAmount.currency_code).toEqual("EUR")
expect(moneyAmount.currency?.code).toEqual("EUR")
})
it("should throw an error when a id does not exist", async () => {
@@ -3,7 +3,6 @@ import { PriceSetMoneyAmount } from "@models"
import { CreatePriceRuleDTO } from "@medusajs/types"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { PriceRuleService } from "@services"
import { createCurrencies } from "../../../__fixtures__/currency"
import { createMoneyAmounts } from "../../../__fixtures__/money-amount"
import { createPriceRules } from "../../../__fixtures__/price-rule"
import { createPriceSets } from "../../../__fixtures__/price-set"
@@ -34,7 +33,6 @@ describe("PriceRule Service", () => {
service = container.resolve("priceRuleService")
await createCurrencies(testManager)
await createMoneyAmounts(testManager)
await createPriceSets(testManager)
await createRuleTypes(testManager)
@@ -3,7 +3,6 @@ import { SqlEntityManager } from "@mikro-orm/postgresql"
import { MoneyAmount, PriceSet } from "@models"
import { PriceSetService } from "@services"
import { createCurrencies } from "../../../__fixtures__/currency"
import { createMoneyAmounts } from "../../../__fixtures__/money-amount"
import { createPriceSets } from "../../../__fixtures__/price-set"
import { MikroOrmWrapper } from "../../../utils"
@@ -63,8 +62,6 @@ describe("PriceSet Service", () => {
service = container.resolve("priceSetService")
await createCurrencies(testManager)
moneyAmountsData = await createMoneyAmounts(
testManager,
moneyAmountsInputData
@@ -85,21 +85,6 @@ describe("PricingModule Service - Calculate Price", () => {
describe("calculatePrices", () => {
beforeEach(async () => {
const currencyData = [
{
symbol: "zł",
name: "Polish Zloty",
symbol_native: "zł",
code: "PLN",
},
{
symbol: "€",
name: "Euro",
symbol_native: "€",
code: "EUR",
},
]
const moneyAmountsData = [
{
id: "money-amount-PLN",
@@ -373,7 +358,6 @@ describe("PricingModule Service - Calculate Price", () => {
] as unknown as CreatePriceRuleDTO[]
await seedPriceData(MikroOrmWrapper.forkManager(), {
currencyData,
moneyAmountsData,
priceSetsData,
priceSetMoneyAmountsData,
@@ -1,277 +0,0 @@
import { IPricingModuleService } from "@medusajs/types"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { Currency } from "@models"
import { createCurrencies } from "../../../__fixtures__/currency"
import { MikroOrmWrapper } from "../../../utils"
import { getInitModuleConfig } from "../../../utils/get-init-module-config"
import { Modules } from "@medusajs/modules-sdk"
import { initModules } from "medusa-test-utils"
describe("PricingModule Service - Currency", () => {
let service: IPricingModuleService
let testManager: SqlEntityManager
let repositoryManager: SqlEntityManager
let data!: Currency[]
let shutdownFunc: () => Promise<void>
beforeAll(async () => {
const initModulesConfig = getInitModuleConfig()
const { medusaApp, shutdown } = await initModules(initModulesConfig)
service = medusaApp.modules[Modules.PRICING]
shutdownFunc = shutdown
})
afterAll(async () => {
await shutdownFunc()
})
beforeEach(async () => {
await MikroOrmWrapper.setupDatabase()
repositoryManager = MikroOrmWrapper.forkManager()
testManager = MikroOrmWrapper.forkManager()
data = await createCurrencies(testManager)
})
afterEach(async () => {
await MikroOrmWrapper.clearDatabase()
})
describe("listCurrencies", () => {
it("list currencies", async () => {
const currenciesResult = await service.listCurrencies()
expect(currenciesResult).toEqual([
expect.objectContaining({
code: "CAD",
name: "Canadian Dollar",
}),
expect.objectContaining({
code: "EUR",
name: "Euro",
}),
expect.objectContaining({
code: "USD",
name: "US Dollar",
}),
])
})
it("list currencies by code", async () => {
const currenciesResult = await service.listCurrencies({ code: ["USD"] })
expect(currenciesResult).toEqual([
expect.objectContaining({
code: "USD",
name: "US Dollar",
}),
])
})
})
describe("listAndCountCurrencies", () => {
it("should return currencies and count", async () => {
const [currenciesResult, count] = await service.listAndCountCurrencies()
expect(count).toEqual(3)
expect(currenciesResult).toEqual([
expect.objectContaining({
code: "CAD",
name: "Canadian Dollar",
}),
expect.objectContaining({
code: "EUR",
name: "Euro",
}),
expect.objectContaining({
code: "USD",
name: "US Dollar",
}),
])
})
it("should return currencies and count when filtered", async () => {
const [currenciesResult, count] = await service.listAndCountCurrencies({
code: ["USD"],
})
expect(count).toEqual(1)
expect(currenciesResult).toEqual([
expect.objectContaining({
code: "USD",
name: "US Dollar",
}),
])
})
it("should return currencies and count when using skip and take", async () => {
const [currenciesResult, count] = await service.listAndCountCurrencies(
{},
{ skip: 1, take: 1 }
)
expect(count).toEqual(3)
expect(currenciesResult).toEqual([
expect.objectContaining({
code: "EUR",
name: "Euro",
symbol: "€",
symbol_native: "€",
}),
])
})
it("should return requested fields", async () => {
const [currenciesResult, count] = await service.listAndCountCurrencies(
{},
{
take: 1,
select: ["code"],
}
)
const serialized = JSON.parse(JSON.stringify(currenciesResult))
expect(count).toEqual(3)
expect(serialized).toEqual([
{
code: "CAD",
},
])
})
})
describe("retrieveCurrency", () => {
const code = "USD"
const name = "US Dollar"
it("should return currency for the given code", async () => {
const currency = await service.retrieveCurrency(code)
expect(currency).toEqual(
expect.objectContaining({
code,
})
)
})
it("should throw an error when currency with code does not exist", async () => {
let error
try {
await service.retrieveCurrency("does-not-exist")
} catch (e) {
error = e
}
expect(error.message).toEqual(
"Currency with code: does-not-exist was not found"
)
})
it("should throw an error when a code is not provided", async () => {
let error
try {
await service.retrieveCurrency(undefined as unknown as string)
} catch (e) {
error = e
}
expect(error.message).toEqual("currency - code must be defined")
})
it("should return currency based on config select param", async () => {
const currency = await service.retrieveCurrency(code, {
select: ["code", "name"],
})
const serialized = JSON.parse(JSON.stringify(currency))
expect(serialized).toEqual({
code,
name,
})
})
})
describe("deleteCurrencies", () => {
const code = "USD"
it("should delete the currencies given an code successfully", async () => {
await service.deleteCurrencies([code])
const currencies = await service.listCurrencies({
code: [code],
})
expect(currencies).toHaveLength(0)
})
})
describe("updateCurrencies", () => {
const code = "USD"
it("should update the name of the currency successfully", async () => {
await service.updateCurrencies([
{
code,
name: "United States Pounds",
},
])
const currency = await service.retrieveCurrency(code)
expect(currency.name).toEqual("United States Pounds")
})
it("should throw an error when a code does not exist", async () => {
let error
try {
await service.updateCurrencies([
{
code: "does-not-exist",
name: "UK",
},
])
} catch (e) {
error = e
}
expect(error.message).toEqual(
'Currency with code "does-not-exist" not found'
)
})
})
describe("createCurrencies", () => {
it("should create a currency successfully", async () => {
await service.createCurrencies([
{
code: "TES",
name: "Test Dollars",
symbol: "TES1",
symbol_native: "TES2",
},
])
const [currency] = await service.listCurrencies({
code: ["TES"],
})
expect(currency).toEqual(
expect.objectContaining({
code: "TES",
name: "Test Dollars",
symbol: "TES1",
symbol_native: "TES2",
})
)
})
})
})
@@ -1,7 +1,6 @@
import { IPricingModuleService } from "@medusajs/types"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { Currency, MoneyAmount } from "@models"
import { createCurrencies } from "../../../__fixtures__/currency"
import { MoneyAmount } from "@models"
import { createMoneyAmounts } from "../../../__fixtures__/money-amount"
import { MikroOrmWrapper } from "../../../utils"
import { createPriceSetMoneyAmounts } from "../../../__fixtures__/price-set-money-amount"
@@ -20,7 +19,6 @@ describe("PricingModule Service - MoneyAmount", () => {
let testManager: SqlEntityManager
let repositoryManager: SqlEntityManager
let data!: MoneyAmount[]
let currencyData!: Currency[]
let shutdownFunc: () => Promise<void>
beforeAll(async () => {
@@ -42,7 +40,6 @@ describe("PricingModule Service - MoneyAmount", () => {
repositoryManager = MikroOrmWrapper.forkManager()
testManager = MikroOrmWrapper.forkManager()
currencyData = await createCurrencies(testManager)
data = await createMoneyAmounts(testManager)
})
@@ -90,8 +87,7 @@ describe("PricingModule Service - MoneyAmount", () => {
id: ["money-amount-USD"],
},
{
select: ["id", "min_quantity", "currency.code"],
relations: ["currency"],
select: ["id", "min_quantity", "currency_code"],
}
)
@@ -103,9 +99,6 @@ describe("PricingModule Service - MoneyAmount", () => {
amount: null,
min_quantity: "1",
currency_code: "USD",
currency: {
code: "USD",
},
},
])
})
@@ -153,8 +146,7 @@ describe("PricingModule Service - MoneyAmount", () => {
id: ["money-amount-USD"],
},
{
select: ["id", "min_quantity", "currency.code", "amount"],
relations: ["currency"],
select: ["id", "min_quantity", "currency_code", "amount"],
}
)
@@ -167,9 +159,6 @@ describe("PricingModule Service - MoneyAmount", () => {
amount: 500,
min_quantity: "1",
currency_code: "USD",
currency: {
code: "USD",
},
},
])
})
@@ -392,12 +381,9 @@ describe("PricingModule Service - MoneyAmount", () => {
},
])
const moneyAmount = await service.retrieveMoneyAmount(id, {
relations: ["currency"],
})
const moneyAmount = await service.retrieveMoneyAmount(id, {})
expect(moneyAmount.currency_code).toEqual("EUR")
expect(moneyAmount.currency?.code).toEqual("EUR")
})
it("should throw an error when a id does not exist", async () => {
@@ -2,7 +2,6 @@ import { MikroOrmWrapper } from "../../../utils"
import { IPricingModuleService } from "@medusajs/types"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { createCurrencies } from "../../../__fixtures__/currency"
import { createPriceLists } from "../../../__fixtures__/price-list"
import { createPriceSets } from "../../../__fixtures__/price-set"
import { Modules } from "@medusajs/modules-sdk"
@@ -35,7 +34,6 @@ describe("PriceList Service", () => {
await MikroOrmWrapper.forkManager()
testManager = await MikroOrmWrapper.forkManager()
await createCurrencies(testManager)
await createPriceSets(testManager)
await createPriceLists(testManager)
await service.createRuleTypes([
@@ -2,7 +2,6 @@ import { CreatePriceRuleDTO, IPricingModuleService } from "@medusajs/types"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { PriceSetMoneyAmount } from "../../../../src"
import { createCurrencies } from "../../../__fixtures__/currency"
import { createMoneyAmounts } from "../../../__fixtures__/money-amount"
import { createPriceRules } from "../../../__fixtures__/price-rule"
import { createPriceSets } from "../../../__fixtures__/price-set"
@@ -39,7 +38,6 @@ describe("PricingModule Service - PriceRule", () => {
await MikroOrmWrapper.setupDatabase()
testManager = MikroOrmWrapper.forkManager()
await createCurrencies(testManager)
await createMoneyAmounts(testManager)
await createPriceSets(testManager)
await createRuleTypes(testManager)
@@ -1,6 +1,5 @@
import { IPricingModuleService } from "@medusajs/types"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { createCurrencies } from "../../../__fixtures__/currency"
import { createMoneyAmounts } from "../../../__fixtures__/money-amount"
import { createPriceSets } from "../../../__fixtures__/price-set"
import { createPriceSetMoneyAmounts } from "../../../__fixtures__/price-set-money-amount"
@@ -38,7 +37,6 @@ describe("PricingModule Service - PriceSetMoneyAmountRules", () => {
repositoryManager = await MikroOrmWrapper.forkManager()
testManager = await MikroOrmWrapper.forkManager()
await createCurrencies(testManager)
await createMoneyAmounts(testManager)
await createPriceSets(testManager)
await createRuleTypes(testManager)
+1 -15
View File
@@ -1,18 +1,11 @@
import { Modules } from "@medusajs/modules-sdk"
import { ModuleJoinerConfig } from "@medusajs/types"
import { MapToConfig } from "@medusajs/utils"
import {
Currency,
MoneyAmount,
PriceList,
PriceSet,
PriceSetMoneyAmount,
} from "@models"
import { MoneyAmount, PriceList, PriceSet, PriceSetMoneyAmount } from "@models"
import schema from "./schema"
export const LinkableKeys = {
money_amount_id: MoneyAmount.name,
currency_code: Currency.name,
price_set_id: PriceSet.name,
price_list_id: PriceList.name,
price_set_money_amount_id: PriceSetMoneyAmount.name,
@@ -48,13 +41,6 @@ export const joinerConfig: ModuleJoinerConfig = {
entity: "MoneyAmount",
},
},
{
name: ["currency", "currencies"],
args: {
methodSuffix: "Currencies",
entity: "Currency",
},
},
{
name: ["price_list", "price_lists"],
args: {
@@ -4,61 +4,6 @@
],
"name": "public",
"tables": [
{
"columns": {
"code": {
"name": "code",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "text"
},
"symbol": {
"name": "symbol",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "text"
},
"symbol_native": {
"name": "symbol_native",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "text"
},
"name": {
"name": "name",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "text"
}
},
"name": "currency",
"schema": "public",
"indexes": [
{
"keyName": "currency_pkey",
"columnNames": [
"code"
],
"composite": false,
"primary": true,
"unique": true
}
],
"checks": [],
"foreignKeys": {}
},
{
"columns": {
"id": {
@@ -172,19 +117,6 @@
],
"checks": [],
"foreignKeys": {
"money_amount_currency_code_foreign": {
"constraintName": "money_amount_currency_code_foreign",
"columnNames": [
"currency_code"
],
"localTableName": "public.money_amount",
"referencedColumnNames": [
"code"
],
"referencedTableName": "public.currency",
"deleteRule": "set null",
"updateRule": "cascade"
}
}
},
{
@@ -2,10 +2,6 @@ import { Migration } from "@mikro-orm/migrations"
export class Migration20230929122253 extends Migration {
async up(): Promise<void> {
this.addSql(
'create table if not exists "currency" ("code" text not null, "symbol" text not null, "symbol_native" text not null, "name" text not null, constraint "currency_pkey" primary key ("code"));'
)
this.addSql(
'create table if not exists "money_amount" ("id" text not null, "currency_code" text null, "amount" numeric null, "min_quantity" numeric null, "max_quantity" numeric null, constraint "money_amount_pkey" primary key ("id"));'
)
@@ -67,10 +63,6 @@ export class Migration20230929122253 extends Migration {
'create index "IDX_price_rule_price_set_money_amount_id" on "price_rule" ("price_set_money_amount_id");'
)
this.addSql(
'alter table "money_amount" add constraint "money_amount_currency_code_foreign" foreign key ("currency_code") references "currency" ("code") on update cascade on delete set null;'
)
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;'
)
-18
View File
@@ -1,18 +0,0 @@
import { Entity, PrimaryKey, Property } from "@mikro-orm/core"
@Entity({ tableName: "currency" })
class Currency {
@PrimaryKey({ columnType: "text" })
code!: string
@Property({ columnType: "text" })
symbol: string
@Property({ columnType: "text" })
symbol_native: string
@Property({ columnType: "text" })
name: string
}
export default Currency
-1
View File
@@ -1,4 +1,3 @@
export { default as Currency } from "./currency"
export { default as MoneyAmount } from "./money-amount"
export { default as PriceList } from "./price-list"
export { default as PriceListRule } from "./price-list-rule"
@@ -14,7 +14,6 @@ import {
Property,
} from "@mikro-orm/core"
import Currency from "./currency"
import { PriceSetMoneyAmount } from "./index"
import PriceSet from "./price-set"
@@ -47,13 +46,6 @@ class MoneyAmount {
})
price_set_money_amount: PriceSetMoneyAmount
@ManyToOne(() => Currency, {
nullable: true,
index: "IDX_money_amount_currency_code",
fieldName: "currency_code",
})
currency: Currency
@Property({
columnType: "numeric",
nullable: true,
-1
View File
@@ -7,7 +7,6 @@ type PriceSet {
type MoneyAmount {
id: String!
currency_code: String
currency: Currency
amount: Float
min_quantity: Float
max_quantity: Float
+8 -26
View File
@@ -22,17 +22,13 @@ export async function run({
logger.info(`Loading seed data from ${path}...`)
const {
currenciesData,
moneyAmountsData,
priceSetsData,
priceSetMoneyAmountsData,
} = 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, currenciesData, moneyAmountsData and priceSetMoneyAmountsData.${EOL}${e}`
)
throw e
})
const { moneyAmountsData, priceSetsData, priceSetMoneyAmountsData } =
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, moneyAmountsData and priceSetMoneyAmountsData.${EOL}${e}`
)
throw e
})
const dbData = ModulesSdkUtils.loadDatabaseConfig("pricing", options)!
const entities = Object.values(PricingModels) as unknown as EntitySchema[]
@@ -47,9 +43,8 @@ export async function run({
const manager = orm.em.fork()
try {
logger.info("Inserting price_sets, currencies & money_amounts")
logger.info("Inserting price_sets & money_amounts")
await createCurrencies(manager as any, currenciesData)
await createMoneyAmounts(manager as any, moneyAmountsData)
await createPriceSets(manager as any, priceSetsData)
await createPriceSetMoneyAmounts(manager as any, priceSetMoneyAmountsData)
@@ -62,19 +57,6 @@ export async function run({
await orm.close(true)
}
async function createCurrencies(
manager: SqlEntityManager<PostgreSqlDriver>,
data: RequiredEntityData<PricingModels.Currency>[]
) {
const currencies = data.map((currencyData) => {
return manager.create(PricingModels.Currency, currencyData)
})
await manager.persistAndFlush(currencies)
return currencies
}
async function createMoneyAmounts(
manager: SqlEntityManager<PostgreSqlDriver>,
data: RequiredEntityData<PricingModels.MoneyAmount>[]
@@ -1,24 +0,0 @@
import { Currency } from "@models"
import { asValue } from "awilix"
;(Currency as any).meta = {
/**
* Need to mock the Currency model as well to expose the primary keys when it is different than `id`
*/
primaryKeys: ["code"],
}
export const nonExistingCurrencyCode = "non-existing-code"
export const currencyRepositoryMock = {
currencyRepository: asValue({
find: jest.fn().mockImplementation(async ({ where: { code } }) => {
if (code === nonExistingCurrencyCode) {
return []
}
return [{}]
}),
findAndCount: jest.fn().mockResolvedValue([[], 0]),
getFreshManager: jest.fn().mockResolvedValue({}),
}),
}
@@ -1,228 +0,0 @@
import {
currencyRepositoryMock,
nonExistingCurrencyCode,
} from "../__fixtures__/currency"
import { createMedusaContainer } from "@medusajs/utils"
import { asValue } from "awilix"
import ContainerLoader from "../../loaders/container"
import { MedusaContainer } from "@medusajs/types"
const code = "existing-currency"
describe("Currency service", function () {
let container: MedusaContainer
beforeEach(async function () {
jest.clearAllMocks()
container = createMedusaContainer()
container.register("manager", asValue({}))
await ContainerLoader({ container })
container.register(currencyRepositoryMock)
})
it("should retrieve a currency", async function () {
const currencyService = container.resolve("currencyService")
const currencyRepository = container.resolve("currencyRepository")
await currencyService.retrieve(code)
expect(currencyRepository.find).toHaveBeenCalledWith(
{
where: {
code,
},
options: {
fields: undefined,
limit: 15,
offset: 0,
populate: [],
},
},
expect.any(Object)
)
})
it("should fail to retrieve a currency", async function () {
const currencyService = container.resolve("currencyService")
const currencyRepository = container.resolve("currencyRepository")
const err = await currencyService
.retrieve(nonExistingCurrencyCode)
.catch((e) => e)
expect(currencyRepository.find).toHaveBeenCalledWith(
{
where: {
code: nonExistingCurrencyCode,
},
options: {
fields: undefined,
limit: 15,
offset: 0,
populate: [],
withDeleted: undefined,
},
},
expect.any(Object)
)
expect(err.message).toBe(
`Currency with code: ${nonExistingCurrencyCode} was not found`
)
})
it("should list currencys", async function () {
const currencyService = container.resolve("currencyService")
const currencyRepository = container.resolve("currencyRepository")
const filters = {}
const config = {
relations: [],
}
await currencyService.list(filters, config)
expect(currencyRepository.find).toHaveBeenCalledWith(
{
where: {},
options: {
fields: undefined,
limit: 15,
offset: 0,
orderBy: {
code: "ASC",
},
populate: [],
withDeleted: undefined,
},
},
expect.any(Object)
)
})
it("should list currencys with filters", async function () {
const currencyService = container.resolve("currencyService")
const currencyRepository = container.resolve("currencyRepository")
const filters = {
tags: {
value: {
$in: ["test"],
},
},
}
const config = {
relations: [],
}
await currencyService.list(filters, config)
expect(currencyRepository.find).toHaveBeenCalledWith(
{
where: {
tags: {
value: {
$in: ["test"],
},
},
},
options: {
fields: undefined,
limit: 15,
offset: 0,
orderBy: {
code: "ASC",
},
populate: [],
withDeleted: undefined,
},
},
expect.any(Object)
)
})
it("should list currencys with filters and relations", async function () {
const currencyService = container.resolve("currencyService")
const currencyRepository = container.resolve("currencyRepository")
const filters = {
tags: {
value: {
$in: ["test"],
},
},
}
const config = {
relations: ["tags"],
}
await currencyService.list(filters, config)
expect(currencyRepository.find).toHaveBeenCalledWith(
{
where: {
tags: {
value: {
$in: ["test"],
},
},
},
options: {
fields: undefined,
limit: 15,
offset: 0,
orderBy: {
code: "ASC",
},
withDeleted: undefined,
populate: ["tags"],
},
},
expect.any(Object)
)
})
it("should list and count the currencies with filters and relations", async function () {
const currencyService = container.resolve("currencyService")
const currencyRepository = container.resolve("currencyRepository")
const filters = {
tags: {
value: {
$in: ["test"],
},
},
}
const config = {
relations: ["tags"],
}
await currencyService.listAndCount(filters, config)
expect(currencyRepository.findAndCount).toHaveBeenCalledWith(
{
where: {
tags: {
value: {
$in: ["test"],
},
},
},
options: {
fields: undefined,
limit: 15,
offset: 0,
orderBy: {
code: "ASC",
},
withDeleted: undefined,
populate: ["tags"],
},
},
expect.any(Object)
)
})
})
@@ -0,0 +1,6 @@
describe("Noop test", () => {
it("noop check", async () => {
expect(true).toBe(true)
})
})
@@ -28,7 +28,6 @@ import {
} from "@medusajs/utils"
import {
Currency,
MoneyAmount,
PriceList,
PriceListRule,
@@ -55,7 +54,6 @@ import { ServiceTypes } from "@types"
type InjectedDependencies = {
baseRepository: DAL.RepositoryService
pricingRepository: PricingRepositoryService
currencyService: ModulesSdkTypes.InternalModuleService<any>
moneyAmountService: ModulesSdkTypes.InternalModuleService<any>
priceSetService: ModulesSdkTypes.InternalModuleService<any>
priceSetMoneyAmountRulesService: ModulesSdkTypes.InternalModuleService<any>
@@ -69,7 +67,6 @@ type InjectedDependencies = {
}
const generateMethodForModels = [
Currency,
MoneyAmount,
PriceList,
PriceListRule,
@@ -84,7 +81,6 @@ const generateMethodForModels = [
export default class PricingModuleService<
TPriceSet extends PriceSet = PriceSet,
TMoneyAmount extends MoneyAmount = MoneyAmount,
TCurrency extends Currency = Currency,
TRuleType extends RuleType = RuleType,
TPriceSetMoneyAmountRules extends PriceSetMoneyAmountRules = PriceSetMoneyAmountRules,
TPriceRule extends PriceRule = PriceRule,
@@ -98,7 +94,6 @@ export default class PricingModuleService<
InjectedDependencies,
PricingTypes.PriceSetDTO,
{
Currency: { dto: PricingTypes.CurrencyDTO }
MoneyAmount: { dto: PricingTypes.MoneyAmountDTO }
PriceSetMoneyAmount: { dto: PricingTypes.PriceSetMoneyAmountDTO }
PriceSetMoneyAmountRules: {
@@ -114,7 +109,6 @@ export default class PricingModuleService<
{
protected baseRepository_: DAL.RepositoryService
protected readonly pricingRepository_: PricingRepositoryService
protected readonly currencyService_: ModulesSdkTypes.InternalModuleService<TCurrency>
protected readonly moneyAmountService_: ModulesSdkTypes.InternalModuleService<TMoneyAmount>
protected readonly ruleTypeService_: RuleTypeService<TRuleType>
protected readonly priceSetService_: ModulesSdkTypes.InternalModuleService<TPriceSet>
@@ -131,7 +125,6 @@ export default class PricingModuleService<
baseRepository,
pricingRepository,
moneyAmountService,
currencyService,
ruleTypeService,
priceSetService,
priceSetMoneyAmountRulesService,
@@ -149,7 +142,6 @@ export default class PricingModuleService<
this.baseRepository_ = baseRepository
this.pricingRepository_ = pricingRepository
this.currencyService_ = currencyService
this.moneyAmountService_ = moneyAmountService
this.ruleTypeService_ = ruleTypeService
this.priceSetService_ = priceSetService
@@ -749,36 +741,6 @@ export default class PricingModuleService<
)
}
@InjectTransactionManager("baseRepository_")
async createCurrencies(
data: PricingTypes.CreateCurrencyDTO[],
@MedusaContext() sharedContext: Context = {}
) {
const currencies = await this.currencyService_.create(data, sharedContext)
return await this.baseRepository_.serialize<PricingTypes.CurrencyDTO[]>(
currencies,
{
populate: true,
}
)
}
@InjectTransactionManager("baseRepository_")
async updateCurrencies(
data: PricingTypes.UpdateCurrencyDTO[],
@MedusaContext() sharedContext: Context = {}
) {
const currencies = await this.currencyService_.update(data, sharedContext)
return await this.baseRepository_.serialize<PricingTypes.CurrencyDTO[]>(
currencies,
{
populate: true,
}
)
}
@InjectTransactionManager("baseRepository_")
async createRuleTypes(
data: PricingTypes.CreateRuleTypeDTO[],
@@ -1,13 +0,0 @@
export interface CreateCurrencyDTO {
code: string
symbol: string
symbol_native: string
name: string
}
export interface UpdateCurrencyDTO {
code: string
symbol?: string
symbol_native?: string
name?: string
}
@@ -1,4 +1,3 @@
export * from "./currency"
export * from "./money-amount"
export * from "./price-list-rule-value"
export * from "./price-list-rule"
@@ -1,9 +1,6 @@
import { Currency } from "@models"
export interface CreateMoneyAmountDTO {
id?: string
currency_code: string
currency?: Currency
amount: number
min_quantity?: number | null
max_quantity?: number | null
@@ -1,27 +0,0 @@
import { BaseFilterable } from "@medusajs/types"
export interface CreateCurrencyDTO {
code: string
symbol: string
symbol_native: string
name: string
}
export interface UpdateCurrencyDTO {
code: string
symbol?: string
symbol_native?: string
name?: string
}
export interface FilterableCurrencyProps
extends BaseFilterable<FilterableCurrencyProps> {
code?: string[]
}
export interface CurrencyDTO {
code: string
symbol?: string
symbol_native?: string
name?: string
}
+1 -2
View File
@@ -1,4 +1,3 @@
export * from "./currency"
export * from "./money-amount"
export * from "./price-list-rule-value"
export * from "./price-list-rule"
@@ -9,4 +8,4 @@ export * from "./price-set-money-amount"
export * from "./price-set-rule-type"
export * from "./price-set"
export * from "./pricing"
export * from "./rule-type"
export * from "./rule-type"
@@ -1,14 +1,8 @@
import {
BaseFilterable,
CreateCurrencyDTO,
CurrencyDTO,
PriceSetMoneyAmountDTO,
} from "@medusajs/types"
import { BaseFilterable, PriceSetMoneyAmountDTO } from "@medusajs/types"
export interface CreateMoneyAmountDTO {
id?: string
currency_code: string
currency?: CreateCurrencyDTO
amount: number
min_quantity?: number | null
max_quantity?: number | null
@@ -25,7 +19,6 @@ export interface UpdateMoneyAmountDTO {
export interface MoneyAmountDTO {
id: string
currency_code?: string
currency?: CurrencyDTO
amount?: number
min_quantity?: number
max_quantity?: number