From 0264294ab55fc34a728834b5d217e0c8a7bf5a90 Mon Sep 17 00:00:00 2001 From: "Carlos R. L. Rodrigues" <37986729+carlos-r-l-rodrigues@users.noreply.github.com> Date: Wed, 11 Dec 2024 13:09:10 -0300 Subject: [PATCH] chore(payment): Payment module DML (#10553) * chore(payment): Payment module DML * rm log * migration --- .changeset/tame-snakes-doubt.md | 5 + .../__tests__/payment/admin/payment.spec.ts | 2 +- .../services/payment-module/index.spec.ts | 14 +- .../migrations/.snapshot-medusa-payment.json | 594 +++++++++++------- .../src/migrations/Migration20241211151053.ts | 45 ++ .../modules/payment/src/models/capture.ts | 92 +-- .../payment/src/models/payment-collection.ts | 155 +---- .../src/models/payment-method-token.ts | 77 +-- .../payment/src/models/payment-provider.ts | 23 +- .../payment/src/models/payment-session.ts | 151 +---- .../modules/payment/src/models/payment.ts | 198 ++---- .../payment/src/models/refund-reason.ts | 72 +-- packages/modules/payment/src/models/refund.ts | 121 +--- .../payment/src/services/payment-module.ts | 72 ++- 14 files changed, 644 insertions(+), 977 deletions(-) create mode 100644 .changeset/tame-snakes-doubt.md create mode 100644 packages/modules/payment/src/migrations/Migration20241211151053.ts diff --git a/.changeset/tame-snakes-doubt.md b/.changeset/tame-snakes-doubt.md new file mode 100644 index 0000000000000..5855658afd8f6 --- /dev/null +++ b/.changeset/tame-snakes-doubt.md @@ -0,0 +1,5 @@ +--- +"@medusajs/payment": patch +--- + +Payment module DML diff --git a/integration-tests/http/__tests__/payment/admin/payment.spec.ts b/integration-tests/http/__tests__/payment/admin/payment.spec.ts index 684a37d9cf96b..3b6ff5741d892 100644 --- a/integration-tests/http/__tests__/payment/admin/payment.spec.ts +++ b/integration-tests/http/__tests__/payment/admin/payment.spec.ts @@ -1,5 +1,5 @@ -import { ClaimType } from "@medusajs/utils" import { medusaIntegrationTestRunner } from "@medusajs/test-utils" +import { ClaimType } from "@medusajs/utils" import { adminHeaders, createAdminUser, diff --git a/packages/modules/payment/integration-tests/__tests__/services/payment-module/index.spec.ts b/packages/modules/payment/integration-tests/__tests__/services/payment-module/index.spec.ts index 8ea2d350951dd..9ab9e14909ea5 100644 --- a/packages/modules/payment/integration-tests/__tests__/services/payment-module/index.spec.ts +++ b/packages/modules/payment/integration-tests/__tests__/services/payment-module/index.spec.ts @@ -1,7 +1,7 @@ import { IPaymentModuleService } from "@medusajs/framework/types" import { Module, Modules, promiseAll } from "@medusajs/framework/utils" -import { PaymentModuleService } from "@services" import { moduleIntegrationTestRunner } from "@medusajs/test-utils" +import { PaymentModuleService } from "@services" import { createPaymentCollections, createPayments, @@ -24,10 +24,9 @@ moduleIntegrationTestRunner({ }).linkable expect(Object.keys(linkable)).toEqual([ - "payment", "paymentCollection", - "paymentProvider", "paymentSession", + "payment", "refundReason", ]) @@ -54,15 +53,6 @@ moduleIntegrationTestRunner({ field: "paymentCollection", }, }, - paymentProvider: { - id: { - linkable: "payment_provider_id", - entity: "PaymentProvider", - primaryKey: "id", - serviceName: "payment", - field: "paymentProvider", - }, - }, paymentSession: { id: { field: "paymentSession", diff --git a/packages/modules/payment/src/migrations/.snapshot-medusa-payment.json b/packages/modules/payment/src/migrations/.snapshot-medusa-payment.json index e95dc6a972fc2..c20fabdfa020d 100644 --- a/packages/modules/payment/src/migrations/.snapshot-medusa-payment.json +++ b/packages/modules/payment/src/migrations/.snapshot-medusa-payment.json @@ -1,5 +1,7 @@ { - "namespaces": ["public"], + "namespaces": [ + "public" + ], "name": "public", "tables": [ { @@ -31,15 +33,6 @@ "nullable": false, "mappedType": "decimal" }, - "raw_amount": { - "name": "raw_amount", - "type": "jsonb", - "unsigned": false, - "autoincrement": false, - "primary": false, - "nullable": false, - "mappedType": "json" - }, "authorized_amount": { "name": "authorized_amount", "type": "numeric", @@ -49,17 +42,17 @@ "nullable": true, "mappedType": "decimal" }, - "raw_authorized_amount": { - "name": "raw_authorized_amount", - "type": "jsonb", + "captured_amount": { + "name": "captured_amount", + "type": "numeric", "unsigned": false, "autoincrement": false, "primary": false, "nullable": true, - "mappedType": "json" + "mappedType": "decimal" }, - "captured_amount": { - "name": "captured_amount", + "refunded_amount": { + "name": "refunded_amount", "type": "numeric", "unsigned": false, "autoincrement": false, @@ -67,8 +60,44 @@ "nullable": true, "mappedType": "decimal" }, - "raw_captured_amount": { - "name": "raw_captured_amount", + "region_id": { + "name": "region_id", + "type": "text", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "mappedType": "text" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamptz", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": true, + "length": 6, + "mappedType": "datetime" + }, + "status": { + "name": "status", + "type": "text", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "default": "'not_paid'", + "enumItems": [ + "not_paid", + "awaiting", + "authorized", + "partially_authorized", + "canceled" + ], + "mappedType": "enum" + }, + "metadata": { + "name": "metadata", "type": "jsonb", "unsigned": false, "autoincrement": false, @@ -76,17 +105,26 @@ "nullable": true, "mappedType": "json" }, - "refunded_amount": { - "name": "refunded_amount", - "type": "numeric", + "raw_amount": { + "name": "raw_amount", + "type": "jsonb", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "mappedType": "json" + }, + "raw_authorized_amount": { + "name": "raw_authorized_amount", + "type": "jsonb", "unsigned": false, "autoincrement": false, "primary": false, "nullable": true, - "mappedType": "decimal" + "mappedType": "json" }, - "raw_refunded_amount": { - "name": "raw_refunded_amount", + "raw_captured_amount": { + "name": "raw_captured_amount", "type": "jsonb", "unsigned": false, "autoincrement": false, @@ -94,14 +132,14 @@ "nullable": true, "mappedType": "json" }, - "region_id": { - "name": "region_id", - "type": "text", + "raw_refunded_amount": { + "name": "raw_refunded_amount", + "type": "jsonb", "unsigned": false, "autoincrement": false, "primary": false, - "nullable": false, - "mappedType": "text" + "nullable": true, + "mappedType": "json" }, "created_at": { "name": "created_at", @@ -134,64 +172,32 @@ "nullable": true, "length": 6, "mappedType": "datetime" - }, - "completed_at": { - "name": "completed_at", - "type": "timestamptz", - "unsigned": false, - "autoincrement": false, - "primary": false, - "nullable": true, - "length": 6, - "mappedType": "datetime" - }, - "status": { - "name": "status", - "type": "text", - "unsigned": false, - "autoincrement": false, - "primary": false, - "nullable": false, - "default": "'not_paid'", - "enumItems": [ - "not_paid", - "awaiting", - "authorized", - "partially_authorized", - "canceled" - ], - "mappedType": "enum" - }, - "metadata": { - "name": "metadata", - "type": "jsonb", - "unsigned": false, - "autoincrement": false, - "primary": false, - "nullable": true, - "mappedType": "json" } }, "name": "payment_collection", "schema": "public", "indexes": [ { - "columnNames": ["region_id"], + "keyName": "IDX_payment_collection_deleted_at", + "columnNames": [], "composite": false, - "keyName": "IDX_payment_collection_region_id", "primary": false, - "unique": false + "unique": false, + "expression": "CREATE INDEX IF NOT EXISTS \"IDX_payment_collection_deleted_at\" ON \"payment_collection\" (deleted_at) WHERE deleted_at IS NULL" }, { - "columnNames": ["deleted_at"], + "keyName": "IDX_payment_collection_region_id", + "columnNames": [], "composite": false, - "keyName": "IDX_payment_collection_deleted_at", "primary": false, - "unique": false + "unique": false, + "expression": "CREATE INDEX IF NOT EXISTS \"IDX_payment_collection_region_id\" ON \"payment_collection\" (region_id) WHERE deleted_at IS NULL" }, { "keyName": "payment_collection_pkey", - "columnNames": ["id"], + "columnNames": [ + "id" + ], "composite": false, "primary": true, "unique": true @@ -256,6 +262,15 @@ "nullable": true, "mappedType": "text" }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": true, + "mappedType": "json" + }, "created_at": { "name": "created_at", "type": "timestamptz", @@ -287,30 +302,24 @@ "nullable": true, "length": 6, "mappedType": "datetime" - }, - "metadata": { - "name": "metadata", - "type": "jsonb", - "unsigned": false, - "autoincrement": false, - "primary": false, - "nullable": true, - "mappedType": "json" } }, "name": "payment_method_token", "schema": "public", "indexes": [ { - "columnNames": ["deleted_at"], - "composite": false, "keyName": "IDX_payment_method_token_deleted_at", + "columnNames": [], + "composite": false, "primary": false, - "unique": false + "unique": false, + "expression": "CREATE INDEX IF NOT EXISTS \"IDX_payment_method_token_deleted_at\" ON \"payment_method_token\" (deleted_at) WHERE deleted_at IS NULL" }, { "keyName": "payment_method_token_pkey", - "columnNames": ["id"], + "columnNames": [ + "id" + ], "composite": false, "primary": true, "unique": true @@ -339,14 +348,56 @@ "nullable": false, "default": "true", "mappedType": "boolean" + }, + "created_at": { + "name": "created_at", + "type": "timestamptz", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "length": 6, + "default": "now()", + "mappedType": "datetime" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamptz", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "length": 6, + "default": "now()", + "mappedType": "datetime" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamptz", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": true, + "length": 6, + "mappedType": "datetime" } }, "name": "payment_provider", "schema": "public", "indexes": [ + { + "keyName": "IDX_payment_provider_deleted_at", + "columnNames": [], + "composite": false, + "primary": false, + "unique": false, + "expression": "CREATE INDEX IF NOT EXISTS \"IDX_payment_provider_deleted_at\" ON \"payment_provider\" (deleted_at) WHERE deleted_at IS NULL" + }, { "keyName": "payment_provider_pkey", - "columnNames": ["id"], + "columnNames": [ + "id" + ], "composite": false, "primary": true, "unique": true @@ -381,7 +432,10 @@ "indexes": [ { "keyName": "payment_collection_payment_providers_pkey", - "columnNames": ["payment_collection_id", "payment_provider_id"], + "columnNames": [ + "payment_collection_id", + "payment_provider_id" + ], "composite": true, "primary": true, "unique": true @@ -391,18 +445,26 @@ "foreignKeys": { "payment_collection_payment_providers_payment_coll_aa276_foreign": { "constraintName": "payment_collection_payment_providers_payment_coll_aa276_foreign", - "columnNames": ["payment_collection_id"], + "columnNames": [ + "payment_collection_id" + ], "localTableName": "public.payment_collection_payment_providers", - "referencedColumnNames": ["id"], + "referencedColumnNames": [ + "id" + ], "referencedTableName": "public.payment_collection", "deleteRule": "cascade", "updateRule": "cascade" }, "payment_collection_payment_providers_payment_provider_id_foreign": { "constraintName": "payment_collection_payment_providers_payment_provider_id_foreign", - "columnNames": ["payment_provider_id"], + "columnNames": [ + "payment_provider_id" + ], "localTableName": "public.payment_collection_payment_providers", - "referencedColumnNames": ["id"], + "referencedColumnNames": [ + "id" + ], "referencedTableName": "public.payment_provider", "deleteRule": "cascade", "updateRule": "cascade" @@ -438,15 +500,6 @@ "nullable": false, "mappedType": "decimal" }, - "raw_amount": { - "name": "raw_amount", - "type": "jsonb", - "unsigned": false, - "autoincrement": false, - "primary": false, - "nullable": false, - "mappedType": "json" - }, "provider_id": { "name": "provider_id", "type": "text", @@ -463,6 +516,7 @@ "autoincrement": false, "primary": false, "nullable": false, + "default": "'{}'", "mappedType": "json" }, "context": { @@ -520,6 +574,15 @@ "nullable": true, "mappedType": "json" }, + "raw_amount": { + "name": "raw_amount", + "type": "jsonb", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "mappedType": "json" + }, "created_at": { "name": "created_at", "type": "timestamptz", @@ -557,22 +620,26 @@ "schema": "public", "indexes": [ { - "columnNames": ["payment_collection_id"], - "composite": false, "keyName": "IDX_payment_session_payment_collection_id", + "columnNames": [], + "composite": false, "primary": false, - "unique": false + "unique": false, + "expression": "CREATE INDEX IF NOT EXISTS \"IDX_payment_session_payment_collection_id\" ON \"payment_session\" (payment_collection_id) WHERE deleted_at IS NULL" }, { - "columnNames": ["deleted_at"], - "composite": false, "keyName": "IDX_payment_session_deleted_at", + "columnNames": [], + "composite": false, "primary": false, - "unique": false + "unique": false, + "expression": "CREATE INDEX IF NOT EXISTS \"IDX_payment_session_deleted_at\" ON \"payment_session\" (deleted_at) WHERE deleted_at IS NULL" }, { "keyName": "payment_session_pkey", - "columnNames": ["id"], + "columnNames": [ + "id" + ], "composite": false, "primary": true, "unique": true @@ -582,10 +649,15 @@ "foreignKeys": { "payment_session_payment_collection_id_foreign": { "constraintName": "payment_session_payment_collection_id_foreign", - "columnNames": ["payment_collection_id"], + "columnNames": [ + "payment_collection_id" + ], "localTableName": "public.payment_session", - "referencedColumnNames": ["id"], + "referencedColumnNames": [ + "id" + ], "referencedTableName": "public.payment_collection", + "deleteRule": "cascade", "updateRule": "cascade" } } @@ -610,15 +682,6 @@ "nullable": false, "mappedType": "decimal" }, - "raw_amount": { - "name": "raw_amount", - "type": "jsonb", - "unsigned": false, - "autoincrement": false, - "primary": false, - "nullable": false, - "mappedType": "json" - }, "currency_code": { "name": "currency_code", "type": "text", @@ -682,38 +745,6 @@ "nullable": true, "mappedType": "json" }, - "created_at": { - "name": "created_at", - "type": "timestamptz", - "unsigned": false, - "autoincrement": false, - "primary": false, - "nullable": false, - "length": 6, - "default": "now()", - "mappedType": "datetime" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamptz", - "unsigned": false, - "autoincrement": false, - "primary": false, - "nullable": false, - "length": 6, - "default": "now()", - "mappedType": "datetime" - }, - "deleted_at": { - "name": "deleted_at", - "type": "timestamptz", - "unsigned": false, - "autoincrement": false, - "primary": false, - "nullable": true, - "length": 6, - "mappedType": "datetime" - }, "captured_at": { "name": "captured_at", "type": "timestamptz", @@ -751,50 +782,98 @@ "primary": false, "nullable": false, "mappedType": "text" + }, + "raw_amount": { + "name": "raw_amount", + "type": "jsonb", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "mappedType": "json" + }, + "created_at": { + "name": "created_at", + "type": "timestamptz", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "length": 6, + "default": "now()", + "mappedType": "datetime" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamptz", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "length": 6, + "default": "now()", + "mappedType": "datetime" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamptz", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": true, + "length": 6, + "mappedType": "datetime" } }, "name": "payment", "schema": "public", "indexes": [ { - "columnNames": ["deleted_at"], + "columnNames": [ + "payment_session_id" + ], "composite": false, - "keyName": "IDX_payment_deleted_at", + "keyName": "payment_payment_session_id_unique", "primary": false, - "unique": false + "unique": true }, { - "columnNames": ["payment_collection_id"], - "composite": false, "keyName": "IDX_payment_payment_collection_id", + "columnNames": [], + "composite": false, "primary": false, - "unique": false + "unique": false, + "expression": "CREATE INDEX IF NOT EXISTS \"IDX_payment_payment_collection_id\" ON \"payment\" (payment_collection_id) WHERE deleted_at IS NULL" }, { - "columnNames": ["payment_session_id"], - "composite": false, "keyName": "IDX_payment_payment_session_id", + "columnNames": [], + "composite": false, "primary": false, - "unique": false + "unique": false, + "expression": "CREATE INDEX IF NOT EXISTS \"IDX_payment_payment_session_id\" ON \"payment\" (payment_session_id) WHERE deleted_at IS NULL" }, { - "columnNames": ["payment_session_id"], + "keyName": "IDX_payment_deleted_at", + "columnNames": [], "composite": false, - "keyName": "payment_payment_session_id_unique", "primary": false, - "unique": true + "unique": false, + "expression": "CREATE INDEX IF NOT EXISTS \"IDX_payment_deleted_at\" ON \"payment\" (deleted_at) WHERE deleted_at IS NULL" }, { "keyName": "IDX_payment_provider_id", - "columnNames": ["provider_id"], + "columnNames": [], "composite": false, "primary": false, "unique": false, - "expression": "CREATE INDEX IF NOT EXISTS \"IDX_payment_provider_id\" ON \"payment\" (provider_id)" + "expression": "CREATE INDEX IF NOT EXISTS \"IDX_payment_provider_id\" ON \"payment\" (provider_id) WHERE deleted_at IS NULL" }, { "keyName": "payment_pkey", - "columnNames": ["id"], + "columnNames": [ + "id" + ], "composite": false, "primary": true, "unique": true @@ -804,17 +883,26 @@ "foreignKeys": { "payment_payment_collection_id_foreign": { "constraintName": "payment_payment_collection_id_foreign", - "columnNames": ["payment_collection_id"], + "columnNames": [ + "payment_collection_id" + ], "localTableName": "public.payment", - "referencedColumnNames": ["id"], + "referencedColumnNames": [ + "id" + ], "referencedTableName": "public.payment_collection", + "deleteRule": "cascade", "updateRule": "cascade" }, "payment_payment_session_id_foreign": { "constraintName": "payment_payment_session_id_foreign", - "columnNames": ["payment_session_id"], + "columnNames": [ + "payment_session_id" + ], "localTableName": "public.payment", - "referencedColumnNames": ["id"], + "referencedColumnNames": [ + "id" + ], "referencedTableName": "public.payment_session", "updateRule": "cascade" } @@ -840,15 +928,6 @@ "nullable": false, "mappedType": "decimal" }, - "raw_amount": { - "name": "raw_amount", - "type": "jsonb", - "unsigned": false, - "autoincrement": false, - "primary": false, - "nullable": false, - "mappedType": "json" - }, "payment_id": { "name": "payment_id", "type": "text", @@ -867,6 +946,24 @@ "nullable": true, "mappedType": "json" }, + "created_by": { + "name": "created_by", + "type": "text", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": true, + "mappedType": "text" + }, + "raw_amount": { + "name": "raw_amount", + "type": "jsonb", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "mappedType": "json" + }, "created_at": { "name": "created_at", "type": "timestamptz", @@ -898,37 +995,32 @@ "nullable": true, "length": 6, "mappedType": "datetime" - }, - "created_by": { - "name": "created_by", - "type": "text", - "unsigned": false, - "autoincrement": false, - "primary": false, - "nullable": true, - "mappedType": "text" } }, "name": "capture", "schema": "public", "indexes": [ { - "columnNames": ["payment_id"], - "composite": false, "keyName": "IDX_capture_payment_id", + "columnNames": [], + "composite": false, "primary": false, - "unique": false + "unique": false, + "expression": "CREATE INDEX IF NOT EXISTS \"IDX_capture_payment_id\" ON \"capture\" (payment_id) WHERE deleted_at IS NULL" }, { - "columnNames": ["deleted_at"], - "composite": false, "keyName": "IDX_capture_deleted_at", + "columnNames": [], + "composite": false, "primary": false, - "unique": false + "unique": false, + "expression": "CREATE INDEX IF NOT EXISTS \"IDX_capture_deleted_at\" ON \"capture\" (deleted_at) WHERE deleted_at IS NULL" }, { "keyName": "capture_pkey", - "columnNames": ["id"], + "columnNames": [ + "id" + ], "composite": false, "primary": true, "unique": true @@ -938,9 +1030,13 @@ "foreignKeys": { "capture_payment_id_foreign": { "constraintName": "capture_payment_id_foreign", - "columnNames": ["payment_id"], + "columnNames": [ + "payment_id" + ], "localTableName": "public.capture", - "referencedColumnNames": ["id"], + "referencedColumnNames": [ + "id" + ], "referencedTableName": "public.payment", "deleteRule": "cascade", "updateRule": "cascade" @@ -1021,9 +1117,19 @@ "name": "refund_reason", "schema": "public", "indexes": [ + { + "keyName": "IDX_refund_reason_deleted_at", + "columnNames": [], + "composite": false, + "primary": false, + "unique": false, + "expression": "CREATE INDEX IF NOT EXISTS \"IDX_refund_reason_deleted_at\" ON \"refund_reason\" (deleted_at) WHERE deleted_at IS NULL" + }, { "keyName": "refund_reason_pkey", - "columnNames": ["id"], + "columnNames": [ + "id" + ], "composite": false, "primary": true, "unique": true @@ -1052,15 +1158,6 @@ "nullable": false, "mappedType": "decimal" }, - "raw_amount": { - "name": "raw_amount", - "type": "jsonb", - "unsigned": false, - "autoincrement": false, - "primary": false, - "nullable": false, - "mappedType": "json" - }, "payment_id": { "name": "payment_id", "type": "text", @@ -1088,6 +1185,33 @@ "nullable": true, "mappedType": "text" }, + "created_by": { + "name": "created_by", + "type": "text", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": true, + "mappedType": "text" + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": true, + "mappedType": "json" + }, + "raw_amount": { + "name": "raw_amount", + "type": "jsonb", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "mappedType": "json" + }, "created_at": { "name": "created_at", "type": "timestamptz", @@ -1119,46 +1243,40 @@ "nullable": true, "length": 6, "mappedType": "datetime" - }, - "created_by": { - "name": "created_by", - "type": "text", - "unsigned": false, - "autoincrement": false, - "primary": false, - "nullable": true, - "mappedType": "text" - }, - "metadata": { - "name": "metadata", - "type": "jsonb", - "unsigned": false, - "autoincrement": false, - "primary": false, - "nullable": true, - "mappedType": "json" } }, "name": "refund", "schema": "public", "indexes": [ { - "columnNames": ["payment_id"], - "composite": false, "keyName": "IDX_refund_payment_id", + "columnNames": [], + "composite": false, "primary": false, - "unique": false + "unique": false, + "expression": "CREATE INDEX IF NOT EXISTS \"IDX_refund_payment_id\" ON \"refund\" (payment_id) WHERE deleted_at IS NULL" }, { - "columnNames": ["deleted_at"], + "keyName": "IDX_refund_refund_reason_id", + "columnNames": [], "composite": false, + "primary": false, + "unique": false, + "expression": "CREATE INDEX IF NOT EXISTS \"IDX_refund_refund_reason_id\" ON \"refund\" (refund_reason_id) WHERE deleted_at IS NULL" + }, + { "keyName": "IDX_refund_deleted_at", + "columnNames": [], + "composite": false, "primary": false, - "unique": false + "unique": false, + "expression": "CREATE INDEX IF NOT EXISTS \"IDX_refund_deleted_at\" ON \"refund\" (deleted_at) WHERE deleted_at IS NULL" }, { "keyName": "refund_pkey", - "columnNames": ["id"], + "columnNames": [ + "id" + ], "composite": false, "primary": true, "unique": true @@ -1168,18 +1286,26 @@ "foreignKeys": { "refund_payment_id_foreign": { "constraintName": "refund_payment_id_foreign", - "columnNames": ["payment_id"], + "columnNames": [ + "payment_id" + ], "localTableName": "public.refund", - "referencedColumnNames": ["id"], + "referencedColumnNames": [ + "id" + ], "referencedTableName": "public.payment", "deleteRule": "cascade", "updateRule": "cascade" }, "refund_refund_reason_id_foreign": { "constraintName": "refund_refund_reason_id_foreign", - "columnNames": ["refund_reason_id"], + "columnNames": [ + "refund_reason_id" + ], "localTableName": "public.refund", - "referencedColumnNames": ["id"], + "referencedColumnNames": [ + "id" + ], "referencedTableName": "public.refund_reason", "deleteRule": "set null", "updateRule": "cascade" diff --git a/packages/modules/payment/src/migrations/Migration20241211151053.ts b/packages/modules/payment/src/migrations/Migration20241211151053.ts new file mode 100644 index 0000000000000..572abfb5d2142 --- /dev/null +++ b/packages/modules/payment/src/migrations/Migration20241211151053.ts @@ -0,0 +1,45 @@ +import { Migration } from '@mikro-orm/migrations'; + +export class Migration20241211151053 extends Migration { + + async up(): Promise { + 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 { + 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";'); + } + +} diff --git a/packages/modules/payment/src/models/capture.ts b/packages/modules/payment/src/models/capture.ts index 94a5b4ff93a40..96eeba5971787 100644 --- a/packages/modules/payment/src/models/capture.ts +++ b/packages/modules/payment/src/models/capture.ts @@ -1,77 +1,21 @@ -import { BigNumberRawValue } from "@medusajs/framework/types" -import { - BigNumber, - MikroOrmBigNumberProperty, - generateEntityId, -} from "@medusajs/framework/utils" -import { - BeforeCreate, - Entity, - ManyToOne, - OnInit, - OptionalProps, - PrimaryKey, - Property, -} from "@mikro-orm/core" +import { model } from "@medusajs/framework/utils" import Payment from "./payment" -type OptionalCaptureProps = "created_at" - -@Entity({ tableName: "capture" }) -export default class Capture { - [OptionalProps]?: OptionalCaptureProps - - @PrimaryKey({ columnType: "text" }) - id: string - - @MikroOrmBigNumberProperty() - amount: BigNumber | number - - @Property({ columnType: "jsonb" }) - raw_amount: BigNumberRawValue - - @ManyToOne(() => Payment, { - onDelete: "cascade", - index: "IDX_capture_payment_id", - fieldName: "payment_id", - }) - payment!: Payment - - @Property({ columnType: "jsonb", nullable: true }) - metadata: Record | null = null - - @Property({ - onCreate: () => new Date(), - columnType: "timestamptz", - defaultRaw: "now()", +const Capture = model + .define("Capture", { + id: model.id({ prefix: "capt" }).primaryKey(), + amount: model.bigNumber(), + payment: model.belongsTo(() => Payment, { + mappedBy: "captures", + }), + metadata: model.json().nullable(), + created_by: model.text().nullable(), }) - 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") - } -} + .indexes([ + { + name: "IDX_capture_payment_id", + on: ["payment_id"], + }, + ]) + +export default Capture diff --git a/packages/modules/payment/src/models/payment-collection.ts b/packages/modules/payment/src/models/payment-collection.ts index d4e178496a62d..0cac199a8b958 100644 --- a/packages/modules/payment/src/models/payment-collection.ts +++ b/packages/modules/payment/src/models/payment-collection.ts @@ -1,127 +1,40 @@ -import { BigNumberRawValue, DAL } from "@medusajs/framework/types" -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 { model, PaymentCollectionStatus } from "@medusajs/framework/utils" import Payment from "./payment" import PaymentProvider from "./payment-provider" import PaymentSession from "./payment-session" -type OptionalPaymentCollectionProps = "status" | DAL.ModelDateColumns - -@Entity({ tableName: "payment_collection" }) -@Filter(DALUtils.mikroOrmSoftDeletableFilterOptions) -export default class PaymentCollection { - [OptionalProps]?: OptionalPaymentCollectionProps - - @PrimaryKey({ columnType: "text" }) - id: string - - @Property({ columnType: "text" }) - currency_code: string - - @MikroOrmBigNumberProperty() - amount: BigNumber | number - - @Property({ columnType: "jsonb" }) - raw_amount: BigNumberRawValue - - @MikroOrmBigNumberProperty({ nullable: true }) - authorized_amount: BigNumber | number | null = null - - @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 - - @Property({ - onCreate: () => new Date(), - onUpdate: () => new Date(), - columnType: "timestamptz", - defaultRaw: "now()", - }) - updated_at: Date - - @Property({ - 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, +const PaymentCollection = model + .define("PaymentCollection", { + id: model.id({ prefix: "pay_col" }).primaryKey(), + currency_code: model.text(), + amount: model.bigNumber(), + authorized_amount: model.bigNumber().nullable(), + captured_amount: model.bigNumber().nullable(), + refunded_amount: model.bigNumber().nullable(), + region_id: model.text(), + completed_at: model.dateTime().nullable(), + status: model + .enum(PaymentCollectionStatus) + .default(PaymentCollectionStatus.NOT_PAID), + metadata: model.json().nullable(), + payment_providers: model.manyToMany(() => PaymentProvider, { + mappedBy: "payment_collections", + }), + payment_sessions: model.hasMany(() => PaymentSession, { + mappedBy: "payment_collection", + }), + payments: model.hasMany(() => Payment, { + mappedBy: "payment_collection", + }), }) - status: PaymentCollectionStatus = PaymentCollectionStatus.NOT_PAID - - @ManyToMany(() => PaymentProvider) - payment_providers = new Collection>(this) - - @OneToMany(() => PaymentSession, (ps) => ps.payment_collection, { - cascade: [Cascade.PERSIST] as any, - }) - payment_sessions = new Collection>(this) - - @OneToMany(() => Payment, (payment) => payment.payment_collection, { - cascade: [Cascade.PERSIST] as any, + .cascades({ + delete: ["payment_sessions", "payments"], }) - payments = new Collection>(this) - - @Property({ columnType: "jsonb", nullable: true }) - metadata: Record | null = null - - @BeforeCreate() - onCreate() { - this.id = generateEntityId(this.id, "pay_col") - } - - @OnInit() - onInit() { - this.id = generateEntityId(this.id, "pay_col") - } -} + .indexes([ + { + name: "IDX_payment_collection_region_id", + on: ["region_id"], + }, + ]) + +export default PaymentCollection diff --git a/packages/modules/payment/src/models/payment-method-token.ts b/packages/modules/payment/src/models/payment-method-token.ts index 2944f232ca380..18ed0340ac696 100644 --- a/packages/modules/payment/src/models/payment-method-token.ts +++ b/packages/modules/payment/src/models/payment-method-token.ts @@ -1,64 +1,13 @@ -import { generateEntityId } from "@medusajs/framework/utils" -import { - BeforeCreate, - Entity, - OnInit, - PrimaryKey, - Property, -} from "@mikro-orm/core" - -@Entity({ tableName: "payment_method_token" }) -export default class PaymentMethodToken { - @PrimaryKey({ columnType: "text" }) - id: string - - @Property({ columnType: "text" }) - provider_id: string - - @Property({ columnType: "jsonb", nullable: true }) - data: Record | 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 | null = null - - @BeforeCreate() - onCreate() { - this.id = generateEntityId(this.id, "paymttok") - } - - @OnInit() - onInit() { - this.id = generateEntityId(this.id, "paymttok") - } -} +import { model } from "@medusajs/framework/utils" + +const PaymentMethodToken = model.define("PaymentMethodToken", { + id: model.id({ prefix: "paymttok" }).primaryKey(), + provider_id: model.text(), + data: model.json().nullable(), + name: model.text(), + type_detail: model.text().nullable(), + description_detail: model.text().nullable(), + metadata: model.json().nullable(), +}) + +export default PaymentMethodToken diff --git a/packages/modules/payment/src/models/payment-provider.ts b/packages/modules/payment/src/models/payment-provider.ts index 42fe25d25663c..d1044675c0275 100644 --- a/packages/modules/payment/src/models/payment-provider.ts +++ b/packages/modules/payment/src/models/payment-provider.ts @@ -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" }) -export default class PaymentProvider { - [OptionalProps]?: "is_enabled" +const PaymentProvider = model.define("PaymentProvider", { + id: model.id().primaryKey(), + is_enabled: model.boolean().default(true), + payment_collections: model.manyToMany(() => PaymentCollection, { + mappedBy: "payment_providers", + }), +}) - @PrimaryKey({ columnType: "text" }) - id: string - - @Property({ - default: true, - columnType: "boolean", - }) - is_enabled: boolean = true -} +export default PaymentProvider diff --git a/packages/modules/payment/src/models/payment-session.ts b/packages/modules/payment/src/models/payment-session.ts index 6375d812155ca..e040bd850a953 100644 --- a/packages/modules/payment/src/models/payment-session.ts +++ b/packages/modules/payment/src/models/payment-session.ts @@ -1,120 +1,37 @@ -import { BigNumberRawValue } from "@medusajs/framework/types" -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 { model, PaymentSessionStatus } from "@medusajs/framework/utils" import Payment from "./payment" import PaymentCollection from "./payment-collection" -@Entity({ tableName: "payment_session" }) -export default class PaymentSession { - [OptionalProps]?: "status" | "data" - - @PrimaryKey({ columnType: "text" }) - id: string - - @Property({ columnType: "text" }) - currency_code: string - - @MikroOrmBigNumberProperty() - amount: BigNumber | number - - @Property({ - columnType: "jsonb", - }) - raw_amount: BigNumberRawValue - - @Property({ columnType: "text" }) - provider_id: string - - @Property({ columnType: "jsonb" }) - data: Record = {} - - @Property({ columnType: "jsonb", nullable: true }) - context: Record | 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 - - @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", - }) - payment?: Rel | null - - @Property({ columnType: "jsonb", nullable: true }) - metadata: Record | 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_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 - } -} +const PaymentSession = model + .define("PaymentSession", { + id: model.id({ prefix: "payses" }).primaryKey(), + currency_code: model.text(), + amount: model.bigNumber(), + provider_id: model.text(), + data: model.json().default({}), + context: model.json().nullable(), + status: model + .enum(PaymentSessionStatus) + .default(PaymentSessionStatus.PENDING), + authorized_at: model.dateTime().nullable(), + payment_collection: model.belongsTo<() => typeof PaymentCollection>( + () => PaymentCollection, + { + mappedBy: "payment_sessions", + } + ), + payment: model + .hasOne(() => Payment, { + mappedBy: "payment_session", + }) + .nullable(), + metadata: model.json().nullable(), + }) + .indexes([ + { + name: "IDX_payment_session_payment_collection_id", + on: ["payment_collection_id"], + }, + ]) + +export default PaymentSession diff --git a/packages/modules/payment/src/models/payment.ts b/packages/modules/payment/src/models/payment.ts index c64582fcf59d0..894ea3ecde013 100644 --- a/packages/modules/payment/src/models/payment.ts +++ b/packages/modules/payment/src/models/payment.ts @@ -1,157 +1,51 @@ -import { BigNumberRawValue, DAL } from "@medusajs/framework/types" -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 { model } from "@medusajs/framework/utils" import Capture from "./capture" import PaymentCollection from "./payment-collection" import PaymentSession from "./payment-session" import Refund from "./refund" -type OptionalPaymentProps = DAL.ModelDateColumns - -const tableName = "payment" -const ProviderIdIndex = createPsqlIndexStatementHelper({ - tableName, - columns: "provider_id", -}) - -@Entity({ tableName }) -@Filter(DALUtils.mikroOrmSoftDeletableFilterOptions) -export default class Payment { - [OptionalProps]?: OptionalPaymentProps - - @PrimaryKey({ columnType: "text" }) - id: string - - @MikroOrmBigNumberProperty() - amount: BigNumber | number - - @Property({ columnType: "jsonb" }) - raw_amount: BigNumberRawValue - - @Property({ columnType: "text" }) - currency_code: string - - @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 | null = null - - @Property({ columnType: "jsonb", nullable: true }) - metadata: Record | 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_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>(this) - - @OneToMany(() => Capture, (capture) => capture.payment, { - cascade: [Cascade.REMOVE], - }) - captures = new Collection>(this) - - @ManyToOne({ - entity: () => PaymentCollection, - persist: false, - }) - payment_collection: Rel - - @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 - - @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 - } -} +const Payment = model + .define("Payment", { + id: model.id({ prefix: "pay" }).primaryKey(), + amount: model.bigNumber(), + currency_code: model.text(), + provider_id: model.text(), + cart_id: model.text().searchable().nullable(), + order_id: model.text().searchable().nullable(), + customer_id: model.text().searchable().nullable(), + data: model.json().nullable(), + metadata: model.json().nullable(), + captured_at: model.dateTime().nullable(), + canceled_at: model.dateTime().nullable(), + payment_collection: model.belongsTo(() => PaymentCollection, { + mappedBy: "payments", + }), + payment_session: model.belongsTo(() => PaymentSession, { + mappedBy: "payment", + }), + refunds: model.hasMany(() => Refund, { + mappedBy: "payment", + }), + captures: model.hasMany(() => Capture, { + mappedBy: "payment", + }), + }) + .cascades({ + delete: ["refunds", "captures"], + }) + .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"], + }, + ]) + +export default Payment diff --git a/packages/modules/payment/src/models/refund-reason.ts b/packages/modules/payment/src/models/refund-reason.ts index d32b3d7bb35d0..026630bff2e46 100644 --- a/packages/modules/payment/src/models/refund-reason.ts +++ b/packages/modules/payment/src/models/refund-reason.ts @@ -1,58 +1,14 @@ -import { - DALUtils, - generateEntityId, - Searchable, -} from "@medusajs/framework/utils" -import { - BeforeCreate, - Entity, - Filter, - OnInit, - PrimaryKey, - Property, -} from "@mikro-orm/core" - -@Entity({ tableName: "refund_reason" }) -@Filter(DALUtils.mikroOrmSoftDeletableFilterOptions) -export default class RefundReason { - @PrimaryKey({ columnType: "text" }) - id: string - - @Searchable() - @Property({ columnType: "text" }) - label: string - - @Property({ columnType: "text", nullable: true }) - description: string | null = null - - @Property({ columnType: "jsonb", nullable: true }) - metadata: Record | 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") - } -} +import { model } from "@medusajs/framework/utils" +import Refund from "./refund" + +const RefundReason = model.define("RefundReason", { + id: model.id({ prefix: "refr" }).primaryKey(), + label: model.text().searchable(), + description: model.text().nullable(), + metadata: model.json().nullable(), + refunds: model.hasMany(() => Refund, { + mappedBy: "refund_reason", + }), +}) + +export default RefundReason diff --git a/packages/modules/payment/src/models/refund.ts b/packages/modules/payment/src/models/refund.ts index f7627c79b5ae1..edb5e3219a594 100644 --- a/packages/modules/payment/src/models/refund.ts +++ b/packages/modules/payment/src/models/refund.ts @@ -1,101 +1,28 @@ -import { BigNumberRawValue, DAL } from "@medusajs/framework/types" -import { - BigNumber, - MikroOrmBigNumberProperty, - generateEntityId, -} from "@medusajs/framework/utils" -import { - BeforeCreate, - Entity, - ManyToOne, - OnInit, - OptionalProps, - PrimaryKey, - Property, - Rel, -} from "@mikro-orm/core" +import { model } from "@medusajs/framework/utils" import Payment from "./payment" import RefundReason from "./refund-reason" -type OptionalProps = - | "note" - | "refund_reason_id" - | "refund_reason" - | DAL.ModelDateColumns - -@Entity({ tableName: "refund" }) -export default class Refund { - [OptionalProps]?: OptionalProps - - @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 - - @Property({ columnType: "text", nullable: true }) - payment_id: string - - @ManyToOne(() => RefundReason, { - columnType: "text", - mapToPk: true, - fieldName: "refund_reason_id", - nullable: true, - }) - refund_reason_id: string | null = null - - @ManyToOne(() => RefundReason, { persist: false, nullable: true }) - refund_reason: Rel | 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", +const Refund = model + .define("Refund", { + id: model.id({ prefix: "ref" }).primaryKey(), + amount: model.bigNumber(), + payment: model.belongsTo(() => Payment, { + mappedBy: "refunds", + }), + refund_reason: model + .belongsTo(() => RefundReason, { + mappedBy: "refunds", + }) + .nullable(), + note: model.text().nullable(), + created_by: model.text().nullable(), + metadata: model.json().nullable(), }) - deleted_at: Date | null = null - - @Property({ columnType: "text", nullable: true }) - created_by: string | null = null - - @Property({ columnType: "jsonb", nullable: true }) - metadata: Record | 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 - } -} + .indexes([ + { + name: "IDX_refund_payment_id", + on: ["payment_id"], + }, + ]) + +export default Refund diff --git a/packages/modules/payment/src/services/payment-module.ts b/packages/modules/payment/src/services/payment-module.ts index fdef4b55afc11..225bbd25db4fa 100644 --- a/packages/modules/payment/src/services/payment-module.ts +++ b/packages/modules/payment/src/services/payment-module.ts @@ -11,6 +11,7 @@ import { FilterablePaymentProviderProps, FilterablePaymentSessionProps, FindConfig, + InferEntityType, InternalModuleDeclaration, IPaymentModuleService, Logger, @@ -87,11 +88,21 @@ export default class PaymentModuleService { protected baseRepository_: DAL.RepositoryService - protected paymentService_: ModulesSdkTypes.IMedusaInternalService - protected captureService_: ModulesSdkTypes.IMedusaInternalService - protected refundService_: ModulesSdkTypes.IMedusaInternalService - protected paymentSessionService_: ModulesSdkTypes.IMedusaInternalService - protected paymentCollectionService_: ModulesSdkTypes.IMedusaInternalService + protected paymentService_: ModulesSdkTypes.IMedusaInternalService< + typeof Payment + > + protected captureService_: ModulesSdkTypes.IMedusaInternalService< + typeof Capture + > + protected refundService_: ModulesSdkTypes.IMedusaInternalService< + typeof Refund + > + protected paymentSessionService_: ModulesSdkTypes.IMedusaInternalService< + typeof PaymentSession + > + protected paymentCollectionService_: ModulesSdkTypes.IMedusaInternalService< + typeof PaymentCollection + > protected paymentProviderService_: PaymentProviderService constructor( @@ -157,7 +168,7 @@ export default class PaymentModuleService async createPaymentCollections_( data: CreatePaymentCollectionDTO[], @MedusaContext() sharedContext?: Context - ): Promise { + ): Promise[]> { return await this.paymentCollectionService_.create(data, sharedContext) } @@ -218,7 +229,7 @@ export default class PaymentModuleService async updatePaymentCollections_( data: UpdatePaymentCollectionDTO[], @MedusaContext() sharedContext?: Context - ): Promise { + ): Promise[]> { return await this.paymentCollectionService_.update(data, sharedContext) } @@ -244,7 +255,8 @@ export default class PaymentModuleService (collection): collection is CreatePaymentCollectionDTO => !collection.id ) - const operations: Promise[] = [] + const operations: Promise[]>[] = + [] if (forCreate.length) { operations.push(this.createPaymentCollections_(forCreate, sharedContext)) @@ -300,7 +312,7 @@ export default class PaymentModuleService input: CreatePaymentSessionDTO, @MedusaContext() sharedContext?: Context ): Promise { - let paymentSession: PaymentSession | undefined + let paymentSession: InferEntityType | undefined let providerPaymentSession: Record | undefined try { @@ -313,7 +325,7 @@ export default class PaymentModuleService providerPaymentSession = await this.paymentProviderService_.createSession( input.provider_id, { - context: { ...input.context, session_id: paymentSession.id }, + context: { ...input.context, session_id: paymentSession!.id }, amount: input.amount, currency_code: input.currency_code, } @@ -322,7 +334,7 @@ export default class PaymentModuleService paymentSession = ( await this.paymentSessionService_.update( { - id: paymentSession.id, + id: paymentSession!.id, data: { ...input.data, ...providerPaymentSession }, }, sharedContext @@ -354,7 +366,7 @@ export default class PaymentModuleService paymentCollectionId: string, data: CreatePaymentSessionDTO, @MedusaContext() sharedContext?: Context - ): Promise { + ): Promise> { const paymentSession = await this.paymentSessionService_.create( { payment_collection_id: paymentCollectionId, @@ -493,11 +505,11 @@ export default class PaymentModuleService @InjectTransactionManager() async authorizePaymentSession_( - session: PaymentSession, + session: InferEntityType, data: Record, status: PaymentSessionStatus, @MedusaContext() sharedContext?: Context - ): Promise { + ): Promise> { let autoCapture = false if (status === PaymentSessionStatus.CAPTURED) { status = PaymentSessionStatus.AUTHORIZED @@ -620,9 +632,9 @@ export default class PaymentModuleService data: CreateCaptureDTO, @MedusaContext() sharedContext: Context = {} ): Promise<{ - payment: Payment + payment: InferEntityType isFullyCaptured: boolean - capture?: Capture + capture?: InferEntityType }> { const payment = await this.paymentService_.retrieve( data.payment_id, @@ -659,10 +671,10 @@ export default class PaymentModuleService } 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)) - const authorizedAmount = new BigNumber(payment.raw_amount) + const authorizedAmount = new BigNumber(payment.raw_amount as BigNumberInput) const newCaptureAmount = new BigNumber(data.amount) const remainingToCapture = MathBN.sub(authorizedAmount, capturedAmount) @@ -692,7 +704,7 @@ export default class PaymentModuleService } @InjectManager() private async capturePaymentFromProvider_( - payment: Payment, + payment: InferEntityType, isFullyCaptured: boolean, @MedusaContext() sharedContext: Context = {} ) { @@ -756,20 +768,20 @@ export default class PaymentModuleService @InjectTransactionManager() private async refundPayment_( - payment: Payment, + payment: InferEntityType, data: CreateRefundDTO, @MedusaContext() sharedContext: Context = {} - ): Promise { + ): Promise> { if (!data.amount) { data.amount = payment.amount as BigNumberInput } 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) }, MathBN.convert(0)) 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)) const totalRefundedAmount = MathBN.add(refundedAmount, data.amount) @@ -797,8 +809,8 @@ export default class PaymentModuleService @InjectManager() private async refundPaymentFromProvider_( - payment: Payment, - refund: Refund, + payment: InferEntityType, + refund: InferEntityType, @MedusaContext() sharedContext: Context = {} ) { const paymentData = await this.paymentProviderService_.refundPayment( @@ -806,7 +818,7 @@ export default class PaymentModuleService data: payment.data!, provider_id: payment.provider_id, }, - refund.raw_amount + refund.raw_amount as BigNumberInput ) await this.paymentService_.update( @@ -828,14 +840,6 @@ export default class PaymentModuleService 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({ data: payment.data!, provider_id: payment.provider_id,