Refactor transit_api into a repo/routes module split
Split the 5,441-line index.js into an 86-line bootstrap, thin domain
route modules, shared lib/ helpers, and a repo/ layer that isolates the
DEV_MOCK branches (repo/*.mock.js). Repo methods return {statusCode, body};
routes are one-line wrappers. Pin search_path to "transit.bus" and
document the /bus/ prefix with legacy root aliases (Deprecation header).
Parity verified: 57/57 byte-identical on the stub differential harness
plus 24/24 live read-only responses vs the original against real
PostgreSQL. The only intentional behavior change: mock reorder/delete
bus-line endpoints no longer require a live DB (previously 500 in
DEV_MOCK=1 without PG). DEV_MOCK gate and node --check clean.
This commit is contained in:
@@ -0,0 +1,663 @@
|
||||
const db = require("../db");
|
||||
const { DEV_MOCK } = require("../lib/env");
|
||||
const { store: _mock } = require("../mock/store");
|
||||
const { calculateDepartureTimes, parseWeekdaysValue, expandRecurringScheduleRows, mapAdminScheduleRow, scheduleMatchesFilters, parseScheduleFilters, checkDriverConflict } = require("../lib/schedule");
|
||||
const { reportError } = require("../lib/report-error");
|
||||
|
||||
// Admin schedules repository methods (PostgreSQL mode). Each returns
|
||||
// { statusCode, body } mirroring the original handler's DB branch.
|
||||
|
||||
async function listAdminSchedules(req) {
|
||||
try {
|
||||
const templatesOnly =
|
||||
String(
|
||||
req.query.templates || req.query.includeTemplates || "",
|
||||
).toLowerCase() === "true" ||
|
||||
String(req.query.templates || req.query.includeTemplates || "") === "1";
|
||||
|
||||
const hasWeekdaysColumn = await db.query(`
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_schema='transit' AND table_name='schedules' AND column_name='weekdays'
|
||||
`);
|
||||
|
||||
const baseSelect = `
|
||||
SELECT
|
||||
s.id,
|
||||
s.bus_line_id,
|
||||
s.bus_id,
|
||||
s.driver_id,
|
||||
s.start_time,
|
||||
s.end_time,
|
||||
s.status,
|
||||
s.created_at,
|
||||
bl.line_number,
|
||||
bl.estimated_duration_minutes,
|
||||
b.name as bus_name,
|
||||
b.license_plate,
|
||||
TRIM(COALESCE(e.firstname, '') || ' ' || COALESCE(e.lastname, '')) as driver_name`;
|
||||
|
||||
const result =
|
||||
hasWeekdaysColumn.rows.length > 0
|
||||
? await db.query(`${baseSelect}, s.weekdays as weekdays
|
||||
FROM schedules s
|
||||
LEFT JOIN bus_lines bl ON s.bus_line_id = bl.id
|
||||
LEFT JOIN fleet.bus b ON s.bus_id = b.id
|
||||
LEFT JOIN workers.employees e ON s.driver_id = e.id
|
||||
ORDER BY s.start_time DESC`)
|
||||
: await db.query(`${baseSelect}, NULL as weekdays
|
||||
FROM schedules s
|
||||
LEFT JOIN bus_lines bl ON s.bus_line_id = bl.id
|
||||
LEFT JOIN fleet.bus b ON s.bus_id = b.id
|
||||
LEFT JOIN workers.employees e ON s.driver_id = e.id
|
||||
ORDER BY s.start_time DESC`);
|
||||
|
||||
const lineIds = Array.from(
|
||||
new Set(
|
||||
result.rows
|
||||
.map((row) => Number(row.bus_line_id))
|
||||
.filter(Number.isFinite),
|
||||
),
|
||||
);
|
||||
|
||||
const routeStopsByLine = new Map();
|
||||
if (lineIds.length > 0) {
|
||||
const routeStopsResult = await db.query(
|
||||
`
|
||||
SELECT
|
||||
rs.bus_line_id,
|
||||
rs.stop_id,
|
||||
rs.stop_order,
|
||||
rs.estimated_arrival_minutes,
|
||||
s.name AS stop_name
|
||||
FROM route_stops rs
|
||||
JOIN stops s ON s.id = rs.stop_id
|
||||
WHERE rs.bus_line_id = ANY($1::int[])
|
||||
ORDER BY rs.bus_line_id ASC, rs.stop_order ASC
|
||||
`,
|
||||
[lineIds],
|
||||
);
|
||||
|
||||
for (const row of routeStopsResult.rows) {
|
||||
const busLineId = Number(row.bus_line_id);
|
||||
if (!routeStopsByLine.has(busLineId)) {
|
||||
routeStopsByLine.set(busLineId, []);
|
||||
}
|
||||
routeStopsByLine.get(busLineId).push(row);
|
||||
}
|
||||
}
|
||||
|
||||
const filters = parseScheduleFilters(req.query);
|
||||
const rowSource = templatesOnly
|
||||
? result.rows
|
||||
: expandRecurringScheduleRows(result.rows);
|
||||
const expandedSchedules = rowSource.filter((row) =>
|
||||
scheduleMatchesFilters(row, filters, routeStopsByLine),
|
||||
);
|
||||
|
||||
const schedules = expandedSchedules
|
||||
.map((row) => mapAdminScheduleRow(row, routeStopsByLine))
|
||||
.sort((a, b) => new Date(a.startTime) - new Date(b.startTime));
|
||||
|
||||
return { statusCode: 200, body: { schedules } };
|
||||
} catch (err) {
|
||||
console.error("GET /admin/schedules error:", err);
|
||||
reportError({ partofservice: "GET /admin/schedules", error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function createAdminSchedule(req) {
|
||||
try {
|
||||
const { busLineId, busId, driverId, startTime, weekdays } = req.body;
|
||||
|
||||
if (!busLineId || !busId || !startTime) {
|
||||
return {
|
||||
statusCode: 400,
|
||||
body: {
|
||||
error:
|
||||
"missing_required_fields: busLineId, busId, startTime required",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Validate weekdays - should be array of day numbers (0-6) or empty for single schedule
|
||||
const scheduleWeekdays =
|
||||
Array.isArray(weekdays) && weekdays.length > 0
|
||||
? weekdays.map((w) => Number(w)).filter((w) => w >= 0 && w <= 6)
|
||||
: [];
|
||||
|
||||
// Database mode (production)
|
||||
const busLine = await db.query(
|
||||
"SELECT estimated_duration_minutes FROM bus_lines WHERE id = $1",
|
||||
[busLineId],
|
||||
);
|
||||
if (!busLine.rows[0]) {
|
||||
return { statusCode: 404, body: { error: "bus_line_not_found" } };
|
||||
}
|
||||
|
||||
const startDate = new Date(startTime);
|
||||
const endDate = new Date(startDate);
|
||||
endDate.setMinutes(
|
||||
endDate.getMinutes() +
|
||||
(busLine.rows[0].estimated_duration_minutes || 60),
|
||||
);
|
||||
|
||||
// Check if weekdays column exists before including it in INSERT
|
||||
const hasWeekdaysColumn = await db.query(`
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_schema='transit' AND table_name='schedules' AND column_name='weekdays'
|
||||
`);
|
||||
|
||||
let result;
|
||||
if (hasWeekdaysColumn.rows.length > 0) {
|
||||
result = await db.query(
|
||||
`
|
||||
WITH next_id AS (
|
||||
SELECT COALESCE(MAX(id), 0) + 1 AS id FROM schedules
|
||||
)
|
||||
INSERT INTO schedules (id, bus_line_id, bus_id, driver_id, start_time, end_time, status, weekdays)
|
||||
SELECT next_id.id, $1, $2, $3, $4, $5, 'planned', $6
|
||||
FROM next_id
|
||||
RETURNING id, bus_line_id, bus_id, driver_id, start_time, end_time, status, weekdays, created_at
|
||||
`,
|
||||
[
|
||||
busLineId,
|
||||
busId,
|
||||
driverId || null,
|
||||
startTime,
|
||||
endDate.toISOString(),
|
||||
JSON.stringify(scheduleWeekdays),
|
||||
],
|
||||
);
|
||||
} else {
|
||||
result = await db.query(
|
||||
`
|
||||
WITH next_id AS (
|
||||
SELECT COALESCE(MAX(id), 0) + 1 AS id FROM schedules
|
||||
)
|
||||
INSERT INTO schedules (id, bus_line_id, bus_id, driver_id, start_time, end_time, status)
|
||||
SELECT next_id.id, $1, $2, $3, $4, $5, 'planned'
|
||||
FROM next_id
|
||||
RETURNING id, bus_line_id, bus_id, driver_id, start_time, end_time, status, created_at
|
||||
`,
|
||||
[
|
||||
busLineId,
|
||||
busId,
|
||||
driverId || null,
|
||||
startTime,
|
||||
endDate.toISOString(),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
const schedule = result.rows[0];
|
||||
const departureTimes = calculateDepartureTimes(
|
||||
startTime,
|
||||
busLineId,
|
||||
_mock,
|
||||
);
|
||||
|
||||
const weekdaysResult = parseWeekdaysValue(schedule.weekdays);
|
||||
|
||||
return {
|
||||
statusCode: 201,
|
||||
body: {
|
||||
schedule: {
|
||||
id: Number(schedule.id),
|
||||
busLineId: Number(schedule.bus_line_id),
|
||||
busId: Number(schedule.bus_id),
|
||||
driverId:
|
||||
schedule.driver_id !== null && schedule.driver_id !== undefined
|
||||
? Number(schedule.driver_id)
|
||||
: null,
|
||||
startTime: schedule.start_time,
|
||||
endTime: schedule.end_time,
|
||||
weekdays: weekdaysResult,
|
||||
departureTimes,
|
||||
status: schedule.status,
|
||||
createdAt: schedule.created_at,
|
||||
},
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function updateAdminSchedule(req) {
|
||||
try {
|
||||
const { scheduleId } = req.params;
|
||||
const { busLineId, busId, driverId, startTime, weekdays } = req.body;
|
||||
|
||||
if (!scheduleId || !Number.isFinite(Number(scheduleId))) {
|
||||
return { statusCode: 400, body: { error: "invalid_schedule_id" } };
|
||||
}
|
||||
|
||||
if (!busLineId || !busId || !startTime) {
|
||||
return {
|
||||
statusCode: 400,
|
||||
body: {
|
||||
error:
|
||||
"missing_required_fields: busLineId, busId, startTime required",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const scheduleWeekdays =
|
||||
Array.isArray(weekdays) && weekdays.length > 0
|
||||
? weekdays.map((w) => Number(w)).filter((w) => w >= 0 && w <= 6)
|
||||
: [];
|
||||
|
||||
const existingResult = await db.query(
|
||||
`
|
||||
SELECT id, status
|
||||
FROM schedules
|
||||
WHERE id = $1
|
||||
`,
|
||||
[scheduleId],
|
||||
);
|
||||
|
||||
if (existingResult.rows.length === 0) {
|
||||
return { statusCode: 404, body: { error: "schedule_not_found" } };
|
||||
}
|
||||
|
||||
const busLine = await db.query(
|
||||
"SELECT estimated_duration_minutes FROM bus_lines WHERE id = $1",
|
||||
[busLineId],
|
||||
);
|
||||
if (!busLine.rows[0]) {
|
||||
return { statusCode: 404, body: { error: "bus_line_not_found" } };
|
||||
}
|
||||
|
||||
const startDate = new Date(startTime);
|
||||
const endDate = new Date(startDate);
|
||||
endDate.setMinutes(
|
||||
endDate.getMinutes() +
|
||||
(busLine.rows[0].estimated_duration_minutes || 60),
|
||||
);
|
||||
|
||||
const hasWeekdaysColumn = await db.query(`
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_schema='transit' AND table_name='schedules' AND column_name='weekdays'
|
||||
`);
|
||||
|
||||
let result;
|
||||
if (hasWeekdaysColumn.rows.length > 0) {
|
||||
result = await db.query(
|
||||
`
|
||||
UPDATE schedules
|
||||
SET
|
||||
bus_line_id = $2,
|
||||
bus_id = $3,
|
||||
driver_id = $4,
|
||||
start_time = $5,
|
||||
end_time = $6,
|
||||
weekdays = $7,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
RETURNING id, bus_line_id, bus_id, driver_id, start_time, end_time, status, weekdays, created_at
|
||||
`,
|
||||
[
|
||||
scheduleId,
|
||||
busLineId,
|
||||
busId,
|
||||
driverId || null,
|
||||
startTime,
|
||||
endDate.toISOString(),
|
||||
JSON.stringify(scheduleWeekdays),
|
||||
],
|
||||
);
|
||||
} else {
|
||||
result = await db.query(
|
||||
`
|
||||
UPDATE schedules
|
||||
SET
|
||||
bus_line_id = $2,
|
||||
bus_id = $3,
|
||||
driver_id = $4,
|
||||
start_time = $5,
|
||||
end_time = $6,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
RETURNING id, bus_line_id, bus_id, driver_id, start_time, end_time, status, created_at
|
||||
`,
|
||||
[
|
||||
scheduleId,
|
||||
busLineId,
|
||||
busId,
|
||||
driverId || null,
|
||||
startTime,
|
||||
endDate.toISOString(),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
const schedule = result.rows[0];
|
||||
return {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
schedule: {
|
||||
id: Number(schedule.id),
|
||||
busLineId: Number(schedule.bus_line_id),
|
||||
busId: Number(schedule.bus_id),
|
||||
driverId:
|
||||
schedule.driver_id !== null && schedule.driver_id !== undefined
|
||||
? Number(schedule.driver_id)
|
||||
: null,
|
||||
startTime: schedule.start_time,
|
||||
endTime: schedule.end_time,
|
||||
weekdays: parseWeekdaysValue(schedule.weekdays),
|
||||
status: schedule.status,
|
||||
createdAt: schedule.created_at,
|
||||
},
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function bulkCreateAdminSchedules(req) {
|
||||
const requestedSchedules = Array.isArray(req.body?.schedules)
|
||||
? req.body.schedules
|
||||
: [];
|
||||
|
||||
if (requestedSchedules.length === 0) {
|
||||
return {
|
||||
statusCode: 400,
|
||||
body: { error: "missing_required_fields: schedules array required" },
|
||||
};
|
||||
}
|
||||
|
||||
const normalizedSchedules = requestedSchedules.map((schedule, index) => {
|
||||
const busLineId = Number(schedule?.busLineId);
|
||||
const busId = Number(schedule?.busId);
|
||||
const driverId =
|
||||
schedule?.driverId !== null &&
|
||||
schedule?.driverId !== undefined &&
|
||||
schedule?.driverId !== ""
|
||||
? Number(schedule.driverId)
|
||||
: null;
|
||||
const startTime = schedule?.startTime ? String(schedule.startTime) : "";
|
||||
const weekdays =
|
||||
Array.isArray(schedule?.weekdays) && schedule.weekdays.length > 0
|
||||
? schedule.weekdays
|
||||
.map((day) => Number(day))
|
||||
.filter((day) => day >= 0 && day <= 6)
|
||||
: [];
|
||||
|
||||
if (
|
||||
!Number.isFinite(busLineId) ||
|
||||
!Number.isFinite(busId) ||
|
||||
!startTime
|
||||
) {
|
||||
throw new Error(`invalid_schedule_entry:${index}`);
|
||||
}
|
||||
|
||||
return { busLineId, busId, driverId, startTime, weekdays };
|
||||
});
|
||||
|
||||
try {
|
||||
const dbClient = await db.pool.connect();
|
||||
try {
|
||||
await dbClient.query("BEGIN");
|
||||
|
||||
const hasWeekdaysColumn = await dbClient.query(`
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_schema='transit' AND table_name='schedules' AND column_name='weekdays'
|
||||
`);
|
||||
|
||||
const createdSchedules = [];
|
||||
|
||||
for (const entry of normalizedSchedules) {
|
||||
const busLine = await dbClient.query(
|
||||
"SELECT estimated_duration_minutes FROM bus_lines WHERE id = $1",
|
||||
[entry.busLineId],
|
||||
);
|
||||
if (!busLine.rows[0]) {
|
||||
throw new Error("bus_line_not_found");
|
||||
}
|
||||
|
||||
const startDate = new Date(entry.startTime);
|
||||
const endDate = new Date(startDate);
|
||||
endDate.setMinutes(
|
||||
endDate.getMinutes() +
|
||||
(busLine.rows[0].estimated_duration_minutes || 60),
|
||||
);
|
||||
|
||||
let result;
|
||||
if (hasWeekdaysColumn.rows.length > 0) {
|
||||
result = await dbClient.query(
|
||||
`
|
||||
WITH next_id AS (
|
||||
SELECT COALESCE(MAX(id), 0) + 1 AS id FROM schedules
|
||||
)
|
||||
INSERT INTO schedules (id, bus_line_id, bus_id, driver_id, start_time, end_time, status, weekdays)
|
||||
SELECT next_id.id, $1, $2, $3, $4, $5, 'planned', $6
|
||||
FROM next_id
|
||||
RETURNING id, bus_line_id, bus_id, driver_id, start_time, end_time, status, weekdays, created_at
|
||||
`,
|
||||
[
|
||||
entry.busLineId,
|
||||
entry.busId,
|
||||
entry.driverId,
|
||||
entry.startTime,
|
||||
endDate.toISOString(),
|
||||
JSON.stringify(entry.weekdays),
|
||||
],
|
||||
);
|
||||
} else {
|
||||
result = await dbClient.query(
|
||||
`
|
||||
WITH next_id AS (
|
||||
SELECT COALESCE(MAX(id), 0) + 1 AS id FROM schedules
|
||||
)
|
||||
INSERT INTO schedules (id, bus_line_id, bus_id, driver_id, start_time, end_time, status)
|
||||
SELECT next_id.id, $1, $2, $3, $4, $5, 'planned'
|
||||
FROM next_id
|
||||
RETURNING id, bus_line_id, bus_id, driver_id, start_time, end_time, status, created_at
|
||||
`,
|
||||
[
|
||||
entry.busLineId,
|
||||
entry.busId,
|
||||
entry.driverId,
|
||||
entry.startTime,
|
||||
endDate.toISOString(),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
const schedule = result.rows[0];
|
||||
createdSchedules.push({
|
||||
id: Number(schedule.id),
|
||||
busLineId: Number(schedule.bus_line_id),
|
||||
busId: Number(schedule.bus_id),
|
||||
driverId:
|
||||
schedule.driver_id !== null && schedule.driver_id !== undefined
|
||||
? Number(schedule.driver_id)
|
||||
: null,
|
||||
startTime: schedule.start_time,
|
||||
endTime: schedule.end_time,
|
||||
weekdays: parseWeekdaysValue(schedule.weekdays),
|
||||
status: schedule.status,
|
||||
createdAt: schedule.created_at,
|
||||
});
|
||||
}
|
||||
|
||||
await dbClient.query("COMMIT");
|
||||
return {
|
||||
statusCode: 201,
|
||||
body: {
|
||||
createdCount: createdSchedules.length,
|
||||
schedules: createdSchedules,
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
await dbClient.query("ROLLBACK");
|
||||
throw err;
|
||||
} finally {
|
||||
dbClient.release();
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: "POST /admin/schedules/bulk", error: err.stack || err.message });
|
||||
const errorMessage =
|
||||
err.message === "bus_line_not_found"
|
||||
? "bus_line_not_found"
|
||||
: err.message.startsWith("invalid_schedule_entry:")
|
||||
? err.message
|
||||
: "internal_error";
|
||||
const statusCode =
|
||||
errorMessage === "bus_line_not_found"
|
||||
? 404
|
||||
: errorMessage.startsWith("invalid_schedule_entry:")
|
||||
? 400
|
||||
: 500;
|
||||
return { statusCode, body: { error: errorMessage, details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteAdminSchedule(req) {
|
||||
try {
|
||||
const { scheduleId } = req.params;
|
||||
|
||||
if (!scheduleId || !Number.isFinite(Number(scheduleId))) {
|
||||
return { statusCode: 400, body: { error: "invalid_schedule_id" } };
|
||||
}
|
||||
|
||||
const result = await db.query(
|
||||
`DELETE FROM schedules WHERE id = $1 RETURNING id`,
|
||||
[scheduleId],
|
||||
);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
return { statusCode: 404, body: { error: "schedule_not_found" } };
|
||||
}
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
body: { success: true, schedule: { id: Number(result.rows[0].id) } },
|
||||
};
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function checkDriverConflicts(req) {
|
||||
try {
|
||||
const {
|
||||
generatedTimes,
|
||||
drivers,
|
||||
busLineId,
|
||||
busId,
|
||||
weekdays = [],
|
||||
} = req.body;
|
||||
|
||||
if (!Array.isArray(generatedTimes) || !Array.isArray(drivers)) {
|
||||
return { statusCode: 400, body: { error: "missing_required_fields" } };
|
||||
}
|
||||
|
||||
// Get all existing schedules
|
||||
const schedResult = DEV_MOCK
|
||||
? { rows: _mock.schedules || [] }
|
||||
: await db.query(
|
||||
`SELECT * FROM schedules WHERE status IN ('planned', 'active')`,
|
||||
);
|
||||
|
||||
const existingSchedules = schedResult.rows.map((row) => ({
|
||||
...row,
|
||||
weekdays: parseWeekdaysValue(row.weekdays || row.weekday_list || "[]"),
|
||||
}));
|
||||
|
||||
// For each generated time, check conflicts with each driver
|
||||
const assignments = generatedTimes.map((timeStr) => {
|
||||
const driverAssignments = drivers.map((driver) => {
|
||||
const hasConflict = checkDriverConflict(
|
||||
driver.id,
|
||||
timeStr,
|
||||
timeStr, // Will be checked with start/end times of conflicts
|
||||
weekdays,
|
||||
existingSchedules,
|
||||
);
|
||||
|
||||
return {
|
||||
driverId: driver.id,
|
||||
driverName: driver.name,
|
||||
hasConflict,
|
||||
assigned: false,
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
time: timeStr,
|
||||
driverAssignments,
|
||||
assignedDriverId: null,
|
||||
};
|
||||
});
|
||||
|
||||
return { statusCode: 200, body: { assignments } };
|
||||
} catch (err) {
|
||||
console.error("/admin/check-driver-conflicts error:", err);
|
||||
reportError({ partofservice: "/admin/check-driver-conflicts", error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function assignSchedules(req) {
|
||||
try {
|
||||
const { assignments, busLineId, busId, weekdays = [] } = req.body;
|
||||
|
||||
if (!Array.isArray(assignments)) {
|
||||
return { statusCode: 400, body: { error: "missing_assignments" } };
|
||||
}
|
||||
|
||||
// Group assignments by driver (round-robin or custom)
|
||||
const schedulesToCreate = [];
|
||||
let driverIndex = 0;
|
||||
|
||||
for (const assignment of assignments) {
|
||||
if (!assignment.time || !assignment.assignedDriverId) continue;
|
||||
|
||||
const startTime = assignment.time;
|
||||
const endTime = assignment.endTime;
|
||||
|
||||
schedulesToCreate.push({
|
||||
busLineId,
|
||||
busId,
|
||||
driverId: assignment.assignedDriverId,
|
||||
startTime,
|
||||
endTime,
|
||||
weekdays,
|
||||
});
|
||||
}
|
||||
|
||||
// For DB: use bulk insert
|
||||
return {
|
||||
statusCode: 201,
|
||||
body: {
|
||||
createdCount: schedulesToCreate.length,
|
||||
message: "would_insert_schedules",
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
console.error("/admin/assign-schedules error:", err);
|
||||
reportError({ partofservice: "/admin/assign-schedules", error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
listAdminSchedules,
|
||||
createAdminSchedule,
|
||||
updateAdminSchedule,
|
||||
bulkCreateAdminSchedules,
|
||||
deleteAdminSchedule,
|
||||
checkDriverConflicts,
|
||||
assignSchedules,
|
||||
};
|
||||
@@ -0,0 +1,390 @@
|
||||
const { store: _mock } = require("../mock/store");
|
||||
const { calculateDepartureTimes, expandRecurringScheduleRows, scheduleMatchesFilters, parseScheduleFilters } = require("../lib/schedule");
|
||||
const { reportError } = require("../lib/report-error");
|
||||
|
||||
// Admin schedules repository methods (DEV_MOCK mode). These are exact copies of
|
||||
// the original handlers’ mock branches, returning { statusCode, body }.
|
||||
|
||||
async function listAdminSchedules(req) {
|
||||
try {
|
||||
const templatesOnly =
|
||||
String(
|
||||
req.query.templates || req.query.includeTemplates || "",
|
||||
).toLowerCase() === "true" ||
|
||||
String(req.query.templates || req.query.includeTemplates || "") === "1";
|
||||
|
||||
const routeStopsByLine = new Map();
|
||||
for (const routeStop of _mock.routeStops || []) {
|
||||
const busLineId = Number(routeStop.busLineId);
|
||||
if (!routeStopsByLine.has(busLineId)) {
|
||||
routeStopsByLine.set(busLineId, []);
|
||||
}
|
||||
routeStopsByLine.get(busLineId).push({
|
||||
stop_id: routeStop.stopId,
|
||||
stop_order: routeStop.stopOrder,
|
||||
});
|
||||
}
|
||||
|
||||
const rawSchedules = (_mock.schedules || []).map((s) => {
|
||||
const busLine = _mock.busLines.find((bl) => bl.id === s.busLineId);
|
||||
const bus = _mock.fleetBuses.find((b) => b.id === s.busId);
|
||||
return {
|
||||
...s,
|
||||
busLineId: s.busLineId,
|
||||
busId: s.busId,
|
||||
startTime: s.startTime,
|
||||
endTime: s.endTime,
|
||||
weekdays: s.weekdays || [],
|
||||
status: s.status,
|
||||
lineNumber: busLine?.lineNumber || 0,
|
||||
busName: bus?.name || "Unknown Bus",
|
||||
driverId: s.driverId || null,
|
||||
estimatedDurationMinutes: busLine?.estimatedDurationMinutes || 60,
|
||||
};
|
||||
});
|
||||
|
||||
const schedules = (
|
||||
templatesOnly
|
||||
? rawSchedules
|
||||
: expandRecurringScheduleRows(rawSchedules)
|
||||
)
|
||||
.filter((row) =>
|
||||
scheduleMatchesFilters(
|
||||
row,
|
||||
parseScheduleFilters(req.query),
|
||||
routeStopsByLine,
|
||||
),
|
||||
)
|
||||
.map((s) => ({
|
||||
...s,
|
||||
departureTimes: calculateDepartureTimes(
|
||||
s.startTime,
|
||||
s.busLineId,
|
||||
_mock,
|
||||
),
|
||||
}))
|
||||
.sort((a, b) => new Date(a.startTime) - new Date(b.startTime));
|
||||
|
||||
return { statusCode: 200, body: { schedules } };
|
||||
} catch (err) {
|
||||
console.error("GET /admin/schedules error:", err);
|
||||
reportError({ partofservice: "GET /admin/schedules", error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function createAdminSchedule(req) {
|
||||
try {
|
||||
const { busLineId, busId, driverId, startTime, weekdays } = req.body;
|
||||
|
||||
if (!busLineId || !busId || !startTime) {
|
||||
return {
|
||||
statusCode: 400,
|
||||
body: {
|
||||
error:
|
||||
"missing_required_fields: busLineId, busId, startTime required",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const scheduleWeekdays =
|
||||
Array.isArray(weekdays) && weekdays.length > 0
|
||||
? weekdays.map((w) => Number(w)).filter((w) => w >= 0 && w <= 6)
|
||||
: [];
|
||||
|
||||
if (!_mock.schedules) _mock.schedules = [];
|
||||
|
||||
const busLine = _mock.busLines.find((bl) => bl.id == busLineId);
|
||||
if (!busLine) {
|
||||
return { statusCode: 404, body: { error: "bus_line_not_found" } };
|
||||
}
|
||||
|
||||
const startDate = new Date(startTime);
|
||||
const endDate = new Date(startDate);
|
||||
endDate.setMinutes(
|
||||
endDate.getMinutes() + (busLine.estimatedDurationMinutes || 60),
|
||||
);
|
||||
|
||||
const departureTimes = calculateDepartureTimes(
|
||||
startTime,
|
||||
Number(busLineId),
|
||||
_mock,
|
||||
);
|
||||
|
||||
const schedule = {
|
||||
id: _mock.nextScheduleId || 1,
|
||||
busLineId,
|
||||
busId,
|
||||
driverId: driverId ? Number(driverId) : null,
|
||||
startTime,
|
||||
endTime: endDate.toISOString(),
|
||||
weekdays: scheduleWeekdays,
|
||||
departureTimes,
|
||||
status: "planned",
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
_mock.nextScheduleId = (_mock.nextScheduleId || 1) + 1;
|
||||
_mock.schedules.push(schedule);
|
||||
return { statusCode: 201, body: { schedule } };
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function updateAdminSchedule(req) {
|
||||
try {
|
||||
const { scheduleId } = req.params;
|
||||
const { busLineId, busId, driverId, startTime, weekdays } = req.body;
|
||||
|
||||
if (!scheduleId || !Number.isFinite(Number(scheduleId))) {
|
||||
return { statusCode: 400, body: { error: "invalid_schedule_id" } };
|
||||
}
|
||||
|
||||
if (!busLineId || !busId || !startTime) {
|
||||
return {
|
||||
statusCode: 400,
|
||||
body: {
|
||||
error:
|
||||
"missing_required_fields: busLineId, busId, startTime required",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const scheduleWeekdays =
|
||||
Array.isArray(weekdays) && weekdays.length > 0
|
||||
? weekdays.map((w) => Number(w)).filter((w) => w >= 0 && w <= 6)
|
||||
: [];
|
||||
|
||||
const index = (_mock.schedules || []).findIndex(
|
||||
(s) => Number(s.id) === Number(scheduleId),
|
||||
);
|
||||
if (index === -1) {
|
||||
return { statusCode: 404, body: { error: "schedule_not_found" } };
|
||||
}
|
||||
|
||||
const busLine = _mock.busLines.find((bl) => bl.id == busLineId);
|
||||
if (!busLine) {
|
||||
return { statusCode: 404, body: { error: "bus_line_not_found" } };
|
||||
}
|
||||
|
||||
const startDate = new Date(startTime);
|
||||
const endDate = new Date(startDate);
|
||||
endDate.setMinutes(
|
||||
endDate.getMinutes() + (busLine.estimatedDurationMinutes || 60),
|
||||
);
|
||||
|
||||
_mock.schedules[index] = {
|
||||
..._mock.schedules[index],
|
||||
busLineId: Number(busLineId),
|
||||
busId: Number(busId),
|
||||
driverId: driverId ? Number(driverId) : null,
|
||||
startTime,
|
||||
endTime: endDate.toISOString(),
|
||||
weekdays: scheduleWeekdays,
|
||||
};
|
||||
|
||||
return { statusCode: 200, body: { schedule: _mock.schedules[index] } };
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function bulkCreateAdminSchedules(req) {
|
||||
const requestedSchedules = Array.isArray(req.body?.schedules)
|
||||
? req.body.schedules
|
||||
: [];
|
||||
|
||||
if (requestedSchedules.length === 0) {
|
||||
return {
|
||||
statusCode: 400,
|
||||
body: { error: "missing_required_fields: schedules array required" },
|
||||
};
|
||||
}
|
||||
|
||||
const normalizedSchedules = requestedSchedules.map((schedule, index) => {
|
||||
const busLineId = Number(schedule?.busLineId);
|
||||
const busId = Number(schedule?.busId);
|
||||
const driverId =
|
||||
schedule?.driverId !== null &&
|
||||
schedule?.driverId !== undefined &&
|
||||
schedule?.driverId !== ""
|
||||
? Number(schedule.driverId)
|
||||
: null;
|
||||
const startTime = schedule?.startTime ? String(schedule.startTime) : "";
|
||||
const weekdays =
|
||||
Array.isArray(schedule?.weekdays) && schedule.weekdays.length > 0
|
||||
? schedule.weekdays
|
||||
.map((day) => Number(day))
|
||||
.filter((day) => day >= 0 && day <= 6)
|
||||
: [];
|
||||
|
||||
if (
|
||||
!Number.isFinite(busLineId) ||
|
||||
!Number.isFinite(busId) ||
|
||||
!startTime
|
||||
) {
|
||||
throw new Error(`invalid_schedule_entry:${index}`);
|
||||
}
|
||||
|
||||
return { busLineId, busId, driverId, startTime, weekdays };
|
||||
});
|
||||
|
||||
try {
|
||||
if (!_mock.schedules) _mock.schedules = [];
|
||||
|
||||
const createdSchedules = [];
|
||||
|
||||
for (const entry of normalizedSchedules) {
|
||||
const busLine = _mock.busLines.find((bl) => bl.id == entry.busLineId);
|
||||
if (!busLine) {
|
||||
return { statusCode: 404, body: { error: "bus_line_not_found" } };
|
||||
}
|
||||
|
||||
const startDate = new Date(entry.startTime);
|
||||
const endDate = new Date(startDate);
|
||||
endDate.setMinutes(
|
||||
endDate.getMinutes() + (busLine.estimatedDurationMinutes || 60),
|
||||
);
|
||||
|
||||
const departureTimes = calculateDepartureTimes(
|
||||
entry.startTime,
|
||||
Number(entry.busLineId),
|
||||
_mock,
|
||||
);
|
||||
|
||||
const schedule = {
|
||||
id: _mock.nextScheduleId || 1,
|
||||
busLineId: entry.busLineId,
|
||||
busId: entry.busId,
|
||||
driverId: entry.driverId,
|
||||
startTime: entry.startTime,
|
||||
endTime: endDate.toISOString(),
|
||||
weekdays: entry.weekdays,
|
||||
departureTimes,
|
||||
status: "planned",
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
_mock.nextScheduleId = (_mock.nextScheduleId || 1) + 1;
|
||||
_mock.schedules.push(schedule);
|
||||
createdSchedules.push(schedule);
|
||||
}
|
||||
|
||||
return {
|
||||
statusCode: 201,
|
||||
body: {
|
||||
createdCount: createdSchedules.length,
|
||||
schedules: createdSchedules,
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: "POST /admin/schedules/bulk", error: err.stack || err.message });
|
||||
const errorMessage =
|
||||
err.message === "bus_line_not_found"
|
||||
? "bus_line_not_found"
|
||||
: err.message.startsWith("invalid_schedule_entry:")
|
||||
? err.message
|
||||
: "internal_error";
|
||||
const statusCode =
|
||||
errorMessage === "bus_line_not_found"
|
||||
? 404
|
||||
: errorMessage.startsWith("invalid_schedule_entry:")
|
||||
? 400
|
||||
: 500;
|
||||
return { statusCode, body: { error: errorMessage, details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteAdminSchedule(req) {
|
||||
try {
|
||||
const { scheduleId } = req.params;
|
||||
|
||||
if (!scheduleId || !Number.isFinite(Number(scheduleId))) {
|
||||
return { statusCode: 400, body: { error: "invalid_schedule_id" } };
|
||||
}
|
||||
|
||||
if (!_mock.schedules) _mock.schedules = [];
|
||||
const index = _mock.schedules.findIndex(
|
||||
(s) => Number(s.id) === Number(scheduleId),
|
||||
);
|
||||
if (index === -1) {
|
||||
return { statusCode: 404, body: { error: "schedule_not_found" } };
|
||||
}
|
||||
const deleted = _mock.schedules.splice(index, 1)[0];
|
||||
return { statusCode: 200, body: { success: true, schedule: deleted } };
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function assignSchedules(req) {
|
||||
try {
|
||||
const { assignments, busLineId, busId, weekdays = [] } = req.body;
|
||||
|
||||
if (!Array.isArray(assignments)) {
|
||||
return { statusCode: 400, body: { error: "missing_assignments" } };
|
||||
}
|
||||
|
||||
const schedulesToCreate = [];
|
||||
let driverIndex = 0;
|
||||
|
||||
for (const assignment of assignments) {
|
||||
if (!assignment.time || !assignment.assignedDriverId) continue;
|
||||
|
||||
const startTime = assignment.time;
|
||||
const endTime = assignment.endTime;
|
||||
|
||||
schedulesToCreate.push({
|
||||
busLineId,
|
||||
busId,
|
||||
driverId: assignment.assignedDriverId,
|
||||
startTime,
|
||||
endTime,
|
||||
weekdays,
|
||||
});
|
||||
}
|
||||
|
||||
if (!_mock.schedules) _mock.schedules = [];
|
||||
const createdSchedules = [];
|
||||
|
||||
for (const entry of schedulesToCreate) {
|
||||
const schedule = {
|
||||
id: _mock.nextScheduleId || 1,
|
||||
...entry,
|
||||
status: "planned",
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
_mock.nextScheduleId = (_mock.nextScheduleId || 1) + 1;
|
||||
_mock.schedules.push(schedule);
|
||||
createdSchedules.push(schedule);
|
||||
}
|
||||
|
||||
return {
|
||||
statusCode: 201,
|
||||
body: {
|
||||
createdCount: createdSchedules.length,
|
||||
schedules: createdSchedules,
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
console.error("/admin/assign-schedules error:", err);
|
||||
reportError({ partofservice: "/admin/assign-schedules", error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
listAdminSchedules,
|
||||
createAdminSchedule,
|
||||
updateAdminSchedule,
|
||||
bulkCreateAdminSchedules,
|
||||
deleteAdminSchedule,
|
||||
assignSchedules,
|
||||
};
|
||||
@@ -0,0 +1,238 @@
|
||||
const db = require("../db");
|
||||
const { DEV_MOCK } = require("../lib/env");
|
||||
const { isValidDateKey } = require("../lib/validate");
|
||||
const { reportError } = require("../lib/report-error");
|
||||
|
||||
// Daily schedule repository methods (PostgreSQL-mode behavior; the original
|
||||
// handlers always queried the DB and only used `DEV_MOCK` to suppress the
|
||||
// fallbacks, so this module is used in both modes).
|
||||
|
||||
async function listDailySchedules(req) {
|
||||
try {
|
||||
const { date } = req.query;
|
||||
const userId = req.user.userId;
|
||||
|
||||
if (!date) {
|
||||
return { statusCode: 400, body: { error: "date query parameter required" } };
|
||||
}
|
||||
|
||||
const result = await db.query(
|
||||
`
|
||||
SELECT
|
||||
r.id,
|
||||
r.start_time,
|
||||
r.end_time,
|
||||
r.status,
|
||||
bl.id as line_id,
|
||||
bl.line_number,
|
||||
bl.start_stop,
|
||||
bl.end_stop,
|
||||
bl.estimated_duration_minutes,
|
||||
bl.description,
|
||||
bt.id as bus_type_id,
|
||||
bt.name as bus_type,
|
||||
bt.seat_capacity,
|
||||
bt.license_plate
|
||||
FROM routes r
|
||||
JOIN bus_lines bl ON r.bus_line_id = bl.id
|
||||
JOIN fleet.bus bt ON r.bus_type_id = bt.id
|
||||
WHERE r.user_id = $1 AND DATE(r.start_time) = $2
|
||||
ORDER BY r.start_time ASC
|
||||
`,
|
||||
[userId, date],
|
||||
);
|
||||
|
||||
let routes = result.rows.map((row) => ({
|
||||
id: row.id,
|
||||
startTime: row.start_time,
|
||||
endTime: row.end_time,
|
||||
status: row.status,
|
||||
busLine: {
|
||||
id: row.line_id,
|
||||
lineNumber: row.line_number,
|
||||
startStop: row.start_stop,
|
||||
endStop: row.end_stop,
|
||||
estimatedDuration: row.estimated_duration_minutes,
|
||||
description: row.description,
|
||||
},
|
||||
busType: {
|
||||
id: row.bus_type_id,
|
||||
name: row.bus_type,
|
||||
seatCapacity: row.seat_capacity,
|
||||
licensePlate: row.license_plate,
|
||||
},
|
||||
}));
|
||||
|
||||
// If no explicit "routes" rows exist for this user/date, fall back to
|
||||
// checking scheduled runs in `schedules` (filtered by driver_id).
|
||||
// This works around cases where DB permissions prevent inserting into
|
||||
// `routes` but schedules exist and should be shown to the driver.
|
||||
if (!DEV_MOCK && routes.length === 0) {
|
||||
const fallback = await db.query(
|
||||
`
|
||||
SELECT
|
||||
s.id,
|
||||
s.start_time,
|
||||
s.end_time,
|
||||
s.status,
|
||||
s.bus_line_id,
|
||||
bl.line_number,
|
||||
bl.start_stop,
|
||||
bl.end_stop,
|
||||
bl.estimated_duration_minutes,
|
||||
bl.description,
|
||||
s.bus_id,
|
||||
bt.id as bus_type_id,
|
||||
bt.name as bus_type,
|
||||
bt.seat_capacity,
|
||||
bt.license_plate
|
||||
FROM schedules s
|
||||
JOIN bus_lines bl ON s.bus_line_id = bl.id
|
||||
JOIN fleet.bus bt ON s.bus_id = bt.id
|
||||
WHERE s.driver_id = $1 AND DATE(s.start_time) = $2
|
||||
ORDER BY s.start_time ASC
|
||||
`,
|
||||
[userId, date],
|
||||
);
|
||||
|
||||
routes = fallback.rows.map((row) => ({
|
||||
id: row.id,
|
||||
startTime: row.start_time,
|
||||
endTime: row.end_time,
|
||||
status: row.status,
|
||||
busLine: {
|
||||
id: row.bus_line_id,
|
||||
lineNumber: row.line_number,
|
||||
startStop: row.start_stop,
|
||||
endStop: row.end_stop,
|
||||
estimatedDuration: row.estimated_duration_minutes,
|
||||
description: row.description,
|
||||
},
|
||||
busType: {
|
||||
id: row.bus_type_id,
|
||||
name: row.bus_type,
|
||||
seatCapacity: row.seat_capacity,
|
||||
licensePlate: row.license_plate,
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
// If still empty, try to synthesize a single route by shifting a recent
|
||||
// schedule's time-of-day to the requested date. This is a non-destructive
|
||||
// fallback to make sure drivers see a trip when DB inserts are restricted.
|
||||
if (!DEV_MOCK && routes.length === 0) {
|
||||
const tmplRes = await db.query(
|
||||
`
|
||||
SELECT s.start_time, s.end_time, s.status, s.bus_line_id, s.bus_id, s.driver_id, bl.estimated_duration_minutes, bl.line_number, bl.start_stop, bl.end_stop, bl.description
|
||||
FROM schedules s
|
||||
JOIN bus_lines bl ON s.bus_line_id = bl.id
|
||||
WHERE s.driver_id = $1
|
||||
ORDER BY s.start_time DESC
|
||||
LIMIT 1
|
||||
`,
|
||||
[userId],
|
||||
);
|
||||
|
||||
if (tmplRes.rowCount > 0) {
|
||||
const t = tmplRes.rows[0];
|
||||
const requestedDate = new Date(date + "T00:00:00.000Z");
|
||||
const srcStart = new Date(t.start_time);
|
||||
const srcEnd = new Date(t.end_time);
|
||||
|
||||
// Preserve time-of-day from template, apply to requested date
|
||||
const newStart = new Date(requestedDate);
|
||||
newStart.setUTCHours(
|
||||
srcStart.getUTCHours(),
|
||||
srcStart.getUTCMinutes(),
|
||||
srcStart.getUTCSeconds(),
|
||||
srcStart.getUTCMilliseconds(),
|
||||
);
|
||||
const durationMs = srcEnd.getTime() - srcStart.getTime();
|
||||
const newEnd = new Date(newStart.getTime() + durationMs);
|
||||
|
||||
routes.push({
|
||||
id: null,
|
||||
startTime: newStart.toISOString(),
|
||||
endTime: newEnd.toISOString(),
|
||||
status: t.status || "planned",
|
||||
busLine: {
|
||||
id: t.bus_line_id,
|
||||
lineNumber: t.line_number,
|
||||
startStop: t.start_stop,
|
||||
endStop: t.end_stop,
|
||||
estimatedDuration: t.estimated_duration_minutes,
|
||||
description: t.description,
|
||||
},
|
||||
busType: {
|
||||
id: t.bus_id,
|
||||
name: null,
|
||||
seatCapacity: null,
|
||||
licensePlate: null,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return { statusCode: 200, body: { date, routes } };
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function listDriverDailySchedules(req) {
|
||||
try {
|
||||
const { date } = req.query;
|
||||
if (!isValidDateKey(date)) {
|
||||
return { statusCode: 400, body: { error: "date must use YYYY-MM-DD format" } };
|
||||
}
|
||||
|
||||
const result = await db.query(
|
||||
`
|
||||
SELECT s.id, s.bus_line_id, s.start_time, s.end_time, s.status, s.day_of_week,
|
||||
bl.line_number, bl.start_stop, bl.end_stop, bl.estimated_duration_minutes,
|
||||
bl.description
|
||||
FROM schedules s
|
||||
JOIN bus_lines bl ON bl.id = s.bus_line_id
|
||||
WHERE EXISTS (
|
||||
SELECT 1
|
||||
FROM shifts sh
|
||||
WHERE sh.schedule_id = s.id AND sh.driver_id = $1
|
||||
)
|
||||
AND s.day_of_week = EXTRACT(DOW FROM $2::date)::int
|
||||
AND s.status <> 'cancelled'
|
||||
ORDER BY s.start_time ASC
|
||||
`,
|
||||
[req.user.userId, date],
|
||||
);
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
date,
|
||||
routes: result.rows.map((row) => ({
|
||||
id: Number(row.id),
|
||||
startTime: row.start_time,
|
||||
endTime: row.end_time,
|
||||
status: row.status,
|
||||
dayOfWeek: Number(row.day_of_week),
|
||||
busLine: {
|
||||
id: Number(row.bus_line_id),
|
||||
lineNumber: row.line_number,
|
||||
startStop: row.start_stop,
|
||||
endStop: row.end_stop,
|
||||
estimatedDuration: row.estimated_duration_minutes,
|
||||
description: row.description,
|
||||
},
|
||||
})),
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
console.error("GET /driver/schedules/daily error:", err);
|
||||
reportError({ partofservice: "GET /driver/schedules/daily", error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error" } };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { listDailySchedules, listDriverDailySchedules };
|
||||
@@ -0,0 +1,88 @@
|
||||
const db = require("../db");
|
||||
const { parseWeekdaysValue, checkDriverConflict } = require("../lib/schedule");
|
||||
const { reportError } = require("../lib/report-error");
|
||||
|
||||
// Driver repository methods (PostgreSQL mode).
|
||||
|
||||
async function listDrivers(req) {
|
||||
try {
|
||||
const result = await db.query(`
|
||||
SELECT id, firstname, lastname, email, phone, job, joined, status
|
||||
FROM workers.employees
|
||||
WHERE status = 'active'
|
||||
ORDER BY firstname, lastname ASC
|
||||
`);
|
||||
|
||||
// Get all schedules to check for conflicts
|
||||
const schedulesResult = await db.query(
|
||||
`SELECT * FROM schedules WHERE status IN ('planned', 'active')`,
|
||||
);
|
||||
const schedules = schedulesResult.rows.map((row) => ({
|
||||
...row,
|
||||
weekdays: parseWeekdaysValue(row.weekdays),
|
||||
}));
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
drivers: result.rows.map((row) => {
|
||||
const driverId = row.id;
|
||||
const now = new Date();
|
||||
const tomorrow = new Date(now);
|
||||
tomorrow.setDate(tomorrow.getDate() + 1);
|
||||
const isAvailable = !checkDriverConflict(
|
||||
driverId,
|
||||
now.toISOString(),
|
||||
tomorrow.toISOString(),
|
||||
[],
|
||||
schedules,
|
||||
);
|
||||
|
||||
return {
|
||||
id: row.id,
|
||||
name: (
|
||||
String(row.firstname || "") +
|
||||
" " +
|
||||
String(row.lastname || "")
|
||||
).trim(),
|
||||
email: row.email,
|
||||
phone: row.phone,
|
||||
job: row.job,
|
||||
joined: row.joined,
|
||||
status: row.status,
|
||||
available: isAvailable,
|
||||
};
|
||||
}),
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function listShiftDrivers(req) {
|
||||
try {
|
||||
const result = await db.query(`
|
||||
SELECT id, usercode
|
||||
FROM workers.users
|
||||
ORDER BY usercode ASC
|
||||
`);
|
||||
return {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
drivers: result.rows.map((row) => ({
|
||||
id: Number(row.id),
|
||||
name: String(row.usercode),
|
||||
})),
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
console.error("GET /admin/shift-drivers error:", err);
|
||||
reportError({ partofservice: "GET /admin/shift-drivers", error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error" } };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { listDrivers, listShiftDrivers };
|
||||
@@ -0,0 +1,34 @@
|
||||
const { store } = require("../mock/store");
|
||||
const { checkDriverConflict } = require("../lib/schedule");
|
||||
const { reportError } = require("../lib/report-error");
|
||||
|
||||
// Driver repository methods (DEV_MOCK mode).
|
||||
|
||||
async function listDrivers(req) {
|
||||
try {
|
||||
const drivers = store.drivers
|
||||
.slice()
|
||||
.filter((d) => d.status === "active");
|
||||
return {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
drivers: drivers.map((d) => ({
|
||||
...d,
|
||||
available: !checkDriverConflict(
|
||||
d.id,
|
||||
new Date().toISOString(),
|
||||
new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
|
||||
[],
|
||||
store.schedules || [],
|
||||
),
|
||||
})),
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { listDrivers };
|
||||
@@ -0,0 +1,159 @@
|
||||
const db = require("../db");
|
||||
const { parseWeekdaysValue, checkBusConflict } = require("../lib/schedule");
|
||||
const { reportError } = require("../lib/report-error");
|
||||
|
||||
// Fleet repository methods (PostgreSQL mode).
|
||||
|
||||
async function listFleetBuses(req) {
|
||||
try {
|
||||
const result = await db.query(`
|
||||
SELECT id, name, seat_capacity, license_plate
|
||||
FROM fleet.bus
|
||||
ORDER BY id ASC
|
||||
`);
|
||||
|
||||
// Get all schedules to check for conflicts
|
||||
const schedulesResult = await db.query(
|
||||
`SELECT * FROM schedules WHERE status IN ('planned', 'active')`,
|
||||
);
|
||||
const schedules = schedulesResult.rows.map((row) => ({
|
||||
...row,
|
||||
weekdays: parseWeekdaysValue(row.weekdays),
|
||||
}));
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
buses: result.rows.map((row) => {
|
||||
const busId = row.id;
|
||||
const now = new Date();
|
||||
const tomorrow = new Date(now);
|
||||
tomorrow.setDate(tomorrow.getDate() + 1);
|
||||
const isAvailable = !checkBusConflict(
|
||||
busId,
|
||||
now.toISOString(),
|
||||
tomorrow.toISOString(),
|
||||
[],
|
||||
schedules,
|
||||
);
|
||||
|
||||
return {
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
seatCapacity: row.seat_capacity,
|
||||
licensePlate: row.license_plate,
|
||||
available: isAvailable,
|
||||
};
|
||||
}),
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function createFleetBus(req) {
|
||||
try {
|
||||
const { name, seatCapacity, licensePlate } = req.body;
|
||||
|
||||
if (!name || seatCapacity === undefined || !licensePlate) {
|
||||
return { statusCode: 400, body: { error: "missing_required_fields" } };
|
||||
}
|
||||
|
||||
const result = await db.query(
|
||||
`
|
||||
WITH next_id AS (
|
||||
SELECT COALESCE(MAX(id), 0) + 1 AS id FROM fleet.bus
|
||||
)
|
||||
INSERT INTO fleet.bus (id, name, seat_capacity, license_plate)
|
||||
SELECT next_id.id, $1, $2, $3
|
||||
FROM next_id
|
||||
RETURNING id, name, seat_capacity, license_plate
|
||||
`,
|
||||
[name, seatCapacity, licensePlate],
|
||||
);
|
||||
|
||||
const bus = result.rows[0];
|
||||
return {
|
||||
statusCode: 201,
|
||||
body: {
|
||||
bus: {
|
||||
id: bus.id,
|
||||
name: bus.name,
|
||||
seatCapacity: bus.seat_capacity,
|
||||
licensePlate: bus.license_plate,
|
||||
},
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function updateFleetBus(req) {
|
||||
try {
|
||||
const { busId } = req.params;
|
||||
const { name, seatCapacity, licensePlate } = req.body;
|
||||
|
||||
if (!busId || !Number.isFinite(Number(busId))) {
|
||||
return { statusCode: 400, body: { error: "invalid_bus_id" } };
|
||||
}
|
||||
|
||||
const result = await db.query(
|
||||
`
|
||||
UPDATE fleet.bus
|
||||
SET name = COALESCE($1, name), seat_capacity = COALESCE($2, seat_capacity), license_plate = COALESCE($3, license_plate), updated_at = NOW()
|
||||
WHERE id = $4
|
||||
RETURNING id, name, seat_capacity, license_plate
|
||||
`,
|
||||
[name ?? null, seatCapacity ?? null, licensePlate ?? null, busId],
|
||||
);
|
||||
|
||||
if (!result.rows[0])
|
||||
return { statusCode: 404, body: { error: "bus_not_found" } };
|
||||
|
||||
const bus = result.rows[0];
|
||||
return {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
bus: {
|
||||
id: bus.id,
|
||||
name: bus.name,
|
||||
seatCapacity: bus.seat_capacity,
|
||||
licensePlate: bus.license_plate,
|
||||
},
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteFleetBus(req) {
|
||||
try {
|
||||
const { busId } = req.params;
|
||||
if (!busId || !Number.isFinite(Number(busId))) {
|
||||
return { statusCode: 400, body: { error: "invalid_bus_id" } };
|
||||
}
|
||||
|
||||
const result = await db.query(
|
||||
`DELETE FROM fleet.bus WHERE id = $1 RETURNING id, name`,
|
||||
[busId],
|
||||
);
|
||||
if (result.rows.length === 0)
|
||||
return { statusCode: 404, body: { error: "bus_not_found" } };
|
||||
return { statusCode: 200, body: { success: true, bus: result.rows[0] } };
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { listFleetBuses, createFleetBus, updateFleetBus, deleteFleetBus };
|
||||
@@ -0,0 +1,102 @@
|
||||
const { store } = require("../mock/store");
|
||||
const { checkBusConflict } = require("../lib/schedule");
|
||||
const { reportError } = require("../lib/report-error");
|
||||
|
||||
// Fleet repository methods (DEV_MOCK mode).
|
||||
|
||||
async function listFleetBuses(req) {
|
||||
try {
|
||||
const buses = store.fleetBuses.slice().sort((a, b) => a.id - b.id);
|
||||
return {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
buses: buses.map((b) => ({
|
||||
...b,
|
||||
available: !checkBusConflict(
|
||||
b.id,
|
||||
new Date().toISOString(),
|
||||
new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
|
||||
[],
|
||||
store.schedules || [],
|
||||
),
|
||||
})),
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function createFleetBus(req) {
|
||||
try {
|
||||
const { name, seatCapacity, licensePlate } = req.body;
|
||||
|
||||
if (!name || seatCapacity === undefined || !licensePlate) {
|
||||
return { statusCode: 400, body: { error: "missing_required_fields" } };
|
||||
}
|
||||
|
||||
const bus = {
|
||||
id: store.nextFleetBusId++,
|
||||
name,
|
||||
seatCapacity: Number(seatCapacity),
|
||||
licensePlate,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
store.fleetBuses.push(bus);
|
||||
return { statusCode: 201, body: { bus } };
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function updateFleetBus(req) {
|
||||
try {
|
||||
const { busId } = req.params;
|
||||
const { name, seatCapacity, licensePlate } = req.body;
|
||||
|
||||
if (!busId || !Number.isFinite(Number(busId))) {
|
||||
return { statusCode: 400, body: { error: "invalid_bus_id" } };
|
||||
}
|
||||
|
||||
const bus = store.fleetBuses.find(
|
||||
(b) => Number(b.id) === Number(busId),
|
||||
);
|
||||
if (!bus) return { statusCode: 404, body: { error: "bus_not_found" } };
|
||||
if (name !== undefined) bus.name = name;
|
||||
if (seatCapacity !== undefined) bus.seatCapacity = Number(seatCapacity);
|
||||
if (licensePlate !== undefined) bus.licensePlate = licensePlate;
|
||||
bus.updatedAt = new Date().toISOString();
|
||||
return { statusCode: 200, body: { bus } };
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteFleetBus(req) {
|
||||
try {
|
||||
const { busId } = req.params;
|
||||
if (!busId || !Number.isFinite(Number(busId))) {
|
||||
return { statusCode: 400, body: { error: "invalid_bus_id" } };
|
||||
}
|
||||
|
||||
const idx = store.fleetBuses.findIndex(
|
||||
(b) => Number(b.id) === Number(busId),
|
||||
);
|
||||
if (idx === -1) return { statusCode: 404, body: { error: "bus_not_found" } };
|
||||
const deleted = store.fleetBuses.splice(idx, 1)[0];
|
||||
return { statusCode: 200, body: { success: true, bus: deleted } };
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { listFleetBuses, createFleetBus, updateFleetBus, deleteFleetBus };
|
||||
@@ -0,0 +1,88 @@
|
||||
const db = require("../db");
|
||||
const { reportError } = require("../lib/report-error");
|
||||
|
||||
// GPS repository methods (PostgreSQL mode; no DEV_MOCK branch).
|
||||
|
||||
async function saveGpsTrack(req) {
|
||||
try {
|
||||
const { routeId, latitude, longitude, speed, heading, accuracy } = req.body;
|
||||
|
||||
if (!routeId || !latitude || !longitude) {
|
||||
return { statusCode: 400, body: { error: "missing_required_fields" } };
|
||||
}
|
||||
|
||||
await db.query(
|
||||
`
|
||||
INSERT INTO gps_tracking
|
||||
(route_id, latitude, longitude, speed_kmh, heading, accuracy, recorded_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, NOW())
|
||||
`,
|
||||
[
|
||||
routeId,
|
||||
latitude,
|
||||
longitude,
|
||||
speed || null,
|
||||
heading || null,
|
||||
accuracy || null,
|
||||
],
|
||||
);
|
||||
|
||||
return { statusCode: 200, body: { ok: true } };
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function listRouteGpsPoints(req) {
|
||||
try {
|
||||
const { routeId } = req.params;
|
||||
const userId = req.user.userId;
|
||||
|
||||
// Verify user owns this route
|
||||
const routeCheck = await db.query(
|
||||
"SELECT id FROM routes WHERE id = $1 AND user_id = $2",
|
||||
[routeId, userId],
|
||||
);
|
||||
|
||||
if (routeCheck.rows.length === 0) {
|
||||
return { statusCode: 403, body: { error: "unauthorized" } };
|
||||
}
|
||||
|
||||
const result = await db.query(
|
||||
`
|
||||
SELECT
|
||||
id,
|
||||
latitude,
|
||||
longitude,
|
||||
speed_kmh,
|
||||
heading,
|
||||
accuracy,
|
||||
recorded_at
|
||||
FROM gps_tracking
|
||||
WHERE route_id = $1
|
||||
ORDER BY recorded_at ASC
|
||||
`,
|
||||
[routeId],
|
||||
);
|
||||
|
||||
const positions = result.rows.map((row) => ({
|
||||
id: row.id,
|
||||
latitude: parseFloat(row.latitude),
|
||||
longitude: parseFloat(row.longitude),
|
||||
speed: row.speed_kmh,
|
||||
heading: row.heading,
|
||||
accuracy: row.accuracy,
|
||||
recordedAt: row.recorded_at,
|
||||
}));
|
||||
|
||||
return { statusCode: 200, body: { positions } };
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { saveGpsTrack, listRouteGpsPoints };
|
||||
@@ -0,0 +1,36 @@
|
||||
const { DEV_MOCK } = require("../lib/env");
|
||||
|
||||
// The repository layer merges every domain's PostgreSQL implementation with the
|
||||
// mock implementations. In DEV_MOCK mode the mock methods (which read the
|
||||
// in-memory `mock/store`) shadow the DB-backed ones; endpoints that have no
|
||||
// mock branch always use the PostgreSQL implementation, exactly as the original
|
||||
// handlers did.
|
||||
//
|
||||
// Every method takes the Express `req` (the original handlers read params,
|
||||
// query, body and user from it) and returns `{ statusCode, body }`. Route
|
||||
// handlers only transform that into `res.status(...).json(...)`.
|
||||
|
||||
const pg = {
|
||||
...require("./stops"),
|
||||
...require("./lines"),
|
||||
...require("./fleet"),
|
||||
...require("./drivers"),
|
||||
...require("./daily"),
|
||||
...require("./weekly"),
|
||||
...require("./adminSchedules"),
|
||||
...require("./schedules"),
|
||||
...require("./route"),
|
||||
...require("./navigation"),
|
||||
...require("./gps"),
|
||||
};
|
||||
|
||||
const mock = {
|
||||
...require("./stops.mock"),
|
||||
...require("./lines.mock"),
|
||||
...require("./fleet.mock"),
|
||||
...require("./drivers.mock"),
|
||||
...require("./adminSchedules.mock"),
|
||||
...require("./schedules.mock"),
|
||||
};
|
||||
|
||||
module.exports = DEV_MOCK ? { ...pg, ...mock } : pg;
|
||||
@@ -0,0 +1,478 @@
|
||||
const db = require("../db");
|
||||
const { reportError } = require("../lib/report-error");
|
||||
|
||||
// Bus-line repository methods (PostgreSQL mode).
|
||||
// The client-based methods keep their original `db.pool.connect()` call before
|
||||
// the try block, preserving the exact original control flow (including the
|
||||
// connection/rollback/release dance) for byte-identical behavior.
|
||||
|
||||
async function listLineStops(req) {
|
||||
try {
|
||||
const { busLineId } = req.params;
|
||||
|
||||
const result = await db.query(
|
||||
`
|
||||
SELECT
|
||||
rs.id,
|
||||
rs.stop_order,
|
||||
s.name as stop_name,
|
||||
s.latitude,
|
||||
s.longitude,
|
||||
rs.estimated_arrival_minutes
|
||||
FROM route_stops rs
|
||||
JOIN stops s ON s.id = rs.stop_id
|
||||
WHERE rs.bus_line_id = $1
|
||||
ORDER BY rs.stop_order ASC
|
||||
`,
|
||||
[busLineId],
|
||||
);
|
||||
|
||||
const stops = result.rows.map((row) => ({
|
||||
id: row.id,
|
||||
order: row.stop_order,
|
||||
name: row.stop_name,
|
||||
latitude: parseFloat(row.latitude),
|
||||
longitude: parseFloat(row.longitude),
|
||||
estimatedArrivalMinutes: row.estimated_arrival_minutes,
|
||||
}));
|
||||
|
||||
return { statusCode: 200, body: { stops } };
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function listLines(req) {
|
||||
try {
|
||||
const result = await db.query(`
|
||||
SELECT id, line_number, start_stop, end_stop, estimated_duration_minutes, description
|
||||
FROM bus_lines
|
||||
ORDER BY line_number ASC, id ASC
|
||||
`);
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
busLines: result.rows.map((row) => ({
|
||||
id: row.id,
|
||||
lineNumber: row.line_number,
|
||||
startStop: row.start_stop,
|
||||
endStop: row.end_stop,
|
||||
estimatedDurationMinutes: row.estimated_duration_minutes,
|
||||
description: row.description,
|
||||
})),
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function createLine(req) {
|
||||
try {
|
||||
const {
|
||||
lineNumber,
|
||||
startStop,
|
||||
endStop,
|
||||
estimatedDurationMinutes,
|
||||
description,
|
||||
} = req.body;
|
||||
|
||||
if (
|
||||
lineNumber === undefined ||
|
||||
!startStop ||
|
||||
!endStop ||
|
||||
estimatedDurationMinutes === undefined
|
||||
) {
|
||||
return { statusCode: 400, body: { error: "missing_required_fields" } };
|
||||
}
|
||||
|
||||
const result = await db.query(
|
||||
`
|
||||
WITH next_id AS (
|
||||
SELECT COALESCE(MAX(id), 0) + 1 AS id FROM bus_lines
|
||||
)
|
||||
INSERT INTO bus_lines (id, line_number, start_stop, end_stop, estimated_duration_minutes, description)
|
||||
SELECT next_id.id, $1, $2, $3, $4, $5
|
||||
FROM next_id
|
||||
RETURNING id, line_number, start_stop, end_stop, estimated_duration_minutes, description
|
||||
`,
|
||||
[
|
||||
lineNumber,
|
||||
startStop,
|
||||
endStop,
|
||||
estimatedDurationMinutes,
|
||||
description || null,
|
||||
],
|
||||
);
|
||||
|
||||
const busLine = result.rows[0];
|
||||
return {
|
||||
statusCode: 201,
|
||||
body: {
|
||||
busLine: {
|
||||
id: busLine.id,
|
||||
lineNumber: busLine.line_number,
|
||||
startStop: busLine.start_stop,
|
||||
endStop: busLine.end_stop,
|
||||
estimatedDurationMinutes: busLine.estimated_duration_minutes,
|
||||
description: busLine.description,
|
||||
},
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function updateLine(req) {
|
||||
try {
|
||||
const { busLineId } = req.params;
|
||||
const {
|
||||
lineNumber,
|
||||
startStop,
|
||||
endStop,
|
||||
estimatedDurationMinutes,
|
||||
description,
|
||||
} = req.body;
|
||||
|
||||
const result = await db.query(
|
||||
`
|
||||
UPDATE bus_lines
|
||||
SET
|
||||
line_number = COALESCE($1, line_number),
|
||||
start_stop = COALESCE($2, start_stop),
|
||||
end_stop = COALESCE($3, end_stop),
|
||||
estimated_duration_minutes = COALESCE($4, estimated_duration_minutes),
|
||||
description = COALESCE($5, description)
|
||||
WHERE id = $6
|
||||
RETURNING id, line_number, start_stop, end_stop, estimated_duration_minutes, description
|
||||
`,
|
||||
[
|
||||
lineNumber ?? null,
|
||||
startStop ?? null,
|
||||
endStop ?? null,
|
||||
estimatedDurationMinutes ?? null,
|
||||
description ?? null,
|
||||
busLineId,
|
||||
],
|
||||
);
|
||||
|
||||
if (!result.rows[0])
|
||||
return { statusCode: 404, body: { error: "bus_line_not_found" } };
|
||||
|
||||
const busLine = result.rows[0];
|
||||
return {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
busLine: {
|
||||
id: busLine.id,
|
||||
lineNumber: busLine.line_number,
|
||||
startStop: busLine.start_stop,
|
||||
endStop: busLine.end_stop,
|
||||
estimatedDurationMinutes: busLine.estimated_duration_minutes,
|
||||
description: busLine.description,
|
||||
},
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function listLineStopsDetailed(req) {
|
||||
try {
|
||||
const { busLineId } = req.params;
|
||||
if (!busLineId || !Number.isFinite(Number(busLineId))) {
|
||||
return { statusCode: 400, body: { error: "invalid_bus_line_id" } };
|
||||
}
|
||||
|
||||
const result = await db.query(
|
||||
`
|
||||
SELECT
|
||||
rs.id,
|
||||
rs.bus_line_id,
|
||||
rs.stop_id,
|
||||
rs.stop_order,
|
||||
rs.estimated_arrival_minutes,
|
||||
s.name as stop_name,
|
||||
s.latitude,
|
||||
s.longitude
|
||||
FROM route_stops rs
|
||||
JOIN stops s ON s.id = rs.stop_id
|
||||
WHERE rs.bus_line_id = $1
|
||||
ORDER BY rs.stop_order ASC
|
||||
`,
|
||||
[busLineId],
|
||||
);
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
routeStops: result.rows.map((row) => ({
|
||||
id: row.id,
|
||||
busLineId: row.bus_line_id,
|
||||
stopId: row.stop_id,
|
||||
stopOrder: row.stop_order,
|
||||
estimatedArrivalMinutes: row.estimated_arrival_minutes,
|
||||
name: row.stop_name,
|
||||
latitude: parseFloat(row.latitude),
|
||||
longitude: parseFloat(row.longitude),
|
||||
})),
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function addLineStop(req) {
|
||||
try {
|
||||
const { busLineId } = req.params;
|
||||
const { stopId, stopOrder, estimatedArrivalMinutes } = req.body;
|
||||
|
||||
if (!stopId || stopOrder === undefined) {
|
||||
return { statusCode: 400, body: { error: "missing_required_fields" } };
|
||||
}
|
||||
|
||||
const result = await db.query(
|
||||
`
|
||||
WITH next_id AS (
|
||||
SELECT COALESCE(MAX(id), 0) + 1 AS id FROM route_stops
|
||||
)
|
||||
INSERT INTO route_stops (id, bus_line_id, stop_id, stop_order, estimated_arrival_minutes)
|
||||
SELECT next_id.id, $1, $2, $3, $4
|
||||
FROM next_id
|
||||
ON CONFLICT (bus_line_id, stop_order) DO UPDATE SET
|
||||
stop_id = EXCLUDED.stop_id,
|
||||
estimated_arrival_minutes = EXCLUDED.estimated_arrival_minutes,
|
||||
updated_at = NOW()
|
||||
RETURNING id, bus_line_id, stop_id, stop_order, estimated_arrival_minutes, created_at, updated_at
|
||||
`,
|
||||
[busLineId, stopId, stopOrder, estimatedArrivalMinutes ?? null],
|
||||
);
|
||||
|
||||
const link = result.rows[0];
|
||||
return {
|
||||
statusCode: 201,
|
||||
body: {
|
||||
routeStop: {
|
||||
id: link.id,
|
||||
busLineId: link.bus_line_id,
|
||||
stopId: link.stop_id,
|
||||
stopOrder: link.stop_order,
|
||||
estimatedArrivalMinutes: link.estimated_arrival_minutes,
|
||||
createdAt: link.created_at,
|
||||
updatedAt: link.updated_at,
|
||||
},
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function reorderLineStops(req) {
|
||||
const client = await db.pool.connect();
|
||||
try {
|
||||
const { busLineId } = req.params;
|
||||
const { routeStopIds } = req.body || {};
|
||||
|
||||
if (!Array.isArray(routeStopIds) || routeStopIds.length === 0) {
|
||||
return { statusCode: 400, body: { error: "routeStopIds array required" } };
|
||||
}
|
||||
|
||||
const normalizedIds = routeStopIds
|
||||
.map((id) => Number(id))
|
||||
.filter((id) => Number.isFinite(id));
|
||||
if (normalizedIds.length !== routeStopIds.length) {
|
||||
return { statusCode: 400, body: { error: "routeStopIds must contain only numeric ids" } };
|
||||
}
|
||||
|
||||
const current = await client.query(
|
||||
`SELECT id FROM route_stops WHERE bus_line_id = $1 ORDER BY stop_order ASC`,
|
||||
[busLineId],
|
||||
);
|
||||
|
||||
const currentIds = current.rows.map((row) => Number(row.id));
|
||||
const sameCount = currentIds.length === normalizedIds.length;
|
||||
const sameIds =
|
||||
sameCount && normalizedIds.every((id) => currentIds.includes(id));
|
||||
|
||||
if (!sameIds) {
|
||||
return { statusCode: 400, body: { error: "routeStopIds must match current bus line stops" } };
|
||||
}
|
||||
|
||||
await client.query("BEGIN");
|
||||
|
||||
for (let index = 0; index < normalizedIds.length; index += 1) {
|
||||
await client.query(
|
||||
`UPDATE route_stops
|
||||
SET stop_order = $1, updated_at = NOW()
|
||||
WHERE id = $2 AND bus_line_id = $3`,
|
||||
[-(index + 1), normalizedIds[index], busLineId],
|
||||
);
|
||||
}
|
||||
|
||||
for (let index = 0; index < normalizedIds.length; index += 1) {
|
||||
await client.query(
|
||||
`UPDATE route_stops
|
||||
SET stop_order = $1, updated_at = NOW()
|
||||
WHERE id = $2 AND bus_line_id = $3`,
|
||||
[index + 1, normalizedIds[index], busLineId],
|
||||
);
|
||||
}
|
||||
|
||||
const result = await client.query(
|
||||
`SELECT
|
||||
rs.id,
|
||||
rs.stop_order,
|
||||
s.name as stop_name,
|
||||
s.latitude,
|
||||
s.longitude,
|
||||
rs.estimated_arrival_minutes
|
||||
FROM route_stops rs
|
||||
JOIN stops s ON s.id = rs.stop_id
|
||||
WHERE rs.bus_line_id = $1
|
||||
ORDER BY rs.stop_order ASC`,
|
||||
[busLineId],
|
||||
);
|
||||
|
||||
await client.query("COMMIT");
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
routeStops: result.rows.map((row) => ({
|
||||
id: row.id,
|
||||
order: row.stop_order,
|
||||
name: row.stop_name,
|
||||
latitude: parseFloat(row.latitude),
|
||||
longitude: parseFloat(row.longitude),
|
||||
estimatedArrivalMinutes: row.estimated_arrival_minutes,
|
||||
})),
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
await client.query("ROLLBACK").catch(() => {});
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteLine(req) {
|
||||
const client = await db.pool.connect();
|
||||
try {
|
||||
const { busLineId } = req.params;
|
||||
|
||||
if (!busLineId || !Number.isFinite(Number(busLineId))) {
|
||||
return { statusCode: 400, body: { error: "invalid_bus_line_id" } };
|
||||
}
|
||||
|
||||
await client.query("BEGIN");
|
||||
|
||||
// Delete associated route_stops first
|
||||
await client.query(
|
||||
`DELETE FROM route_stops WHERE bus_line_id = $1`,
|
||||
[busLineId],
|
||||
);
|
||||
|
||||
// Delete the bus line
|
||||
const result = await client.query(
|
||||
`DELETE FROM bus_lines WHERE id = $1 RETURNING id, line_number`,
|
||||
[busLineId],
|
||||
);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
await client.query("ROLLBACK");
|
||||
return { statusCode: 404, body: { error: "bus_line_not_found" } };
|
||||
}
|
||||
|
||||
await client.query("COMMIT");
|
||||
return { statusCode: 200, body: { success: true, busLine: result.rows[0] } };
|
||||
} catch (err) {
|
||||
await client.query("ROLLBACK").catch(() => {});
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteLineStop(req) {
|
||||
const client = await db.pool.connect();
|
||||
try {
|
||||
const { busLineId, routeStopId } = req.params;
|
||||
|
||||
if (!busLineId || !Number.isFinite(Number(busLineId))) {
|
||||
return { statusCode: 400, body: { error: "invalid_bus_line_id" } };
|
||||
}
|
||||
|
||||
if (!routeStopId || !Number.isFinite(Number(routeStopId))) {
|
||||
return { statusCode: 400, body: { error: "invalid_route_stop_id" } };
|
||||
}
|
||||
|
||||
await client.query("BEGIN");
|
||||
|
||||
// Find and delete the route_stop
|
||||
const result = await client.query(
|
||||
`DELETE FROM route_stops
|
||||
WHERE id = $1 AND bus_line_id = $2
|
||||
RETURNING id, stop_order`,
|
||||
[routeStopId, busLineId],
|
||||
);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
await client.query("ROLLBACK");
|
||||
return { statusCode: 404, body: { error: "route_stop_not_found" } };
|
||||
}
|
||||
|
||||
const deletedOrder = result.rows[0].stop_order;
|
||||
|
||||
// Re-order remaining stops
|
||||
await client.query(
|
||||
`UPDATE route_stops
|
||||
SET stop_order = stop_order - 1, updated_at = NOW()
|
||||
WHERE bus_line_id = $1 AND stop_order > $2`,
|
||||
[busLineId, deletedOrder],
|
||||
);
|
||||
|
||||
await client.query("COMMIT");
|
||||
return { statusCode: 200, body: { success: true, routeStop: result.rows[0] } };
|
||||
} catch (err) {
|
||||
await client.query("ROLLBACK").catch(() => {});
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
listLineStops,
|
||||
listLines,
|
||||
createLine,
|
||||
updateLine,
|
||||
listLineStopsDetailed,
|
||||
addLineStop,
|
||||
reorderLineStops,
|
||||
deleteLine,
|
||||
deleteLineStop,
|
||||
};
|
||||
@@ -0,0 +1,308 @@
|
||||
const { store } = require("../mock/store");
|
||||
const { reportError } = require("../lib/report-error");
|
||||
|
||||
// Bus-line repository methods (DEV_MOCK mode). Each mirrors the original
|
||||
// handler's `if (DEV_MOCK) { ... }` branch verbatim and returns
|
||||
// { statusCode, body }. The original reorder/delete handlers acquired a
|
||||
// db.pool.connect() before the mock branch; the mock implementation below
|
||||
// intentionally skips that so mock-only deletion/reorder work without a
|
||||
// database (documented improvement).
|
||||
|
||||
async function listLineStops(req) {
|
||||
try {
|
||||
const { busLineId } = req.params;
|
||||
const stops = store.routeStops
|
||||
.filter((rs) => String(rs.busLineId) === String(busLineId))
|
||||
.sort((a, b) => a.stopOrder - b.stopOrder)
|
||||
.map((rs) => ({
|
||||
id: rs.id,
|
||||
order: rs.stopOrder,
|
||||
name: rs.name,
|
||||
latitude: rs.latitude,
|
||||
longitude: rs.longitude,
|
||||
estimatedArrivalMinutes: rs.estimatedArrivalMinutes,
|
||||
}));
|
||||
return { statusCode: 200, body: { stops } };
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function listLines(req) {
|
||||
try {
|
||||
return {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
busLines: store.busLines
|
||||
.slice()
|
||||
.sort((a, b) => a.lineNumber - b.lineNumber),
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function createLine(req) {
|
||||
try {
|
||||
const {
|
||||
lineNumber,
|
||||
startStop,
|
||||
endStop,
|
||||
estimatedDurationMinutes,
|
||||
description,
|
||||
} = req.body;
|
||||
|
||||
if (
|
||||
lineNumber === undefined ||
|
||||
!startStop ||
|
||||
!endStop ||
|
||||
estimatedDurationMinutes === undefined
|
||||
) {
|
||||
return { statusCode: 400, body: { error: "missing_required_fields" } };
|
||||
}
|
||||
|
||||
const busLine = {
|
||||
id: store.nextBusLineId++,
|
||||
lineNumber: Number(lineNumber),
|
||||
startStop,
|
||||
endStop,
|
||||
estimatedDurationMinutes: Number(estimatedDurationMinutes),
|
||||
description: description || "",
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
store.busLines.push(busLine);
|
||||
return { statusCode: 201, body: { busLine } };
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function updateLine(req) {
|
||||
try {
|
||||
const { busLineId } = req.params;
|
||||
const {
|
||||
lineNumber,
|
||||
startStop,
|
||||
endStop,
|
||||
estimatedDurationMinutes,
|
||||
description,
|
||||
} = req.body;
|
||||
|
||||
const existing = store.busLines.find(
|
||||
(line) => String(line.id) === String(busLineId),
|
||||
);
|
||||
if (!existing)
|
||||
return { statusCode: 404, body: { error: "bus_line_not_found" } };
|
||||
if (lineNumber !== undefined) existing.lineNumber = Number(lineNumber);
|
||||
if (startStop !== undefined) existing.startStop = startStop;
|
||||
if (endStop !== undefined) existing.endStop = endStop;
|
||||
if (estimatedDurationMinutes !== undefined)
|
||||
existing.estimatedDurationMinutes = Number(estimatedDurationMinutes);
|
||||
if (description !== undefined) existing.description = description;
|
||||
existing.updatedAt = new Date().toISOString();
|
||||
return { statusCode: 200, body: { busLine: existing } };
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function listLineStopsDetailed(req) {
|
||||
try {
|
||||
const { busLineId } = req.params;
|
||||
if (!busLineId || !Number.isFinite(Number(busLineId))) {
|
||||
return { statusCode: 400, body: { error: "invalid_bus_line_id" } };
|
||||
}
|
||||
|
||||
const stops = store.routeStops
|
||||
.filter((rs) => String(rs.busLineId) === String(busLineId))
|
||||
.sort((a, b) => a.stopOrder - b.stopOrder)
|
||||
.map((rs) => ({
|
||||
id: rs.id,
|
||||
busLineId: rs.busLineId,
|
||||
stopId: rs.stopId,
|
||||
stopOrder: rs.stopOrder,
|
||||
estimatedArrivalMinutes: rs.estimatedArrivalMinutes,
|
||||
name: rs.name,
|
||||
latitude: rs.latitude,
|
||||
longitude: rs.longitude,
|
||||
}));
|
||||
return { statusCode: 200, body: { routeStops: stops } };
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function addLineStop(req) {
|
||||
try {
|
||||
const { busLineId } = req.params;
|
||||
const { stopId, stopOrder, estimatedArrivalMinutes } = req.body;
|
||||
|
||||
if (!stopId || stopOrder === undefined) {
|
||||
return { statusCode: 400, body: { error: "missing_required_fields" } };
|
||||
}
|
||||
|
||||
const stop = store.stops.find((s) => String(s.id) === String(stopId));
|
||||
const routeStop = {
|
||||
id: store.nextRouteStopId++,
|
||||
busLineId: Number(busLineId),
|
||||
stopId: Number(stopId),
|
||||
stopOrder: Number(stopOrder),
|
||||
estimatedArrivalMinutes: estimatedArrivalMinutes ?? null,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
name: stop ? stop.name : `stop-${stopId}`,
|
||||
latitude: stop ? stop.latitude : 0,
|
||||
longitude: stop ? stop.longitude : 0,
|
||||
};
|
||||
// remove existing with same busLineId & stopOrder
|
||||
store.routeStops = store.routeStops.filter(
|
||||
(rs) =>
|
||||
!(
|
||||
rs.busLineId === routeStop.busLineId &&
|
||||
rs.stopOrder === routeStop.stopOrder
|
||||
),
|
||||
);
|
||||
store.routeStops.push(routeStop);
|
||||
return { statusCode: 201, body: { routeStop } };
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function reorderLineStops(req) {
|
||||
try {
|
||||
const { busLineId } = req.params;
|
||||
const { routeStopIds } = req.body || {};
|
||||
|
||||
if (!Array.isArray(routeStopIds) || routeStopIds.length === 0) {
|
||||
return { statusCode: 400, body: { error: "routeStopIds array required" } };
|
||||
}
|
||||
|
||||
const normalizedIds = routeStopIds
|
||||
.map((id) => Number(id))
|
||||
.filter((id) => Number.isFinite(id));
|
||||
if (normalizedIds.length !== routeStopIds.length) {
|
||||
return { statusCode: 400, body: { error: "routeStopIds must contain only numeric ids" } };
|
||||
}
|
||||
|
||||
const busLineStops = store.routeStops
|
||||
.filter((rs) => String(rs.busLineId) === String(busLineId))
|
||||
.sort((a, b) => a.stopOrder - b.stopOrder);
|
||||
|
||||
const idSet = new Set(busLineStops.map((rs) => Number(rs.id)));
|
||||
const sameCount = busLineStops.length === normalizedIds.length;
|
||||
const sameIds = sameCount && normalizedIds.every((id) => idSet.has(id));
|
||||
if (!sameIds) {
|
||||
return { statusCode: 400, body: { error: "routeStopIds must match current bus line stops" } };
|
||||
}
|
||||
|
||||
const updated = normalizedIds.map((routeStopId, index) => {
|
||||
const stop = store.routeStops.find(
|
||||
(rs) =>
|
||||
Number(rs.id) === routeStopId &&
|
||||
String(rs.busLineId) === String(busLineId),
|
||||
);
|
||||
if (!stop) return null;
|
||||
stop.stopOrder = index + 1;
|
||||
stop.updatedAt = new Date().toISOString();
|
||||
return stop;
|
||||
});
|
||||
|
||||
if (updated.some((item) => !item)) {
|
||||
return { statusCode: 400, body: { error: "routeStopIds must match current bus line stops" } };
|
||||
}
|
||||
|
||||
store.routeStops = store.routeStops.map((routeStop) => {
|
||||
const reordered = updated.find((item) => item.id === routeStop.id);
|
||||
return reordered || routeStop;
|
||||
});
|
||||
|
||||
return { statusCode: 200, body: { routeStops: updated } };
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteLine(req) {
|
||||
try {
|
||||
const { busLineId } = req.params;
|
||||
|
||||
if (!busLineId || !Number.isFinite(Number(busLineId))) {
|
||||
return { statusCode: 400, body: { error: "invalid_bus_line_id" } };
|
||||
}
|
||||
|
||||
const lineIndex = store.busLines.findIndex(
|
||||
(bl) => Number(bl.id) === Number(busLineId),
|
||||
);
|
||||
if (lineIndex === -1) {
|
||||
return { statusCode: 404, body: { error: "bus_line_not_found" } };
|
||||
}
|
||||
const deletedLine = store.busLines.splice(lineIndex, 1)[0];
|
||||
// Also delete route_stops for this line
|
||||
store.routeStops = store.routeStops.filter(
|
||||
(rs) => String(rs.busLineId) !== String(busLineId),
|
||||
);
|
||||
return { statusCode: 200, body: { success: true, busLine: deletedLine } };
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteLineStop(req) {
|
||||
try {
|
||||
const { busLineId, routeStopId } = req.params;
|
||||
|
||||
if (!busLineId || !Number.isFinite(Number(busLineId))) {
|
||||
return { statusCode: 400, body: { error: "invalid_bus_line_id" } };
|
||||
}
|
||||
|
||||
if (!routeStopId || !Number.isFinite(Number(routeStopId))) {
|
||||
return { statusCode: 400, body: { error: "invalid_route_stop_id" } };
|
||||
}
|
||||
|
||||
const index = store.routeStops.findIndex(
|
||||
(rs) =>
|
||||
Number(rs.id) === Number(routeStopId) &&
|
||||
String(rs.busLineId) === String(busLineId),
|
||||
);
|
||||
if (index === -1) {
|
||||
return { statusCode: 404, body: { error: "route_stop_not_found" } };
|
||||
}
|
||||
const deletedRouteStop = store.routeStops.splice(index, 1)[0];
|
||||
return { statusCode: 200, body: { success: true, routeStop: deletedRouteStop } };
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
listLineStops,
|
||||
listLines,
|
||||
createLine,
|
||||
updateLine,
|
||||
listLineStopsDetailed,
|
||||
addLineStop,
|
||||
reorderLineStops,
|
||||
deleteLine,
|
||||
deleteLineStop,
|
||||
};
|
||||
@@ -0,0 +1,67 @@
|
||||
const db = require("../db");
|
||||
const { reportError } = require("../lib/report-error");
|
||||
|
||||
// Navigation repository methods (PostgreSQL mode; no DEV_MOCK branch).
|
||||
|
||||
async function saveNavigationRoute(req) {
|
||||
try {
|
||||
const {
|
||||
routeId,
|
||||
startLat,
|
||||
startLon,
|
||||
endLat,
|
||||
endLon,
|
||||
totalDistance,
|
||||
totalDuration,
|
||||
geojson,
|
||||
} = req.body;
|
||||
|
||||
if (
|
||||
!routeId ||
|
||||
!startLat ||
|
||||
!startLon ||
|
||||
!endLat ||
|
||||
!endLon ||
|
||||
!totalDistance ||
|
||||
!totalDuration
|
||||
) {
|
||||
return { statusCode: 400, body: { error: "missing_required_fields" } };
|
||||
}
|
||||
|
||||
const result = await db.query(
|
||||
`
|
||||
INSERT INTO navigation_routes
|
||||
(route_id, start_lat, start_lon, end_lat, end_lon,
|
||||
total_distance_meters, total_duration_seconds, polyline_geojson)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
ON CONFLICT (route_id) DO UPDATE SET
|
||||
start_lat = $2,
|
||||
start_lon = $3,
|
||||
end_lat = $4,
|
||||
end_lon = $5,
|
||||
total_distance_meters = $6,
|
||||
total_duration_seconds = $7,
|
||||
polyline_geojson = $8
|
||||
RETURNING *
|
||||
`,
|
||||
[
|
||||
routeId,
|
||||
startLat,
|
||||
startLon,
|
||||
endLat,
|
||||
endLon,
|
||||
totalDistance,
|
||||
totalDuration,
|
||||
JSON.stringify(geojson),
|
||||
],
|
||||
);
|
||||
|
||||
return { statusCode: 200, body: { route: result.rows[0] } };
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { saveNavigationRoute };
|
||||
@@ -0,0 +1,109 @@
|
||||
const db = require("../db");
|
||||
const { reportError } = require("../lib/report-error");
|
||||
|
||||
// Per-user driving route repository methods (PostgreSQL mode; no DEV_MOCK
|
||||
// branch in the original handlers, so this is used in both modes).
|
||||
|
||||
async function getRoute(req) {
|
||||
try {
|
||||
const { routeId } = req.params;
|
||||
const userId = req.user.userId;
|
||||
|
||||
const result = await db.query(
|
||||
`
|
||||
SELECT
|
||||
r.id,
|
||||
r.start_time,
|
||||
r.end_time,
|
||||
r.status,
|
||||
bl.id as line_id,
|
||||
bl.line_number,
|
||||
bl.start_stop,
|
||||
bl.end_stop,
|
||||
bl.estimated_duration_minutes,
|
||||
bl.description,
|
||||
bt.id as bus_type_id,
|
||||
bt.name as bus_type,
|
||||
bt.seat_capacity,
|
||||
bt.license_plate
|
||||
FROM routes r
|
||||
JOIN bus_lines bl ON r.bus_line_id = bl.id
|
||||
JOIN bus_types bt ON r.bus_type_id = bt.id
|
||||
WHERE r.id = $1 AND r.user_id = $2
|
||||
`,
|
||||
[routeId, userId],
|
||||
);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
return { statusCode: 404, body: { error: "route_not_found" } };
|
||||
}
|
||||
|
||||
const row = result.rows[0];
|
||||
const route = {
|
||||
id: row.id,
|
||||
startTime: row.start_time,
|
||||
endTime: row.end_time,
|
||||
status: row.status,
|
||||
busLine: {
|
||||
id: row.line_id,
|
||||
lineNumber: row.line_number,
|
||||
startStop: row.start_stop,
|
||||
endStop: row.end_stop,
|
||||
estimatedDuration: row.estimated_duration_minutes,
|
||||
description: row.description,
|
||||
},
|
||||
busType: {
|
||||
id: row.bus_type_id,
|
||||
name: row.bus_type,
|
||||
seatCapacity: row.seat_capacity,
|
||||
licensePlate: row.license_plate,
|
||||
},
|
||||
};
|
||||
|
||||
return { statusCode: 200, body: { route } };
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function updateRouteStatus(req) {
|
||||
try {
|
||||
const { routeId } = req.params;
|
||||
const { status } = req.body;
|
||||
const userId = req.user.userId;
|
||||
|
||||
const validStatuses = [
|
||||
"scheduled",
|
||||
"in_progress",
|
||||
"completed",
|
||||
"cancelled",
|
||||
];
|
||||
if (!validStatuses.includes(status)) {
|
||||
return { statusCode: 400, body: { error: "invalid_status" } };
|
||||
}
|
||||
|
||||
const result = await db.query(
|
||||
`
|
||||
UPDATE routes
|
||||
SET status = $1, updated_at = NOW()
|
||||
WHERE id = $2 AND user_id = $3
|
||||
RETURNING *
|
||||
`,
|
||||
[status, routeId, userId],
|
||||
);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
return { statusCode: 404, body: { error: "route_not_found" } };
|
||||
}
|
||||
|
||||
return { statusCode: 200, body: { route: result.rows[0] } };
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { getRoute, updateRouteStatus };
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,545 @@
|
||||
const { store: _mock } = require("../mock/store");
|
||||
const { toDateKey, expandRecurringScheduleRows, scheduleMatchesFilters, parseScheduleFilters, mapRecurringOccurrenceRows, materializeScheduleOverviewRow } = require("../lib/schedule");
|
||||
const { reportError } = require("../lib/report-error");
|
||||
|
||||
// Schedules repository methods (DEV_MOCK mode). Exact copies of the original
|
||||
// handlers’ mock branches, returning { statusCode, body }. Note: the markStopPassed
|
||||
// mock branch reproduces the original ReferenceError (it reads an undeclared
|
||||
// `delayMinutes`), so it always returns 500 in mock mode, exactly as before.
|
||||
|
||||
async function listSchedules(req) {
|
||||
try {
|
||||
const filters = parseScheduleFilters(req.query, {
|
||||
statuses: ["planned", "active"],
|
||||
});
|
||||
|
||||
const routeStopsByLine = new Map();
|
||||
for (const routeStop of _mock.routeStops || []) {
|
||||
const busLineId = Number(routeStop.busLineId);
|
||||
if (!routeStopsByLine.has(busLineId)) {
|
||||
routeStopsByLine.set(busLineId, []);
|
||||
}
|
||||
routeStopsByLine.get(busLineId).push({
|
||||
stop_id: routeStop.stopId,
|
||||
stop_order: routeStop.stopOrder,
|
||||
});
|
||||
}
|
||||
|
||||
const schedules = expandRecurringScheduleRows(
|
||||
(_mock.schedules || []).map((s) => {
|
||||
const busLine = _mock.busLines.find((bl) => bl.id === s.busLineId);
|
||||
const bus = _mock.fleetBuses.find((b) => b.id === s.busId);
|
||||
return {
|
||||
id: s.id,
|
||||
busLineId: s.busLineId,
|
||||
busId: s.busId,
|
||||
startTime: s.startTime,
|
||||
endTime: s.endTime,
|
||||
weekdays: s.weekdays || [],
|
||||
status: s.status,
|
||||
lineNumber: busLine?.lineNumber || 0,
|
||||
busName: bus?.name || "Unknown Bus",
|
||||
driverId: null,
|
||||
estimatedDurationMinutes: busLine?.estimatedDurationMinutes || 60,
|
||||
};
|
||||
}),
|
||||
).filter((row) => scheduleMatchesFilters(row, filters, routeStopsByLine));
|
||||
|
||||
return { statusCode: 200, body: { schedules } };
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function getSchedulesOverview(req) {
|
||||
try {
|
||||
const filters = parseScheduleFilters(req.query, {
|
||||
statuses: ["planned", "active"],
|
||||
});
|
||||
const overviewDateKey = filters.date || null;
|
||||
|
||||
const routeStopsByLine = new Map();
|
||||
|
||||
for (const routeStop of _mock.routeStops || []) {
|
||||
const busLineId = Number(routeStop.busLineId);
|
||||
if (!routeStopsByLine.has(busLineId)) {
|
||||
routeStopsByLine.set(busLineId, []);
|
||||
}
|
||||
|
||||
routeStopsByLine.get(busLineId).push({
|
||||
bus_line_id: busLineId,
|
||||
stop_id: routeStop.stopId,
|
||||
stop_order: routeStop.stopOrder,
|
||||
estimated_arrival_minutes: routeStop.estimatedArrivalMinutes,
|
||||
stop_name: routeStop.name || "",
|
||||
});
|
||||
}
|
||||
|
||||
const baseRows = (_mock.schedules || []).map((schedule) => {
|
||||
const busLine = _mock.busLines.find(
|
||||
(line) => Number(line.id) === Number(schedule.busLineId),
|
||||
);
|
||||
const bus = _mock.fleetBuses.find(
|
||||
(vehicle) => Number(vehicle.id) === Number(schedule.busId),
|
||||
);
|
||||
const driver = _mock.drivers.find(
|
||||
(person) => Number(person.id) === Number(schedule.driverId),
|
||||
);
|
||||
|
||||
return {
|
||||
id: schedule.id,
|
||||
busLineId: schedule.busLineId,
|
||||
busId: schedule.busId,
|
||||
driverId: schedule.driverId ?? null,
|
||||
driverName: driver ? driver.name : null,
|
||||
startTime: schedule.startTime,
|
||||
endTime: schedule.endTime,
|
||||
weekdays: schedule.weekdays || [],
|
||||
status: schedule.status,
|
||||
lineNumber: busLine?.lineNumber || 0,
|
||||
busName: bus?.name || "Unknown Bus",
|
||||
licensePlate: bus?.licensePlate || "",
|
||||
createdAt: schedule.createdAt,
|
||||
};
|
||||
});
|
||||
|
||||
const schedules = mapRecurringOccurrenceRows(
|
||||
baseRows,
|
||||
overviewDateKey,
|
||||
routeStopsByLine,
|
||||
).filter((row) => scheduleMatchesFilters(row, filters, routeStopsByLine));
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
date: overviewDateKey,
|
||||
summary: {
|
||||
total: schedules.length,
|
||||
recurring: schedules.filter(
|
||||
(schedule) => schedule.scheduleType === "recurring",
|
||||
).length,
|
||||
oneTime: schedules.filter(
|
||||
(schedule) => schedule.scheduleType === "one_time",
|
||||
).length,
|
||||
},
|
||||
schedules,
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function listRecurringSchedules(req) {
|
||||
try {
|
||||
const filters = parseScheduleFilters(req.query);
|
||||
|
||||
const routeStopsByLine = new Map();
|
||||
|
||||
for (const routeStop of _mock.routeStops || []) {
|
||||
const busLineId = Number(routeStop.busLineId);
|
||||
if (!routeStopsByLine.has(busLineId)) {
|
||||
routeStopsByLine.set(busLineId, []);
|
||||
}
|
||||
|
||||
routeStopsByLine.get(busLineId).push({
|
||||
bus_line_id: busLineId,
|
||||
stop_id: routeStop.stopId,
|
||||
stop_order: routeStop.stopOrder,
|
||||
estimated_arrival_minutes: routeStop.estimatedArrivalMinutes,
|
||||
stop_name: routeStop.name || "",
|
||||
});
|
||||
}
|
||||
|
||||
const baseRows = (_mock.schedules || [])
|
||||
.filter(
|
||||
(schedule) =>
|
||||
Array.isArray(schedule.weekdays) && schedule.weekdays.length > 0,
|
||||
)
|
||||
.map((schedule) => {
|
||||
const busLine = _mock.busLines.find(
|
||||
(line) => Number(line.id) === Number(schedule.busLineId),
|
||||
);
|
||||
const bus = _mock.fleetBuses.find(
|
||||
(vehicle) => Number(vehicle.id) === Number(schedule.busId),
|
||||
);
|
||||
const driver = _mock.drivers.find(
|
||||
(person) => Number(person.id) === Number(schedule.driverId),
|
||||
);
|
||||
|
||||
return {
|
||||
id: schedule.id,
|
||||
busLineId: schedule.busLineId,
|
||||
busId: schedule.busId,
|
||||
driverId: schedule.driverId ?? null,
|
||||
driverName: driver ? driver.name : null,
|
||||
startTime: schedule.startTime,
|
||||
endTime: schedule.endTime,
|
||||
weekdays: schedule.weekdays || [],
|
||||
lineNumber: busLine?.lineNumber || 0,
|
||||
busName: bus?.name || "Unknown Bus",
|
||||
licensePlate: bus?.licensePlate || "",
|
||||
createdAt: schedule.createdAt,
|
||||
};
|
||||
});
|
||||
|
||||
const schedules = baseRows
|
||||
.filter((row) => scheduleMatchesFilters(row, filters, routeStopsByLine))
|
||||
.map((row) => {
|
||||
const materialized = materializeScheduleOverviewRow(
|
||||
row,
|
||||
null,
|
||||
routeStopsByLine,
|
||||
);
|
||||
return {
|
||||
...materialized,
|
||||
status: undefined,
|
||||
};
|
||||
});
|
||||
|
||||
return { statusCode: 200, body: { schedules } };
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function getScheduleById(req) {
|
||||
try {
|
||||
const { scheduleId } = req.params;
|
||||
|
||||
const schedule = (_mock.schedules || []).find(
|
||||
(s) => Number(s.id) === Number(scheduleId),
|
||||
);
|
||||
if (!schedule) {
|
||||
return { statusCode: 404, body: { error: "schedule_not_found" } };
|
||||
}
|
||||
|
||||
const busLine = _mock.busLines.find((bl) => bl.id === schedule.busLineId);
|
||||
const bus = _mock.fleetBuses.find((b) => b.id === schedule.busId);
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
schedule: {
|
||||
id: schedule.id,
|
||||
busLineId: schedule.busLineId,
|
||||
busId: schedule.busId,
|
||||
startTime: schedule.startTime,
|
||||
endTime: schedule.endTime,
|
||||
weekdays: schedule.weekdays || [],
|
||||
status: schedule.status,
|
||||
lineNumber: busLine?.lineNumber || 0,
|
||||
busName: bus?.name || "Unknown Bus",
|
||||
},
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function getScheduleStops(req) {
|
||||
try {
|
||||
const { scheduleId } = req.params;
|
||||
|
||||
const schedule = (_mock.schedules || []).find(
|
||||
(s) => Number(s.id) === Number(scheduleId),
|
||||
);
|
||||
if (!schedule) {
|
||||
return { statusCode: 404, body: { error: "schedule_not_found" } };
|
||||
}
|
||||
const routeStops = (_mock.routeStops || [])
|
||||
.filter((rs) => Number(rs.busLineId) === Number(schedule.busLineId))
|
||||
.sort((a, b) => a.stopOrder - b.stopOrder);
|
||||
|
||||
const formattedStops = routeStops.map((rs) => {
|
||||
const stop = (_mock.stops || []).find(
|
||||
(s) => Number(s.id) === Number(rs.stopId),
|
||||
);
|
||||
return {
|
||||
id: rs.id,
|
||||
order: rs.stopOrder,
|
||||
name: stop?.name || rs.name || "Unknown Stop",
|
||||
latitude: stop?.latitude ?? rs.latitude ?? 0,
|
||||
longitude: stop?.longitude ?? rs.longitude ?? 0,
|
||||
estimatedArrivalMinutes: rs.estimatedArrivalMinutes || 0,
|
||||
};
|
||||
});
|
||||
return { statusCode: 200, body: { stops: formattedStops } };
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function markStopPassed(req) {
|
||||
try {
|
||||
const scheduleId = Number(req.params.scheduleId);
|
||||
const stopOrder = Number(req.params.stopOrder);
|
||||
|
||||
if (
|
||||
!Number.isFinite(scheduleId) ||
|
||||
!Number.isFinite(stopOrder) ||
|
||||
stopOrder < 1
|
||||
) {
|
||||
return {
|
||||
statusCode: 400,
|
||||
body: { error: "invalid_schedule_or_stop_order" },
|
||||
};
|
||||
}
|
||||
|
||||
const actualPassedAt = req.body?.actualPassedAt
|
||||
? new Date(req.body.actualPassedAt)
|
||||
: new Date();
|
||||
if (Number.isNaN(actualPassedAt.getTime())) {
|
||||
return { statusCode: 400, body: { error: "invalid_actual_passed_at" } };
|
||||
}
|
||||
|
||||
const schedule = (_mock.schedules || []).find(
|
||||
(s) => Number(s.id) === scheduleId,
|
||||
);
|
||||
if (!schedule) {
|
||||
return { statusCode: 404, body: { error: "schedule_not_found" } };
|
||||
}
|
||||
|
||||
const routeStop = (_mock.routeStops || []).find(
|
||||
(rs) =>
|
||||
Number(rs.busLineId) === Number(schedule.busLineId) &&
|
||||
Number(rs.stopOrder) === stopOrder,
|
||||
);
|
||||
|
||||
if (!routeStop) {
|
||||
return { statusCode: 404, body: { error: "stop_not_found_for_schedule" } };
|
||||
}
|
||||
|
||||
const stop = (_mock.stops || []).find(
|
||||
(s) => Number(s.id) === Number(routeStop.stopId),
|
||||
);
|
||||
const occurrenceDateKey =
|
||||
req.query.date || req.body.date || toDateKey(schedule.startTime);
|
||||
const templateStart = new Date(schedule.startTime);
|
||||
const scheduledPassedAt = new Date(`${occurrenceDateKey}T00:00:00`);
|
||||
scheduledPassedAt.setHours(
|
||||
templateStart.getHours(),
|
||||
templateStart.getMinutes(),
|
||||
templateStart.getSeconds(),
|
||||
templateStart.getMilliseconds(),
|
||||
);
|
||||
scheduledPassedAt.setMinutes(
|
||||
scheduledPassedAt.getMinutes() +
|
||||
(Number(routeStop.estimatedArrivalMinutes) || 0),
|
||||
);
|
||||
|
||||
const existingIndex = (_mock.scheduleStopProgress || []).findIndex(
|
||||
(p) =>
|
||||
Number(p.scheduleId) === scheduleId &&
|
||||
Number(p.stopOrder) === stopOrder,
|
||||
);
|
||||
|
||||
const progressRow = {
|
||||
id:
|
||||
existingIndex >= 0
|
||||
? _mock.scheduleStopProgress[existingIndex].id
|
||||
: _mock.nextScheduleStopProgressId++,
|
||||
scheduleId,
|
||||
busLineId: Number(schedule.busLineId),
|
||||
stopId: Number(routeStop.stopId),
|
||||
stopOrder,
|
||||
stopName: stop?.name || routeStop.name || "Unknown Stop",
|
||||
estimatedArrivalMinutes:
|
||||
Number(routeStop.estimatedArrivalMinutes) || 0,
|
||||
scheduledPassedAt: scheduledPassedAt.toISOString(),
|
||||
scheduledPassedDate: occurrenceDateKey,
|
||||
actualPassedAt: actualPassedAt.toISOString(),
|
||||
delayMinutes,
|
||||
markedByUserId: Number(req.user?.userId) || null,
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
if (existingIndex >= 0) {
|
||||
_mock.scheduleStopProgress[existingIndex] = progressRow;
|
||||
} else {
|
||||
_mock.scheduleStopProgress.push(progressRow);
|
||||
}
|
||||
|
||||
const totalStops = (_mock.routeStops || []).filter(
|
||||
(rs) => Number(rs.busLineId) === Number(schedule.busLineId),
|
||||
).length;
|
||||
const passedCount = (_mock.scheduleStopProgress || []).filter(
|
||||
(p) =>
|
||||
Number(p.scheduleId) === scheduleId &&
|
||||
p.scheduledPassedDate === occurrenceDateKey,
|
||||
).length;
|
||||
|
||||
if (passedCount >= totalStops) {
|
||||
schedule.status = "completed";
|
||||
schedule.endTime = actualPassedAt.toISOString();
|
||||
} else if (schedule.status === "planned") {
|
||||
schedule.status = "in_progress";
|
||||
}
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
scheduleId,
|
||||
stopOrder,
|
||||
status: schedule.status,
|
||||
delayMinutes,
|
||||
passedStops: passedCount,
|
||||
totalStops,
|
||||
occurrenceDate: occurrenceDateKey,
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
console.error(
|
||||
"POST /driver/schedules/:scheduleId/stops/:stopOrder/passed error:",
|
||||
err,
|
||||
);
|
||||
reportError({ partofservice: "POST /driver/schedules/:scheduleId/stops/:stopOrder/passed", error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function getPublicScheduleProgress(req) {
|
||||
try {
|
||||
const scheduleId = Number(req.params.scheduleId);
|
||||
if (!Number.isFinite(scheduleId)) {
|
||||
return { statusCode: 400, body: { error: "invalid_schedule_id" } };
|
||||
}
|
||||
|
||||
const schedule = (_mock.schedules || []).find(
|
||||
(s) => Number(s.id) === scheduleId,
|
||||
);
|
||||
if (!schedule) {
|
||||
return { statusCode: 404, body: { error: "schedule_not_found" } };
|
||||
}
|
||||
|
||||
const busLine = (_mock.busLines || []).find(
|
||||
(bl) => Number(bl.id) === Number(schedule.busLineId),
|
||||
);
|
||||
const routeStops = (_mock.routeStops || [])
|
||||
.filter((rs) => Number(rs.busLineId) === Number(schedule.busLineId))
|
||||
.sort((a, b) => Number(a.stopOrder) - Number(b.stopOrder));
|
||||
|
||||
const mockProgressDate =
|
||||
req.query.date || req.query.occurrenceDate || null;
|
||||
let progressEvents = (_mock.scheduleStopProgress || []).filter(
|
||||
(p) => Number(p.scheduleId) === scheduleId,
|
||||
);
|
||||
if (mockProgressDate) {
|
||||
progressEvents = progressEvents.filter(
|
||||
(p) => p.scheduledPassedDate === mockProgressDate,
|
||||
);
|
||||
}
|
||||
progressEvents = progressEvents.sort(
|
||||
(a, b) => Number(a.stopOrder) - Number(b.stopOrder),
|
||||
);
|
||||
|
||||
const progressByOrder = new Map(
|
||||
progressEvents.map((p) => [Number(p.stopOrder), p]),
|
||||
);
|
||||
const latestProgress =
|
||||
progressEvents.length > 0
|
||||
? progressEvents[progressEvents.length - 1]
|
||||
: null;
|
||||
const currentDelayMinutes = latestProgress
|
||||
? Number(latestProgress.delayMinutes) || 0
|
||||
: 0;
|
||||
|
||||
const occurrenceDateKey =
|
||||
req.query.date ||
|
||||
req.query.occurrenceDate ||
|
||||
toDateKey(schedule.startTime);
|
||||
const stops = routeStops.map((rs) => {
|
||||
const stop = (_mock.stops || []).find(
|
||||
(s) => Number(s.id) === Number(rs.stopId),
|
||||
);
|
||||
const templateStart = new Date(schedule.startTime);
|
||||
const scheduledTime = new Date(`${occurrenceDateKey}T00:00:00`);
|
||||
scheduledTime.setHours(
|
||||
templateStart.getHours(),
|
||||
templateStart.getMinutes(),
|
||||
templateStart.getSeconds(),
|
||||
templateStart.getMilliseconds(),
|
||||
);
|
||||
scheduledTime.setMinutes(
|
||||
scheduledTime.getMinutes() +
|
||||
(Number(rs.estimatedArrivalMinutes) || 0),
|
||||
);
|
||||
const progress = progressByOrder.get(Number(rs.stopOrder));
|
||||
|
||||
return {
|
||||
stopId: Number(rs.stopId),
|
||||
stopOrder: Number(rs.stopOrder),
|
||||
stopName: stop?.name || rs.name || "Unknown Stop",
|
||||
estimatedArrivalMinutes: Number(rs.estimatedArrivalMinutes) || 0,
|
||||
scheduledPassedAt: scheduledTime.toISOString(),
|
||||
actualPassedAt: progress?.actualPassedAt || null,
|
||||
delayMinutes: progress ? Number(progress.delayMinutes) || 0 : null,
|
||||
status: progress ? "passed" : "pending",
|
||||
};
|
||||
});
|
||||
|
||||
const passedStops = stops.filter((s) => s.status === "passed");
|
||||
const nextStop = stops.find((s) => s.status === "pending") || null;
|
||||
const driverState =
|
||||
passedStops.length === 0
|
||||
? "not_started"
|
||||
: passedStops.length >= stops.length
|
||||
? "completed"
|
||||
: "en_route";
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
schedule: {
|
||||
id: scheduleId,
|
||||
lineNumber: Number(busLine?.lineNumber || 0),
|
||||
startStop: busLine?.startStop || null,
|
||||
endStop: busLine?.endStop || null,
|
||||
startTime: schedule.startTime,
|
||||
endTime: schedule.endTime,
|
||||
status: schedule.status,
|
||||
},
|
||||
driverState,
|
||||
currentDelayMinutes,
|
||||
passedStopCount: passedStops.length,
|
||||
totalStopCount: stops.length,
|
||||
nextStop: nextStop
|
||||
? {
|
||||
...nextStop,
|
||||
predictedPassedAt: new Date(
|
||||
new Date(nextStop.scheduledPassedAt).getTime() +
|
||||
currentDelayMinutes * 60000,
|
||||
).toISOString(),
|
||||
}
|
||||
: null,
|
||||
stops,
|
||||
updatedAt: latestProgress?.actualPassedAt || null,
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
console.error("GET /public/schedules/:scheduleId/progress error:", err);
|
||||
reportError({ partofservice: "GET /public/schedules/:scheduleId/progress", error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
listSchedules,
|
||||
getSchedulesOverview,
|
||||
listRecurringSchedules,
|
||||
getScheduleById,
|
||||
getScheduleStops,
|
||||
markStopPassed,
|
||||
getPublicScheduleProgress,
|
||||
};
|
||||
@@ -0,0 +1,149 @@
|
||||
const db = require("../db");
|
||||
const { reportError } = require("../lib/report-error");
|
||||
|
||||
// Stop repository methods (PostgreSQL mode). Each returns { statusCode, body }
|
||||
// mirroring the original handler's DB branch.
|
||||
|
||||
async function listStops(req) {
|
||||
try {
|
||||
const result = await db.query(`
|
||||
SELECT id, name, latitude, longitude, created_at, updated_at
|
||||
FROM stops
|
||||
ORDER BY id ASC
|
||||
`);
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
stops: result.rows.map((row) => ({
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
latitude: parseFloat(row.latitude),
|
||||
longitude: parseFloat(row.longitude),
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
})),
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function createStop(req) {
|
||||
try {
|
||||
const { name, latitude, longitude } = req.body;
|
||||
|
||||
if (!name || latitude === undefined || longitude === undefined) {
|
||||
return { statusCode: 400, body: { error: "missing_required_fields" } };
|
||||
}
|
||||
|
||||
const result = await db.query(
|
||||
`
|
||||
WITH next_id AS (
|
||||
SELECT COALESCE(MAX(id), 0) + 1 AS id FROM stops
|
||||
)
|
||||
INSERT INTO stops (id, name, latitude, longitude)
|
||||
SELECT next_id.id, $1, $2, $3
|
||||
FROM next_id
|
||||
RETURNING id, name, latitude, longitude, created_at, updated_at
|
||||
`,
|
||||
[name, latitude, longitude],
|
||||
);
|
||||
|
||||
const stop = result.rows[0];
|
||||
return {
|
||||
statusCode: 201,
|
||||
body: {
|
||||
stop: {
|
||||
id: stop.id,
|
||||
name: stop.name,
|
||||
latitude: parseFloat(stop.latitude),
|
||||
longitude: parseFloat(stop.longitude),
|
||||
createdAt: stop.created_at,
|
||||
updatedAt: stop.updated_at,
|
||||
},
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteStop(req) {
|
||||
try {
|
||||
const { stopId } = req.params;
|
||||
|
||||
if (!stopId || !Number.isFinite(Number(stopId))) {
|
||||
return { statusCode: 400, body: { error: "invalid_stop_id" } };
|
||||
}
|
||||
|
||||
const result = await db.query(
|
||||
`DELETE FROM stops WHERE id = $1 RETURNING id, name`,
|
||||
[stopId],
|
||||
);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
return { statusCode: 404, body: { error: "stop_not_found" } };
|
||||
}
|
||||
|
||||
return { statusCode: 200, body: { success: true, stop: result.rows[0] } };
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
if (err.code === "23503") {
|
||||
return { statusCode: 409, body: { error: "foreign_key_violation", message: "This stop is referenced by route_stops" } };
|
||||
}
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function updateStop(req) {
|
||||
try {
|
||||
const { stopId } = req.params;
|
||||
const { name, latitude, longitude } = req.body;
|
||||
|
||||
if (!stopId || !Number.isFinite(Number(stopId))) {
|
||||
return { statusCode: 400, body: { error: "invalid_stop_id" } };
|
||||
}
|
||||
|
||||
const result = await db.query(
|
||||
`UPDATE stops
|
||||
SET name = COALESCE($1, name),
|
||||
latitude = COALESCE($2, latitude),
|
||||
longitude = COALESCE($3, longitude),
|
||||
updated_at = NOW()
|
||||
WHERE id = $4
|
||||
RETURNING id, name, latitude, longitude, created_at, updated_at`,
|
||||
[name ?? null, latitude ?? null, longitude ?? null, stopId],
|
||||
);
|
||||
|
||||
if (!result.rows[0])
|
||||
return { statusCode: 404, body: { error: "stop_not_found" } };
|
||||
|
||||
const stop = result.rows[0];
|
||||
return {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
stop: {
|
||||
id: stop.id,
|
||||
name: stop.name,
|
||||
latitude: parseFloat(stop.latitude),
|
||||
longitude: parseFloat(stop.longitude),
|
||||
createdAt: stop.created_at,
|
||||
updatedAt: stop.updated_at,
|
||||
},
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { listStops, createStop, updateStop, deleteStop };
|
||||
@@ -0,0 +1,96 @@
|
||||
const { store } = require("../mock/store");
|
||||
const { reportError } = require("../lib/report-error");
|
||||
|
||||
// Stop repository methods (DEV_MOCK mode). Each mirrors the original handler's
|
||||
// `if (DEV_MOCK) { ... }` branch verbatim and returns { statusCode, body }.
|
||||
|
||||
async function listStops(req) {
|
||||
try {
|
||||
return {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
stops: store.stops.slice().sort((a, b) => a.id - b.id),
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function createStop(req) {
|
||||
try {
|
||||
const { name, latitude, longitude } = req.body;
|
||||
|
||||
if (!name || latitude === undefined || longitude === undefined) {
|
||||
return { statusCode: 400, body: { error: "missing_required_fields" } };
|
||||
}
|
||||
|
||||
const stop = {
|
||||
id: store.nextStopId++,
|
||||
name,
|
||||
latitude: parseFloat(latitude),
|
||||
longitude: parseFloat(longitude),
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
store.stops.push(stop);
|
||||
return { statusCode: 201, body: { stop } };
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteStop(req) {
|
||||
try {
|
||||
const { stopId } = req.params;
|
||||
|
||||
if (!stopId || !Number.isFinite(Number(stopId))) {
|
||||
return { statusCode: 400, body: { error: "invalid_stop_id" } };
|
||||
}
|
||||
|
||||
const index = store.stops.findIndex(
|
||||
(s) => Number(s.id) === Number(stopId),
|
||||
);
|
||||
if (index === -1) {
|
||||
return { statusCode: 404, body: { error: "stop_not_found" } };
|
||||
}
|
||||
const deletedStop = store.stops.splice(index, 1)[0];
|
||||
return { statusCode: 200, body: { success: true, stop: deletedStop } };
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
if (err.code === "23503") {
|
||||
return { statusCode: 409, body: { error: "foreign_key_violation", message: "This stop is referenced by route_stops" } };
|
||||
}
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
async function updateStop(req) {
|
||||
try {
|
||||
const { stopId } = req.params;
|
||||
const { name, latitude, longitude } = req.body;
|
||||
|
||||
if (!stopId || !Number.isFinite(Number(stopId))) {
|
||||
return { statusCode: 400, body: { error: "invalid_stop_id" } };
|
||||
}
|
||||
|
||||
const stop = store.stops.find((s) => Number(s.id) === Number(stopId));
|
||||
if (!stop) return { statusCode: 404, body: { error: "stop_not_found" } };
|
||||
if (name !== undefined) stop.name = name;
|
||||
if (latitude !== undefined) stop.latitude = parseFloat(latitude);
|
||||
if (longitude !== undefined) stop.longitude = parseFloat(longitude);
|
||||
stop.updatedAt = new Date().toISOString();
|
||||
return { statusCode: 200, body: { stop } };
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error", details: err.message } };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { listStops, createStop, updateStop, deleteStop };
|
||||
@@ -0,0 +1,330 @@
|
||||
const db = require("../db");
|
||||
const { reportError } = require("../lib/report-error");
|
||||
|
||||
// Weekly schedule repository methods (PostgreSQL mode; no DEV_MOCK branch in
|
||||
// the original handlers, so this module is used in both modes).
|
||||
|
||||
async function updateWeeklyScheduleStatus(req) {
|
||||
try {
|
||||
const scheduleId = Number(req.params.scheduleId);
|
||||
const { status } = req.body;
|
||||
const validStatuses = [
|
||||
"planned",
|
||||
"in_progress",
|
||||
"completed",
|
||||
"cancelled",
|
||||
"active",
|
||||
];
|
||||
if (!Number.isInteger(scheduleId) || !validStatuses.includes(status)) {
|
||||
return { statusCode: 400, body: { error: "invalid_status" } };
|
||||
}
|
||||
|
||||
const normalizedStatus = status === "active" ? "in_progress" : status;
|
||||
const result = await db.query(
|
||||
`
|
||||
UPDATE schedules s
|
||||
SET status = $1, updated_at = NOW()
|
||||
WHERE s.id = $2
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM shifts sh
|
||||
WHERE sh.schedule_id = s.id AND sh.driver_id = $3
|
||||
)
|
||||
RETURNING s.id, s.status
|
||||
`,
|
||||
[normalizedStatus, scheduleId, req.user.userId],
|
||||
);
|
||||
|
||||
if (result.rows.length === 0)
|
||||
return { statusCode: 404, body: { error: "schedule_not_found" } };
|
||||
return {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
schedule: {
|
||||
id: Number(result.rows[0].id),
|
||||
status: result.rows[0].status,
|
||||
},
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
console.error("PATCH /driver/weekly-schedules/:id/status error:", err);
|
||||
reportError({ partofservice: "PATCH /driver/weekly-schedules/:id/status", error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error" } };
|
||||
}
|
||||
}
|
||||
|
||||
async function listWeeklySchedules(req) {
|
||||
try {
|
||||
const result = await db.query(`
|
||||
SELECT s.id, s.bus_line_id, s.start_time, s.end_time, s.status, s.day_of_week,
|
||||
bl.line_number, bl.start_stop, bl.end_stop,
|
||||
sh.id AS shift_id, sh.driver_id, u.usercode AS driver_name
|
||||
FROM schedules s
|
||||
JOIN bus_lines bl ON bl.id = s.bus_line_id
|
||||
LEFT JOIN shifts sh ON sh.schedule_id = s.id
|
||||
LEFT JOIN workers.users u ON u.id = sh.driver_id
|
||||
ORDER BY s.day_of_week ASC, s.start_time ASC, s.id ASC
|
||||
`);
|
||||
return {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
schedules: result.rows.map((row) => ({
|
||||
id: Number(row.id),
|
||||
busLineId: Number(row.bus_line_id),
|
||||
lineNumber: row.line_number,
|
||||
startStop: row.start_stop,
|
||||
endStop: row.end_stop,
|
||||
startTime: row.start_time,
|
||||
endTime: row.end_time,
|
||||
status: row.status,
|
||||
dayOfWeek: Number(row.day_of_week),
|
||||
shiftId: row.shift_id ? Number(row.shift_id) : null,
|
||||
driverId: row.driver_id ? Number(row.driver_id) : null,
|
||||
driverName: row.driver_name || null,
|
||||
})),
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
console.error("GET /admin/weekly-schedules error:", err);
|
||||
reportError({ partofservice: "GET /admin/weekly-schedules", error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error" } };
|
||||
}
|
||||
}
|
||||
|
||||
async function createWeeklySchedule(req) {
|
||||
try {
|
||||
const busLineId = Number(req.body?.busLineId);
|
||||
const dayOfWeek = Number(req.body?.dayOfWeek);
|
||||
const startTime = String(req.body?.startTime || "");
|
||||
const endTime = String(req.body?.endTime || "");
|
||||
const driverId = req.body?.driverId ? Number(req.body.driverId) : null;
|
||||
|
||||
if (
|
||||
!Number.isInteger(busLineId) ||
|
||||
!Number.isInteger(dayOfWeek) ||
|
||||
dayOfWeek < 0 ||
|
||||
dayOfWeek > 6 ||
|
||||
!startTime ||
|
||||
!endTime
|
||||
) {
|
||||
return {
|
||||
statusCode: 400,
|
||||
body: {
|
||||
error: "busLineId, dayOfWeek, startTime and endTime are required",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const created = await db.query(
|
||||
`
|
||||
INSERT INTO schedules (bus_line_id, start_time, end_time, status, day_of_week)
|
||||
VALUES ($1, $2::time, $3::time, 'planned', $4)
|
||||
RETURNING id, bus_line_id, start_time, end_time, status, day_of_week
|
||||
`,
|
||||
[busLineId, startTime, endTime, dayOfWeek],
|
||||
);
|
||||
|
||||
const schedule = created.rows[0];
|
||||
if (driverId) {
|
||||
await db.query(
|
||||
`
|
||||
INSERT INTO shifts (schedule_id, driver_id)
|
||||
VALUES ($1, $2)
|
||||
`,
|
||||
[schedule.id, driverId],
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
statusCode: 201,
|
||||
body: {
|
||||
schedule: {
|
||||
id: Number(schedule.id),
|
||||
busLineId: Number(schedule.bus_line_id),
|
||||
startTime: schedule.start_time,
|
||||
endTime: schedule.end_time,
|
||||
status: schedule.status,
|
||||
dayOfWeek: Number(schedule.day_of_week),
|
||||
driverId,
|
||||
},
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
console.error("POST /admin/weekly-schedules error:", err);
|
||||
reportError({ partofservice: "POST /admin/weekly-schedules", error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error" } };
|
||||
}
|
||||
}
|
||||
|
||||
async function bulkCreateWeeklySchedules(req) {
|
||||
const busLineId = Number(req.body?.busLineId);
|
||||
const dayOfWeeks = Array.isArray(req.body?.dayOfWeeks)
|
||||
? req.body.dayOfWeeks
|
||||
.map(Number)
|
||||
.filter((day) => Number.isInteger(day) && day >= 0 && day <= 6)
|
||||
: [];
|
||||
const startTimes = Array.isArray(req.body?.startTimes)
|
||||
? [...new Set(req.body.startTimes.map(String).filter(Boolean))]
|
||||
: [];
|
||||
const driverId = req.body?.driverId ? Number(req.body.driverId) : null;
|
||||
|
||||
if (
|
||||
!Number.isInteger(busLineId) ||
|
||||
dayOfWeeks.length === 0 ||
|
||||
startTimes.length === 0
|
||||
) {
|
||||
return {
|
||||
statusCode: 400,
|
||||
body: { error: "busLineId, dayOfWeeks and startTimes are required" },
|
||||
};
|
||||
}
|
||||
|
||||
const client = await db.pool.connect();
|
||||
try {
|
||||
await client.query("BEGIN");
|
||||
const line = await client.query(
|
||||
"SELECT estimated_duration_minutes FROM bus_lines WHERE id = $1",
|
||||
[busLineId],
|
||||
);
|
||||
if (line.rows.length === 0) {
|
||||
await client.query("ROLLBACK");
|
||||
return { statusCode: 404, body: { error: "bus_line_not_found" } };
|
||||
}
|
||||
|
||||
const duration = Number(line.rows[0].estimated_duration_minutes) || 60;
|
||||
const created = [];
|
||||
for (const dayOfWeek of dayOfWeeks) {
|
||||
for (const startTime of startTimes) {
|
||||
const result = await client.query(
|
||||
`INSERT INTO schedules
|
||||
(bus_line_id, start_time, end_time, status, day_of_week)
|
||||
VALUES ($1, $2::time, ($2::time + ($3::text || ' minutes')::interval)::time, 'planned', $4)
|
||||
RETURNING id, bus_line_id, start_time, end_time, status, day_of_week`,
|
||||
[busLineId, startTime, duration, dayOfWeek],
|
||||
);
|
||||
const schedule = result.rows[0];
|
||||
if (driverId) {
|
||||
await client.query(
|
||||
"INSERT INTO shifts (schedule_id, driver_id) VALUES ($1, $2)",
|
||||
[schedule.id, driverId],
|
||||
);
|
||||
}
|
||||
created.push(schedule);
|
||||
}
|
||||
}
|
||||
|
||||
await client.query("COMMIT");
|
||||
return {
|
||||
statusCode: 201,
|
||||
body: {
|
||||
createdCount: created.length,
|
||||
schedules: created.map((schedule) => ({
|
||||
id: Number(schedule.id),
|
||||
busLineId: Number(schedule.bus_line_id),
|
||||
startTime: schedule.start_time,
|
||||
endTime: schedule.end_time,
|
||||
status: schedule.status,
|
||||
dayOfWeek: Number(schedule.day_of_week),
|
||||
driverId,
|
||||
})),
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
await client.query("ROLLBACK");
|
||||
console.error("POST /admin/weekly-schedules/bulk error:", err);
|
||||
reportError({ partofservice: "POST /admin/weekly-schedules/bulk", error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error" } };
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
async function updateWeeklySchedule(req) {
|
||||
try {
|
||||
const scheduleId = Number(req.params.scheduleId);
|
||||
const busLineId = Number(req.body?.busLineId);
|
||||
const dayOfWeek = Number(req.body?.dayOfWeek);
|
||||
const startTime = String(req.body?.startTime || "");
|
||||
const endTime = String(req.body?.endTime || "");
|
||||
if (
|
||||
!Number.isInteger(scheduleId) ||
|
||||
!Number.isInteger(busLineId) ||
|
||||
!Number.isInteger(dayOfWeek) ||
|
||||
dayOfWeek < 0 ||
|
||||
dayOfWeek > 6 ||
|
||||
!startTime ||
|
||||
!endTime
|
||||
) {
|
||||
return { statusCode: 400, body: { error: "invalid_schedule" } };
|
||||
}
|
||||
|
||||
const result = await db.query(
|
||||
`
|
||||
UPDATE schedules
|
||||
SET bus_line_id = $2, start_time = $3::time, end_time = $4::time,
|
||||
day_of_week = $5, updated_at = NOW()
|
||||
WHERE id = $1
|
||||
RETURNING id, bus_line_id, start_time, end_time, status, day_of_week
|
||||
`,
|
||||
[scheduleId, busLineId, startTime, endTime, dayOfWeek],
|
||||
);
|
||||
if (result.rows.length === 0)
|
||||
return { statusCode: 404, body: { error: "schedule_not_found" } };
|
||||
return { statusCode: 200, body: { schedule: result.rows[0] } };
|
||||
} catch (err) {
|
||||
console.error("PUT /admin/weekly-schedules error:", err);
|
||||
reportError({ partofservice: "PUT /admin/weekly-schedules", error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error" } };
|
||||
}
|
||||
}
|
||||
|
||||
async function updateWeeklyScheduleShift(req) {
|
||||
try {
|
||||
const scheduleId = Number(req.params.scheduleId);
|
||||
const driverId = req.body?.driverId ? Number(req.body.driverId) : null;
|
||||
if (!Number.isInteger(scheduleId))
|
||||
return { statusCode: 400, body: { error: "invalid_schedule_id" } };
|
||||
await db.query("DELETE FROM shifts WHERE schedule_id = $1", [
|
||||
scheduleId,
|
||||
]);
|
||||
if (driverId) {
|
||||
await db.query(
|
||||
"INSERT INTO shifts (schedule_id, driver_id) VALUES ($1, $2)",
|
||||
[scheduleId, driverId],
|
||||
);
|
||||
}
|
||||
return { statusCode: 200, body: { scheduleId, driverId } };
|
||||
} catch (err) {
|
||||
console.error("PUT /admin/weekly-schedules/:id/shift error:", err);
|
||||
reportError({ partofservice: "PUT /admin/weekly-schedules/:id/shift", error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error" } };
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteWeeklySchedule(req) {
|
||||
try {
|
||||
const scheduleId = Number(req.params.scheduleId);
|
||||
if (!Number.isInteger(scheduleId))
|
||||
return { statusCode: 400, body: { error: "invalid_schedule_id" } };
|
||||
const result = await db.query(
|
||||
"DELETE FROM schedules WHERE id = $1 RETURNING id",
|
||||
[scheduleId],
|
||||
);
|
||||
if (result.rows.length === 0)
|
||||
return { statusCode: 404, body: { error: "schedule_not_found" } };
|
||||
return { statusCode: 200, body: { success: true, scheduleId } };
|
||||
} catch (err) {
|
||||
console.error("DELETE /admin/weekly-schedules error:", err);
|
||||
reportError({ partofservice: "DELETE /admin/weekly-schedules", error: err.stack || err.message });
|
||||
return { statusCode: 500, body: { error: "internal_error" } };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
updateWeeklyScheduleStatus,
|
||||
listWeeklySchedules,
|
||||
createWeeklySchedule,
|
||||
bulkCreateWeeklySchedules,
|
||||
updateWeeklySchedule,
|
||||
updateWeeklyScheduleShift,
|
||||
deleteWeeklySchedule,
|
||||
};
|
||||
Reference in New Issue
Block a user