forked from StellarSplit/StellarSplit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpayment-settlement.processor.ts
More file actions
174 lines (151 loc) · 5.08 KB
/
Copy pathpayment-settlement.processor.ts
File metadata and controls
174 lines (151 loc) · 5.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
import { Injectable, Logger } from "@nestjs/common";
import { Processor, Process, OnQueueFailed } from "@nestjs/bull";
import { Job } from "bull";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { Payment, PaymentSettlementStatus } from "../entities/payment.entity";
import { Participant } from "../entities/participant.entity";
import { Split } from "../entities/split.entity";
import { EmailService } from "../email/email.service";
import { EventsGateway } from "../gateway/events.gateway";
import { logJobFailure } from "../common/queue-job-policy";
/**
* Job data for settlement processing
*/
interface SettlementJobData {
paymentId: string;
splitId: string;
participantId: string;
}
/**
* Queue processor for payment settlement jobs
*/
@Processor("payment-settlement")
@Injectable()
export class PaymentSettlementProcessor {
private readonly logger = new Logger(PaymentSettlementProcessor.name);
constructor(
@InjectRepository(Payment) private paymentRepository: Repository<Payment>,
@InjectRepository(Participant)
private participantRepository: Repository<Participant>,
@InjectRepository(Split) private splitRepository: Repository<Split>,
private readonly emailService: EmailService,
private readonly eventsGateway: EventsGateway,
) {}
/**
* Process a settlement after on-chain confirmation
*/
@Process("process-settlement")
async handleSettlement(job: Job<SettlementJobData>): Promise<void> {
const { paymentId, splitId, participantId } = job.data;
this.logger.log(`Processing settlement for payment: ${paymentId}`);
try {
// Get payment details
const payment = await this.paymentRepository.findOne({
where: { id: paymentId },
});
if (!payment) {
this.logger.error(`Payment not found: ${paymentId}`);
return;
}
// Verify payment is confirmed
if (payment.settlementStatus !== PaymentSettlementStatus.CONFIRMED) {
this.logger.warn(
`Payment ${paymentId} is not confirmed, skipping settlement`,
);
return;
}
// Get participant details
const participant = await this.participantRepository.findOne({
where: { id: participantId },
});
if (!participant) {
this.logger.error(`Participant not found: ${participantId}`);
return;
}
// Get split details
const split = await this.splitRepository.findOne({
where: { id: splitId },
relations: ["participants"],
});
if (!split) {
this.logger.error(`Split not found: ${splitId}`);
return;
}
// Check if split is now complete
await this.checkAndUpdateSplitCompletion(splitId);
// Send settlement confirmation
await this.sendSettlementConfirmation(payment, participant, split);
// Emit settlement event
this.eventsGateway.emitSplitUpdated(splitId, {
type: "settlement_completed",
paymentId,
participantId,
amount: payment.amount,
timestamp: new Date().toISOString(),
});
this.logger.log(
`Settlement processed for payment: ${paymentId}`,
);
} catch (error: any) {
logJobFailure(this.logger, job, error, { context: 'payment-settlement' });
throw error;
}
}
/**
* Dead-letter handler: fires when the settlement job has exhausted all retries.
*/
@OnQueueFailed()
onFailed(job: Job<SettlementJobData>, err: Error) {
logJobFailure(this.logger, job, err, { context: 'payment-settlement-dead-letter' });
}
/**
* Check if split is complete after payment and update status
*/
private async checkAndUpdateSplitCompletion(splitId: string): Promise<void> {
const split = await this.splitRepository.findOne({
where: { id: splitId },
relations: ["participants"],
});
if (!split) return;
// Check if all participants are paid
const allPaid = split.participants.every(
(p: Participant) => p.status === "paid" || Number(p.amountPaid) >= Number(p.amountOwed),
);
if (allPaid && split.status !== "completed") {
await this.splitRepository.update(splitId, {
status: "completed",
});
// Emit split completed event
this.eventsGateway.emitSplitUpdated(splitId, {
type: "split_completed",
splitId,
timestamp: new Date().toISOString(),
});
this.logger.log(`Split ${splitId} marked as completed`);
}
}
/**
* Send settlement confirmation email
*/
private async sendSettlementConfirmation(
payment: Payment,
participant: Participant,
split: Split,
): Promise<void> {
try {
const user = await this.emailService.getUser(participant.userId);
if (user) {
// In a real implementation, we'd send a settlement-specific email
// For now, we'll just log it
this.logger.log(
`Would send settlement confirmation to ${user.email} for payment ${payment.id}`,
);
}
} catch (error) {
this.logger.warn(
`Failed to send settlement confirmation: ${error}`,
);
}
}
}