Roadbound-BRR/supabase/functions/operations-trip-detail/index.ts

59 lines
2 KiB
TypeScript

import { fail, handleOptions, json } from "../_shared/http.ts";
import { requireUser } from "../_shared/supabase.ts";
Deno.serve(async (req) => {
const preflight = handleOptions(req);
if (preflight) return preflight;
if (req.method !== "POST") return fail("Method not allowed", 405);
const { client, user, error: userError } = await requireUser(req);
if (!user) return fail(userError ?? "Unauthorized", 401);
let body: { channel_id?: string; schedule_id?: string; trip_number?: string };
try {
body = await req.json();
} catch {
return fail("Invalid JSON body");
}
const channelId = (body.channel_id ?? "").trim();
const scheduleId = (body.schedule_id ?? "").trim();
const tripNumber = (body.trip_number ?? "").trim();
if (!channelId) return fail("channel_id is required");
if (!scheduleId) return fail("schedule_id is required");
if (!tripNumber) return fail("trip_number is required");
const { data: schedule, error: scheduleError } = await client
.from("operations_schedules")
.select("id, channel_id")
.eq("id", scheduleId)
.eq("channel_id", channelId)
.maybeSingle();
if (scheduleError) return fail(scheduleError.message, 400);
if (!schedule) return fail("forbidden", 403);
const { data: tripRow, error: tripError } = await client
.from("operations_trips")
.select("id, trip_number, duty_number, bus_work_number, direction, sort_order")
.eq("schedule_id", scheduleId)
.eq("trip_number", tripNumber)
.maybeSingle();
if (tripError) return fail(tripError.message, 500);
if (!tripRow) return json({ trip: null, stops: [] });
const trip = tripRow as { id: string };
const { data: stopRows, error: stopError } = await client
.from("operations_trip_stops")
.select("id, trip_id, stop_sequence, stop_name, scheduled_time")
.eq("trip_id", trip.id)
.order("stop_sequence", { ascending: true });
if (stopError) return fail(stopError.message, 500);
return json({ trip: tripRow, stops: stopRows ?? [] });
});