feat: customer module skeleton (#6126)

This commit is contained in:
Sebastian Rindom
2024-01-19 10:18:54 +00:00
committed by GitHub
parent a12c28b7d5
commit 12aa1737d5
47 changed files with 1157 additions and 0 deletions
+24
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"
+31
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]
}
+31
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,
},
},
}
@@ -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,
})
}
@@ -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(),
})
}
+2
View File
@@ -0,0 +1,2 @@
export * from "./connection"
export * from "./container"
+89
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")
}
}
@@ -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")
}
}
@@ -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")
}
}
+115
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")
}
}
+4
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"
@@ -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,
}
@@ -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) {}
@@ -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) {}
@@ -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) {}
@@ -0,0 +1,4 @@
export { MikroOrmBaseRepository as BaseRepository } from "@medusajs/utils"
export * from "./address"
export * from "./customer"
export * from "./customer-group"
@@ -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 })
})()
+58
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)
}
@@ -0,0 +1,5 @@
describe("Noop test", () => {
it("noop check", async () => {
expect(true).toBe(true)
})
})
+23
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)
}
}
@@ -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)
}
}
@@ -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,
}
)
}
}
@@ -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)
}
}
+4
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"
+28
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
}
@@ -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
}
+7
View File
@@ -0,0 +1,7 @@
import { Logger } from "@medusajs/types"
export * from "./address"
export * from "./customer-group"
export type InitializeModuleInjectableDependencies = {
logger?: Logger
}