Skip to content

Pm 1345 trolley trust module #71

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 4 commits into from
Jun 16, 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
-- CreateEnum
CREATE TYPE "verification_status" AS ENUM ('ACTIVE', 'INACTIVE');

-- CreateTable
CREATE TABLE "user_identity_verification_associations" (
"id" UUID NOT NULL DEFAULT uuid_generate_v4(),
"user_id" VARCHAR(80) NOT NULL,
"verification_id" TEXT NOT NULL,
"date_filed" TIMESTAMP(6) WITHOUT TIME ZONE NOT NULL,

Choose a reason for hiding this comment

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

medium
correctness
Ensure that the date_filed column is set to the correct time zone if your application requires time zone awareness. Using TIMESTAMP WITHOUT TIME ZONE might lead to inconsistencies if time zones are not handled properly in the application logic.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

@kkartunov do we really want this to be without timezone?

"verification_status" "verification_status" NOT NULL,

CONSTRAINT "user_identity_verification_associations_pkey" PRIMARY KEY ("id")
);
13 changes: 13 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -207,13 +207,26 @@ model trolley_webhook_log {
created_at DateTime? @default(now()) @db.Timestamp(6)
}

model user_identity_verification_associations {
id String @id @default(dbgenerated("uuid_generate_v4()")) @db.Uuid
user_id String @db.VarChar(80)
verification_id String @db.Text
date_filed DateTime @db.Timestamp(6)
verification_status verification_status
}

model trolley_recipient_payment_method {
id String @id @default(dbgenerated("uuid_generate_v4()")) @db.Uuid
trolley_recipient_id Int
recipient_account_id String @unique @db.VarChar(80)
trolley_recipient trolley_recipient @relation(fields: [trolley_recipient_id], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "fk_trolley_recipient_trolley_recipient_payment_method")
}

enum verification_status {
ACTIVE
INACTIVE
}

enum action_type {
INITIATE_WITHDRAWAL
ADD_WITHDRAWAL_METHOD
Expand Down
26 changes: 26 additions & 0 deletions src/api/repository/identity-verification.repo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Injectable } from '@nestjs/common';
import { verification_status } from '@prisma/client';
import { PrismaService } from 'src/shared/global/prisma.service';

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

/**
* Checks if the user has completed their identity verification by checking the identity verification associations
*
* @param userId - The unique identifier of the user.
* @returns A promise that resolves to `true` if the user has at least one active identity verification association, otherwise `false`.
*/
async completedIdentityVerification(userId: string): Promise<boolean> {
const count =
await this.prisma.user_identity_verification_associations.count({
where: {
user_id: userId,
verification_status: verification_status.ACTIVE,
},
});

return count > 0;
}
}
23 changes: 22 additions & 1 deletion src/api/user/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,19 @@ import { ResponseDto, ResponseStatusType } from 'src/dto/api-response.dto';
import { SearchWinningResult, WinningRequestDto } from 'src/dto/winning.dto';
import { UserInfo } from 'src/dto/user.type';
import { UserWinningRequestDto } from './dto/user.dto';
import { PaymentsService } from 'src/shared/payments';
import { Logger } from 'src/shared/global';

@ApiTags('UserWinning')
@Controller('/user')
@ApiBearerAuth()
export class UserController {
constructor(private readonly winningsRepo: WinningsRepository) {}
private readonly logger = new Logger(UserController.name);

constructor(
private readonly winningsRepo: WinningsRepository,
private readonly paymentsService: PaymentsService,
) {}

@Post('/winnings')
@Roles(Role.User)
Expand Down Expand Up @@ -59,6 +66,20 @@ export class UserController {
throw new ForbiddenException('insufficient permissions');
}

try {
await this.paymentsService.reconcileUserPayments(user.id);
} catch (e) {
this.logger.error('Error reconciling user payments', e);

Choose a reason for hiding this comment

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

medium
maintainability
Consider including more context in the error log, such as the user ID, to aid in debugging.


return {
error: {
code: HttpStatus.INTERNAL_SERVER_ERROR,
message: 'Failed to reconcile user payments.',
},
status: ResponseStatusType.ERROR,
} as ResponseDto<SearchWinningResult>;
}

const result = await this.winningsRepo.searchWinnings(
body as WinningRequestDto,
);
Expand Down
3 changes: 2 additions & 1 deletion src/api/user/user.module.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { Module } from '@nestjs/common';
import { UserController } from './user.controller';
import { WinningsRepository } from '../repository/winnings.repo';
import { PaymentsModule } from 'src/shared/payments';

@Module({
imports: [],
imports: [PaymentsModule],
controllers: [UserController],
providers: [WinningsRepository],
})
Expand Down
8 changes: 7 additions & 1 deletion src/api/wallet/wallet.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,16 @@ import { WalletController } from './wallet.controller';
import { WalletService } from './wallet.service';
import { TaxFormRepository } from '../repository/taxForm.repo';
import { PaymentMethodRepository } from '../repository/paymentMethod.repo';
import { IdentityVerificationRepository } from '../repository/identity-verification.repo';

@Module({
imports: [],
controllers: [WalletController],
providers: [WalletService, TaxFormRepository, PaymentMethodRepository],
providers: [
WalletService,
TaxFormRepository,
PaymentMethodRepository,
IdentityVerificationRepository,
],
})
export class WalletModule {}
9 changes: 9 additions & 0 deletions src/api/wallet/wallet.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
TrolleyService,
} from 'src/shared/global/trolley.service';
import { Logger } from 'src/shared/global';
import { IdentityVerificationRepository } from '../repository/identity-verification.repo';

/**
* The winning service.
Expand All @@ -28,6 +29,7 @@ export class WalletService {
private readonly prisma: PrismaService,
private readonly taxFormRepo: TaxFormRepository,
private readonly paymentMethodRepo: PaymentMethodRepository,
private readonly identityVerificationRepo: IdentityVerificationRepository,
private readonly trolleyService: TrolleyService,
) {}

Expand Down Expand Up @@ -57,6 +59,10 @@ export class WalletService {
const winnings = await this.getWinningsTotalsByWinnerID(userId);

const hasActiveTaxForm = await this.taxFormRepo.hasActiveTaxForm(userId);
const isIdentityVerified =
await this.identityVerificationRepo.completedIdentityVerification(
userId,
);
const hasVerifiedPaymentMethod = Boolean(
await this.paymentMethodRepo.getConnectedPaymentMethod(userId),
);
Expand Down Expand Up @@ -91,6 +97,9 @@ export class WalletService {
taxForm: {
isSetupComplete: hasActiveTaxForm,
},
identityVerification: {
isSetupComplete: isIdentityVerified,
},
...(taxWithholdingDetails ?? {}),
};
} catch (error) {
Expand Down
17 changes: 15 additions & 2 deletions src/api/webhooks/trolley/handlers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { PaymentHandler } from './payment.handler';
import { TaxFormHandler } from './tax-form.handler';
import { getWebhooksEventHandlersProvider } from '../../webhooks.event-handlers.provider';
import { RecipientAccountHandler } from './recipient-account.handler';
import { RecipientVerificationHandler } from './recipient-verification.handler';

export const TrolleyWebhookHandlers: Provider[] = [
getWebhooksEventHandlersProvider(
Expand All @@ -12,14 +13,26 @@ export const TrolleyWebhookHandlers: Provider[] = [

PaymentHandler,
RecipientAccountHandler,
RecipientVerificationHandler,
TaxFormHandler,
{
provide: 'TrolleyWebhookHandlers',
inject: [PaymentHandler, RecipientAccountHandler, TaxFormHandler],
inject: [
PaymentHandler,
RecipientAccountHandler,
RecipientVerificationHandler,
TaxFormHandler,
],
useFactory: (
paymentHandler: PaymentHandler,
recipientAccountHandler: RecipientAccountHandler,
recipientVerificationHandler: RecipientVerificationHandler,
taxFormHandler: TaxFormHandler,
) => [paymentHandler, recipientAccountHandler, taxFormHandler],
) => [
paymentHandler,
recipientAccountHandler,
recipientVerificationHandler,
taxFormHandler,
],
},
];
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { Injectable } from '@nestjs/common';
import { WebhookEvent } from '../../webhooks.decorators';
import { PrismaService } from 'src/shared/global/prisma.service';
import { PaymentsService } from 'src/shared/payments';
import { Logger } from 'src/shared/global';
import {
RecipientVerificationStatusUpdateEventData,
RecipientVerificationWebhookEvent,
} from './recipient-verification.types';
import { Prisma, verification_status } from '@prisma/client';

@Injectable()
export class RecipientVerificationHandler {
private readonly logger = new Logger(RecipientVerificationHandler.name);

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

@WebhookEvent(RecipientVerificationWebhookEvent.statusUpdated)
async handleStatusUpdated(
payload: RecipientVerificationStatusUpdateEventData,
): Promise<void> {
const recipient = await this.prisma.trolley_recipient.findFirst({
where: { trolley_id: payload.recipientId },
});

if (!recipient) {
this.logger.error(
`Recipient with trolley_id ${payload.recipientId} not found.`,
);
throw new Error(
`Recipient with trolley_id ${payload.recipientId} not found.`,
);
}

const userIDV =
await this.prisma.user_identity_verification_associations.findFirst({
where: {
user_id: recipient.user_id,
},
});

const verificationData: Prisma.user_identity_verification_associationsCreateInput =
{
user_id: recipient.user_id,
verification_id: payload.id,
date_filed: payload.submittedAt ?? new Date(),
verification_status:
payload.status === 'approved'
? verification_status.ACTIVE
: verification_status.INACTIVE,
};

if (userIDV) {
await this.prisma.user_identity_verification_associations.update({
where: {
id: userIDV.id,
},
data: { ...verificationData },
});
} else {
await this.prisma.user_identity_verification_associations.create({
data: { ...verificationData },
});
}

await this.paymentsService.reconcileUserPayments(recipient.user_id);
}
}
21 changes: 21 additions & 0 deletions src/api/webhooks/trolley/handlers/recipient-verification.types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
export enum RecipientVerificationWebhookEvent {
statusUpdated = 'recipientVerification.status_updated',
}

export interface RecipientVerificationStatusUpdateEventData {
type: string;
recipientId: string;
status: 'pending' | 'approved' | 'rejected';
createdAt: string;
updatedAt: string;
submittedAt: string | null;
decisionAt: string | null;
id: string;
reasonType: string | null;
verifiedData: {
channel: 'sms' | 'email';
phone: string;
phoneExtension: string | null;
country: string;
};
}
2 changes: 1 addition & 1 deletion src/api/webhooks/trolley/trolley.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ export class TrolleyService {
this.logger.debug(
`Invoking handler for event - ${requestId} - ${model}.${action}`,
);
await handler(body[model]);
await handler(body[model] ?? Object.values(body)?.[0]);

this.logger.debug(`Successfully processed event with ID: ${requestId}`);
await this.setEventState(requestId, webhook_status.processed);
Expand Down
2 changes: 2 additions & 0 deletions src/api/winnings/winnings.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { WinningsRepository } from '../repository/winnings.repo';
import { TaxFormRepository } from '../repository/taxForm.repo';
import { PaymentMethodRepository } from '../repository/paymentMethod.repo';
import { TopcoderModule } from 'src/shared/topcoder/topcoder.module';
import { IdentityVerificationRepository } from '../repository/identity-verification.repo';

@Module({
imports: [TopcoderModule],
Expand All @@ -16,6 +17,7 @@ import { TopcoderModule } from 'src/shared/topcoder/topcoder.module';
TaxFormRepository,
WinningsRepository,
PaymentMethodRepository,
IdentityVerificationRepository,
],
})
export class WinningsModule {}
8 changes: 7 additions & 1 deletion src/api/winnings/winnings.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { BASIC_MEMBER_FIELDS } from 'src/shared/topcoder';
import { ENV_CONFIG } from 'src/config';
import { Logger } from 'src/shared/global';
import { TopcoderEmailService } from 'src/shared/topcoder/tc-email.service';
import { IdentityVerificationRepository } from '../repository/identity-verification.repo';

/**
* The winning service.
Expand All @@ -37,6 +38,7 @@ export class WinningsService {
private readonly paymentMethodRepo: PaymentMethodRepository,
private readonly originRepo: OriginRepository,
private readonly tcMembersService: TopcoderMembersService,
private readonly identityVerificationRepo: IdentityVerificationRepository,
private readonly tcEmailService: TopcoderEmailService,
) {}

Expand Down Expand Up @@ -182,6 +184,10 @@ export class WinningsService {
const hasConnectedPaymentMethod = Boolean(
await this.paymentMethodRepo.getConnectedPaymentMethod(body.winnerId),
);
const isIdentityVerified =
await this.identityVerificationRepo.completedIdentityVerification(
userId,
);

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

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

Expand Down
8 changes: 7 additions & 1 deletion src/api/withdrawal/withdrawal.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,16 @@ import { WithdrawalService } from './withdrawal.service';
import { TaxFormRepository } from '../repository/taxForm.repo';
import { PaymentMethodRepository } from '../repository/paymentMethod.repo';
import { TopcoderModule } from 'src/shared/topcoder/topcoder.module';
import { IdentityVerificationRepository } from '../repository/identity-verification.repo';

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