Skip to content

PM-1099 withdraw action #45

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
May 7, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions prisma/migrations/20250506093230_new_payment_status/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
-- AlterEnum
-- This migration adds more than one value to an enum.
-- With PostgreSQL versions 11 and earlier, this is not possible
-- in a single migration. This can be worked around by creating
-- multiple migrations, each migration adding only one value to
-- the enum.


ALTER TYPE "payment_status" ADD VALUE 'FAILED';
ALTER TYPE "payment_status" ADD VALUE 'RETURNED';
2 changes: 2 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,8 @@ enum payment_status {
OWED
PROCESSING
CANCELLED
FAILED
RETURNED
}

enum reference_type {
Expand Down
2 changes: 2 additions & 0 deletions src/api/api.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { AdminModule } from './admin/admin.module';
import { WinningsModule } from './winnings/winnings.module';
import { UserModule } from './user/user.module';
import { WalletModule } from './wallet/wallet.module';
import { WithdrawalModule } from './withdrawal/withdrawal.module';

@Module({
imports: [
Expand All @@ -26,6 +27,7 @@ import { WalletModule } from './wallet/wallet.module';
WinningsModule,
UserModule,
WalletModule,
WithdrawalModule,
],
controllers: [HealthCheckController],
providers: [
Expand Down
10 changes: 6 additions & 4 deletions src/api/repository/paymentMethod.repo.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
import { Injectable } from '@nestjs/common';
import { payment_method_status } from '@prisma/client';
import { payment_method_status, user_payment_methods } from '@prisma/client';
import { PrismaService } from 'src/shared/global/prisma.service';

@Injectable()
export class PaymentMethodRepository {
constructor(private readonly prisma: PrismaService) {}

/**
* Check user has verified payment method
* Get the user's connected payment method (if there is one)
*
* @param userId user id
* @param tx transaction
*/
async hasVerifiedPaymentMethod(userId: string): Promise<boolean> {
async getConnectedPaymentMethod(
userId: string,
): Promise<user_payment_methods | null> {
const connectedUserPaymentMethod =
await this.prisma.user_payment_methods.findFirst({
where: {
Expand All @@ -21,6 +23,6 @@ export class PaymentMethodRepository {
},
});

return !!connectedUserPaymentMethod;
return connectedUserPaymentMethod;
}
}
9 changes: 5 additions & 4 deletions src/api/wallet/wallet.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,9 @@ export class WalletService {
const winnings = await this.getWinningsTotalsByWinnerID(userId);

const hasActiveTaxForm = await this.taxFormRepo.hasActiveTaxForm(userId);
const hasVerifiedPaymentMethod =
await this.paymentMethodRepo.hasVerifiedPaymentMethod(userId);
const hasVerifiedPaymentMethod = Boolean(
await this.paymentMethodRepo.getConnectedPaymentMethod(userId),
);

const winningTotals: WalletDetailDto = {
account: {
Expand All @@ -62,10 +63,10 @@ export class WalletService {
],
},
withdrawalMethod: {
isSetupComplete: Boolean(hasVerifiedPaymentMethod),
isSetupComplete: hasVerifiedPaymentMethod,
},
taxForm: {
isSetupComplete: Boolean(hasActiveTaxForm),
isSetupComplete: hasActiveTaxForm,
},
};

Expand Down
94 changes: 87 additions & 7 deletions src/api/webhooks/trolley/handlers/payment.handler.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,91 @@
import { Injectable } from '@nestjs/common';
// import { WebhookEvent } from '../../webhooks.decorators';
import { Injectable, Logger } from '@nestjs/common';
import {
PaymentProcessedEventData,
PaymentProcessedEventStatus,
PaymentWebhookEvent,
} from './payment.types';
import { WebhookEvent } from '../../webhooks.decorators';
import { PaymentsService } from 'src/shared/payments';
import { payment_status } from '@prisma/client';
import { PrismaService } from 'src/shared/global/prisma.service';
import { JsonObject } from '@prisma/client/runtime/library';

@Injectable()
export class PaymentHandler {
// @WebhookEvent(TrolleyWebhookEvent.paymentCreated)
// async handlePaymentCreated(payload: any): Promise<any> {
// // TODO: Build out logic for payment.created event
// console.log('handling', TrolleyWebhookEvent.paymentCreated);
// }
private readonly logger = new Logger(PaymentHandler.name);

constructor(
private readonly prisma: PrismaService,
private readonly paymentsService: PaymentsService,
) {}

@WebhookEvent(
PaymentWebhookEvent.processed,
PaymentWebhookEvent.failed,
PaymentWebhookEvent.returned,
)
async handlePaymentProcessed(
payload: PaymentProcessedEventData,
): Promise<any> {
// TODO: remove slice-1
const winningIds = (payload.externalId ?? '').split(',').slice(0, -1);
const externalTransactionId = payload.batch.id;

if (!winningIds.length) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code should throw here. Noting of the following logic will or shouldn't work without winningIds.
Agian, why we call those winnings as they are actually payment IDs? Can we update all of the refs and service signatures to reflect that?

this.logger.error(
`No valid winning IDs found in the externalId: ${payload.externalId}`,
);
throw new Error('No valid winning IDs found in the externalId!');
}

if (payload.status !== PaymentProcessedEventStatus.PROCESSED) {
await this.updatePaymentStates(
winningIds,
externalTransactionId,
payload.status.toUpperCase() as payment_status,
payload.status.toUpperCase(),
{ failureMessage: payload.failureMessage },
);

return;
}

await this.updatePaymentStates(
winningIds,
externalTransactionId,
payment_status.PAID,
'PROCESSED',
);
}

private async updatePaymentStates(
winningIds: string[],
paymentId: string,
processingState: payment_status,
releaseState: string,
metadata?: JsonObject,
): Promise<void> {
try {
await this.prisma.$transaction(async (tx) => {
await this.paymentsService.updatePaymentProcessingState(
winningIds,
processingState,
tx,
);

await this.paymentsService.updatePaymentReleaseState(
paymentId,
releaseState,
tx,
metadata,
);
});
} catch (error) {
this.logger.error(
`Failed to update payment states for paymentId: ${paymentId}, winnings: ${winningIds.join(',')}, error: ${error.message}`,
error.stack,
);
throw error;
}
}
}
30 changes: 30 additions & 0 deletions src/api/webhooks/trolley/handlers/payment.types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
export enum PaymentWebhookEvent {
processed = 'payment.processed',
failed = 'payment.failed',
returned = 'payment.returned',
}

export enum PaymentProcessedEventStatus {
PROCESSED = 'processed',
FAILED = 'failed',
RETURNED = 'returned',
}

export interface PaymentProcessedEventData {
id: string;
recipient: {
id: string;
referenceId: string;
email: string;
};
status: PaymentProcessedEventStatus;
externalId?: string;
sourceAmount: string; // gross amount
fees: string;
targetAmount: string; // net amount
failureMessage: string | null;
memo: string | null;
batch: {
id: string;
};
}
20 changes: 18 additions & 2 deletions src/api/webhooks/trolley/trolley.service.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import crypto from 'crypto';
import { Inject, Injectable } from '@nestjs/common';
import { Inject, Injectable, Logger } from '@nestjs/common';
import { trolley_webhook_log, webhook_status } from '@prisma/client';
import { PrismaService } from 'src/shared/global/prisma.service';
import { ENV_CONFIG } from 'src/config';
Expand All @@ -20,6 +20,8 @@ if (!trolleyWhHmac) {
*/
@Injectable()
export class TrolleyService {
private readonly logger = new Logger('Webhooks/TrolleyService');

constructor(
@Inject('trolleyHandlerFns')
private readonly handlers: Map<
Expand Down Expand Up @@ -118,22 +120,36 @@ export class TrolleyService {
*/
async handleEvent(headers: Request['headers'], payload: any) {
const requestId = headers[TrolleyHeaders.id];
this.logger.debug(`Received webhook event with ID: ${requestId}`);

try {
await this.setEventState(requestId, webhook_status.logged, payload, {
event_time: headers[TrolleyHeaders.created],
});

const { model, action, body } = payload;
this.logger.debug(`Processing event - ${requestId} - ${model}.${action}`);

const handler = this.handlers.get(`${model}.${action}`);
// do nothing if there's no handler for the event (event was logged in db)
if (!handler) {
this.logger.debug(
`No handler found for event - ${requestId} - ${model}.${action}. Event logged but not processed.`,
);
return;
}

this.logger.debug(
`Invoking handler for event - ${requestId} - ${model}.${action}`,
);
await handler(body[model]);

this.logger.debug(`Successfully processed event with ID: ${requestId}`);
await this.setEventState(requestId, webhook_status.processed);
} catch (e) {
this.logger.error(
`Error processing event with ID: ${requestId} - ${e.message ?? e}`,
e.stack,
);
await this.setEventState(requestId, webhook_status.error, void 0, {
error_message: e.message ?? e,
});
Expand Down
7 changes: 4 additions & 3 deletions src/api/winnings/winnings.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,9 @@ export class WinningsService {
const hasActiveTaxForm = await this.taxFormRepo.hasActiveTaxForm(
body.winnerId,
);
const hasPaymentMethod =
await this.paymentMethodRepo.hasVerifiedPaymentMethod(body.winnerId);
const hasConnectedPaymentMethod = Boolean(
await this.paymentMethodRepo.getConnectedPaymentMethod(body.winnerId),
);

for (const detail of body.details || []) {
const paymentModel = {
Expand All @@ -90,7 +91,7 @@ export class WinningsService {

paymentModel.net_amount = Prisma.Decimal(detail.grossAmount);
paymentModel.payment_status =
hasPaymentMethod && hasActiveTaxForm
hasConnectedPaymentMethod && hasActiveTaxForm
? PaymentStatus.OWED
: PaymentStatus.ON_HOLD;

Expand Down
14 changes: 14 additions & 0 deletions src/api/withdrawal/dto/withdraw.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { ApiProperty } from '@nestjs/swagger';
import { ArrayNotEmpty, IsArray, IsNotEmpty, IsUUID } from 'class-validator';

export class WithdrawRequestDto {
@ApiProperty({
description: 'The ID of the winnings to withdraw',
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we rename winnings to payments?

example: ['3fa85f64-5717-4562-b3fc-2c963f66afa6'],
})
@IsArray()
@ArrayNotEmpty()
@IsUUID('4',{ each: true })
@IsNotEmpty({ each: true })
winningsIds: string[];
}
65 changes: 65 additions & 0 deletions src/api/withdrawal/withdrawal.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import {
Controller,
Post,
HttpCode,
HttpStatus,
Body,
BadRequestException,
} from '@nestjs/common';
import {
ApiOperation,
ApiTags,
ApiResponse,
ApiBearerAuth,
ApiBody,
} from '@nestjs/swagger';

import { Role } from 'src/core/auth/auth.constants';
import { Roles, User } from 'src/core/auth/decorators';
import { UserInfo } from 'src/dto/user.type';
import { ResponseDto, ResponseStatusType } from 'src/dto/api-response.dto';

import { WithdrawalService } from './withdrawal.service';
import { WithdrawRequestDto } from './dto/withdraw.dto';

@ApiTags('Withdrawal')
@Controller('/withdraw')
@ApiBearerAuth()
export class WithdrawalController {
constructor(private readonly withdrawalService: WithdrawalService) {}

@Post()
@Roles(Role.User)
@ApiOperation({
summary: 'User call this operation to process withdrawal.',
description: 'jwt required.',
})
@ApiBody({
description: 'Request body',
type: WithdrawRequestDto,
})
@ApiResponse({
status: 200,
description: 'Operation successful.',
type: ResponseDto<string>,
})
@HttpCode(HttpStatus.OK)
async doWithdraw(
@User() user: UserInfo,
@Body() body: WithdrawRequestDto,
): Promise<ResponseDto<string>> {
const result = new ResponseDto<string>();

try {
await this.withdrawalService.withdraw(
user.id,
user.handle,
body.winningsIds,
);
result.status = ResponseStatusType.SUCCESS;
return result;
} catch (e) {
throw new BadRequestException(e.message);
}
}
}
13 changes: 13 additions & 0 deletions src/api/withdrawal/withdrawal.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { PaymentsModule } from 'src/shared/payments';
import { WithdrawalController } from './withdrawal.controller';
import { WithdrawalService } from './withdrawal.service';
import { TaxFormRepository } from '../repository/taxForm.repo';
import { PaymentMethodRepository } from '../repository/paymentMethod.repo';

@Module({
imports: [PaymentsModule],
controllers: [WithdrawalController],
providers: [WithdrawalService, TaxFormRepository, PaymentMethodRepository],
})
export class WithdrawalModule {}
Loading