mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-06-19 13:21:46 +00:00
d152f9d02b
* fix(shared-view): render each leg of multi-leg flights correctly The read-only shared view showed the overall trip start/end airports and the first leg's flight number on every leg of a multi-leg flight. The Day Plan already expands legs (each carries __leg), but the renderer ignored it and read flat top-level metadata; the Bookings tab had the same bug. - Day Plan: use __leg for per-leg airline/flight number/route, plus dep-arr time - Bookings tab: list each leg via getFlightLegs() - unique React keys for multi-leg rows Closes #1219 * feat(pdf): add legs to pdf export * fix(demo): skip first-run admin seed in demo mode When DEMO_MODE is on, the demo seeder creates its own admin (admin@trek.app, username "admin") right after the generic seeds run. The first-run admin bootstrap was grabbing username "admin" first, so the demo seeder hit the UNIQUE(username) constraint and aborted before the demo user was ever created - which surfaced as a 500 "Demo user not found" on demo-login. Skip the generic admin bootstrap when demo mode owns the admin account. * fix(docker): ship the encryption-key migration script in the image The production image only copied server/dist, so the documented rotation command `node --import tsx scripts/migrate-encryption.ts` failed inside the container with a module-not-found error - the raw .ts was never present. The script runs via tsx straight from source and only pulls node builtins plus better-sqlite3 (both prod deps), so copying the single file into /app/server/scripts is enough to make the rotation work again. * fix(vacay): keep the mode toolbar above the mobile bottom nav The floating Vacation/Company toolbar was pinned at bottom-3 with z-30, so on mobile it landed in the same band as the fixed bottom nav (z-60) and got hidden behind it - and could scroll out of reach entirely. Pin it above the nav with the shared --bottom-nav-h variable (0px on desktop, so nothing changes there) and reserve matching space below the calendar grid so it never gets swallowed. * fix(dashboard): show the correct reservation date regardless of timezone The upcoming-reservations widget built the date with new Date(reservation_time) .toISOString(), which reinterprets the stored naive local time as UTC and can roll the displayed day forward in non-UTC timezones (e.g. a 23:30 reservation showing the next day). Read the date and time straight from the stored string parts via splitReservationDateTime, and format the time with the shared formatTime helper so it also honours the user's 12h/24h preference. * fix(atlas): cursor-following tooltips and removing countries from search Two related Atlas fixes: - Country tooltips were bound with sticky:false, which anchors them at the feature's bounds centre. For countries with overseas territories (e.g. France) that centre sits far out in the ocean, so the tooltip popped up nowhere near the area being hovered. Make them sticky so they track the cursor. - Selecting an already-visited country from the search bar always opened the "Mark / Bucket" dialog, with no way to remove it. Tiny countries like Vatican City or Singapore are hard to hit on the map, so search was the only way in. Mirror the map-click behaviour: a manually-marked country opens the Remove confirmation, a trip/place-backed one opens its detail. * fix(oidc): keep dots in generated usernames The OIDC username sanitizer stripped dots because they were missing from the allowed character class, so a name claim like "first.last" became "firstlast". Dots are valid usernames (the profile validator already allows ^[a-zA-Z0-9_.-]+$), so add the dot to the sanitizer. * fix(collab): show poll option labels in the UI The poll API formatted each option as { label, voters }, but the React poll component renders opt.text - so every option button came out blank. Emit text alongside label (kept for any other consumer) so options render again. * feat(backup): make the upload size limit configurable The restore upload was capped at a hard-coded 500 MB, so instances whose backup archive (uploads/ included) grew past that got a 413 "File too large" with no way to raise it. Add a BACKUP_UPLOAD_LIMIT_MB env var (default 500, invalid values warn and fall back), documented in .env.example. * feat(costs): create an expense from a booking, fix editing total-only items Replace the inline price + budget-category fields in the Transport and Reservation booking modals with a "Create expense" flow: the modal saves the booking, then opens the full Costs editor prefilled (name + category mapped from the booking type) and linked to the reservation. A booking with a linked expense shows it inline with edit / remove. Also fix the Costs editor so an expense with a recorded total but no payers (transport-derived or pre-rework items) opens with its amount, lets you set the currency, and saves - it previously showed 0 everywhere and could not be saved. Legacy / localized categories now map to the fixed keys, and changing a booking's type keeps its linked expense category in sync (unless it was manually set). - shared: reservation_id on budget create, typeToCostCategory helper, i18n keys - server: createBudgetItem stores reservation_id; keep total_price for payerless items; a booking update no longer wipes its linked expense and syncs the category on type change - client: shared BookingCostsSection, exported ExpenseModal with prefill and an editable total, page-level save-then-open wiring * test(reservations): align syncBudgetOnUpdate unit tests with no-wipe + type-sync The service now leaves a linked expense alone when no budget entry is on the payload (only an explicit total_price 0 deletes it) and syncs the category on a booking type change. Update the unit tests accordingly - the old "price cleared" case passed entry: undefined, which is now a no-op and left a mocked return queued that leaked into the next test. * fix(planner): keep a reservation on its day when edited (#1237) Editing a booking forced its day_id to the globally selected day, which is null when editing from the Book tab - so the booking lost its day and vanished from the Plan. Preserve the reservation own day_id on edit instead. * fix(planner): derive a booking day from its date when none is set (#1237) The client always sends day_id on a reservation update, so the server only derived it from reservation_time when the field was absent. A non-transport booking saved without a selected day (Book tab) therefore got day_id null and vanished from the Plan, even though its date matched a day. Derive the day from reservation_time whenever day_id is null, mirroring create. * fix(planner): let a booking's day follow its date when edited (#1237) Preserving the old day_id on edit left a re-dated booking on its previous start day while end_day_id followed the new date, so it spanned both. Stop sending day_id from the edit modal entirely - the server derives both ends from the booking's date (and keeps the current day when there is no date), so a re-dated booking moves cleanly to the matching day. * fix(atlas): keep the continent breakdown in sync on mark/unmark (#1225) The optimistic mark/unmark updates bumped the country total but never the per-continent counts, so the continent column froze until a full reload. Move the country to continent map into @trek/shared (single source for server and client) and adjust the matching continent count at every optimistic site: the country confirm flow plus the choose / region mark and region unmark handlers. * feat(admin): let admins set a default currency for new users Adds a currency picker to Admin > User Defaults. Stored as the default_currency user-default, so users who have not picked their own currency inherit it in Costs. * fix(atlas): give every sub-national region a distinct code (#1217) geoBoundaries fills shapeISO with the bare country code for some countries (every Spanish region got "ESP", every Chinese "CHN", also Chile/Oman), so marking one region lit up the whole country. build-atlas-geo.mjs now keeps shapeISO only when it is a real "XX-..." subdivision code and otherwise synthesizes a unique per-country id from the region name. Regenerated admin1.geojson.gz: Spain/China/ Chile/Oman now carry distinct region codes (countries with real codes, e.g. Germany, are unchanged). * fix(dashboard): never crash on a malformed reservation date A reservation with an invalid date blanked the whole My Trips page: the old Upcoming widget did new Date(value).toISOString(), which throws "Invalid time value" (fixed in #1222 by reading the string parts). Also guard splitDate so a bad date renders a dash instead of "Invalid Date" or throwing. * fix(airtrail): gate airtrail update behind a user setting, on airtrail update: rebuild payload from fresh data to prevent any data loss * fix(airtrail): add back missing tests * fix(costs): rework the cost panel UX wise and apply prettier on the shared package * chore(prettier) prettier this file * fix(airtrail): don't use cabin class as seat on import When an AirTrail flight has a cabin class but no seat number, the mapper fell back to the class for metadata.seat, so reservations showed e.g. "economy" as the seat. Use only the seat number; leave the seat blank otherwise. The class is still surfaced separately in the import picker. Closes #1246 * fix(airtrail): import scheduled flight times instead of actual AirTrail exposes both scheduled (departureScheduled/arrivalScheduled) and actual (departure/arrival) times. TREK read the actual times, so a delayed or early flight imported the wrong time for planning. Read the scheduled times on import and on poll-sync (both go through mapFlightToReservation); when a flight has no scheduled time, leave the clock blank (date preserved) rather than fabricating 00:00 or falling back to actual. The change-detection hash now tracks the scheduled values, so existing linked reservations re-sync once on the next poll. The opt-in writeback mirrors the read, pushing TREK edits to the scheduled fields so they round-trip. * fix(planner): hydrate per-assignment times when editing a place from the pool Times live per day-assignment, not on the pool place, so reopening a place from the Places panel / inspector showed empty Start/End fields (#1247). The editor now resolves a place's lone assignment when no day is in context and hydrates the fields from it; ambiguous (0 or 2+ days) edits hide the fields instead of showing non-persisting inputs. * fix(mcp): make write tools return client-valid, hydrated entities Audit of all write tools under server/src/mcp/tools (issue #1244 anchor). S1 (broken): - create_budget_item / create_budget_item_with_members now default the split to all trip members when member_ids omitted, so the entry passes the client save-gate instead of being member-less (#1244). - create_transport / update_transport backfill lat/lng/timezone for code-only flight endpoints (NOT NULL columns) and return a clean error for unresolvable endpoints instead of crashing. S2 (under-hydration): set_budget_item_members, create_journey, create_journey_entry, create_packing_bag, bulk_import_packing and update_vacay_plan now return the hydrated shape the matching read/REST route returns; bulk_import widened to accept bag/weight_grams/checked. S3 (parity): check_in_end added to accommodation tools; atlas mark_region_visited echoes the client shape; update_journey_entry/ update_journey_preferences, set_bag_members, set_packing_category_assignees, apply_packing_template return hydrated payloads; set_vacay_color echoes the color. Auth: save_packing_template now requires admin, matching the REST gate. Also refactors server/src/config.ts (JWT-secret handling). Adds getBudgetItem hydrated getter, exports EndpointInput, and MCP regression tests (incl. new tools-transports and tools-journey suites). * fix(mcp): fix ICS/maps/accommodation bugs, add settlement & template tools Bugs: - export_trip_ics: include flights that store times per-endpoint (local_date/local_time) instead of a top-level reservation_time - resolve_maps_url: follow redirects for cid=/share links and fall back to parsing the page body, all SSRF-guarded - link_hotel_accommodation: normalize accommodation_id (TEXT column) to an integer in the reservation read paths so it no longer returns "14.0" Gaps: - packing: save_packing_template returns the new template id; add list_packing_templates (read) and delete_packing_template (admin) - budget: update_budget_item accepts payers/member_ids; clarify create/ update/members descriptions to ask which members share the expense and who paid - budget: add settlement tools — get_settlement_summary, list_settlements, create/update/delete_settlement (budget_edit, mirrors REST + WS events) * chore: bump nodemailer * chore: bump multer --------- Co-authored-by: Maurice <mauriceboe@icloud.com>
475 lines
20 KiB
TypeScript
475 lines
20 KiB
TypeScript
import { db } from '../db/database';
|
|
import { Reservation } from '../types';
|
|
|
|
export { verifyTripAccess } from './tripAccess';
|
|
|
|
export interface ReservationEndpoint {
|
|
id?: number;
|
|
reservation_id?: number;
|
|
role: 'from' | 'to' | 'stop';
|
|
sequence: number;
|
|
name: string;
|
|
code: string | null;
|
|
lat: number;
|
|
lng: number;
|
|
timezone: string | null;
|
|
local_time: string | null;
|
|
local_date: string | null;
|
|
}
|
|
|
|
export type EndpointInput = Omit<ReservationEndpoint, 'id' | 'reservation_id' | 'sequence'> & { sequence?: number };
|
|
|
|
export function loadEndpointsByTrip(tripId: string | number): Map<number, ReservationEndpoint[]> {
|
|
const rows = db.prepare(`
|
|
SELECT e.* FROM reservation_endpoints e
|
|
JOIN reservations r ON e.reservation_id = r.id
|
|
WHERE r.trip_id = ?
|
|
ORDER BY e.reservation_id, e.sequence
|
|
`).all(tripId) as ReservationEndpoint[];
|
|
const map = new Map<number, ReservationEndpoint[]>();
|
|
for (const r of rows) {
|
|
const list = map.get(r.reservation_id!) ?? [];
|
|
list.push(r);
|
|
map.set(r.reservation_id!, list);
|
|
}
|
|
return map;
|
|
}
|
|
|
|
function loadEndpoints(reservationId: number): ReservationEndpoint[] {
|
|
return db.prepare(
|
|
'SELECT * FROM reservation_endpoints WHERE reservation_id = ? ORDER BY sequence'
|
|
).all(reservationId) as ReservationEndpoint[];
|
|
}
|
|
|
|
// Resolve the day row whose date matches the date portion of an ISO-ish
|
|
// timestamp. Used to keep `day_id` / `end_day_id` in sync with
|
|
// `reservation_time` / `reservation_end_time` so non-transport bookings
|
|
// (tours, restaurants, events, ...) end up on the right day in the UI,
|
|
// which now filters by day_id instead of reservation_time.
|
|
function resolveDayIdFromTime(
|
|
tripId: string | number,
|
|
time: string | null | undefined,
|
|
): number | null {
|
|
if (!time) return null;
|
|
const datePart = time.slice(0, 10);
|
|
if (!/^\d{4}-\d{2}-\d{2}$/.test(datePart)) return null;
|
|
const row = db
|
|
.prepare('SELECT id FROM days WHERE trip_id = ? AND date = ? LIMIT 1')
|
|
.get(tripId, datePart) as { id: number } | undefined;
|
|
return row?.id ?? null;
|
|
}
|
|
|
|
function saveEndpoints(reservationId: number, endpoints: EndpointInput[]): void {
|
|
// Bind the transaction lazily on each call. Binding at module load time
|
|
// captures the DB connection that was open then, which becomes invalid
|
|
// after demo-reset / restore-from-backup closes and reinitialises the
|
|
// connection — every later endpoint save would throw
|
|
// "The database connection is not open".
|
|
const tx = db.transaction((rid: number, eps: EndpointInput[]) => {
|
|
db.prepare('DELETE FROM reservation_endpoints WHERE reservation_id = ?').run(rid);
|
|
const insert = db.prepare(`
|
|
INSERT INTO reservation_endpoints (reservation_id, role, sequence, name, code, lat, lng, timezone, local_time, local_date)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
`);
|
|
eps.forEach((e, i) => {
|
|
insert.run(rid, e.role, e.sequence ?? i, e.name, e.code ?? null, e.lat, e.lng, e.timezone ?? null, e.local_time ?? null, e.local_date ?? null);
|
|
});
|
|
});
|
|
tx(reservationId, endpoints);
|
|
}
|
|
|
|
export function listReservations(tripId: string | number) {
|
|
const reservations = db.prepare(`
|
|
SELECT r.*, d.day_number, p.name as place_name, r.assignment_id,
|
|
ap.place_id as accommodation_place_id, acc_p.name as accommodation_name,
|
|
ap.start_day_id as accommodation_start_day_id, ap.end_day_id as accommodation_end_day_id
|
|
FROM reservations r
|
|
LEFT JOIN days d ON r.day_id = d.id
|
|
LEFT JOIN places p ON r.place_id = p.id
|
|
LEFT JOIN day_accommodations ap ON r.accommodation_id = ap.id
|
|
LEFT JOIN places acc_p ON ap.place_id = acc_p.id
|
|
WHERE r.trip_id = ?
|
|
ORDER BY r.reservation_time ASC, r.created_at ASC
|
|
`).all(tripId) as any[];
|
|
|
|
const dayPositions = db.prepare(`
|
|
SELECT rdp.reservation_id, rdp.day_id, rdp.position
|
|
FROM reservation_day_positions rdp
|
|
JOIN reservations r ON rdp.reservation_id = r.id
|
|
WHERE r.trip_id = ?
|
|
`).all(tripId) as { reservation_id: number; day_id: number; position: number }[];
|
|
|
|
const posMap = new Map<number, Record<number, number>>();
|
|
for (const dp of dayPositions) {
|
|
if (!posMap.has(dp.reservation_id)) posMap.set(dp.reservation_id, {});
|
|
posMap.get(dp.reservation_id)![dp.day_id] = dp.position;
|
|
}
|
|
|
|
const endpointsMap = loadEndpointsByTrip(tripId);
|
|
|
|
for (const r of reservations) {
|
|
r.day_positions = posMap.get(r.id) || null;
|
|
r.endpoints = endpointsMap.get(r.id) || [];
|
|
// accommodation_id is a TEXT column; the integer FK reads back as a numeric
|
|
// string (e.g. "14.0"). Normalize to an int so clients can parse it.
|
|
r.accommodation_id = r.accommodation_id == null ? null : Math.trunc(Number(r.accommodation_id));
|
|
}
|
|
|
|
return reservations;
|
|
}
|
|
|
|
/**
|
|
* Upcoming reservations across all of a user's active trips, soonest first.
|
|
* Used by the dashboard's "Upcoming reservations" widget. A reservation counts
|
|
* as upcoming when its own time is in the future, or — for timeless entries —
|
|
* when its day falls on or after today. Cancelled bookings are skipped.
|
|
*/
|
|
export function getUpcomingReservations(userId: number, limit = 6) {
|
|
const today = new Date().toISOString().slice(0, 10);
|
|
const now = new Date().toISOString();
|
|
|
|
const reservations = db.prepare(`
|
|
SELECT r.id, r.trip_id, r.title, r.type, r.status, r.location,
|
|
r.reservation_time, r.confirmation_number,
|
|
t.title as trip_title, t.cover_image as trip_cover,
|
|
d.date as day_date, p.name as place_name, p.image_url as place_image
|
|
FROM reservations r
|
|
JOIN trips t ON t.id = r.trip_id
|
|
LEFT JOIN trip_members tm ON tm.trip_id = t.id AND tm.user_id = ?
|
|
LEFT JOIN days d ON r.day_id = d.id
|
|
LEFT JOIN places p ON r.place_id = p.id
|
|
WHERE (t.user_id = ? OR tm.user_id IS NOT NULL)
|
|
AND t.is_archived = 0
|
|
AND r.status != 'cancelled'
|
|
AND (
|
|
(r.reservation_time IS NOT NULL AND r.reservation_time >= ?)
|
|
OR (r.reservation_time IS NULL AND d.date IS NOT NULL AND d.date >= ?)
|
|
)
|
|
ORDER BY COALESCE(r.reservation_time, d.date) ASC
|
|
LIMIT ?
|
|
`).all(userId, userId, now, today, limit) as any[];
|
|
|
|
return reservations;
|
|
}
|
|
|
|
export function getReservationWithJoins(id: string | number) {
|
|
const row = db.prepare(`
|
|
SELECT r.*, d.day_number, p.name as place_name, r.assignment_id,
|
|
ap.place_id as accommodation_place_id, acc_p.name as accommodation_name,
|
|
ap.start_day_id as accommodation_start_day_id, ap.end_day_id as accommodation_end_day_id
|
|
FROM reservations r
|
|
LEFT JOIN days d ON r.day_id = d.id
|
|
LEFT JOIN places p ON r.place_id = p.id
|
|
LEFT JOIN day_accommodations ap ON r.accommodation_id = ap.id
|
|
LEFT JOIN places acc_p ON ap.place_id = acc_p.id
|
|
WHERE r.id = ?
|
|
`).get(id) as any;
|
|
if (!row) return undefined;
|
|
row.endpoints = loadEndpoints(row.id);
|
|
// accommodation_id is a TEXT column; the integer FK reads back as a numeric
|
|
// string (e.g. "14.0"). Normalize to an int so clients can parse it.
|
|
row.accommodation_id = row.accommodation_id == null ? null : Math.trunc(Number(row.accommodation_id));
|
|
return row;
|
|
}
|
|
|
|
interface CreateAccommodation {
|
|
place_id?: number;
|
|
start_day_id?: number;
|
|
end_day_id?: number;
|
|
check_in?: string;
|
|
check_out?: string;
|
|
confirmation?: string;
|
|
}
|
|
|
|
interface CreateReservationData {
|
|
title: string;
|
|
reservation_time?: string;
|
|
reservation_end_time?: string;
|
|
location?: string;
|
|
confirmation_number?: string;
|
|
notes?: string;
|
|
day_id?: number;
|
|
end_day_id?: number;
|
|
place_id?: number;
|
|
assignment_id?: number;
|
|
status?: string;
|
|
type?: string;
|
|
accommodation_id?: number;
|
|
metadata?: any;
|
|
create_accommodation?: CreateAccommodation;
|
|
endpoints?: EndpointInput[];
|
|
needs_review?: boolean;
|
|
}
|
|
|
|
export function createReservation(tripId: string | number, data: CreateReservationData): { reservation: any; accommodationCreated: boolean } {
|
|
const {
|
|
title, reservation_time, reservation_end_time, location,
|
|
confirmation_number, notes, day_id, end_day_id, place_id, assignment_id,
|
|
status, type, accommodation_id, metadata, create_accommodation,
|
|
endpoints, needs_review
|
|
} = data;
|
|
|
|
let accommodationCreated = false;
|
|
|
|
// Auto-create accommodation for hotel reservations
|
|
let resolvedAccommodationId: number | null = accommodation_id || null;
|
|
if (type === 'hotel' && !resolvedAccommodationId && create_accommodation) {
|
|
const { place_id: accPlaceId, start_day_id, end_day_id, check_in, check_out, confirmation: accConf } = create_accommodation;
|
|
if (start_day_id && end_day_id) {
|
|
const accResult = db.prepare(
|
|
'INSERT INTO day_accommodations (trip_id, place_id, start_day_id, end_day_id, check_in, check_out, confirmation) VALUES (?, ?, ?, ?, ?, ?, ?)'
|
|
).run(tripId, accPlaceId || null, start_day_id, end_day_id, check_in || null, check_out || null, accConf || confirmation_number || null);
|
|
resolvedAccommodationId = Number(accResult.lastInsertRowid);
|
|
accommodationCreated = true;
|
|
}
|
|
}
|
|
|
|
// Derive day_id / end_day_id from reservation_time when the client
|
|
// didn't explicitly set them (non-hotel bookings only — hotels store
|
|
// their date range on the linked day_accommodation).
|
|
const resolvedType = type || 'other';
|
|
let resolvedDayId: number | null = day_id ?? null;
|
|
if (resolvedDayId == null && resolvedType !== 'hotel' && reservation_time) {
|
|
resolvedDayId = resolveDayIdFromTime(tripId, reservation_time);
|
|
}
|
|
let resolvedEndDayId: number | null = end_day_id ?? null;
|
|
if (resolvedEndDayId == null && resolvedType !== 'hotel' && reservation_end_time) {
|
|
resolvedEndDayId = resolveDayIdFromTime(tripId, reservation_end_time);
|
|
}
|
|
|
|
const result = db.prepare(`
|
|
INSERT INTO reservations (trip_id, day_id, end_day_id, place_id, assignment_id, title, reservation_time, reservation_end_time, location, confirmation_number, notes, status, type, accommodation_id, metadata, needs_review)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
`).run(
|
|
tripId,
|
|
resolvedDayId,
|
|
resolvedEndDayId,
|
|
place_id || null,
|
|
assignment_id || null,
|
|
title,
|
|
reservation_time || null,
|
|
reservation_end_time || null,
|
|
location || null,
|
|
confirmation_number || null,
|
|
notes || null,
|
|
status || 'pending',
|
|
resolvedType,
|
|
resolvedAccommodationId,
|
|
metadata ? JSON.stringify(metadata) : null,
|
|
needs_review ? 1 : 0
|
|
);
|
|
|
|
if (endpoints && endpoints.length > 0) {
|
|
saveEndpoints(Number(result.lastInsertRowid), endpoints);
|
|
}
|
|
|
|
// Sync check-in/out to accommodation if linked
|
|
if (accommodation_id && metadata) {
|
|
const meta = typeof metadata === 'string' ? JSON.parse(metadata) : metadata;
|
|
if (meta.check_in_time || meta.check_in_end_time || meta.check_out_time) {
|
|
db.prepare('UPDATE day_accommodations SET check_in = COALESCE(?, check_in), check_in_end = COALESCE(?, check_in_end), check_out = COALESCE(?, check_out) WHERE id = ?')
|
|
.run(meta.check_in_time || null, meta.check_in_end_time || null, meta.check_out_time || null, accommodation_id);
|
|
}
|
|
if (confirmation_number) {
|
|
db.prepare('UPDATE day_accommodations SET confirmation = COALESCE(?, confirmation) WHERE id = ?')
|
|
.run(confirmation_number, accommodation_id);
|
|
}
|
|
}
|
|
|
|
const reservation = getReservationWithJoins(Number(result.lastInsertRowid));
|
|
return { reservation, accommodationCreated };
|
|
}
|
|
|
|
export function updatePositions(tripId: string | number, positions: { id: number; day_plan_position: number }[], dayId?: number | string) {
|
|
if (dayId) {
|
|
// Per-day positions for multi-day reservations
|
|
const stmt = db.prepare('INSERT OR REPLACE INTO reservation_day_positions (reservation_id, day_id, position) VALUES (?, ?, ?)');
|
|
const updateMany = db.transaction((items: { id: number; day_plan_position: number }[]) => {
|
|
for (const item of items) {
|
|
stmt.run(item.id, dayId, item.day_plan_position);
|
|
}
|
|
});
|
|
updateMany(positions);
|
|
} else {
|
|
// Legacy: update global position
|
|
const stmt = db.prepare('UPDATE reservations SET day_plan_position = ? WHERE id = ? AND trip_id = ?');
|
|
const updateMany = db.transaction((items: { id: number; day_plan_position: number }[]) => {
|
|
for (const item of items) {
|
|
stmt.run(item.day_plan_position, item.id, tripId);
|
|
}
|
|
});
|
|
updateMany(positions);
|
|
}
|
|
}
|
|
|
|
export function getReservation(id: string | number, tripId: string | number) {
|
|
return db.prepare('SELECT * FROM reservations WHERE id = ? AND trip_id = ?').get(id, tripId) as Reservation | undefined;
|
|
}
|
|
|
|
interface UpdateReservationData {
|
|
title?: string;
|
|
reservation_time?: string;
|
|
reservation_end_time?: string;
|
|
location?: string;
|
|
confirmation_number?: string;
|
|
notes?: string;
|
|
day_id?: number;
|
|
end_day_id?: number | null;
|
|
place_id?: number;
|
|
assignment_id?: number;
|
|
status?: string;
|
|
type?: string;
|
|
accommodation_id?: number;
|
|
metadata?: any;
|
|
create_accommodation?: CreateAccommodation;
|
|
endpoints?: EndpointInput[];
|
|
needs_review?: boolean;
|
|
}
|
|
|
|
export function updateReservation(id: string | number, tripId: string | number, data: UpdateReservationData, current: Reservation): { reservation: any; accommodationChanged: boolean } {
|
|
const {
|
|
title, reservation_time, reservation_end_time, location,
|
|
confirmation_number, notes, day_id, end_day_id, place_id, assignment_id,
|
|
status, type, accommodation_id, metadata, create_accommodation,
|
|
endpoints, needs_review
|
|
} = data;
|
|
|
|
let accommodationChanged = false;
|
|
|
|
// Update or create accommodation for hotel reservations
|
|
let resolvedAccId: number | null = accommodation_id !== undefined ? (accommodation_id || null) : (current.accommodation_id ?? null);
|
|
if (resolvedAccId) {
|
|
const accExists = db.prepare('SELECT id FROM day_accommodations WHERE id = ?').get(resolvedAccId);
|
|
if (!accExists) resolvedAccId = null;
|
|
}
|
|
if (type === 'hotel' && create_accommodation) {
|
|
const { place_id: accPlaceId, start_day_id, end_day_id, check_in, check_out, confirmation: accConf } = create_accommodation;
|
|
if (start_day_id && end_day_id) {
|
|
if (resolvedAccId) {
|
|
db.prepare('UPDATE day_accommodations SET place_id = ?, start_day_id = ?, end_day_id = ?, check_in = ?, check_out = ?, confirmation = ? WHERE id = ?')
|
|
.run(accPlaceId || null, start_day_id, end_day_id, check_in || null, check_out || null, accConf || confirmation_number || null, resolvedAccId);
|
|
} else if (accPlaceId) {
|
|
const accResult = db.prepare(
|
|
'INSERT INTO day_accommodations (trip_id, place_id, start_day_id, end_day_id, check_in, check_out, confirmation) VALUES (?, ?, ?, ?, ?, ?, ?)'
|
|
).run(tripId, accPlaceId, start_day_id, end_day_id, check_in || null, check_out || null, accConf || confirmation_number || null);
|
|
resolvedAccId = Number(accResult.lastInsertRowid);
|
|
}
|
|
accommodationChanged = true;
|
|
}
|
|
}
|
|
|
|
const resolvedType = (type ?? current.type) || 'other';
|
|
const nextReservationTime = resolvedType === 'hotel'
|
|
? null
|
|
: (reservation_time !== undefined ? (reservation_time || null) : current.reservation_time);
|
|
const nextReservationEndTime = resolvedType === 'hotel'
|
|
? null
|
|
: (reservation_end_time !== undefined ? (reservation_end_time || null) : current.reservation_end_time);
|
|
|
|
// day_id / end_day_id: honour an explicit value from the client,
|
|
// otherwise derive from the (possibly updated) reservation_time so the
|
|
// planner renders the booking on the correct day.
|
|
let nextDayId: number | null;
|
|
if (day_id != null) {
|
|
// Explicit day from the client (e.g. moved on the planner).
|
|
nextDayId = day_id;
|
|
} else if (resolvedType !== 'hotel' && nextReservationTime) {
|
|
// No day set but we have a date — pin it to the matching day so the booking
|
|
// still shows in the Plan (covers bookings saved without a selected day, and
|
|
// the case where an earlier edit cleared day_id).
|
|
nextDayId = resolveDayIdFromTime(tripId, nextReservationTime);
|
|
} else if (day_id === undefined) {
|
|
// Field absent and nothing to derive from — keep whatever it had.
|
|
nextDayId = current.day_id ?? null;
|
|
} else {
|
|
nextDayId = null;
|
|
}
|
|
|
|
let nextEndDayId: number | null;
|
|
if (end_day_id !== undefined) {
|
|
nextEndDayId = end_day_id ?? null;
|
|
} else if (reservation_end_time !== undefined && resolvedType !== 'hotel') {
|
|
nextEndDayId = resolveDayIdFromTime(tripId, nextReservationEndTime);
|
|
} else {
|
|
nextEndDayId = (current as any).end_day_id ?? null;
|
|
}
|
|
|
|
db.prepare(`
|
|
UPDATE reservations SET
|
|
title = COALESCE(?, title),
|
|
reservation_time = ?,
|
|
reservation_end_time = ?,
|
|
location = ?,
|
|
confirmation_number = ?,
|
|
notes = ?,
|
|
day_id = ?,
|
|
end_day_id = ?,
|
|
place_id = ?,
|
|
assignment_id = ?,
|
|
status = COALESCE(?, status),
|
|
type = COALESCE(?, type),
|
|
accommodation_id = ?,
|
|
metadata = ?,
|
|
needs_review = COALESCE(?, needs_review)
|
|
WHERE id = ?
|
|
`).run(
|
|
title || null,
|
|
nextReservationTime,
|
|
nextReservationEndTime,
|
|
location !== undefined ? (location || null) : current.location,
|
|
confirmation_number !== undefined ? (confirmation_number || null) : current.confirmation_number,
|
|
notes !== undefined ? (notes || null) : current.notes,
|
|
nextDayId,
|
|
nextEndDayId,
|
|
place_id !== undefined ? (place_id || null) : current.place_id,
|
|
assignment_id !== undefined ? (assignment_id || null) : current.assignment_id,
|
|
status || null,
|
|
type || null,
|
|
resolvedAccId,
|
|
metadata !== undefined ? (metadata ? JSON.stringify(metadata) : null) : current.metadata,
|
|
needs_review === undefined ? null : (needs_review ? 1 : 0),
|
|
id
|
|
);
|
|
|
|
if (endpoints !== undefined) {
|
|
saveEndpoints(Number(id), endpoints);
|
|
}
|
|
|
|
// Sync check-in/out to accommodation if linked
|
|
const resolvedMeta = metadata !== undefined ? metadata : (current.metadata ? JSON.parse(current.metadata as string) : null);
|
|
if (resolvedAccId && resolvedMeta) {
|
|
const meta = typeof resolvedMeta === 'string' ? JSON.parse(resolvedMeta) : resolvedMeta;
|
|
if (meta.check_in_time || meta.check_in_end_time || meta.check_out_time) {
|
|
db.prepare('UPDATE day_accommodations SET check_in = COALESCE(?, check_in), check_in_end = COALESCE(?, check_in_end), check_out = COALESCE(?, check_out) WHERE id = ?')
|
|
.run(meta.check_in_time || null, meta.check_in_end_time || null, meta.check_out_time || null, resolvedAccId);
|
|
}
|
|
const resolvedConf = confirmation_number !== undefined ? confirmation_number : current.confirmation_number;
|
|
if (resolvedConf) {
|
|
db.prepare('UPDATE day_accommodations SET confirmation = COALESCE(?, confirmation) WHERE id = ?')
|
|
.run(resolvedConf, resolvedAccId);
|
|
}
|
|
}
|
|
|
|
const reservation = getReservationWithJoins(id);
|
|
return { reservation, accommodationChanged };
|
|
}
|
|
|
|
export function deleteReservation(id: string | number, tripId: string | number): { deleted: { id: number; title: string; type: string; accommodation_id: number | null } | undefined; accommodationDeleted: boolean; deletedBudgetItemId: number | null } {
|
|
const reservation = db.prepare('SELECT id, title, type, accommodation_id FROM reservations WHERE id = ? AND trip_id = ?').get(id, tripId) as { id: number; title: string; type: string; accommodation_id: number | null } | undefined;
|
|
if (!reservation) return { deleted: undefined, accommodationDeleted: false, deletedBudgetItemId: null };
|
|
|
|
let accommodationDeleted = false;
|
|
if (reservation.accommodation_id) {
|
|
db.prepare('DELETE FROM day_accommodations WHERE id = ?').run(reservation.accommodation_id);
|
|
accommodationDeleted = true;
|
|
}
|
|
|
|
const linkedBudget = db.prepare('SELECT id FROM budget_items WHERE trip_id = ? AND reservation_id = ?').get(tripId, id) as { id: number } | undefined;
|
|
if (linkedBudget) {
|
|
db.prepare('DELETE FROM budget_items WHERE id = ?').run(linkedBudget.id);
|
|
}
|
|
|
|
db.prepare('DELETE FROM reservations WHERE id = ?').run(id);
|
|
return { deleted: reservation, accommodationDeleted, deletedBudgetItemId: linkedBudget ? linkedBudget.id : null };
|
|
}
|