A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(billing): review disputes, revoke lost buys, close accounts
Hampus7e2854e356fa
diff --git a/fluxer_api/src/api/stripe/services/StripeDisputeWebhookHandler.ts b/fluxer_api/src/api/stripe/services/StripeDisputeWebhookHandler.tsindex f460948d6..eb1f8b506 100644--- a/fluxer_api/src/api/stripe/services/StripeDisputeWebhookHandler.ts+++ b/fluxer_api/src/api/stripe/services/StripeDisputeWebhookHandler.ts@@ -1,139 +1,350 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import type {UserRow} from '@app/api/database/types/UserTypes';+import type {UserID} from '@app/api/BrandedTypes';+import {getWithdrawalPeriodEndsAt} from '@app/api/billing/WithdrawalPeriod';+import {SYSTEM_USER_ID} from '@app/api/constants/Core';+import type {BillingChargeRow} from '@app/api/database/types/BillingTypes';+import type {OperatorPassPurchaseRow} from '@app/api/database/types/OperatorPassTypes';+import type {PaymentDisputeReviewRow} from '@app/api/database/types/PaymentDisputeTypes';import type {DonationRepository} from '@app/api/donation/DonationRepository';-import type {Donor} from '@app/api/donation/models/Donor';import type {EnforcementDecisionService} from '@app/api/enforcement/EnforcementDecisionService';-import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';import type {KVAccountDeletionQueueService} from '@app/api/infrastructure/KVAccountDeletionQueueService';import type {UserCacheService} from '@app/api/infrastructure/UserCacheService';import {Logger} from '@app/api/Logger';import {getBillingRepository} from '@app/api/middleware/ServiceRegistry';import type {GiftCode} from '@app/api/models/GiftCode';-import type {User} from '@app/api/models/User';+import type {Payment} from '@app/api/models/Payment';+import type {OperatorPassFulfilmentService} from '@app/api/operator_pass/OperatorPassFulfilmentService';+import {followOperatorPassWallStanding} from '@app/api/operator_pass/OperatorPassWallStanding';+import {+ type PaymentDisputeEnforcementService,+ shouldCloseAfterPaymentDispute,+} from '@app/api/payment_disputes/PaymentDisputeEnforcement';+import {+ getOperatorPassDisputeSubject,+ type PaymentDisputeReviewService,+ type PaymentDisputeSubject,+} from '@app/api/payment_disputes/PaymentDisputeReviews';import {extractId} from '@app/api/stripe/StripeUtils';-import {shouldBlockFurtherPurchases} from '@app/api/stripe/services/RefundAllowance';import type {StripeGiftReversalHandler} from '@app/api/stripe/services/StripeGiftReversalHandler';import type {StripePaymentFraudService} from '@app/api/stripe/services/StripePaymentFraudService';+import type {StripeSubscriptionService} from '@app/api/stripe/services/StripeSubscriptionService';import type {UserRepository} from '@app/api/user/repositories/UserRepository';import {clearPendingDeletion} from '@app/api/user/services/PendingDeletionCoordinator';-import {dispatchUserUpdate} from '@app/api/user/UserMappers';import {DeletionReasons} from '@fluxer/constants/src/Core';-import {PremiumFlags, UserFlags} from '@fluxer/constants/src/UserConstants';+import {UserFlags} from '@fluxer/constants/src/UserConstants';import {StripeError} from '@fluxer/errors/src/domains/payment/StripeError';import type {IEmailService} from '@pkgs/email/src/IEmailService';import type Stripe from 'stripe';-export const REFUND_ALLOWANCE_CLAIM_PREFIX = 'refund-allowance';+type PlutoniumDisputeTarget =+ | {kind: 'gift'; purchaserId: UserID; giftCode: GiftCode; payment: Payment | null}+ | {kind: 'purchase'; purchaserId: UserID; payment: Payment | null};export class StripeDisputeWebhookHandler {constructor(private userRepository: UserRepository,private userCacheService: UserCacheService,private emailService: IEmailService,- private gatewayService: IGatewayService,private donationRepository: DonationRepository,private kvDeletionQueue: KVAccountDeletionQueueService,private giftReversalHandler: StripeGiftReversalHandler,private paymentFraudService: StripePaymentFraudService,private enforcement: EnforcementDecisionService,+ private subscriptionService: Pick<+ StripeSubscriptionService,+ 'cancelSubscriptionAtPeriodEnd' | 'cancelSubscriptionImmediately'+ >,+ private disputeReviews: PaymentDisputeReviewService,+ private disputeEnforcement: PaymentDisputeEnforcementService,+ private operatorPassFulfilment: OperatorPassFulfilmentService | null = null,) {}async handleChargebackCreated(dispute: Stripe.Dispute): Promise<void> {- await this.paymentFraudService.handleFraudulentDispute(dispute);const paymentIntentId = extractId(dispute.payment_intent);+ const operatorPassPurchase = paymentIntentId ? await this.findOperatorPassPurchase(paymentIntentId) : null;+ await this.paymentFraudService.handleFraudulentDispute(dispute);if (!paymentIntentId) {Logger.error({dispute}, 'Chargeback missing payment intent');throw new StripeError('Chargeback missing payment intent');}- const giftCode = await this.userRepository.findGiftCodeByPaymentIntent(paymentIntentId);- if (giftCode) {- await this.handleGiftChargeback(giftCode, dispute);+ if (operatorPassPurchase && this.operatorPassFulfilment) {+ await this.operatorPassFulfilment.handleDisputeCreated(operatorPassPurchase, dispute);+ const current = (await this.findOperatorPassPurchase(paymentIntentId)) ?? operatorPassPurchase;+ await this.disputeReviews.openReview(await this.buildOperatorPassSubject(current, dispute), dispute);return;}- const payment = await this.userRepository.getPaymentByPaymentIntent(paymentIntentId);- if (!payment) {- const donor = await this.findDonorForDispute(dispute);- if (donor) {- Logger.info(- {paymentIntentId, disputeId: dispute.id, email: donor.email},- 'Chargeback for donation customer - no premium action required',- );- return;- }- Logger.error({paymentIntentId}, 'No payment found for chargeback');- throw new StripeError('No payment found for chargeback');+ const target = await this.resolvePlutoniumTarget(dispute, paymentIntentId);+ if (!target) {+ return;}- await this.paymentFraudService.limitPurchasesForFraudSignal({- userId: payment.userId,- source: 'chargeback',- signalId: dispute.id,- chargeId: extractId(dispute.charge),- paymentIntentId,- customerId: null,- fraudType: null,- paymentAt: payment.createdAt,- });+ await this.disputeReviews.openReview(await this.buildPlutoniumSubject(target, dispute, paymentIntentId), dispute);+ Logger.info(+ {disputeId: dispute.id, paymentIntentId, purchaserId: target.purchaserId, kind: target.kind},+ 'Plutonium payment dispute opened; purchases are blocked until it closes',+ );}async handleChargebackClosed(dispute: Stripe.Dispute): Promise<void> {- if (dispute.status !== 'won') {- return;- }const paymentIntentId = extractId(dispute.payment_intent);if (!paymentIntentId) {throw new StripeError('Chargeback withdrawal missing payment intent');}+ const operatorPassPurchase = await this.findOperatorPassPurchase(paymentIntentId);+ if (operatorPassPurchase && this.operatorPassFulfilment) {+ if (dispute.status === 'lost') {+ await this.operatorPassFulfilment.handleDisputeLost(operatorPassPurchase, dispute);+ } else {+ await this.operatorPassFulfilment.handleDisputeReleased(operatorPassPurchase, dispute);+ }+ const current = (await this.findOperatorPassPurchase(paymentIntentId)) ?? operatorPassPurchase;+ const review = await this.disputeReviews.closeReview(+ await this.buildOperatorPassSubject(current, dispute),+ dispute,+ );+ await this.enforceAfterClose(review);+ return;+ }+ const target = await this.resolvePlutoniumTarget(dispute, paymentIntentId);+ if (!target) {+ return;+ }+ if (dispute.status === 'lost') {+ await this.endWhatTheDisputedPaymentBought(target, dispute);+ } else {+ await this.cancelAutomaticDisputeDeletion(target.purchaserId);+ if (target.payment) {+ await this.enforcement.reverseAutomatedPurchaseLimits(+ target.purchaserId,+ target.payment.createdAt,+ `Stripe dispute ${dispute.id} was won`,+ );+ }+ Logger.info(+ {disputeId: dispute.id, paymentIntentId, status: dispute.status},+ 'Plutonium payment dispute closed without the money being returned',+ );+ }+ const review = await this.disputeReviews.closeReview(+ await this.buildPlutoniumSubject(target, dispute, paymentIntentId),+ dispute,+ );+ await this.enforceAfterClose(review);+ }++ async handleDisputeUpdated(dispute: Stripe.Dispute): Promise<void> {+ await this.disputeReviews.refreshReview(dispute);+ }++ private async enforceAfterClose(review: PaymentDisputeReviewRow): Promise<void> {+ if (!shouldCloseAfterPaymentDispute(review)) {+ return;+ }+ const user = await this.userRepository.findUnique(review.purchaser_id);+ if (user?.stripeSubscriptionId && !user.premiumWillCancel) {+ try {+ await this.subscriptionService.cancelSubscriptionAtPeriodEnd(user.id);+ } catch (error) {+ Logger.error(+ {error, disputeId: review.dispute_id, userId: user.id},+ 'Failed to stop the subscription of an account closed after a dispute',+ );+ }+ }+ await this.disputeEnforcement.closeAccount(review);+ }++ private async buildOperatorPassSubject(+ purchase: OperatorPassPurchaseRow,+ dispute: Stripe.Dispute,+ ): Promise<PaymentDisputeSubject> {+ const holderRemovals = this.operatorPassFulfilment+ ? await this.operatorPassFulfilment.repository.listRemovalHistory(purchase.purchaser_id)+ : [];+ return getOperatorPassDisputeSubject(purchase, dispute, holderRemovals);+ }++ private async resolvePlutoniumTarget(+ dispute: Stripe.Dispute,+ paymentIntentId: string,+ ): Promise<PlutoniumDisputeTarget | null> {const payment = await this.userRepository.getPaymentByPaymentIntent(paymentIntentId);- if (!payment) {- const donor = await this.findDonorForDispute(dispute);+ const giftCode =+ (await this.userRepository.findGiftCodeByPaymentIntent(paymentIntentId)) ??+ (payment?.giftCode ? await this.userRepository.findGiftCode(payment.giftCode) : null);+ if (giftCode) {+ return {kind: 'gift', purchaserId: giftCode.createdByUserId, giftCode, payment};+ }+ if (payment) {+ return {kind: 'purchase', purchaserId: payment.userId, payment};+ }+ const customerId = await this.resolveDisputeCustomerId(dispute);+ if (customerId) {+ const donor = await this.donationRepository.findDonorByStripeCustomerId(customerId);if (donor) {Logger.info({paymentIntentId, disputeId: dispute.id, email: donor.email},- 'Chargeback withdrawal for donation customer - no premium action required',+ 'Dispute on a donation payment - no account action',);- return;+ return null;+ }+ const user = await this.userRepository.findByStripeCustomerId(customerId);+ if (user) {+ return {kind: 'purchase', purchaserId: user.id, payment: null};}- throw new StripeError('No payment found for chargeback withdrawal');}- const user = await this.userRepository.findUnique(payment.userId);- if (!user) {- throw new StripeError('User not found for chargeback withdrawal');+ Logger.error({paymentIntentId, disputeId: dispute.id}, 'No payment found for chargeback');+ throw new StripeError('No payment found for chargeback');+ }++ private async findPlutoniumInvoiceNumber(+ invoiceId: string | null,+ charge: BillingChargeRow | null,+ ): Promise<string | null> {+ const invoice = invoiceId ? await getBillingRepository().invoices.findById(invoiceId) : null;+ return invoice?.number ?? charge?.receipt_number ?? null;+ }++ private async buildPlutoniumSubject(+ target: PlutoniumDisputeTarget,+ dispute: Stripe.Dispute,+ paymentIntentId: string,+ ): Promise<PaymentDisputeSubject> {+ const chargeId = extractId(dispute.charge);+ const charge = chargeId ? await getBillingRepository().charges.findById(chargeId) : null;+ const payment = target.payment;+ const purchasedAt =+ charge?.stripe_created_at ??+ payment?.completedAt ??+ payment?.createdAt ??+ (target.kind === 'gift' ? target.giftCode.createdAt : null);+ const disputedAt = new Date(dispute.created * 1000);+ return {+ product: 'plutonium',+ orderId:+ payment?.checkoutSessionId ??+ (target.kind === 'gift' ? target.giftCode.checkoutSessionId : null) ??+ payment?.invoiceId ??+ paymentIntentId,+ invoiceNumber: await this.findPlutoniumInvoiceNumber(charge?.invoice_id ?? payment?.invoiceId ?? null, charge),+ purchaserId: target.purchaserId,+ isGift: target.kind === 'gift' || payment?.isGift === true,+ paymentIntentId,+ amountMinor: dispute.amount ?? payment?.amountCents ?? 0,+ currency: dispute.currency ?? payment?.currency ?? 'usd',+ disputedAt,+ purchasedAt,+ perksStartedAt: this.plutoniumProvidedAt(target, purchasedAt),+ withdrawalEndsAt: purchasedAt ? getWithdrawalPeriodEndsAt(purchasedAt) : null,+ withdrawnAt: null,+ refundedAt: await this.findFirstRefundAt(paymentIntentId, payment, disputedAt),+ perksRemovedAt: null,+ };+ }++ private plutoniumProvidedAt(target: PlutoniumDisputeTarget, purchasedAt: Date | null): Date | null {+ if (target.kind === 'gift') {+ return target.giftCode.createdAt;+ }+ return target.payment?.isGift ? null : purchasedAt;+ }++ private async findFirstRefundAt(+ paymentIntentId: string,+ payment: Payment | null,+ disputedAt: Date,+ ): Promise<Date | null> {+ const refunds = await getBillingRepository().refunds.listByPaymentIntent(paymentIntentId);+ const times = refunds+ .filter((refund) => refund.status === 'succeeded' || refund.status === 'pending')+ .map((refund) => refund.stripe_created_at?.getTime() ?? disputedAt.getTime());+ if (times.length > 0) {+ return new Date(Math.min(...times));+ }+ return payment?.status === 'refunded' ? disputedAt : null;+ }++ private async endWhatTheDisputedPaymentBought(+ target: PlutoniumDisputeTarget,+ dispute: Stripe.Dispute,+ ): Promise<void> {+ if (target.kind === 'gift') {+ await this.takeBackGift(target.giftCode, dispute);+ return;+ }+ const payment = target.payment;+ if (payment && !payment.subscriptionId && !payment.productType?.includes('subscription')) {+ return;+ }+ const user = await this.userRepository.findUnique(target.purchaserId);+ if (!user?.stripeSubscriptionId) {+ return;+ }+ if (payment?.subscriptionId && payment.subscriptionId !== user.stripeSubscriptionId) {+ return;}- await this.enforcement.reverseAutomatedPurchaseLimits(+ await this.subscriptionService.cancelSubscriptionImmediately(user.id,- payment.createdAt,- `Stripe dispute ${dispute.id} was won`,+ 'payment_dispute_lost',+ user.stripeSubscriptionId,);- if (- user.flags & UserFlags.DELETED &&- user.deletionReasonCode === DeletionReasons.BILLING_DISPUTE_OR_ABUSE &&- user.enforcementDecisionId === null- ) {- const updatedUser = await this.userRepository.updateDeletionSchedule(user, {- flags: user.flags & ~UserFlags.DELETED,- pending_deletion_at: null,- deletion_reason_code: null,- deletion_public_reason: null,- deletion_audit_log_reason: null,- first_refund_at: user.firstRefundAt || new Date(),- });- await clearPendingDeletion({userId: payment.userId, deletionQueue: this.kvDeletionQueue});- await this.userCacheService.setUserPartialResponseFromUser(updatedUser);- if (updatedUser.email) {- await this.emailService.sendAccountDeletionCancelledEmail(- updatedUser.email,- updatedUser.username,- updatedUser.locale,- );+ Logger.info(+ {disputeId: dispute.id, userId: user.id, subscriptionId: user.stripeSubscriptionId},+ 'Plutonium ended right away after a dispute returned the money',+ );+ }++ private async takeBackGift(giftCode: GiftCode, dispute: Stripe.Dispute): Promise<void> {+ if (giftCode.redeemedByUserId) {+ await this.giftReversalHandler.handleGiftPremiumReversal(giftCode, {reason: 'gift_chargeback'});+ const redeemer = await this.userRepository.findUnique(giftCode.redeemedByUserId);+ if (redeemer?.email) {+ await this.emailService.send('gift_chargeback_notification', redeemer.email, {}, redeemer.locale);}Logger.debug(- {userId: payment.userId},- 'User unsuspended after chargeback withdrawal - 30 day self-serve refund cooldown applied',+ {giftCode: giftCode.code, redeemerId: giftCode.redeemedByUserId},+ 'Premium taken back after a lost gift dispute',+ );+ } else if (!giftCode.revokedAt) {+ await this.userRepository.revokeGiftCode(giftCode.code);+ Logger.debug(+ {giftCode: giftCode.code, chargeId: extractId(dispute.charge)},+ 'Revoked unredeemed gift code after a lost dispute',);}}+ private async cancelAutomaticDisputeDeletion(userId: UserID): Promise<void> {+ const user = await this.userRepository.findUnique(userId);+ if (+ !user ||+ !(user.flags & UserFlags.DELETED) ||+ user.deletionReasonCode !== DeletionReasons.BILLING_DISPUTE_OR_ABUSE ||+ (user.deletionScheduledBy !== null && user.deletionScheduledBy !== SYSTEM_USER_ID) ||+ user.enforcementDecisionId !== null+ ) {+ return;+ }+ const updatedUser = await this.userRepository.updateDeletionSchedule(user, {+ flags: user.flags & ~UserFlags.DELETED,+ pending_deletion_at: null,+ deletion_reason_code: null,+ deletion_public_reason: null,+ deletion_audit_log_reason: null,+ });+ await followOperatorPassWallStanding(user, updatedUser);+ await clearPendingDeletion({userId, deletionQueue: this.kvDeletionQueue});+ await this.userCacheService.setUserPartialResponseFromUser(updatedUser);+ if (updatedUser.email) {+ await this.emailService.send('account_deletion_cancelled', updatedUser.email, {}, updatedUser.locale);+ }+ Logger.info({userId}, 'Cancelled an automatic deletion scheduled for a payment dispute');+ }++ private async findOperatorPassPurchase(paymentIntentId: string): Promise<OperatorPassPurchaseRow | null> {+ return (await this.operatorPassFulfilment?.findPurchaseByPaymentIntent(paymentIntentId)) ?? null;+ }+private async resolveDisputeCustomerId(dispute: Stripe.Dispute): Promise<string | null> {const expandedCharge = typeof dispute.charge === 'object' ? dispute.charge : null;if (expandedCharge) {@@ -150,20 +361,17 @@ export class StripeDisputeWebhookHandler {return mirroredCharge?.customer_id ?? null;}- private async findDonorForDispute(dispute: Stripe.Dispute): Promise<Donor | null> {- const customerId = await this.resolveDisputeCustomerId(dispute);- if (!customerId) {- return null;- }- return await this.donationRepository.findDonorByStripeCustomerId(customerId);- }-async handleRefund(charge: Stripe.Charge): Promise<void> {const paymentIntentId = extractId(charge.payment_intent);if (!paymentIntentId) {Logger.error({chargeId: charge.id}, 'Refund missing payment intent');throw new StripeError('Refund missing payment intent');}+ const operatorPassPurchase = await this.findOperatorPassPurchase(paymentIntentId);+ if (operatorPassPurchase && this.operatorPassFulfilment) {+ await this.operatorPassFulfilment.handleChargeRefunded(operatorPassPurchase, charge);+ return;+ }const giftCode = await this.userRepository.findGiftCodeByPaymentIntent(paymentIntentId);if (giftCode) {if (giftCode.redeemedByUserId) {@@ -178,176 +386,11 @@ export class StripeDisputeWebhookHandler {return;}const payment = await this.userRepository.getPaymentByPaymentIntent(paymentIntentId);- let user: User;if (payment) {- const foundUser = await this.userRepository.findUnique(payment.userId);- if (!foundUser) {- Logger.error({userId: payment.userId, chargeId: charge.id}, 'User not found for refund');- throw new StripeError('User not found for refund');- }await this.userRepository.updatePayment({...payment.toRow(),status: 'refunded',});- user = foundUser;- } else {- const customerId = extractId(charge.customer);- if (!customerId) {- Logger.error(- {paymentIntentId, chargeId: charge.id},- 'No payment found for refund and charge has no customer ID',- );- throw new StripeError('No payment found for refund');- }- const donor = await this.donationRepository.findDonorByStripeCustomerId(customerId);- if (donor) {- Logger.info({customerId, chargeId: charge.id}, 'Refund for donation customer - no premium action required');- return;- }- const foundUser = await this.userRepository.findByStripeCustomerId(customerId);- if (!foundUser) {- Logger.error({customerId, paymentIntentId, chargeId: charge.id}, 'No user found for refund by customer ID');- throw new StripeError('No user found for refund');- }- Logger.debug(- {userId: foundUser.id, paymentIntentId, chargeId: charge.id},- 'Processing refund via customer ID (payment intent not indexed)',- );- user = foundUser;- }- const claimKeys = await this.resolveRefundAllowanceClaimKeys(charge);- if (claimKeys.length === 0) {- Logger.debug(- {userId: user.id, chargeId: charge.id, paymentIntentId},- 'Refund was issued by Fluxer - not counted against the user refund allowance',- );- return;}- const claimedKeys: Array<string> = [];- let alreadyCounted = false;- for (const claimKey of claimKeys) {- const claim = await getBillingRepository().webhookEvents.tryClaim(claimKey);- if (claim === 'claimed') {- claimedKeys.push(claimKey);- } else {- alreadyCounted = true;- }- }- if (alreadyCounted) {- for (const claimKey of claimedKeys) {- await getBillingRepository().webhookEvents.markProcessed(claimKey);- }- Logger.debug(- {userId: user.id, chargeId: charge.id, paymentIntentId, claimKeys},- 'Refund already counted against the user refund allowance',- );- return;- }- const isFirstRefund = !user.firstRefundAt;- let patch: Partial<UserRow>;- let countedRefundIds: Array<string> = [];- if (isFirstRefund) {- patch = {first_refund_at: new Date()};- } else {- const outcome = await shouldBlockFurtherPurchases(user, this.userRepository);- countedRefundIds = outcome.countedRefundIds;- if (!outcome.blocked) {- for (const claimKey of claimedKeys) {- await getBillingRepository().webhookEvents.markProcessed(claimKey);- }- Logger.info(- {userId: user.id, chargeId: charge.id, paymentIntentId, countedRefundIds},- 'Refund redelivered after the allowance claim expired; not counting it twice',- );- return;- }- patch = {premium_flags: user.premiumFlags | PremiumFlags.PURCHASE_DISABLED};- }- let updatedUser: User;- try {- updatedUser = await this.userRepository.patchUpsert(user.id, patch, user.toRow());- } catch (error) {- for (const claimKey of claimedKeys) {- await getBillingRepository().webhookEvents.releaseClaim(claimKey);- }- throw error;- }- for (const claimKey of claimedKeys) {- await getBillingRepository().webhookEvents.markProcessed(claimKey);- }- await dispatchUserUpdate(this.gatewayService, updatedUser);- Logger.debug(- {userId: user.id, chargeId: charge.id, paymentIntentId, countedRefundIds},- isFirstRefund- ? 'First refund recorded - 30 day self-serve refund cooldown applied'- : 'Second refund recorded - permanent purchase block applied',- );- }-- private async resolveRefundAllowanceClaimKeys(charge: Stripe.Charge): Promise<Array<string>> {- const chargeClaimKey = `${REFUND_ALLOWANCE_CLAIM_PREFIX}:${charge.id}`;- const inlined = charge.refunds?.data ?? [];- const refunds = (- inlined.length > 0- ? inlined.map((refund) => ({- id: refund.id,- createdAtMs: refund.created * 1000,- status: refund.status,- rejectionReason: refund.metadata?.rejection_reason ?? null,- }))- : (await getBillingRepository().refunds.listByCharge(charge.id)).map((row) => ({- id: row.provider_id,- createdAtMs: row.stripe_created_at?.getTime() ?? 0,- status: row.status,- rejectionReason: row.metadata?.get('rejection_reason') ?? null,- }))- ).filter((refund) => refund.status !== 'failed' && refund.status !== 'canceled');- if (refunds.length === 0) {- Logger.warn(- {chargeId: charge.id},- 'No refund records found for refunded charge; counting the charge once against the user refund allowance',- );- return [chargeClaimKey];- }- const customerRefunds = refunds- .filter((refund) => refund.rejectionReason === null)- .sort((left, right) => left.createdAtMs - right.createdAtMs || left.id.localeCompare(right.id));- const earliest = customerRefunds[0];- const latest = customerRefunds[customerRefunds.length - 1];- if (!earliest || !latest) {- return [];- }- const latestClaimKey = `${REFUND_ALLOWANCE_CLAIM_PREFIX}:${latest.id}`;- return latest.id === earliest.id ? [chargeClaimKey, latestClaimKey] : [latestClaimKey];- }-- private async handleGiftChargeback(giftCode: GiftCode, dispute: Stripe.Dispute): Promise<void> {- if (giftCode.redeemedByUserId) {- await this.giftReversalHandler.handleGiftPremiumReversal(giftCode, {reason: 'gift_chargeback'});- const redeemer = await this.userRepository.findUnique(giftCode.redeemedByUserId);- if (redeemer?.email) {- await this.emailService.sendGiftChargebackNotification(redeemer.email, redeemer.username, redeemer.locale);- }- Logger.debug(- {giftCode: giftCode.code, redeemerId: giftCode.redeemedByUserId},- 'Premium revoked due to gift chargeback',- );- } else if (!giftCode.revokedAt) {- await this.userRepository.revokeGiftCode(giftCode.code);- Logger.debug(- {giftCode: giftCode.code, chargeId: extractId(dispute.charge)},- 'Revoked unredeemed gift code after chargeback',- );- }- await this.paymentFraudService.limitPurchasesForFraudSignal({- userId: giftCode.createdByUserId,- source: 'chargeback',- signalId: extractId(dispute.charge) ?? dispute.id,- chargeId: extractId(dispute.charge),- paymentIntentId: giftCode.stripePaymentIntentId,- customerId: null,- fraudType: null,- paymentAt: await this.paymentFraudService.resolvePaymentTime(giftCode.stripePaymentIntentId, giftCode.createdAt),- });}}