mirror of
https://github.com/Tria-plc/edr-platform.git
synced 2026-08-30 09:58:12 +00:00
feat: ( payment ) integrate the passenger to payment microservice
This commit is contained in:
@@ -1,22 +1,37 @@
|
||||
import { Injectable, Logger, NotFoundException, BadRequestException } from '@nestjs/common';
|
||||
import { PrismaService } from '../../common/prisma.service';
|
||||
import { SeatsService } from '../seats/seats.service';
|
||||
import { TicketsService } from '../tickets/tickets.service';
|
||||
import { EventEmitter2 } from '@nestjs/event-emitter';
|
||||
import { Prisma, PaymentIntentStatus, PaymentMethodType, PaymentRegion } from '@prisma/client';
|
||||
import { InitiatePaymentDto, RefundDto, AddPaymentMethodDto, InitiateResponseDto, IntentStatusDto, PaymentRegionEnum } from './payments.dto';
|
||||
import {
|
||||
Injectable,
|
||||
Logger,
|
||||
NotFoundException,
|
||||
BadRequestException,
|
||||
} from "@nestjs/common";
|
||||
import { PrismaService } from "../../common/prisma.service";
|
||||
import { SeatsService } from "../seats/seats.service";
|
||||
import { TicketsService } from "../tickets/tickets.service";
|
||||
import { EventEmitter2 } from "@nestjs/event-emitter";
|
||||
import {
|
||||
Prisma,
|
||||
PaymentIntentStatus,
|
||||
PaymentMethodType,
|
||||
PaymentRegion,
|
||||
} from "@prisma/client";
|
||||
import {
|
||||
InitiatePaymentDto,
|
||||
RefundDto,
|
||||
AddPaymentMethodDto,
|
||||
InitiateResponseDto,
|
||||
IntentStatusDto,
|
||||
PaymentRegionEnum,
|
||||
} from "./payments.dto";
|
||||
import { PaymentEventDto, MarkPaidResponseDto } from "./internal-payments.dto";
|
||||
import { PaymentClientService } from "./payment-client.service";
|
||||
import {
|
||||
PaymentService as PaymentServiceEnum,
|
||||
PaymentReferenceType,
|
||||
PaymentIntentSnapshot,
|
||||
ProviderMethod,
|
||||
ClientAction,
|
||||
PaymentProvider,
|
||||
ProviderStatus,
|
||||
ProviderPaymentStatus,
|
||||
TelebirrProvider,
|
||||
CbeBirrProvider,
|
||||
EBirrProvider,
|
||||
CardProvider,
|
||||
WaafiProvider,
|
||||
createMerchantOrderId,
|
||||
} from '@edr/payment-providers';
|
||||
} from "@edr/types";
|
||||
|
||||
const NON_TERMINAL_STATUSES: PaymentIntentStatus[] = [
|
||||
PaymentIntentStatus.REQUIRES_ACTION,
|
||||
@@ -27,37 +42,30 @@ const NON_TERMINAL_STATUSES: PaymentIntentStatus[] = [
|
||||
@Injectable()
|
||||
export class PaymentsService {
|
||||
private readonly logger = new Logger(PaymentsService.name);
|
||||
private readonly providers: Map<PaymentMethodType, PaymentProvider>;
|
||||
|
||||
constructor(
|
||||
private prisma: PrismaService,
|
||||
private seatsService: SeatsService,
|
||||
private ticketsService: TicketsService,
|
||||
private eventEmitter: EventEmitter2,
|
||||
private telebirrProvider: TelebirrProvider,
|
||||
private cbeBirrProvider: CbeBirrProvider,
|
||||
private eBirrProvider: EBirrProvider,
|
||||
private cardProvider: CardProvider,
|
||||
private waafiProvider: WaafiProvider,
|
||||
) {
|
||||
this.providers = new Map<PaymentMethodType, PaymentProvider>([
|
||||
[PaymentMethodType.TELEBIRR, this.telebirrProvider],
|
||||
[PaymentMethodType.CBE_BIRR, this.cbeBirrProvider],
|
||||
[PaymentMethodType.EBIRR, this.eBirrProvider],
|
||||
[PaymentMethodType.CARD, this.cardProvider],
|
||||
[PaymentMethodType.WAAFI, this.waafiProvider],
|
||||
]);
|
||||
}
|
||||
private paymentClient: PaymentClientService,
|
||||
) {}
|
||||
|
||||
async getAll(filters: { search?: string; status?: string; method?: string; page?: number; pageSize?: number }) {
|
||||
async getAll(filters: {
|
||||
search?: string;
|
||||
status?: string;
|
||||
method?: string;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
}) {
|
||||
const { search, status, method, page = 1, pageSize = 10 } = filters;
|
||||
const skip = (page - 1) * pageSize;
|
||||
|
||||
const where: any = {};
|
||||
if (search) {
|
||||
where.OR = [
|
||||
{ id: { contains: search, mode: 'insensitive' } },
|
||||
{ booking: { bookingRef: { contains: search, mode: 'insensitive' } } },
|
||||
{ id: { contains: search, mode: "insensitive" } },
|
||||
{ booking: { bookingRef: { contains: search, mode: "insensitive" } } },
|
||||
];
|
||||
}
|
||||
if (status) {
|
||||
@@ -73,13 +81,13 @@ export class PaymentsService {
|
||||
include: { booking: true },
|
||||
skip,
|
||||
take: pageSize,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
orderBy: { createdAt: "desc" },
|
||||
}),
|
||||
this.prisma.paymentIntent.count({ where }),
|
||||
]);
|
||||
|
||||
return {
|
||||
items: items.map(item => ({
|
||||
items: items.map((item) => ({
|
||||
id: item.id,
|
||||
reference: item.id.substring(0, 8),
|
||||
bookingId: item.bookingId,
|
||||
@@ -102,30 +110,87 @@ export class PaymentsService {
|
||||
where: { id: dto.bookingId },
|
||||
include: { seats: true },
|
||||
});
|
||||
if (!booking) throw new NotFoundException('Booking not found');
|
||||
if (booking.status !== 'PENDING_PAYMENT') {
|
||||
throw new BadRequestException('Booking not payable');
|
||||
}
|
||||
|
||||
const existing = await this.prisma.paymentIntent.findUnique({
|
||||
where: { bookingId: dto.bookingId },
|
||||
});
|
||||
if (existing && NON_TERMINAL_STATUSES.includes(existing.status)) {
|
||||
return this.formatIntentResponse(existing);
|
||||
if (!booking) throw new NotFoundException("Booking not found");
|
||||
if (booking.status !== "PENDING_PAYMENT") {
|
||||
throw new BadRequestException("Booking not payable");
|
||||
}
|
||||
|
||||
const method = dto.method as PaymentMethodType;
|
||||
|
||||
// WALLET is an internal balance debit — it never leaves this app.
|
||||
if (method === PaymentMethodType.WALLET) {
|
||||
const existing = await this.prisma.paymentIntent.findUnique({
|
||||
where: { bookingId: dto.bookingId },
|
||||
});
|
||||
if (existing && NON_TERMINAL_STATUSES.includes(existing.status)) {
|
||||
return this.formatIntentResponse(existing);
|
||||
}
|
||||
return this.initiateWalletPayment(booking);
|
||||
}
|
||||
|
||||
const provider = this.providers.get(method);
|
||||
if (provider) {
|
||||
return this.initiateProviderPayment(booking, provider, dto.platform);
|
||||
}
|
||||
// Provider methods go through the payment microservice (docs/payment-service §7.1):
|
||||
// it owns the intent, the provider session, and the single webhook per provider.
|
||||
// Re-initiating is safe — the service returns the existing active intent (idempotent).
|
||||
const snapshot = await this.paymentClient.initiate({
|
||||
service: PaymentServiceEnum.PASSENGER,
|
||||
referenceType: PaymentReferenceType.BOOKING,
|
||||
referenceId: booking.id,
|
||||
orderRef: booking.bookingRef,
|
||||
amountMinor: booking.totalMinor,
|
||||
currency: booking.currency,
|
||||
provider: method as unknown as ProviderMethod,
|
||||
platform: dto.platform,
|
||||
// PASSENGER-owned browser bounce-back after the hosted page (freight passes its own).
|
||||
// UX only — payment is confirmed by the webhook/mark-paid event, never this redirect.
|
||||
returnUrl: process.env.PAYMENT_RETURN_URL || undefined,
|
||||
failureUrl: process.env.PAYMENT_FAILURE_URL || undefined,
|
||||
});
|
||||
|
||||
throw new BadRequestException(`Unsupported payment method: ${method}`);
|
||||
let intent = await this.syncIntentProjection(booking.id, snapshot);
|
||||
if (snapshot.status === ProviderPaymentStatus.SUCCEEDED) {
|
||||
// Already-paid order re-initiated: converge the booking now (idempotent).
|
||||
await this.finalizePaymentSuccess({
|
||||
intentId: intent.id,
|
||||
providerTxnId: snapshot.providerTxnId,
|
||||
paidAt: snapshot.paidAt ? new Date(snapshot.paidAt) : undefined,
|
||||
});
|
||||
intent = await this.prisma.paymentIntent.findUniqueOrThrow({
|
||||
where: { id: intent.id },
|
||||
});
|
||||
}
|
||||
return this.formatIntentResponse(intent);
|
||||
}
|
||||
|
||||
private async syncIntentProjection(
|
||||
bookingId: string,
|
||||
snapshot: PaymentIntentSnapshot,
|
||||
) {
|
||||
const status =
|
||||
snapshot.status === ProviderPaymentStatus.SUCCEEDED
|
||||
? PaymentIntentStatus.PROCESSING
|
||||
: (snapshot.status as unknown as PaymentIntentStatus);
|
||||
const data = {
|
||||
status,
|
||||
method: snapshot.provider as unknown as PaymentMethodType,
|
||||
merchantOrderId: snapshot.merchantOrderId,
|
||||
clientAction: snapshot.clientAction
|
||||
? (snapshot.clientAction as unknown as Prisma.InputJsonValue)
|
||||
: Prisma.DbNull,
|
||||
providerTxnId: snapshot.providerTxnId ?? null,
|
||||
expiresAt: snapshot.expiresAt ? new Date(snapshot.expiresAt) : null,
|
||||
failureCode: snapshot.failureCode ?? null,
|
||||
failureMessage: snapshot.failureMessage ?? null,
|
||||
};
|
||||
return this.prisma.paymentIntent.upsert({
|
||||
where: { bookingId },
|
||||
update: data,
|
||||
create: {
|
||||
bookingId,
|
||||
amountMinor: snapshot.amountMinor,
|
||||
currency: snapshot.currency,
|
||||
...data,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private async initiateWalletPayment(
|
||||
@@ -146,7 +211,7 @@ export class PaymentsService {
|
||||
await tx.walletLedgerEntry.create({
|
||||
data: {
|
||||
walletId: wallet.id,
|
||||
type: 'DEBIT',
|
||||
type: "DEBIT",
|
||||
amountMinor: booking.totalMinor,
|
||||
balanceAfterMinor: newBalance,
|
||||
description: `Train Ticket - ${booking.bookingRef}`,
|
||||
@@ -161,14 +226,14 @@ export class PaymentsService {
|
||||
where: { bookingId: booking.id },
|
||||
update: {
|
||||
status: PaymentIntentStatus.FAILED,
|
||||
failureCode: 'INSUFFICIENT_BALANCE',
|
||||
failureCode: "INSUFFICIENT_BALANCE",
|
||||
},
|
||||
create: {
|
||||
bookingId: booking.id,
|
||||
amountMinor: booking.totalMinor,
|
||||
method: PaymentMethodType.WALLET,
|
||||
status: PaymentIntentStatus.FAILED,
|
||||
failureCode: 'INSUFFICIENT_BALANCE',
|
||||
failureCode: "INSUFFICIENT_BALANCE",
|
||||
},
|
||||
});
|
||||
return this.formatIntentResponse(failed);
|
||||
@@ -192,55 +257,11 @@ export class PaymentsService {
|
||||
return this.formatIntentResponse(refreshed);
|
||||
}
|
||||
|
||||
private async initiateProviderPayment(
|
||||
booking: Prisma.BookingGetPayload<{ include: { seats: true } }>,
|
||||
provider: PaymentProvider,
|
||||
platform: 'web' | 'mobile' | undefined,
|
||||
): Promise<InitiateResponseDto> {
|
||||
const merchantOrderId = createMerchantOrderId();
|
||||
const result = await provider.initiate({
|
||||
merchantOrderId,
|
||||
orderRef: booking.bookingRef,
|
||||
amountMinor: booking.totalMinor,
|
||||
currency: booking.currency,
|
||||
platform,
|
||||
});
|
||||
|
||||
const providerMethod = provider.method as unknown as PaymentMethodType;
|
||||
const intent = await this.prisma.paymentIntent.upsert({
|
||||
where: { bookingId: booking.id },
|
||||
update: {
|
||||
status: PaymentIntentStatus.REQUIRES_ACTION,
|
||||
method: providerMethod,
|
||||
merchantOrderId,
|
||||
providerOrderId: result.providerOrderId,
|
||||
clientAction: result.clientAction as unknown as Prisma.InputJsonValue,
|
||||
rawInitiation: result.rawInitiation as Prisma.InputJsonValue,
|
||||
expiresAt: result.expiresAt,
|
||||
failureCode: null,
|
||||
failureMessage: null,
|
||||
},
|
||||
create: {
|
||||
bookingId: booking.id,
|
||||
amountMinor: booking.totalMinor,
|
||||
currency: booking.currency,
|
||||
method: providerMethod,
|
||||
status: PaymentIntentStatus.REQUIRES_ACTION,
|
||||
merchantOrderId,
|
||||
providerOrderId: result.providerOrderId,
|
||||
clientAction: result.clientAction as unknown as Prisma.InputJsonValue,
|
||||
rawInitiation: result.rawInitiation as Prisma.InputJsonValue,
|
||||
expiresAt: result.expiresAt,
|
||||
},
|
||||
});
|
||||
return this.formatIntentResponse(intent);
|
||||
}
|
||||
|
||||
private formatIntentResponse(
|
||||
intent: Prisma.PaymentIntentGetPayload<Record<string, never>>,
|
||||
): InitiateResponseDto {
|
||||
const clientAction =
|
||||
intent.clientAction && typeof intent.clientAction === 'object'
|
||||
intent.clientAction && typeof intent.clientAction === "object"
|
||||
? (intent.clientAction as unknown as ClientAction)
|
||||
: undefined;
|
||||
return {
|
||||
@@ -252,65 +273,52 @@ export class PaymentsService {
|
||||
}
|
||||
|
||||
async getIntentByBookingId(bookingId: string): Promise<IntentStatusDto> {
|
||||
const intent = await this.prisma.paymentIntent.findUnique({
|
||||
const local = await this.prisma.paymentIntent.findUnique({
|
||||
where: { bookingId },
|
||||
});
|
||||
if (!intent) throw new NotFoundException('PaymentIntent not found');
|
||||
|
||||
const refreshable =
|
||||
intent.status === PaymentIntentStatus.REQUIRES_ACTION ||
|
||||
intent.status === PaymentIntentStatus.PROCESSING;
|
||||
const stale = intent.updatedAt.getTime() < Date.now() - 5_000;
|
||||
const provider = this.providers.get(intent.method);
|
||||
|
||||
if (refreshable && stale && intent.merchantOrderId && provider) {
|
||||
try {
|
||||
const status = await provider.queryStatus(intent.merchantOrderId);
|
||||
this.logger.log(status);
|
||||
await this.applyProviderStatus(intent.id, status);
|
||||
const refreshed = await this.prisma.paymentIntent.findUniqueOrThrow({
|
||||
where: { id: intent.id },
|
||||
});
|
||||
return this.formatIntentStatus(refreshed);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
this.logger.warn(
|
||||
`queryStatus failed for intent ${intent.id}: ${message}; returning cached`,
|
||||
);
|
||||
}
|
||||
// WALLET payments never leave this app — no remote intent exists for them.
|
||||
if (local?.method === PaymentMethodType.WALLET) {
|
||||
return this.formatIntentStatus(local);
|
||||
}
|
||||
|
||||
return this.formatIntentStatus(intent);
|
||||
}
|
||||
// Pull/reconcile through the payment microservice (it refreshes stale intents from the
|
||||
// provider itself). Falls back to the legacy local path when the service is unreachable
|
||||
// or only a pre-cutover local intent exists.
|
||||
let snapshot: PaymentIntentSnapshot | null = null;
|
||||
try {
|
||||
snapshot = await this.paymentClient.getIntentByReference(
|
||||
PaymentReferenceType.BOOKING,
|
||||
bookingId,
|
||||
);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
this.logger.warn(
|
||||
`payment service lookup failed for booking ${bookingId}: ${message}; using local intent`,
|
||||
);
|
||||
}
|
||||
|
||||
private async applyProviderStatus(
|
||||
intentId: string,
|
||||
status: ProviderStatus,
|
||||
): Promise<void> {
|
||||
const bizContent = (status.rawResponse as { biz_content?: { order_status?: string } })
|
||||
?.biz_content;
|
||||
if (bizContent?.order_status === 'PAY_SUCCESS') {
|
||||
if (!snapshot) {
|
||||
// Pre-cutover/local-only intent (or service briefly unreachable): serve the cached
|
||||
// status. The payment service owns provider refresh for everything initiated after
|
||||
// the cutover; webhooks/mark-paid converge the rest.
|
||||
if (!local) throw new NotFoundException("PaymentIntent not found");
|
||||
return this.formatIntentStatus(local);
|
||||
}
|
||||
|
||||
let intent = await this.syncIntentProjection(bookingId, snapshot);
|
||||
if (snapshot.status === ProviderPaymentStatus.SUCCEEDED) {
|
||||
// Poll observed success before (or instead of) the mark-paid event — converge now.
|
||||
await this.finalizePaymentSuccess({
|
||||
intentId,
|
||||
providerTxnId: status.providerTxnId,
|
||||
intentId: intent.id,
|
||||
providerTxnId: snapshot.providerTxnId,
|
||||
paidAt: snapshot.paidAt ? new Date(snapshot.paidAt) : undefined,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (status.status === ProviderPaymentStatus.FAILED) {
|
||||
await this.markPaymentFailed({
|
||||
intentId,
|
||||
failureCode: status.failureCode,
|
||||
failureMessage: status.failureMessage,
|
||||
intent = await this.prisma.paymentIntent.findUniqueOrThrow({
|
||||
where: { id: intent.id },
|
||||
});
|
||||
return;
|
||||
}
|
||||
await this.prisma.paymentIntent.update({
|
||||
where: { id: intentId },
|
||||
data: {
|
||||
status: status.status as unknown as PaymentIntentStatus,
|
||||
providerTxnId: status.providerTxnId ?? undefined,
|
||||
},
|
||||
});
|
||||
return this.formatIntentStatus(intent);
|
||||
}
|
||||
|
||||
private formatIntentStatus(
|
||||
@@ -326,13 +334,25 @@ export class PaymentsService {
|
||||
}
|
||||
|
||||
async refund(dto: RefundDto) {
|
||||
const intent = await this.prisma.paymentIntent.findUnique({ where: { bookingId: dto.bookingId } });
|
||||
if (!intent || intent.status !== 'SUCCEEDED') throw new BadRequestException('No successful payment to refund');
|
||||
await this.prisma.paymentIntent.update({ where: { bookingId: dto.bookingId }, data: { status: 'CANCELLED' } });
|
||||
const booking = await this.prisma.booking.findUnique({ where: { id: dto.bookingId }, include: { seats: true } });
|
||||
const intent = await this.prisma.paymentIntent.findUnique({
|
||||
where: { bookingId: dto.bookingId },
|
||||
});
|
||||
if (!intent || intent.status !== "SUCCEEDED")
|
||||
throw new BadRequestException("No successful payment to refund");
|
||||
await this.prisma.paymentIntent.update({
|
||||
where: { bookingId: dto.bookingId },
|
||||
data: { status: "CANCELLED" },
|
||||
});
|
||||
const booking = await this.prisma.booking.findUnique({
|
||||
where: { id: dto.bookingId },
|
||||
include: { seats: true },
|
||||
});
|
||||
if (booking) {
|
||||
await this.seatsService.releaseSeats(booking.seats.map((s) => s.seatId));
|
||||
await this.prisma.booking.update({ where: { id: dto.bookingId }, data: { status: 'CANCELLED' } });
|
||||
await this.prisma.booking.update({
|
||||
where: { id: dto.bookingId },
|
||||
data: { status: "CANCELLED" },
|
||||
});
|
||||
}
|
||||
return { refunded: true, bookingRef: booking?.bookingRef };
|
||||
}
|
||||
@@ -342,7 +362,7 @@ export class PaymentsService {
|
||||
type: dto.type as unknown as PaymentMethodType,
|
||||
displayName: dto.displayName,
|
||||
region: dto.region as unknown as PaymentRegion,
|
||||
currency: dto.currency ?? 'ETB',
|
||||
currency: dto.currency ?? "ETB",
|
||||
providerId: dto.providerId,
|
||||
enabled: dto.enabled ?? true,
|
||||
sortOrder: dto.sortOrder ?? 0,
|
||||
@@ -359,10 +379,17 @@ export class PaymentsService {
|
||||
where: {
|
||||
enabled: true,
|
||||
...(region
|
||||
? { region: { in: [region, PaymentRegionEnum.GLOBAL] as unknown as PaymentRegion[] } }
|
||||
? {
|
||||
region: {
|
||||
in: [
|
||||
region,
|
||||
PaymentRegionEnum.GLOBAL,
|
||||
] as unknown as PaymentRegion[],
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
orderBy: [{ sortOrder: 'asc' }, { displayName: 'asc' }],
|
||||
orderBy: [{ sortOrder: "asc" }, { displayName: "asc" }],
|
||||
});
|
||||
}
|
||||
|
||||
@@ -374,19 +401,21 @@ export class PaymentsService {
|
||||
const intent = await this.prisma.paymentIntent.findUnique({
|
||||
where: { id: input.intentId },
|
||||
});
|
||||
if (!intent) throw new NotFoundException('PaymentIntent not found');
|
||||
if (!intent) throw new NotFoundException("PaymentIntent not found");
|
||||
if (intent.status === PaymentIntentStatus.SUCCEEDED) {
|
||||
return { alreadyFinalized: true };
|
||||
}
|
||||
if (intent.status === PaymentIntentStatus.CANCELLED) {
|
||||
throw new BadRequestException('PaymentIntent is cancelled; cannot finalize');
|
||||
throw new BadRequestException(
|
||||
"PaymentIntent is cancelled; cannot finalize",
|
||||
);
|
||||
}
|
||||
|
||||
const booking = await this.prisma.booking.findUnique({
|
||||
where: { id: intent.bookingId },
|
||||
include: { seats: true },
|
||||
});
|
||||
if (!booking) throw new NotFoundException('Booking not found');
|
||||
if (!booking) throw new NotFoundException("Booking not found");
|
||||
|
||||
const paidAt = input.paidAt ?? new Date();
|
||||
await this.prisma.$transaction(async (tx) => {
|
||||
@@ -394,45 +423,134 @@ export class PaymentsService {
|
||||
where: { id: intent.id },
|
||||
data: {
|
||||
status: PaymentIntentStatus.SUCCEEDED,
|
||||
providerTxnId: input.providerTxnId ?? intent.providerTxnId ?? undefined,
|
||||
providerTxnId:
|
||||
input.providerTxnId ?? intent.providerTxnId ?? undefined,
|
||||
paidAt,
|
||||
},
|
||||
});
|
||||
await tx.booking.update({
|
||||
where: { id: booking.id },
|
||||
data: { status: 'CONFIRMED' },
|
||||
data: { status: "CONFIRMED" },
|
||||
});
|
||||
});
|
||||
|
||||
try {
|
||||
await this.seatsService.confirmSeats(booking.seats.map((s) => s.seatId));
|
||||
} catch (err) {
|
||||
this.logger.error(`Error confirming seats: ${err instanceof Error ? err.message : String(err)}`);
|
||||
this.logger.error(
|
||||
`Error confirming seats: ${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
await this.createJourneySegments(booking);
|
||||
} catch (err) {
|
||||
this.logger.error(`Error creating journey segments: ${err instanceof Error ? err.message : String(err)}`);
|
||||
this.logger.error(
|
||||
`Error creating journey segments: ${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
await this.ticketsService.generate(booking.id);
|
||||
} catch (err) {
|
||||
this.logger.error(`Error generating ticket: ${err instanceof Error ? err.message : String(err)}`);
|
||||
this.logger.error(
|
||||
`Error generating ticket: ${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
throw err;
|
||||
}
|
||||
|
||||
try {
|
||||
await this.awardLoyaltyPoints(booking.passengerId, booking.totalMinor, booking.id);
|
||||
await this.awardLoyaltyPoints(
|
||||
booking.passengerId,
|
||||
booking.totalMinor,
|
||||
booking.id,
|
||||
);
|
||||
} catch (err) {
|
||||
this.logger.warn(`Error awarding loyalty points: ${err instanceof Error ? err.message : String(err)}`);
|
||||
this.logger.warn(
|
||||
`Error awarding loyalty points: ${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
}
|
||||
|
||||
this.eventEmitter.emit('payment.succeeded', { booking });
|
||||
this.eventEmitter.emit("payment.succeeded", { booking });
|
||||
return { alreadyFinalized: false };
|
||||
}
|
||||
|
||||
async handlePaymentEvent(
|
||||
event: PaymentEventDto,
|
||||
): Promise<MarkPaidResponseDto> {
|
||||
if (
|
||||
event.service !== PaymentServiceEnum.PASSENGER ||
|
||||
event.referenceType !== PaymentReferenceType.BOOKING
|
||||
) {
|
||||
this.logger.warn(
|
||||
`mark-paid: ignoring foreign reference ${event.service}/${event.referenceType}/${event.referenceId}`,
|
||||
);
|
||||
return { processed: false, reason: "foreign-reference" };
|
||||
}
|
||||
|
||||
if (event.eventType === "payment.failed") {
|
||||
const intent = await this.prisma.paymentIntent.findUnique({
|
||||
where: { bookingId: event.referenceId },
|
||||
});
|
||||
if (intent) {
|
||||
await this.markPaymentFailed({
|
||||
intentId: intent.id,
|
||||
failureCode: event.failureCode,
|
||||
failureMessage: event.failureMessage,
|
||||
});
|
||||
}
|
||||
return { processed: true };
|
||||
}
|
||||
|
||||
const booking = await this.prisma.booking.findUnique({
|
||||
where: { id: event.referenceId },
|
||||
});
|
||||
if (!booking) {
|
||||
// Ack (200) — a missing booking will not appear on redelivery; needs investigation.
|
||||
this.logger.error(
|
||||
`mark-paid: no booking for reference ${event.referenceId}`,
|
||||
);
|
||||
return { processed: false, reason: "booking-not-found" };
|
||||
}
|
||||
|
||||
if (booking.totalMinor !== event.amountMinor) {
|
||||
// Refuse to confirm: a 4xx makes the relay retry and eventually flag the row FAILED,
|
||||
// which is the alertable signal for an asserted-vs-paid amount divergence.
|
||||
this.logger.error(
|
||||
`mark-paid: amount mismatch for booking ${booking.id}: booking=${booking.totalMinor} event=${event.amountMinor}`,
|
||||
);
|
||||
throw new BadRequestException(
|
||||
"Event amount does not match booking total",
|
||||
);
|
||||
}
|
||||
|
||||
// Local intent row is a projection during the strangler migration: reuse it when the
|
||||
// legacy initiate path created one, otherwise materialize it from the event.
|
||||
let intent = await this.prisma.paymentIntent.findUnique({
|
||||
where: { bookingId: event.referenceId },
|
||||
});
|
||||
if (!intent) {
|
||||
intent = await this.prisma.paymentIntent.create({
|
||||
data: {
|
||||
bookingId: event.referenceId,
|
||||
amountMinor: event.amountMinor,
|
||||
currency: event.currency,
|
||||
method: event.provider as unknown as PaymentMethodType,
|
||||
status: PaymentIntentStatus.PROCESSING,
|
||||
merchantOrderId: event.merchantOrderId,
|
||||
providerTxnId: event.providerTxnId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const { alreadyFinalized } = await this.finalizePaymentSuccess({
|
||||
intentId: intent.id,
|
||||
providerTxnId: event.providerTxnId,
|
||||
paidAt: event.paidAt ? new Date(event.paidAt) : undefined,
|
||||
});
|
||||
return { processed: true, alreadyFinalized };
|
||||
}
|
||||
|
||||
async markPaymentFailed(input: {
|
||||
intentId: string;
|
||||
failureCode?: string;
|
||||
@@ -441,7 +559,7 @@ export class PaymentsService {
|
||||
const intent = await this.prisma.paymentIntent.findUnique({
|
||||
where: { id: input.intentId },
|
||||
});
|
||||
if (!intent) throw new NotFoundException('PaymentIntent not found');
|
||||
if (!intent) throw new NotFoundException("PaymentIntent not found");
|
||||
if (
|
||||
intent.status === PaymentIntentStatus.SUCCEEDED ||
|
||||
intent.status === PaymentIntentStatus.CANCELLED
|
||||
@@ -458,35 +576,72 @@ export class PaymentsService {
|
||||
});
|
||||
}
|
||||
|
||||
private async awardLoyaltyPoints(passengerId: string, amountMinor: number, bookingId: string) {
|
||||
private async awardLoyaltyPoints(
|
||||
passengerId: string,
|
||||
amountMinor: number,
|
||||
bookingId: string,
|
||||
) {
|
||||
const points = Math.floor(amountMinor / 100);
|
||||
const account = await this.prisma.loyaltyAccount.findUnique({ where: { passengerId } });
|
||||
const account = await this.prisma.loyaltyAccount.findUnique({
|
||||
where: { passengerId },
|
||||
});
|
||||
if (!account) return;
|
||||
const newBalance = account.pointsBalance + points;
|
||||
const tier = newBalance >= 10000 ? 'PLATINUM' : newBalance >= 5000 ? 'GOLD' : newBalance >= 2000 ? 'SILVER' : 'BRONZE';
|
||||
await this.prisma.loyaltyAccount.update({ where: { passengerId }, data: { pointsBalance: { increment: points }, tier: tier as any } });
|
||||
await this.prisma.loyaltyLedgerEntry.create({ data: { accountId: account.id, delta: points, reason: 'TRIP_COMPLETED', bookingId, balanceAfter: newBalance } });
|
||||
const tier =
|
||||
newBalance >= 10000
|
||||
? "PLATINUM"
|
||||
: newBalance >= 5000
|
||||
? "GOLD"
|
||||
: newBalance >= 2000
|
||||
? "SILVER"
|
||||
: "BRONZE";
|
||||
await this.prisma.loyaltyAccount.update({
|
||||
where: { passengerId },
|
||||
data: { pointsBalance: { increment: points }, tier: tier as any },
|
||||
});
|
||||
await this.prisma.loyaltyLedgerEntry.create({
|
||||
data: {
|
||||
accountId: account.id,
|
||||
delta: points,
|
||||
reason: "TRIP_COMPLETED",
|
||||
bookingId,
|
||||
balanceAfter: newBalance,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private async createJourneySegments(booking: Prisma.BookingGetPayload<{ include: { seats: true } }>) {
|
||||
private async createJourneySegments(
|
||||
booking: Prisma.BookingGetPayload<{ include: { seats: true } }>,
|
||||
) {
|
||||
const schedule = await this.prisma.trainSchedule.findUnique({
|
||||
where: { id: booking.scheduleId },
|
||||
include: { stopTimes: { include: { station: true }, orderBy: { sequence: 'asc' } } },
|
||||
include: {
|
||||
stopTimes: { include: { station: true }, orderBy: { sequence: "asc" } },
|
||||
},
|
||||
});
|
||||
if (!schedule) return;
|
||||
|
||||
const stopTimes = schedule.stopTimes;
|
||||
if (stopTimes.length < 2) return;
|
||||
|
||||
const originSequence = stopTimes.findIndex(st => st.stationId === schedule.originStationId);
|
||||
const destSequence = stopTimes.findIndex(st => st.stationId === schedule.destinationStationId);
|
||||
const originSequence = stopTimes.findIndex(
|
||||
(st) => st.stationId === schedule.originStationId,
|
||||
);
|
||||
const destSequence = stopTimes.findIndex(
|
||||
(st) => st.stationId === schedule.destinationStationId,
|
||||
);
|
||||
|
||||
if (originSequence < 0 || destSequence < 0 || originSequence >= destSequence) return;
|
||||
if (
|
||||
originSequence < 0 ||
|
||||
destSequence < 0 ||
|
||||
originSequence >= destSequence
|
||||
)
|
||||
return;
|
||||
|
||||
const journey = await this.prisma.journey.create({
|
||||
data: {
|
||||
passengerId: booking.passengerId,
|
||||
status: 'CONFIRMED',
|
||||
status: "CONFIRMED",
|
||||
totalMinor: booking.totalMinor,
|
||||
currency: booking.currency,
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user