chore(order): dml (#10292)

* ../../core/types/src/dml/index.ts

* ../../core/types/src/dml/index.ts

* fix: relationships mapping

* handle nullable foreign keys types

* handle nullable foreign keys types

* handle nullable foreign keys types

* continue to update product category repository

* fix all product category repositories issues

* fix product category service types

* fix product module service types

* fix product module service types

* fix repository template type

* refactor: use a singleton DMLToMikroORM factory instance

Since the MikroORM MetadataStorage is global, we will also have to turn DML
to MikroORM entities conversion use a global bucket as well

* refactor: update product module to use DML in tests

* wip: tests

* WIP product linkable fixes

* continue type fixing and start test fixing

* test: fix more tests

* fix repository

* fix pivot table computaion + fix mikro orm repository

* fix many to many management and configuration

* fix many to many management and configuration

* fix many to many management and configuration

* update product tag relation configuration

* Introduce experimental dml hooks to fix some issues with categories

* more fixes

* fix product tests

* add missing id prefixes

* fix product category handle management

* test: fix more failing tests

* test: make it all green

* test: fix breaking tests

* fix: build issues

* fix: build issues

* fix: more breaking tests

* refactor: fix issues after merge

* refactor: fix issues after merge

* refactor: surpress types error

* test: fix DML failing tests

* improve many to many inference + tests

* Wip fix columns from product entity

* remove product model before create hook and manage handle validation and transformation at the service level

* test: fix breaking unit tests

* fix: product module service to not update handle on product update

* fix define link and joiner config

* test: fix joiner config test

* test: fix joiner config test

* fix joiner config primary keys

* Fix joiner config builder

* Fix joiner config builder

* test: remove only modifier from test

* refactor: remove hooks usage from product collection

* refactor: remove hooks usage from product-option

* refactor: remove hooks usage for computing category handle

* refactor: remove hooks usage from productCategory model

* refactor: remove hooks from DML

* refactor: remove cruft

* order dml

* cleanup

* re add foerign key indexes

* wip

* chore: remove unused types

* wip

* changes

* rm raw

* autoincrement

* wip

* rel

* refactor: cleanup

* migration and models configuration adjustments

* cleanup

* number searchable

* fix random ordering

* fix

* test: fix product-category tests

* test: update breaking DML tests

* test: array assertion to not care about ordering

* fix: temporarily apply id ordering for products

* types

* wip

* WIP type improvements

* update order models

* partially fix types temporarely

* rel

* fix: recursive type issue

* improve type inference breaks

* improve type inference breaks

* update models

* rm nullable

* default value

* repository

* update default value handling

* fix unit tests

* WIP

* toMikroORM

* fix relations

* cascades

* fix

* experimental dml hooks

* rm migration

* serial

* nullable autoincrement

* fix model

* model changes

* fix one to one DML

* order test

* fix addresses

* fix unit tests

* Re align dml entity name inference

* update model table name config

* update model table name config

* revert

* update return relation

* WIP

* hasOne

* models

* fix

* model

* initial commit

* cart service

* order module

* utils unit test

* index engine

* changeset

* merge

* fix hasOne with fk

* update

* free text filter per entity

* tests

* prod category

* property string many to many

* fix big number

* link modules migration set names

* merge

* shipping option rules

* serializer

* unit test

* fix test mikro orm init

* fix test mikro orm init

* Maintain merge object properties

* fix test mikro orm init

* prevent unit test from connecting to db

* wip

* fix test

* fix test

* link test

* schema

* models

* auto increment

* hook

* model hooks

* order

* wip

* orm version

* request return field

* fix return configuration on order model

* workflows

* core flows

* unit test

* test

* base repo

* test

* base repo

* test fix

* inventory move

* locking inventory

* test

* free text fix

* rm timeout mock

* migrate fulfillment values

* v6.4.3

* cleanup

* link-modules update sql

* revert test

* remove fake timers

---------

Co-authored-by: adrien2p <adrien.deperetti@gmail.com>
Co-authored-by: Harminder Virk <virk.officials@gmail.com>
Co-authored-by: Oli Juhl <59018053+olivermrbl@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2025-01-21 08:04:47 -05:00
1 parent 05c8a67d8e
commit cc73802ab3
178 files changed
+5731 -7120

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -0,0 +1,18 @@
import { Migration } from "@mikro-orm/migrations"
export class Migration20241129124827 extends Migration {
async up(): Promise<void> {
this.addSql(
'alter table if exists "order_address" add column if not exists "deleted_at" timestamptz null;'
)
this.addSql(
'CREATE INDEX IF NOT EXISTS "IDX_order_address_deleted_at" ON "order_address" (deleted_at) WHERE deleted_at IS NULL;'
)
}
async down(): Promise<void> {
this.addSql(`
ALTER TABLE "order_address" DROP COLUMN if exists "deleted_at";
`)
}
}
+24 -97
View File
@@ -1,100 +1,27 @@
import { DAL } from "@medusajs/framework/types"
import {
createPsqlIndexStatementHelper,
generateEntityId,
Searchable,
} from "@medusajs/framework/utils"
import {
BeforeCreate,
Entity,
OnInit,
OptionalProps,
PrimaryKey,
Property,
} from "@mikro-orm/core"
import { model } from "@medusajs/framework/utils"
type OptionalAddressProps = DAL.ModelDateColumns
const CustomerIdIndex = createPsqlIndexStatementHelper({
tableName: "order_address",
columns: "customer_id",
})
@Entity({ tableName: "order_address" })
export default class OrderAddress {
[OptionalProps]: OptionalAddressProps
@PrimaryKey({ columnType: "text" })
id!: string
@Property({ columnType: "text", nullable: true })
@CustomerIdIndex.MikroORMIndex()
customer_id: string | null = null
@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
@Searchable()
@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()",
const _OrderAddress = model
.define("OrderAddress", {
id: model.id({ prefix: "ordaddr" }).primaryKey(),
customer_id: model.text().nullable(),
company: model.text().searchable().nullable(),
first_name: model.text().searchable().nullable(),
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().searchable().nullable(),
metadata: model.json().nullable(),
})
created_at: Date
.indexes([
{
name: "IDX_order_address_customer_id",
on: ["customer_id"],
unique: false,
},
])
@Property({
onCreate: () => new Date(),
onUpdate: () => new Date(),
columnType: "timestamptz",
defaultRaw: "now()",
})
updated_at: Date
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "ordaddr")
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "ordaddr")
}
}
export const OrderAddress = _OrderAddress
@@ -1,55 +0,0 @@
import { BigNumberRawValue, DAL } from "@medusajs/framework/types"
import { BigNumber, MikroOrmBigNumberProperty } from "@medusajs/framework/utils"
import { OptionalProps, PrimaryKey, Property } from "@mikro-orm/core"
type OptionalAdjustmentLineProps = DAL.ModelDateColumns
/**
* As per the Mikro ORM docs, superclasses should use the abstract class definition
* Source: https://mikro-orm.io/docs/inheritance-mapping
*/
export default abstract class AdjustmentLine {
[OptionalProps]: OptionalAdjustmentLineProps
@PrimaryKey({ columnType: "text" })
id: string
@Property({ columnType: "text", nullable: true })
description: string | null = null
@Property({
columnType: "text",
nullable: true,
})
promotion_id: string | null = null
@Property({ columnType: "text", nullable: true })
code: string | null = null
@MikroOrmBigNumberProperty()
amount: BigNumber | number
@Property({ columnType: "jsonb" })
raw_amount: BigNumberRawValue
@Property({ columnType: "text", nullable: true })
provider_id: 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
}
@@ -1,92 +1,31 @@
import { DAL } from "@medusajs/framework/types"
import {
DALUtils,
createPsqlIndexStatementHelper,
generateEntityId,
} from "@medusajs/framework/utils"
import {
BeforeCreate,
Entity,
Filter,
ManyToOne,
OnInit,
OptionalProps,
PrimaryKey,
Property,
Rel,
} from "@mikro-orm/core"
import ClaimItem from "./claim-item"
import { model } from "@medusajs/framework/utils"
import { OrderClaimItem } from "./claim-item"
type OptionalClaimItemImageProps = DAL.ModelDateColumns
const ClaimItemImageDeletedAtIndex = createPsqlIndexStatementHelper({
tableName: "order_claim_item_image",
columns: "deleted_at",
where: "deleted_at IS NOT NULL",
})
const ClaimItemIdIndex = createPsqlIndexStatementHelper({
tableName: "order_claim_item_image",
columns: ["claim_item_id"],
where: "deleted_at IS NOT NULL",
})
@Entity({ tableName: "order_claim_item_image" })
@Filter(DALUtils.mikroOrmSoftDeletableFilterOptions)
export default class OrderClaimItemImage {
[OptionalProps]?: OptionalClaimItemImageProps
@PrimaryKey({ columnType: "text" })
id: string
@ManyToOne({
entity: () => ClaimItem,
mapToPk: true,
fieldName: "claim_item_id",
columnType: "text",
const _OrderClaimItemImage = model
.define("OrderClaimItemImage", {
id: model.id({ prefix: "climg" }).primaryKey(),
claim_item: model.belongsTo<() => typeof OrderClaimItem>(
() => OrderClaimItem,
{
mappedBy: "images",
}
),
url: model.text(),
metadata: model.json().nullable(),
})
@ClaimItemIdIndex.MikroORMIndex()
claim_item_id: string
.indexes([
{
name: "IDX_order_claim_item_image_deleted_at",
on: ["deleted_at"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_claim_item_image_claim_item_id",
on: ["claim_item_id"],
unique: false,
where: "deleted_at IS NOT NULL",
},
])
@ManyToOne(() => ClaimItem, {
persist: false,
})
item: Rel<ClaimItem>
@Property({ columnType: "text" })
url: 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: "timestamptz", nullable: true })
@ClaimItemImageDeletedAtIndex.MikroORMIndex()
deleted_at: Date | null = null
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "climg")
this.claim_item_id ??= this.item?.id
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "climg")
this.claim_item_id ??= this.item?.id
}
}
export const OrderClaimItemImage = _OrderClaimItemImage
+47 -131
View File
@@ -1,135 +1,51 @@
import { BigNumberRawValue, DAL } from "@medusajs/framework/types"
import {
ClaimReason,
MikroOrmBigNumberProperty,
createPsqlIndexStatementHelper,
generateEntityId,
} from "@medusajs/framework/utils"
import {
BeforeCreate,
Cascade,
Collection,
Entity,
Enum,
ManyToOne,
OnInit,
OneToMany,
OptionalProps,
PrimaryKey,
Property,
Rel,
} from "@mikro-orm/core"
import Claim from "./claim"
import OrderClaimItemImage from "./claim-item-image"
import OrderLineItem from "./line-item"
import { ClaimReason, model } from "@medusajs/framework/utils"
import { OrderClaim } from "./claim"
import { OrderClaimItemImage } from "./claim-item-image"
import { OrderLineItem } from "./line-item"
type OptionalLineItemProps = DAL.ModelDateColumns
const tableName = "order_claim_item"
const ClaimIdIndex = createPsqlIndexStatementHelper({
tableName,
columns: "claim_id",
where: "deleted_at IS NOT NULL",
})
const ItemIdIndex = createPsqlIndexStatementHelper({
tableName,
columns: "item_id",
where: "deleted_at IS NOT NULL",
})
const DeletedAtIndex = createPsqlIndexStatementHelper({
tableName,
columns: "deleted_at",
where: "deleted_at IS NOT NULL",
})
@Entity({ tableName })
export default class OrderClaimItem {
[OptionalProps]?: OptionalLineItemProps
@PrimaryKey({ columnType: "text" })
id: string
@OneToMany(() => OrderClaimItemImage, (ci) => ci.item, {
cascade: [Cascade.PERSIST, Cascade.REMOVE],
const _OrderClaimItem = model
.define("OrderClaimItem", {
id: model.id({ prefix: "claitem" }).primaryKey(),
reason: model.enum(ClaimReason).nullable(),
quantity: model.bigNumber(),
is_additional_item: model.boolean().default(false),
note: model.text().nullable(),
metadata: model.json().nullable(),
claim: model.belongsTo<() => typeof OrderClaim>(() => OrderClaim, {
mappedBy: "additional_items",
}),
item: model.belongsTo<() => typeof OrderLineItem>(() => OrderLineItem, {
mappedBy: "claim_items",
}),
images: model.hasMany<() => typeof OrderClaimItemImage>(
() => OrderClaimItemImage,
{
mappedBy: "claim_item",
}
),
})
images = new Collection<Rel<OrderClaimItemImage>>(this)
@Enum({ items: () => ClaimReason, nullable: true })
reason: Rel<ClaimReason> | null = null
@MikroOrmBigNumberProperty()
quantity: Number | number
@Property({ columnType: "jsonb" })
raw_quantity: BigNumberRawValue
@ManyToOne(() => Claim, {
columnType: "text",
fieldName: "claim_id",
mapToPk: true,
onDelete: "cascade",
.cascades({
delete: ["images"],
})
@ClaimIdIndex.MikroORMIndex()
claim_id: string
.indexes([
{
name: "IDX_order_claim_item_claim_id",
on: ["claim_id"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_claim_item_item_id",
on: ["item_id"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_claim_item_deleted_at",
on: ["deleted_at"],
unique: false,
where: "deleted_at IS NOT NULL",
},
])
@ManyToOne(() => Claim, {
persist: false,
})
claim: Rel<Claim>
@ManyToOne({
entity: () => OrderLineItem,
fieldName: "item_id",
mapToPk: true,
columnType: "text",
})
@ItemIdIndex.MikroORMIndex()
item_id: string
@ManyToOne(() => OrderLineItem, {
persist: false,
})
item: Rel<OrderLineItem>
@Property({ columnType: "boolean", default: false })
is_additional_item: boolean = false
@Property({ columnType: "text", nullable: true })
note: 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: "timestamptz", nullable: true })
@DeletedAtIndex.MikroORMIndex()
deleted_at: Date | null = null
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "claitem")
this.claim_id ??= this.claim?.id
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "claitem")
this.claim_id ??= this.claim?.id
}
}
export const OrderClaimItem = _OrderClaimItem
+80 -169
View File
@@ -1,173 +1,84 @@
import { BigNumberRawValue, DAL } from "@medusajs/framework/types"
import {
BigNumber,
ClaimType,
DALUtils,
MikroOrmBigNumberProperty,
createPsqlIndexStatementHelper,
generateEntityId,
} from "@medusajs/framework/utils"
import {
BeforeCreate,
Cascade,
Collection,
Entity,
Enum,
Filter,
ManyToOne,
OnInit,
OneToMany,
OneToOne,
OptionalProps,
PrimaryKey,
Property,
Rel,
} from "@mikro-orm/core"
import ClaimItem from "./claim-item"
import Order from "./order"
import OrderShipping from "./order-shipping-method"
import Return from "./return"
import OrderTransaction from "./transaction"
import { ClaimType, model } from "@medusajs/framework/utils"
import { OrderClaimItem } from "./claim-item"
import { Order } from "./order"
import { OrderShipping } from "./order-shipping-method"
import { Return } from "./return"
import { OrderTransaction } from "./transaction"
type OptionalOrderClaimProps = DAL.ModelDateColumns
const DisplayIdIndex = createPsqlIndexStatementHelper({
tableName: "order_claim",
columns: "display_id",
where: "deleted_at IS NOT NULL",
})
const OrderClaimDeletedAtIndex = createPsqlIndexStatementHelper({
tableName: "order_claim",
columns: "deleted_at",
where: "deleted_at IS NOT NULL",
})
const OrderIdIndex = createPsqlIndexStatementHelper({
tableName: "order_claim",
columns: ["order_id"],
where: "deleted_at IS NOT NULL",
})
const ReturnIdIndex = createPsqlIndexStatementHelper({
tableName: "order_claim",
columns: "return_id",
where: "return_id IS NOT NULL AND deleted_at IS NOT NULL",
})
@Entity({ tableName: "order_claim" })
@Filter(DALUtils.mikroOrmSoftDeletableFilterOptions)
export default class OrderClaim {
[OptionalProps]?: OptionalOrderClaimProps
@PrimaryKey({ columnType: "text" })
id: string
@ManyToOne({
entity: () => Order,
mapToPk: true,
fieldName: "order_id",
columnType: "text",
const _OrderClaim = model
.define("OrderClaim", {
id: model.id({ prefix: "claim" }).primaryKey(),
order_version: model.number(),
display_id: model.autoincrement(),
type: model.enum(ClaimType),
no_notification: model.boolean().nullable(),
refund_amount: model.bigNumber().nullable(),
created_by: model.text().nullable(),
canceled_at: model.dateTime().nullable(),
metadata: model.json().nullable(),
order: model.hasOne<() => typeof Order>(() => Order, {
mappedBy: undefined,
foreignKey: true,
}),
return: model
.hasOne<() => typeof Return>(() => Return, {
mappedBy: undefined,
foreignKey: true,
})
.nullable(),
additional_items: model.hasMany<() => typeof OrderClaimItem>(
() => OrderClaimItem,
{
mappedBy: "claim",
}
),
claim_items: model.hasMany<() => typeof OrderClaimItem>(
() => OrderClaimItem,
{
mappedBy: "claim",
}
),
shipping_methods: model.hasMany<() => typeof OrderShipping>(
() => OrderShipping,
{
mappedBy: "claim",
}
),
transactions: model.hasMany<() => typeof OrderTransaction>(
() => OrderTransaction,
{
mappedBy: "claim",
}
),
})
@OrderIdIndex.MikroORMIndex()
order_id: string
@ManyToOne(() => Order, {
persist: false,
.cascades({
delete: ["additional_items", "claim_items", "transactions"],
})
order: Rel<Order>
.indexes([
{
name: "IDX_order_claim_display_id",
on: ["display_id"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_claim_deleted_at",
on: ["deleted_at"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_claim_order_id",
on: ["order_id"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_claim_return_id",
on: ["return_id"],
unique: false,
where: "return_id IS NOT NULL AND deleted_at IS NOT NULL",
},
])
@OneToOne({
entity: () => Return,
mappedBy: (ret) => ret.claim,
fieldName: "return_id",
nullable: true,
owner: true,
})
return: Rel<Return>
@Property({ columnType: "text", nullable: true })
@ReturnIdIndex.MikroORMIndex()
return_id: string | null = null
@Property({
columnType: "integer",
})
order_version: number
@Property({ autoincrement: true, primary: false })
@DisplayIdIndex.MikroORMIndex()
display_id: number
@Enum({ items: () => ClaimType })
type: Rel<ClaimType>
@Property({ columnType: "boolean", nullable: true })
no_notification: boolean | null = null
@MikroOrmBigNumberProperty({
nullable: true,
})
refund_amount: BigNumber | number
@Property({ columnType: "jsonb", nullable: true })
raw_refund_amount: BigNumberRawValue
@OneToMany(() => ClaimItem, (item) => item.claim, {
cascade: [Cascade.PERSIST],
})
additional_items = new Collection<Rel<ClaimItem>>(this)
@OneToMany(() => ClaimItem, (item) => item.claim, {
cascade: [Cascade.PERSIST],
})
claim_items = new Collection<Rel<ClaimItem>>(this)
@OneToMany(() => OrderShipping, (shippingMethod) => shippingMethod.claim, {
cascade: [Cascade.PERSIST],
})
shipping_methods = new Collection<Rel<OrderShipping>>(this)
@OneToMany(() => OrderTransaction, (transaction) => transaction.claim, {
cascade: [Cascade.PERSIST],
})
transactions = new Collection<OrderTransaction>(this)
@Property({ columnType: "text", nullable: true })
created_by: 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
@Property({ columnType: "timestamptz", nullable: true })
@OrderClaimDeletedAtIndex.MikroORMIndex()
deleted_at: Date | null = null
@Property({ columnType: "timestamptz", nullable: true })
canceled_at: Date | null = null
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "claim")
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "claim")
}
}
export const OrderClaim = _OrderClaim
+28 -104
View File
@@ -1,107 +1,31 @@
import { BigNumberRawValue, DAL } from "@medusajs/framework/types"
import {
BigNumber,
createPsqlIndexStatementHelper,
generateEntityId,
MikroOrmBigNumberProperty,
} from "@medusajs/framework/utils"
import {
BeforeCreate,
Entity,
ManyToOne,
OnInit,
OptionalProps,
PrimaryKey,
Property,
Rel,
} from "@mikro-orm/core"
import Order from "./order"
import { model } from "@medusajs/framework/utils"
import { Order } from "./order"
type OptionalLineItemProps = DAL.ModelDateColumns
const tableName = "order_credit_line"
const OrderIdIndex = createPsqlIndexStatementHelper({
tableName,
columns: ["order_id"],
where: "deleted_at IS NOT NULL",
})
const DeletedAtIndex = createPsqlIndexStatementHelper({
tableName,
columns: "deleted_at",
where: "deleted_at IS NOT NULL",
})
@Entity({ tableName })
export default class OrderCreditLine {
[OptionalProps]?: OptionalLineItemProps
@PrimaryKey({ columnType: "text" })
id: string
@ManyToOne({
entity: () => Order,
mapToPk: true,
fieldName: "order_id",
columnType: "text",
const OrderCreditLine_ = model
.define("OrderCreditLine", {
id: model.id({ prefix: "ordcl" }).primaryKey(),
order: model.belongsTo(() => Order, {
mappedBy: "credit_lines",
}),
reference: model.text().nullable(),
reference_id: model.text().nullable(),
amount: model.bigNumber(),
raw_amount: model.json(),
metadata: model.json().nullable(),
})
@OrderIdIndex.MikroORMIndex()
order_id: string
.indexes([
{
name: "IDX_order_credit_line_order_id",
on: ["order_id"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_credit_line_deleted_at",
on: ["deleted_at"],
unique: false,
where: "deleted_at IS NOT NULL",
},
])
@ManyToOne(() => Order, {
persist: false,
})
order: Rel<Order>
@Property({
columnType: "text",
nullable: true,
})
reference: string | null = null
@Property({
columnType: "text",
nullable: true,
})
reference_id: string | null = null
@MikroOrmBigNumberProperty()
amount: BigNumber | number
@Property({ columnType: "jsonb" })
raw_amount: BigNumberRawValue
@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: "timestamptz", nullable: true })
@DeletedAtIndex.MikroORMIndex()
deleted_at: Date | null = null
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "ordcl")
this.order_id ??= this.order?.id
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "ordcl")
this.order_id ??= this.order?.id
}
}
export const OrderCreditLine = OrderCreditLine_
@@ -1,116 +1,39 @@
import { BigNumberRawValue, DAL } from "@medusajs/framework/types"
import {
MikroOrmBigNumberProperty,
createPsqlIndexStatementHelper,
generateEntityId,
} from "@medusajs/framework/utils"
import {
BeforeCreate,
Entity,
ManyToOne,
OnInit,
OptionalProps,
PrimaryKey,
Property,
} from "@mikro-orm/core"
import Exchange from "./exchange"
import OrderLineItem from "./line-item"
import { model } from "@medusajs/framework/utils"
import { OrderExchange } from "./exchange"
import { OrderLineItem } from "./line-item"
type OptionalLineItemProps = DAL.ModelDateColumns
const ExchangeIdIndex = createPsqlIndexStatementHelper({
tableName: "order_exchange_item",
columns: "exchange_id",
where: "deleted_at IS NOT NULL",
})
const ItemIdIndex = createPsqlIndexStatementHelper({
tableName: "order_exchange_item",
columns: "item_id",
where: "deleted_at IS NOT NULL",
})
const DeletedAtIndex = createPsqlIndexStatementHelper({
tableName: "order_claim_item_image",
columns: "deleted_at",
where: "deleted_at IS NOT NULL",
})
@Entity({ tableName: "order_exchange_item" })
export default class OrderExchangeItem {
[OptionalProps]?: OptionalLineItemProps
@PrimaryKey({ columnType: "text" })
id: string
@MikroOrmBigNumberProperty()
quantity: Number | number
@Property({ columnType: "jsonb" })
raw_quantity: BigNumberRawValue
@ManyToOne(() => Exchange, {
columnType: "text",
fieldName: "exchange_id",
mapToPk: true,
onDelete: "cascade",
const _OrderExchangeItem = model
.define("OrderExchangeItem", {
id: model.id({ prefix: "oexcitem" }).primaryKey(),
quantity: model.bigNumber(),
note: model.text().nullable(),
metadata: model.json().nullable(),
exchange: model.belongsTo<() => typeof OrderExchange>(() => OrderExchange, {
mappedBy: "additional_items",
}),
item: model.belongsTo<() => typeof OrderLineItem>(() => OrderLineItem, {
mappedBy: "exchange_items",
}),
})
@ExchangeIdIndex.MikroORMIndex()
exchange_id: string
.indexes([
{
name: "IDX_order_exchange_item_exchange_id",
on: ["exchange_id"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_exchange_item_item_id",
on: ["item_id"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_exchange_item_deleted_at",
on: ["deleted_at"],
unique: false,
where: "deleted_at IS NOT NULL",
},
])
@ManyToOne(() => Exchange, {
persist: false,
})
exchange: Exchange
@ManyToOne({
entity: () => OrderLineItem,
fieldName: "item_id",
mapToPk: true,
columnType: "text",
})
@ItemIdIndex.MikroORMIndex()
item_id: string
@ManyToOne(() => OrderLineItem, {
persist: false,
})
item: OrderLineItem
@Property({ columnType: "text", nullable: true })
note: 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: "timestamptz", nullable: true })
@DeletedAtIndex.MikroORMIndex()
deleted_at: Date | null = null
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "oexcitem")
this.exchange_id ??= this.exchange?.id
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "oexcitem")
this.exchange_id ??= this.exchange?.id
}
}
export const OrderExchangeItem = _OrderExchangeItem
+74 -161
View File
@@ -1,165 +1,78 @@
import { BigNumberRawValue, DAL } from "@medusajs/framework/types"
import {
BigNumber,
DALUtils,
MikroOrmBigNumberProperty,
createPsqlIndexStatementHelper,
generateEntityId,
} from "@medusajs/framework/utils"
import {
BeforeCreate,
Cascade,
Collection,
Entity,
Filter,
ManyToOne,
OnInit,
OneToMany,
OneToOne,
OptionalProps,
PrimaryKey,
Property,
Rel,
} from "@mikro-orm/core"
import { OrderExchangeItem, OrderTransaction } from "@models"
import Order from "./order"
import OrderShipping from "./order-shipping-method"
import Return from "./return"
import { model } from "@medusajs/framework/utils"
import { OrderExchangeItem } from "./exchange-item"
import { Order } from "./order"
import { OrderShipping } from "./order-shipping-method"
import { Return } from "./return"
import { OrderTransaction } from "./transaction"
type OptionalOrderExchangeProps = DAL.ModelDateColumns
const DisplayIdIndex = createPsqlIndexStatementHelper({
tableName: "order_exchange",
columns: "display_id",
where: "deleted_at IS NOT NULL",
})
const OrderExchangeDeletedAtIndex = createPsqlIndexStatementHelper({
tableName: "order_exchange",
columns: "deleted_at",
where: "deleted_at IS NOT NULL",
})
const OrderIdIndex = createPsqlIndexStatementHelper({
tableName: "order_exchange",
columns: ["order_id"],
where: "deleted_at IS NOT NULL",
})
const ReturnIdIndex = createPsqlIndexStatementHelper({
tableName: "order_exchange",
columns: "return_id",
where: "return_id IS NOT NULL AND deleted_at IS NOT NULL",
})
@Entity({ tableName: "order_exchange" })
@Filter(DALUtils.mikroOrmSoftDeletableFilterOptions)
export default class OrderExchange {
[OptionalProps]?: OptionalOrderExchangeProps
@PrimaryKey({ columnType: "text" })
id: string
@ManyToOne({
entity: () => Order,
mapToPk: true,
fieldName: "order_id",
columnType: "text",
const _OrderExchange = model
.define("OrderExchange", {
id: model.id({ prefix: "oexc" }).primaryKey(),
order_version: model.number(),
display_id: model.autoincrement(),
no_notification: model.boolean().nullable(),
difference_due: model.bigNumber().nullable(),
allow_backorder: model.boolean().default(false),
created_by: model.text().nullable(),
metadata: model.json().nullable(),
canceled_at: model.dateTime().nullable(),
order: model.hasOne<() => typeof Order>(() => Order, {
mappedBy: undefined,
foreignKey: true,
}),
return: model
.hasOne<() => typeof Return>(() => Return, {
mappedBy: undefined,
foreignKey: true,
})
.nullable(),
additional_items: model.hasMany<() => typeof OrderExchangeItem>(
() => OrderExchangeItem,
{
mappedBy: "exchange",
}
),
shipping_methods: model.hasMany<() => typeof OrderShipping>(
() => OrderShipping,
{
mappedBy: "exchange",
}
),
transactions: model.hasMany<() => typeof OrderTransaction>(
() => OrderTransaction,
{
mappedBy: "exchange",
}
),
})
@OrderIdIndex.MikroORMIndex()
order_id: string
@ManyToOne(() => Order, {
persist: false,
.cascades({
delete: ["additional_items", "transactions"],
})
order: Rel<Order>
.indexes([
{
name: "IDX_order_exchange_display_id",
on: ["display_id"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_exchange_deleted_at",
on: ["deleted_at"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_exchange_order_id",
on: ["order_id"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_exchange_return_id",
on: ["return_id"],
unique: false,
where: "return_id IS NOT NULL AND deleted_at IS NOT NULL",
},
])
@OneToOne({
entity: () => Return,
mappedBy: (ret) => ret.exchange,
fieldName: "return_id",
nullable: true,
owner: true,
})
return: Rel<Return>
@Property({ columnType: "text", nullable: true })
@ReturnIdIndex.MikroORMIndex()
return_id: string | null = null
@Property({
columnType: "integer",
})
order_version: number
@Property({ autoincrement: true, primary: false })
@DisplayIdIndex.MikroORMIndex()
display_id: number
@Property({ columnType: "boolean", nullable: true })
no_notification: boolean | null = null
@MikroOrmBigNumberProperty({
nullable: true,
})
difference_due: BigNumber | number
@Property({ columnType: "jsonb", nullable: true })
raw_difference_due: BigNumberRawValue
@Property({ columnType: "boolean", default: false })
allow_backorder: boolean = false
@OneToMany(() => OrderExchangeItem, (item) => item.exchange, {
cascade: [Cascade.PERSIST],
})
additional_items = new Collection<Rel<OrderExchangeItem>>(this)
@OneToMany(() => OrderShipping, (shippingMethod) => shippingMethod.exchange, {
cascade: [Cascade.PERSIST],
})
shipping_methods = new Collection<Rel<OrderShipping>>(this)
@OneToMany(() => OrderTransaction, (transaction) => transaction.exchange, {
cascade: [Cascade.PERSIST],
})
transactions = new Collection<OrderTransaction>(this)
@Property({ columnType: "text", nullable: true })
created_by: 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
@Property({ columnType: "timestamptz", nullable: true })
@OrderExchangeDeletedAtIndex.MikroORMIndex()
deleted_at: Date | null = null
@Property({ columnType: "timestamptz", nullable: true })
canceled_at: Date | null = null
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "oexc")
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "oexc")
}
}
export const OrderExchange = _OrderExchange
+23 -23
View File
@@ -1,23 +1,23 @@
export { default as OrderAddress } from "./address"
export { default as OrderClaim } from "./claim"
export { default as OrderClaimItem } from "./claim-item"
export { default as OrderClaimItemImage } from "./claim-item-image"
export { default as OrderCreditLine } from "./credit-line"
export { default as OrderExchange } from "./exchange"
export { default as OrderExchangeItem } from "./exchange-item"
export { default as OrderLineItem } from "./line-item"
export { default as OrderLineItemAdjustment } from "./line-item-adjustment"
export { default as OrderLineItemTaxLine } from "./line-item-tax-line"
export { default as Order } from "./order"
export { default as OrderChange } from "./order-change"
export { default as OrderChangeAction } from "./order-change-action"
export { default as OrderItem } from "./order-item"
export { default as OrderShipping } from "./order-shipping-method"
export { default as OrderSummary } from "./order-summary"
export { default as Return } from "./return"
export { default as ReturnItem } from "./return-item"
export { default as ReturnReason } from "./return-reason"
export { default as OrderShippingMethod } from "./shipping-method"
export { default as OrderShippingMethodAdjustment } from "./shipping-method-adjustment"
export { default as OrderShippingMethodTaxLine } from "./shipping-method-tax-line"
export { default as OrderTransaction } from "./transaction"
export { OrderAddress } from "./address"
export { OrderClaim } from "./claim"
export { OrderClaimItem } from "./claim-item"
export { OrderClaimItemImage } from "./claim-item-image"
export { OrderCreditLine } from "./credit-line"
export { OrderExchange } from "./exchange"
export { OrderExchangeItem } from "./exchange-item"
export { OrderLineItem } from "./line-item"
export { OrderLineItemAdjustment } from "./line-item-adjustment"
export { OrderLineItemTaxLine } from "./line-item-tax-line"
export { Order } from "./order"
export { OrderChange } from "./order-change"
export { OrderChangeAction } from "./order-change-action"
export { OrderItem } from "./order-item"
export { OrderShipping } from "./order-shipping-method"
export { OrderSummary } from "./order-summary"
export { Return } from "./return"
export { ReturnItem } from "./return-item"
export { ReturnReason } from "./return-reason"
export { OrderShippingMethod } from "./shipping-method"
export { OrderShippingMethodAdjustment } from "./shipping-method-adjustment"
export { OrderShippingMethodTaxLine } from "./shipping-method-tax-line"
export { OrderTransaction } from "./transaction"
@@ -1,42 +1,24 @@
import {
createPsqlIndexStatementHelper,
generateEntityId,
} from "@medusajs/framework/utils"
import { BeforeCreate, Entity, ManyToOne, OnInit, Rel } from "@mikro-orm/core"
import AdjustmentLine from "./adjustment-line"
import OrderLineItem from "./line-item"
import { model } from "@medusajs/framework/utils"
import { OrderLineItem } from "./line-item"
const ItemIdIndex = createPsqlIndexStatementHelper({
tableName: "order_line_item_adjustment",
columns: "item_id",
})
@Entity({ tableName: "order_line_item_adjustment" })
export default class OrderLineItemAdjustment extends AdjustmentLine {
@ManyToOne(() => OrderLineItem, {
persist: false,
const _OrderLineItemAdjustment = model
.define("OrderLineItemAdjustment", {
id: model.id({ prefix: "ordliadj" }).primaryKey(),
description: model.text().nullable(),
promotion_id: model.text().nullable(),
code: model.text().nullable(),
amount: model.bigNumber(),
provider_id: model.text().nullable(),
item: model.belongsTo<() => typeof OrderLineItem>(() => OrderLineItem, {
mappedBy: "adjustments",
}),
})
item: Rel<OrderLineItem>
.indexes([
{
name: "IDX_order_order_line_item_adjustment_item_id",
on: ["item_id"],
unique: false,
},
])
@ManyToOne({
entity: () => OrderLineItem,
columnType: "text",
fieldName: "item_id",
onDelete: "cascade",
mapToPk: true,
})
@ItemIdIndex.MikroORMIndex()
item_id: string
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "ordliadj")
this.item_id ??= this.item?.id
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "ordliadj")
this.item_id ??= this.item?.id
}
}
export const OrderLineItemAdjustment = _OrderLineItemAdjustment
@@ -1,50 +1,24 @@
import {
createPsqlIndexStatementHelper,
generateEntityId,
} from "@medusajs/framework/utils"
import {
BeforeCreate,
Cascade,
Entity,
ManyToOne,
OnInit,
Rel,
} from "@mikro-orm/core"
import OrderLineItem from "./line-item"
import TaxLine from "./tax-line"
import { model } from "@medusajs/framework/utils"
import { OrderLineItem } from "./line-item"
const ItemIdIndex = createPsqlIndexStatementHelper({
tableName: "order_line_item_tax_line",
columns: "item_id",
})
@Entity({ tableName: "order_line_item_tax_line" })
export default class OrderLineItemTaxLine extends TaxLine {
@ManyToOne(() => OrderLineItem, {
fieldName: "item_id",
persist: false,
const _OrderLineItemTaxLine = model
.define("OrderLineItemTaxLine", {
id: model.id({ prefix: "ordlitxl" }).primaryKey(),
description: model.text().nullable(),
tax_rate_id: model.text().nullable(),
code: model.text(),
rate: model.bigNumber(),
provider_id: model.text().nullable(),
item: model.belongsTo<() => typeof OrderLineItem>(() => OrderLineItem, {
mappedBy: "tax_lines",
}),
})
item: Rel<OrderLineItem>
.indexes([
{
name: "IDX_order_line_item_tax_line_item_id",
on: ["item_id"],
unique: false,
},
])
@ManyToOne({
entity: () => OrderLineItem,
columnType: "text",
fieldName: "item_id",
cascade: [Cascade.PERSIST, Cascade.REMOVE],
mapToPk: true,
})
@ItemIdIndex.MikroORMIndex()
item_id: string
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "ordlitxl")
this.item_id ??= this.item?.id
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "ordlitxl")
this.item_id ??= this.item?.id
}
}
export const OrderLineItemTaxLine = _OrderLineItemTaxLine
+70 -182
View File
@@ -1,186 +1,74 @@
import { BigNumberRawValue, DAL } from "@medusajs/framework/types"
import {
BigNumber,
DALUtils,
MikroOrmBigNumberProperty,
createPsqlIndexStatementHelper,
generateEntityId,
} from "@medusajs/framework/utils"
import {
BeforeCreate,
Cascade,
Collection,
Entity,
Filter,
OnInit,
OneToMany,
OptionalProps,
PrimaryKey,
Property,
Rel,
} from "@mikro-orm/core"
import OrderLineItemAdjustment from "./line-item-adjustment"
import OrderLineItemTaxLine from "./line-item-tax-line"
import { model } from "@medusajs/framework/utils"
import { OrderLineItemAdjustment } from "./line-item-adjustment"
import { OrderLineItemTaxLine } from "./line-item-tax-line"
type OptionalLineItemProps = DAL.ModelDateColumns
const DeletedAtIndex = createPsqlIndexStatementHelper({
tableName: "order_line_item",
columns: "deleted_at",
where: "deleted_at IS NOT NULL",
})
const ProductIdIndex = createPsqlIndexStatementHelper({
tableName: "order_line_item",
columns: "product_id",
where: "deleted_at IS NOT NULL",
})
const ProductTypeIdIndex = createPsqlIndexStatementHelper({
name: "IDX_line_item_product_type_id",
tableName: "order_line_item",
columns: "product_type_id",
where: "deleted_at IS NOT NULL AND product_type_id IS NOT NULL",
}).MikroORMIndex
const VariantIdIndex = createPsqlIndexStatementHelper({
tableName: "order_line_item",
columns: "variant_id",
where: "deleted_at IS NOT NULL",
})
@Entity({ tableName: "order_line_item" })
@Filter(DALUtils.mikroOrmSoftDeletableFilterOptions)
export default class OrderLineItem {
[OptionalProps]?: OptionalLineItemProps
@PrimaryKey({ columnType: "text" })
id: string
@Property({ columnType: "text" })
title: string
@Property({ columnType: "text", nullable: true })
subtitle: string | null = null
@Property({ columnType: "text", nullable: true })
thumbnail: string | null = null
@Property({
columnType: "text",
nullable: true,
const _OrderLineItem = model
.define("OrderLineItem", {
id: model.id({ prefix: "ordli" }).primaryKey(),
title: model.text(),
subtitle: model.text().nullable(),
thumbnail: model.text().nullable(),
variant_id: model.text().nullable(),
product_id: model.text().nullable(),
product_title: model.text().nullable(),
product_description: model.text().nullable(),
product_subtitle: model.text().nullable(),
product_type: model.text().nullable(),
product_type_id: model.text().nullable(),
product_collection: model.text().nullable(),
product_handle: model.text().nullable(),
variant_sku: model.text().nullable(),
variant_barcode: model.text().nullable(),
variant_title: model.text().nullable(),
variant_option_values: model.json().nullable(),
requires_shipping: model.boolean().default(true),
is_discountable: model.boolean().default(true),
is_tax_inclusive: model.boolean().default(false),
compare_at_unit_price: model.bigNumber().nullable(),
unit_price: model.bigNumber().nullable(),
is_custom_price: model.boolean().default(false),
metadata: model.json().nullable(),
tax_lines: model.hasMany<() => typeof OrderLineItemTaxLine>(
() => OrderLineItemTaxLine,
{
mappedBy: "item",
}
),
adjustments: model.hasMany<() => typeof OrderLineItemAdjustment>(
() => OrderLineItemAdjustment,
{
mappedBy: "item",
}
),
})
@VariantIdIndex.MikroORMIndex()
variant_id: string | null = null
@Property({
columnType: "text",
nullable: true,
.cascades({
delete: ["tax_lines", "adjustments"],
})
@ProductIdIndex.MikroORMIndex()
product_id: string | null = null
.indexes([
{
name: "IDX_order_line_item_deleted_at",
on: ["deleted_at"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_line_item_product_id",
on: ["product_id"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_line_item_product_type_id",
on: ["product_type_id"],
unique: false,
where: "deleted_at IS NOT NULL AND product_type_id IS NOT NULL",
},
{
name: "IDX_order_line_item_variant_id",
on: ["variant_id"],
unique: false,
where: "deleted_at IS NOT NULL",
},
])
@Property({ columnType: "text", nullable: true })
product_title: string | null = null
@Property({ columnType: "text", nullable: true })
product_description: string | null = null
@Property({ columnType: "text", nullable: true })
product_subtitle: string | null = null
@Property({ columnType: "text", nullable: true })
product_type: string | null = null
@ProductTypeIdIndex()
@Property({ columnType: "text", nullable: true })
product_type_id: string | null = null
@Property({ columnType: "text", nullable: true })
product_collection: string | null = null
@Property({ columnType: "text", nullable: true })
product_handle: string | null = null
@Property({ columnType: "text", nullable: true })
variant_sku: string | null = null
@Property({ columnType: "text", nullable: true })
variant_barcode: string | null = null
@Property({ columnType: "text", nullable: true })
variant_title: string | null = null
@Property({ columnType: "jsonb", nullable: true })
variant_option_values: Record<string, unknown> | null = null
@Property({ columnType: "boolean" })
requires_shipping: boolean = true
@Property({ columnType: "boolean" })
is_discountable: boolean = true
@Property({ columnType: "boolean" })
is_tax_inclusive: boolean = false
@MikroOrmBigNumberProperty({
nullable: true,
})
compare_at_unit_price?: BigNumber | number | null = null
@Property({ columnType: "jsonb", nullable: true })
raw_compare_at_unit_price: BigNumberRawValue | null = null
@MikroOrmBigNumberProperty({
nullable: true,
})
unit_price: BigNumber | number
@Property({ columnType: "jsonb" })
raw_unit_price: BigNumberRawValue
@Property({ columnType: "boolean", default: false })
is_custom_price: boolean = false
@OneToMany(() => OrderLineItemTaxLine, (taxLine) => taxLine.item, {
cascade: [Cascade.PERSIST, "soft-remove" as Cascade],
})
tax_lines = new Collection<Rel<OrderLineItemTaxLine>>(this)
@OneToMany(() => OrderLineItemAdjustment, (adjustment) => adjustment.item, {
cascade: [Cascade.PERSIST, "soft-remove" as Cascade],
})
adjustments = new Collection<Rel<OrderLineItemAdjustment>>(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
@Property({ columnType: "timestamptz", nullable: true })
@DeletedAtIndex.MikroORMIndex()
deleted_at: Date | null = null
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "ordli")
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "ordli")
}
}
export const OrderLineItem = _OrderLineItem
@@ -1,251 +1,72 @@
import { BigNumberRawValue, DAL } from "@medusajs/framework/types"
import {
BigNumber,
DALUtils,
MikroOrmBigNumberProperty,
createPsqlIndexStatementHelper,
generateEntityId,
} from "@medusajs/framework/utils"
import {
BeforeCreate,
Entity,
Filter,
ManyToOne,
OnInit,
OptionalProps,
PrimaryKey,
Property,
Rel,
} from "@mikro-orm/core"
import OrderClaim from "./claim"
import OrderExchange from "./exchange"
import Order from "./order"
import OrderChange from "./order-change"
import Return from "./return"
import { model } from "@medusajs/framework/utils"
type OptionalLineItemProps = DAL.ModelDateColumns
import { OrderChange } from "./order-change"
const OrderChangeIdIndex = createPsqlIndexStatementHelper({
tableName: "order_change_action",
columns: "order_change_id",
where: "deleted_at IS NOT NULL",
})
const OrderIdIndex = createPsqlIndexStatementHelper({
tableName: "order_change_action",
columns: "order_id",
where: "deleted_at IS NOT NULL",
})
const ReturnIdIndex = createPsqlIndexStatementHelper({
tableName: "order_change_action",
columns: "return_id",
where: "return_id IS NOT NULL AND deleted_at IS NOT NULL",
})
const OrderClaimIdIndex = createPsqlIndexStatementHelper({
tableName: "order_change_action",
columns: "claim_id",
where: "claim_id IS NOT NULL AND deleted_at IS NOT NULL",
})
const OrderExchangeIdIndex = createPsqlIndexStatementHelper({
tableName: "order_change_action",
columns: "exchange_id",
where: "exchange_id IS NOT NULL AND deleted_at IS NOT NULL",
})
const DeletedAtIndex = createPsqlIndexStatementHelper({
tableName: "order_change_action",
columns: "deleted_at",
where: "deleted_at IS NOT NULL",
})
const ActionOrderingIndex = createPsqlIndexStatementHelper({
tableName: "order_change_action",
columns: "ordering",
where: "deleted_at IS NOT NULL",
})
@Entity({ tableName: "order_change_action" })
@Filter(DALUtils.mikroOrmSoftDeletableFilterOptions)
export default class OrderChangeAction {
[OptionalProps]?: OptionalLineItemProps
@PrimaryKey({ columnType: "text" })
id: string
@Property({ columnType: "integer", autoincrement: true })
@ActionOrderingIndex.MikroORMIndex()
ordering: number
@ManyToOne({
entity: () => Order,
columnType: "text",
fieldName: "order_id",
onDelete: "cascade",
mapToPk: true,
nullable: true,
const _OrderChangeAction = model
.define("OrderChangeAction", {
id: model.id({ prefix: "ordchact" }).primaryKey(),
order_id: model.text(),
return_id: model.text().nullable(),
claim_id: model.text().nullable(),
exchange_id: model.text().nullable(),
ordering: model.autoincrement(),
version: model.number().nullable(),
reference: model.text().nullable(),
reference_id: model.text().nullable(),
action: model.text(),
details: model.json().default({}),
amount: model.bigNumber().nullable(),
internal_note: model.text().nullable(),
applied: model.boolean().default(false),
order_change: model
.belongsTo<() => typeof OrderChange>(() => OrderChange, {
mappedBy: "actions",
})
.nullable(),
})
@OrderIdIndex.MikroORMIndex()
order_id: string | null = null
.indexes([
{
name: "IDX_order_change_action_order_change_id",
on: ["order_change_id"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_change_action_order_id",
on: ["order_id"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_change_action_return_id",
on: ["return_id"],
unique: false,
where: "return_id IS NOT NULL AND deleted_at IS NOT NULL",
},
{
name: "IDX_order_change_action_claim_id",
on: ["claim_id"],
unique: false,
where: "claim_id IS NOT NULL AND deleted_at IS NOT NULL",
},
{
name: "IDX_order_change_action_exchange_id",
on: ["exchange_id"],
unique: false,
where: "exchange_id IS NOT NULL AND deleted_at IS NOT NULL",
},
{
name: "IDX_order_change_action_deleted_at",
on: ["deleted_at"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_change_action_ordering",
on: ["ordering"],
unique: false,
where: "deleted_at IS NOT NULL",
},
])
@ManyToOne(() => Order, {
persist: false,
nullable: true,
})
order: Rel<Order> | null = null
@ManyToOne({
entity: () => Return,
mapToPk: true,
fieldName: "return_id",
columnType: "text",
nullable: true,
})
@ReturnIdIndex.MikroORMIndex()
return_id: string | null = null
@ManyToOne(() => Return, {
persist: false,
nullable: true,
})
return: Return
@ManyToOne({
entity: () => OrderClaim,
mapToPk: true,
fieldName: "claim_id",
columnType: "text",
nullable: true,
})
@OrderClaimIdIndex.MikroORMIndex()
claim_id: string | null = null
@ManyToOne(() => OrderClaim, {
persist: false,
nullable: true,
})
claim: OrderClaim
@ManyToOne({
entity: () => OrderExchange,
mapToPk: true,
fieldName: "exchange_id",
columnType: "text",
nullable: true,
})
@OrderExchangeIdIndex.MikroORMIndex()
exchange_id: string | null = null
@ManyToOne(() => OrderExchange, {
persist: false,
nullable: true,
})
exchange: OrderExchange
@Property({ columnType: "integer", nullable: true })
version: number | null = null
@ManyToOne({
entity: () => OrderChange,
columnType: "text",
fieldName: "order_change_id",
onDelete: "cascade",
mapToPk: true,
nullable: true,
})
@OrderChangeIdIndex.MikroORMIndex()
order_change_id: string | null
@ManyToOne(() => OrderChange, {
persist: false,
nullable: true,
})
order_change: Rel<OrderChange> | null = null
@Property({
columnType: "text",
nullable: true,
})
reference: string | null = null
@Property({
columnType: "text",
nullable: true,
})
reference_id: string | null = null
@Property({ columnType: "text" })
action: string
@Property({ columnType: "jsonb" })
details: Record<string, unknown> = {}
@MikroOrmBigNumberProperty({ nullable: true })
amount: BigNumber | number | null = null
@Property({ columnType: "jsonb", nullable: true })
raw_amount: BigNumberRawValue | null = null
@Property({
columnType: "text",
nullable: true,
})
internal_note: string | null = null
@Property({
columnType: "boolean",
defaultRaw: "false",
})
applied: boolean = false
@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 })
@DeletedAtIndex.MikroORMIndex()
deleted_at: Date | null = null
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "ordchact")
this.order_id ??= this.order?.id ?? this.order_change?.order_id ?? null
this.claim_id ??= this.claim?.id ?? this.order_change?.claim_id ?? null
this.exchange_id ??=
this.exchange?.id ?? this.order_change?.exchange_id ?? null
this.order_change_id ??= this.order_change?.id ?? null
this.version ??= this.order_change?.version ?? null
if (!this.claim_id && !this.exchange_id) {
this.return_id ??= this.return?.id ?? this.order_change?.return_id ?? null
}
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "ordchact")
this.order_id ??= this.order?.id ?? this.order_change?.order_id ?? null
this.claim_id ??= this.claim?.id ?? this.order_change?.claim_id ?? null
this.exchange_id ??=
this.exchange?.id ?? this.order_change?.exchange_id ?? null
this.order_change_id ??= this.order_change?.id ?? null
this.version ??= this.order_change?.version ?? null
if (!this.claim_id && !this.exchange_id) {
this.return_id ??= this.return?.id ?? this.order_change?.return_id ?? null
}
}
}
export const OrderChangeAction = _OrderChangeAction
+81 -248
View File
@@ -1,252 +1,85 @@
import { DAL } from "@medusajs/framework/types"
import {
createPsqlIndexStatementHelper,
DALUtils,
generateEntityId,
OrderChangeStatus,
} from "@medusajs/framework/utils"
import {
BeforeCreate,
Cascade,
Collection,
Entity,
Enum,
Filter,
ManyToOne,
OneToMany,
OnInit,
OptionalProps,
PrimaryKey,
Property,
Rel,
} from "@mikro-orm/core"
import {} from "@types"
import OrderClaim from "./claim"
import OrderExchange from "./exchange"
import Order from "./order"
import OrderChangeAction from "./order-change-action"
import Return from "./return"
import { model, OrderChangeStatus } from "@medusajs/framework/utils"
import { Order } from "./order"
import { OrderChangeAction } from "./order-change-action"
type OptionalLineItemProps = DAL.ModelDateColumns
const OrderIdIndex = createPsqlIndexStatementHelper({
tableName: "order_change",
columns: "order_id",
where: "deleted_at IS NOT NULL",
})
const ReturnIdIndex = createPsqlIndexStatementHelper({
tableName: "order_change",
columns: "return_id",
where: "return_id IS NOT NULL AND deleted_at IS NOT NULL",
})
const OrderClaimIdIndex = createPsqlIndexStatementHelper({
tableName: "order_change",
columns: "claim_id",
where: "claim_id IS NOT NULL AND deleted_at IS NOT NULL",
})
const OrderExchangeIdIndex = createPsqlIndexStatementHelper({
tableName: "order_change",
columns: "exchange_id",
where: "exchange_id IS NOT NULL AND deleted_at IS NOT NULL",
})
const OrderChangeStatusIndex = createPsqlIndexStatementHelper({
tableName: "order_change",
columns: "status",
where: "deleted_at IS NOT NULL",
})
const DeletedAtIndex = createPsqlIndexStatementHelper({
tableName: "order_change",
columns: "deleted_at",
where: "deleted_at IS NOT NULL",
})
const VersionIndex = createPsqlIndexStatementHelper({
tableName: "order_change",
columns: ["order_id", "version"],
where: "deleted_at IS NOT NULL",
})
@Entity({ tableName: "order_change" })
@Filter(DALUtils.mikroOrmSoftDeletableFilterOptions)
@VersionIndex.MikroORMIndex()
export default class OrderChange {
[OptionalProps]?: OptionalLineItemProps
@PrimaryKey({ columnType: "text" })
id: string
@ManyToOne({
entity: () => Order,
columnType: "text",
fieldName: "order_id",
onDelete: "cascade",
mapToPk: true,
const _OrderChange = model
.define("OrderChange", {
id: model.id({ prefix: "ordch" }).primaryKey(),
return_id: model.text().nullable(),
claim_id: model.text().nullable(),
exchange_id: model.text().nullable(),
version: model.number(),
change_type: model.text().nullable(),
description: model.text().nullable(),
status: model
.enum(OrderChangeStatus)
.default(OrderChangeStatus.PENDING)
.nullable(),
internal_note: model.text().nullable(),
created_by: model.text().nullable(),
requested_by: model.text().nullable(),
requested_at: model.dateTime().nullable(),
confirmed_by: model.text().nullable(),
confirmed_at: model.dateTime().nullable(),
declined_by: model.text().nullable(),
declined_reason: model.text().nullable(),
metadata: model.json().nullable(),
declined_at: model.dateTime().nullable(),
canceled_by: model.text().nullable(),
canceled_at: model.dateTime().nullable(),
order: model.belongsTo<() => typeof Order>(() => Order, {
mappedBy: "changes",
}),
actions: model.hasMany<() => typeof OrderChangeAction>(
() => OrderChangeAction
),
})
@OrderIdIndex.MikroORMIndex()
order_id: string
@ManyToOne(() => Order, {
persist: false,
.cascades({
delete: ["actions"],
})
order: Rel<Order>
.indexes([
{
name: "IDX_order_change_order_id",
on: ["order_id"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_change_return_id",
on: ["return_id"],
unique: false,
where: "return_id IS NOT NULL AND deleted_at IS NOT NULL",
},
{
name: "IDX_order_change_claim_id",
on: ["claim_id"],
unique: false,
where: "claim_id IS NOT NULL AND deleted_at IS NOT NULL",
},
{
name: "IDX_order_change_exchange_id",
on: ["exchange_id"],
unique: false,
where: "exchange_id IS NOT NULL AND deleted_at IS NOT NULL",
},
{
name: "IDX_order_change_status",
on: ["status"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_change_deleted_at",
on: ["deleted_at"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_change_version",
on: ["order_id", "version"],
unique: false,
where: "deleted_at IS NOT NULL",
},
])
@ManyToOne({
entity: () => Return,
mapToPk: true,
fieldName: "return_id",
columnType: "text",
nullable: true,
})
@ReturnIdIndex.MikroORMIndex()
return_id: string | null = null
@ManyToOne(() => Return, {
persist: false,
nullable: true,
})
return: Rel<Return>
@ManyToOne({
entity: () => OrderClaim,
mapToPk: true,
fieldName: "claim_id",
columnType: "text",
nullable: true,
})
@OrderClaimIdIndex.MikroORMIndex()
claim_id: string | null = null
@ManyToOne(() => OrderClaim, {
persist: false,
nullable: true,
})
claim: OrderClaim
@ManyToOne({
entity: () => OrderExchange,
mapToPk: true,
fieldName: "exchange_id",
columnType: "text",
nullable: true,
})
@OrderExchangeIdIndex.MikroORMIndex()
exchange_id: string | null = null
@ManyToOne(() => OrderExchange, {
persist: false,
nullable: true,
})
exchange: OrderExchange
@Property({ columnType: "integer" })
@VersionIndex.MikroORMIndex()
version: number
@Property({ columnType: "text", nullable: true })
change_type: string | null = null
@OneToMany(() => OrderChangeAction, (action) => action.order_change, {
cascade: [Cascade.PERSIST, "soft-remove" as Cascade],
})
actions = new Collection<Rel<OrderChangeAction>>(this)
@Property({
columnType: "text",
nullable: true,
})
description: string | null = null
@Enum({ items: () => OrderChangeStatus, default: OrderChangeStatus.PENDING })
@OrderChangeStatusIndex.MikroORMIndex()
status: OrderChangeStatus = OrderChangeStatus.PENDING
@Property({ columnType: "text", nullable: true })
internal_note: string | null = null
@Property({ columnType: "text", nullable: true })
created_by: string // customer, user, third party, etc.
@Property({ columnType: "text", nullable: true })
requested_by: string | null = null // customer or user ID
@Property({
columnType: "timestamptz",
nullable: true,
})
requested_at: Date | null = null
@Property({ columnType: "text", nullable: true })
confirmed_by: string | null = null // customer or user ID
@Property({
columnType: "timestamptz",
nullable: true,
})
confirmed_at: Date | null = null
@Property({ columnType: "text", nullable: true })
declined_by: string | null = null // customer or user ID
@Property({ columnType: "text", nullable: true })
declined_reason: string | null = null
@Property({ columnType: "jsonb", nullable: true })
metadata: Record<string, unknown> | null = null
@Property({
columnType: "timestamptz",
nullable: true,
})
declined_at?: Date
@Property({ columnType: "text", nullable: true })
canceled_by: string | null = null
@Property({
columnType: "timestamptz",
nullable: true,
})
canceled_at?: Date | 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 })
@DeletedAtIndex.MikroORMIndex()
deleted_at: Date | null = null
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "ordch")
this.order_id ??= this.order?.id
this.return_id ??= this.return?.id
this.claim_id ??= this.claim?.id
this.exchange_id ??= this.exchange?.id
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "ordch")
this.order_id ??= this.order?.id
this.return_id ??= this.return?.id
this.claim_id ??= this.claim?.id
this.exchange_id ??= this.exchange?.id
}
}
export const OrderChange = _OrderChange
+52 -180
View File
@@ -1,184 +1,56 @@
import { BigNumberRawValue, DAL } from "@medusajs/framework/types"
import {
BigNumber,
MikroOrmBigNumberProperty,
createPsqlIndexStatementHelper,
generateEntityId,
} from "@medusajs/framework/utils"
import {
BeforeCreate,
Entity,
ManyToOne,
OnInit,
OptionalProps,
PrimaryKey,
Property,
Rel,
} from "@mikro-orm/core"
import OrderLineItem from "./line-item"
import Order from "./order"
import { model } from "@medusajs/framework/utils"
type OptionalLineItemProps = DAL.ModelDateColumns
import { OrderLineItem } from "./line-item"
import { Order } from "./order"
const tableName = "order_item"
const OrderIdIndex = createPsqlIndexStatementHelper({
tableName,
columns: ["order_id"],
where: "deleted_at IS NOT NULL",
})
const OrderVersionIndex = createPsqlIndexStatementHelper({
tableName,
columns: ["version"],
where: "deleted_at IS NOT NULL",
})
const ItemIdIndex = createPsqlIndexStatementHelper({
tableName,
columns: ["item_id"],
where: "deleted_at IS NOT NULL",
})
const DeletedAtIndex = createPsqlIndexStatementHelper({
tableName,
columns: "deleted_at",
where: "deleted_at IS NOT NULL",
})
@Entity({ tableName })
export default class OrderItem {
[OptionalProps]?: OptionalLineItemProps
@PrimaryKey({ columnType: "text" })
id: string
@ManyToOne({
entity: () => Order,
mapToPk: true,
fieldName: "order_id",
columnType: "text",
const _OrderItem = model
.define("OrderItem", {
id: model.id({ prefix: "orditem" }).primaryKey(),
version: model.number().default(1),
unit_price: model.bigNumber().nullable(),
compare_at_unit_price: model.bigNumber().nullable(),
quantity: model.bigNumber(),
fulfilled_quantity: model.bigNumber().default(0),
delivered_quantity: model.bigNumber().default(0),
shipped_quantity: model.bigNumber().default(0),
return_requested_quantity: model.bigNumber().default(0),
return_received_quantity: model.bigNumber().default(0),
return_dismissed_quantity: model.bigNumber().default(0),
written_off_quantity: model.bigNumber().default(0),
metadata: model.json().nullable(),
order: model.belongsTo<() => typeof Order>(() => Order, {
mappedBy: "items",
}),
item: model.hasOne<() => typeof OrderLineItem>(() => OrderLineItem, {
mappedBy: undefined,
foreignKey: true,
}),
})
@OrderIdIndex.MikroORMIndex()
order_id: string
.indexes([
{
name: "IDX_order_item_order_id",
on: ["order_id"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_item_version",
on: ["version"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_item_item_id",
on: ["item_id"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_item_deleted_at",
on: ["deleted_at"],
unique: false,
where: "deleted_at IS NOT NULL",
},
])
@ManyToOne(() => Order, {
persist: false,
})
order: Rel<Order>
@Property({ columnType: "integer" })
@OrderVersionIndex.MikroORMIndex()
version: number
@ManyToOne({
entity: () => OrderLineItem,
fieldName: "item_id",
mapToPk: true,
columnType: "text",
})
@ItemIdIndex.MikroORMIndex()
item_id: string
@ManyToOne(() => OrderLineItem, {
persist: false,
})
item: Rel<OrderLineItem>
@MikroOrmBigNumberProperty({ nullable: true })
unit_price: BigNumber | number | null = null
@Property({ columnType: "jsonb", nullable: true })
raw_unit_price: BigNumberRawValue | null = null
@MikroOrmBigNumberProperty({ nullable: true })
compare_at_unit_price: BigNumber | number | null = null
@Property({ columnType: "jsonb", nullable: true })
raw_compare_at_unit_price: BigNumberRawValue | null = null
@MikroOrmBigNumberProperty()
quantity: BigNumber | number
@Property({ columnType: "jsonb" })
raw_quantity: BigNumberRawValue
@MikroOrmBigNumberProperty()
fulfilled_quantity: BigNumber | number = 0
@Property({ columnType: "jsonb" })
raw_fulfilled_quantity: BigNumberRawValue
@MikroOrmBigNumberProperty()
delivered_quantity: BigNumber | number = 0
@Property({ columnType: "jsonb" })
raw_delivered_quantity: BigNumberRawValue
@MikroOrmBigNumberProperty()
shipped_quantity: BigNumber | number = 0
@Property({ columnType: "jsonb" })
raw_shipped_quantity: BigNumberRawValue
@MikroOrmBigNumberProperty()
return_requested_quantity: BigNumber | number = 0
@Property({ columnType: "jsonb" })
raw_return_requested_quantity: BigNumberRawValue
@MikroOrmBigNumberProperty()
return_received_quantity: BigNumber | number = 0
@Property({ columnType: "jsonb" })
raw_return_received_quantity: BigNumberRawValue
@MikroOrmBigNumberProperty()
return_dismissed_quantity: BigNumber | number = 0
@Property({ columnType: "jsonb" })
raw_return_dismissed_quantity: BigNumberRawValue
@MikroOrmBigNumberProperty()
written_off_quantity: BigNumber | number = 0
@Property({ columnType: "jsonb" })
raw_written_off_quantity: BigNumberRawValue
@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: "timestamptz", nullable: true })
@DeletedAtIndex.MikroORMIndex()
deleted_at: Date | null = null
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "orditem")
this.order_id ??= this.order?.id
this.item_id ??= this.item?.id
this.version ??= this.order?.version
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "orditem")
this.order_id ??= this.order?.id
this.item_id ??= this.item?.id
this.version ??= this.order?.version
}
}
export const OrderItem = _OrderItem
@@ -1,194 +1,83 @@
import { DAL } from "@medusajs/framework/types"
import {
createPsqlIndexStatementHelper,
generateEntityId,
} from "@medusajs/framework/utils"
import {
BeforeCreate,
Entity,
ManyToOne,
OnInit,
OptionalProps,
PrimaryKey,
Property,
Rel,
} from "@mikro-orm/core"
import Claim from "./claim"
import Exchange from "./exchange"
import Order from "./order"
import Return from "./return"
import OrderShippingMethod from "./shipping-method"
import { model } from "@medusajs/framework/utils"
import { OrderClaim } from "./claim"
import { OrderExchange } from "./exchange"
import { Order } from "./order"
import { Return } from "./return"
import { OrderShippingMethod } from "./shipping-method"
type OptionalShippingMethodProps = DAL.ModelDateColumns
const tableName = "order_shipping"
const OrderIdIndex = createPsqlIndexStatementHelper({
tableName,
columns: ["order_id"],
where: "deleted_at IS NOT NULL",
})
const ReturnIdIndex = createPsqlIndexStatementHelper({
tableName,
columns: "return_id",
where: "return_id IS NOT NULL AND deleted_at IS NOT NULL",
})
const ExchangeIdIndex = createPsqlIndexStatementHelper({
tableName,
columns: ["exchange_id"],
where: "exchange_id IS NOT NULL AND deleted_at IS NOT NULL",
})
const ClaimIdIndex = createPsqlIndexStatementHelper({
tableName,
columns: ["claim_id"],
where: "claim_id IS NOT NULL AND deleted_at IS NOT NULL",
})
const OrderVersionIndex = createPsqlIndexStatementHelper({
tableName,
columns: ["version"],
where: "deleted_at IS NOT NULL",
})
const ItemIdIndex = createPsqlIndexStatementHelper({
tableName,
columns: ["shipping_method_id"],
where: "deleted_at IS NOT NULL",
})
const DeletedAtIndex = createPsqlIndexStatementHelper({
tableName,
columns: "deleted_at",
where: "deleted_at IS NOT NULL",
})
@Entity({ tableName })
export default class OrderShipping {
[OptionalProps]?: OptionalShippingMethodProps
@PrimaryKey({ columnType: "text" })
id: string
@ManyToOne({
entity: () => Order,
mapToPk: true,
fieldName: "order_id",
columnType: "text",
const _OrderShipping = model
.define("OrderShipping", {
id: model.id({ prefix: "ordspmv" }).primaryKey(),
version: model.number().default(1),
order: model.belongsTo<() => typeof Order>(() => Order, {
mappedBy: "shipping_methods",
}),
return: model
.belongsTo<() => typeof Return>(() => Return, {
mappedBy: "shipping_methods",
})
.nullable(),
exchange: model
.belongsTo<() => typeof OrderExchange>(() => OrderExchange, {
mappedBy: "shipping_methods",
})
.nullable(),
claim: model
.belongsTo<() => typeof OrderClaim>(() => OrderClaim, {
mappedBy: "shipping_methods",
})
.nullable(),
shipping_method: model.hasOne<() => typeof OrderShippingMethod>(
() => OrderShippingMethod,
{
mappedBy: undefined,
foreignKey: true,
}
),
})
@OrderIdIndex.MikroORMIndex()
order_id: string
.indexes([
{
name: "IDX_order_shipping_order_id",
on: ["order_id"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_shipping_return_id",
on: ["return_id"],
unique: false,
where: "return_id IS NOT NULL AND deleted_at IS NOT NULL",
},
{
name: "IDX_order_shipping_exchange_id",
on: ["exchange_id"],
unique: false,
where: "exchange_id IS NOT NULL AND deleted_at IS NOT NULL",
},
{
name: "IDX_order_shipping_claim_id",
on: ["claim_id"],
unique: false,
where: "claim_id IS NOT NULL AND deleted_at IS NOT NULL",
},
{
name: "IDX_order_shipping_version",
on: ["version"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_shipping_shipping_method_id",
on: ["shipping_method_id"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_shipping_deleted_at",
on: ["deleted_at"],
unique: false,
where: "deleted_at IS NOT NULL",
},
])
@ManyToOne(() => Order, {
persist: false,
})
order: Rel<Order>
@ManyToOne({
entity: () => Return,
mapToPk: true,
fieldName: "return_id",
columnType: "text",
nullable: true,
})
@ReturnIdIndex.MikroORMIndex()
return_id: string | null = null
@ManyToOne(() => Return, {
persist: false,
nullable: true,
})
return: Rel<Return>
@ManyToOne({
entity: () => Exchange,
mapToPk: true,
fieldName: "exchange_id",
columnType: "text",
nullable: true,
})
@ExchangeIdIndex.MikroORMIndex()
exchange_id: string | null
@ManyToOne(() => Exchange, {
persist: false,
nullable: true,
})
exchange: Rel<Exchange>
@ManyToOne({
entity: () => Claim,
mapToPk: true,
fieldName: "claim_id",
columnType: "text",
nullable: true,
})
@ClaimIdIndex.MikroORMIndex()
claim_id: string | null
@ManyToOne(() => Claim, {
persist: false,
nullable: true,
})
claim: Rel<Claim>
@Property({ columnType: "integer" })
@OrderVersionIndex.MikroORMIndex()
version: number
@ManyToOne({
entity: () => OrderShippingMethod,
fieldName: "shipping_method_id",
mapToPk: true,
columnType: "text",
})
@ItemIdIndex.MikroORMIndex()
shipping_method_id: string
@ManyToOne(() => OrderShippingMethod, {
persist: false,
})
shipping_method: Rel<OrderShippingMethod>
@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 })
@DeletedAtIndex.MikroORMIndex()
deleted_at: Date | null = null
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "ordspmv")
this.order_id ??= this.order?.id
this.return_id ??= this.return?.id
this.claim_id ??= this.claim?.id
this.exchange_id ??= this.exchange?.id
this.shipping_method_id ??= this.shipping_method?.id
this.version ??= this.order?.version
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "ordspmv")
this.order_id ??= this.order?.id
this.return_id ??= this.return?.id
this.claim_id ??= this.claim?.id
this.exchange_id ??= this.exchange?.id
this.shipping_method_id ??= this.shipping_method?.id
this.version ??= this.order?.version
}
}
export const OrderShipping = _OrderShipping
@@ -1,112 +1,33 @@
import {
BigNumber,
createPsqlIndexStatementHelper,
generateEntityId,
} from "@medusajs/framework/utils"
import {
BeforeCreate,
Entity,
ManyToOne,
OnInit,
PrimaryKey,
Property,
Rel,
} from "@mikro-orm/core"
import Order from "./order"
import { model } from "@medusajs/framework/utils"
import { Order } from "./order"
type OrderSummaryTotals = {
total: BigNumber
subtotal: BigNumber
total_tax: BigNumber
const _OrderSummary = model
.define(
{
tableName: "order_summary",
},
{
id: model.id({ prefix: "ordsum" }).primaryKey(),
version: model.number().default(1),
totals: model.json(),
order: model.belongsTo<() => typeof Order>(() => Order, {
mappedBy: "summary",
}),
}
)
.indexes([
{
name: "IDX_order_summary_order_id_version",
on: ["order_id", "version"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_summary_deleted_at",
on: ["deleted_at"],
unique: false,
where: "deleted_at IS NOT NULL",
},
])
ordered_total: BigNumber
fulfilled_total: BigNumber
returned_total: BigNumber
return_request_total: BigNumber
write_off_total: BigNumber
projected_total: BigNumber
net_total: BigNumber
net_subtotal: BigNumber
net_total_tax: BigNumber
balance: BigNumber
paid_total: BigNumber
refunded_total: BigNumber
}
const tableName = "order_summary"
const OrderIdVersionIndex = createPsqlIndexStatementHelper({
tableName,
columns: ["order_id", "version"],
where: "deleted_at IS NOT NULL",
})
const DeletedAtIndex = createPsqlIndexStatementHelper({
tableName,
columns: "deleted_at",
where: "deleted_at IS NOT NULL",
})
@Entity({ tableName })
@OrderIdVersionIndex.MikroORMIndex()
export default class OrderSummary {
@PrimaryKey({ columnType: "text" })
id: string
@ManyToOne({
entity: () => Order,
columnType: "text",
fieldName: "order_id",
mapToPk: true,
onDelete: "cascade",
})
order_id: string
@ManyToOne(() => Order, {
persist: false,
})
order: Rel<Order>
@Property({
columnType: "integer",
defaultRaw: "1",
})
version: number = 1
@Property({ columnType: "jsonb" })
totals: OrderSummaryTotals | null = {} as OrderSummaryTotals
@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 })
@DeletedAtIndex.MikroORMIndex()
deleted_at: Date | null = null
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "ordsum")
this.order_id ??= this.order?.id
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "ordsum")
this.order_id ??= this.order?.id
}
}
export const OrderSummary = _OrderSummary
+112 -226
View File
@@ -1,230 +1,116 @@
import { DAL } from "@medusajs/framework/types"
import {
OrderStatus,
Searchable,
createPsqlIndexStatementHelper,
generateEntityId,
} from "@medusajs/framework/utils"
import {
BeforeCreate,
Cascade,
Collection,
Entity,
Enum,
ManyToOne,
OnInit,
OneToMany,
OptionalProps,
PrimaryKey,
Property,
Rel,
} from "@mikro-orm/core"
import OrderAddress from "./address"
import OrderCreditLine from "./credit-line"
import OrderItem from "./order-item"
import OrderShipping from "./order-shipping-method"
import OrderSummary from "./order-summary"
import OrderTransaction from "./transaction"
import { model, OrderStatus } from "@medusajs/framework/utils"
import { OrderAddress } from "./address"
import { OrderCreditLine } from "./credit-line"
import { OrderItem } from "./order-item"
import { OrderShipping } from "./order-shipping-method"
import { OrderSummary } from "./order-summary"
import { OrderTransaction } from "./transaction"
import { Return } from "@models"
type OptionalOrderProps =
| "shipping_address"
| "billing_address"
| DAL.ModelDateColumns
const DisplayIdIndex = createPsqlIndexStatementHelper({
tableName: "order",
columns: "display_id",
where: "deleted_at IS NOT NULL",
})
const RegionIdIndex = createPsqlIndexStatementHelper({
tableName: "order",
columns: "region_id",
where: "deleted_at IS NOT NULL",
})
const CustomerIdIndex = createPsqlIndexStatementHelper({
tableName: "order",
columns: "customer_id",
where: "deleted_at IS NOT NULL",
})
const SalesChannelIdIndex = createPsqlIndexStatementHelper({
tableName: "order",
columns: "customer_id",
where: "deleted_at IS NOT NULL",
})
const OrderDeletedAtIndex = createPsqlIndexStatementHelper({
tableName: "order",
columns: "deleted_at",
where: "deleted_at IS NOT NULL",
})
const CurrencyCodeIndex = createPsqlIndexStatementHelper({
tableName: "order",
columns: "currency_code",
where: "deleted_at IS NOT NULL",
})
const ShippingAddressIdIndex = createPsqlIndexStatementHelper({
tableName: "order",
columns: "shipping_address_id",
where: "deleted_at IS NOT NULL",
})
const BillingAddressIdIndex = createPsqlIndexStatementHelper({
tableName: "order",
columns: "billing_address_id",
where: "deleted_at IS NOT NULL",
})
const IsDraftOrderIndex = createPsqlIndexStatementHelper({
tableName: "order",
columns: "is_draft_order",
where: "deleted_at IS NOT NULL",
})
@Entity({ tableName: "order" })
export default class Order {
[OptionalProps]?: OptionalOrderProps
@PrimaryKey({ columnType: "text" })
id: string
@Searchable()
@Property({ autoincrement: true, primary: false })
@DisplayIdIndex.MikroORMIndex()
display_id: number
@Property({
columnType: "text",
nullable: true,
const _Order = model
.define("Order", {
id: model.id({ prefix: "order" }).primaryKey(),
display_id: model.autoincrement(),
region_id: model.text().nullable(),
customer_id: model.text().nullable(),
version: model.number().default(1),
sales_channel_id: model.text().nullable(),
status: model.enum(OrderStatus).default(OrderStatus.PENDING),
is_draft_order: model.boolean().default(false),
email: model.text().searchable().nullable(),
currency_code: model.text(),
no_notification: model.boolean().nullable(),
metadata: model.json().nullable(),
canceled_at: model.dateTime().nullable(),
shipping_address: model
.hasOne<any>(() => OrderAddress, {
mappedBy: undefined,
foreignKey: true,
})
.nullable(),
billing_address: model
.hasOne<any>(() => OrderAddress, {
mappedBy: undefined,
foreignKey: true,
})
.nullable(),
summary: model.hasMany<any>(() => OrderSummary, {
mappedBy: "order",
}),
items: model.hasMany<any>(() => OrderItem, {
mappedBy: "order",
}),
shipping_methods: model.hasMany<any>(() => OrderShipping, {
mappedBy: "order",
}),
transactions: model.hasMany<any>(() => OrderTransaction, {
mappedBy: "order",
}),
credit_lines: model.hasMany<any>(() => OrderCreditLine, {
mappedBy: "order",
}),
returns: model.hasMany<any>(() => Return, {
mappedBy: "order",
}),
})
@RegionIdIndex.MikroORMIndex()
region_id: string | null = null
@Property({
columnType: "text",
nullable: true,
.cascades({
delete: ["summary", "items", "shipping_methods", "transactions"],
})
@CustomerIdIndex.MikroORMIndex()
customer_id: string | null = null
.indexes([
{
name: "IDX_order_display_id",
on: ["display_id"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_region_id",
on: ["region_id"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_customer_id",
on: ["customer_id"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_sales_channel_id",
on: ["sales_channel_id"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_deleted_at",
on: ["deleted_at"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_currency_code",
on: ["currency_code"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_shipping_address_id",
on: ["shipping_address_id"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_billing_address_id",
on: ["billing_address_id"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_is_draft_order",
on: ["is_draft_order"],
unique: false,
where: "deleted_at IS NOT NULL",
},
])
@Property({
columnType: "integer",
defaultRaw: "1",
})
version: number = 1
@Property({
columnType: "text",
nullable: true,
})
@SalesChannelIdIndex.MikroORMIndex()
sales_channel_id: string | null = null
@Enum({ items: () => OrderStatus, default: OrderStatus.PENDING })
status: OrderStatus
@Property({
columnType: "boolean",
})
@IsDraftOrderIndex.MikroORMIndex()
is_draft_order: boolean = false
@Searchable()
@Property({ columnType: "text", nullable: true })
email: string | null = null
@Property({ columnType: "text" })
@CurrencyCodeIndex.MikroORMIndex()
currency_code: string
@Property({ columnType: "text", nullable: true })
@ShippingAddressIdIndex.MikroORMIndex()
shipping_address_id?: string | null
@ManyToOne({
entity: () => OrderAddress,
fieldName: "shipping_address_id",
nullable: true,
cascade: [Cascade.PERSIST],
})
shipping_address?: Rel<OrderAddress> | null
@Property({ columnType: "text", nullable: true })
@BillingAddressIdIndex.MikroORMIndex()
billing_address_id?: string | null
@ManyToOne({
entity: () => OrderAddress,
fieldName: "billing_address_id",
nullable: true,
cascade: [Cascade.PERSIST],
})
billing_address?: Rel<OrderAddress> | null
@Property({ columnType: "boolean", nullable: true })
no_notification: boolean | null = null
@OneToMany(() => OrderSummary, (summary) => summary.order, {
cascade: [Cascade.PERSIST],
})
summary = new Collection<Rel<OrderSummary>>(this)
@Property({ columnType: "jsonb", nullable: true })
metadata: Record<string, unknown> | null = null
@OneToMany(() => OrderItem, (itemDetail) => itemDetail.order, {
cascade: [Cascade.PERSIST],
})
items = new Collection<Rel<OrderItem>>(this)
@OneToMany(() => OrderCreditLine, (creditLine) => creditLine.order, {
cascade: [Cascade.PERSIST],
})
credit_lines = new Collection<Rel<OrderCreditLine>>(this)
@OneToMany(() => OrderShipping, (shippingMethod) => shippingMethod.order, {
cascade: [Cascade.PERSIST],
})
shipping_methods = new Collection<Rel<OrderShipping>>(this)
@OneToMany(() => OrderTransaction, (transaction) => transaction.order, {
cascade: [Cascade.PERSIST],
})
transactions = new Collection<Rel<OrderTransaction>>(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 })
@OrderDeletedAtIndex.MikroORMIndex()
deleted_at: Date | null = null
@Property({ columnType: "timestamptz", nullable: true })
canceled_at: Date | null = null
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "order")
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "order")
}
}
export const Order = _Order
+56 -148
View File
@@ -1,150 +1,58 @@
import { BigNumberRawValue, DAL } from "@medusajs/framework/types"
import {
MikroOrmBigNumberProperty,
createPsqlIndexStatementHelper,
generateEntityId,
} from "@medusajs/framework/utils"
import {
BeforeCreate,
Entity,
ManyToOne,
OnInit,
OptionalProps,
PrimaryKey,
Property,
} from "@mikro-orm/core"
import OrderLineItem from "./line-item"
import Return from "./return"
import ReturnReason from "./return-reason"
import { model } from "@medusajs/framework/utils"
import { OrderLineItem } from "./line-item"
import { Return } from "./return"
import { ReturnReason } from "./return-reason"
type OptionalLineItemProps = DAL.ModelDateColumns
const _ReturnItem = model
.define(
{
tableName: "return_item",
},
{
id: model.id({ prefix: "retitem" }).primaryKey(),
quantity: model.bigNumber(),
received_quantity: model.bigNumber().default(0),
damaged_quantity: model.bigNumber().default(0),
note: model.text().nullable(),
metadata: model.json().nullable(),
reason: model
.belongsTo<() => typeof ReturnReason>(() => ReturnReason, {
mappedBy: "return_items",
})
.nullable(),
return: model.belongsTo<() => typeof Return>(() => Return, {
mappedBy: "items",
}),
item: model.belongsTo<() => typeof OrderLineItem>(() => OrderLineItem, {
mappedBy: "return_items",
}),
}
)
.indexes([
{
name: "IDX_return_item_return_id",
on: ["return_id"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_return_item_reason_id",
on: ["reason_id"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_return_item_item_id",
on: ["item_id"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_return_item_deleted_at",
on: ["deleted_at"],
unique: false,
where: "deleted_at IS NOT NULL",
},
])
const tableName = "return_item"
const ReturnIdIndex = createPsqlIndexStatementHelper({
tableName,
columns: "return_id",
where: "deleted_at IS NOT NULL",
})
const ReturnReasonIdIndex = createPsqlIndexStatementHelper({
tableName,
columns: "reason_id",
where: "deleted_at IS NOT NULL",
})
const ItemIdIndex = createPsqlIndexStatementHelper({
tableName,
columns: "item_id",
where: "deleted_at IS NOT NULL",
})
const DeletedAtIndex = createPsqlIndexStatementHelper({
tableName,
columns: "deleted_at",
where: "deleted_at IS NOT NULL",
})
@Entity({ tableName })
export default class ReturnItem {
[OptionalProps]?: OptionalLineItemProps
@PrimaryKey({ columnType: "text" })
id: string
@ManyToOne(() => ReturnReason, {
columnType: "text",
fieldName: "reason_id",
mapToPk: true,
nullable: true,
})
@ReturnReasonIdIndex.MikroORMIndex()
reason_id: string | null = null
@ManyToOne(() => ReturnReason, {
persist: false,
})
reason: ReturnReason
@MikroOrmBigNumberProperty()
quantity: Number | number
@Property({ columnType: "jsonb" })
raw_quantity: BigNumberRawValue
@MikroOrmBigNumberProperty()
received_quantity: Number | number = 0
@Property({ columnType: "jsonb" })
raw_received_quantity: BigNumberRawValue
@MikroOrmBigNumberProperty()
damaged_quantity: Number | number = 0
@Property({ columnType: "jsonb" })
raw_damaged_quantity: BigNumberRawValue
@ManyToOne(() => Return, {
columnType: "text",
fieldName: "return_id",
mapToPk: true,
onDelete: "cascade",
})
@ReturnIdIndex.MikroORMIndex()
return_id: string
@ManyToOne(() => Return, {
persist: false,
})
return: Return
@ManyToOne({
entity: () => OrderLineItem,
fieldName: "item_id",
mapToPk: true,
columnType: "text",
})
@ItemIdIndex.MikroORMIndex()
item_id: string
@ManyToOne(() => OrderLineItem, {
persist: false,
})
item: OrderLineItem
@Property({ columnType: "text", nullable: true })
note: 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: "timestamptz", nullable: true })
@DeletedAtIndex.MikroORMIndex()
deleted_at: Date | null = null
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "retitem")
this.return_id ??= this.return?.id
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "retitem")
this.return_id ??= this.return?.id
}
}
export const ReturnItem = _ReturnItem
@@ -1,111 +1,43 @@
import { DAL } from "@medusajs/framework/types"
import {
DALUtils,
Searchable,
createPsqlIndexStatementHelper,
generateEntityId,
} from "@medusajs/framework/utils"
import {
BeforeCreate,
Cascade,
Entity,
Filter,
ManyToOne,
OnInit,
OneToMany,
OptionalProps,
PrimaryKey,
Property,
Rel,
} from "@mikro-orm/core"
import { model } from "@medusajs/framework/utils"
const DeletedAtIndex = createPsqlIndexStatementHelper({
tableName: "return_reason",
columns: "deleted_at",
where: "deleted_at IS NOT NULL",
})
const ValueIndex = createPsqlIndexStatementHelper({
tableName: "return_reason",
columns: "value",
where: "deleted_at IS NOT NULL",
})
const ParentIndex = createPsqlIndexStatementHelper({
tableName: "return_reason",
columns: "parent_return_reason_id",
where: "deleted_at IS NOT NULL",
})
type OptionalOrderProps = "parent_return_reason" | DAL.ModelDateColumns
@Entity({ tableName: "return_reason" })
@Filter(DALUtils.mikroOrmSoftDeletableFilterOptions)
export default class ReturnReason {
[OptionalProps]?: OptionalOrderProps
@PrimaryKey({ columnType: "text" })
id: string
@Searchable()
@Property({ columnType: "text" })
@ValueIndex.MikroORMIndex()
value: string
@Searchable()
@Property({ columnType: "text" })
label: string
@Property({ columnType: "text", nullable: true })
description: string | null = null
@Property({ columnType: "text", nullable: true })
@ParentIndex.MikroORMIndex()
parent_return_reason_id?: string | null
@ManyToOne({
entity: () => ReturnReason,
fieldName: "parent_return_reason_id",
nullable: true,
cascade: [Cascade.PERSIST],
const _ReturnReason = model
.define("ReturnReason", {
id: model.id({ prefix: "rr" }).primaryKey(),
value: model.text().searchable(),
label: model.text().searchable(),
description: model.text().nullable(),
metadata: model.json().nullable(),
parent_return_reason: model
.belongsTo<() => typeof _ReturnReason>(() => _ReturnReason, {
mappedBy: "return_reason_children",
})
.nullable(),
return_reason_children: model.hasMany<() => typeof _ReturnReason>(
() => _ReturnReason,
{
mappedBy: "parent_return_reason",
}
),
})
parent_return_reason?: Rel<ReturnReason> | null
@OneToMany(
() => ReturnReason,
(return_reason) => return_reason.parent_return_reason,
{ cascade: [Cascade.PERSIST] }
)
return_reason_children: Rel<ReturnReason>[]
.indexes([
{
name: "IDX_return_reason_deleted_at",
on: ["deleted_at"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_return_reason_value",
on: ["value"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_return_reason_parent_return_reason_id",
on: ["parent_return_reason_id"],
unique: false,
where: "deleted_at IS NOT 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
@Property({ columnType: "timestamptz", nullable: true })
@DeletedAtIndex.MikroORMIndex()
deleted_at: Date | null = null
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "rr")
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "rr")
}
}
export const ReturnReason = _ReturnReason
+86 -188
View File
@@ -1,192 +1,90 @@
import { BigNumberRawValue, DAL } from "@medusajs/framework/types"
import {
BigNumber,
DALUtils,
MikroOrmBigNumberProperty,
ReturnStatus,
createPsqlIndexStatementHelper,
generateEntityId,
} from "@medusajs/framework/utils"
import {
BeforeCreate,
Cascade,
Collection,
Entity,
Enum,
Filter,
ManyToOne,
OnInit,
OneToMany,
OneToOne,
OptionalProps,
PrimaryKey,
Property,
Rel,
} from "@mikro-orm/core"
import { OrderTransaction, ReturnItem } from "@models"
import Claim from "./claim"
import Exchange from "./exchange"
import Order from "./order"
import OrderShipping from "./order-shipping-method"
import { model, ReturnStatus } from "@medusajs/framework/utils"
import { OrderClaim } from "./claim"
import { OrderExchange } from "./exchange"
import { Order } from "./order"
import { OrderShipping } from "./order-shipping-method"
import { ReturnItem } from "./return-item"
import { OrderTransaction } from "./transaction"
type OptionalReturnProps = DAL.ModelDateColumns
const DisplayIdIndex = createPsqlIndexStatementHelper({
tableName: "return",
columns: "display_id",
where: "deleted_at IS NOT NULL",
})
const ReturnDeletedAtIndex = createPsqlIndexStatementHelper({
tableName: "return",
columns: "deleted_at",
where: "deleted_at IS NOT NULL",
})
const OrderIdIndex = createPsqlIndexStatementHelper({
tableName: "return",
columns: ["order_id"],
where: "deleted_at IS NOT NULL",
})
const ExchangeIdIndex = createPsqlIndexStatementHelper({
tableName: "return",
columns: ["exchange_id"],
where: "exchange_id IS NOT NULL AND deleted_at IS NOT NULL",
})
const ClaimIdIndex = createPsqlIndexStatementHelper({
tableName: "return",
columns: ["claim_id"],
where: "claim_id IS NOT NULL AND deleted_at IS NOT NULL",
})
@Entity({ tableName: "return" })
@Filter(DALUtils.mikroOrmSoftDeletableFilterOptions)
export default class Return {
[OptionalProps]?: OptionalReturnProps
@PrimaryKey({ columnType: "text" })
id: string
@ManyToOne({
entity: () => Order,
mapToPk: true,
fieldName: "order_id",
columnType: "text",
const _Return = model
.define("Return", {
id: model.id({ prefix: "return" }).primaryKey(),
order_version: model.number(),
display_id: model.autoincrement(),
status: model.enum(ReturnStatus).default(ReturnStatus.OPEN),
location_id: model.text().nullable(),
no_notification: model.boolean().nullable(),
refund_amount: model.bigNumber().nullable(),
created_by: model.text().nullable(),
metadata: model.json().nullable(),
requested_at: model.dateTime().nullable(),
received_at: model.dateTime().nullable(),
canceled_at: model.dateTime().nullable(),
order: model.belongsTo<() => typeof Order>(() => Order, {
mappedBy: "returns",
}),
exchange: model
.hasOne<() => typeof OrderExchange>(() => OrderExchange, {
mappedBy: undefined,
foreignKey: true,
})
.nullable(),
claim: model
.hasOne<() => typeof OrderClaim>(() => OrderClaim, {
mappedBy: undefined,
foreignKey: true,
})
.nullable(),
items: model.hasMany<() => typeof ReturnItem>(() => ReturnItem, {
mappedBy: "return",
}),
shipping_methods: model.hasMany<() => typeof OrderShipping>(
() => OrderShipping,
{
mappedBy: "return",
}
),
transactions: model.hasMany<() => typeof OrderTransaction>(
() => OrderTransaction,
{
mappedBy: "return",
}
),
})
@OrderIdIndex.MikroORMIndex()
order_id: string
@ManyToOne(() => Order, {
persist: false,
.cascades({
delete: ["items", "shipping_methods", "transactions"],
})
order: Rel<Order>
.indexes([
{
name: "IDX_return_display_id",
on: ["display_id"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_return_deleted_at",
on: ["deleted_at"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_return_order_id",
on: ["order_id"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_return_exchange_id",
on: ["exchange_id"],
unique: false,
where: "exchange_id IS NOT NULL AND deleted_at IS NOT NULL",
},
{
name: "IDX_return_claim_id",
on: ["claim_id"],
unique: false,
where: "claim_id IS NOT NULL AND deleted_at IS NOT NULL",
},
])
@OneToOne({
entity: () => Exchange,
fieldName: "exchange_id",
nullable: true,
})
exchange: Rel<Exchange>
@Property({ columnType: "text", nullable: true })
@ExchangeIdIndex.MikroORMIndex()
exchange_id: string | null = null
@OneToOne({
entity: () => Claim,
fieldName: "claim_id",
nullable: true,
})
claim: Rel<Claim>
@Property({ columnType: "text", nullable: true })
@ClaimIdIndex.MikroORMIndex()
claim_id: string | null = null
@Property({
columnType: "integer",
})
order_version: number
@Property({ autoincrement: true, primary: false })
@DisplayIdIndex.MikroORMIndex()
display_id: number
@Enum({ items: () => ReturnStatus, default: ReturnStatus.OPEN })
status: ReturnStatus = ReturnStatus.OPEN
@Property({ columnType: "text", nullable: true })
location_id: string | null = null
@Property({ columnType: "boolean", nullable: true })
no_notification: boolean | null = null
@MikroOrmBigNumberProperty({
nullable: true,
})
refund_amount: BigNumber | number
@Property({ columnType: "jsonb", nullable: true })
raw_refund_amount: BigNumberRawValue
@OneToMany(() => ReturnItem, (itemDetail) => itemDetail.return, {
cascade: [Cascade.PERSIST],
})
items = new Collection<Rel<ReturnItem>>(this)
@OneToMany(() => OrderShipping, (shippingMethod) => shippingMethod.return, {
cascade: [Cascade.PERSIST],
})
shipping_methods = new Collection<OrderShipping>(this)
@OneToMany(() => OrderTransaction, (transaction) => transaction.return, {
cascade: [Cascade.PERSIST],
})
transactions = new Collection<OrderTransaction>(this)
@Property({ columnType: "text", nullable: true })
created_by: 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
@Property({ columnType: "timestamptz", nullable: true })
@ReturnDeletedAtIndex.MikroORMIndex()
deleted_at: Date | null = null
@Property({ columnType: "timestamptz", nullable: true })
requested_at: Date | null = null
@Property({ columnType: "timestamptz", nullable: true })
received_at: Date | null = null
@Property({ columnType: "timestamptz", nullable: true })
canceled_at: Date | null = null
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "return")
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "return")
}
}
export const Return = _Return
@@ -1,42 +1,32 @@
import {
createPsqlIndexStatementHelper,
generateEntityId,
} from "@medusajs/framework/utils"
import { BeforeCreate, Entity, ManyToOne, OnInit, Rel } from "@mikro-orm/core"
import AdjustmentLine from "./adjustment-line"
import OrderShippingMethod from "./shipping-method"
import { model } from "@medusajs/framework/utils"
import { OrderShippingMethod } from "./shipping-method"
const ShippingMethodIdIdIndex = createPsqlIndexStatementHelper({
tableName: "order_shipping_method_adjustment",
columns: "shipping_method_id",
})
const _OrderShippingMethodAdjustment = model
.define(
{
tableName: "order_shipping_method_adjustment",
},
{
id: model.id({ prefix: "ordsmadj" }).primaryKey(),
description: model.text().nullable(),
promotion_id: model.text().nullable(),
code: model.text().nullable(),
amount: model.bigNumber(),
provider_id: model.text().nullable(),
shipping_method: model.belongsTo<() => typeof OrderShippingMethod>(
() => OrderShippingMethod,
{
mappedBy: "adjustments",
}
),
}
)
.indexes([
{
name: "IDX_order_shipping_method_adjustment_shipping_method_id",
on: ["shipping_method_id"],
unique: false,
},
])
@Entity({ tableName: "order_shipping_method_adjustment" })
export default class OrderShippingMethodAdjustment extends AdjustmentLine {
@ManyToOne(() => OrderShippingMethod, {
persist: false,
})
shipping_method: Rel<OrderShippingMethod>
@ManyToOne({
entity: () => OrderShippingMethod,
columnType: "text",
fieldName: "shipping_method_id",
mapToPk: true,
onDelete: "cascade",
})
@ShippingMethodIdIdIndex.MikroORMIndex()
shipping_method_id: string
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "ordsmadj")
this.shipping_method_id ??= this.shipping_method?.id
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "ordsmadj")
this.shipping_method_id ??= this.shipping_method?.id
}
}
export const OrderShippingMethodAdjustment = _OrderShippingMethodAdjustment
@@ -1,42 +1,32 @@
import {
createPsqlIndexStatementHelper,
generateEntityId,
} from "@medusajs/framework/utils"
import { BeforeCreate, Entity, ManyToOne, OnInit, Rel } from "@mikro-orm/core"
import OrderShippingMethod from "./shipping-method"
import TaxLine from "./tax-line"
import { model } from "@medusajs/framework/utils"
import { OrderShippingMethod } from "./shipping-method"
const ShippingMethodIdIdIndex = createPsqlIndexStatementHelper({
tableName: "order_shipping_method_tax_line",
columns: "shipping_method_id",
})
const _OrderShippingMethodTaxLine = model
.define(
{
tableName: "order_shipping_method_tax_line",
},
{
id: model.id({ prefix: "ordsmtxl" }).primaryKey(),
description: model.text().nullable(),
tax_rate_id: model.text().nullable(),
code: model.text(),
rate: model.bigNumber(),
provider_id: model.text().nullable(),
shipping_method: model.belongsTo<() => typeof OrderShippingMethod>(
() => OrderShippingMethod,
{
mappedBy: "tax_lines",
}
),
}
)
.indexes([
{
name: "IDX_order_shipping_method_tax_line_shipping_method_id",
on: ["shipping_method_id"],
unique: false,
},
])
@Entity({ tableName: "order_shipping_method_tax_line" })
export default class OrderShippingMethodTaxLine extends TaxLine {
@ManyToOne(() => OrderShippingMethod, {
persist: false,
})
shipping_method: Rel<OrderShippingMethod>
@ManyToOne({
entity: () => OrderShippingMethod,
fieldName: "shipping_method_id",
columnType: "text",
mapToPk: true,
onDelete: "cascade",
})
@ShippingMethodIdIdIndex.MikroORMIndex()
shipping_method_id: string
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "ordsmtxl")
this.shipping_method_id ??= this.shipping_method?.id
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "ordsmtxl")
this.shipping_method_id ??= this.shipping_method?.id
}
}
export const OrderShippingMethodTaxLine = _OrderShippingMethodTaxLine
@@ -1,118 +1,40 @@
import { BigNumberRawValue } from "@medusajs/framework/types"
import {
BigNumber,
createPsqlIndexStatementHelper,
DALUtils,
generateEntityId,
MikroOrmBigNumberProperty,
} from "@medusajs/framework/utils"
import {
BeforeCreate,
Cascade,
Collection,
Entity,
Filter,
OneToMany,
OnInit,
PrimaryKey,
Property,
Rel,
} from "@mikro-orm/core"
import OrderShippingMethodAdjustment from "./shipping-method-adjustment"
import OrderShippingMethodTaxLine from "./shipping-method-tax-line"
import { model } from "@medusajs/framework/utils"
import { OrderShippingMethodAdjustment } from "./shipping-method-adjustment"
import { OrderShippingMethodTaxLine } from "./shipping-method-tax-line"
const DeletedAtIndex = createPsqlIndexStatementHelper({
tableName: "order_shipping_method",
columns: "deleted_at",
where: "deleted_at IS NOT NULL",
})
const ShippingOptionIdIndex = createPsqlIndexStatementHelper({
tableName: "order_shipping_method",
columns: "shipping_option_id",
where: "deleted_at IS NOT NULL",
})
@Entity({ tableName: "order_shipping_method" })
@Filter(DALUtils.mikroOrmSoftDeletableFilterOptions)
export default class OrderShippingMethod {
@PrimaryKey({ columnType: "text" })
id: string
@Property({ columnType: "text" })
name: string
@Property({ columnType: "jsonb", nullable: true })
description: string | null = null
@MikroOrmBigNumberProperty()
amount: BigNumber | number
@Property({ columnType: "jsonb" })
raw_amount: BigNumberRawValue
@Property({ columnType: "boolean" })
is_tax_inclusive: boolean = false
@Property({ columnType: "boolean", default: false })
is_custom_amount: boolean = false
@Property({
columnType: "text",
nullable: true,
const _OrderShippingMethod = model
.define("OrderShippingMethod", {
id: model.id({ prefix: "ordsm" }).primaryKey(),
name: model.text(),
description: model.json().nullable(),
amount: model.bigNumber(),
is_tax_inclusive: model.boolean().default(false),
is_custom_amount: model.boolean().default(false),
shipping_option_id: model.text().nullable(),
data: model.json().nullable(),
metadata: model.json().nullable(),
tax_lines: model.hasMany<() => typeof OrderShippingMethodTaxLine>(
() => OrderShippingMethodTaxLine,
{
mappedBy: "shipping_method",
}
),
adjustments: model.hasMany<() => typeof OrderShippingMethodAdjustment>(
() => OrderShippingMethodAdjustment,
{
mappedBy: "shipping_method",
}
),
})
@ShippingOptionIdIndex.MikroORMIndex()
shipping_option_id: string | null = null
@Property({ columnType: "jsonb", nullable: true })
data: Record<string, unknown> | null = null
@Property({ columnType: "jsonb", nullable: true })
metadata: Record<string, unknown> | null = null
@OneToMany(
() => OrderShippingMethodTaxLine,
(taxLine) => taxLine.shipping_method,
.cascades({
delete: ["tax_lines", "adjustments"],
})
.indexes([
{
cascade: [Cascade.PERSIST, "soft-remove" as Cascade],
}
)
tax_lines = new Collection<Rel<OrderShippingMethodTaxLine>>(this)
name: "IDX_order_shipping_method_shipping_option_id",
on: ["shipping_option_id"],
unique: false,
},
])
@OneToMany(
() => OrderShippingMethodAdjustment,
(adjustment) => adjustment.shipping_method,
{
cascade: [Cascade.PERSIST, "soft-remove" as Cascade],
}
)
adjustments = new Collection<Rel<OrderShippingMethodAdjustment>>(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 })
@DeletedAtIndex.MikroORMIndex()
deleted_at: Date | null = null
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "ordsm")
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "ordsm")
}
}
export const OrderShippingMethod = _OrderShippingMethod
@@ -1,51 +0,0 @@
import { BigNumberRawValue } from "@medusajs/framework/types"
import { BigNumber, MikroOrmBigNumberProperty } from "@medusajs/framework/utils"
import { PrimaryKey, Property } from "@mikro-orm/core"
/**
* As per the Mikro ORM docs, superclasses should use the abstract class definition
* Source: https://mikro-orm.io/docs/inheritance-mapping
*/
export default abstract class TaxLine {
@PrimaryKey({ columnType: "text" })
id: string
@Property({ columnType: "text", nullable: true })
description?: string | null
@Property({
columnType: "text",
nullable: true,
})
tax_rate_id?: string | null
@Property({ columnType: "text" })
code: string
@MikroOrmBigNumberProperty()
rate: BigNumber | number
@Property({ columnType: "jsonb" })
raw_rate: BigNumberRawValue
@Property({ columnType: "text", nullable: true })
provider_id?: string | 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
}
+87 -209
View File
@@ -1,214 +1,92 @@
import { BigNumberRawValue, DAL } from "@medusajs/framework/types"
import {
BigNumber,
DALUtils,
MikroOrmBigNumberProperty,
createPsqlIndexStatementHelper,
generateEntityId,
DmlEntity,
DMLEntitySchemaBuilder,
model,
} from "@medusajs/framework/utils"
import {
BeforeCreate,
Entity,
Filter,
ManyToOne,
OnInit,
OptionalProps,
PrimaryKey,
Property,
Rel,
} from "@mikro-orm/core"
import Claim from "./claim"
import Exchange from "./exchange"
import Order from "./order"
import Return from "./return"
import { OrderClaim } from "./claim"
import { OrderExchange } from "./exchange"
import { Order } from "./order"
import { Return } from "./return"
type OptionalLineItemProps = DAL.ModelDateColumns
const tableName = "order_transaction"
const ReferenceIdIndex = createPsqlIndexStatementHelper({
tableName,
columns: "reference_id",
where: "deleted_at IS NOT NULL",
})
const OrderIdIndex = createPsqlIndexStatementHelper({
tableName,
columns: "order_id",
where: "deleted_at IS NOT NULL",
})
const ReturnIdIndex = createPsqlIndexStatementHelper({
tableName,
columns: "return_id",
where: "return_id IS NOT NULL AND deleted_at IS NOT NULL",
})
const ExchangeIdIndex = createPsqlIndexStatementHelper({
tableName,
columns: ["exchange_id"],
where: "exchange_id IS NOT NULL AND deleted_at IS NOT NULL",
})
const ClaimIdIndex = createPsqlIndexStatementHelper({
tableName,
columns: ["claim_id"],
where: "claim_id IS NOT NULL AND deleted_at IS NOT NULL",
})
const CurrencyCodeIndex = createPsqlIndexStatementHelper({
tableName,
columns: "currency_code",
where: "deleted_at IS NOT NULL",
})
const DeletedAtIndex = createPsqlIndexStatementHelper({
tableName,
columns: "deleted_at",
where: "deleted_at IS NOT NULL",
})
const OrderIdVersionIndex = createPsqlIndexStatementHelper({
tableName,
columns: ["order_id", "version"],
where: "deleted_at IS NOT NULL",
})
@Entity({ tableName })
@Filter(DALUtils.mikroOrmSoftDeletableFilterOptions)
@OrderIdVersionIndex.MikroORMIndex()
export default class OrderTransaction {
[OptionalProps]?: OptionalLineItemProps
@PrimaryKey({ columnType: "text" })
id: string
@ManyToOne({
entity: () => Order,
columnType: "text",
fieldName: "order_id",
onDelete: "cascade",
mapToPk: true,
const _OrderTransaction = model
.define("OrderTransaction", {
id: model.id({ prefix: "ordtrx" }).primaryKey(),
version: model.number().default(1),
amount: model.bigNumber(),
currency_code: model.text(),
reference: model.text().nullable(),
reference_id: model.text().nullable(),
order: model.belongsTo<() => typeof Order>(() => Order, {
mappedBy: "transactions",
}),
return: model
.belongsTo<() => typeof Return>(() => Return, {
mappedBy: "transactions",
})
.nullable(),
exchange: model
.belongsTo<() => typeof OrderExchange>(() => OrderExchange, {
mappedBy: "transactions",
})
.nullable(),
claim: model
.belongsTo<() => typeof OrderClaim>(() => OrderClaim, {
mappedBy: "transactions",
})
.nullable(),
})
@OrderIdIndex.MikroORMIndex()
order_id: string
.indexes([
{
name: "IDX_order_transaction_reference_id",
on: ["reference_id"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_transaction_order_id",
on: ["order_id"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_transaction_return_id",
on: ["return_id"],
unique: false,
where: "return_id IS NOT NULL AND deleted_at IS NOT NULL",
},
{
name: "IDX_order_transaction_exchange_id",
on: ["exchange_id"],
unique: false,
where: "exchange_id IS NOT NULL AND deleted_at IS NOT NULL",
},
{
name: "IDX_order_transaction_claim_id",
on: ["claim_id"],
unique: false,
where: "claim_id IS NOT NULL AND deleted_at IS NOT NULL",
},
{
name: "IDX_order_transaction_currency_code",
on: ["currency_code"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_transaction_deleted_at",
on: ["deleted_at"],
unique: false,
where: "deleted_at IS NOT NULL",
},
{
name: "IDX_order_transaction_order_id_version",
on: ["order_id", "version"],
unique: false,
where: "deleted_at IS NOT NULL",
},
])
@ManyToOne(() => Order, {
persist: false,
})
order: Rel<Order>
@ManyToOne({
entity: () => Return,
mapToPk: true,
fieldName: "return_id",
columnType: "text",
nullable: true,
})
@ReturnIdIndex.MikroORMIndex()
return_id: string | null = null
@ManyToOne(() => Return, {
persist: false,
nullable: true,
})
return: Rel<Return>
@ManyToOne({
entity: () => Exchange,
mapToPk: true,
fieldName: "exchange_id",
columnType: "text",
nullable: true,
})
@ExchangeIdIndex.MikroORMIndex()
exchange_id: string | null
@ManyToOne(() => Exchange, {
persist: false,
nullable: true,
})
exchange: Rel<Exchange>
@ManyToOne({
entity: () => Claim,
mapToPk: true,
fieldName: "claim_id",
columnType: "text",
nullable: true,
})
@ClaimIdIndex.MikroORMIndex()
claim_id: string | null
@ManyToOne(() => Claim, {
persist: false,
nullable: true,
})
claim: Rel<Claim>
@Property({
columnType: "integer",
defaultRaw: "1",
})
version: number = 1
@MikroOrmBigNumberProperty()
amount: BigNumber | number
@Property({ columnType: "jsonb" })
raw_amount: BigNumberRawValue
@Property({ columnType: "text" })
@CurrencyCodeIndex.MikroORMIndex()
currency_code: string
@Property({
columnType: "text",
nullable: true,
})
reference: string | null = null
@Property({
columnType: "text",
nullable: true,
})
@ReferenceIdIndex.MikroORMIndex()
reference_id: 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 })
@DeletedAtIndex.MikroORMIndex()
deleted_at: Date | null = null
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "ordtrx")
this.order_id ??= this.order?.id
this.return_id ??= this.return?.id
this.claim_id ??= this.claim?.id
this.exchange_id ??= this.exchange?.id
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "ordtrx")
this.order_id ??= this.order?.id
this.return_id ??= this.return?.id
this.claim_id ??= this.claim?.id
this.exchange_id ??= this.exchange?.id
}
}
export const OrderTransaction = _OrderTransaction as DmlEntity<
DMLEntitySchemaBuilder<(typeof _OrderTransaction)["schema"]>,
"OrderTransaction"
>
@@ -11,11 +11,12 @@ import {
getShippingMethodsTotals,
isString,
promiseAll,
toMikroORMEntity,
} from "@medusajs/framework/utils"
import { OrderClaim, OrderClaimItem, Return, ReturnItem } from "@models"
function createClaimAndReturnEntities(em, data, order) {
const claimReference = em.create(OrderClaim, {
const claimReference = em.create(toMikroORMEntity(OrderClaim), {
order_id: data.order_id,
order_version: order.version,
type: data.type as ClaimType,
@@ -25,16 +26,16 @@ function createClaimAndReturnEntities(em, data, order) {
const returnReference =
data.type === ClaimType.REPLACE
? em.create(Return, {
? em.create(toMikroORMEntity(Return), {
order_id: data.order_id,
order_version: order.version,
status: ReturnStatus.REQUESTED,
claim_id: claimReference.id,
claim: claimReference.id,
refund_amount: (data.refund_amount as unknown) ?? null,
})
: undefined
claimReference.return_id = returnReference?.id
claimReference.return = returnReference?.id
return { claimReference, returnReference }
}
@@ -51,7 +52,7 @@ function createReturnItem(em, item, claimReference, returnReference, actions) {
},
})
return em.create(ReturnItem, {
return em.create(toMikroORMEntity(ReturnItem), {
item_id: item.id,
return_id: returnReference.id,
quantity: item.quantity,
@@ -67,7 +68,7 @@ function createClaimAndReturnItems(
returnReference,
actions
) {
const returnItems: ReturnItem[] = []
const returnItems: (typeof ReturnItem)[] = []
const claimItems = data.claim_items?.map((item) => {
actions.push({
action: ChangeActionType.WRITE_OFF_ITEM,
@@ -86,7 +87,7 @@ function createClaimAndReturnItems(
: undefined
)
return em.create(OrderClaimItem, {
return em.create(toMikroORMEntity(OrderClaimItem), {
item_id: item.id,
reason: item.reason,
quantity: item.quantity,
@@ -108,8 +109,8 @@ async function processAdditionalItems(
sharedContext
) {
const itemsToAdd: any[] = []
const additionalNewItems: OrderClaimItem[] = []
const additionalItems: OrderClaimItem[] = []
const additionalNewItems: any[] = []
const additionalItems: any[] = []
data.additional_items?.forEach((item) => {
const hasItem = item.id
? order.items.find((o) => o.item.id === item.id)
@@ -131,7 +132,7 @@ async function processAdditionalItems(
})
additionalItems.push(
em.create(OrderClaimItem, {
em.create(toMikroORMEntity(OrderClaimItem), {
item_id: item.id,
quantity: item.quantity,
note: item.note,
@@ -143,7 +144,7 @@ async function processAdditionalItems(
itemsToAdd.push(item)
additionalNewItems.push(
em.create(OrderClaimItem, {
em.create(toMikroORMEntity(OrderClaimItem), {
quantity: item.quantity,
unit_price: item.unit_price,
note: item.note,
@@ -10,11 +10,12 @@ import {
getShippingMethodsTotals,
isString,
promiseAll,
toMikroORMEntity,
} from "@medusajs/framework/utils"
import { OrderExchange, OrderExchangeItem, Return, ReturnItem } from "@models"
function createExchangeAndReturnEntities(em, data, order) {
const exchangeReference = em.create(OrderExchange, {
const exchangeReference = em.create(toMikroORMEntity(OrderExchange), {
order_id: data.order_id,
order_version: order.version,
no_notification: data.no_notification,
@@ -22,7 +23,7 @@ function createExchangeAndReturnEntities(em, data, order) {
difference_due: data.difference_due,
})
const returnReference = em.create(Return, {
const returnReference = em.create(toMikroORMEntity(Return), {
order_id: data.order_id,
order_version: order.version,
status: ReturnStatus.REQUESTED,
@@ -30,7 +31,7 @@ function createExchangeAndReturnEntities(em, data, order) {
refund_amount: (data.refund_amount as unknown) ?? null,
})
exchangeReference.return_id = returnReference.id
exchangeReference.return = returnReference
return { exchangeReference, returnReference }
}
@@ -54,7 +55,7 @@ function createReturnItems(
},
})
return em.create(ReturnItem, {
return em.create(toMikroORMEntity(ReturnItem), {
item_id: item.id,
return_id: returnReference.id,
reason: item.reason,
@@ -75,8 +76,8 @@ async function processAdditionalItems(
sharedContext
) {
const itemsToAdd: any[] = []
const additionalNewItems: OrderExchangeItem[] = []
const additionalItems: OrderExchangeItem[] = []
const additionalNewItems: any[] = []
const additionalItems: any[] = []
data.additional_items?.forEach((item) => {
const hasItem = item.id
? order.items.find((o) => o.item.id === item.id)
@@ -98,7 +99,7 @@ async function processAdditionalItems(
})
additionalItems.push(
em.create(OrderExchangeItem, {
em.create(toMikroORMEntity(OrderExchangeItem), {
item_id: item.id,
quantity: item.quantity,
note: item.note,
@@ -110,7 +111,7 @@ async function processAdditionalItems(
itemsToAdd.push(item)
additionalNewItems.push(
em.create(OrderExchangeItem, {
em.create(toMikroORMEntity(OrderExchangeItem), {
quantity: item.quantity,
unit_price: item.unit_price,
note: item.note,
@@ -313,6 +314,5 @@ export async function createExchange(
this.createOrderExchanges([exchangeReference], sharedContext),
this.confirmOrderChange(change[0].id, sharedContext),
])
return exchangeReference
}
@@ -11,11 +11,12 @@ import {
isDefined,
isString,
promiseAll,
toMikroORMEntity,
} from "@medusajs/framework/utils"
import { Return, ReturnItem } from "@models"
function createReturnReference(em, data, order) {
return em.create(Return, {
return em.create(toMikroORMEntity(Return), {
order_id: data.order_id,
order_version: order.version,
status: ReturnStatus.REQUESTED,
@@ -39,7 +40,7 @@ function createReturnItems(em, data, returnRef, actions) {
},
})
return em.create(ReturnItem, {
return em.create(toMikroORMEntity(ReturnItem), {
reason_id: item.reason_id,
return_id: returnRef.id,
item_id: item.id,
@@ -85,7 +85,7 @@ export async function receiveReturn(
data.return_id,
{
select: ["id", "order_id"],
relations: ["items"],
relations: ["items", "items.item"],
},
sharedContext
)
@@ -4,6 +4,7 @@ import {
DAL,
FilterableOrderReturnReasonProps,
FindConfig,
InferEntityType,
InternalModuleDeclaration,
IOrderModuleService,
ModuleJoinerConfig,
@@ -37,8 +38,10 @@ import {
OrderChangeStatus,
OrderStatus,
promiseAll,
toMikroORMEntity,
transformPropertiesToBigNumber,
} from "@medusajs/framework/utils"
import { BeforeCreate, OnInit, rel } from "@mikro-orm/core"
import {
Order,
OrderAddress,
@@ -136,32 +139,56 @@ const generateMethodForModels = {
OrderCreditLine,
}
{
const MikroORMEntity = toMikroORMEntity(OrderChangeAction)
MikroORMEntity.prototype["onInit_OrderChangeAction"] = function () {
this.version ??= this.order_change?.version ?? null
this.order_id ??= this.order_change?.order_id ?? null
this.claim_id ??= this.order_change?.claim_id ?? null
this.exchange_id ??= this.order_change?.exchange_id ?? null
if (!this.claim_id && !this.exchange_id) {
this.return_id = this.return?.id ?? this.order_change?.return_id ?? null
}
}
OnInit()(MikroORMEntity.prototype, "onInit_OrderChangeAction")
BeforeCreate()(MikroORMEntity.prototype, "onInit_OrderChangeAction")
}
{
const MikroORMEntity = toMikroORMEntity(OrderShipping)
MikroORMEntity.prototype["onInit_OrderShipping"] = function () {
this.version ??= this.order?.version ?? null
this.order ??= rel(toMikroORMEntity(Order), this.order?.id ?? null)
this.return ??= rel(toMikroORMEntity(Return), this.return?.id ?? null)
this.claim ??= rel(toMikroORMEntity(OrderClaim), this.claim?.id ?? null)
this.exchange ??= rel(
toMikroORMEntity(OrderExchange),
this.exchange?.id ?? null
)
this.shipping_method ??= rel(
toMikroORMEntity(OrderShippingMethod),
this.shipping_method?.id ?? null
)
}
OnInit()(MikroORMEntity.prototype, "onInit_OrderShipping")
BeforeCreate()(MikroORMEntity.prototype, "onInit_OrderShipping")
}
{
const MikroORMEntity = toMikroORMEntity(OrderItem)
MikroORMEntity.prototype["onInit_OrderItem"] = function () {
this.version ??= this.order?.version ?? null
this.order ??= rel(toMikroORMEntity(Order), this.order?.id ?? null)
this.item ??= rel(toMikroORMEntity(OrderLineItem), this.item?.id ?? null)
}
OnInit()(MikroORMEntity.prototype, "onInit_OrderItem")
BeforeCreate()(MikroORMEntity.prototype, "onInit_OrderItem")
}
// TODO: rm template args here, keep it for later to not collide with carlos work at least as little as possible
export default class OrderModuleService<
TOrder extends Order = Order,
TAddress extends OrderAddress = OrderAddress,
TLineItem extends OrderLineItem = OrderLineItem,
TLineItemAdjustment extends OrderLineItemAdjustment = OrderLineItemAdjustment,
TLineItemTaxLine extends OrderLineItemTaxLine = OrderLineItemTaxLine,
TOrderShippingMethodAdjustment extends OrderShippingMethodAdjustment = OrderShippingMethodAdjustment,
TOrderShippingMethodTaxLine extends OrderShippingMethodTaxLine = OrderShippingMethodTaxLine,
TOrderShippingMethod extends OrderShippingMethod = OrderShippingMethod,
TOrderTransaction extends OrderTransaction = OrderTransaction,
TOrderChange extends OrderChange = OrderChange,
TOrderChangeAction extends OrderChangeAction = OrderChangeAction,
TOrderItem extends OrderItem = OrderItem,
TOrderSummary extends OrderSummary = OrderSummary,
TOrderShipping extends OrderShipping = OrderShipping,
TReturnReason extends ReturnReason = ReturnReason,
TReturn extends Return = Return,
TReturnItem extends ReturnItem = ReturnItem,
TClaim extends OrderClaim = OrderClaim,
TClaimItem extends OrderClaimItem = OrderClaimItem,
TClaimItemImage extends OrderClaimItemImage = OrderClaimItemImage,
TExchange extends OrderExchange = OrderExchange,
TExchangeItem extends OrderExchangeItem = OrderExchangeItem,
TCreditLine extends OrderCreditLine = OrderCreditLine
>
export default class OrderModuleService
extends ModulesSdkUtils.MedusaService<{
Order: { dto: OrderTypes.OrderDTO }
OrderAddress: { dto: OrderTypes.OrderAddressDTO }
@@ -195,27 +222,69 @@ export default class OrderModuleService<
{
protected baseRepository_: DAL.RepositoryService
protected orderService_: OrderService
protected orderAddressService_: ModulesSdkTypes.IMedusaInternalService<TAddress>
protected orderLineItemService_: ModulesSdkTypes.IMedusaInternalService<TLineItem>
protected orderShippingMethodAdjustmentService_: ModulesSdkTypes.IMedusaInternalService<TOrderShippingMethodAdjustment>
protected orderShippingMethodService_: ModulesSdkTypes.IMedusaInternalService<TOrderShippingMethod>
protected orderLineItemAdjustmentService_: ModulesSdkTypes.IMedusaInternalService<TLineItemAdjustment>
protected orderLineItemTaxLineService_: ModulesSdkTypes.IMedusaInternalService<TLineItemTaxLine>
protected orderShippingMethodTaxLineService_: ModulesSdkTypes.IMedusaInternalService<TOrderShippingMethodTaxLine>
protected orderTransactionService_: ModulesSdkTypes.IMedusaInternalService<TOrderTransaction>
protected orderChangeService_: ModulesSdkTypes.IMedusaInternalService<TOrderChange>
protected orderChangeActionService_: ModulesSdkTypes.IMedusaInternalService<TOrderChangeAction>
protected orderItemService_: ModulesSdkTypes.IMedusaInternalService<TOrderItem>
protected orderSummaryService_: ModulesSdkTypes.IMedusaInternalService<TOrderSummary>
protected orderShippingService_: ModulesSdkTypes.IMedusaInternalService<TOrderShipping>
protected returnReasonService_: ModulesSdkTypes.IMedusaInternalService<TReturnReason>
protected returnService_: ModulesSdkTypes.IMedusaInternalService<TReturn>
protected returnItemService_: ModulesSdkTypes.IMedusaInternalService<TReturnItem>
protected orderClaimService_: ModulesSdkTypes.IMedusaInternalService<TClaim>
protected orderClaimItemService_: ModulesSdkTypes.IMedusaInternalService<TClaimItem>
protected orderClaimItemImageService_: ModulesSdkTypes.IMedusaInternalService<TClaimItemImage>
protected orderExchangeService_: ModulesSdkTypes.IMedusaInternalService<TExchange>
protected orderExchangeItemService_: ModulesSdkTypes.IMedusaInternalService<TExchangeItem>
protected orderAddressService_: ModulesSdkTypes.IMedusaInternalService<
InferEntityType<typeof OrderAddress>
>
protected orderLineItemService_: ModulesSdkTypes.IMedusaInternalService<
InferEntityType<typeof OrderLineItem>
>
protected orderShippingMethodAdjustmentService_: ModulesSdkTypes.IMedusaInternalService<
InferEntityType<typeof OrderShippingMethodAdjustment>
>
protected orderShippingMethodService_: ModulesSdkTypes.IMedusaInternalService<
InferEntityType<typeof OrderShippingMethod>
>
protected orderLineItemAdjustmentService_: ModulesSdkTypes.IMedusaInternalService<
InferEntityType<typeof OrderLineItemAdjustment>
>
protected orderLineItemTaxLineService_: ModulesSdkTypes.IMedusaInternalService<
InferEntityType<typeof OrderLineItemTaxLine>
>
protected orderShippingMethodTaxLineService_: ModulesSdkTypes.IMedusaInternalService<
InferEntityType<typeof OrderShippingMethodTaxLine>
>
protected orderTransactionService_: ModulesSdkTypes.IMedusaInternalService<
InferEntityType<typeof OrderTransaction>
>
protected orderChangeService_: ModulesSdkTypes.IMedusaInternalService<
InferEntityType<typeof OrderChange>
>
protected orderChangeActionService_: ModulesSdkTypes.IMedusaInternalService<
InferEntityType<typeof OrderChangeAction>
>
protected orderItemService_: ModulesSdkTypes.IMedusaInternalService<
InferEntityType<typeof OrderItem>
>
protected orderSummaryService_: ModulesSdkTypes.IMedusaInternalService<
InferEntityType<typeof OrderSummary>
>
protected orderShippingService_: ModulesSdkTypes.IMedusaInternalService<
InferEntityType<typeof OrderShipping>
>
protected returnReasonService_: ModulesSdkTypes.IMedusaInternalService<
InferEntityType<typeof ReturnReason>
>
protected returnService_: ModulesSdkTypes.IMedusaInternalService<
InferEntityType<typeof Return>
>
protected returnItemService_: ModulesSdkTypes.IMedusaInternalService<
InferEntityType<typeof ReturnItem>
>
protected orderClaimService_: ModulesSdkTypes.IMedusaInternalService<
InferEntityType<typeof OrderClaim>
>
protected orderClaimItemService_: ModulesSdkTypes.IMedusaInternalService<
InferEntityType<typeof OrderClaimItem>
>
protected orderClaimItemImageService_: ModulesSdkTypes.IMedusaInternalService<
InferEntityType<typeof OrderClaimItemImage>
>
protected orderExchangeService_: ModulesSdkTypes.IMedusaInternalService<
InferEntityType<typeof OrderExchange>
>
protected orderExchangeItemService_: ModulesSdkTypes.IMedusaInternalService<
InferEntityType<typeof OrderExchangeItem>
>
constructor(
{
@@ -640,9 +709,11 @@ export default class OrderModuleService<
data: OrderTypes.CreateOrderDTO[],
@MedusaContext() sharedContext: Context = {}
) {
await this.createOrderAddresses_(data, sharedContext)
const lineItemsToCreate: CreateOrderLineItemDTO[] = []
const createdOrders: Order[] = []
const createdOrders: InferEntityType<typeof Order>[] = []
for (const { items, shipping_methods, ...order } of data) {
const ord = order as any
@@ -693,6 +764,52 @@ export default class OrderModuleService<
return createdOrders
}
@InjectTransactionManager()
protected async createOrderAddresses_(
input: OrderTypes.CreateOrderDTO[],
@MedusaContext() sharedContext: Context = {}
) {
const allAddresses: {
data: any
type: "billing" | "shipping"
source: OrderTypes.CreateOrderDTO
}[] = []
input.forEach((inputData) => {
if (inputData.billing_address) {
allAddresses.push({
data: inputData.billing_address,
type: "billing",
source: inputData,
})
}
if (inputData.shipping_address) {
allAddresses.push({
data: inputData.shipping_address,
type: "shipping",
source: inputData,
})
}
})
const createdAddresses = allAddresses.length
? await this.orderAddressService_.create(
allAddresses.map((a) => a.data),
sharedContext
)
: []
createdAddresses.forEach((createdAddress, index) => {
const { type, source } = allAddresses[index]
if (type === "billing") {
source.billing_address_id = createdAddress.id
} else if (type === "shipping") {
source.shipping_address_id = createdAddress.id
}
})
}
// @ts-expect-error
async updateOrders(
data: OrderTypes.UpdateOrderDTO[]
@@ -794,7 +911,7 @@ export default class OrderModuleService<
| OrderTypes.CreateOrderLineItemDTO,
@MedusaContext() sharedContext: Context = {}
): Promise<OrderTypes.OrderLineItemDTO[]> {
let items: OrderLineItem[] = []
let items: InferEntityType<typeof OrderLineItem>[] = []
if (isString(orderIdOrData)) {
items = await this.createOrderLineItems_(
orderIdOrData,
@@ -840,7 +957,7 @@ export default class OrderModuleService<
orderId: string,
items: OrderTypes.CreateOrderLineItemDTO[],
@MedusaContext() sharedContext: Context = {}
): Promise<OrderLineItem[]> {
): Promise<InferEntityType<typeof OrderLineItem>[]> {
const order = await this.retrieveOrder(
orderId,
{ select: ["id", "version"] },
@@ -862,7 +979,7 @@ export default class OrderModuleService<
protected async createOrderLineItemsBulk_(
data: CreateOrderLineItemDTO[],
@MedusaContext() sharedContext: Context = {}
): Promise<OrderLineItem[]> {
): Promise<InferEntityType<typeof OrderLineItem>[]> {
const orderItemToCreate: CreateOrderItemDTO[] = []
const lineItems = await this.orderLineItemService_.create(
@@ -917,7 +1034,7 @@ export default class OrderModuleService<
| Partial<OrderTypes.UpdateOrderLineItemDTO>,
@MedusaContext() sharedContext: Context = {}
): Promise<OrderTypes.OrderLineItemDTO[] | OrderTypes.OrderLineItemDTO> {
let items: OrderLineItem[] = []
let items: InferEntityType<typeof OrderLineItem>[] = []
if (isString(lineItemIdOrDataOrSelector)) {
const item = await this.updateOrderLineItem_(
lineItemIdOrDataOrSelector,
@@ -960,7 +1077,7 @@ export default class OrderModuleService<
lineItemId: string,
data: Partial<OrderTypes.UpdateOrderLineItemDTO>,
@MedusaContext() sharedContext: Context = {}
): Promise<OrderLineItem> {
): Promise<InferEntityType<typeof OrderLineItem>> {
const [item] = await this.orderLineItemService_.update(
[{ id: lineItemId, ...data }],
sharedContext
@@ -985,7 +1102,7 @@ export default class OrderModuleService<
protected async updateOrderLineItemsWithSelector_(
updates: OrderTypes.UpdateOrderLineItemWithSelectorDTO[],
@MedusaContext() sharedContext: Context = {}
): Promise<OrderLineItem[]> {
): Promise<InferEntityType<typeof OrderLineItem>[]> {
let toUpdate: UpdateOrderLineItemDTO[] = []
const detailsToUpdate: UpdateOrderItemWithSelectorDTO[] = []
for (const { selector, data } of updates) {
@@ -1039,7 +1156,7 @@ export default class OrderModuleService<
| Partial<OrderTypes.UpdateOrderItemDTO>,
@MedusaContext() sharedContext: Context = {}
): Promise<OrderTypes.OrderItemDTO[] | OrderTypes.OrderItemDTO> {
let items: OrderItem[] = []
let items: InferEntityType<typeof OrderItem>[] = []
if (isString(orderItemIdOrDataOrSelector)) {
const item = await this.updateOrderItem_(
orderItemIdOrDataOrSelector,
@@ -1079,7 +1196,7 @@ export default class OrderModuleService<
orderItemId: string,
data: Partial<OrderTypes.UpdateOrderItemDTO>,
@MedusaContext() sharedContext: Context = {}
): Promise<OrderItem> {
): Promise<InferEntityType<typeof OrderItem>> {
const [detail] = await this.orderItemService_.update(
[{ id: orderItemId, ...data }],
sharedContext
@@ -1092,7 +1209,7 @@ export default class OrderModuleService<
protected async updateOrderItemWithSelector_(
updates: OrderTypes.UpdateOrderItemWithSelectorDTO[],
@MedusaContext() sharedContext: Context = {}
): Promise<OrderItem[]> {
): Promise<InferEntityType<typeof OrderItem>[]> {
let toUpdate: UpdateOrderItemDTO[] = []
for (const { selector, data } of updates) {
const details = await this.listOrderItems(
@@ -1136,7 +1253,7 @@ export default class OrderModuleService<
): Promise<
OrderTypes.OrderShippingMethodDTO[] | OrderTypes.OrderShippingMethodDTO
> {
let methods: OrderShippingMethod[]
let methods: InferEntityType<typeof OrderShippingMethod>[]
if (isString(orderIdOrData)) {
methods = await this.createOrderShippingMethods_(
orderIdOrData,
@@ -1186,7 +1303,7 @@ export default class OrderModuleService<
orderId: string,
data: CreateOrderShippingMethodDTO[],
@MedusaContext() sharedContext: Context = {}
): Promise<OrderShippingMethod[]> {
): Promise<InferEntityType<typeof OrderShippingMethod>[]> {
const order = await this.retrieveOrder(
orderId,
{ select: ["id", "version"] },
@@ -1215,13 +1332,10 @@ export default class OrderModuleService<
version: number
}[],
@MedusaContext() sharedContext: Context = {}
): Promise<OrderShippingMethod[]> {
const sm = await this.orderShippingService_.create(
data as unknown as CreateOrderShippingMethodDTO[],
sharedContext
)
): Promise<InferEntityType<typeof OrderShippingMethod>[]> {
const sm = await this.orderShippingService_.create(data, sharedContext)
return sm.map((s) => s.shipping_method)
return sm.map((s) => s.shipping_method) as any
}
@InjectManager()
@@ -1298,7 +1412,7 @@ export default class OrderModuleService<
adjustments?: OrderTypes.CreateOrderLineItemAdjustmentDTO[],
@MedusaContext() sharedContext: Context = {}
): Promise<OrderTypes.OrderLineItemAdjustmentDTO[]> {
let addedAdjustments: OrderLineItemAdjustment[] = []
let addedAdjustments: InferEntityType<typeof OrderLineItemAdjustment>[] = []
if (isString(orderIdOrData)) {
const order = await this.retrieveOrder(
orderIdOrData,
@@ -1471,7 +1585,9 @@ export default class OrderModuleService<
| OrderTypes.OrderShippingMethodAdjustmentDTO[]
| OrderTypes.OrderShippingMethodAdjustmentDTO
> {
let addedAdjustments: OrderShippingMethodAdjustment[] = []
let addedAdjustments: InferEntityType<
typeof OrderShippingMethodAdjustment
>[] = []
if (isString(orderIdOrData)) {
const order = await this.retrieveOrder(
orderIdOrData,
@@ -1551,7 +1667,7 @@ export default class OrderModuleService<
): Promise<
OrderTypes.OrderLineItemTaxLineDTO[] | OrderTypes.OrderLineItemTaxLineDTO
> {
let addedTaxLines: OrderLineItemTaxLine[]
let addedTaxLines: InferEntityType<typeof OrderLineItemTaxLine>[]
if (isString(orderIdOrData)) {
const lines = Array.isArray(taxLines) ? taxLines : [taxLines]
@@ -1663,7 +1779,7 @@ export default class OrderModuleService<
| OrderTypes.OrderShippingMethodTaxLineDTO[]
| OrderTypes.OrderShippingMethodTaxLineDTO
> {
let addedTaxLines: OrderShippingMethodTaxLine[]
let addedTaxLines: InferEntityType<typeof OrderShippingMethodTaxLine>[]
if (isString(orderIdOrData)) {
const lines = Array.isArray(taxLines) ? taxLines : [taxLines]
@@ -1905,7 +2021,7 @@ export default class OrderModuleService<
protected async createOrderChange_(
data: CreateOrderChangeDTO | CreateOrderChangeDTO[],
@MedusaContext() sharedContext?: Context
): Promise<OrderChange[]> {
): Promise<InferEntityType<typeof OrderChange>[]> {
const dataArr = Array.isArray(data) ? data : [data]
const orderIds: string[] = []
const dataMap: Record<string, object> = {}
@@ -1955,7 +2071,7 @@ export default class OrderModuleService<
return {
...dataMap[order.id],
version: order.version + 1,
version: order.version! + 1,
} as any
})
@@ -2002,7 +2118,9 @@ export default class OrderModuleService<
quantity: item.detail?.quantity ?? item.quantity,
unit_price: item.detail?.unit_price || item.unit_price,
compare_at_unit_price:
item.detail?.compare_at_unit_price || item.compare_at_unit_price,
item.detail?.compare_at_unit_price ||
item.compare_at_unit_price ||
null,
}
}
}
@@ -2032,6 +2150,7 @@ export default class OrderModuleService<
const actions = item.actions
delete item.actions
//@ts-ignore
const newItem = itemsToUpsert.find((d) => d.item_id === item.id)!
const unitPrice = newItem?.unit_price ?? item.unit_price
const compareAtUnitPrice =
@@ -2042,7 +2161,7 @@ export default class OrderModuleService<
actions,
quantity: newItem.quantity,
unit_price: unitPrice,
compare_at_unit_price: compareAtUnitPrice,
compare_at_unit_price: compareAtUnitPrice || null,
detail: {
...newItem,
...item,
@@ -2284,9 +2403,9 @@ export default class OrderModuleService<
applied: true,
},
],
})) as CreateOrderChangeDTO[],
})),
sharedContext
)) as OrderTypes.OrderChangeDTO[]
)) as unknown as OrderTypes.OrderChangeDTO[]
return Array.isArray(data) ? changes : changes[0]
}
@@ -2338,7 +2457,7 @@ export default class OrderModuleService<
)
return await this.applyOrderChanges_(
changes as ApplyOrderChangeDTO[],
changes as unknown as ApplyOrderChangeDTO[],
sharedContext
)
}
@@ -2745,6 +2864,7 @@ export default class OrderModuleService<
data: OrderTypes.CreateOrderChangeActionDTO[],
sharedContext?: Context
): Promise<OrderTypes.OrderChangeActionDTO[]>
@InjectTransactionManager()
async addOrderAction(
data:
@@ -2786,7 +2906,8 @@ export default class OrderModuleService<
const actions = (await this.orderChangeActionService_.create(
dataArr,
sharedContext
)) as OrderTypes.OrderChangeActionDTO[]
)) as unknown as OrderTypes.OrderChangeActionDTO[]
return Array.isArray(data) ? actions : actions[0]
}
@@ -2836,10 +2957,10 @@ export default class OrderModuleService<
"items.detail",
"shipping_methods",
],
}
// sharedContext
// TODO: investigate issue while using sharedContext in receive return action
},
sharedContext
)
orders = formatOrder(orders, {
entity: Order,
}) as OrderDTO[]
@@ -2922,10 +3043,10 @@ export default class OrderModuleService<
}
}
const created = await this.orderTransactionService_.create(
const created = (await this.orderTransactionService_.create(
data,
sharedContext
)
)) as (InferEntityType<typeof OrderTransaction> & { order_id: string })[]
await this.updateOrderPaidRefundableAmount_(created, false, sharedContext)
@@ -3281,6 +3402,7 @@ export default class OrderModuleService<
return await this.retrieveReturn(ret.id, {
relations: [
"items",
"items.item",
"shipping_methods",
"shipping_methods.tax_lines",
"shipping_methods.adjustments",
@@ -3390,7 +3512,7 @@ export default class OrderModuleService<
): Promise<OrderTypes.OrderExchangeDTO> {
const ret = await this.createExchange_(data, sharedContext)
const claim = await this.retrieveOrderExchange(
const exchange = await this.retrieveOrderExchange(
ret.id,
{
relations: [
@@ -3408,7 +3530,7 @@ export default class OrderModuleService<
)
return await this.baseRepository_.serialize<OrderTypes.OrderExchangeDTO>(
claim,
exchange,
{
populate: true,
}
@@ -2,6 +2,7 @@ import {
Context,
DAL,
FindConfig,
InferEntityType,
OrderTypes,
RepositoryService,
} from "@medusajs/framework/types"
@@ -19,9 +20,11 @@ type InjectedDependencies = {
export default class OrderService extends ModulesSdkUtils.MedusaInternalService<
InjectedDependencies,
Order
InferEntityType<typeof Order>
>(Order) {
protected readonly orderRepository_: RepositoryService<Order>
protected readonly orderRepository_: RepositoryService<
InferEntityType<typeof Order>
>
constructor(container: InjectedDependencies) {
// @ts-ignore
@@ -35,10 +38,10 @@ export default class OrderService extends ModulesSdkUtils.MedusaInternalService<
version: number,
config: FindConfig<TEntityMethod> = {},
@MedusaContext() sharedContext: Context = {}
): Promise<Order> {
const queryConfig = ModulesSdkUtils.buildQuery<Order>(
): Promise<typeof Order> {
const queryConfig = ModulesSdkUtils.buildQuery<typeof Order>(
{ id, items: { version } },
{ ...config, take: 1 }
{ ...config, take: 1 } as any
)
const [result] = await this.orderRepository_.find(
queryConfig,
@@ -1,4 +1,7 @@
import { OrderChangeActionDTO } from "@medusajs/framework/types"
import {
InferEntityType,
OrderChangeActionDTO,
} from "@medusajs/framework/types"
import {
ChangeActionType,
MathBN,
@@ -22,8 +25,9 @@ export function applyChangesToOrder(
addActionReferenceToObject?: boolean
}
) {
const itemsToUpsert: OrderItem[] = []
const shippingMethodsToUpsert: OrderShippingMethod[] = []
const itemsToUpsert: InferEntityType<typeof OrderItem>[] = []
const shippingMethodsToUpsert: InferEntityType<typeof OrderShippingMethod>[] =
[]
const summariesToUpsert: any[] = []
const orderToUpdate: any[] = []
@@ -69,7 +73,7 @@ export function applyChangesToOrder(
const orderItem = isExistingItem ? (item.detail as any) : item
const itemId = isExistingItem ? orderItem.item_id : item.id
itemsToUpsert.push({
const itemToUpsert = {
id: orderItem.version === version ? orderItem.id : undefined,
item_id: itemId,
order_id: order.id,
@@ -86,7 +90,9 @@ export function applyChangesToOrder(
return_dismissed_quantity: orderItem.return_dismissed_quantity ?? 0,
written_off_quantity: orderItem.written_off_quantity ?? 0,
metadata: orderItem.metadata,
} as OrderItem)
} as any
itemsToUpsert.push(itemToUpsert)
}
const orderSummary = order.summary as any
@@ -1,4 +1,5 @@
import { Constructor, Context, DAL } from "@medusajs/framework/types"
import { toMikroORMEntity } from "@medusajs/framework/utils"
import { LoadStrategy } from "@mikro-orm/core"
import { Order, OrderClaim } from "@models"
import { mapRepositoryToOrderModel } from "."
@@ -15,7 +16,6 @@ export function setFindMethods<T>(klass: Constructor<T>, entity: any) {
const findOptions_ = { ...options } as any
findOptions_.options ??= {}
findOptions_.where ??= {}
findOptions_.populate ??= []
if (!("strategy" in findOptions_.options)) {
if (findOptions_.options.limit != null || findOptions_.options.offset) {
@@ -29,12 +29,13 @@ export function setFindMethods<T>(klass: Constructor<T>, entity: any) {
}
}
const isRelatedEntity = entity !== Order
const isRelatedEntity = entity.name !== Order.name
const config = mapRepositoryToOrderModel(findOptions_, isRelatedEntity)
config.options ??= {}
config.options.populate ??= []
const strategy = config.options.strategy ?? LoadStrategy.JOINED
const strategy = findOptions_.options.strategy ?? LoadStrategy.JOINED
let orderAlias = "o0"
if (isRelatedEntity) {
if (entity === OrderClaim) {
@@ -65,7 +66,7 @@ export function setFindMethods<T>(klass: Constructor<T>, entity: any) {
if (strategy === LoadStrategy.SELECT_IN) {
const sql = manager
.qb(Order, "_sub0")
.qb(toMikroORMEntity(Order), "_sub0")
.select("version")
.where({ id: knex.raw(`"${orderAlias}"."order_id"`) })
.getKnexQuery()
@@ -74,46 +75,18 @@ export function setFindMethods<T>(klass: Constructor<T>, entity: any) {
defaultVersion = knex.raw(`(${sql})`)
}
const version = config.where.version ?? defaultVersion
const version = config.where?.version ?? defaultVersion
delete config.where?.version
config.options.populateWhere ??= {}
const popWhere = config.options.populateWhere
if (isRelatedEntity) {
popWhere.order ??= {}
popWhere.shipping_methods ??= {}
popWhere.shipping_methods.deleted_at ??= null
popWhere.shipping_methods.shipping_method ??= {}
popWhere.shipping_methods.shipping_method.deleted_at ??= null
}
const orderWhere = isRelatedEntity ? popWhere.order : popWhere
orderWhere.summary ??= {}
orderWhere.summary.version = version
orderWhere.items ??= {}
orderWhere.items.version = version
orderWhere.items.deleted_at ??= null
orderWhere.shipping_methods ??= {}
orderWhere.shipping_methods.version = version
orderWhere.shipping_methods.deleted_at ??= null
orderWhere.shipping_methods.shipping_method ??= {}
orderWhere.shipping_methods.shipping_method.deleted_at ??= null
configurePopulateWhere(config, isRelatedEntity, version)
if (!config.options.orderBy) {
config.options.orderBy = { id: "ASC" }
}
config.where ??= {}
config.where.deleted_at ??= null
return await manager.find(entity, config.where, config.options)
return await manager.find(this.entity, config.where, config.options)
}
klass.prototype.findAndCount = async function findAndCount(
@@ -134,7 +107,8 @@ export function setFindMethods<T>(klass: Constructor<T>, entity: any) {
})
}
const isRelatedEntity = entity !== Order
const isRelatedEntity = entity.name !== Order.name
const config = mapRepositoryToOrderModel(findOptions_, isRelatedEntity)
let orderAlias = "o0"
@@ -148,7 +122,6 @@ export function setFindMethods<T>(klass: Constructor<T>, entity: any) {
}
}
// first relation is always order if the entity is not Order
const index = config.options.populate.findIndex((p) => p === "order")
if (index > -1) {
config.options.populate.splice(index, 1)
@@ -161,43 +134,107 @@ export function setFindMethods<T>(klass: Constructor<T>, entity: any) {
let defaultVersion = knex.raw(`"${orderAlias}"."version"`)
const strategy = config.options.strategy ?? LoadStrategy.JOINED
if (strategy === LoadStrategy.SELECT_IN) {
const sql = manager
.qb(Order, "_sub0")
.select("version")
.where({ id: knex.raw(`"${orderAlias}"."order_id"`) })
.getKnexQuery()
.toString()
defaultVersion = knex.raw(`(${sql})`)
defaultVersion = getVersionSubQuery(manager, orderAlias)
}
const version = config.where.version ?? defaultVersion
delete config.where.version
config.options.populateWhere ??= {}
const popWhere = config.options.populateWhere
if (isRelatedEntity) {
popWhere.order ??= {}
}
const orderWhere = isRelatedEntity ? popWhere.order : popWhere
orderWhere.summary ??= {}
orderWhere.summary.version = version
orderWhere.items ??= {}
orderWhere.items.version = version
orderWhere.items.deleted_at ??= null
popWhere.shipping_methods ??= {}
popWhere.shipping_methods.version = version
popWhere.shipping_methods.deleted_at ??= null
configurePopulateWhere(
config,
isRelatedEntity,
version,
strategy === LoadStrategy.SELECT_IN,
manager
)
if (!config.options.orderBy) {
config.options.orderBy = { id: "ASC" }
}
return await manager.findAndCount(entity, config.where, config.options)
return await manager.findAndCount(this.entity, config.where, config.options)
}
}
function getVersionSubQuery(manager, alias, field = "order_id") {
const knex = manager.getKnex()
const sql = manager
.qb(toMikroORMEntity(Order), "_sub0")
.select("version")
.where({ id: knex.raw(`"${alias}"."${field}"`) })
.getKnexQuery()
.toString()
return knex.raw(`(${sql})`)
}
function configurePopulateWhere(
config: any,
isRelatedEntity: boolean,
version: any,
isSelectIn = false,
manager?
) {
const requestedPopulate = config.options?.populate ?? []
const hasRelation = (relation: string) =>
requestedPopulate.some(
(p) => p === relation || p.startsWith(`${relation}.`)
)
config.options.populateWhere ??= {}
const popWhere = config.options.populateWhere
// isSelectIn && isRelatedEntity - Order is always the FROM clause (field o0.id)
if (isRelatedEntity) {
popWhere.order ??= {}
const popWhereOrder = popWhere.order
popWhereOrder.version = isSelectIn
? getVersionSubQuery(manager, "o0", "id")
: version
// related entity shipping method
if (hasRelation("shipping_methods")) {
popWhere.shipping_methods ??= {}
popWhere.shipping_methods.version = isSelectIn
? getVersionSubQuery(manager, "s0")
: version
}
if (hasRelation("items") || hasRelation("order.items")) {
popWhereOrder.items ??= {}
popWhereOrder.items.version = isSelectIn
? getVersionSubQuery(manager, "o0", "id")
: version
}
if (hasRelation("shipping_methods")) {
popWhereOrder.shipping_methods ??= {}
popWhereOrder.shipping_methods.version = isSelectIn
? getVersionSubQuery(manager, "o0", "id")
: version
}
return
}
if (isSelectIn) {
version = getVersionSubQuery(manager, "o0")
}
if (hasRelation("summary")) {
popWhere.summary ??= {}
popWhere.summary.version = version
}
if (hasRelation("items") || hasRelation("order.items")) {
popWhere.items ??= {}
popWhere.items.version = version
}
if (hasRelation("shipping_methods")) {
popWhere.shipping_methods ??= {}
popWhere.shipping_methods.version = version
}
}
@@ -4,6 +4,7 @@ import {
deduplicate,
isDefined,
isObject,
toMikroORMEntity,
} from "@medusajs/framework/utils"
// Reshape the order object to match the OrderDTO
@@ -20,8 +21,9 @@ export function formatOrder<T = any>(
orders.map((order) => {
let mainOrder = order
const entity = options?.entity ? toMikroORMEntity(options.entity) : null
const isRelatedEntity = options?.entity?.name !== "Order"
const isRelatedEntity = entity?.name !== "Order"
// If the entity is a related entity, the original order is located in the order property
if (isRelatedEntity) {