chore(payment): Payment module DML (#10553)

* chore(payment): Payment module DML

* rm log

* migration
This commit is contained in:
Carlos R. L. Rodrigues authored and GitHub committed 2024-12-11 13:09:10 -03:00
1 parent 91cd9aad47
commit 0264294ab5
14 files changed
+703 -1036

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
"@medusajs/payment": patch
---
Payment module DML
@@ -1,5 +1,5 @@
import { ClaimType } from "@medusajs/utils"
import { medusaIntegrationTestRunner } from "@medusajs/test-utils" import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
import { ClaimType } from "@medusajs/utils"
import { import {
adminHeaders, adminHeaders,
createAdminUser, createAdminUser,
@@ -1,7 +1,7 @@
import { IPaymentModuleService } from "@medusajs/framework/types" import { IPaymentModuleService } from "@medusajs/framework/types"
import { Module, Modules, promiseAll } from "@medusajs/framework/utils" import { Module, Modules, promiseAll } from "@medusajs/framework/utils"
import { PaymentModuleService } from "@services"
import { moduleIntegrationTestRunner } from "@medusajs/test-utils" import { moduleIntegrationTestRunner } from "@medusajs/test-utils"
import { PaymentModuleService } from "@services"
import { import {
createPaymentCollections, createPaymentCollections,
createPayments, createPayments,
@@ -24,10 +24,9 @@ moduleIntegrationTestRunner<IPaymentModuleService>({
}).linkable }).linkable
expect(Object.keys(linkable)).toEqual([ expect(Object.keys(linkable)).toEqual([
"payment",
"paymentCollection", "paymentCollection",
"paymentProvider",
"paymentSession", "paymentSession",
"payment",
"refundReason", "refundReason",
]) ])
@@ -54,15 +53,6 @@ moduleIntegrationTestRunner<IPaymentModuleService>({
field: "paymentCollection", field: "paymentCollection",
}, },
}, },
paymentProvider: {
id: {
linkable: "payment_provider_id",
entity: "PaymentProvider",
primaryKey: "id",
serviceName: "payment",
field: "paymentProvider",
},
},
paymentSession: { paymentSession: {
id: { id: {
field: "paymentSession", field: "paymentSession",
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,45 @@
import { Migration } from '@mikro-orm/migrations';
export class Migration20241211151053 extends Migration {
async up(): Promise<void> {
this.addSql('alter table if exists "payment_session" drop constraint if exists "payment_session_payment_collection_id_foreign";');
this.addSql('alter table if exists "payment" drop constraint if exists "payment_payment_collection_id_foreign";');
this.addSql('alter table if exists "payment_provider" add column if not exists "created_at" timestamptz not null default now(), add column if not exists "updated_at" timestamptz not null default now(), add column if not exists "deleted_at" timestamptz null;');
this.addSql('CREATE INDEX IF NOT EXISTS "IDX_payment_provider_deleted_at" ON "payment_provider" (deleted_at) WHERE deleted_at IS NULL;');
this.addSql('alter table if exists "payment_session" alter column "data" type jsonb using ("data"::jsonb);');
this.addSql('alter table if exists "payment_session" alter column "data" set default \'{}\';');
this.addSql('alter table if exists "payment_session" add constraint "payment_session_payment_collection_id_foreign" foreign key ("payment_collection_id") references "payment_collection" ("id") on update cascade on delete cascade;');
this.addSql('alter table if exists "payment" add constraint "payment_payment_collection_id_foreign" foreign key ("payment_collection_id") references "payment_collection" ("id") on update cascade on delete cascade;');
this.addSql('CREATE INDEX IF NOT EXISTS "IDX_refund_reason_deleted_at" ON "refund_reason" (deleted_at) WHERE deleted_at IS NULL;');
this.addSql('CREATE INDEX IF NOT EXISTS "IDX_refund_refund_reason_id" ON "refund" (refund_reason_id) WHERE deleted_at IS NULL;');
}
async down(): Promise<void> {
this.addSql('alter table if exists "payment_session" drop constraint if exists "payment_session_payment_collection_id_foreign";');
this.addSql('alter table if exists "payment" drop constraint if exists "payment_payment_collection_id_foreign";');
this.addSql('drop index if exists "IDX_payment_provider_deleted_at";');
this.addSql('alter table if exists "payment_provider" drop column if exists "created_at";');
this.addSql('alter table if exists "payment_provider" drop column if exists "updated_at";');
this.addSql('alter table if exists "payment_provider" drop column if exists "deleted_at";');
this.addSql('alter table if exists "payment_session" alter column "data" drop default;');
this.addSql('alter table if exists "payment_session" alter column "data" type jsonb using ("data"::jsonb);');
this.addSql('alter table if exists "payment_session" add constraint "payment_session_payment_collection_id_foreign" foreign key ("payment_collection_id") references "payment_collection" ("id") on update cascade;');
this.addSql('alter table if exists "payment" add constraint "payment_payment_collection_id_foreign" foreign key ("payment_collection_id") references "payment_collection" ("id") on update cascade;');
this.addSql('drop index if exists "IDX_refund_reason_deleted_at";');
this.addSql('drop index if exists "IDX_refund_refund_reason_id";');
}
}
+17 -73
View File
@@ -1,77 +1,21 @@
import { BigNumberRawValue } from "@medusajs/framework/types" import { model } from "@medusajs/framework/utils"
import {
BigNumber,
MikroOrmBigNumberProperty,
generateEntityId,
} from "@medusajs/framework/utils"
import {
BeforeCreate,
Entity,
ManyToOne,
OnInit,
OptionalProps,
PrimaryKey,
Property,
} from "@mikro-orm/core"
import Payment from "./payment" import Payment from "./payment"
type OptionalCaptureProps = "created_at" const Capture = model
.define("Capture", {
@Entity({ tableName: "capture" }) id: model.id({ prefix: "capt" }).primaryKey(),
export default class Capture { amount: model.bigNumber(),
[OptionalProps]?: OptionalCaptureProps payment: model.belongsTo(() => Payment, {
mappedBy: "captures",
@PrimaryKey({ columnType: "text" }) }),
id: string metadata: model.json().nullable(),
created_by: model.text().nullable(),
@MikroOrmBigNumberProperty()
amount: BigNumber | number
@Property({ columnType: "jsonb" })
raw_amount: BigNumberRawValue
@ManyToOne(() => Payment, {
onDelete: "cascade",
index: "IDX_capture_payment_id",
fieldName: "payment_id",
}) })
payment!: Payment .indexes([
{
name: "IDX_capture_payment_id",
on: ["payment_id"],
},
])
@Property({ columnType: "jsonb", nullable: true }) export default Capture
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,
index: "IDX_capture_deleted_at",
})
deleted_at: Date | null = null
@Property({ columnType: "text", nullable: true })
created_by: string | null = null
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "capt")
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "capt")
}
}
@@ -1,127 +1,40 @@
import { BigNumberRawValue, DAL } from "@medusajs/framework/types" import { model, PaymentCollectionStatus } from "@medusajs/framework/utils"
import {
BigNumber,
DALUtils,
MikroOrmBigNumberProperty,
PaymentCollectionStatus,
generateEntityId,
} from "@medusajs/framework/utils"
import {
BeforeCreate,
Cascade,
Collection,
Entity,
Enum,
Filter,
ManyToMany,
OnInit,
OneToMany,
OptionalProps,
PrimaryKey,
Property,
Rel,
} from "@mikro-orm/core"
import Payment from "./payment" import Payment from "./payment"
import PaymentProvider from "./payment-provider" import PaymentProvider from "./payment-provider"
import PaymentSession from "./payment-session" import PaymentSession from "./payment-session"
type OptionalPaymentCollectionProps = "status" | DAL.ModelDateColumns const PaymentCollection = model
.define("PaymentCollection", {
@Entity({ tableName: "payment_collection" }) id: model.id({ prefix: "pay_col" }).primaryKey(),
@Filter(DALUtils.mikroOrmSoftDeletableFilterOptions) currency_code: model.text(),
export default class PaymentCollection { amount: model.bigNumber(),
[OptionalProps]?: OptionalPaymentCollectionProps authorized_amount: model.bigNumber().nullable(),
captured_amount: model.bigNumber().nullable(),
@PrimaryKey({ columnType: "text" }) refunded_amount: model.bigNumber().nullable(),
id: string region_id: model.text(),
completed_at: model.dateTime().nullable(),
@Property({ columnType: "text" }) status: model
currency_code: string .enum(PaymentCollectionStatus)
.default(PaymentCollectionStatus.NOT_PAID),
@MikroOrmBigNumberProperty() metadata: model.json().nullable(),
amount: BigNumber | number payment_providers: model.manyToMany(() => PaymentProvider, {
mappedBy: "payment_collections",
@Property({ columnType: "jsonb" }) }),
raw_amount: BigNumberRawValue payment_sessions: model.hasMany(() => PaymentSession, {
mappedBy: "payment_collection",
@MikroOrmBigNumberProperty({ nullable: true }) }),
authorized_amount: BigNumber | number | null = null payments: model.hasMany(() => Payment, {
mappedBy: "payment_collection",
@Property({ columnType: "jsonb", nullable: true }) }),
raw_authorized_amount: BigNumberRawValue | null = null
@MikroOrmBigNumberProperty({ nullable: true })
captured_amount: BigNumber | number | null = null
@Property({ columnType: "jsonb", nullable: true })
raw_captured_amount: BigNumberRawValue | null = null
@MikroOrmBigNumberProperty({ nullable: true })
refunded_amount: BigNumber | number | null = null
@Property({ columnType: "jsonb", nullable: true })
raw_refunded_amount: BigNumberRawValue | null = null
@Property({ columnType: "text", index: "IDX_payment_collection_region_id" })
region_id: string
@Property({
onCreate: () => new Date(),
columnType: "timestamptz",
defaultRaw: "now()",
}) })
created_at: Date .cascades({
delete: ["payment_sessions", "payments"],
@Property({
onCreate: () => new Date(),
onUpdate: () => new Date(),
columnType: "timestamptz",
defaultRaw: "now()",
}) })
updated_at: Date .indexes([
{
name: "IDX_payment_collection_region_id",
on: ["region_id"],
},
])
@Property({ export default PaymentCollection
columnType: "timestamptz",
nullable: true,
index: "IDX_payment_collection_deleted_at",
})
deleted_at: Date | null = null
@Property({
columnType: "timestamptz",
nullable: true,
})
completed_at: Date | null = null
@Enum({
items: () => PaymentCollectionStatus,
default: PaymentCollectionStatus.NOT_PAID,
})
status: PaymentCollectionStatus = PaymentCollectionStatus.NOT_PAID
@ManyToMany(() => PaymentProvider)
payment_providers = new Collection<Rel<PaymentProvider>>(this)
@OneToMany(() => PaymentSession, (ps) => ps.payment_collection, {
cascade: [Cascade.PERSIST] as any,
})
payment_sessions = new Collection<Rel<PaymentSession>>(this)
@OneToMany(() => Payment, (payment) => payment.payment_collection, {
cascade: [Cascade.PERSIST] as any,
})
payments = new Collection<Rel<Payment>>(this)
@Property({ columnType: "jsonb", nullable: true })
metadata: Record<string, unknown> | null = null
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "pay_col")
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "pay_col")
}
}
@@ -1,64 +1,13 @@
import { generateEntityId } from "@medusajs/framework/utils" import { model } from "@medusajs/framework/utils"
import {
BeforeCreate,
Entity,
OnInit,
PrimaryKey,
Property,
} from "@mikro-orm/core"
@Entity({ tableName: "payment_method_token" }) const PaymentMethodToken = model.define("PaymentMethodToken", {
export default class PaymentMethodToken { id: model.id({ prefix: "paymttok" }).primaryKey(),
@PrimaryKey({ columnType: "text" }) provider_id: model.text(),
id: string data: model.json().nullable(),
name: model.text(),
type_detail: model.text().nullable(),
description_detail: model.text().nullable(),
metadata: model.json().nullable(),
})
@Property({ columnType: "text" }) export default PaymentMethodToken
provider_id: string
@Property({ columnType: "jsonb", nullable: true })
data: Record<string, unknown> | null = null
@Property({ columnType: "text" })
name: string
@Property({ columnType: "text", nullable: true })
type_detail: string | null = null
@Property({ columnType: "text", nullable: true })
description_detail: 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,
index: "IDX_payment_method_token_deleted_at",
})
deleted_at: Date | null = null
@Property({ columnType: "jsonb", nullable: true })
metadata: Record<string, unknown> | null = null
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "paymttok")
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "paymttok")
}
}
@@ -1,15 +1,12 @@
import { Entity, OptionalProps, PrimaryKey, Property } from "@mikro-orm/core" import { model } from "@medusajs/framework/utils"
import PaymentCollection from "./payment-collection"
@Entity({ tableName: "payment_provider" }) const PaymentProvider = model.define("PaymentProvider", {
export default class PaymentProvider { id: model.id().primaryKey(),
[OptionalProps]?: "is_enabled" is_enabled: model.boolean().default(true),
payment_collections: model.manyToMany(() => PaymentCollection, {
mappedBy: "payment_providers",
}),
})
@PrimaryKey({ columnType: "text" }) export default PaymentProvider
id: string
@Property({
default: true,
columnType: "boolean",
})
is_enabled: boolean = true
}
@@ -1,120 +1,37 @@
import { BigNumberRawValue } from "@medusajs/framework/types" import { model, PaymentSessionStatus } from "@medusajs/framework/utils"
import {
BigNumber,
generateEntityId,
MikroOrmBigNumberProperty,
PaymentSessionStatus,
} from "@medusajs/framework/utils"
import {
BeforeCreate,
Entity,
Enum,
ManyToOne,
OneToOne,
OnInit,
OptionalProps,
PrimaryKey,
Property,
Rel,
} from "@mikro-orm/core"
import Payment from "./payment" import Payment from "./payment"
import PaymentCollection from "./payment-collection" import PaymentCollection from "./payment-collection"
@Entity({ tableName: "payment_session" }) const PaymentSession = model
export default class PaymentSession { .define("PaymentSession", {
[OptionalProps]?: "status" | "data" id: model.id({ prefix: "payses" }).primaryKey(),
currency_code: model.text(),
@PrimaryKey({ columnType: "text" }) amount: model.bigNumber(),
id: string provider_id: model.text(),
data: model.json().default({}),
@Property({ columnType: "text" }) context: model.json().nullable(),
currency_code: string status: model
.enum(PaymentSessionStatus)
@MikroOrmBigNumberProperty() .default(PaymentSessionStatus.PENDING),
amount: BigNumber | number authorized_at: model.dateTime().nullable(),
payment_collection: model.belongsTo<() => typeof PaymentCollection>(
@Property({ () => PaymentCollection,
columnType: "jsonb", {
}) mappedBy: "payment_sessions",
raw_amount: BigNumberRawValue }
),
@Property({ columnType: "text" }) payment: model
provider_id: string .hasOne(() => Payment, {
@Property({ columnType: "jsonb" })
data: Record<string, unknown> = {}
@Property({ columnType: "jsonb", nullable: true })
context: Record<string, unknown> | null
@Enum({
items: () => PaymentSessionStatus,
})
status: PaymentSessionStatus = PaymentSessionStatus.PENDING
@Property({
columnType: "timestamptz",
nullable: true,
})
authorized_at: Date | null = null
@ManyToOne(() => PaymentCollection, {
persist: false,
})
payment_collection: Rel<PaymentCollection>
@ManyToOne({
entity: () => PaymentCollection,
columnType: "text",
index: "IDX_payment_session_payment_collection_id",
fieldName: "payment_collection_id",
mapToPk: true,
})
payment_collection_id: string
@OneToOne({
entity: () => Payment,
nullable: true,
mappedBy: "payment_session", mappedBy: "payment_session",
}) })
payment?: Rel<Payment> | null .nullable(),
metadata: model.json().nullable(),
@Property({ columnType: "jsonb", nullable: true })
metadata: Record<string, unknown> | null = null
@Property({
onCreate: () => new Date(),
columnType: "timestamptz",
defaultRaw: "now()",
}) })
created_at: Date .indexes([
{
name: "IDX_payment_session_payment_collection_id",
on: ["payment_collection_id"],
},
])
@Property({ export default PaymentSession
onCreate: () => new Date(),
onUpdate: () => new Date(),
columnType: "timestamptz",
defaultRaw: "now()",
})
updated_at: Date
@Property({
columnType: "timestamptz",
nullable: true,
index: "IDX_payment_session_deleted_at",
})
deleted_at: Date | null = null
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "payses")
this.payment_collection_id ??=
this.payment_collection_id ?? this.payment_collection?.id
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "payses")
this.payment_collection_id ??=
this.payment_collection_id ?? this.payment_collection?.id
}
}
+43 -149
View File
@@ -1,157 +1,51 @@
import { BigNumberRawValue, DAL } from "@medusajs/framework/types" import { model } from "@medusajs/framework/utils"
import {
BigNumber,
DALUtils,
MikroOrmBigNumberProperty,
Searchable,
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 Capture from "./capture" import Capture from "./capture"
import PaymentCollection from "./payment-collection" import PaymentCollection from "./payment-collection"
import PaymentSession from "./payment-session" import PaymentSession from "./payment-session"
import Refund from "./refund" import Refund from "./refund"
type OptionalPaymentProps = DAL.ModelDateColumns const Payment = model
.define("Payment", {
const tableName = "payment" id: model.id({ prefix: "pay" }).primaryKey(),
const ProviderIdIndex = createPsqlIndexStatementHelper({ amount: model.bigNumber(),
tableName, currency_code: model.text(),
columns: "provider_id", provider_id: model.text(),
}) cart_id: model.text().searchable().nullable(),
order_id: model.text().searchable().nullable(),
@Entity({ tableName }) customer_id: model.text().searchable().nullable(),
@Filter(DALUtils.mikroOrmSoftDeletableFilterOptions) data: model.json().nullable(),
export default class Payment { metadata: model.json().nullable(),
[OptionalProps]?: OptionalPaymentProps captured_at: model.dateTime().nullable(),
canceled_at: model.dateTime().nullable(),
@PrimaryKey({ columnType: "text" }) payment_collection: model.belongsTo(() => PaymentCollection, {
id: string mappedBy: "payments",
}),
@MikroOrmBigNumberProperty() payment_session: model.belongsTo(() => PaymentSession, {
amount: BigNumber | number mappedBy: "payment",
}),
@Property({ columnType: "jsonb" }) refunds: model.hasMany(() => Refund, {
raw_amount: BigNumberRawValue mappedBy: "payment",
}),
@Property({ columnType: "text" }) captures: model.hasMany(() => Capture, {
currency_code: string mappedBy: "payment",
}),
@Property({ columnType: "text" })
@ProviderIdIndex.MikroORMIndex()
provider_id: string
@Searchable()
@Property({ columnType: "text", nullable: true })
cart_id: string | null = null
@Searchable()
@Property({ columnType: "text", nullable: true })
order_id: string | null = null
@Searchable()
@Property({ columnType: "text", nullable: true })
customer_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
@Property({
onCreate: () => new Date(),
columnType: "timestamptz",
defaultRaw: "now()",
}) })
created_at: Date .cascades({
delete: ["refunds", "captures"],
@Property({
onCreate: () => new Date(),
onUpdate: () => new Date(),
columnType: "timestamptz",
defaultRaw: "now()",
}) })
updated_at: Date .indexes([
{
name: "IDX_payment_provider_id",
on: ["provider_id"],
},
{
name: "IDX_payment_payment_collection_id",
on: ["payment_collection_id"],
},
{
name: "IDX_payment_payment_session_id",
on: ["payment_session_id"],
},
])
@Property({ export default Payment
columnType: "timestamptz",
nullable: true,
index: "IDX_payment_deleted_at",
})
deleted_at: Date | null = null
@Property({
columnType: "timestamptz",
nullable: true,
})
captured_at: Date | null = null
@Property({
columnType: "timestamptz",
nullable: true,
})
canceled_at: Date | null = null
@OneToMany(() => Refund, (refund) => refund.payment, {
cascade: [Cascade.REMOVE],
})
refunds = new Collection<Rel<Refund>>(this)
@OneToMany(() => Capture, (capture) => capture.payment, {
cascade: [Cascade.REMOVE],
})
captures = new Collection<Rel<Capture>>(this)
@ManyToOne({
entity: () => PaymentCollection,
persist: false,
})
payment_collection: Rel<PaymentCollection>
@ManyToOne({
entity: () => PaymentCollection,
columnType: "text",
index: "IDX_payment_payment_collection_id",
fieldName: "payment_collection_id",
mapToPk: true,
})
payment_collection_id: string
@OneToOne({
entity: () => PaymentSession,
owner: true,
fieldName: "payment_session_id",
index: "IDX_payment_payment_session_id",
})
payment_session: Rel<PaymentSession>
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "pay")
this.payment_collection_id ??=
this.payment_collection_id ?? this.payment_collection?.id
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "pay")
this.payment_collection_id ??=
this.payment_collection_id ?? this.payment_collection?.id
}
}
@@ -1,58 +1,14 @@
import { import { model } from "@medusajs/framework/utils"
DALUtils, import Refund from "./refund"
generateEntityId,
Searchable,
} from "@medusajs/framework/utils"
import {
BeforeCreate,
Entity,
Filter,
OnInit,
PrimaryKey,
Property,
} from "@mikro-orm/core"
@Entity({ tableName: "refund_reason" }) const RefundReason = model.define("RefundReason", {
@Filter(DALUtils.mikroOrmSoftDeletableFilterOptions) id: model.id({ prefix: "refr" }).primaryKey(),
export default class RefundReason { label: model.text().searchable(),
@PrimaryKey({ columnType: "text" }) description: model.text().nullable(),
id: string metadata: model.json().nullable(),
refunds: model.hasMany(() => Refund, {
mappedBy: "refund_reason",
}),
})
@Searchable() export default RefundReason
@Property({ columnType: "text" })
label: string
@Property({ columnType: "text", nullable: true })
description: 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 })
deleted_at: Date | null = null
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "refr")
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "refr")
}
}
+22 -95
View File
@@ -1,101 +1,28 @@
import { BigNumberRawValue, DAL } from "@medusajs/framework/types" import { model } from "@medusajs/framework/utils"
import {
BigNumber,
MikroOrmBigNumberProperty,
generateEntityId,
} from "@medusajs/framework/utils"
import {
BeforeCreate,
Entity,
ManyToOne,
OnInit,
OptionalProps,
PrimaryKey,
Property,
Rel,
} from "@mikro-orm/core"
import Payment from "./payment" import Payment from "./payment"
import RefundReason from "./refund-reason" import RefundReason from "./refund-reason"
type OptionalProps = const Refund = model
| "note" .define("Refund", {
| "refund_reason_id" id: model.id({ prefix: "ref" }).primaryKey(),
| "refund_reason" amount: model.bigNumber(),
| DAL.ModelDateColumns payment: model.belongsTo(() => Payment, {
mappedBy: "refunds",
@Entity({ tableName: "refund" }) }),
export default class Refund { refund_reason: model
[OptionalProps]?: OptionalProps .belongsTo(() => RefundReason, {
mappedBy: "refunds",
@PrimaryKey({ columnType: "text" })
id: string
@MikroOrmBigNumberProperty()
amount: BigNumber | number
@Property({ columnType: "jsonb" })
raw_amount: BigNumberRawValue
@ManyToOne(() => Payment, {
onDelete: "cascade",
index: "IDX_refund_payment_id",
fieldName: "payment_id",
}) })
payment!: Rel<Payment> .nullable(),
note: model.text().nullable(),
@Property({ columnType: "text", nullable: true }) created_by: model.text().nullable(),
payment_id: string metadata: model.json().nullable(),
@ManyToOne(() => RefundReason, {
columnType: "text",
mapToPk: true,
fieldName: "refund_reason_id",
nullable: true,
}) })
refund_reason_id: string | null = null .indexes([
{
name: "IDX_refund_payment_id",
on: ["payment_id"],
},
])
@ManyToOne(() => RefundReason, { persist: false, nullable: true }) export default Refund
refund_reason: Rel<RefundReason> | null = null
@Property({ columnType: "text", nullable: true })
note: string | null = null
@Property({
onCreate: () => new Date(),
columnType: "timestamptz",
defaultRaw: "now()",
})
created_at: Date
@Property({
onCreate: () => new Date(),
columnType: "timestamptz",
defaultRaw: "now()",
})
updated_at: Date
@Property({
columnType: "timestamptz",
nullable: true,
index: "IDX_refund_deleted_at",
})
deleted_at: Date | null = null
@Property({ columnType: "text", nullable: true })
created_by: string | null = null
@Property({ columnType: "jsonb", nullable: true })
metadata: Record<string, unknown> | null = null
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "ref")
this.refund_reason_id ??= this.refund_reason?.id || null
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "ref")
this.refund_reason_id ??= this.refund_reason?.id || null
}
}
@@ -11,6 +11,7 @@ import {
FilterablePaymentProviderProps, FilterablePaymentProviderProps,
FilterablePaymentSessionProps, FilterablePaymentSessionProps,
FindConfig, FindConfig,
InferEntityType,
InternalModuleDeclaration, InternalModuleDeclaration,
IPaymentModuleService, IPaymentModuleService,
Logger, Logger,
@@ -87,11 +88,21 @@ export default class PaymentModuleService
{ {
protected baseRepository_: DAL.RepositoryService protected baseRepository_: DAL.RepositoryService
protected paymentService_: ModulesSdkTypes.IMedusaInternalService<Payment> protected paymentService_: ModulesSdkTypes.IMedusaInternalService<
protected captureService_: ModulesSdkTypes.IMedusaInternalService<Capture> typeof Payment
protected refundService_: ModulesSdkTypes.IMedusaInternalService<Refund> >
protected paymentSessionService_: ModulesSdkTypes.IMedusaInternalService<PaymentSession> protected captureService_: ModulesSdkTypes.IMedusaInternalService<
protected paymentCollectionService_: ModulesSdkTypes.IMedusaInternalService<PaymentCollection> typeof Capture
>
protected refundService_: ModulesSdkTypes.IMedusaInternalService<
typeof Refund
>
protected paymentSessionService_: ModulesSdkTypes.IMedusaInternalService<
typeof PaymentSession
>
protected paymentCollectionService_: ModulesSdkTypes.IMedusaInternalService<
typeof PaymentCollection
>
protected paymentProviderService_: PaymentProviderService protected paymentProviderService_: PaymentProviderService
constructor( constructor(
@@ -157,7 +168,7 @@ export default class PaymentModuleService
async createPaymentCollections_( async createPaymentCollections_(
data: CreatePaymentCollectionDTO[], data: CreatePaymentCollectionDTO[],
@MedusaContext() sharedContext?: Context @MedusaContext() sharedContext?: Context
): Promise<PaymentCollection[]> { ): Promise<InferEntityType<typeof PaymentCollection>[]> {
return await this.paymentCollectionService_.create(data, sharedContext) return await this.paymentCollectionService_.create(data, sharedContext)
} }
@@ -218,7 +229,7 @@ export default class PaymentModuleService
async updatePaymentCollections_( async updatePaymentCollections_(
data: UpdatePaymentCollectionDTO[], data: UpdatePaymentCollectionDTO[],
@MedusaContext() sharedContext?: Context @MedusaContext() sharedContext?: Context
): Promise<PaymentCollection[]> { ): Promise<InferEntityType<typeof PaymentCollection>[]> {
return await this.paymentCollectionService_.update(data, sharedContext) return await this.paymentCollectionService_.update(data, sharedContext)
} }
@@ -244,7 +255,8 @@ export default class PaymentModuleService
(collection): collection is CreatePaymentCollectionDTO => !collection.id (collection): collection is CreatePaymentCollectionDTO => !collection.id
) )
const operations: Promise<PaymentCollection[]>[] = [] const operations: Promise<InferEntityType<typeof PaymentCollection>[]>[] =
[]
if (forCreate.length) { if (forCreate.length) {
operations.push(this.createPaymentCollections_(forCreate, sharedContext)) operations.push(this.createPaymentCollections_(forCreate, sharedContext))
@@ -300,7 +312,7 @@ export default class PaymentModuleService
input: CreatePaymentSessionDTO, input: CreatePaymentSessionDTO,
@MedusaContext() sharedContext?: Context @MedusaContext() sharedContext?: Context
): Promise<PaymentSessionDTO> { ): Promise<PaymentSessionDTO> {
let paymentSession: PaymentSession | undefined let paymentSession: InferEntityType<typeof PaymentSession> | undefined
let providerPaymentSession: Record<string, unknown> | undefined let providerPaymentSession: Record<string, unknown> | undefined
try { try {
@@ -313,7 +325,7 @@ export default class PaymentModuleService
providerPaymentSession = await this.paymentProviderService_.createSession( providerPaymentSession = await this.paymentProviderService_.createSession(
input.provider_id, input.provider_id,
{ {
context: { ...input.context, session_id: paymentSession.id }, context: { ...input.context, session_id: paymentSession!.id },
amount: input.amount, amount: input.amount,
currency_code: input.currency_code, currency_code: input.currency_code,
} }
@@ -322,7 +334,7 @@ export default class PaymentModuleService
paymentSession = ( paymentSession = (
await this.paymentSessionService_.update( await this.paymentSessionService_.update(
{ {
id: paymentSession.id, id: paymentSession!.id,
data: { ...input.data, ...providerPaymentSession }, data: { ...input.data, ...providerPaymentSession },
}, },
sharedContext sharedContext
@@ -354,7 +366,7 @@ export default class PaymentModuleService
paymentCollectionId: string, paymentCollectionId: string,
data: CreatePaymentSessionDTO, data: CreatePaymentSessionDTO,
@MedusaContext() sharedContext?: Context @MedusaContext() sharedContext?: Context
): Promise<PaymentSession> { ): Promise<InferEntityType<typeof PaymentSession>> {
const paymentSession = await this.paymentSessionService_.create( const paymentSession = await this.paymentSessionService_.create(
{ {
payment_collection_id: paymentCollectionId, payment_collection_id: paymentCollectionId,
@@ -493,11 +505,11 @@ export default class PaymentModuleService
@InjectTransactionManager() @InjectTransactionManager()
async authorizePaymentSession_( async authorizePaymentSession_(
session: PaymentSession, session: InferEntityType<typeof PaymentSession>,
data: Record<string, unknown>, data: Record<string, unknown>,
status: PaymentSessionStatus, status: PaymentSessionStatus,
@MedusaContext() sharedContext?: Context @MedusaContext() sharedContext?: Context
): Promise<Payment> { ): Promise<InferEntityType<typeof Payment>> {
let autoCapture = false let autoCapture = false
if (status === PaymentSessionStatus.CAPTURED) { if (status === PaymentSessionStatus.CAPTURED) {
status = PaymentSessionStatus.AUTHORIZED status = PaymentSessionStatus.AUTHORIZED
@@ -620,9 +632,9 @@ export default class PaymentModuleService
data: CreateCaptureDTO, data: CreateCaptureDTO,
@MedusaContext() sharedContext: Context = {} @MedusaContext() sharedContext: Context = {}
): Promise<{ ): Promise<{
payment: Payment payment: InferEntityType<typeof Payment>
isFullyCaptured: boolean isFullyCaptured: boolean
capture?: Capture capture?: InferEntityType<typeof Capture>
}> { }> {
const payment = await this.paymentService_.retrieve( const payment = await this.paymentService_.retrieve(
data.payment_id, data.payment_id,
@@ -659,10 +671,10 @@ export default class PaymentModuleService
} }
const capturedAmount = payment.captures.reduce((captureAmount, next) => { const capturedAmount = payment.captures.reduce((captureAmount, next) => {
return MathBN.add(captureAmount, next.raw_amount) return MathBN.add(captureAmount, next.raw_amount as BigNumberInput)
}, MathBN.convert(0)) }, MathBN.convert(0))
const authorizedAmount = new BigNumber(payment.raw_amount) const authorizedAmount = new BigNumber(payment.raw_amount as BigNumberInput)
const newCaptureAmount = new BigNumber(data.amount) const newCaptureAmount = new BigNumber(data.amount)
const remainingToCapture = MathBN.sub(authorizedAmount, capturedAmount) const remainingToCapture = MathBN.sub(authorizedAmount, capturedAmount)
@@ -692,7 +704,7 @@ export default class PaymentModuleService
} }
@InjectManager() @InjectManager()
private async capturePaymentFromProvider_( private async capturePaymentFromProvider_(
payment: Payment, payment: InferEntityType<typeof Payment>,
isFullyCaptured: boolean, isFullyCaptured: boolean,
@MedusaContext() sharedContext: Context = {} @MedusaContext() sharedContext: Context = {}
) { ) {
@@ -756,20 +768,20 @@ export default class PaymentModuleService
@InjectTransactionManager() @InjectTransactionManager()
private async refundPayment_( private async refundPayment_(
payment: Payment, payment: InferEntityType<typeof Payment>,
data: CreateRefundDTO, data: CreateRefundDTO,
@MedusaContext() sharedContext: Context = {} @MedusaContext() sharedContext: Context = {}
): Promise<Refund> { ): Promise<InferEntityType<typeof Refund>> {
if (!data.amount) { if (!data.amount) {
data.amount = payment.amount as BigNumberInput data.amount = payment.amount as BigNumberInput
} }
const capturedAmount = payment.captures.reduce((captureAmount, next) => { const capturedAmount = payment.captures.reduce((captureAmount, next) => {
const amountAsBigNumber = new BigNumber(next.raw_amount) const amountAsBigNumber = new BigNumber(next.raw_amount as BigNumberInput)
return MathBN.add(captureAmount, amountAsBigNumber) return MathBN.add(captureAmount, amountAsBigNumber)
}, MathBN.convert(0)) }, MathBN.convert(0))
const refundedAmount = payment.refunds.reduce((refundedAmount, next) => { const refundedAmount = payment.refunds.reduce((refundedAmount, next) => {
return MathBN.add(refundedAmount, next.raw_amount) return MathBN.add(refundedAmount, next.raw_amount as BigNumberInput)
}, MathBN.convert(0)) }, MathBN.convert(0))
const totalRefundedAmount = MathBN.add(refundedAmount, data.amount) const totalRefundedAmount = MathBN.add(refundedAmount, data.amount)
@@ -797,8 +809,8 @@ export default class PaymentModuleService
@InjectManager() @InjectManager()
private async refundPaymentFromProvider_( private async refundPaymentFromProvider_(
payment: Payment, payment: InferEntityType<typeof Payment>,
refund: Refund, refund: InferEntityType<typeof Refund>,
@MedusaContext() sharedContext: Context = {} @MedusaContext() sharedContext: Context = {}
) { ) {
const paymentData = await this.paymentProviderService_.refundPayment( const paymentData = await this.paymentProviderService_.refundPayment(
@@ -806,7 +818,7 @@ export default class PaymentModuleService
data: payment.data!, data: payment.data!,
provider_id: payment.provider_id, provider_id: payment.provider_id,
}, },
refund.raw_amount refund.raw_amount as BigNumberInput
) )
await this.paymentService_.update( await this.paymentService_.update(
@@ -828,14 +840,6 @@ export default class PaymentModuleService
sharedContext sharedContext
) )
// TODO: revisit when totals are implemented
// if (payment.captured_amount !== 0) {
// throw new MedusaError(
// MedusaError.Types.INVALID_DATA,
// `Cannot cancel a payment: ${payment.id} that has been captured.`
// )
// }
await this.paymentProviderService_.cancelPayment({ await this.paymentProviderService_.cancelPayment({
data: payment.data!, data: payment.data!,
provider_id: payment.provider_id, provider_id: payment.provider_id,