feat: Refund payment (#6610)

Essentially the same as #6601 but for refunds
This commit is contained in:
Oli Juhl
2024-03-07 12:34:36 +00:00
committed by GitHub
parent 7dee1a3fd3
commit e5cbe28d54
10 changed files with 246 additions and 37 deletions
@@ -6,7 +6,7 @@ export class Migration20240225134525 extends Migration {
const paymentCollectionExists = await this.execute(
`SELECT * FROM information_schema.tables where table_name = 'payment_collection' and table_schema = 'public';`
)
if (paymentCollectionExists.length) {
this.addSql(`
${generatePostgresAlterColummnIfExistStatement(
@@ -39,6 +39,12 @@ export class Migration20240225134525 extends Migration {
ALTER TABLE IF EXISTS "refund" ADD COLUMN IF NOT EXISTS "raw_amount" JSONB NOT NULL;
ALTER TABLE IF EXISTS "refund" ADD COLUMN IF NOT EXISTS "deleted_at" TIMESTAMPTZ NULL;
ALTER TABLE IF EXISTS "refund" ADD COLUMN IF NOT EXISTS "created_by" TEXT NULL;
${generatePostgresAlterColummnIfExistStatement(
"refund",
["reason"],
"DROP NOT NULL"
)}
CREATE TABLE IF NOT EXISTS "capture" (
"id" TEXT NOT NULL,
+23 -11
View File
@@ -450,9 +450,9 @@ export default class PaymentModuleService<
)
}
const capturedAmount = payment.captures.reduce((acc, next) => {
const bn = new BigNumber(next.raw_amount.value)
return acc.plus(bn)
const capturedAmount = payment.captures.reduce((captureAmount, next) => {
const amountAsBigNumber = new BigNumber(next.raw_amount.value)
return captureAmount.plus(amountAsBigNumber)
}, BigNumber(0))
const authorizedAmount = BigNumber(payment.raw_amount.value)
@@ -507,17 +507,29 @@ export default class PaymentModuleService<
): Promise<PaymentDTO> {
const payment = await this.paymentService_.retrieve(
data.payment_id,
{ select: ["id", "data", "provider_id"] },
{
select: ["id", "data", "provider_id", "amount", "raw_amount"],
relations: ["captures.raw_amount"],
},
sharedContext
)
// TODO: revisit when https://github.com/medusajs/medusa/pull/6253 is merged
// if (payment.captured_amount < input.amount) {
// throw new MedusaError(
// MedusaError.Types.INVALID_DATA,
// `Refund amount for payment: ${payment.id} cannot be greater than the amount captured on the payment.`
// )
// }
if (!data.amount) {
data.amount = payment.amount as number
}
const capturedAmount = payment.captures.reduce((captureAmount, next) => {
const amountAsBigNumber = new BigNumber(next.raw_amount.value)
return captureAmount.plus(amountAsBigNumber)
}, BigNumber(0))
const refundAmount = BigNumber(data.amount)
if (capturedAmount.lt(refundAmount)) {
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
`You cannot refund more than what is captured on the payment.`
)
}
const paymentData = await this.paymentProviderService_.refundPayment(
{