feat: Migrate customer module to DML (#10499)

This commit is contained in:
Harminder Virk authored and GitHub committed 2024-12-11 14:37:27 +05:30
1 parent d8a92dbb2d
commit 16d27ea6e4
13 files changed
+421 -473

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
---
"@medusajs/customer": patch
"@medusajs/types": patch
"@medusajs/utils": patch
---
Feat/customer dml
+3 -2
View File
@@ -242,12 +242,13 @@ export type Infer<T> = T extends IDmlEntity<infer Schema, any>
* The actions to cascade from a given entity to its * The actions to cascade from a given entity to its
* relationship. * relationship.
*/ */
export type EntityCascades<Relationships> = { export type EntityCascades<DeletableRelationships, DetachableRelationships> = {
/** /**
* The related models to delete when a record of this data model * The related models to delete when a record of this data model
* is deleted. * is deleted.
*/ */
delete?: Relationships delete?: DeletableRelationships
detach?: DetachableRelationships
} }
/** /**
@@ -6231,6 +6231,86 @@ describe("Entity builder", () => {
}) })
}) })
test("should define onDelete cascade on pivot entity when applying detach cascade", () => {
const teamUser = model.define("teamUser", {
id: model.number(),
user: model.belongsTo(() => user, { mappedBy: "teams" }),
team: model.belongsTo(() => team, { mappedBy: "users" }),
})
const user = model
.define("user", {
id: model.number(),
username: model.text(),
teams: model.manyToMany(() => team, {
pivotEntity: () => teamUser,
}),
})
.cascades({
detach: ["teams"],
})
const team = model
.define("team", {
id: model.number(),
name: model.text(),
users: model.manyToMany(() => user, {
pivotEntity: () => teamUser,
}),
})
.cascades({
detach: ["users"],
})
type CascadeDetach = Parameters<(typeof team)["cascades"]>[0]["detach"]
expectTypeOf<CascadeDetach>().toEqualTypeOf<"users"[] | undefined>()
const [, , TeamUserEntity] = toMikroOrmEntities([user, team, teamUser])
const teamUserMetadata =
MetadataStorage.getMetadataFromDecorator(TeamUserEntity)
expect(teamUserMetadata.properties).toEqual(
expect.objectContaining({
user_id: {
reference: "scalar",
type: "User",
columnType: "text",
fieldName: "user_id",
nullable: false,
name: "user_id",
getter: false,
setter: false,
},
user: {
name: "user",
reference: "m:1",
entity: "User",
nullable: false,
persist: false,
onDelete: "cascade",
},
team_id: {
reference: "scalar",
type: "Team",
columnType: "text",
fieldName: "team_id",
nullable: false,
name: "team_id",
getter: false,
setter: false,
},
team: {
name: "team",
reference: "m:1",
entity: "Team",
nullable: false,
persist: false,
onDelete: "cascade",
},
})
)
})
test("throw error when unable to locate relationship via mappedBy", () => { test("throw error when unable to locate relationship via mappedBy", () => {
const team = model.define("team", { const team = model.define("team", {
id: model.number(), id: model.number(),
+4 -3
View File
@@ -71,7 +71,7 @@ export class DmlEntity<
schema: Schema schema: Schema
readonly #tableName: string readonly #tableName: string
#cascades: EntityCascades<string[]> = {} #cascades: EntityCascades<string[], string[]> = {}
#indexes: EntityIndex<Schema>[] = [] #indexes: EntityIndex<Schema>[] = []
#checks: CheckConstraint<Schema>[] = [] #checks: CheckConstraint<Schema>[] = []
@@ -100,7 +100,7 @@ export class DmlEntity<
name: InferDmlEntityNameFromConfig<TConfig> name: InferDmlEntityNameFromConfig<TConfig>
tableName: string tableName: string
schema: DMLSchema schema: DMLSchema
cascades: EntityCascades<string[]> cascades: EntityCascades<string[], string[]>
indexes: EntityIndex<Schema>[] indexes: EntityIndex<Schema>[]
checks: CheckConstraint<Schema>[] checks: CheckConstraint<Schema>[]
} { } {
@@ -139,7 +139,8 @@ export class DmlEntity<
*/ */
cascades( cascades(
options: EntityCascades< options: EntityCascades<
ExtractEntityRelations<Schema, "hasOne" | "hasOneWithFK" | "hasMany"> ExtractEntityRelations<Schema, "hasOne" | "hasOneWithFK" | "hasMany">,
ExtractEntityRelations<Schema, "manyToMany">
> >
) { ) {
const childToParentCascades = options.delete?.filter((relationship) => { const childToParentCascades = options.delete?.filter((relationship) => {
@@ -144,7 +144,7 @@ export function defineHasOneRelationship(
any any
>, >,
{ relatedModelName }: { relatedModelName: string }, { relatedModelName }: { relatedModelName: string },
cascades: EntityCascades<string[]> cascades: EntityCascades<string[], string[]>
) { ) {
const shouldRemoveRelated = !!cascades.delete?.includes(relationship.name) const shouldRemoveRelated = !!cascades.delete?.includes(relationship.name)
const { schema: relationSchema } = relatedEntity.parse() const { schema: relationSchema } = relatedEntity.parse()
@@ -179,7 +179,7 @@ export function defineHasOneWithFKRelationship(
MikroORMEntity: EntityConstructor<any>, MikroORMEntity: EntityConstructor<any>,
relationship: RelationshipMetadata, relationship: RelationshipMetadata,
{ relatedModelName }: { relatedModelName: string }, { relatedModelName }: { relatedModelName: string },
cascades: EntityCascades<string[]> cascades: EntityCascades<string[], string[]>
) { ) {
const foreignKeyName = camelToSnakeCase(`${relationship.name}Id`) const foreignKeyName = camelToSnakeCase(`${relationship.name}Id`)
const shouldRemoveRelated = !!cascades.delete?.includes(relationship.name) const shouldRemoveRelated = !!cascades.delete?.includes(relationship.name)
@@ -213,7 +213,7 @@ export function defineHasManyRelationship(
MikroORMEntity: EntityConstructor<any>, MikroORMEntity: EntityConstructor<any>,
relationship: RelationshipMetadata, relationship: RelationshipMetadata,
{ relatedModelName }: { relatedModelName: string }, { relatedModelName }: { relatedModelName: string },
cascades: EntityCascades<string[]> cascades: EntityCascades<string[], string[]>
) { ) {
const shouldRemoveRelated = !!cascades.delete?.includes(relationship.name) const shouldRemoveRelated = !!cascades.delete?.includes(relationship.name)
@@ -259,7 +259,7 @@ export function defineBelongsToRelationship(
* define a onDelete: cascade when we are included in the delete * define a onDelete: cascade when we are included in the delete
* list of parent cascade. * list of parent cascade.
*/ */
const shouldCascade = relationCascades.delete?.includes(mappedBy) const shouldCascade = !!relationCascades.delete?.includes(mappedBy)
/** /**
* Ensure the mapped by is defined as relationship on the other side * Ensure the mapped by is defined as relationship on the other side
@@ -337,6 +337,9 @@ export function defineBelongsToRelationship(
DmlManyToMany.isManyToMany(otherSideRelation) DmlManyToMany.isManyToMany(otherSideRelation)
) { ) {
const foreignKeyName = camelToSnakeCase(`${relationship.name}Id`) const foreignKeyName = camelToSnakeCase(`${relationship.name}Id`)
const detachCascade =
!!relationship.mappedBy &&
relationCascades.detach?.includes(relationship.mappedBy)
if (DmlManyToMany.isManyToMany(otherSideRelation)) { if (DmlManyToMany.isManyToMany(otherSideRelation)) {
Property({ Property({
@@ -350,6 +353,7 @@ export function defineBelongsToRelationship(
entity: relatedModelName, entity: relatedModelName,
nullable: relationship.nullable, nullable: relationship.nullable,
persist: false, persist: false,
onDelete: shouldCascade || detachCascade ? "cascade" : undefined,
})(MikroORMEntity.prototype, relationship.name) })(MikroORMEntity.prototype, relationship.name)
} else { } else {
ManyToOne({ ManyToOne({
@@ -660,7 +664,7 @@ export function defineRelationship(
MikroORMEntity: EntityConstructor<any>, MikroORMEntity: EntityConstructor<any>,
entity: DmlEntity<any, any>, entity: DmlEntity<any, any>,
relationship: RelationshipMetadata, relationship: RelationshipMetadata,
cascades: EntityCascades<string[]>, cascades: EntityCascades<string[], string[]>,
context: Context context: Context
) { ) {
/** /**
@@ -16,9 +16,9 @@ moduleIntegrationTestRunner<ICustomerModuleService>({
expect(Object.keys(linkable)).toEqual([ expect(Object.keys(linkable)).toEqual([
"customerAddress", "customerAddress",
"customerGroupCustomer",
"customerGroup",
"customer", "customer",
"customerGroup",
"customerGroupCustomer",
]) ])
Object.keys(linkable).forEach((key) => { Object.keys(linkable).forEach((key) => {
@@ -1,5 +1,7 @@
{ {
"namespaces": ["public"], "namespaces": [
"public"
],
"name": "public", "name": "public",
"tables": [ "tables": [
{ {
@@ -77,6 +79,15 @@
"nullable": true, "nullable": true,
"mappedType": "json" "mappedType": "json"
}, },
"created_by": {
"name": "created_by",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"mappedType": "text"
},
"created_at": { "created_at": {
"name": "created_at", "name": "created_at",
"type": "timestamptz", "type": "timestamptz",
@@ -108,20 +119,19 @@
"nullable": true, "nullable": true,
"length": 6, "length": 6,
"mappedType": "datetime" "mappedType": "datetime"
},
"created_by": {
"name": "created_by",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"mappedType": "text"
} }
}, },
"name": "customer", "name": "customer",
"schema": "public", "schema": "public",
"indexes": [ "indexes": [
{
"keyName": "IDX_customer_deleted_at",
"columnNames": [],
"composite": false,
"primary": false,
"unique": false,
"expression": "CREATE INDEX IF NOT EXISTS \"IDX_customer_deleted_at\" ON \"customer\" (deleted_at) WHERE deleted_at IS NULL"
},
{ {
"keyName": "IDX_customer_email_has_account_unique", "keyName": "IDX_customer_email_has_account_unique",
"columnNames": [], "columnNames": [],
@@ -132,7 +142,9 @@
}, },
{ {
"keyName": "customer_pkey", "keyName": "customer_pkey",
"columnNames": ["id"], "columnNames": [
"id"
],
"composite": false, "composite": false,
"primary": true, "primary": true,
"unique": true "unique": true
@@ -181,15 +193,6 @@
"default": "false", "default": "false",
"mappedType": "boolean" "mappedType": "boolean"
}, },
"customer_id": {
"name": "customer_id",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "text"
},
"company": { "company": {
"name": "company", "name": "company",
"type": "text", "type": "text",
@@ -289,6 +292,15 @@
"nullable": true, "nullable": true,
"mappedType": "json" "mappedType": "json"
}, },
"customer_id": {
"name": "customer_id",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "text"
},
"created_at": { "created_at": {
"name": "created_at", "name": "created_at",
"type": "timestamptz", "type": "timestamptz",
@@ -310,17 +322,36 @@
"length": 6, "length": 6,
"default": "now()", "default": "now()",
"mappedType": "datetime" "mappedType": "datetime"
},
"deleted_at": {
"name": "deleted_at",
"type": "timestamptz",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"length": 6,
"mappedType": "datetime"
} }
}, },
"name": "customer_address", "name": "customer_address",
"schema": "public", "schema": "public",
"indexes": [ "indexes": [
{ {
"columnNames": ["customer_id"],
"composite": false,
"keyName": "IDX_customer_address_customer_id", "keyName": "IDX_customer_address_customer_id",
"columnNames": [],
"composite": false,
"primary": false, "primary": false,
"unique": false "unique": false,
"expression": "CREATE INDEX IF NOT EXISTS \"IDX_customer_address_customer_id\" ON \"customer_address\" (customer_id) WHERE deleted_at IS NULL"
},
{
"keyName": "IDX_customer_address_deleted_at",
"columnNames": [],
"composite": false,
"primary": false,
"unique": false,
"expression": "CREATE INDEX IF NOT EXISTS \"IDX_customer_address_deleted_at\" ON \"customer_address\" (deleted_at) WHERE deleted_at IS NULL"
}, },
{ {
"keyName": "IDX_customer_address_unique_customer_billing", "keyName": "IDX_customer_address_unique_customer_billing",
@@ -328,7 +359,7 @@
"composite": false, "composite": false,
"primary": false, "primary": false,
"unique": false, "unique": false,
"expression": "CREATE UNIQUE INDEX IF NOT EXISTS \"IDX_customer_address_unique_customer_billing\" ON \"customer_address\" (customer_id) WHERE \"is_default_billing\" = true" "expression": "CREATE UNIQUE INDEX IF NOT EXISTS \"IDX_customer_address_unique_customer_billing\" ON \"customer_address\" (customer_id) WHERE \"is_default_billing\" = true AND deleted_at IS NULL"
}, },
{ {
"keyName": "IDX_customer_address_unique_customer_shipping", "keyName": "IDX_customer_address_unique_customer_shipping",
@@ -336,11 +367,13 @@
"composite": false, "composite": false,
"primary": false, "primary": false,
"unique": false, "unique": false,
"expression": "CREATE UNIQUE INDEX IF NOT EXISTS \"IDX_customer_address_unique_customer_shipping\" ON \"customer_address\" (customer_id) WHERE \"is_default_shipping\" = true" "expression": "CREATE UNIQUE INDEX IF NOT EXISTS \"IDX_customer_address_unique_customer_shipping\" ON \"customer_address\" (customer_id) WHERE \"is_default_shipping\" = true AND deleted_at IS NULL"
}, },
{ {
"keyName": "customer_address_pkey", "keyName": "customer_address_pkey",
"columnNames": ["id"], "columnNames": [
"id"
],
"composite": false, "composite": false,
"primary": true, "primary": true,
"unique": true "unique": true
@@ -350,9 +383,13 @@
"foreignKeys": { "foreignKeys": {
"customer_address_customer_id_foreign": { "customer_address_customer_id_foreign": {
"constraintName": "customer_address_customer_id_foreign", "constraintName": "customer_address_customer_id_foreign",
"columnNames": ["customer_id"], "columnNames": [
"customer_id"
],
"localTableName": "public.customer_address", "localTableName": "public.customer_address",
"referencedColumnNames": ["id"], "referencedColumnNames": [
"id"
],
"referencedTableName": "public.customer", "referencedTableName": "public.customer",
"deleteRule": "cascade", "deleteRule": "cascade",
"updateRule": "cascade" "updateRule": "cascade"
@@ -433,9 +470,17 @@
"name": "customer_group", "name": "customer_group",
"schema": "public", "schema": "public",
"indexes": [ "indexes": [
{
"keyName": "IDX_customer_group_deleted_at",
"columnNames": [],
"composite": false,
"primary": false,
"unique": false,
"expression": "CREATE INDEX IF NOT EXISTS \"IDX_customer_group_deleted_at\" ON \"customer_group\" (deleted_at) WHERE deleted_at IS NULL"
},
{ {
"keyName": "IDX_customer_group_name_unique", "keyName": "IDX_customer_group_name_unique",
"columnNames": ["name"], "columnNames": [],
"composite": false, "composite": false,
"primary": false, "primary": false,
"unique": false, "unique": false,
@@ -443,7 +488,9 @@
}, },
{ {
"keyName": "customer_group_pkey", "keyName": "customer_group_pkey",
"columnNames": ["id"], "columnNames": [
"id"
],
"composite": false, "composite": false,
"primary": true, "primary": true,
"unique": true "unique": true
@@ -463,6 +510,24 @@
"nullable": false, "nullable": false,
"mappedType": "text" "mappedType": "text"
}, },
"created_by": {
"name": "created_by",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"mappedType": "text"
},
"metadata": {
"name": "metadata",
"type": "jsonb",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"mappedType": "json"
},
"customer_id": { "customer_id": {
"name": "customer_id", "name": "customer_id",
"type": "text", "type": "text",
@@ -481,15 +546,6 @@
"nullable": false, "nullable": false,
"mappedType": "text" "mappedType": "text"
}, },
"metadata": {
"name": "metadata",
"type": "jsonb",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"mappedType": "json"
},
"created_at": { "created_at": {
"name": "created_at", "name": "created_at",
"type": "timestamptz", "type": "timestamptz",
@@ -512,60 +568,56 @@
"default": "now()", "default": "now()",
"mappedType": "datetime" "mappedType": "datetime"
}, },
"created_by": { "deleted_at": {
"name": "created_by", "name": "deleted_at",
"type": "text", "type": "timestamptz",
"unsigned": false, "unsigned": false,
"autoincrement": false, "autoincrement": false,
"primary": false, "primary": false,
"nullable": true, "nullable": true,
"mappedType": "text" "length": 6,
"mappedType": "datetime"
} }
}, },
"name": "customer_group_customer", "name": "customer_group_customer",
"schema": "public", "schema": "public",
"indexes": [ "indexes": [
{ {
"columnNames": ["customer_group_id"], "keyName": "IDX_customer_group_customer_customer_id",
"columnNames": [],
"composite": false, "composite": false,
"keyName": "IDX_customer_group_customer_group_id",
"primary": false, "primary": false,
"unique": false "unique": false,
"expression": "CREATE INDEX IF NOT EXISTS \"IDX_customer_group_customer_customer_id\" ON \"customer_group_customer\" (customer_id) WHERE deleted_at IS NULL"
}, },
{ {
"columnNames": ["customer_id"], "keyName": "IDX_customer_group_customer_customer_group_id",
"columnNames": [],
"composite": false, "composite": false,
"keyName": "IDX_customer_group_customer_customer_id",
"primary": false, "primary": false,
"unique": false "unique": false,
"expression": "CREATE INDEX IF NOT EXISTS \"IDX_customer_group_customer_customer_group_id\" ON \"customer_group_customer\" (customer_group_id) WHERE deleted_at IS NULL"
},
{
"keyName": "IDX_customer_group_customer_deleted_at",
"columnNames": [],
"composite": false,
"primary": false,
"unique": false,
"expression": "CREATE INDEX IF NOT EXISTS \"IDX_customer_group_customer_deleted_at\" ON \"customer_group_customer\" (deleted_at) WHERE deleted_at IS NULL"
}, },
{ {
"keyName": "customer_group_customer_pkey", "keyName": "customer_group_customer_pkey",
"columnNames": ["id"], "columnNames": [
"id"
],
"composite": false, "composite": false,
"primary": true, "primary": true,
"unique": true "unique": true
} }
], ],
"checks": [], "checks": [],
"foreignKeys": { "foreignKeys": {}
"customer_group_customer_customer_group_id_foreign": {
"constraintName": "customer_group_customer_customer_group_id_foreign",
"columnNames": ["customer_group_id"],
"localTableName": "public.customer_group_customer",
"referencedColumnNames": ["id"],
"referencedTableName": "public.customer_group",
"deleteRule": "cascade"
},
"customer_group_customer_customer_id_foreign": {
"constraintName": "customer_group_customer_customer_id_foreign",
"columnNames": ["customer_id"],
"localTableName": "public.customer_group_customer",
"referencedColumnNames": ["id"],
"referencedTableName": "public.customer",
"deleteRule": "cascade"
}
}
} }
] ]
} }
@@ -0,0 +1,75 @@
import { Migration } from "@mikro-orm/migrations"
export class Migration20241211074630 extends Migration {
async up(): Promise<void> {
this.addSql(
'alter table if exists "customer_group_customer" drop constraint if exists "customer_group_customer_customer_group_id_foreign";'
)
this.addSql(
'alter table if exists "customer_group_customer" drop constraint if exists "customer_group_customer_customer_id_foreign";'
)
this.addSql(
'CREATE INDEX IF NOT EXISTS "IDX_customer_deleted_at" ON "customer" (deleted_at) WHERE deleted_at IS NULL;'
)
this.addSql(
'alter table if exists "customer_address" add column if not exists "deleted_at" timestamptz null;'
)
this.addSql(
'CREATE INDEX IF NOT EXISTS "IDX_customer_address_deleted_at" ON "customer_address" (deleted_at) WHERE deleted_at IS NULL;'
)
this.addSql(
'CREATE INDEX IF NOT EXISTS "IDX_customer_group_deleted_at" ON "customer_group" (deleted_at) WHERE deleted_at IS NULL;'
)
this.addSql(
'alter table if exists "customer_group_customer" add column if not exists "deleted_at" timestamptz null;'
)
this.addSql('drop index if exists "IDX_customer_group_customer_group_id";')
this.addSql(
'alter table if exists "customer_group_customer" add constraint "customer_group_customer_customer_group_id_foreign" foreign key ("customer_group_id") references "customer_group" ("id") on update cascade on delete cascade;'
)
this.addSql(
'alter table if exists "customer_group_customer" add constraint "customer_group_customer_customer_id_foreign" foreign key ("customer_id") references "customer" ("id") on update cascade on delete cascade;'
)
this.addSql(
'CREATE INDEX IF NOT EXISTS "IDX_customer_group_customer_customer_group_id" ON "customer_group_customer" (customer_group_id) WHERE deleted_at IS NULL;'
)
this.addSql(
'CREATE INDEX IF NOT EXISTS "IDX_customer_group_customer_deleted_at" ON "customer_group_customer" (deleted_at) WHERE deleted_at IS NULL;'
)
}
async down(): Promise<void> {
this.addSql('drop index if exists "IDX_customer_deleted_at";')
this.addSql('drop index if exists "IDX_customer_address_deleted_at";')
this.addSql(
'alter table if exists "customer_address" drop column if exists "deleted_at";'
)
this.addSql('drop index if exists "IDX_customer_group_deleted_at";')
this.addSql(
'drop index if exists "IDX_customer_group_customer_customer_group_id";'
)
this.addSql(
'drop index if exists "IDX_customer_group_customer_deleted_at";'
)
this.addSql(
'alter table if exists "customer_group_customer" drop column if exists "deleted_at";'
)
this.addSql(
'alter table if exists "customer_group_customer" add constraint "customer_group_customer_customer_group_id_foreign" foreign key ("customer_group_id") references "customer_group" ("id") on delete cascade;'
)
this.addSql(
'alter table if exists "customer_group_customer" add constraint "customer_group_customer_customer_id_foreign" foreign key ("customer_id") references "customer" ("id") on delete cascade;'
)
this.addSql(
'create index if not exists "IDX_customer_group_customer_group_id" on "customer_group_customer" ("customer_group_id");'
)
}
}
+33 -126
View File
@@ -1,133 +1,40 @@
import { DAL } from "@medusajs/framework/types" import { model } from "@medusajs/framework/utils"
import {
createPsqlIndexStatementHelper,
generateEntityId,
Searchable,
} from "@medusajs/framework/utils"
import {
BeforeCreate,
Cascade,
Entity,
ManyToOne,
OnInit,
OptionalProps,
PrimaryKey,
Property,
} from "@mikro-orm/core"
import Customer from "./customer" import Customer from "./customer"
type OptionalAddressProps = DAL.ModelDateColumns // TODO: To be revisited when more clear const CustomerAddress = model
.define("CustomerAddress", {
const CustomerAddressUniqueCustomerShippingAddress = id: model.id({ prefix: "cuaddr" }).primaryKey(),
createPsqlIndexStatementHelper({ address_name: model.text().searchable().nullable(),
name: "IDX_customer_address_unique_customer_shipping", is_default_shipping: model.boolean().default(false),
tableName: "customer_address", is_default_billing: model.boolean().default(false),
columns: "customer_id", company: model.text().searchable().nullable(),
unique: true, first_name: model.text().searchable().nullable(),
where: '"is_default_shipping" = true', last_name: model.text().searchable().nullable(),
address_1: model.text().searchable().nullable(),
address_2: model.text().searchable().nullable(),
city: model.text().searchable().nullable(),
country_code: model.text().nullable(),
province: model.text().searchable().nullable(),
postal_code: model.text().searchable().nullable(),
phone: model.text().nullable(),
metadata: model.json().nullable(),
customer: model.belongsTo(() => Customer, {
mappedBy: "addresses",
}),
}) })
.indexes([
const CustomerAddressUniqueCustomerBillingAddress = {
createPsqlIndexStatementHelper({
name: "IDX_customer_address_unique_customer_billing", name: "IDX_customer_address_unique_customer_billing",
tableName: "customer_address", on: ["customer_id"],
columns: "customer_id",
unique: true, unique: true,
where: '"is_default_billing" = true', where: '"is_default_billing" = true',
}) },
{
name: "IDX_customer_address_unique_customer_shipping",
on: ["customer_id"],
unique: true,
where: '"is_default_shipping" = true',
},
])
@Entity({ tableName: "customer_address" }) export default CustomerAddress
@CustomerAddressUniqueCustomerShippingAddress.MikroORMIndex()
@CustomerAddressUniqueCustomerBillingAddress.MikroORMIndex()
export default class CustomerAddress {
[OptionalProps]: OptionalAddressProps
@PrimaryKey({ columnType: "text" })
id!: string
@Searchable()
@Property({ columnType: "text", nullable: true })
address_name: string | null = null
@Property({ columnType: "boolean", default: false })
is_default_shipping: boolean = false
@Property({ columnType: "boolean", default: false })
is_default_billing: boolean = false
@Property({ columnType: "text" })
customer_id: string
@ManyToOne(() => Customer, {
fieldName: "customer_id",
index: "IDX_customer_address_customer_id",
cascade: [Cascade.REMOVE, Cascade.PERSIST],
})
customer: Customer
@Searchable()
@Property({ columnType: "text", nullable: true })
company: string | null = null
@Searchable()
@Property({ columnType: "text", nullable: true })
first_name: string | null = null
@Searchable()
@Property({ columnType: "text", nullable: true })
last_name: string | null = null
@Searchable()
@Property({ columnType: "text", nullable: true })
address_1: string | null = null
@Searchable()
@Property({ columnType: "text", nullable: true })
address_2: string | null = null
@Searchable()
@Property({ columnType: "text", nullable: true })
city: string | null = null
@Property({ columnType: "text", nullable: true })
country_code: string | null = null
@Searchable()
@Property({ columnType: "text", nullable: true })
province: string | null = null
@Searchable()
@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")
}
}
@@ -1,78 +1,17 @@
import { DAL } from "@medusajs/framework/types" import { model } from "@medusajs/framework/utils"
import { generateEntityId } from "@medusajs/framework/utils"
import {
BeforeCreate,
Cascade,
Entity,
ManyToOne,
OnInit,
OptionalProps,
PrimaryKey,
Property,
Rel,
} from "@mikro-orm/core"
import Customer from "./customer" import Customer from "./customer"
import CustomerGroup from "./customer-group" import CustomerGroup from "./customer-group"
type OptionalGroupProps = "customer_group" | "customer" | DAL.ModelDateColumns // TODO: To be revisited when more clear const CustomerGroupCustomer = model.define("CustomerGroupCustomer", {
id: model.id({ prefix: "cusgc" }).primaryKey(),
@Entity({ tableName: "customer_group_customer" }) created_by: model.text().nullable(),
export default class CustomerGroupCustomer { metadata: model.json().nullable(),
[OptionalProps]: OptionalGroupProps customer: model.belongsTo(() => Customer, {
mappedBy: "groups",
@PrimaryKey({ columnType: "text" }) }),
id!: string customer_group: model.belongsTo(() => CustomerGroup, {
mappedBy: "customers",
@Property({ columnType: "text" }) }),
customer_id: string
@Property({ columnType: "text" })
customer_group_id: string
@ManyToOne({
entity: () => Customer,
fieldName: "customer_id",
index: "IDX_customer_group_customer_customer_id",
cascade: [Cascade.REMOVE],
}) })
customer: Rel<Customer>
@ManyToOne({ export default CustomerGroupCustomer
entity: () => CustomerGroup,
fieldName: "customer_group_id",
index: "IDX_customer_group_customer_group_id",
cascade: [Cascade.REMOVE],
})
customer_group: Rel<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
@Property({ columnType: "text", nullable: true })
created_by: string | null = null
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "cusgc")
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "cusgc")
}
}
@@ -1,84 +1,27 @@
import { DAL } from "@medusajs/framework/types" import { model } from "@medusajs/framework/utils"
import {
DALUtils,
Searchable,
createPsqlIndexStatementHelper,
generateEntityId,
} from "@medusajs/framework/utils"
import {
BeforeCreate,
Collection,
Entity,
Filter,
ManyToMany,
OnInit,
OptionalProps,
PrimaryKey,
Property,
Rel,
} from "@mikro-orm/core"
import Customer from "./customer" import Customer from "./customer"
import CustomerGroupCustomer from "./customer-group-customer" import { CustomerGroupCustomer } from "@models"
type OptionalGroupProps = DAL.SoftDeletableModelDateColumns // TODO: To be revisited when more clear const CustomerGroup = model
.define("CustomerGroup", {
const CustomerGroupUniqueName = createPsqlIndexStatementHelper({ id: model.id({ prefix: "cusgroup" }).primaryKey(),
tableName: "customer_group", name: model.text().searchable(),
columns: ["name"], metadata: model.json().nullable(),
created_by: model.text().nullable(),
customers: model.manyToMany(() => Customer, {
mappedBy: "groups",
pivotEntity: () => CustomerGroupCustomer,
}),
})
.indexes([
{
on: ["name"],
unique: true, unique: true,
where: "deleted_at IS NULL", where: "deleted_at IS NULL",
},
])
.cascades({
detach: ["customers"],
}) })
@Entity({ tableName: "customer_group" }) export default CustomerGroup
@Filter(DALUtils.mikroOrmSoftDeletableFilterOptions)
export default class CustomerGroup {
[OptionalProps]: OptionalGroupProps
@PrimaryKey({ columnType: "text" })
id!: string
@Searchable()
@CustomerGroupUniqueName.MikroORMIndex()
@Property({ columnType: "text" })
name: string
@ManyToMany({
entity: () => Customer,
pivotEntity: () => CustomerGroupCustomer,
})
customers = new Collection<Rel<Customer>>(this)
@Property({ columnType: "jsonb", nullable: true })
metadata: Record<string, unknown> | null = null
@Property({ columnType: "text", nullable: true })
created_by: string | 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: "timestamptz", nullable: true })
deleted_at: Date | null = null
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "cusgroup")
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "cusgroup")
}
}
+30 -108
View File
@@ -1,115 +1,37 @@
import { DAL } from "@medusajs/framework/types" import { model } from "@medusajs/framework/utils"
import {
createPsqlIndexStatementHelper,
DALUtils,
generateEntityId,
Searchable,
} from "@medusajs/framework/utils"
import {
BeforeCreate,
Cascade,
Collection,
Entity,
Filter,
ManyToMany,
OneToMany,
OnInit,
OptionalProps,
PrimaryKey,
Property,
Rel,
} from "@mikro-orm/core"
import CustomerAddress from "./address" import CustomerAddress from "./address"
import CustomerGroup from "./customer-group" import CustomerGroup from "./customer-group"
import CustomerGroupCustomer from "./customer-group-customer" import CustomerGroupCustomer from "./customer-group-customer"
type OptionalCustomerProps = const Customer = model
| "groups" .define("Customer", {
| "addresses" id: model.id({ prefix: "cus" }).primaryKey(),
| DAL.SoftDeletableModelDateColumns company_name: model.text().searchable().nullable(),
first_name: model.text().searchable().nullable(),
const CustomerUniqueEmail = createPsqlIndexStatementHelper({ last_name: model.text().searchable().nullable(),
tableName: "customer", email: model.text().searchable().nullable(),
columns: ["email", "has_account"], phone: model.text().searchable().nullable(),
has_account: model.boolean().default(false),
metadata: model.json().nullable(),
created_by: model.text().nullable(),
groups: model.manyToMany(() => CustomerGroup, {
mappedBy: "customers",
pivotEntity: () => CustomerGroupCustomer,
}),
addresses: model.hasMany(() => CustomerAddress, {
mappedBy: "customer",
}),
})
.cascades({
delete: ["addresses"],
detach: ["groups"],
})
.indexes([
{
on: ["email", "has_account"],
unique: true, unique: true,
where: "deleted_at IS NULL", where: "deleted_at IS NULL",
}) },
])
@Entity({ tableName: "customer" }) export default Customer
@Filter(DALUtils.mikroOrmSoftDeletableFilterOptions)
@CustomerUniqueEmail.MikroORMIndex()
export default class Customer {
[OptionalProps]?: OptionalCustomerProps
@PrimaryKey({ columnType: "text" })
id: string
@Searchable()
@Property({ columnType: "text", nullable: true })
company_name: string | null = null
@Searchable()
@Property({ columnType: "text", nullable: true })
first_name: string | null = null
@Searchable()
@Property({ columnType: "text", nullable: true })
last_name: string | null = null
@Searchable()
@Property({ columnType: "text", nullable: true })
email: string | null = null
@Searchable()
@Property({ columnType: "text", nullable: true })
phone: string | null = null
@Property({ columnType: "boolean", default: false })
has_account: boolean = false
@Property({ columnType: "jsonb", nullable: true })
metadata: Record<string, unknown> | null = null
@ManyToMany({
mappedBy: "customers",
entity: () => CustomerGroup,
pivotEntity: () => CustomerGroupCustomer,
})
groups = new Collection<Rel<CustomerGroup>>(this)
@OneToMany(() => CustomerAddress, (address) => address.customer, {
cascade: [Cascade.REMOVE],
})
addresses = new Collection<Rel<CustomerAddress>>(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")
}
}
@@ -7,6 +7,7 @@ import {
CustomerTypes, CustomerTypes,
DAL, DAL,
ICustomerModuleService, ICustomerModuleService,
InferEntityType,
InternalModuleDeclaration, InternalModuleDeclaration,
ModuleJoinerConfig, ModuleJoinerConfig,
ModulesSdkTypes, ModulesSdkTypes,
@@ -51,10 +52,18 @@ export default class CustomerModuleService
implements ICustomerModuleService implements ICustomerModuleService
{ {
protected baseRepository_: DAL.RepositoryService protected baseRepository_: DAL.RepositoryService
protected customerService_: ModulesSdkTypes.IMedusaInternalService<Customer> protected customerService_: ModulesSdkTypes.IMedusaInternalService<
protected customerAddressService_: ModulesSdkTypes.IMedusaInternalService<CustomerAddress> InferEntityType<typeof Customer>
protected customerGroupService_: ModulesSdkTypes.IMedusaInternalService<CustomerGroup> >
protected customerGroupCustomerService_: ModulesSdkTypes.IMedusaInternalService<CustomerGroupCustomer> protected customerAddressService_: ModulesSdkTypes.IMedusaInternalService<
InferEntityType<typeof CustomerAddress>
>
protected customerGroupService_: ModulesSdkTypes.IMedusaInternalService<
InferEntityType<typeof CustomerGroup>
>
protected customerGroupCustomerService_: ModulesSdkTypes.IMedusaInternalService<
InferEntityType<typeof CustomerGroupCustomer>
>
constructor( constructor(
{ {
@@ -117,8 +126,14 @@ export default class CustomerModuleService
@MedusaContext() sharedContext: Context = {} @MedusaContext() sharedContext: Context = {}
): Promise<CustomerTypes.CustomerDTO[]> { ): Promise<CustomerTypes.CustomerDTO[]> {
const data = Array.isArray(dataOrArray) ? dataOrArray : [dataOrArray] const data = Array.isArray(dataOrArray) ? dataOrArray : [dataOrArray]
const customerAttributes = data.map(({ addresses, ...rest }) => {
return rest
})
const customers = await this.customerService_.create(data, sharedContext) const customers = await this.customerService_.create(
customerAttributes,
sharedContext
)
const addressDataWithCustomerIds = data const addressDataWithCustomerIds = data
.map(({ addresses }, i) => { .map(({ addresses }, i) => {
@@ -320,9 +335,11 @@ export default class CustomerModuleService
) )
if (Array.isArray(data)) { if (Array.isArray(data)) {
return (groupCustomers as unknown as CustomerGroupCustomer[]).map( return (
(gc) => ({ id: gc.id }) groupCustomers as unknown as InferEntityType<
) typeof CustomerGroupCustomer
>[]
).map((gc) => ({ id: gc.id }))
} }
return { id: groupCustomers.id } return { id: groupCustomers.id }