feat(pricing, types, utils, medusa-sdk): Pricing Module Setup + Currency (#4860)
What: - Setups the skeleton for pricing module - Creates service/model/repository for currency model - Setups types - Setups DB - Moved some utils to a common place RESOLVES CORE-1477 RESOLVES CORE-1476
This commit is contained in:
8
.changeset/itchy-worms-press.md
Normal file
8
.changeset/itchy-worms-press.md
Normal file
@@ -0,0 +1,8 @@
|
||||
---
|
||||
"@medusajs/modules-sdk": patch
|
||||
"@medusajs/pricing": patch
|
||||
"@medusajs/types": patch
|
||||
"@medusajs/utils": patch
|
||||
---
|
||||
|
||||
feat(pricing, types, utils, medusa-sdk): Pricing Module Setup + Currency service
|
||||
@@ -1,9 +0,0 @@
|
||||
{
|
||||
"plugins": ["@babel/plugin-proposal-class-properties"],
|
||||
"presets": ["@babel/preset-env"],
|
||||
"env": {
|
||||
"test": {
|
||||
"plugins": ["@babel/plugin-transform-runtime"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,10 +9,11 @@
|
||||
"directory": "packages/medusa-test-utils"
|
||||
},
|
||||
"scripts": {
|
||||
"prepublishOnly": "cross-env NODE_ENV=production tsc --build",
|
||||
"prepare": "cross-env NODE_ENV=production yarn run build",
|
||||
"test": "jest --passWithNoTests src",
|
||||
"build": "babel src --out-dir dist/ --ignore '**/__tests__','**/__mocks__'",
|
||||
"watch": "babel -w src --out-dir dist/ --ignore '**/__tests__','**/__mocks__'"
|
||||
"build": "rimraf dist && tsc --build",
|
||||
"watch": "tsc --build --watch",
|
||||
"test": "jest --passWithNoTests src"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
@@ -20,18 +21,16 @@
|
||||
"author": "Sebastian Rindom",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@babel/cli": "^7.7.5",
|
||||
"@babel/core": "^7.7.5",
|
||||
"@babel/plugin-proposal-class-properties": "^7.7.4",
|
||||
"@babel/plugin-transform-runtime": "^7.7.6",
|
||||
"@babel/preset-env": "^7.7.5",
|
||||
"@babel/runtime": "^7.9.6",
|
||||
"cross-env": "^5.2.1",
|
||||
"jest": "^25.5.4"
|
||||
"jest": "^25.5.4",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^5.1.6"
|
||||
},
|
||||
"dependencies": {
|
||||
"@babel/plugin-transform-classes": "^7.9.5",
|
||||
"@mikro-orm/migrations": "5.7.12",
|
||||
"@mikro-orm/postgresql": "5.7.12",
|
||||
"medusa-core-utils": "^1.2.0",
|
||||
"pg-god": "^1.0.12",
|
||||
"randomatic": "^3.1.1"
|
||||
},
|
||||
"gitHead": "81a7ff73d012fda722f6e9ef0bd9ba0232d37808"
|
||||
|
||||
111
packages/medusa-test-utils/src/database.ts
Normal file
111
packages/medusa-test-utils/src/database.ts
Normal file
@@ -0,0 +1,111 @@
|
||||
import { TSMigrationGenerator } from "@mikro-orm/migrations"
|
||||
import { MikroORM, Options, SqlEntityManager } from "@mikro-orm/postgresql"
|
||||
import * as process from "process"
|
||||
|
||||
export function getDatabaseURL(): string {
|
||||
const DB_HOST = process.env.DB_HOST ?? "localhost"
|
||||
const DB_USERNAME = process.env.DB_USERNAME ?? ""
|
||||
const DB_PASSWORD = process.env.DB_PASSWORD
|
||||
const DB_NAME = process.env.DB_TEMP_NAME
|
||||
|
||||
return `postgres://${DB_USERNAME}${
|
||||
DB_PASSWORD ? `:${DB_PASSWORD}` : ""
|
||||
}@${DB_HOST}/${DB_NAME}`
|
||||
}
|
||||
|
||||
export function getMikroOrmConfig(
|
||||
mikroOrmEntities: any[],
|
||||
pathToMigrations: string
|
||||
): Options {
|
||||
const DB_URL = getDatabaseURL()
|
||||
|
||||
return {
|
||||
type: "postgresql",
|
||||
clientUrl: DB_URL,
|
||||
entities: Object.values(mikroOrmEntities),
|
||||
schema: process.env.MEDUSA_DB_SCHEMA,
|
||||
debug: false,
|
||||
migrations: {
|
||||
path: pathToMigrations,
|
||||
pathTs: pathToMigrations,
|
||||
glob: "!(*.d).{js,ts}",
|
||||
silent: true,
|
||||
dropTables: true,
|
||||
transactional: true,
|
||||
allOrNothing: true,
|
||||
safe: false,
|
||||
generator: TSMigrationGenerator,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export interface TestDatabase {
|
||||
orm: MikroORM | null
|
||||
manager: SqlEntityManager | null
|
||||
|
||||
setupDatabase(): Promise<void>
|
||||
clearDatabase(): Promise<void>
|
||||
getManager(): SqlEntityManager
|
||||
forkManager(): SqlEntityManager
|
||||
getOrm(): MikroORM
|
||||
}
|
||||
|
||||
export function getMikroOrmWrapper(
|
||||
mikroOrmEntities: any[],
|
||||
pathToMigrations: string
|
||||
): TestDatabase {
|
||||
return {
|
||||
orm: null,
|
||||
manager: null,
|
||||
|
||||
getManager() {
|
||||
if (this.manager === null) {
|
||||
throw new Error("manager entity not available")
|
||||
}
|
||||
|
||||
return this.manager
|
||||
},
|
||||
|
||||
forkManager() {
|
||||
if (this.manager === null) {
|
||||
throw new Error("manager entity not available")
|
||||
}
|
||||
|
||||
return this.manager.fork()
|
||||
},
|
||||
|
||||
getOrm() {
|
||||
if (this.orm === null) {
|
||||
throw new Error("orm entity not available")
|
||||
}
|
||||
|
||||
return this.orm
|
||||
},
|
||||
|
||||
async setupDatabase() {
|
||||
const OrmConfig = getMikroOrmConfig(mikroOrmEntities, pathToMigrations)
|
||||
|
||||
// Initializing the ORM
|
||||
this.orm = await MikroORM.init(OrmConfig)
|
||||
|
||||
if (this.orm === null) {
|
||||
throw new Error("ORM not configured")
|
||||
}
|
||||
|
||||
this.manager = await this.orm.em
|
||||
|
||||
await this.orm.schema.refreshDatabase() // ensure db exists and is fresh
|
||||
},
|
||||
|
||||
async clearDatabase() {
|
||||
if (this.orm === null) {
|
||||
throw new Error("ORM not configured")
|
||||
}
|
||||
|
||||
await this.orm.close()
|
||||
|
||||
this.orm = null
|
||||
this.manager = null
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,19 +1,19 @@
|
||||
import randomize from "randomatic";
|
||||
import randomize from "randomatic"
|
||||
|
||||
class IdMap {
|
||||
ids = {};
|
||||
ids = {}
|
||||
|
||||
getId(key, prefix = "", length = 10) {
|
||||
if (this.ids[key]) {
|
||||
return this.ids[key];
|
||||
return this.ids[key]
|
||||
}
|
||||
|
||||
const id = `${prefix && prefix + "_"}${randomize("Aa0", length)}`;
|
||||
this.ids[key] = id;
|
||||
const id = `${prefix && prefix + "_"}${randomize("Aa0", length)}`
|
||||
this.ids[key] = id
|
||||
|
||||
return id;
|
||||
return id
|
||||
}
|
||||
}
|
||||
|
||||
const instance = new IdMap();
|
||||
export default instance;
|
||||
const instance = new IdMap()
|
||||
export default instance
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
export { default as IdMap } from "./id-map";
|
||||
export { default as MockRepository } from "./mock-repository";
|
||||
export { default as MockManager } from "./mock-manager";
|
||||
5
packages/medusa-test-utils/src/index.ts
Normal file
5
packages/medusa-test-utils/src/index.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export * as TestDatabaseUtils from "./database"
|
||||
export { default as IdMap } from "./id-map"
|
||||
export * as JestUtils from "./jest"
|
||||
export { default as MockManager } from "./mock-manager"
|
||||
export { default as MockRepository } from "./mock-repository"
|
||||
24
packages/medusa-test-utils/src/jest.ts
Normal file
24
packages/medusa-test-utils/src/jest.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { dropDatabase } from "pg-god"
|
||||
|
||||
export function afterAllHookDropDatabase() {
|
||||
const DB_HOST = process.env.DB_HOST ?? "localhost"
|
||||
const DB_USERNAME = process.env.DB_USERNAME ?? "postgres"
|
||||
const DB_PASSWORD = process.env.DB_PASSWORD ?? ""
|
||||
const DB_NAME = process.env.DB_TEMP_NAME || ""
|
||||
|
||||
const pgGodCredentials = {
|
||||
user: DB_USERNAME,
|
||||
password: DB_PASSWORD,
|
||||
host: DB_HOST,
|
||||
}
|
||||
|
||||
afterAll(async () => {
|
||||
try {
|
||||
await dropDatabase({ databaseName: DB_NAME }, pgGodCredentials)
|
||||
} catch (e) {
|
||||
console.error(
|
||||
`This might fail if it is run during the unit tests since there is no database to drop. Otherwise, please check what is the issue. ${e.message}`
|
||||
)
|
||||
}
|
||||
})
|
||||
}
|
||||
23
packages/medusa-test-utils/tsconfig.json
Normal file
23
packages/medusa-test-utils/tsconfig.json
Normal file
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"lib": ["es5", "es6", "es2019"],
|
||||
"target": "es5",
|
||||
"outDir": "./dist",
|
||||
"esModuleInterop": true,
|
||||
"declaration": false,
|
||||
"module": "commonjs",
|
||||
"moduleResolution": "node",
|
||||
"emitDecoratorMetadata": true,
|
||||
"experimentalDecorators": true,
|
||||
"sourceMap": true,
|
||||
"noImplicitReturns": true,
|
||||
"strictNullChecks": true,
|
||||
"strictFunctionTypes": true,
|
||||
"noImplicitThis": true,
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"downlevelIteration": true
|
||||
},
|
||||
"include": ["src"],
|
||||
"exclude": ["dist", "node_modules"]
|
||||
}
|
||||
@@ -10,6 +10,7 @@ export enum Modules {
|
||||
INVENTORY = "inventoryService",
|
||||
CACHE = "cacheService",
|
||||
PRODUCT = "productService",
|
||||
PRICING = "pricingService",
|
||||
}
|
||||
|
||||
export enum ModuleRegistrationName {
|
||||
@@ -18,6 +19,7 @@ export enum ModuleRegistrationName {
|
||||
INVENTORY = "inventoryService",
|
||||
CACHE = "cacheService",
|
||||
PRODUCT = "productModuleService",
|
||||
PRICING = "pricingModuleService",
|
||||
}
|
||||
|
||||
export const MODULE_PACKAGE_NAMES = {
|
||||
@@ -26,6 +28,7 @@ export const MODULE_PACKAGE_NAMES = {
|
||||
[Modules.STOCK_LOCATION]: "@medusajs/stock-location",
|
||||
[Modules.INVENTORY]: "@medusajs/inventory",
|
||||
[Modules.CACHE]: "@medusajs/cache-inmemory",
|
||||
[Modules.PRICING]: "@medusajs/pricing",
|
||||
}
|
||||
|
||||
export const ModulesDefinition: { [key: string | Modules]: ModuleDefinition } =
|
||||
@@ -97,6 +100,20 @@ export const ModulesDefinition: { [key: string | Modules]: ModuleDefinition } =
|
||||
resources: MODULE_RESOURCE_TYPE.SHARED,
|
||||
},
|
||||
},
|
||||
[Modules.PRICING]: {
|
||||
key: Modules.PRICING,
|
||||
registrationName: ModuleRegistrationName.PRICING,
|
||||
defaultPackage: false,
|
||||
label: "PricingModuleService",
|
||||
isRequired: false,
|
||||
canOverride: true,
|
||||
isQueryable: true,
|
||||
dependencies: ["logger"],
|
||||
defaultModuleDeclaration: {
|
||||
scope: MODULE_SCOPE.INTERNAL,
|
||||
resources: MODULE_RESOURCE_TYPE.SHARED,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
export const MODULE_DEFINITIONS: ModuleDefinition[] =
|
||||
|
||||
6
packages/pricing/.gitignore
vendored
Normal file
6
packages/pricing/.gitignore
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
/dist
|
||||
node_modules
|
||||
.DS_store
|
||||
.env*
|
||||
.env
|
||||
*.sql
|
||||
0
packages/pricing/CHANGELOG.md
Normal file
0
packages/pricing/CHANGELOG.md
Normal file
3
packages/pricing/README.md
Normal file
3
packages/pricing/README.md
Normal file
@@ -0,0 +1,3 @@
|
||||
# Pricing Module
|
||||
|
||||
The Pricing Module gives you access MoneyAmounts, Currency and PriceList through a standalone package that can be installed and run in Next.js functions and other Node.js compatible runtimes.
|
||||
@@ -0,0 +1,20 @@
|
||||
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",
|
||||
},
|
||||
]
|
||||
@@ -0,0 +1,20 @@
|
||||
import { SqlEntityManager } from "@mikro-orm/postgresql"
|
||||
import { Currency } from "@models"
|
||||
import { defaultCurrencyData } 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
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
import { SqlEntityManager } from "@mikro-orm/postgresql"
|
||||
|
||||
import { Currency } from "@models"
|
||||
import { CurrencyRepository } from "@repositories"
|
||||
import { CurrencyService } from "@services"
|
||||
|
||||
import { createCurrencies } from "../../../__fixtures__/currency"
|
||||
import { MikroOrmWrapper } from "../../../utils"
|
||||
|
||||
jest.setTimeout(30000)
|
||||
|
||||
describe("Currency Service", () => {
|
||||
let service: CurrencyService
|
||||
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 currencyRepository = new CurrencyRepository({
|
||||
manager: repositoryManager,
|
||||
})
|
||||
|
||||
service = new CurrencyService({
|
||||
currencyRepository,
|
||||
})
|
||||
|
||||
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: "USD",
|
||||
name: "US Dollar",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
code: "CAD",
|
||||
name: "Canadian 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: "USD",
|
||||
name: "US Dollar",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
code: "CAD",
|
||||
name: "Canadian 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: "CAD",
|
||||
name: "Canadian 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: "USD",
|
||||
},
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
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('"currencyCode" 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",
|
||||
})
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,269 @@
|
||||
import { initialize } from "../../../../src"
|
||||
|
||||
import { IPricingModuleService } from "@medusajs/types"
|
||||
|
||||
import { SqlEntityManager } from "@mikro-orm/postgresql"
|
||||
|
||||
import { Currency } from "@models"
|
||||
|
||||
import { createCurrencies } from "../../../__fixtures__/currency"
|
||||
import { DB_URL, MikroOrmWrapper } from "../../../utils"
|
||||
|
||||
describe("PricingModuleService currency", () => {
|
||||
let service: IPricingModuleService
|
||||
let testManager: SqlEntityManager
|
||||
let repositoryManager: SqlEntityManager
|
||||
let data!: Currency[]
|
||||
|
||||
beforeEach(async () => {
|
||||
await MikroOrmWrapper.setupDatabase()
|
||||
repositoryManager = MikroOrmWrapper.forkManager()
|
||||
|
||||
service = await initialize({
|
||||
database: {
|
||||
clientUrl: DB_URL,
|
||||
schema: process.env.MEDUSA_PRICING_DB_SCHEMA,
|
||||
},
|
||||
})
|
||||
|
||||
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: "USD",
|
||||
name: "US Dollar",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
code: "CAD",
|
||||
name: "Canadian Dollar",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
code: "EUR",
|
||||
name: "Euro",
|
||||
}),
|
||||
])
|
||||
})
|
||||
|
||||
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: "USD",
|
||||
name: "US Dollar",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
code: "CAD",
|
||||
name: "Canadian Dollar",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
code: "EUR",
|
||||
name: "Euro",
|
||||
}),
|
||||
])
|
||||
})
|
||||
|
||||
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: "CAD",
|
||||
name: "Canadian Dollar",
|
||||
}),
|
||||
])
|
||||
})
|
||||
|
||||
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: "USD",
|
||||
},
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
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('"currencyCode" 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",
|
||||
})
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
6
packages/pricing/integration-tests/setup-env.js
Normal file
6
packages/pricing/integration-tests/setup-env.js
Normal file
@@ -0,0 +1,6 @@
|
||||
if (typeof process.env.DB_TEMP_NAME === "undefined") {
|
||||
const tempName = parseInt(process.env.JEST_WORKER_ID || "1")
|
||||
process.env.DB_TEMP_NAME = `medusa-integration-${tempName}`
|
||||
}
|
||||
|
||||
process.env.MEDUSA_PRICING_DB_SCHEMA = "public"
|
||||
3
packages/pricing/integration-tests/setup.js
Normal file
3
packages/pricing/integration-tests/setup.js
Normal file
@@ -0,0 +1,3 @@
|
||||
import { JestUtils } from "medusa-test-utils"
|
||||
|
||||
JestUtils.afterAllHookDropDatabase()
|
||||
6
packages/pricing/integration-tests/utils/config.ts
Normal file
6
packages/pricing/integration-tests/utils/config.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
import { ModuleServiceInitializeOptions } from "@medusajs/types"
|
||||
|
||||
export const databaseOptions: ModuleServiceInitializeOptions["database"] = {
|
||||
schema: "public",
|
||||
clientUrl: "medusa-pricing-test",
|
||||
}
|
||||
18
packages/pricing/integration-tests/utils/database.ts
Normal file
18
packages/pricing/integration-tests/utils/database.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { TestDatabaseUtils } from "medusa-test-utils"
|
||||
|
||||
import * as PricingModels from "@models"
|
||||
|
||||
const pathToMigrations = "../../src/migrations"
|
||||
const mikroOrmEntities = PricingModels as unknown as any[]
|
||||
|
||||
export const MikroOrmWrapper = TestDatabaseUtils.getMikroOrmWrapper(
|
||||
mikroOrmEntities,
|
||||
pathToMigrations
|
||||
)
|
||||
|
||||
export const MikroOrmConfig = TestDatabaseUtils.getMikroOrmConfig(
|
||||
mikroOrmEntities,
|
||||
pathToMigrations
|
||||
)
|
||||
|
||||
export const DB_URL = TestDatabaseUtils.getDatabaseURL()
|
||||
1
packages/pricing/integration-tests/utils/index.ts
Normal file
1
packages/pricing/integration-tests/utils/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from "./database"
|
||||
21
packages/pricing/jest.config.js
Normal file
21
packages/pricing/jest.config.js
Normal file
@@ -0,0 +1,21 @@
|
||||
module.exports = {
|
||||
moduleNameMapper: {
|
||||
"^@models": "<rootDir>/src/models",
|
||||
"^@services": "<rootDir>/src/services",
|
||||
"^@repositories": "<rootDir>/src/repositories",
|
||||
},
|
||||
transform: {
|
||||
"^.+\\.[jt]s?$": [
|
||||
"ts-jest",
|
||||
{
|
||||
tsConfig: "tsconfig.spec.json",
|
||||
isolatedModules: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
testEnvironment: `node`,
|
||||
moduleFileExtensions: [`js`, `ts`],
|
||||
modulePathIgnorePatterns: ["dist/"],
|
||||
setupFiles: ["<rootDir>/integration-tests/setup-env.js"],
|
||||
setupFilesAfterEnv: ["<rootDir>/integration-tests/setup.js"],
|
||||
}
|
||||
8
packages/pricing/mikro-orm.config.dev.ts
Normal file
8
packages/pricing/mikro-orm.config.dev.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import * as entities from "./src/models"
|
||||
|
||||
module.exports = {
|
||||
entities: Object.values(entities),
|
||||
schema: "public",
|
||||
clientUrl: "postgres://postgres@localhost/medusa-pricing",
|
||||
type: "postgresql",
|
||||
}
|
||||
60
packages/pricing/package.json
Normal file
60
packages/pricing/package.json
Normal file
@@ -0,0 +1,60 @@
|
||||
{
|
||||
"name": "@medusajs/pricing",
|
||||
"version": "0.0.1",
|
||||
"description": "Medusa Pricing module",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"bin": {
|
||||
"medusa-pricing-migrations-down": "dist/scripts/bin/run-migration-down.js",
|
||||
"medusa-pricing-migrations-up": "dist/scripts/bin/run-migration-up.js",
|
||||
"medusa-pricing-seed": "dist/scripts/bin/run-seed.js"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/medusajs/medusa",
|
||||
"directory": "packages/pricing"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"author": "Medusa",
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"watch": "tsc --build --watch",
|
||||
"watch:test": "tsc --build tsconfig.spec.json --watch",
|
||||
"prepublishOnly": "cross-env NODE_ENV=production tsc --build && tsc-alias -p tsconfig.json",
|
||||
"build": "rimraf dist && tsc --build && tsc-alias -p tsconfig.json",
|
||||
"test": "jest --runInBand --bail --forceExit -- src/**/__tests__/**/*.ts",
|
||||
"test:integration": "jest --runInBand --forceExit -- integration-tests/**/__tests__/**/*.ts",
|
||||
"migration:generate": " MIKRO_ORM_CLI=./mikro-orm.config.dev.ts mikro-orm migration:generate",
|
||||
"migration:initial": " MIKRO_ORM_CLI=./mikro-orm.config.dev.ts mikro-orm migration:create --initial",
|
||||
"migration:create": " MIKRO_ORM_CLI=./mikro-orm.config.dev.ts mikro-orm migration:create",
|
||||
"migration:up": " MIKRO_ORM_CLI=./mikro-orm.config.dev.ts mikro-orm migration:up",
|
||||
"orm:cache:clear": " MIKRO_ORM_CLI=./mikro-orm.config.dev.ts mikro-orm cache:clear"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@mikro-orm/cli": "5.7.12",
|
||||
"cross-env": "^5.2.1",
|
||||
"jest": "^29.6.3",
|
||||
"medusa-test-utils": "^1.1.40",
|
||||
"rimraf": "^3.0.2",
|
||||
"ts-jest": "^29.1.1",
|
||||
"ts-node": "^10.9.1",
|
||||
"tsc-alias": "^1.8.6",
|
||||
"typescript": "^5.1.6"
|
||||
},
|
||||
"dependencies": {
|
||||
"@medusajs/modules-sdk": "^1.9.2",
|
||||
"@medusajs/types": "^1.10.2",
|
||||
"@medusajs/utils": "^1.9.7",
|
||||
"@mikro-orm/core": "5.7.12",
|
||||
"@mikro-orm/migrations": "5.7.12",
|
||||
"@mikro-orm/postgresql": "5.7.12",
|
||||
"awilix": "^8.0.0",
|
||||
"dotenv": "^16.1.4",
|
||||
"knex": "2.4.2"
|
||||
}
|
||||
}
|
||||
10
packages/pricing/src/index.ts
Normal file
10
packages/pricing/src/index.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { moduleDefinition } from "./module-definition"
|
||||
|
||||
export default moduleDefinition
|
||||
|
||||
export * from "./scripts"
|
||||
export * from "./initialize"
|
||||
export * from "./types"
|
||||
export * from "./loaders"
|
||||
export * from "./models"
|
||||
export * from "./services"
|
||||
31
packages/pricing/src/initialize/index.ts
Normal file
31
packages/pricing/src/initialize/index.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import {
|
||||
ExternalModuleDeclaration,
|
||||
InternalModuleDeclaration,
|
||||
MedusaModule,
|
||||
MODULE_PACKAGE_NAMES,
|
||||
Modules,
|
||||
} from "@medusajs/modules-sdk"
|
||||
import { IPricingModuleService, ModulesSdkTypes } from "@medusajs/types"
|
||||
import { moduleDefinition } from "../module-definition"
|
||||
import { InitializeModuleInjectableDependencies } from "../types"
|
||||
|
||||
export const initialize = async (
|
||||
options?:
|
||||
| ModulesSdkTypes.ModuleServiceInitializeOptions
|
||||
| ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions
|
||||
| ExternalModuleDeclaration
|
||||
| InternalModuleDeclaration,
|
||||
injectedDependencies?: InitializeModuleInjectableDependencies
|
||||
): Promise<IPricingModuleService> => {
|
||||
const serviceKey = Modules.PRICING
|
||||
|
||||
const loaded = await MedusaModule.bootstrap<IPricingModuleService>(
|
||||
serviceKey,
|
||||
MODULE_PACKAGE_NAMES[Modules.PRICING],
|
||||
options as InternalModuleDeclaration | ExternalModuleDeclaration,
|
||||
moduleDefinition,
|
||||
injectedDependencies
|
||||
)
|
||||
|
||||
return loaded[serviceKey]
|
||||
}
|
||||
38
packages/pricing/src/joiner-config.ts
Normal file
38
packages/pricing/src/joiner-config.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { Modules } from "@medusajs/modules-sdk"
|
||||
import { JoinerServiceConfig } from "@medusajs/types"
|
||||
import { MapToConfig } from "@medusajs/utils"
|
||||
import { Currency } from "@models"
|
||||
|
||||
export enum LinkableKeys {
|
||||
MONEY_AMOUNT_ID = "money_amount_id",
|
||||
CURRENCY_CODE = "code",
|
||||
}
|
||||
|
||||
export const entityNameToLinkableKeysMap: MapToConfig = {
|
||||
[Currency.name]: [{ mapTo: LinkableKeys.CURRENCY_CODE, valueFrom: "code" }],
|
||||
}
|
||||
|
||||
export const joinerConfig: JoinerServiceConfig = {
|
||||
serviceName: Modules.PRICING,
|
||||
primaryKeys: ["code"],
|
||||
alias: [
|
||||
// {
|
||||
// name: "money_amount",
|
||||
// },
|
||||
// {
|
||||
// name: "money_amounts",
|
||||
// },
|
||||
{
|
||||
name: "currency",
|
||||
args: {
|
||||
methodSuffix: "Currencies",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "currencies",
|
||||
args: {
|
||||
methodSuffix: "Currencies",
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
27
packages/pricing/src/loaders/connection.ts
Normal file
27
packages/pricing/src/loaders/connection.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { InternalModuleDeclaration, LoaderOptions } from "@medusajs/modules-sdk"
|
||||
import { ModulesSdkTypes } from "@medusajs/types"
|
||||
import { ModulesSdkUtils } from "@medusajs/utils"
|
||||
import { EntitySchema } from "@mikro-orm/core"
|
||||
import * as PricingModels from "../models"
|
||||
|
||||
export default async (
|
||||
{
|
||||
options,
|
||||
container,
|
||||
logger,
|
||||
}: LoaderOptions<
|
||||
| ModulesSdkTypes.ModuleServiceInitializeOptions
|
||||
| ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions
|
||||
>,
|
||||
moduleDeclaration?: InternalModuleDeclaration
|
||||
): Promise<void> => {
|
||||
const entities = Object.values(PricingModels) as unknown as EntitySchema[]
|
||||
|
||||
await ModulesSdkUtils.mikroOrmConnectionLoader({
|
||||
entities,
|
||||
container,
|
||||
options,
|
||||
moduleDeclaration,
|
||||
logger,
|
||||
})
|
||||
}
|
||||
41
packages/pricing/src/loaders/container.ts
Normal file
41
packages/pricing/src/loaders/container.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { ModulesSdkTypes } from "@medusajs/types"
|
||||
import * as defaultRepositories from "@repositories"
|
||||
import { BaseRepository, CurrencyRepository } from "@repositories"
|
||||
import { CurrencyService } from "@services"
|
||||
|
||||
import { LoaderOptions } from "@medusajs/modules-sdk"
|
||||
import { loadCustomRepositories } from "@medusajs/utils"
|
||||
import { asClass } from "awilix"
|
||||
|
||||
export default async ({
|
||||
container,
|
||||
options,
|
||||
}: LoaderOptions<
|
||||
| ModulesSdkTypes.ModuleServiceInitializeOptions
|
||||
| ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions
|
||||
>): Promise<void> => {
|
||||
const customRepositories = (
|
||||
options as ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions
|
||||
)?.repositories
|
||||
|
||||
container.register({
|
||||
currencyService: asClass(CurrencyService).singleton(),
|
||||
})
|
||||
|
||||
if (customRepositories) {
|
||||
loadCustomRepositories({
|
||||
defaultRepositories,
|
||||
customRepositories,
|
||||
container,
|
||||
})
|
||||
} else {
|
||||
loadDefaultRepositories({ container })
|
||||
}
|
||||
}
|
||||
|
||||
function loadDefaultRepositories({ container }) {
|
||||
container.register({
|
||||
baseRepository: asClass(BaseRepository).singleton(),
|
||||
currencyRepository: asClass(CurrencyRepository).singleton(),
|
||||
})
|
||||
}
|
||||
2
packages/pricing/src/loaders/index.ts
Normal file
2
packages/pricing/src/loaders/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from "./connection"
|
||||
export * from "./container"
|
||||
@@ -0,0 +1,63 @@
|
||||
{
|
||||
"namespaces": [
|
||||
"public"
|
||||
],
|
||||
"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": {}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Migration } from '@mikro-orm/migrations';
|
||||
|
||||
export class Migration20230828182018 extends Migration {
|
||||
|
||||
async up(): Promise<void> {
|
||||
this.addSql('create table "currency" ("code" text not null, "symbol" text not null, "symbol_native" text not null, "name" text not null, constraint "currency_pkey" primary key ("code"));');
|
||||
}
|
||||
|
||||
}
|
||||
27
packages/pricing/src/models/currency.ts
Normal file
27
packages/pricing/src/models/currency.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
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
|
||||
|
||||
// @Property({ persist: false })
|
||||
// get includes_tax() {
|
||||
// // TODO: This comes from a feature flag
|
||||
// // Figure out how we're handling FF in modules
|
||||
// // For now, returning default as true
|
||||
// // This should also not fall on the hands of the model
|
||||
// return true
|
||||
// }
|
||||
}
|
||||
|
||||
export default Currency
|
||||
1
packages/pricing/src/models/index.ts
Normal file
1
packages/pricing/src/models/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { default as Currency } from "./currency"
|
||||
12
packages/pricing/src/module-definition.ts
Normal file
12
packages/pricing/src/module-definition.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { ModuleExports } from "@medusajs/types"
|
||||
import { PricingModuleService } from "@services"
|
||||
import loadConnection from "./loaders/connection"
|
||||
import loadContainer from "./loaders/container"
|
||||
|
||||
const service = PricingModuleService
|
||||
const loaders = [loadContainer, loadConnection] as any
|
||||
|
||||
export const moduleDefinition: ModuleExports = {
|
||||
service,
|
||||
loaders,
|
||||
}
|
||||
127
packages/pricing/src/repositories/currency.ts
Normal file
127
packages/pricing/src/repositories/currency.ts
Normal file
@@ -0,0 +1,127 @@
|
||||
import {
|
||||
Context,
|
||||
CreateCurrencyDTO,
|
||||
DAL,
|
||||
UpdateCurrencyDTO,
|
||||
} from "@medusajs/types"
|
||||
import { DALUtils, MedusaError } from "@medusajs/utils"
|
||||
import {
|
||||
LoadStrategy,
|
||||
FilterQuery as MikroFilterQuery,
|
||||
FindOptions as MikroOptions,
|
||||
} from "@mikro-orm/core"
|
||||
import { SqlEntityManager } from "@mikro-orm/postgresql"
|
||||
import { Currency } from "@models"
|
||||
|
||||
export class CurrencyRepository extends DALUtils.MikroOrmBaseRepository {
|
||||
protected readonly manager_: SqlEntityManager
|
||||
|
||||
constructor({ manager }: { manager: SqlEntityManager }) {
|
||||
// @ts-ignore
|
||||
// eslint-disable-next-line prefer-rest-params
|
||||
super(...arguments)
|
||||
this.manager_ = manager
|
||||
}
|
||||
|
||||
async find(
|
||||
findOptions: DAL.FindOptions<Currency> = { where: {} },
|
||||
context: Context = {}
|
||||
): Promise<Currency[]> {
|
||||
const manager = this.getActiveManager<SqlEntityManager>(context)
|
||||
|
||||
const findOptions_ = { ...findOptions }
|
||||
findOptions_.options ??= {}
|
||||
|
||||
Object.assign(findOptions_.options, {
|
||||
strategy: LoadStrategy.SELECT_IN,
|
||||
})
|
||||
|
||||
return await manager.find(
|
||||
Currency,
|
||||
findOptions_.where as MikroFilterQuery<Currency>,
|
||||
findOptions_.options as MikroOptions<Currency>
|
||||
)
|
||||
}
|
||||
|
||||
async findAndCount(
|
||||
findOptions: DAL.FindOptions<Currency> = { where: {} },
|
||||
context: Context = {}
|
||||
): Promise<[Currency[], number]> {
|
||||
const manager = this.getActiveManager<SqlEntityManager>(context)
|
||||
|
||||
const findOptions_ = { ...findOptions }
|
||||
findOptions_.options ??= {}
|
||||
|
||||
Object.assign(findOptions_.options, {
|
||||
strategy: LoadStrategy.SELECT_IN,
|
||||
})
|
||||
|
||||
return await manager.findAndCount(
|
||||
Currency,
|
||||
findOptions_.where as MikroFilterQuery<Currency>,
|
||||
findOptions_.options as MikroOptions<Currency>
|
||||
)
|
||||
}
|
||||
|
||||
async delete(codes: string[], context: Context = {}): Promise<void> {
|
||||
const manager = this.getActiveManager<SqlEntityManager>(context)
|
||||
await manager.nativeDelete(Currency, { code: { $in: codes } }, {})
|
||||
}
|
||||
|
||||
async create(
|
||||
data: CreateCurrencyDTO[],
|
||||
context: Context = {}
|
||||
): Promise<Currency[]> {
|
||||
const manager = this.getActiveManager<SqlEntityManager>(context)
|
||||
|
||||
const currencies = data.map((currencyData) => {
|
||||
return manager.create(Currency, currencyData)
|
||||
})
|
||||
|
||||
manager.persist(currencies)
|
||||
|
||||
return currencies
|
||||
}
|
||||
|
||||
async update(
|
||||
data: UpdateCurrencyDTO[],
|
||||
context: Context = {}
|
||||
): Promise<Currency[]> {
|
||||
const manager = this.getActiveManager<SqlEntityManager>(context)
|
||||
const currencyCodes = data.map((currencyData) => currencyData.code)
|
||||
const existingCurrencies = await this.find(
|
||||
{
|
||||
where: {
|
||||
code: {
|
||||
$in: currencyCodes,
|
||||
},
|
||||
},
|
||||
},
|
||||
context
|
||||
)
|
||||
|
||||
const existingCurrencyMap = new Map(
|
||||
existingCurrencies.map<[string, Currency]>((currency) => [
|
||||
currency.code,
|
||||
currency,
|
||||
])
|
||||
)
|
||||
|
||||
const currencies = data.map((currencyData) => {
|
||||
const existingCurrency = existingCurrencyMap.get(currencyData.code)
|
||||
|
||||
if (!existingCurrency) {
|
||||
throw new MedusaError(
|
||||
MedusaError.Types.NOT_FOUND,
|
||||
`Currency with code "${currencyData.code}" not found`
|
||||
)
|
||||
}
|
||||
|
||||
return manager.assign(existingCurrency, currencyData)
|
||||
})
|
||||
|
||||
manager.persist(currencies)
|
||||
|
||||
return currencies
|
||||
}
|
||||
}
|
||||
2
packages/pricing/src/repositories/index.ts
Normal file
2
packages/pricing/src/repositories/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export { MikroOrmBaseRepository as BaseRepository } from "@medusajs/utils"
|
||||
export { CurrencyRepository } from "./currency"
|
||||
8
packages/pricing/src/scripts/bin/run-migration-down.ts
Normal file
8
packages/pricing/src/scripts/bin/run-migration-down.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
export default (async () => {
|
||||
const { revertMigration } = await import("../migration-down")
|
||||
const { config } = await import("dotenv")
|
||||
config()
|
||||
await revertMigration()
|
||||
})()
|
||||
8
packages/pricing/src/scripts/bin/run-migration-up.ts
Normal file
8
packages/pricing/src/scripts/bin/run-migration-up.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
export default (async () => {
|
||||
const { runMigrations } = await import("../migration-up")
|
||||
const { config } = await import("dotenv")
|
||||
config()
|
||||
await runMigrations()
|
||||
})()
|
||||
19
packages/pricing/src/scripts/bin/run-seed.ts
Normal file
19
packages/pricing/src/scripts/bin/run-seed.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { EOL } from "os"
|
||||
import { run } from "../seed"
|
||||
|
||||
const args = process.argv
|
||||
const path = args.pop() as string
|
||||
|
||||
export default (async () => {
|
||||
const { config } = await import("dotenv")
|
||||
config()
|
||||
if (!path) {
|
||||
throw new Error(
|
||||
`filePath is required.${EOL}Example: medusa-pricing-seed <filePath>`
|
||||
)
|
||||
}
|
||||
|
||||
await run({ path })
|
||||
})()
|
||||
2
packages/pricing/src/scripts/index.ts
Normal file
2
packages/pricing/src/scripts/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from "./migration-up"
|
||||
export * from "./migration-down"
|
||||
39
packages/pricing/src/scripts/migration-down.ts
Normal file
39
packages/pricing/src/scripts/migration-down.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import * as PricingModels from "@models"
|
||||
|
||||
import { LoaderOptions, Logger, ModulesSdkTypes } from "@medusajs/types"
|
||||
|
||||
import { DALUtils, ModulesSdkUtils } from "@medusajs/utils"
|
||||
import { EntitySchema } from "@mikro-orm/core"
|
||||
|
||||
/**
|
||||
* This script is only valid for mikro orm managers. If a user provide a custom manager
|
||||
* he is in charge of reverting the migrations.
|
||||
* @param options
|
||||
* @param logger
|
||||
* @param moduleDeclaration
|
||||
*/
|
||||
export async function revertMigration({
|
||||
options,
|
||||
logger,
|
||||
}: Pick<
|
||||
LoaderOptions<ModulesSdkTypes.ModuleServiceInitializeOptions>,
|
||||
"options" | "logger"
|
||||
> = {}) {
|
||||
logger ??= console as unknown as Logger
|
||||
|
||||
const dbData = ModulesSdkUtils.loadDatabaseConfig("pricing", options)!
|
||||
const entities = Object.values(PricingModels) as unknown as EntitySchema[]
|
||||
|
||||
const orm = await DALUtils.mikroOrmCreateConnection(dbData, entities)
|
||||
|
||||
try {
|
||||
const migrator = orm.getMigrator()
|
||||
await migrator.down()
|
||||
|
||||
logger?.info("Pricing module migration executed")
|
||||
} catch (error) {
|
||||
logger?.error(`Pricing module migration failed to run - Error: ${error}`)
|
||||
}
|
||||
|
||||
await orm.close()
|
||||
}
|
||||
43
packages/pricing/src/scripts/migration-up.ts
Normal file
43
packages/pricing/src/scripts/migration-up.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import { LoaderOptions, Logger, ModulesSdkTypes } from "@medusajs/types"
|
||||
import { DALUtils, ModulesSdkUtils } from "@medusajs/utils"
|
||||
import { EntitySchema } from "@mikro-orm/core"
|
||||
import * as PricingModels from "@models"
|
||||
|
||||
/**
|
||||
* This script is only valid for mikro orm managers. If a user provide a custom manager
|
||||
* he is in charge of running the migrations.
|
||||
* @param options
|
||||
* @param logger
|
||||
* @param moduleDeclaration
|
||||
*/
|
||||
export async function runMigrations({
|
||||
options,
|
||||
logger,
|
||||
}: Pick<
|
||||
LoaderOptions<ModulesSdkTypes.ModuleServiceInitializeOptions>,
|
||||
"options" | "logger"
|
||||
> = {}) {
|
||||
logger ??= console as unknown as Logger
|
||||
|
||||
const dbData = ModulesSdkUtils.loadDatabaseConfig("pricing", options)!
|
||||
const entities = Object.values(PricingModels) as unknown as EntitySchema[]
|
||||
|
||||
const orm = await DALUtils.mikroOrmCreateConnection(dbData, entities)
|
||||
|
||||
try {
|
||||
const migrator = orm.getMigrator()
|
||||
|
||||
const pendingMigrations = await migrator.getPendingMigrations()
|
||||
logger.info(`Running pending migrations: ${pendingMigrations}`)
|
||||
|
||||
await migrator.up({
|
||||
migrations: pendingMigrations.map((m) => m.name),
|
||||
})
|
||||
|
||||
logger.info("Pricing module migration executed")
|
||||
} catch (error) {
|
||||
logger.error(`Pricing module migration failed to run - Error: ${error}`)
|
||||
}
|
||||
|
||||
await orm.close()
|
||||
}
|
||||
64
packages/pricing/src/scripts/seed.ts
Normal file
64
packages/pricing/src/scripts/seed.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
import { LoaderOptions, Logger, ModulesSdkTypes } from "@medusajs/types"
|
||||
import { DALUtils, ModulesSdkUtils } from "@medusajs/utils"
|
||||
import { EntitySchema, RequiredEntityData } from "@mikro-orm/core"
|
||||
import { SqlEntityManager } from "@mikro-orm/postgresql"
|
||||
import * as PricingModels from "@models"
|
||||
import { EOL } from "os"
|
||||
import { resolve } from "path"
|
||||
|
||||
export async function run({
|
||||
options,
|
||||
logger,
|
||||
path,
|
||||
}: Partial<
|
||||
Pick<
|
||||
LoaderOptions<ModulesSdkTypes.ModuleServiceInitializeOptions>,
|
||||
"options" | "logger"
|
||||
>
|
||||
> & {
|
||||
path: string
|
||||
}) {
|
||||
logger ??= console as unknown as Logger
|
||||
|
||||
logger.info(`Loading seed data from ${path}...`)
|
||||
|
||||
const { currenciesData } = 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 currenciesData.${EOL}${e}`
|
||||
)
|
||||
throw e
|
||||
}
|
||||
)
|
||||
|
||||
const dbData = ModulesSdkUtils.loadDatabaseConfig("pricing", options)!
|
||||
const entities = Object.values(PricingModels) as unknown as EntitySchema[]
|
||||
|
||||
const orm = await DALUtils.mikroOrmCreateConnection(dbData, entities)
|
||||
const manager = orm.em.fork()
|
||||
|
||||
try {
|
||||
logger.info("Inserting currencies")
|
||||
|
||||
await createCurrencies(manager, currenciesData)
|
||||
} catch (e) {
|
||||
logger.error(
|
||||
`Failed to insert the seed data in the PostgreSQL database ${dbData.clientUrl}.${EOL}${e}`
|
||||
)
|
||||
}
|
||||
|
||||
await orm.close(true)
|
||||
}
|
||||
|
||||
async function createCurrencies(
|
||||
manager: SqlEntityManager,
|
||||
data: RequiredEntityData<PricingModels.Currency>[]
|
||||
) {
|
||||
const currencies: any[] = data.map((currencyData) => {
|
||||
return manager.create(PricingModels.Currency, currencyData)
|
||||
})
|
||||
|
||||
await manager.persistAndFlush(currencies)
|
||||
|
||||
return currencies
|
||||
}
|
||||
21
packages/pricing/src/services/__fixtures__/currency.ts
Normal file
21
packages/pricing/src/services/__fixtures__/currency.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import { CurrencyService } from "@services"
|
||||
import { asClass, asValue, createContainer } from "awilix"
|
||||
|
||||
export const nonExistingCurrencyCode = "non-existing-code"
|
||||
export const mockContainer = createContainer()
|
||||
|
||||
mockContainer.register({
|
||||
transaction: asValue(async (task) => await task()),
|
||||
currencyRepository: asValue({
|
||||
find: jest.fn().mockImplementation(async ({ where: { code } }) => {
|
||||
if (code === nonExistingCurrencyCode) {
|
||||
return []
|
||||
}
|
||||
|
||||
return [{}]
|
||||
}),
|
||||
findAndCount: jest.fn().mockResolvedValue([[], 0]),
|
||||
getFreshManager: jest.fn().mockResolvedValue({}),
|
||||
}),
|
||||
currencyService: asClass(CurrencyService),
|
||||
})
|
||||
203
packages/pricing/src/services/__tests__/currency.spec.ts
Normal file
203
packages/pricing/src/services/__tests__/currency.spec.ts
Normal file
@@ -0,0 +1,203 @@
|
||||
import {
|
||||
mockContainer,
|
||||
nonExistingCurrencyCode,
|
||||
} from "../__fixtures__/currency"
|
||||
|
||||
const code = "existing-currency"
|
||||
|
||||
describe("Currency service", function () {
|
||||
beforeEach(function () {
|
||||
jest.clearAllMocks()
|
||||
})
|
||||
|
||||
it("should retrieve a currency", async function () {
|
||||
const currencyService = mockContainer.resolve("currencyService")
|
||||
const currencyRepository = mockContainer.resolve("currencyRepository")
|
||||
|
||||
await currencyService.retrieve(code)
|
||||
|
||||
expect(currencyRepository.find).toHaveBeenCalledWith(
|
||||
{
|
||||
where: {
|
||||
code,
|
||||
},
|
||||
options: {
|
||||
fields: undefined,
|
||||
limit: 15,
|
||||
offset: undefined,
|
||||
populate: [],
|
||||
},
|
||||
},
|
||||
expect.any(Object)
|
||||
)
|
||||
})
|
||||
|
||||
it("should fail to retrieve a currency", async function () {
|
||||
const currencyService = mockContainer.resolve("currencyService")
|
||||
const currencyRepository = mockContainer.resolve("currencyRepository")
|
||||
|
||||
const err = await currencyService
|
||||
.retrieve(nonExistingCurrencyCode)
|
||||
.catch((e) => e)
|
||||
|
||||
expect(currencyRepository.find).toHaveBeenCalledWith(
|
||||
{
|
||||
where: {
|
||||
code: nonExistingCurrencyCode,
|
||||
},
|
||||
options: {
|
||||
fields: undefined,
|
||||
limit: 15,
|
||||
offset: undefined,
|
||||
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 = mockContainer.resolve("currencyService")
|
||||
const currencyRepository = mockContainer.resolve("currencyRepository")
|
||||
|
||||
const filters = {}
|
||||
const config = {
|
||||
relations: [],
|
||||
}
|
||||
|
||||
await currencyService.list(filters, config)
|
||||
|
||||
expect(currencyRepository.find).toHaveBeenCalledWith(
|
||||
{
|
||||
where: {},
|
||||
options: {
|
||||
fields: undefined,
|
||||
limit: 15,
|
||||
offset: undefined,
|
||||
populate: [],
|
||||
withDeleted: undefined,
|
||||
},
|
||||
},
|
||||
expect.any(Object)
|
||||
)
|
||||
})
|
||||
|
||||
it("should list currencys with filters", async function () {
|
||||
const currencyService = mockContainer.resolve("currencyService")
|
||||
const currencyRepository = mockContainer.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: undefined,
|
||||
populate: [],
|
||||
withDeleted: undefined,
|
||||
},
|
||||
},
|
||||
expect.any(Object)
|
||||
)
|
||||
})
|
||||
|
||||
it("should list currencys with filters and relations", async function () {
|
||||
const currencyService = mockContainer.resolve("currencyService")
|
||||
const currencyRepository = mockContainer.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: undefined,
|
||||
withDeleted: undefined,
|
||||
populate: ["tags"],
|
||||
},
|
||||
},
|
||||
expect.any(Object)
|
||||
)
|
||||
})
|
||||
|
||||
it("should list and count the currencys with filters and relations", async function () {
|
||||
const currencyService = mockContainer.resolve("currencyService")
|
||||
const currencyRepository = mockContainer.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: undefined,
|
||||
withDeleted: undefined,
|
||||
populate: ["tags"],
|
||||
},
|
||||
},
|
||||
expect.any(Object)
|
||||
)
|
||||
})
|
||||
})
|
||||
107
packages/pricing/src/services/currency.ts
Normal file
107
packages/pricing/src/services/currency.ts
Normal file
@@ -0,0 +1,107 @@
|
||||
import { Context, DAL, FindConfig, PricingTypes } from "@medusajs/types"
|
||||
import {
|
||||
InjectManager,
|
||||
InjectTransactionManager,
|
||||
MedusaContext,
|
||||
ModulesSdkUtils,
|
||||
retrieveEntity,
|
||||
} from "@medusajs/utils"
|
||||
import { Currency } from "@models"
|
||||
import { CurrencyRepository } from "@repositories"
|
||||
|
||||
import { doNotForceTransaction, shouldForceTransaction } from "@medusajs/utils"
|
||||
|
||||
type InjectedDependencies = {
|
||||
currencyRepository: DAL.RepositoryService
|
||||
}
|
||||
|
||||
export default class CurrencyService<TEntity extends Currency = Currency> {
|
||||
protected readonly currencyRepository_: DAL.RepositoryService
|
||||
|
||||
constructor({ currencyRepository }: InjectedDependencies) {
|
||||
this.currencyRepository_ = currencyRepository
|
||||
}
|
||||
|
||||
@InjectManager("currencyRepository_")
|
||||
async retrieve(
|
||||
currencyCode: string,
|
||||
config: FindConfig<PricingTypes.CurrencyDTO> = {},
|
||||
@MedusaContext() sharedContext: Context = {}
|
||||
): Promise<TEntity> {
|
||||
return (await retrieveEntity<Currency, PricingTypes.CurrencyDTO>({
|
||||
id: currencyCode,
|
||||
identifierColumn: "code",
|
||||
entityName: Currency.name,
|
||||
repository: this.currencyRepository_,
|
||||
config,
|
||||
sharedContext,
|
||||
})) as TEntity
|
||||
}
|
||||
|
||||
@InjectManager("currencyRepository_")
|
||||
async list(
|
||||
filters: PricingTypes.FilterableCurrencyProps = {},
|
||||
config: FindConfig<PricingTypes.CurrencyDTO> = {},
|
||||
@MedusaContext() sharedContext: Context = {}
|
||||
): Promise<TEntity[]> {
|
||||
return (await this.currencyRepository_.find(
|
||||
this.buildQueryForList(filters, config),
|
||||
sharedContext
|
||||
)) as TEntity[]
|
||||
}
|
||||
|
||||
@InjectManager("currencyRepository_")
|
||||
async listAndCount(
|
||||
filters: PricingTypes.FilterableCurrencyProps = {},
|
||||
config: FindConfig<PricingTypes.CurrencyDTO> = {},
|
||||
@MedusaContext() sharedContext: Context = {}
|
||||
): Promise<[TEntity[], number]> {
|
||||
return (await this.currencyRepository_.findAndCount(
|
||||
this.buildQueryForList(filters, config),
|
||||
sharedContext
|
||||
)) as [TEntity[], number]
|
||||
}
|
||||
|
||||
private buildQueryForList(
|
||||
filters: PricingTypes.FilterableCurrencyProps = {},
|
||||
config: FindConfig<PricingTypes.CurrencyDTO> = {}
|
||||
) {
|
||||
const queryOptions = ModulesSdkUtils.buildQuery<Currency>(filters, config)
|
||||
|
||||
if (filters.code) {
|
||||
queryOptions.where["code"] = { $in: filters.code }
|
||||
}
|
||||
|
||||
return queryOptions
|
||||
}
|
||||
|
||||
@InjectTransactionManager(shouldForceTransaction, "currencyRepository_")
|
||||
async create(
|
||||
data: PricingTypes.CreateCurrencyDTO[],
|
||||
@MedusaContext() sharedContext: Context = {}
|
||||
): Promise<TEntity[]> {
|
||||
return (await (this.currencyRepository_ as CurrencyRepository).create(
|
||||
data,
|
||||
sharedContext
|
||||
)) as TEntity[]
|
||||
}
|
||||
|
||||
@InjectTransactionManager(shouldForceTransaction, "currencyRepository_")
|
||||
async update(
|
||||
data: PricingTypes.UpdateCurrencyDTO[],
|
||||
@MedusaContext() sharedContext: Context = {}
|
||||
): Promise<TEntity[]> {
|
||||
return (await (this.currencyRepository_ as CurrencyRepository).update(
|
||||
data,
|
||||
sharedContext
|
||||
)) as TEntity[]
|
||||
}
|
||||
|
||||
@InjectTransactionManager(doNotForceTransaction, "currencyRepository_")
|
||||
async delete(
|
||||
ids: string[],
|
||||
@MedusaContext() sharedContext: Context = {}
|
||||
): Promise<void> {
|
||||
await this.currencyRepository_.delete(ids, sharedContext)
|
||||
}
|
||||
}
|
||||
2
packages/pricing/src/services/index.ts
Normal file
2
packages/pricing/src/services/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export { default as CurrencyService } from "./currency"
|
||||
export { default as PricingModuleService } from "./pricing-module"
|
||||
141
packages/pricing/src/services/pricing-module.ts
Normal file
141
packages/pricing/src/services/pricing-module.ts
Normal file
@@ -0,0 +1,141 @@
|
||||
import {
|
||||
Context,
|
||||
DAL,
|
||||
FindConfig,
|
||||
InternalModuleDeclaration,
|
||||
JoinerServiceConfig,
|
||||
PricingTypes,
|
||||
} from "@medusajs/types"
|
||||
import { Currency } from "@models"
|
||||
import { CurrencyService } from "@services"
|
||||
|
||||
import {
|
||||
InjectManager,
|
||||
InjectTransactionManager,
|
||||
MedusaContext,
|
||||
} from "@medusajs/utils"
|
||||
|
||||
import { shouldForceTransaction } from "@medusajs/utils"
|
||||
import { joinerConfig } from "../joiner-config"
|
||||
|
||||
type InjectedDependencies = {
|
||||
baseRepository: DAL.RepositoryService
|
||||
currencyService: CurrencyService<any>
|
||||
}
|
||||
|
||||
export default class PricingModuleService<TCurrency extends Currency = Currency>
|
||||
implements PricingTypes.IPricingModuleService
|
||||
{
|
||||
protected baseRepository_: DAL.RepositoryService
|
||||
protected readonly currencyService_: CurrencyService<TCurrency>
|
||||
|
||||
constructor(
|
||||
{ baseRepository, currencyService }: InjectedDependencies,
|
||||
protected readonly moduleDeclaration: InternalModuleDeclaration
|
||||
) {
|
||||
this.baseRepository_ = baseRepository
|
||||
this.currencyService_ = currencyService
|
||||
}
|
||||
|
||||
__joinerConfig(): JoinerServiceConfig {
|
||||
return joinerConfig
|
||||
}
|
||||
|
||||
@InjectManager("baseRepository_")
|
||||
async retrieveCurrency(
|
||||
code: string,
|
||||
config: FindConfig<PricingTypes.CurrencyDTO> = {},
|
||||
@MedusaContext() sharedContext: Context = {}
|
||||
): Promise<PricingTypes.CurrencyDTO> {
|
||||
const currency = await this.currencyService_.retrieve(
|
||||
code,
|
||||
config,
|
||||
sharedContext
|
||||
)
|
||||
|
||||
return this.baseRepository_.serialize<PricingTypes.CurrencyDTO>(currency, {
|
||||
populate: true,
|
||||
})
|
||||
}
|
||||
|
||||
@InjectManager("baseRepository_")
|
||||
async listCurrencies(
|
||||
filters: PricingTypes.FilterableCurrencyProps = {},
|
||||
config: FindConfig<PricingTypes.CurrencyDTO> = {},
|
||||
@MedusaContext() sharedContext: Context = {}
|
||||
): Promise<PricingTypes.CurrencyDTO[]> {
|
||||
const currencies = await this.currencyService_.list(
|
||||
filters,
|
||||
config,
|
||||
sharedContext
|
||||
)
|
||||
|
||||
return this.baseRepository_.serialize<PricingTypes.CurrencyDTO[]>(
|
||||
currencies,
|
||||
{
|
||||
populate: true,
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@InjectManager("baseRepository_")
|
||||
async listAndCountCurrencies(
|
||||
filters: PricingTypes.FilterableCurrencyProps = {},
|
||||
config: FindConfig<PricingTypes.CurrencyDTO> = {},
|
||||
@MedusaContext() sharedContext: Context = {}
|
||||
): Promise<[PricingTypes.CurrencyDTO[], number]> {
|
||||
const [currencies, count] = await this.currencyService_.listAndCount(
|
||||
filters,
|
||||
config,
|
||||
sharedContext
|
||||
)
|
||||
|
||||
return [
|
||||
await this.baseRepository_.serialize<PricingTypes.CurrencyDTO[]>(
|
||||
currencies,
|
||||
{
|
||||
populate: true,
|
||||
}
|
||||
),
|
||||
count,
|
||||
]
|
||||
}
|
||||
|
||||
@InjectTransactionManager(shouldForceTransaction, "baseRepository_")
|
||||
async createCurrencies(
|
||||
data: PricingTypes.CreateCurrencyDTO[],
|
||||
@MedusaContext() sharedContext: Context = {}
|
||||
) {
|
||||
const currencies = await this.currencyService_.create(data, sharedContext)
|
||||
|
||||
return this.baseRepository_.serialize<PricingTypes.CurrencyDTO[]>(
|
||||
currencies,
|
||||
{
|
||||
populate: true,
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@InjectTransactionManager(shouldForceTransaction, "baseRepository_")
|
||||
async updateCurrencies(
|
||||
data: PricingTypes.UpdateCurrencyDTO[],
|
||||
@MedusaContext() sharedContext: Context = {}
|
||||
) {
|
||||
const currencies = await this.currencyService_.update(data, sharedContext)
|
||||
|
||||
return this.baseRepository_.serialize<PricingTypes.CurrencyDTO[]>(
|
||||
currencies,
|
||||
{
|
||||
populate: true,
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@InjectTransactionManager(shouldForceTransaction, "baseRepository_")
|
||||
async deleteCurrencies(
|
||||
currencyCodes: string[],
|
||||
@MedusaContext() sharedContext: Context = {}
|
||||
): Promise<void> {
|
||||
await this.currencyService_.delete(currencyCodes, sharedContext)
|
||||
}
|
||||
}
|
||||
5
packages/pricing/src/types/index.ts
Normal file
5
packages/pricing/src/types/index.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
import { Logger } from "@medusajs/types"
|
||||
|
||||
export type InitializeModuleInjectableDependencies = {
|
||||
logger?: Logger
|
||||
}
|
||||
36
packages/pricing/tsconfig.json
Normal file
36
packages/pricing/tsconfig.json
Normal file
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"lib": ["es2020"],
|
||||
"target": "es2020",
|
||||
"outDir": "./dist",
|
||||
"esModuleInterop": true,
|
||||
"declaration": true,
|
||||
"module": "commonjs",
|
||||
"moduleResolution": "node",
|
||||
"emitDecoratorMetadata": true,
|
||||
"experimentalDecorators": true,
|
||||
"sourceMap": false,
|
||||
"noImplicitReturns": true,
|
||||
"strictNullChecks": true,
|
||||
"strictFunctionTypes": true,
|
||||
"noImplicitThis": true,
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"downlevelIteration": true, // to use ES5 specific tooling
|
||||
"baseUrl": ".",
|
||||
"resolveJsonModule": true,
|
||||
"paths": {
|
||||
"@models": ["./src/models"],
|
||||
"@services": ["./src/services"],
|
||||
"@repositories": ["./src/repositories"]
|
||||
}
|
||||
},
|
||||
"include": ["src"],
|
||||
"exclude": [
|
||||
"dist",
|
||||
"./src/**/__tests__",
|
||||
"./src/**/__mocks__",
|
||||
"./src/**/__fixtures__",
|
||||
"node_modules"
|
||||
]
|
||||
}
|
||||
5
packages/pricing/tsconfig.spec.json
Normal file
5
packages/pricing/tsconfig.spec.json
Normal file
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"include": ["src", "integration-tests"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
@@ -1,14 +1,15 @@
|
||||
export * as CacheTypes from "./cache"
|
||||
export * as CommonTypes from "./common"
|
||||
export * as DAL from "./dal"
|
||||
export * as EventBusTypes from "./event-bus"
|
||||
export * as FeatureFlagTypes from "./feature-flag"
|
||||
export * as InventoryTypes from "./inventory"
|
||||
export * as ProductTypes from "./product"
|
||||
export * as LoggerTypes from "./logger"
|
||||
export * as ModulesSdkTypes from "./modules-sdk"
|
||||
export * as PricingTypes from "./pricing"
|
||||
export * as ProductTypes from "./product"
|
||||
export * as SalesChannelTypes from "./sales-channel"
|
||||
export * as SearchTypes from "./search"
|
||||
export * as StockLocationTypes from "./stock-location"
|
||||
export * as TransactionBaseTypes from "./transaction-base"
|
||||
export * as DAL from "./dal"
|
||||
export * as LoggerTypes from "./logger"
|
||||
export * as FeatureFlagTypes from "./feature-flag"
|
||||
export * as SalesChannelTypes from "./sales-channel"
|
||||
export * as WorkflowTypes from "./workflow"
|
||||
|
||||
@@ -11,6 +11,7 @@ export * from "./inventory"
|
||||
export * from "./joiner"
|
||||
export * from "./logger"
|
||||
export * from "./modules-sdk"
|
||||
export * from "./pricing"
|
||||
export * from "./product"
|
||||
export * from "./product-category"
|
||||
export * from "./sales-channel"
|
||||
|
||||
27
packages/types/src/pricing/common/currency.ts
Normal file
27
packages/types/src/pricing/common/currency.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { BaseFilterable } from "../../dal"
|
||||
|
||||
export interface CurrencyDTO {
|
||||
code: string
|
||||
symbol?: string
|
||||
symbol_native?: string
|
||||
name?: string
|
||||
}
|
||||
|
||||
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[]
|
||||
}
|
||||
1
packages/types/src/pricing/common/index.ts
Normal file
1
packages/types/src/pricing/common/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from "./currency"
|
||||
2
packages/types/src/pricing/index.ts
Normal file
2
packages/types/src/pricing/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from "./common"
|
||||
export * from "./service"
|
||||
45
packages/types/src/pricing/service.ts
Normal file
45
packages/types/src/pricing/service.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import { FindConfig } from "../common"
|
||||
import { JoinerServiceConfig } from "../joiner"
|
||||
import { Context } from "../shared-context"
|
||||
import {
|
||||
CreateCurrencyDTO,
|
||||
CurrencyDTO,
|
||||
FilterableCurrencyProps,
|
||||
UpdateCurrencyDTO,
|
||||
} from "./common"
|
||||
export interface IPricingModuleService {
|
||||
__joinerConfig(): JoinerServiceConfig
|
||||
|
||||
retrieveCurrency(
|
||||
code: string,
|
||||
config?: FindConfig<CurrencyDTO>,
|
||||
sharedContext?: Context
|
||||
): Promise<CurrencyDTO>
|
||||
|
||||
listCurrencies(
|
||||
filters?: FilterableCurrencyProps,
|
||||
config?: FindConfig<CurrencyDTO>,
|
||||
sharedContext?: Context
|
||||
): Promise<CurrencyDTO[]>
|
||||
|
||||
listAndCountCurrencies(
|
||||
filters?: FilterableCurrencyProps,
|
||||
config?: FindConfig<CurrencyDTO>,
|
||||
sharedContext?: Context
|
||||
): Promise<[CurrencyDTO[], number]>
|
||||
|
||||
createCurrencies(
|
||||
data: CreateCurrencyDTO[],
|
||||
sharedContext?: Context
|
||||
): Promise<CurrencyDTO[]>
|
||||
|
||||
updateCurrencies(
|
||||
data: UpdateCurrencyDTO[],
|
||||
sharedContext?: Context
|
||||
): Promise<CurrencyDTO[]>
|
||||
|
||||
deleteCurrencies(
|
||||
currencyCodes: string[],
|
||||
sharedContext?: Context
|
||||
): Promise<void>
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
export * as DALUtils from "./dal"
|
||||
export * as DecoratorUtils from "./decorators"
|
||||
export * as EventBusUtils from "./event-bus"
|
||||
export * as SearchUtils from "./search"
|
||||
export * as ModulesSdkUtils from "./modules-sdk"
|
||||
export * as DALUtils from "./dal"
|
||||
export * as FeatureFlagUtils from "./feature-flags"
|
||||
export * as ShippingProfileUtils from "./shipping"
|
||||
export * as ModulesSdkUtils from "./modules-sdk"
|
||||
export * as ProductUtils from "./product"
|
||||
export * as SearchUtils from "./search"
|
||||
export * as ShippingProfileUtils from "./shipping"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
export * from "./build-query"
|
||||
export * from "./container"
|
||||
export * from "./deduplicate"
|
||||
export * from "./errors"
|
||||
export * from "./generate-entity-id"
|
||||
@@ -20,6 +21,6 @@ export * from "./stringify-circular"
|
||||
export * from "./to-camel-case"
|
||||
export * from "./to-kebab-case"
|
||||
export * from "./to-pascal-case"
|
||||
export * from "./transaction"
|
||||
export * from "./upper-case-first"
|
||||
export * from "./wrap-handler"
|
||||
export * from "./container"
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
export function doNotForceTransaction(): boolean {
|
||||
return false
|
||||
}
|
||||
2
packages/utils/src/common/transaction/index.ts
Normal file
2
packages/utils/src/common/transaction/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from "./do-not-force-transaction"
|
||||
export * from "./should-force-transaction"
|
||||
@@ -0,0 +1,5 @@
|
||||
import { MODULE_RESOURCE_TYPE } from "@medusajs/types"
|
||||
|
||||
export function shouldForceTransaction(target: any): boolean {
|
||||
return target.moduleDeclaration?.resources === MODULE_RESOURCE_TYPE.ISOLATED
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
export * from "./mikro-orm/mikro-orm-create-connection"
|
||||
export * from "./mikro-orm/mikro-orm-repository"
|
||||
export * from "./mikro-orm/mikro-orm-soft-deletable-filter"
|
||||
export * from "./mikro-orm/utils"
|
||||
export * from "./repositories"
|
||||
export * from "./repository"
|
||||
export * from "./utils"
|
||||
export * from "./mikro-orm/utils"
|
||||
export * from "./mikro-orm/mikro-orm-create-connection"
|
||||
export * from "./mikro-orm/mikro-orm-soft-deletable-filter"
|
||||
|
||||
1
packages/utils/src/dal/repositories/index.ts
Normal file
1
packages/utils/src/dal/repositories/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from "./load-custom-repositories"
|
||||
@@ -0,0 +1,35 @@
|
||||
import { Constructor, DAL } from "@medusajs/types"
|
||||
import { asClass } from "awilix"
|
||||
import { lowerCaseFirst } from "../../common"
|
||||
|
||||
/**
|
||||
* Load the repositories from the custom repositories object. If a repository is not
|
||||
* present in the custom repositories object, the default repository will be used.
|
||||
*
|
||||
* @param customRepositories
|
||||
* @param container
|
||||
*/
|
||||
export function loadCustomRepositories({
|
||||
defaultRepositories,
|
||||
customRepositories,
|
||||
container,
|
||||
}) {
|
||||
const customRepositoriesMap = new Map(Object.entries(customRepositories))
|
||||
|
||||
Object.entries(defaultRepositories).forEach(([key, defaultRepository]) => {
|
||||
let finalRepository = customRepositoriesMap.get(key)
|
||||
|
||||
if (
|
||||
!finalRepository ||
|
||||
!(finalRepository as Constructor<DAL.RepositoryService>).prototype.find
|
||||
) {
|
||||
finalRepository = defaultRepository
|
||||
}
|
||||
|
||||
container.register({
|
||||
[lowerCaseFirst(key)]: asClass(
|
||||
finalRepository as Constructor<DAL.RepositoryService>
|
||||
).singleton(),
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
export * from "./bundles"
|
||||
export * from "./common"
|
||||
export * from "./dal"
|
||||
export * from "./decorators"
|
||||
export * from "./event-bus"
|
||||
export * from "./search"
|
||||
export * from "./modules-sdk"
|
||||
export * from "./dal"
|
||||
export * from "./feature-flags"
|
||||
export * from "./shipping"
|
||||
export * from "./modules-sdk"
|
||||
export * from "./product"
|
||||
export * from "./search"
|
||||
export * from "./shipping"
|
||||
|
||||
@@ -1,20 +1,24 @@
|
||||
import { FindConfig, DAL, Context } from "@medusajs/types"
|
||||
import { MedusaError, isDefined, lowerCaseFirst } from "../common"
|
||||
import { Context, DAL, FindConfig } from "@medusajs/types"
|
||||
import {
|
||||
MedusaError,
|
||||
isDefined,
|
||||
lowerCaseFirst,
|
||||
upperCaseFirst,
|
||||
} from "../common"
|
||||
import { buildQuery } from "./build-query"
|
||||
|
||||
type RetrieveEntityParams<TDTO> = {
|
||||
id: string,
|
||||
entityName: string,
|
||||
id: string
|
||||
identifierColumn?: string
|
||||
entityName: string
|
||||
repository: DAL.TreeRepositoryService | DAL.RepositoryService
|
||||
config: FindConfig<TDTO>
|
||||
sharedContext?: Context
|
||||
}
|
||||
|
||||
export async function retrieveEntity<
|
||||
TEntity,
|
||||
TDTO,
|
||||
>({
|
||||
export async function retrieveEntity<TEntity, TDTO>({
|
||||
id,
|
||||
identifierColumn = "id",
|
||||
entityName,
|
||||
repository,
|
||||
config = {},
|
||||
@@ -23,23 +27,25 @@ export async function retrieveEntity<
|
||||
if (!isDefined(id)) {
|
||||
throw new MedusaError(
|
||||
MedusaError.Types.NOT_FOUND,
|
||||
`"${lowerCaseFirst(entityName)}Id" must be defined`
|
||||
`"${lowerCaseFirst(entityName)}${upperCaseFirst(
|
||||
identifierColumn
|
||||
)}" must be defined`
|
||||
)
|
||||
}
|
||||
|
||||
const queryOptions = buildQuery<TEntity>({
|
||||
id,
|
||||
}, config)
|
||||
|
||||
const entities = await repository.find(
|
||||
queryOptions,
|
||||
sharedContext
|
||||
const queryOptions = buildQuery<TEntity>(
|
||||
{
|
||||
[identifierColumn]: id,
|
||||
},
|
||||
config
|
||||
)
|
||||
|
||||
const entities = await repository.find(queryOptions, sharedContext)
|
||||
|
||||
if (!entities?.length) {
|
||||
throw new MedusaError(
|
||||
MedusaError.Types.NOT_FOUND,
|
||||
`${entityName} with id: ${id} was not found`
|
||||
`${entityName} with ${identifierColumn}: ${id} was not found`
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user