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:
1 parent
470379e631
commit
460161a69f
70 files changed
+3022
-75
No files matched your search
@@ -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"
|
||||
@@ -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]
|
||||
}
|
||||
@@ -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",
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
@@ -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(),
|
||||
})
|
||||
}
|
||||
@@ -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"));');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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
|
||||
@@ -0,0 +1 @@
|
||||
export { default as Currency } from "./currency"
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export { MikroOrmBaseRepository as BaseRepository } from "@medusajs/utils"
|
||||
export { CurrencyRepository } from "./currency"
|
||||
@@ -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()
|
||||
})()
|
||||
@@ -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()
|
||||
})()
|
||||
@@ -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 })
|
||||
})()
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from "./migration-up"
|
||||
export * from "./migration-down"
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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),
|
||||
})
|
||||
@@ -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)
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export { default as CurrencyService } from "./currency"
|
||||
export { default as PricingModuleService } from "./pricing-module"
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { Logger } from "@medusajs/types"
|
||||
|
||||
export type InitializeModuleInjectableDependencies = {
|
||||
logger?: Logger
|
||||
}
|
||||
Reference in new issue
Block a user