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
2024-02-29 15:09:59 +00:00
committed by GitHub
parent 06f706a51a
commit dc025302a1
102 changed files with 1502 additions and 2128 deletions
+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