-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathsettlement.controller.ts
More file actions
78 lines (68 loc) · 2.54 KB
/
settlement.controller.ts
File metadata and controls
78 lines (68 loc) · 2.54 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
import type { Request, Response, NextFunction } from "express";
import Joi from "joi";
import type { SettlementService } from "../services/settlement.service";
import { HttpError } from "../utils/http-error";
import { ServiceError } from "../utils/service-error";
import { UserType } from "../types/enums";
const settleInvoiceSchema = Joi.object({
paidAmount: Joi.string().regex(/^\d+(\.\d{1,4})?$/).required(),
stellarTxHash: Joi.string().length(64).optional(),
settledAt: Joi.date().iso().optional(),
});
export interface SettleInvoiceRequest extends Request {
params: {
id: string;
};
body: {
paidAmount: string;
stellarTxHash?: string;
settledAt?: string;
};
}
export function createSettlementController(settlementService: SettlementService) {
return {
async settleInvoice(
req: SettleInvoiceRequest,
res: Response,
next: NextFunction,
): Promise<void> {
try {
if (!req.user) {
throw new HttpError(401, "Authentication required");
}
// MVP: Only sellers can settle their own invoices
if (req.user.userType !== UserType.SELLER && req.user.userType !== UserType.BOTH) {
throw new HttpError(403, "Only sellers can settle invoices");
}
const { error, value } = settleInvoiceSchema.validate(req.body, {
abortEarly: false,
stripUnknown: true,
});
if (error) {
throw new HttpError(
400,
"Request validation failed.",
error.details.map((detail) => detail.message),
);
}
const { id: invoiceId } = req.params;
const result = await settlementService.settleInvoice({
invoiceId,
paidAmount: value.paidAmount,
stellarTxHash: value.stellarTxHash,
settledAt: value.settledAt ? new Date(value.settledAt) : undefined,
});
res.status(200).json({
success: true,
data: result,
});
} catch (error) {
if (error instanceof ServiceError) {
next(new HttpError(error.statusCode, error.message));
return;
}
next(error);
}
},
};
}