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 6 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
8 changes: 5 additions & 3 deletions src/api/repository/paymentMethod.repo.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
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()
Expand All @@ -12,7 +12,9 @@ export class PaymentMethodRepository {
* @param userId user id
* @param tx transaction
*/
async hasVerifiedPaymentMethod(userId: string): Promise<boolean> {
async hasVerifiedPaymentMethod(
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 please rename this to getConnectedPaymentMethod as it is more explainatory and makes sense after recent changes.

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;
}
}
93 changes: 86 additions & 7 deletions src/api/webhooks/trolley/handlers/payment.handler.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,90 @@
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}`,
);
}

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
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, IsString } 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()
@IsString({ each: true })
Copy link
Contributor

Choose a reason for hiding this comment

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

Probably we could refactor this a bit by using @IsUUID decorator as payment IDs are UUIDs?

@IsNotEmpty({ each: true })
paymentIds: 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.paymentIds,
);
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