feat: customer module skeleton (#6126)

This commit is contained in:
Sebastian Rindom
2024-01-19 11:18:54 +01:00
committed by GitHub
parent a12c28b7d5
commit 12aa1737d5
47 changed files with 1157 additions and 0 deletions

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

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

View File

View File

@@ -0,0 +1,8 @@
# Customer Module
Customers represent entities who can make purchases in a store.
### Features
- The customer module enables you to store your customerss contact details.
- The customer module enables you to group your customers.

View File

@@ -0,0 +1,41 @@
import { ICustomerModuleService } from "@medusajs/types"
import { initialize } from "../../../../src/initialize"
import { DB_URL, MikroOrmWrapper } from "../../../utils"
jest.setTimeout(30000)
describe("Customer Module Service", () => {
let service: ICustomerModuleService
beforeEach(async () => {
await MikroOrmWrapper.setupDatabase()
service = await initialize({
database: {
clientUrl: DB_URL,
schema: process.env.MEDUSA_CUSTOMER_DB_SCHEMA,
},
})
})
afterEach(async () => {
await MikroOrmWrapper.clearDatabase()
})
describe("create", () => {
it("should create a customer", async () => {
const customerPromise = service.create({
first_name: "John",
last_name: "Doe",
})
await expect(customerPromise).resolves.toEqual(
expect.objectContaining({
id: expect.any(String),
first_name: "John",
last_name: "Doe",
})
)
})
})
})

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

View File

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

View File

@@ -0,0 +1,6 @@
import { ModuleServiceInitializeOptions } from "@medusajs/types"
export const databaseOptions: ModuleServiceInitializeOptions["database"] = {
schema: "public",
clientUrl: "medusa-customer-test",
}

View File

@@ -0,0 +1,18 @@
import { TestDatabaseUtils } from "medusa-test-utils"
import * as Models from "@models"
const pathToMigrations = "../../src/migrations"
const mikroOrmEntities = Models as unknown as any[]
export const MikroOrmWrapper = TestDatabaseUtils.getMikroOrmWrapper(
mikroOrmEntities,
pathToMigrations
)
export const MikroOrmConfig = TestDatabaseUtils.getMikroOrmConfig(
mikroOrmEntities,
pathToMigrations
)
export const DB_URL = TestDatabaseUtils.getDatabaseURL()

View File

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

View 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"],
}

View File

@@ -0,0 +1,8 @@
import * as entities from "./src/models"
module.exports = {
entities: Object.values(entities),
schema: "public",
clientUrl: "postgres://postgres@localhost/medusa-customer",
type: "postgresql",
}

View File

@@ -0,0 +1,61 @@
{
"name": "@medusajs/customer",
"version": "0.0.1",
"description": "Medusa Customer module",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist"
],
"engines": {
"node": ">=16"
},
"bin": {
"medusa-customer-seed": "dist/scripts/bin/run-seed.js"
},
"repository": {
"type": "git",
"url": "https://github.com/medusajs/medusa",
"directory": "packages/customer"
},
"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": {
"@medusajs/types": "workspace:^",
"@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.5",
"@medusajs/utils": "^1.11.2",
"@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"
}
}

View File

@@ -0,0 +1,24 @@
import { Modules } from "@medusajs/modules-sdk"
import { ModulesSdkUtils } from "@medusajs/utils"
import * as Models from "@models"
import { moduleDefinition } from "./module-definition"
export default moduleDefinition
const migrationScriptOptions = {
moduleName: Modules.CUSTOMER,
models: Models,
pathToMigrations: __dirname + "/migrations",
}
export const revertMigration = ModulesSdkUtils.buildRevertMigrationScript(
migrationScriptOptions
)
export const runMigration = ModulesSdkUtils.buildMigrationScript(
migrationScriptOptions
)
export * from "./initialize"
export * from "./loaders"

View File

@@ -0,0 +1,31 @@
import {
ExternalModuleDeclaration,
InternalModuleDeclaration,
MedusaModule,
MODULE_PACKAGE_NAMES,
Modules,
} from "@medusajs/modules-sdk"
import { ICustomerModuleService, 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<ICustomerModuleService> => {
const loaded = await MedusaModule.bootstrap<ICustomerModuleService>({
moduleKey: Modules.CUSTOMER,
defaultPath: MODULE_PACKAGE_NAMES[Modules.CUSTOMER],
declaration: options as
| InternalModuleDeclaration
| ExternalModuleDeclaration,
injectedDependencies,
moduleExports: moduleDefinition,
})
return loaded[Modules.CUSTOMER]
}

View File

@@ -0,0 +1,31 @@
import { Modules } from "@medusajs/modules-sdk"
import { ModuleJoinerConfig } from "@medusajs/types"
import { MapToConfig } from "@medusajs/utils"
import { Customer } from "@models"
export const LinkableKeys = {
customer_id: Customer.name,
}
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.CUSTOMER,
primaryKeys: ["id"],
linkableKeys: LinkableKeys,
alias: {
name: ["customer", "customers"],
args: {
entity: Customer.name,
},
},
}

View File

@@ -0,0 +1,34 @@
import {
InternalModuleDeclaration,
LoaderOptions,
Modules,
} from "@medusajs/modules-sdk"
import { ModulesSdkTypes } from "@medusajs/types"
import { ModulesSdkUtils } from "@medusajs/utils"
import { EntitySchema } from "@mikro-orm/core"
import * as CustomerModels from "../models"
export default async (
{
options,
container,
logger,
}: LoaderOptions<
| ModulesSdkTypes.ModuleServiceInitializeOptions
| ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions
>,
moduleDeclaration?: InternalModuleDeclaration
): Promise<void> => {
const entities = Object.values(CustomerModels) as unknown as EntitySchema[]
const pathToMigrations = __dirname + "/../migrations"
await ModulesSdkUtils.mikroOrmConnectionLoader({
moduleName: Modules.CUSTOMER,
entities,
container,
options,
moduleDeclaration,
logger,
pathToMigrations,
})
}

View File

@@ -0,0 +1,52 @@
import * as defaultRepositories from "@repositories"
import { LoaderOptions } from "@medusajs/modules-sdk"
import { ModulesSdkTypes } from "@medusajs/types"
import { loadCustomRepositories } from "@medusajs/utils"
import * as defaultServices from "@services"
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({
customerService: asClass(defaultServices.CustomerService).singleton(),
addressService: asClass(defaultServices.AddressService).singleton(),
customerGroupService: asClass(
defaultServices.CustomerGroupService
).singleton(),
})
if (customRepositories) {
loadCustomRepositories({
defaultRepositories,
customRepositories,
container,
})
} else {
loadDefaultRepositories({ container })
}
}
function loadDefaultRepositories({ container }) {
container.register({
baseRepository: asClass(defaultRepositories.BaseRepository).singleton(),
customerRepository: asClass(
defaultRepositories.CustomerRepository
).singleton(),
addressRepository: asClass(
defaultRepositories.AddressRepository
).singleton(),
customerGroupRepository: asClass(
defaultRepositories.CustomerGroupRepository
).singleton(),
})
}

View File

@@ -0,0 +1,2 @@
export * from "./connection"
export * from "./container"

View File

@@ -0,0 +1,89 @@
import { DAL } from "@medusajs/types"
import { generateEntityId } from "@medusajs/utils"
import {
BeforeCreate,
Entity,
OnInit,
OptionalProps,
PrimaryKey,
Property,
ManyToOne,
} from "@mikro-orm/core"
import Customer from "./customer"
type OptionalAddressProps = DAL.EntityDateColumns // TODO: To be revisited when more clear
@Entity({ tableName: "customer_address" })
export default class Address {
[OptionalProps]: OptionalAddressProps
@PrimaryKey({ columnType: "text" })
id!: string
@Property({ columnType: "text" })
customer_id: string
@ManyToOne(() => Customer, {
fieldName: "customer_id",
nullable: true,
})
customer?: Customer
@Property({ columnType: "text", nullable: true })
company: string | null = null
@Property({ columnType: "text", nullable: true })
first_name: string | null = null
@Property({ columnType: "text", nullable: true })
last_name: string | null = null
@Property({ columnType: "text", nullable: true })
address_1: string | null = null
@Property({ columnType: "text", nullable: true })
address_2: string | null = null
@Property({ columnType: "text", nullable: true })
city: string | null = null
@Property({ columnType: "text", nullable: true })
country_code: string | null = null
@Property({ columnType: "text", nullable: true })
province: string | null = null
@Property({ columnType: "text", nullable: true })
postal_code: string | null = null
@Property({ columnType: "text", nullable: true })
phone: string | null = null
@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
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "cuaddr")
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "cuaddr")
}
}

View File

@@ -0,0 +1,65 @@
import { DAL } from "@medusajs/types"
import { generateEntityId } from "@medusajs/utils"
import {
BeforeCreate,
ManyToOne,
Entity,
OnInit,
OptionalProps,
PrimaryKey,
Property,
} from "@mikro-orm/core"
import Customer from "./customer"
import CustomerGroup from "./customer-group"
type OptionalGroupProps = DAL.EntityDateColumns // TODO: To be revisited when more clear
@Entity({ tableName: "customer_group_customer" })
export default class CustomerGroupCustomer {
[OptionalProps]: OptionalGroupProps
@PrimaryKey({ columnType: "text" })
id!: string
@ManyToOne({
entity: () => Customer,
fieldName: "customer__id",
index: "IDX_customer_group_customer_customer_id",
})
customer: Customer
@ManyToOne({
entity: () => CustomerGroup,
fieldName: "customer_group_id",
index: "IDX_customer_group_customer_group_id",
})
customer_group: CustomerGroup
@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
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "cusgc")
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "cusgc")
}
}

View File

@@ -0,0 +1,61 @@
import { DAL } from "@medusajs/types"
import { generateEntityId } from "@medusajs/utils"
import {
BeforeCreate,
Entity,
OnInit,
OptionalProps,
PrimaryKey,
Property,
ManyToMany,
Collection,
} from "@mikro-orm/core"
import Customer from "./customer"
import CustomerGroupCustomer from "./customer-group-customer"
type OptionalGroupProps = DAL.EntityDateColumns // TODO: To be revisited when more clear
@Entity({ tableName: "customer_group" })
export default class CustomerGroup {
[OptionalProps]: OptionalGroupProps
@PrimaryKey({ columnType: "text" })
id!: string
@Property({ columnType: "text", nullable: true })
name: string | null = null
@ManyToMany({
entity: () => Customer,
pivotEntity: () => CustomerGroupCustomer,
})
customers = new Collection<Customer>(this)
@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
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "cusgroup")
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "cusgroup")
}
}

View File

@@ -0,0 +1,115 @@
import { DAL } from "@medusajs/types"
import { generateEntityId } from "@medusajs/utils"
import {
BeforeCreate,
Cascade,
Collection,
Entity,
Index,
ManyToMany,
ManyToOne,
OnInit,
OneToMany,
OptionalProps,
PrimaryKey,
Property,
} from "@mikro-orm/core"
import CustomerGroup from "./customer-group"
import CustomerGroupCustomer from "./customer-group-customer"
import Address from "./address"
type OptionalCustomerProps =
| "groups"
| "addresses"
| "default_shipping_address"
| "default_billing_address"
| DAL.EntityDateColumns
@Entity({ tableName: "customer" })
export default class Customer {
[OptionalProps]?: OptionalCustomerProps
@PrimaryKey({ columnType: "text" })
id: string
@Property({ columnType: "text", nullable: true })
company_name: string | null = null
@Property({ columnType: "text", nullable: true })
first_name: string | null = null
@Property({ columnType: "text", nullable: true })
last_name: string | null = null
@Property({ columnType: "text", nullable: true })
email: string | null = null
@Property({ columnType: "text", nullable: true })
phone: string | null = null
@Index({ name: "IDX_customer_default_shipping_address_id" })
@Property({ columnType: "text", nullable: true })
default_shipping_address_id: string | null = null
@ManyToOne(() => Address, {
fieldName: "default_shipping_address_id",
nullable: true,
})
default_shipping_address: Address | null
@Index({ name: "IDX_customer_default_billing_address_id" })
@Property({ columnType: "text", nullable: true })
default_billing_address_id: string | null = null
@ManyToOne(() => Address, {
fieldName: "default_billing_address_id",
nullable: true,
})
default_billing_address: Address | null
@Property({ columnType: "jsonb", nullable: true })
metadata: Record<string, unknown> | null = null
@ManyToMany({
inversedBy: (group) => group.customers,
entity: () => CustomerGroup,
pivotEntity: () => CustomerGroupCustomer,
})
groups = new Collection<CustomerGroup>(this)
@OneToMany(() => Address, (address) => address.customer, {
cascade: [Cascade.REMOVE],
})
addresses = new Collection<Address>(this)
@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: "timestamptz", nullable: true })
deleted_at: Date | null = null
@Property({ columnType: "text", nullable: true })
created_by: string | null = null
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "cus")
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "cus")
}
}

View File

@@ -0,0 +1,4 @@
export { default as Address } from "./address"
export { default as Customer } from "./customer"
export { default as CustomerGroup } from "./customer-group"
export { default as CustomerGroupCustomer } from "./customer-group-customer"

View File

@@ -0,0 +1,12 @@
import { ModuleExports } from "@medusajs/types"
import { CustomerModuleService } from "@services"
import loadConnection from "./loaders/connection"
import loadContainer from "./loaders/container"
const service = CustomerModuleService
const loaders = [loadContainer, loadConnection] as any
export const moduleDefinition: ModuleExports = {
service,
loaders,
}

View File

@@ -0,0 +1,11 @@
import { DALUtils } from "@medusajs/utils"
import { Address } from "@models"
import { CreateAddressDTO, UpdateAddressDTO } from "@types"
export class AddressRepository extends DALUtils.mikroOrmBaseRepositoryFactory<
Address,
{
create: CreateAddressDTO
update: UpdateAddressDTO
}
>(Address) {}

View File

@@ -0,0 +1,11 @@
import { DALUtils } from "@medusajs/utils"
import { CustomerGroup } from "@models"
import { CreateCustomerGroupDTO, UpdateCustomerGroupDTO } from "@types"
export class CustomerGroupRepository extends DALUtils.mikroOrmBaseRepositoryFactory<
CustomerGroup,
{
create: CreateCustomerGroupDTO
update: UpdateCustomerGroupDTO
}
>(CustomerGroup) {}

View File

@@ -0,0 +1,11 @@
import { DALUtils } from "@medusajs/utils"
import { Customer } from "@models"
import { CreateCustomerDTO, UpdateCustomerDTO } from "@medusajs/types"
export class CustomerRepository extends DALUtils.mikroOrmBaseRepositoryFactory<
Customer,
{
create: CreateCustomerDTO
update: UpdateCustomerDTO
}
>(Customer) {}

View File

@@ -0,0 +1,4 @@
export { MikroOrmBaseRepository as BaseRepository } from "@medusajs/utils"
export * from "./address"
export * from "./customer"
export * from "./customer-group"

View 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-cart-seed <filePath>`
)
}
await run({ path })
})()

View File

@@ -0,0 +1,58 @@
import { Modules } from "@medusajs/modules-sdk"
import { LoaderOptions, Logger, ModulesSdkTypes } from "@medusajs/types"
import { DALUtils, ModulesSdkUtils } from "@medusajs/utils"
import { EntitySchema } from "@mikro-orm/core"
import * as CustomerModels 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 { customerData } = 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: customerData.${EOL}${e}`
)
throw e
}
)
const dbData = ModulesSdkUtils.loadDatabaseConfig(Modules.CUSTOMER, options)!
const entities = Object.values(CustomerModels) as unknown as EntitySchema[]
const pathToMigrations = __dirname + "/../migrations"
const orm = await DALUtils.mikroOrmCreateConnection(
dbData,
entities,
pathToMigrations
)
const manager = orm.em.fork()
try {
logger.info("Seeding customer data..")
// TODO: implement customer seed data
// await createCustomers(manager, customersData)
} catch (e) {
logger.error(
`Failed to insert the seed data in the PostgreSQL database ${dbData.clientUrl}.${EOL}${e}`
)
}
await orm.close(true)
}

View File

@@ -0,0 +1,5 @@
describe("Noop test", () => {
it("noop check", async () => {
expect(true).toBe(true)
})
})

View File

@@ -0,0 +1,23 @@
import { DAL } from "@medusajs/types"
import { ModulesSdkUtils } from "@medusajs/utils"
import { Address } from "@models"
import { CreateAddressDTO, UpdateAddressDTO } from "@types"
type InjectedDependencies = {
addressRepository: DAL.RepositoryService
}
export default class AddressService<
TEntity extends Address = Address
> extends ModulesSdkUtils.abstractServiceFactory<
InjectedDependencies,
{
create: CreateAddressDTO
update: UpdateAddressDTO
}
>(Address)<TEntity> {
constructor(container: InjectedDependencies) {
// @ts-ignore
super(...arguments)
}
}

View File

@@ -0,0 +1,23 @@
import { DAL } from "@medusajs/types"
import { ModulesSdkUtils } from "@medusajs/utils"
import { CustomerGroup } from "@models"
import { CreateCustomerGroupDTO, UpdateCustomerGroupDTO } from "@types"
type InjectedDependencies = {
customerGroupRepository: DAL.RepositoryService
}
export default class CustomerGroupService<
TEntity extends CustomerGroup = CustomerGroup
> extends ModulesSdkUtils.abstractServiceFactory<
InjectedDependencies,
{
create: CreateCustomerGroupDTO
update: UpdateCustomerGroupDTO
}
>(CustomerGroup)<TEntity> {
constructor(container: InjectedDependencies) {
// @ts-ignore
super(...arguments)
}
}

View File

@@ -0,0 +1,81 @@
import {
Context,
DAL,
FindConfig,
ICustomerModuleService,
InternalModuleDeclaration,
ModuleJoinerConfig,
CustomerTypes,
} from "@medusajs/types"
import { InjectManager, MedusaContext } from "@medusajs/utils"
import { joinerConfig } from "../joiner-config"
import * as services from "../services"
type InjectedDependencies = {
baseRepository: DAL.RepositoryService
customerService: services.CustomerService
addressService: services.AddressService
customerGroupService: services.CustomerGroupService
}
export default class CustomerModuleService implements ICustomerModuleService {
protected baseRepository_: DAL.RepositoryService
protected customerService_: services.CustomerService
protected addressService_: services.AddressService
protected customerGroupService_: services.CustomerGroupService
constructor(
{
baseRepository,
customerService,
addressService,
customerGroupService,
}: InjectedDependencies,
protected readonly moduleDeclaration: InternalModuleDeclaration
) {
this.baseRepository_ = baseRepository
this.customerService_ = customerService
this.addressService_ = addressService
this.customerGroupService_ = customerGroupService
}
__joinerConfig(): ModuleJoinerConfig {
return joinerConfig
}
@InjectManager("baseRepository_")
async retrieve(
id: string,
config: FindConfig<CustomerTypes.CustomerDTO> = {},
@MedusaContext() sharedContext: Context = {}
): Promise<CustomerTypes.CustomerDTO> {
const customer = await this.customerService_.retrieve(
id,
config,
sharedContext
)
return await this.baseRepository_.serialize<CustomerTypes.CustomerDTO>(
customer,
{
populate: true,
}
)
}
@InjectManager("baseRepository_")
async create(
data: CustomerTypes.CreateCustomerDTO,
@MedusaContext() sharedContext: Context = {}
): Promise<CustomerTypes.CustomerDTO> {
const [customer] = await this.customerService_.create([data], sharedContext)
return await this.baseRepository_.serialize<CustomerTypes.CustomerDTO>(
customer,
{
populate: true,
}
)
}
}

View File

@@ -0,0 +1,19 @@
import { CreateCustomerDTO, DAL } from "@medusajs/types"
import { ModulesSdkUtils } from "@medusajs/utils"
import { Customer } from "@models"
type InjectedDependencies = {
cartRepository: DAL.RepositoryService
}
export default class CustomerService<
TEntity extends Customer = Customer
> extends ModulesSdkUtils.abstractServiceFactory<
InjectedDependencies,
{ create: CreateCustomerDTO }
>(Customer)<TEntity> {
constructor(container: InjectedDependencies) {
// @ts-ignore
super(...arguments)
}
}

View File

@@ -0,0 +1,4 @@
export { default as AddressService } from "./address"
export { default as CustomerGroupService } from "./customer-group"
export { default as CustomerService } from "./customer"
export { default as CustomerModuleService } from "./customer-module"

View File

@@ -0,0 +1,28 @@
export type CreateAddressDTO = {
customer_id: string
company?: string | null
first_name?: string | null
last_name?: string | null
address_1?: string | null
address_2?: string | null
city?: string | null
country_code?: string | null
province?: string | null
postal_code?: string | null
phone?: string | null
metadata?: Record<string, unknown> | null
}
export type UpdateAddressDTO = {
company?: string | null
first_name?: string | null
last_name?: string | null
address_1?: string | null
address_2?: string | null
city?: string | null
country_code?: string | null
province?: string | null
postal_code?: string | null
phone?: string | null
metadata?: Record<string, unknown> | null
}

View File

@@ -0,0 +1,11 @@
export type CreateCustomerGroupDTO = {
name: string
customer_ids?: string[]
metadata?: Record<string, unknown> | null
}
export type UpdateCustomerGroupDTO = {
name?: string
customer_ids?: string[]
metadata?: Record<string, unknown> | null
}

View File

@@ -0,0 +1,7 @@
import { Logger } from "@medusajs/types"
export * from "./address"
export * from "./customer-group"
export type InitializeModuleInjectableDependencies = {
logger?: Logger
}

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

@@ -16,6 +16,7 @@ export enum Modules {
PROMOTION = "promotion",
AUTHENTICATION = "authentication",
CART = "cart",
CUSTOMER = "customer",
PAYMENT = "payment",
}
@@ -29,6 +30,7 @@ export enum ModuleRegistrationName {
PROMOTION = "promotionModuleService",
AUTHENTICATION = "authenticationModuleService",
CART = "cartModuleService",
CUSTOMER = "customerModuleService",
PAYMENT = "paymentModuleService",
}
@@ -42,6 +44,7 @@ export const MODULE_PACKAGE_NAMES = {
[Modules.PROMOTION]: "@medusajs/promotion",
[Modules.AUTHENTICATION]: "@medusajs/authentication",
[Modules.CART]: "@medusajs/cart",
[Modules.CUSTOMER]: "@medusajs/customer",
[Modules.PAYMENT]: "@medusajs/payment",
}
@@ -174,6 +177,20 @@ export const ModulesDefinition: { [key: string | Modules]: ModuleDefinition } =
resources: MODULE_RESOURCE_TYPE.SHARED,
},
},
[Modules.CUSTOMER]: {
key: Modules.CUSTOMER,
registrationName: ModuleRegistrationName.CUSTOMER,
defaultPackage: false,
label: upperCaseFirst(ModuleRegistrationName.CUSTOMER),
isRequired: false,
canOverride: true,
isQueryable: true,
dependencies: ["logger"],
defaultModuleDeclaration: {
scope: MODULE_SCOPE.INTERNAL,
resources: MODULE_RESOURCE_TYPE.SHARED,
},
},
[Modules.PAYMENT]: {
key: Modules.PAYMENT,
registrationName: ModuleRegistrationName.PAYMENT,

View File

@@ -1,6 +1,25 @@
import { AddressDTO } from "../address"
export interface CustomerDTO {
id: string
email: string
default_billing_address_id?: string | null
default_shipping_address_id?: string | null
company_name?: string | null
first_name?: string | null
last_name?: string | null
default_billing_address?: AddressDTO
default_shipping_address?: AddressDTO
addresses?: AddressDTO[]
phone?: string | null
groups?: { id: string }[]
metadata?: Record<string, unknown>
deleted_at?: Date | string
created_at?: Date | string
updated_at?: Date | string
}
export type legacy_CustomerDTO = {
id: string
email: string
billing_address_id?: string | null

View File

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

View File

@@ -0,0 +1,17 @@
export interface CreateCustomerDTO {
company_name?: string
first_name?: string
last_name?: string
email?: string
phone?: string
metadata?: Record<string, unknown>
}
export interface UpdateCustomerDTO {
company_name?: string
first_name?: string
last_name?: string
email?: string
phone?: string
metadata?: Record<string, unknown>
}

View File

@@ -0,0 +1,15 @@
import { FindConfig } from "../common"
import { IModuleService } from "../modules-sdk"
import { Context } from "../shared-context"
import { CustomerDTO } from "./common"
import { CreateCustomerDTO } from "./mutations"
export interface ICustomerModuleService extends IModuleService {
retrieve(
customerId: string,
config?: FindConfig<CustomerDTO>,
sharedContext?: Context
): Promise<CustomerDTO>
create(data: CreateCustomerDTO, sharedContext?: Context): Promise<CustomerDTO>
}

View File

@@ -7960,6 +7960,33 @@ __metadata:
languageName: unknown
linkType: soft
"@medusajs/customer@workspace:packages/customer":
version: 0.0.0-use.local
resolution: "@medusajs/customer@workspace:packages/customer"
dependencies:
"@medusajs/modules-sdk": ^1.12.5
"@medusajs/types": "workspace:^"
"@medusajs/utils": ^1.11.2
"@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-customer-seed: dist/scripts/bin/run-seed.js
languageName: unknown
linkType: soft
"@medusajs/dashboard@workspace:packages/admin-next/dashboard":
version: 0.0.0-use.local
resolution: "@medusajs/dashboard@workspace:packages/admin-next/dashboard"