|
| 1 | +import { db, getServerTime } from "database"; |
| 2 | +import { createOperation } from "lib/operation"; |
| 3 | +import { bookingInput } from "@floyd-run/schema/inputs"; |
| 4 | +import { ConflictError, NotFoundError } from "lib/errors"; |
| 5 | +import { emitEvent } from "infra/event-bus"; |
| 6 | +import { serializeBooking, serializeAllocation } from "routes/v1/serializers"; |
| 7 | +import { evaluatePolicy, type PolicyConfig } from "domain/policy/evaluate"; |
| 8 | +import { insertAllocation } from "../allocation/internal/insert"; |
| 9 | + |
| 10 | +const DEFAULT_HOLD_DURATION_MS = 15 * 60 * 1000; // 15 minutes |
| 11 | + |
| 12 | +export default createOperation({ |
| 13 | + input: bookingInput.reschedule, |
| 14 | + execute: async (input) => { |
| 15 | + return await db.transaction().execute(async (trx) => { |
| 16 | + // 1. Lock booking row |
| 17 | + const existing = await trx |
| 18 | + .selectFrom("bookings") |
| 19 | + .selectAll() |
| 20 | + .where("id", "=", input.id) |
| 21 | + .where("ledgerId", "=", input.ledgerId) |
| 22 | + .forUpdate() |
| 23 | + .executeTakeFirst(); |
| 24 | + |
| 25 | + if (!existing) { |
| 26 | + throw new NotFoundError("Booking not found"); |
| 27 | + } |
| 28 | + |
| 29 | + // 2. Capture server time |
| 30 | + const serverTime = await getServerTime(trx); |
| 31 | + |
| 32 | + // 3. Validate state |
| 33 | + if (existing.status !== "hold" && existing.status !== "confirmed") { |
| 34 | + throw new ConflictError("booking.invalid_transition", { |
| 35 | + currentStatus: existing.status, |
| 36 | + requestedAction: "reschedule", |
| 37 | + }); |
| 38 | + } |
| 39 | + |
| 40 | + // 4. Check hold expiry |
| 41 | + if (existing.status === "hold" && existing.expiresAt && serverTime >= existing.expiresAt) { |
| 42 | + throw new ConflictError("booking.hold_expired", { |
| 43 | + expiresAt: existing.expiresAt, |
| 44 | + serverTime, |
| 45 | + }); |
| 46 | + } |
| 47 | + |
| 48 | + // 5. Snapshot current active allocations (for event payload) and derive resourceId |
| 49 | + const previousAllocations = await trx |
| 50 | + .selectFrom("allocations") |
| 51 | + .selectAll() |
| 52 | + .where("bookingId", "=", existing.id) |
| 53 | + .where("active", "=", true) |
| 54 | + .execute(); |
| 55 | + |
| 56 | + const resourceId = previousAllocations[0]!.resourceId; |
| 57 | + |
| 58 | + // 6. Lock resource row (serializes concurrent allocation writes) |
| 59 | + const resource = await trx |
| 60 | + .selectFrom("resources") |
| 61 | + .selectAll() |
| 62 | + .where("id", "=", resourceId) |
| 63 | + .where("ledgerId", "=", input.ledgerId) |
| 64 | + .forUpdate() |
| 65 | + .executeTakeFirstOrThrow(); |
| 66 | + |
| 67 | + // 7. Load service + current policy version |
| 68 | + const service = await trx |
| 69 | + .selectFrom("services") |
| 70 | + .selectAll() |
| 71 | + .where("id", "=", existing.serviceId) |
| 72 | + .where("ledgerId", "=", input.ledgerId) |
| 73 | + .executeTakeFirst(); |
| 74 | + |
| 75 | + if (!service) { |
| 76 | + throw new NotFoundError("Service not found"); |
| 77 | + } |
| 78 | + |
| 79 | + if (!service.policyId) { |
| 80 | + throw new ConflictError("service.no_policy", { |
| 81 | + message: "Service must have a policy to reschedule bookings", |
| 82 | + }); |
| 83 | + } |
| 84 | + |
| 85 | + const policyRow = await trx |
| 86 | + .selectFrom("policies") |
| 87 | + .select("currentVersionId") |
| 88 | + .where("id", "=", service.policyId) |
| 89 | + .executeTakeFirstOrThrow(); |
| 90 | + |
| 91 | + const version = await trx |
| 92 | + .selectFrom("policyVersions") |
| 93 | + .selectAll() |
| 94 | + .where("id", "=", policyRow.currentVersionId) |
| 95 | + .executeTakeFirstOrThrow(); |
| 96 | + |
| 97 | + // 8. Evaluate policy against new times |
| 98 | + const result = evaluatePolicy( |
| 99 | + version.config as unknown as PolicyConfig, |
| 100 | + { startTime: input.startTime, endTime: input.endTime }, |
| 101 | + { decisionTime: serverTime, timezone: resource.timezone }, |
| 102 | + ); |
| 103 | + |
| 104 | + if (!result.allowed) { |
| 105 | + throw new ConflictError("policy.rejected", { |
| 106 | + code: result.code, |
| 107 | + message: result.message, |
| 108 | + ...("details" in result ? { details: result.details } : {}), |
| 109 | + }); |
| 110 | + } |
| 111 | + |
| 112 | + const startTime = result.effectiveStartTime; |
| 113 | + const endTime = result.effectiveEndTime; |
| 114 | + const bufferBeforeMs = result.bufferBeforeMs; |
| 115 | + const bufferAfterMs = result.bufferAfterMs; |
| 116 | + |
| 117 | + let holdDurationMs = DEFAULT_HOLD_DURATION_MS; |
| 118 | + if (result.resolvedConfig.hold?.duration_ms !== undefined) { |
| 119 | + holdDurationMs = result.resolvedConfig.hold.duration_ms; |
| 120 | + } |
| 121 | + |
| 122 | + // 9. Compute new expiresAt |
| 123 | + const isHold = existing.status === "hold"; |
| 124 | + const expiresAt = isHold ? new Date(serverTime.getTime() + holdDurationMs) : null; |
| 125 | + |
| 126 | + // 10. Deactivate old allocations |
| 127 | + await trx |
| 128 | + .updateTable("allocations") |
| 129 | + .set({ active: false, expiresAt: null }) |
| 130 | + .where("bookingId", "=", existing.id) |
| 131 | + .where("active", "=", true) |
| 132 | + .execute(); |
| 133 | + |
| 134 | + // 11. Insert new allocation (conflict check runs against other allocations only) |
| 135 | + await insertAllocation(trx, { |
| 136 | + ledgerId: input.ledgerId, |
| 137 | + resourceId, |
| 138 | + bookingId: existing.id, |
| 139 | + startTime, |
| 140 | + endTime, |
| 141 | + bufferBeforeMs, |
| 142 | + bufferAfterMs, |
| 143 | + expiresAt, |
| 144 | + metadata: {}, |
| 145 | + serverTime, |
| 146 | + }); |
| 147 | + |
| 148 | + // 12. Update booking |
| 149 | + const booking = await trx |
| 150 | + .updateTable("bookings") |
| 151 | + .set({ |
| 152 | + policyVersionId: version.id, |
| 153 | + expiresAt, |
| 154 | + }) |
| 155 | + .where("id", "=", existing.id) |
| 156 | + .returningAll() |
| 157 | + .executeTakeFirstOrThrow(); |
| 158 | + |
| 159 | + // 13. Fetch all allocations for response |
| 160 | + const allocations = await trx |
| 161 | + .selectFrom("allocations") |
| 162 | + .selectAll() |
| 163 | + .where("bookingId", "=", existing.id) |
| 164 | + .execute(); |
| 165 | + |
| 166 | + // 14. Emit event |
| 167 | + await emitEvent(trx, "booking.rescheduled", booking.ledgerId, { |
| 168 | + booking: serializeBooking(booking, allocations), |
| 169 | + previousAllocations: previousAllocations.map((a) => serializeAllocation(a)), |
| 170 | + }); |
| 171 | + |
| 172 | + return { booking, allocations, serverTime }; |
| 173 | + }); |
| 174 | + }, |
| 175 | +}); |
0 commit comments