feat(tax): tax module scaffolding (#6417)

**What**
- Scaffolds the tax module
This commit is contained in:
Sebastian Rindom
2024-02-16 14:24:23 +01:00
committed by GitHub
parent 0d68eadf84
commit 7df4947ecf
31 changed files with 606 additions and 1 deletions

View File

@@ -19,6 +19,7 @@ export enum Modules {
PRODUCT = "productService",
PROMOTION = "promotion",
SALES_CHANNEL = "salesChannel",
TAX = "tax",
FULFILLMENT = "fulfillment",
STOCK_LOCATION = "stockLocationService",
USER = "user",
@@ -41,6 +42,7 @@ export enum ModuleRegistrationName {
SALES_CHANNEL = "salesChannelModuleService",
FULFILLMENT = "fulfillmentModuleService",
STOCK_LOCATION = "stockLocationService",
TAX = "taxModuleService",
USER = "userModuleService",
WORKFLOW_ENGINE = "workflowsModuleService",
REGION = "regionModuleService",
@@ -62,6 +64,7 @@ export const MODULE_PACKAGE_NAMES = {
[Modules.SALES_CHANNEL]: "@medusajs/sales-channel",
[Modules.FULFILLMENT]: "@medusajs/fulfillment",
[Modules.STOCK_LOCATION]: "@medusajs/stock-location",
[Modules.TAX]: "@medusajs/tax",
[Modules.USER]: "@medusajs/user",
[Modules.WORKFLOW_ENGINE]: "@medusajs/workflow-engine-inmemory",
[Modules.REGION]: "@medusajs/region",
@@ -292,6 +295,19 @@ export const ModulesDefinition: { [key: string | Modules]: ModuleDefinition } =
resources: MODULE_RESOURCE_TYPE.SHARED,
},
},
[Modules.TAX]: {
key: Modules.TAX,
registrationName: ModuleRegistrationName.TAX,
defaultPackage: false,
label: upperCaseFirst(ModuleRegistrationName.TAX),
isRequired: false,
isQueryable: true,
dependencies: ["logger", "eventBusService"],
defaultModuleDeclaration: {
scope: MODULE_SCOPE.INTERNAL,
resources: MODULE_RESOURCE_TYPE.SHARED,
},
},
}
export const MODULE_DEFINITIONS: ModuleDefinition[] =

View File

@@ -7,7 +7,7 @@ const mikroOrmEntities = Models as unknown as any[]
export const MikroOrmWrapper = TestDatabaseUtils.getMikroOrmWrapper(
mikroOrmEntities,
null,
process.env.MEDUSA_FULFILLMENT_DB_SCHEMA
process.env.MEDUSA_ORDER_DB_SCHEMA
)
export const DB_URL = TestDatabaseUtils.getDatabaseURL()

6
packages/tax/.gitignore vendored Normal file
View File

@@ -0,0 +1,6 @@
/dist
node_modules
.DS_store
.env*
.env
*.sql

1
packages/tax/README.md Normal file
View File

@@ -0,0 +1 @@
# Tax Module

View File

@@ -0,0 +1,5 @@
describe("noop", function () {
it("should run", function () {
expect(true).toBe(true)
})
})

View 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-tax-integration-${tempName}`
}
process.env.MEDUSA_TAX_DB_SCHEMA = "public"

View File

@@ -0,0 +1,3 @@
import { JestUtils } from "medusa-test-utils"
JestUtils.afterAllHookDropDatabase()

View File

@@ -0,0 +1,13 @@
import { TestDatabaseUtils } from "medusa-test-utils"
import * as Models from "@models"
const mikroOrmEntities = Models as unknown as any[]
export const MikroOrmWrapper = TestDatabaseUtils.getMikroOrmWrapper(
mikroOrmEntities,
null,
process.env.MEDUSA_TAX_DB_SCHEMA
)
export const DB_URL = TestDatabaseUtils.getDatabaseURL()

View File

@@ -0,0 +1,33 @@
import { Modules, ModulesDefinition } from "@medusajs/modules-sdk"
import { DB_URL } from "./database"
export function getInitModuleConfig() {
const moduleOptions = {
defaultAdapterOptions: {
database: {
clientUrl: DB_URL,
schema: process.env.MEDUSA_TAX_DB_SCHEMA,
},
},
}
const injectedDependencies = {}
const modulesConfig_ = {
[Modules.TAX]: {
definition: ModulesDefinition[Modules.TAX],
options: moduleOptions,
},
}
return {
injectedDependencies,
modulesConfig: modulesConfig_,
databaseConfig: {
clientUrl: DB_URL,
schema: process.env.MEDUSA_TAX_DB_SCHEMA,
},
joinerConfig: [],
}
}

View File

@@ -0,0 +1,2 @@
export * from "./database"
export * from "./get-init-module-config"

View File

@@ -0,0 +1,22 @@
module.exports = {
moduleNameMapper: {
"^@models": "<rootDir>/src/models",
"^@services": "<rootDir>/src/services",
"^@repositories": "<rootDir>/src/repositories",
"^@types": "<rootDir>/src/types",
},
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"],
}

View File

@@ -0,0 +1,12 @@
import { TSMigrationGenerator } from "@medusajs/utils"
import * as entities from "./src/models"
module.exports = {
entities: Object.values(entities),
schema: "public",
clientUrl: "postgres://postgres@localhost/medusa-tax",
type: "postgresql",
migrations: {
generator: TSMigrationGenerator,
},
}

61
packages/tax/package.json Normal file
View File

@@ -0,0 +1,61 @@
{
"name": "@medusajs/tax",
"version": "0.1.0",
"description": "Medusa Tax module",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist"
],
"engines": {
"node": ">=16"
},
"bin": {
"medusa-tax-seed": "dist/scripts/bin/run-seed.js"
},
"repository": {
"type": "git",
"url": "https://github.com/medusajs/medusa",
"directory": "packages/tax"
},
"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.9.7",
"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.12.4",
"@medusajs/types": "^1.11.8",
"@medusajs/utils": "^1.11.1",
"@mikro-orm/core": "5.9.7",
"@mikro-orm/migrations": "5.9.7",
"@mikro-orm/postgresql": "5.9.7",
"awilix": "^8.0.0",
"dotenv": "^16.1.4",
"knex": "2.4.2"
}
}

13
packages/tax/src/index.ts Normal file
View File

@@ -0,0 +1,13 @@
import { initializeFactory, Modules } from "@medusajs/modules-sdk"
import { moduleDefinition } from "./module-definition"
export * from "./models"
export * from "./services"
export const initialize = initializeFactory({
moduleName: Modules.TAX,
moduleDefinition,
})
export const runMigrations = moduleDefinition.runMigrations
export const revertMigration = moduleDefinition.revertMigration
export default moduleDefinition

View File

@@ -0,0 +1,25 @@
import { Modules } from "@medusajs/modules-sdk"
import { ModuleJoinerConfig } from "@medusajs/types"
import { MapToConfig } from "@medusajs/utils"
export const LinkableKeys: Record<string, string> = {
tax_rate_id: "TaxRate",
}
const entityLinkableKeysMap: MapToConfig = {}
Object.entries(LinkableKeys).forEach(([key, value]) => {
entityLinkableKeysMap[value] ??= []
entityLinkableKeysMap[value].push({
mapTo: key,
valueFrom: key.split("_").pop()!,
})
})
export const entityNameToLinkableKeysMap: MapToConfig = entityLinkableKeysMap
export const joinerConfig: ModuleJoinerConfig = {
serviceName: Modules.TAX,
primaryKeys: ["id"],
linkableKeys: LinkableKeys,
alias: [],
} as ModuleJoinerConfig

View File

@@ -0,0 +1 @@
export { default as TaxRate } from "./tax-rate"

View File

@@ -0,0 +1,60 @@
import { DAL } from "@medusajs/types"
import { generateEntityId } from "@medusajs/utils"
import {
BeforeCreate,
Entity,
OnInit,
OptionalProps,
PrimaryKey,
Property,
} from "@mikro-orm/core"
type OptionalTaxRateProps = DAL.EntityDateColumns
@Entity({ tableName: "tax_rate" })
export default class TaxRate {
[OptionalProps]: OptionalTaxRateProps
@PrimaryKey({ columnType: "text" })
id!: string
@Property({ columnType: "real", nullable: true })
rate: number | null = null
@Property({ columnType: "text", nullable: true })
code: string | null = null
@Property({ columnType: "text" })
name: string
@Property({ columnType: "jsonb", nullable: true })
metadata: Record<string, unknown> | null = null
@Property({
onCreate: () => new Date(),
columnType: "timestamptz",
defaultRaw: "now()",
})
created_at: Date
@Property({
onCreate: () => new Date(),
onUpdate: () => new Date(),
columnType: "timestamptz",
defaultRaw: "now()",
})
updated_at: Date
@Property({ columnType: "text", nullable: true })
created_by: string | null = null
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "txr")
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "txr")
}
}

View File

@@ -0,0 +1,43 @@
import { MikroOrmBaseRepository, ModulesSdkUtils } from "@medusajs/utils"
import { Modules } from "@medusajs/modules-sdk"
import { ModuleExports } from "@medusajs/types"
import * as Models from "@models"
import * as ModuleModels from "@models"
import * as ModuleServices from "@services"
import { TaxModuleService } from "@services"
const migrationScriptOptions = {
moduleName: Modules.TAX,
models: Models,
pathToMigrations: __dirname + "/migrations",
}
const runMigrations = ModulesSdkUtils.buildMigrationScript(
migrationScriptOptions
)
const revertMigration = ModulesSdkUtils.buildRevertMigrationScript(
migrationScriptOptions
)
const containerLoader = ModulesSdkUtils.moduleContainerLoaderFactory({
moduleModels: ModuleModels,
moduleRepositories: { BaseRepository: MikroOrmBaseRepository },
moduleServices: ModuleServices,
})
const connectionLoader = ModulesSdkUtils.mikroOrmConnectionLoaderFactory({
moduleName: Modules.TAX,
moduleModels: Object.values(Models),
migrationsPath: __dirname + "/migrations",
})
const service = TaxModuleService
const loaders = [containerLoader, connectionLoader] as any
export const moduleDefinition: ModuleExports = {
service,
loaders,
revertMigration,
runMigrations,
}

View File

@@ -0,0 +1,29 @@
#!/usr/bin/env node
import { Modules } from "@medusajs/modules-sdk"
import { ModulesSdkUtils } from "@medusajs/utils"
import * as Models from "@models"
import { EOL } from "os"
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-tax-seed <filePath>`
)
}
const run = ModulesSdkUtils.buildSeedScript({
moduleName: Modules.TAX,
models: Models,
pathToMigrations: __dirname + "/../../migrations",
seedHandler: async ({ manager, data }) => {
// TODO: Add seed logic
},
})
await run({ path })
})()

View File

@@ -0,0 +1,5 @@
describe("noop", function () {
it("should run", function () {
expect(true).toBe(true)
})
})

View File

@@ -0,0 +1 @@
export { default as TaxModuleService } from "./tax-module-service"

View File

@@ -0,0 +1,81 @@
import {
Context,
DAL,
ITaxRateModuleService,
InternalModuleDeclaration,
ModuleJoinerConfig,
ModulesSdkTypes,
TaxTypes,
} from "@medusajs/types"
import {
InjectManager,
InjectTransactionManager,
MedusaContext,
ModulesSdkUtils,
} from "@medusajs/utils"
import { TaxRate } from "@models"
import { entityNameToLinkableKeysMap, joinerConfig } from "../joiner-config"
type InjectedDependencies = {
baseRepository: DAL.RepositoryService
taxRateService: ModulesSdkTypes.InternalModuleService<any>
}
export default class TaxModuleService<TTaxRate extends TaxRate = TaxRate>
extends ModulesSdkUtils.abstractModuleServiceFactory<
InjectedDependencies,
TaxTypes.TaxRateDTO,
{}
>(TaxRate, [], entityNameToLinkableKeysMap)
implements ITaxRateModuleService
{
protected baseRepository_: DAL.RepositoryService
protected taxRateService_: ModulesSdkTypes.InternalModuleService<TTaxRate>
constructor(
{ baseRepository, taxRateService }: InjectedDependencies,
protected readonly moduleDeclaration: InternalModuleDeclaration
) {
// @ts-ignore
super(...arguments)
this.baseRepository_ = baseRepository
this.taxRateService_ = taxRateService
}
__joinerConfig(): ModuleJoinerConfig {
return joinerConfig
}
async create(
data: TaxTypes.CreateTaxRateDTO[],
sharedContext?: Context
): Promise<TaxTypes.TaxRateDTO[]>
async create(
data: TaxTypes.CreateTaxRateDTO,
sharedContext?: Context
): Promise<TaxTypes.TaxRateDTO>
@InjectManager("baseRepository_")
async create(
data: TaxTypes.CreateTaxRateDTO[] | TaxTypes.CreateTaxRateDTO,
@MedusaContext() sharedContext: Context = {}
): Promise<TaxTypes.TaxRateDTO[] | TaxTypes.TaxRateDTO> {
const input = Array.isArray(data) ? data : [data]
const rates = await this.create_(input, sharedContext)
const result = await this.baseRepository_.serialize<TaxTypes.TaxRateDTO>(
rates,
{ populate: true }
)
return Array.isArray(data) ? result : result[0]
}
@InjectTransactionManager("baseRepository_")
protected async create_(
data: TaxTypes.CreateTaxRateDTO[],
@MedusaContext() sharedContext: Context = {}
) {
return await this.taxRateService_.create(data, sharedContext)
}
}

View File

@@ -0,0 +1,37 @@
{
"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"],
"@types": ["./src/types"]
}
},
"include": ["src"],
"exclude": [
"dist",
"./src/**/__tests__",
"./src/**/__mocks__",
"./src/**/__fixtures__",
"node_modules"
]
}

View File

@@ -0,0 +1,8 @@
{
"extends": "./tsconfig.json",
"include": ["src", "integration-tests"],
"exclude": ["node_modules", "dist"],
"compilerOptions": {
"sourceMap": true
}
}

View File

@@ -18,6 +18,7 @@ export * as RegionTypes from "./region__legacy"
export * as SalesChannelTypes from "./sales-channel"
export * as SearchTypes from "./search"
export * as StockLocationTypes from "./stock-location"
export * as TaxTypes from "./tax"
export * as TransactionBaseTypes from "./transaction-base"
export * as UserTypes from "./user"
export * as WorkflowTypes from "./workflow"

View File

@@ -27,6 +27,7 @@ export * from "./sales-channel"
export * from "./search"
export * from "./shared-context"
export * from "./stock-location"
export * from "./tax"
export * from "./totals"
export * from "./transaction-base"
export * from "./user"

View File

@@ -0,0 +1,49 @@
import { BaseFilterable } from "../dal"
import { OperatorMap } from "../dal/utils"
export interface TaxRateDTO {
/**
* The ID of the Tax Rate.
*/
id: string
/**
* The numerical rate to charge.
*/
rate: number | null
/**
* The code the tax rate is identified by.
*/
code: string | null
/**
* The name of the Tax Rate. E.g. "VAT".
*/
name: string
/**
* Holds custom data in key-value pairs.
*/
metadata: Record<string, unknown> | null
/**
* When the Tax Rate was created.
*/
created_at: string | Date
/**
* When the Tax Rate was updated.
*/
updated_at: string | Date
/**
* The ID of the user that created the Tax Rate.
*/
created_by: string
}
export interface FilterableTaxRateProps
extends BaseFilterable<FilterableTaxRateProps> {
id?: string | string[]
rate?: number | number[] | OperatorMap<number>
code?: string | string[] | OperatorMap<string>
name?: string | string[] | OperatorMap<string>
created_at?: OperatorMap<string>
updated_at?: OperatorMap<string>
created_by?: string | string[] | OperatorMap<string>
}

View File

@@ -0,0 +1,3 @@
export * from "./common"
export * from "./mutations"
export * from "./service"

View File

@@ -0,0 +1,7 @@
export interface CreateTaxRateDTO {
rate?: number | null
code?: string | null
name: string
created_by?: string
metadata?: Record<string, unknown>
}

View File

@@ -0,0 +1,34 @@
import { FindConfig } from "../common"
import { IModuleService } from "../modules-sdk"
import { Context } from "../shared-context"
import { FilterableTaxRateProps, TaxRateDTO } from "./common"
import { CreateTaxRateDTO } from "./mutations"
export interface ITaxRateModuleService extends IModuleService {
retrieve(
taxRateId: string,
config?: FindConfig<TaxRateDTO>,
sharedContext?: Context
): Promise<TaxRateDTO>
list(
filters?: FilterableTaxRateProps,
config?: FindConfig<TaxRateDTO>,
sharedContext?: Context
): Promise<TaxRateDTO[]>
listAndCount(
filters?: FilterableTaxRateProps,
config?: FindConfig<TaxRateDTO>,
sharedContext?: Context
): Promise<[TaxRateDTO[], number]>
create(
data: CreateTaxRateDTO[],
sharedContext?: Context
): Promise<TaxRateDTO[]>
create(data: CreateTaxRateDTO, sharedContext?: Context): Promise<TaxRateDTO>
delete(taxRateIds: string[], sharedContext?: Context): Promise<void>
delete(taxRateId: string, sharedContext?: Context): Promise<void>
}

View File

@@ -8703,6 +8703,33 @@ __metadata:
languageName: unknown
linkType: soft
"@medusajs/tax@workspace:packages/tax":
version: 0.0.0-use.local
resolution: "@medusajs/tax@workspace:packages/tax"
dependencies:
"@medusajs/modules-sdk": ^1.12.4
"@medusajs/types": ^1.11.8
"@medusajs/utils": ^1.11.1
"@mikro-orm/cli": 5.9.7
"@mikro-orm/core": 5.9.7
"@mikro-orm/migrations": 5.9.7
"@mikro-orm/postgresql": 5.9.7
awilix: ^8.0.0
cross-env: ^5.2.1
dotenv: ^16.1.4
jest: ^29.6.3
knex: 2.4.2
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
bin:
medusa-tax-seed: dist/scripts/bin/run-seed.js
languageName: unknown
linkType: soft
"@medusajs/toolbox@^0.0.1, @medusajs/toolbox@workspace:packages/design-system/toolbox":
version: 0.0.0-use.local
resolution: "@medusajs/toolbox@workspace:packages/design-system/toolbox"