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

81 lines
2.5 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; bus_work_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 busWorkNumber = (body.bus_work_number ?? "").trim();
if (!channelId) return fail("channel_id is required");
if (!scheduleId) return fail("schedule_id is required");
if (!busWorkNumber) return fail("bus_work_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: tripRows, error: tripError } = await client
.from("operations_trips")
.select("id, trip_number, duty_number, bus_work_number, direction, sort_order")
.eq("schedule_id", scheduleId)
.eq("bus_work_number", busWorkNumber)
.order("sort_order", { ascending: true });
if (tripError) return fail(tripError.message, 500);
const trips = (tripRows ?? []) as {
id: string;
trip_number: string;
duty_number: string;
bus_work_number: string;
direction: string;
sort_order: number;
}[];
if (trips.length === 0) return json({ trips: [] });
const tripIds = trips.map((t) => t.id);
const { data: stopRows, error: stopError } = await client
.from("operations_trip_stops")
.select("id, trip_id, stop_sequence, stop_name, scheduled_time")
.in("trip_id", tripIds)
.order("stop_sequence", { ascending: true });
if (stopError) return fail(stopError.message, 500);
const stopsByTripId: Record<string, typeof stopRows> = {};
for (const stop of stopRows ?? []) {
const s = stop as { trip_id: string };
if (!stopsByTripId[s.trip_id]) stopsByTripId[s.trip_id] = [];
stopsByTripId[s.trip_id]!.push(stop);
}
const result = trips.map((trip) => ({
...trip,
stops: stopsByTripId[trip.id] ?? [],
}));
return json({ trips: result });
});