|
| 1 | +import { type ActionFunctionArgs, json } from "@remix-run/server-runtime"; |
| 2 | +import { z } from "zod"; |
| 3 | +import { prisma } from "~/db.server"; |
| 4 | +import { requireAdminApiRequest } from "~/services/personalAccessToken.server"; |
| 5 | +import { completeBillingLimitResolve } from "~/services/platform.v3.server"; |
| 6 | +import { logger } from "~/services/logger.server"; |
| 7 | +import { |
| 8 | + convergeBillingLimitResolve, |
| 9 | + type PendingBillingLimitResolve, |
| 10 | +} from "~/v3/services/billingLimit/billingLimitConvergeResolve.server"; |
| 11 | + |
| 12 | +const ParamsSchema = z.object({ |
| 13 | + organizationId: z.string(), |
| 14 | +}); |
| 15 | + |
| 16 | +const BodySchema = z.object({ |
| 17 | + resumeMode: z.enum(["queue", "new_only"]), |
| 18 | + resolvedAt: z.string(), |
| 19 | +}); |
| 20 | + |
| 21 | +/** Billing platform webhook: org resolved billing limit to ok. Idempotent — returns 202. */ |
| 22 | +export async function action({ request, params }: ActionFunctionArgs) { |
| 23 | + await requireAdminApiRequest(request); |
| 24 | + |
| 25 | + if (request.method.toLowerCase() !== "post") { |
| 26 | + return json({ error: "Method not allowed" }, { status: 405 }); |
| 27 | + } |
| 28 | + |
| 29 | + const { organizationId } = ParamsSchema.parse(params); |
| 30 | + |
| 31 | + const organization = await prisma.organization.findFirst({ |
| 32 | + where: { id: organizationId }, |
| 33 | + select: { id: true }, |
| 34 | + }); |
| 35 | + |
| 36 | + if (!organization) { |
| 37 | + return json({ error: "Organization not found" }, { status: 404 }); |
| 38 | + } |
| 39 | + |
| 40 | + let pending: PendingBillingLimitResolve; |
| 41 | + try { |
| 42 | + const body = await request.json(); |
| 43 | + pending = { |
| 44 | + organizationId, |
| 45 | + ...BodySchema.parse(body), |
| 46 | + }; |
| 47 | + } catch (error) { |
| 48 | + logger.error("Invalid billing limit resolve webhook payload", { |
| 49 | + error, |
| 50 | + organizationId, |
| 51 | + }); |
| 52 | + return json({ error: "Invalid request body" }, { status: 400 }); |
| 53 | + } |
| 54 | + |
| 55 | + try { |
| 56 | + await convergeBillingLimitResolve(pending); |
| 57 | + await completeBillingLimitResolve(organizationId); |
| 58 | + } catch (error) { |
| 59 | + logger.error("Billing limit resolve webhook failed", { |
| 60 | + error, |
| 61 | + organizationId, |
| 62 | + resumeMode: pending.resumeMode, |
| 63 | + resolvedAt: pending.resolvedAt, |
| 64 | + }); |
| 65 | + return json({ error: "Failed to process billing limit resolve" }, { status: 500 }); |
| 66 | + } |
| 67 | + |
| 68 | + return json({ success: true, accepted: true }, { status: 202 }); |
| 69 | +} |
0 commit comments