-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsaga.service.ts
More file actions
141 lines (119 loc) · 4.87 KB
/
Copy pathsaga.service.ts
File metadata and controls
141 lines (119 loc) · 4.87 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
import { Inject, Injectable } from '@nestjs/common';
import { and, eq } from 'drizzle-orm';
import { orders, type Db } from '@tickethub/db';
import {
ORDER_ROUTING_KEYS,
PAYMENT_ROUTING_KEYS,
SHOW_ROUTING_KEYS,
type EventEnvelope,
} from '@tickethub/contracts';
import { canTransition, type OrderStatus } from '../orders.state';
import { OrderRepository } from '../orders.repository';
// The event-driven half of Orders (payments.events → order-state) plus the TTL release.
// All idempotent via processed_messages, and the state machine is the only authority on
// transitions.
@Injectable()
export class OrderSagaService {
constructor(
@Inject('DB') private readonly db: Db,
private readonly orderRepository: OrderRepository,
) {}
// Unblock seats and mark the order as expired. Called by the release worker.
async release(orderId: string): Promise<void> {
await this.db.transaction(async (tx) => {
const order = await this.orderRepository.lockOrder(tx, orderId);
// paid/expired/cancelled → nothing to release.
if (!order || !canTransition(order.status as OrderStatus, 'expired')) return;
const seatIds = await this.orderRepository.settle(tx, order, 'expired', 'released');
await this.orderRepository.emit(tx, ORDER_ROUTING_KEYS.ORDER_EXPIRED, {
orderId,
showId: order.showId,
});
await this.orderRepository.emitPerSeat(tx, ORDER_ROUTING_KEYS.SEAT_RELEASED, order, seatIds);
await this.orderRepository.unlockSeats(order, seatIds);
});
}
// payment.succeeded → confirm the order. If it can no longer become paid (expire-then-pay
// race), auto-refund instead of resurrecting it.
async markPaid(
event: EventEnvelope<typeof PAYMENT_ROUTING_KEYS.PAYMENT_SUCCEEDED>,
): Promise<void> {
await this.db.transaction(async (tx) => {
if (await this.orderRepository.alreadyProcessed(tx, event.messageId)) return;
const order = await this.orderRepository.lockOrder(tx, event.orderId);
if (!order) return;
if (!canTransition(order.status as OrderStatus, 'paid')) {
if (order.status === 'expired' || order.status === 'cancelled') {
await this.orderRepository.emit(tx, ORDER_ROUTING_KEYS.REFUND_REQUESTED, {
orderId: order.id,
paymentIntentId: event.paymentIntentId,
});
}
return;
}
await this.orderRepository.settle(tx, order, 'paid', 'confirmed');
await this.orderRepository.emit(tx, ORDER_ROUTING_KEYS.ORDER_PAID, {
orderId: order.id,
userId: order.userId,
showId: order.showId,
});
});
}
// payment.failed → cancel the order, release its seats and locks.
async markFailed(
event: EventEnvelope<typeof PAYMENT_ROUTING_KEYS.PAYMENT_FAILED>,
): Promise<void> {
await this.close(
event.messageId,
event.orderId,
'cancelled',
ORDER_ROUTING_KEYS.ORDER_CANCELLED,
);
}
// refund.succeeded → close out a paid order as refunded, release its seats and locks.
async markRefunded(
event: EventEnvelope<typeof PAYMENT_ROUTING_KEYS.REFUND_SUCCEEDED>,
): Promise<void> {
await this.close(event.messageId, event.orderId, 'refunded');
}
// show.cancelled → refund every paid order for that show (each downstream refund reuses
// the same refund.requested → Payments → charge.refunded → markRefunded path).
async refundAllPaidForShow(
event: EventEnvelope<typeof SHOW_ROUTING_KEYS.SHOW_CANCELLED>,
): Promise<void> {
await this.db.transaction(async (tx) => {
if (await this.orderRepository.alreadyProcessed(tx, event.messageId)) return;
const paid = await tx
.select({ id: orders.id })
.from(orders)
.where(and(eq(orders.showId, event.showId), eq(orders.status, 'paid')));
for (const order of paid) {
await this.orderRepository.emit(tx, ORDER_ROUTING_KEYS.REFUND_REQUESTED, {
orderId: order.id,
});
}
});
}
// Terminal transitions that free the seats: cancelled and refunded differ only in the
// order-level event they announce (a refund's is emitted by Payments, not here).
private async close(
messageId: string,
orderId: string,
to: Extract<OrderStatus, 'cancelled' | 'refunded'>,
routingKey?: typeof ORDER_ROUTING_KEYS.ORDER_CANCELLED,
): Promise<void> {
await this.db.transaction(async (tx) => {
const order = await this.orderRepository.claim(tx, messageId, orderId, to);
if (!order) return;
const seatIds = await this.orderRepository.settle(tx, order, to, 'released');
if (routingKey) {
await this.orderRepository.emit(tx, routingKey, {
orderId: order.id,
showId: order.showId,
});
}
await this.orderRepository.emitPerSeat(tx, ORDER_ROUTING_KEYS.SEAT_RELEASED, order, seatIds);
await this.orderRepository.unlockSeats(order, seatIds);
});
}
}