merge dev into feat/postgres-support

This commit is contained in:
Maurice
2026-11-17 11:10:01 +01:00
3032 changed files with 153102 additions and 20800 deletions
@@ -179,9 +179,13 @@ export class CollabMessagesRepository extends TrekRepository<CollabMessages> {
return await this.insert({ trip: trip_id, user: user_id, text, reply_to, origin });
}
/** CB54 (`deleteMessage`, inside its transaction) — `UPDATE collab_messages SET deleted = 1 WHERE id = ?`, soft delete — the row survives for the placeholder. */
/**
* CB54 (`deleteMessage`, inside its transaction) — `UPDATE collab_messages SET deleted = 1, text = '' WHERE id = ?`,
* soft delete: the row survives for the placeholder, its text does not, so a deleted message is gone from the
* database and every backup made after it, not only hidden from the client.
*/
async softDelete(id: number): Promise<void> {
await this.nativeUpdate({ id }, { deleted: 1 });
await this.nativeUpdate({ id }, { deleted: 1, text: '' });
}
// -------------------------------------------------------------------------
@@ -171,6 +171,13 @@ export class CollectionPlacesRepository extends TrekRepository<CollectionPlaces>
category_id: number | null;
image_url: string | null;
links: string | null;
google_place_id: string | null;
google_ftid: string | null;
osm_id: string | null;
website: string | null;
phone: string | null;
price: number | null;
currency: string | null;
collection_id: number;
owner_id: number;
}>,
@@ -84,6 +84,42 @@ type CollectionPlacesWriteKyselyDB = Pick<DB, 'collection_places'>;
type CollectionPlaceLabelsKyselyDB = Pick<DB, 'collection_place_labels'>;
type CollectionPlacesPageKyselyDB = Pick<DB, 'collection_places' | 'collection_place_labels'>;
/** Which of a list's places a page holds (list_collection_places, #2647); every filter left out matches all. */
interface CollectionPlacePageFilter {
status?: string;
labelId?: number;
unlabeled?: boolean;
}
/**
* A place's position in its list: the keys both a page and getCollection order
* by, in that order. A missing sort_order reads as the column default and a
* missing created_at as the earliest, so the order is total on every engine and
* a page can go on after any place.
*/
export interface CollectionPlacePosition {
sortOrder: number;
createdAt: string;
id: number;
}
/** A saved place as a page names it: the fields an agent finds it by, plus its position. */
export interface CollectionPlacePageRow {
id: number;
name: string;
status: string;
address: string | null;
lat: number | null;
lng: number | null;
google_place_id: string | null;
website: string | null;
phone: string | null;
sort_key: number;
created_key: string;
}
/**
* `collections` — the root of the collections cluster (Plan 3h Task 1, part
* A). Owns every CL1-CL36 statement not moved to `CollectionMembersRepository`/
@@ -254,6 +290,23 @@ export class CollectionsRepository extends TrekRepository<Collections> {
await this.readDb().deleteFrom('collections').where('id', '=', id).execute();
}
/**
* `deleteCollection`: deletes a list like `deleteById` and hands back the uploads it
* named, its cover and its saved places' images, read before the cascade takes their
* rows, so they can go like a single place's do once nothing else names them (#2924).
*/
async deleteWithImages(id: number): Promise<Array<string | null>> {
const cover = (await this.coverImage(id)) ?? null;
const places = await this.placesReadDb()
.selectFrom('collection_places')
.select('image_url')
.where('collection_id', '=', id)
.where('image_url', 'is not', null)
.execute();
await this.deleteById(id);
return [cover, ...places.map((place) => place.image_url)];
}
/**
* CL36 (`reorderCollections`, TX `:712`) — `UPDATE collections SET
* sort_order=? WHERE id=?`, looped per visible id. The legacy statement
@@ -327,7 +380,9 @@ export class CollectionsRepository extends TrekRepository<Collections> {
* CL16/CL17 (`getCollection`/`exportCollection`'s dup-text pair, collapsed
* onto ONE repository method as the brief directs) — the same
* `cp.*`/category-alias select as {@link findPlaceRowById}, scoped by
* `cp.collection_id` and ordered by `cp.sort_order, cp.created_at`.
* `cp.collection_id` and ordered by the place's position: `sort_order`,
* `created_at`, then `id`, so two places saved in the same second keep one
* order, the one list_collection_places pages through (#2647).
*/
async listPlaceRows(collectionId: number): Promise<CollectionPlaceRow[]> {
return await this.placesReadDb()
@@ -365,8 +420,99 @@ export class CollectionsRepository extends TrekRepository<Collections> {
'c.icon as category_icon',
])
.where('cp.collection_id', '=', collectionId)
.orderBy('cp.sort_order')
.orderBy('cp.created_at')
.orderBy((eb) => eb.fn.coalesce('cp.sort_order', eb.val(0)))
.orderBy((eb) => eb.fn.coalesce('cp.created_at', eb.val('')))
.orderBy('cp.id')
.execute();
}
/** The places of a list the filter matches, before any paging. */
private filteredPlaces(collectionId: number, filter: CollectionPlacePageFilter) {
const { status, labelId, unlabeled } = filter;
let query = this.kysely<CollectionPlacesPageKyselyDB>()
.selectFrom('collection_places as cp')
.where('cp.collection_id', '=', collectionId);
if (status !== undefined) query = query.where('cp.status', '=', status);
if (labelId !== undefined) {
query = query.where((eb) =>
eb.exists(
eb
.selectFrom('collection_place_labels as cpl')
.select('cpl.label_id')
.whereRef('cpl.collection_place_id', '=', 'cp.id')
.where('cpl.label_id', '=', labelId),
),
);
}
if (unlabeled) {
query = query.where((eb) =>
eb.not(
eb.exists(
eb
.selectFrom('collection_place_labels as cpl')
.select('cpl.label_id')
.whereRef('cpl.collection_place_id', '=', 'cp.id'),
),
),
);
}
return query;
}
/** How many places of a list the filter matches (list_collection_places' total). */
async countPlacePage(collectionId: number, filter: CollectionPlacePageFilter): Promise<number> {
const row = await this.filteredPlaces(collectionId, filter)
.select((eb) => eb.fn.countAll<number>().as('n'))
.executeTakeFirstOrThrow();
return Number(row.n);
}
/**
* Up to `limit` places of a list the filter matches, in the list's order
* (listPlaceRows'), starting after the position `after` names: a keyset, so
* a place that stops matching between two pages moves none of the others.
*/
async listPlacePage(
collectionId: number,
filter: CollectionPlacePageFilter,
after: CollectionPlacePosition | null,
limit: number,
): Promise<CollectionPlacePageRow[]> {
let query = this.filteredPlaces(collectionId, filter);
if (after) {
query = query.where((eb) => {
const sortKey = eb.fn.coalesce('cp.sort_order', eb.val(0));
const createdKey = eb.fn.coalesce('cp.created_at', eb.val(''));
return eb.or([
eb(sortKey, '>', after.sortOrder),
eb.and([
eb(sortKey, '=', after.sortOrder),
eb.or([
eb(createdKey, '>', after.createdAt),
eb.and([eb(createdKey, '=', after.createdAt), eb('cp.id', '>', after.id)]),
]),
]),
]);
});
}
return await query
.select((eb) => [
'cp.id',
'cp.name',
'cp.status',
'cp.address',
'cp.lat',
'cp.lng',
'cp.google_place_id',
'cp.website',
'cp.phone',
eb.fn.coalesce('cp.sort_order', eb.val(0)).as('sort_key'),
eb.fn.coalesce('cp.created_at', eb.val('')).as('created_key'),
])
.orderBy('sort_key')
.orderBy('created_key')
.orderBy('cp.id')
.limit(limit)
.execute();
}
@@ -266,6 +266,8 @@ export class DayAssignmentsRepository extends TrekRepository<DayAssignments> {
accommodation_id: number | null;
/** MDT-02: one stage of a multi-day tour, by its starting stop's key; absent for the whole tour or a place. */
tour_stage_key?: string | null;
/** #3092: the visit's own stay; absent or null reads the place's. */
stay_minutes?: number | null;
}): Promise<number> {
return await this.insert({
day: input.day_id,
@@ -274,6 +276,7 @@ export class DayAssignmentsRepository extends TrekRepository<DayAssignments> {
notes: input.notes,
accommodation_id: input.accommodation_id,
tour_stage_key: input.tour_stage_key ?? null,
stay_minutes: input.stay_minutes ?? null,
});
}
@@ -424,6 +427,14 @@ export class DayAssignmentsRepository extends TrekRepository<DayAssignments> {
await this.nativeUpdate({ id }, { end_day });
}
/**
* `UPDATE day_assignments SET stay_minutes = ? WHERE id = ?` (#3092). Null hands the
* visit back to the stay its place carries.
*/
async setStayMinutes(id: number, stay_minutes: number | null): Promise<void> {
await this.nativeUpdate({ id }, { stay_minutes });
}
/** AS25 — `UPDATE day_assignments SET notes = ? WHERE id = ?`. */
async setNotes(id: number, notes: string | null): Promise<void> {
await this.nativeUpdate({ id }, { notes });
@@ -542,6 +553,8 @@ export class DayAssignmentsRepository extends TrekRepository<DayAssignments> {
end_day: number;
/** MDT-02: the copied tour keeps its stops' keys, so a day holding one of its stages keeps holding it. */
tour_stage_key?: string | null;
/** #3092: the visit's own stay goes with it. */
stay_minutes?: number | null;
}): Promise<number> {
return await this.insert({
day: input.day_id,
@@ -555,6 +568,7 @@ export class DayAssignmentsRepository extends TrekRepository<DayAssignments> {
assignment_end_time: input.assignment_end_time,
end_day: input.end_day,
tour_stage_key: input.tour_stage_key ?? null,
stay_minutes: input.stay_minutes ?? null,
});
}
@@ -637,7 +651,9 @@ export class DayAssignmentsRepository extends TrekRepository<DayAssignments> {
'p.lng as lng',
eb.fn.coalesce('a.assignment_time', 'p.place_time').as('time'),
eb.fn.coalesce('a.assignment_end_time', 'p.end_time').as('end_time'),
'p.duration_minutes as duration_minutes',
// A visit's own stay before the place's (#3092): the same place planned twice
// on a day can be stood at for two different lengths.
eb.fn.coalesce('a.stay_minutes', 'p.duration_minutes').as('duration_minutes'),
'a.end_day as end_day',
'a.leg_transport_mode as leg_transport_mode',
'a.incoming_leg_transport_mode as incoming_leg_transport_mode',
@@ -0,0 +1,210 @@
import type { FlightLiveStates } from '../entities/FlightLiveStates.entity';
import type { DB } from '../kysely/db';
import type { DbTimestamp } from '../types';
import { TrekRepository } from './_shared/trek-repository';
/** A flight booking as the live flight status reads it; the metadata is the stored text. */
export interface FlightBookingDbRow {
id: number;
trip_id: number;
trip_title: string;
metadata: string | null;
day_id: number | null;
end_day_id: number | null;
reservation_time: string | null;
reservation_end_time: string | null;
}
interface FlightEndpointDbRow {
reservation_id: number;
role: string;
sequence: number;
name: string;
code: string | null;
lat: number;
lng: number;
timezone: string | null;
local_date: string | null;
local_time: string | null;
}
/**
* One flight state, every column; timestamps in the canonical UTC text. `T`
* is `string` for a row read back and `DbTimestamp` for one being written.
*/
interface FlightLiveStateFields<T extends string> {
callsign: string;
service_date: string;
origin: string;
destination: string;
phase: string;
departed_at: T | null;
landed_at: T | null;
lat: number | null;
lng: number | null;
altitude_ft: number | null;
ground_speed_kt: number | null;
track_deg: number | null;
vertical_rate_fpm: number | null;
on_ground: number | null;
registration: string | null;
aircraft_type: string | null;
source: string | null;
first_seen_at: T | null;
last_seen_at: T | null;
fetched_at: T | null;
next_poll_at: T | null;
fail_count: number;
departed_notified: number;
landed_notified: number;
delay_notified: number;
}
export type FlightLiveStateRow = FlightLiveStateFields<string>;
export type FlightLiveStateWrite = FlightLiveStateFields<DbTimestamp>;
const BOOKING_COLUMNS = [
'reservations.id',
'reservations.trip_id',
'reservations.metadata',
'reservations.day_id',
'reservations.end_day_id',
'reservations.reservation_time',
'reservations.reservation_end_time',
] as const;
const ENDPOINT_COLUMNS = [
'reservation_id',
'role',
'sequence',
'name',
'code',
'lat',
'lng',
'timezone',
'local_date',
'local_time',
] as const;
/**
* `flight_live_states`: what the open ADS-B feeds last said about a flight on
* a day, one row per (callsign, service date, origin, destination) whichever
* trips booked it.
*
* The flight bookings, their endpoints, the days they name and their
* travellers are read here too, through Kysely: the live status only reads
* them, and the reservations domain has no read of flights across all trips.
*/
export class FlightLiveStatesRepository extends TrekRepository<FlightLiveStates> {
/** The flight bookings of one trip. */
async listFlightBookingsForTrip(trip_id: number): Promise<FlightBookingDbRow[]> {
return await this.kysely<Pick<DB, 'reservations' | 'trips'>>()
.selectFrom('reservations')
.innerJoin('trips', 'trips.id', 'reservations.trip_id')
.select([...BOOKING_COLUMNS, 'trips.title as trip_title'])
.where('reservations.trip_id', '=', trip_id)
.where('reservations.type', '=', 'flight')
.orderBy('reservations.id')
.execute();
}
/**
* The flight bookings of every trip that is not archived and whose dates
* (where it has any) reach into `from_date`..`to_date`: the candidates for a
* poll. Which leg is really in its window the caller works out from the
* schedule.
*/
async listFlightBookingsBetween(from_date: string, to_date: string): Promise<FlightBookingDbRow[]> {
return await this.kysely<Pick<DB, 'reservations' | 'trips'>>()
.selectFrom('reservations')
.innerJoin('trips', 'trips.id', 'reservations.trip_id')
.select([...BOOKING_COLUMNS, 'trips.title as trip_title'])
.where('reservations.type', '=', 'flight')
.where((eb) => eb.or([eb('trips.is_archived', 'is', null), eb('trips.is_archived', '=', 0)]))
.where((eb) => eb.or([eb('trips.end_date', 'is', null), eb('trips.end_date', '>=', from_date)]))
.where((eb) => eb.or([eb('trips.start_date', 'is', null), eb('trips.start_date', '<=', to_date)]))
.orderBy('reservations.id')
.execute();
}
/** The endpoints of the given bookings, in their order. */
async listEndpoints(reservation_ids: readonly number[]): Promise<FlightEndpointDbRow[]> {
if (reservation_ids.length === 0) return [];
return await this.kysely<Pick<DB, 'reservation_endpoints'>>()
.selectFrom('reservation_endpoints')
.select([...ENDPOINT_COLUMNS])
.where('reservation_id', 'in', [...reservation_ids])
.orderBy('reservation_id')
.orderBy('sequence')
.execute();
}
/** The date of each given trip day that has one. */
async listDayDates(day_ids: readonly number[]): Promise<Array<{ id: number; date: string }>> {
if (day_ids.length === 0) return [];
const rows = await this.kysely<Pick<DB, 'days'>>()
.selectFrom('days')
.select(['id', 'date'])
.where('id', 'in', [...day_ids])
.execute();
return rows.flatMap((row) => (row.date ? [{ id: row.id, date: row.date }] : []));
}
/**
* The users put on a booking as its travellers who still belong to its trip:
* the owner or a member. Someone removed from the trip stays on the
* traveller list until it is edited, and must hear nothing more of it.
*/
async listTravelerIds(reservation_id: number): Promise<number[]> {
const rows = await this.kysely<Pick<DB, 'reservation_travelers' | 'reservations' | 'trips' | 'trip_members'>>()
.selectFrom('reservation_travelers as rt')
.innerJoin('reservations as r', 'r.id', 'rt.reservation_id')
.innerJoin('trips as t', 't.id', 'r.trip_id')
.select('rt.user_id')
.where('rt.reservation_id', '=', reservation_id)
.where((eb) =>
eb.or([
eb('t.user_id', '=', eb.ref('rt.user_id')),
eb.exists(
eb
.selectFrom('trip_members as tm')
.select('tm.id')
.whereRef('tm.trip_id', '=', 'r.trip_id')
.whereRef('tm.user_id', '=', 'rt.user_id'),
),
]),
)
.orderBy('rt.user_id')
.execute();
return rows.map((row) => row.user_id);
}
/** Every stored state of the given callsigns, whatever their day. */
async findForCallsigns(callsigns: readonly string[]): Promise<FlightLiveStateRow[]> {
if (callsigns.length === 0) return [];
return await this.kysely<Pick<DB, 'flight_live_states'>>()
.selectFrom('flight_live_states')
.selectAll()
.where('callsign', 'in', [...callsigns])
.execute();
}
/** Writes a flight's whole state, replacing the one stored under its key. */
async saveState(row: FlightLiveStateWrite): Promise<void> {
const { callsign, service_date, origin, destination, ...changes } = row;
await this.kysely<Pick<DB, 'flight_live_states'>>()
.insertInto('flight_live_states')
.values({ callsign, service_date, origin, destination, ...changes })
.onConflict((oc) => oc.columns(['callsign', 'service_date', 'origin', 'destination']).doUpdateSet(changes))
.execute();
}
/** Drops the states of flights that departed before `service_date`; answers how many went. */
async deleteBefore(service_date: string): Promise<number> {
const result = await this.kysely<Pick<DB, 'flight_live_states'>>()
.deleteFrom('flight_live_states')
.where('service_date', '<', service_date)
.executeTakeFirst();
return Number(result.numDeletedRows);
}
}
@@ -52,6 +52,19 @@ type JourneyListKyselyDB = Pick<
/** The `journeys`/`journey_contributors` tables {@link JourneysRepository.listRecipientUserIds} reads. */
type JourneyRecipientsKyselyDB = Pick<DB, 'journeys' | 'journey_contributors'>;
/** The tables {@link JourneysRepository.listGalleryPhotos} and {@link JourneysRepository.deleteUnlinkedPhotos} touch. */
type JourneyPhotoFilesKyselyDB = Pick<DB, 'journeys' | 'journey_photos' | 'trek_photos' | 'trip_photos'>;
/** A photo behind a journey's gallery, with the stored paths its row names. */
export interface JourneyGalleryPhotoFiles {
photo_id: number;
file_path: string | null;
thumbnail_path: string | null;
}
/** Ids per DELETE, well under SQLite's bound-parameter limit. */
const PHOTO_DELETE_BATCH = 500;
/**
* `journeys` — the root of the journey cluster (Plan 3g Task 1, R9's Part A).
* Every method here is a Part-A-owned statement (JG1-JG29 group) or a shared
@@ -261,4 +274,49 @@ export class JourneysRepository extends TrekRepository<Journeys> {
async deleteOwnedByUser(userId: number): Promise<void> {
await this.nativeDelete({ user: userId });
}
/**
* The photos in the gallery of one journey, or of every journey a user owns,
* with the paths their `trek_photos` rows store. Read before the journey is
* deleted: the cascade takes the gallery rows, and with them the only way
* back to the photos.
*/
async listGalleryPhotos(scope: { journeyId: number } | { ownerId: number }): Promise<JourneyGalleryPhotoFiles[]> {
const [column, value] =
'journeyId' in scope ? (['j.id', scope.journeyId] as const) : (['j.user_id', scope.ownerId] as const);
return await this.kysely<JourneyPhotoFilesKyselyDB>()
.selectFrom('journey_photos as jp')
.innerJoin('journeys as j', 'j.id', 'jp.journey_id')
.innerJoin('trek_photos as tp', 'tp.id', 'jp.photo_id')
.select(['jp.photo_id', 'tp.file_path', 'tp.thumbnail_path'])
.distinct()
.where(column, '=', value)
.execute();
}
/**
* Deletes the `trek_photos` rows among `photoIds` that no trip and no journey
* links any more, after their journeys went: the same rule as
* `TrekPhotoRegistrationService.deleteIfOrphan` with `local`, for a whole
* gallery at once. A row left behind would keep naming its file, and the
* storage reclaim counts every row with a path as live (#2924). A photo still
* in another journey's gallery, or in a trip's, keeps its row. Answers how
* many rows went.
*/
async deleteUnlinkedPhotos(photoIds: readonly number[]): Promise<number> {
const pages = Array.from({ length: Math.ceil(photoIds.length / PHOTO_DELETE_BATCH) }, (_unused, i) =>
photoIds.slice(i * PHOTO_DELETE_BATCH, (i + 1) * PHOTO_DELETE_BATCH),
);
// One page after the other: they share the caller's transaction.
return await pages.reduce<Promise<number>>(async (previous, page) => {
const deleted = await previous;
const result = await this.kysely<JourneyPhotoFilesKyselyDB>()
.deleteFrom('trek_photos')
.where('id', 'in', page)
.where('id', 'not in', (eb) => eb.selectFrom('trip_photos').select('photo_id'))
.where('id', 'not in', (eb) => eb.selectFrom('journey_photos').select('photo_id'))
.executeTakeFirst();
return deleted + Number(result.numDeletedRows);
}, Promise.resolve(0));
}
}
@@ -0,0 +1,113 @@
import type { MailIngestAddresses } from '../entities/MailIngestAddresses.entity';
import type { DB } from '../kysely/db';
import type { DbTimestamp } from '../types';
import type { AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
/** One `mail_ingest_addresses` row as stored. */
export interface MailIngestAddressRow {
id: number;
token_hash: string;
token_enc: string;
user_id: number;
trip_id: number | null;
created_at: string;
revoked_at: string | null;
last_used_at: string | null;
}
const _mailIngestAddressRowKeys: AssertRowKeys<MailIngestAddressRow, MailIngestAddresses> = true;
/** A new address: whose it is, for which trip (null for the person's own), and its token in both forms. */
interface MailIngestAddressInsert {
userId: number;
tripId: number | null;
tokenHash: string;
tokenEnc: string;
createdAt: DbTimestamp;
}
type AddressesKyselyDB = Pick<DB, 'mail_ingest_addresses'>;
/**
* `mail_ingest_addresses`: the forwarding addresses. A person has at most one
* live address of their own and one per trip; renewing one revokes the old row
* instead of deleting it, so a mail that still reaches the old token is
* recognised and refused rather than taken for a stranger's.
*/
export class MailIngestAddressesRepository extends TrekRepository<MailIngestAddresses> {
private db() {
return this.kysely<AddressesKyselyDB>();
}
async insertAddress(row: MailIngestAddressInsert): Promise<number> {
const inserted = await this.db()
.insertInto('mail_ingest_addresses')
.values({
user_id: row.userId,
trip_id: row.tripId,
token_hash: row.tokenHash,
token_enc: row.tokenEnc,
created_at: row.createdAt,
})
.returning('id')
.executeTakeFirstOrThrow();
return inserted.id;
}
/** The person's live address for the trip, or their own one with `tripId` null. */
async findLive(userId: number, tripId: number | null): Promise<MailIngestAddressRow | null> {
let query = this.db()
.selectFrom('mail_ingest_addresses')
.selectAll()
.where('user_id', '=', userId)
.where('revoked_at', 'is', null);
query = tripId === null ? query.where('trip_id', 'is', null) : query.where('trip_id', '=', tripId);
const row = await query.orderBy('id', 'desc').executeTakeFirst();
return row ?? null;
}
/** The address a token names, revoked or not. */
async findByTokenHash(tokenHash: string): Promise<MailIngestAddressRow | null> {
const row = await this.db()
.selectFrom('mail_ingest_addresses')
.selectAll()
.where('token_hash', '=', tokenHash)
.executeTakeFirst();
return row ?? null;
}
async findById(id: number): Promise<MailIngestAddressRow | null> {
const row = await this.db().selectFrom('mail_ingest_addresses').selectAll().where('id', '=', id).executeTakeFirst();
return row ?? null;
}
/** Revokes the person's live address for the trip (their own with `tripId` null); answers how many went. */
async revokeLive(userId: number, tripId: number | null, at: DbTimestamp): Promise<number> {
let query = this.db()
.updateTable('mail_ingest_addresses')
.set({ revoked_at: at })
.where('user_id', '=', userId)
.where('revoked_at', 'is', null);
query = tripId === null ? query.where('trip_id', 'is', null) : query.where('trip_id', '=', tripId);
const result = await query.executeTakeFirst();
return Number(result.numUpdatedRows);
}
/** The people who hold at least one address that is not revoked. */
async listHolders(): Promise<number[]> {
const rows = await this.db()
.selectFrom('mail_ingest_addresses')
.select('user_id')
.distinct()
.where('revoked_at', 'is', null)
.orderBy('user_id')
.execute();
return rows.map((row) => row.user_id);
}
/** Notes that a mail came in on the address. */
async touchUsed(id: number, at: DbTimestamp): Promise<void> {
await this.db().updateTable('mail_ingest_addresses').set({ last_used_at: at }).where('id', '=', id).execute();
}
}
@@ -0,0 +1,492 @@
import type { MailIngestCandidates } from '../entities/MailIngestCandidates.entity';
import type { DB } from '../kysely/db';
import type { DbTimestamp } from '../types';
import type { AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
import type { Expression, SqlBool } from 'kysely';
/** One `mail_ingest_candidates` row as stored: the JSON columns as text. */
export interface MailIngestCandidateRow {
id: number;
message_id: number;
user_id: number;
position: number;
item_json: string | null;
source: string | null;
checks_json: string | null;
uncertain_fields: string | null;
match_json: string | null;
suggested_trip_id: number | null;
dedupe_key: string | null;
content_hash: string | null;
resolution: string;
reason: string | null;
resolved_trip_id: number | null;
created_ids_json: string | null;
attach_error: string | null;
resolved_by: number | null;
resolved_at: string | null;
undo_until: string | null;
created_at: string;
}
const _mailIngestCandidateRowKeys: AssertRowKeys<MailIngestCandidateRow, MailIngestCandidates> = true;
/** A booking read from a mail, as the pipeline writes it: waiting, or already decided in the same write. */
export interface MailIngestCandidateInsert {
messageId: number;
userId: number;
position: number;
itemJson: string | null;
source: string | null;
checksJson: string | null;
uncertainFields: string | null;
matchJson: string | null;
suggestedTripId: number | null;
dedupeKey: string | null;
contentHash: string | null;
resolution: string;
reason: string | null;
createdAt: DbTimestamp;
/** For an entry decided as it is written: the trip it went to, what it created, until when it can be undone. */
resolvedTripId?: number | null;
createdIdsJson?: string | null;
resolvedAt?: DbTimestamp | null;
undoUntil?: DbTimestamp | null;
}
/** What deciding an entry writes. */
interface MailIngestResolutionPatch {
resolution: string;
reason: string | null;
resolvedTripId: number | null;
createdIdsJson: string | null;
resolvedBy: number | null;
/** Null puts an entry back into the inbox. */
resolvedAt: DbTimestamp | null;
undoUntil: DbTimestamp | null;
}
/** A trip a booking from a mail may go to, as the import weighs it. */
export interface MailIngestTripRow {
id: number;
title: string;
start_date: string | null;
end_date: string | null;
/** The owner, for the permission check. */
user_id: number;
currency: string | null;
}
/** A place of a trip with a position, for naming its destinations and checking a booking lies near them. */
interface MailIngestTripPlaceRow {
trip_id: number;
name: string;
address: string | null;
lat: number;
lng: number;
}
/** A trip as the inbox names it to a person who can see it. */
interface MailIngestTripRefRow {
id: number;
title: string;
start_date: string | null;
end_date: string | null;
}
/** The person a mail is for, as the pipeline needs them. */
export interface MailIngestPersonRow {
id: number;
username: string;
email: string;
role: string;
}
/** What tells one booking from another already in a trip: its type, its start window and its reference. */
interface MailIngestSimilarProbe {
type: string;
startFrom: string | null;
startTo: string | null;
confirmation: string | null;
}
type CandidatesKyselyDB = Pick<
DB,
| 'mail_ingest_candidates'
| 'trips'
| 'trip_members'
| 'days'
| 'places'
| 'users'
| 'reservations'
| 'day_assignments'
| 'day_accommodations'
| 'budget_item_payers'
>;
/** The most places a trip lends its destinations and its geography to the import. */
const PLACES_PER_LOOKUP = 2000;
/**
* `mail_ingest_candidates`: the bookings read from forwarded mails, and the
* reads the import makes of the trips they may go to. Those reads touch the
* trips, days, places, users and reservations tables directly, by column, so
* the import weighs a booking without reaching into five other domains for
* one projection each; every write it makes to a trip goes through the
* owning services.
*/
export class MailIngestCandidatesRepository extends TrekRepository<MailIngestCandidates> {
private db() {
return this.kysely<CandidatesKyselyDB>();
}
async insertCandidate(row: MailIngestCandidateInsert): Promise<number> {
const inserted = await this.db()
.insertInto('mail_ingest_candidates')
.values({
message_id: row.messageId,
user_id: row.userId,
position: row.position,
item_json: row.itemJson,
source: row.source,
checks_json: row.checksJson,
uncertain_fields: row.uncertainFields,
match_json: row.matchJson,
suggested_trip_id: row.suggestedTripId,
dedupe_key: row.dedupeKey,
content_hash: row.contentHash,
resolution: row.resolution,
reason: row.reason,
created_at: row.createdAt,
resolved_trip_id: row.resolvedTripId ?? null,
created_ids_json: row.createdIdsJson ?? null,
resolved_at: row.resolvedAt ?? null,
undo_until: row.undoUntil ?? null,
})
.returning('id')
.executeTakeFirstOrThrow();
return inserted.id;
}
async findById(id: number): Promise<MailIngestCandidateRow | null> {
const row = await this.db()
.selectFrom('mail_ingest_candidates')
.selectAll()
.where('id', '=', id)
.executeTakeFirst();
return row ?? null;
}
/** The entries read from one mail, in the order the mail listed them. */
async listForMessage(messageId: number): Promise<MailIngestCandidateRow[]> {
return this.db()
.selectFrom('mail_ingest_candidates')
.selectAll()
.where('message_id', '=', messageId)
.orderBy('position', 'asc')
.orderBy('id', 'asc')
.execute();
}
/**
* Decides an entry, if it is still in one of the `from` states: one
* conditional update, so of two decisions at once only the first lands.
* With `held`, only while the entry still holds that trip and those
* created ids: a move keeps the resolution and changes only these.
*/
async resolve(
id: number,
from: readonly string[],
patch: MailIngestResolutionPatch,
held?: { tripId: number; createdIdsJson: string | null },
): Promise<boolean> {
let query = this.db()
.updateTable('mail_ingest_candidates')
.set({
resolution: patch.resolution,
reason: patch.reason,
resolved_trip_id: patch.resolvedTripId,
created_ids_json: patch.createdIdsJson,
resolved_by: patch.resolvedBy,
resolved_at: patch.resolvedAt,
undo_until: patch.undoUntil,
})
.where('id', '=', id)
.where('resolution', 'in', [...from]);
if (held) {
query = query.where('resolved_trip_id', '=', held.tripId);
query =
held.createdIdsJson === null
? query.where('created_ids_json', 'is', null)
: query.where('created_ids_json', '=', held.createdIdsJson);
}
const result = await query.executeTakeFirst();
return Number(result.numUpdatedRows) > 0;
}
/** Records the documents attached after the booking was written, or why that failed. */
async setAttachments(id: number, createdIdsJson: string, attachError: string | null): Promise<void> {
await this.db()
.updateTable('mail_ingest_candidates')
.set({ created_ids_json: createdIdsJson, attach_error: attachError })
.where('id', '=', id)
.execute();
}
/** The person's entries waiting in the inbox. */
async countPending(userId: number): Promise<number> {
const row = await this.db()
.selectFrom('mail_ingest_candidates')
.select((eb) => eb.fn.countAll<number>().as('n'))
.where('user_id', '=', userId)
.where('resolution', '=', 'pending')
.executeTakeFirstOrThrow();
return Number(row.n);
}
/**
* The person's entries, waiting (`open`) or decided, newest first; with
* `beforeId` only those older than it, so a page follows on from the last.
*/
async listForUser(
userId: number,
open: boolean,
beforeId: number | null,
limit: number,
): Promise<MailIngestCandidateRow[]> {
let query = this.db()
.selectFrom('mail_ingest_candidates')
.selectAll()
.where('user_id', '=', userId)
.where('resolution', open ? '=' : '<>', 'pending');
if (beforeId !== null) query = query.where('id', '<', beforeId);
return query.orderBy('id', 'desc').limit(limit).execute();
}
/** The entries made since `since`, counted by what became of them. */
async tallyResolutionsSince(since: DbTimestamp): Promise<Array<{ resolution: string; n: number }>> {
const rows = await this.db()
.selectFrom('mail_ingest_candidates')
.select((eb) => ['resolution', eb.fn.countAll<number>().as('n')])
.where('created_at', '>=', since)
.groupBy('resolution')
.execute();
return rows.map((row) => ({ resolution: row.resolution, n: Number(row.n) }));
}
/** How many entries wait for each person who has any, the most first; who they are is left out. */
async pendingPerUser(): Promise<number[]> {
const rows = await this.db()
.selectFrom('mail_ingest_candidates')
.select((eb) => ['user_id', eb.fn.countAll<number>().as('n')])
.where('resolution', '=', 'pending')
.groupBy('user_id')
.execute();
return rows.map((row) => Number(row.n)).sort((a, b) => b - a);
}
/** Whether a booking of this content went into the trip from a mail and was undone: never added again on its own. */
async wasUndoneInTrip(tripId: number, contentHash: string): Promise<boolean> {
const row = await this.db()
.selectFrom('mail_ingest_candidates')
.select('id')
.where('resolved_trip_id', '=', tripId)
.where('content_hash', '=', contentHash)
.where('resolution', '=', 'undone')
.executeTakeFirst();
return row !== undefined;
}
/** Retention: deletes the entries decided before `cutoff`; answers how many went. */
async deleteResolvedBefore(cutoff: DbTimestamp): Promise<number> {
const result = await this.db()
.deleteFrom('mail_ingest_candidates')
.where('resolution', '!=', 'pending')
.where('resolved_at', '<', cutoff)
.executeTakeFirst();
return Number(result.numDeletedRows);
}
// ── What the import reads of the trips ────────────────────────────────────
/**
* The trips the person owns or is a member of, not archived, that end on or
* after `endCutoff` or have no end date, most recent start first. Whether
* the person may add bookings to each is the service's check.
*/
async listOpenTrips(userId: number, endCutoff: string, limit: number): Promise<MailIngestTripRow[]> {
return this.db()
.selectFrom('trips as t')
.select(['t.id', 't.title', 't.start_date', 't.end_date', 't.user_id', 't.currency'])
.where((eb) =>
eb.or([
eb('t.user_id', '=', userId),
eb.exists(
eb
.selectFrom('trip_members as m')
.select('m.id')
.whereRef('m.trip_id', '=', 't.id')
.where('m.user_id', '=', userId),
),
]),
)
.where((eb) => eb.or([eb('t.is_archived', 'is', null), eb('t.is_archived', '=', 0)]))
.where((eb) => eb.or([eb('t.end_date', 'is', null), eb('t.end_date', '>=', endCutoff)]))
.orderBy('t.start_date', 'desc')
.orderBy('t.id', 'desc')
.limit(limit)
.execute();
}
/** One trip the person owns or is a member of and that is not archived, whatever its dates; null otherwise. */
async findOpenTrip(userId: number, tripId: number): Promise<MailIngestTripRow | null> {
const row = await this.db()
.selectFrom('trips as t')
.select(['t.id', 't.title', 't.start_date', 't.end_date', 't.user_id', 't.currency'])
.where('t.id', '=', tripId)
.where((eb) =>
eb.or([
eb('t.user_id', '=', userId),
eb.exists(
eb
.selectFrom('trip_members as m')
.select('m.id')
.whereRef('m.trip_id', '=', 't.id')
.where('m.user_id', '=', userId),
),
]),
)
.where((eb) => eb.or([eb('t.is_archived', 'is', null), eb('t.is_archived', '=', 0)]))
.executeTakeFirst();
return row ?? null;
}
/**
* The trips among `tripIds` the person owns or is a member of, archived or
* not: a suggestion names only a trip its reader can see.
*/
async listTripRefs(userId: number, tripIds: readonly number[]): Promise<MailIngestTripRefRow[]> {
if (tripIds.length === 0) return [];
return this.db()
.selectFrom('trips as t')
.select(['t.id', 't.title', 't.start_date', 't.end_date'])
.where('t.id', 'in', [...tripIds])
.where((eb) =>
eb.or([
eb('t.user_id', '=', userId),
eb.exists(
eb
.selectFrom('trip_members as m')
.select('m.id')
.whereRef('m.trip_id', '=', 't.id')
.where('m.user_id', '=', userId),
),
]),
)
.execute();
}
/** The dated days of these trips, by date. */
async listDatedDays(tripIds: readonly number[]): Promise<Array<{ id: number; trip_id: number; date: string }>> {
if (tripIds.length === 0) return [];
const rows = await this.db()
.selectFrom('days')
.select(['id', 'trip_id', 'date'])
.where('trip_id', 'in', [...tripIds])
.where('date', 'is not', null)
.orderBy('trip_id', 'asc')
.orderBy('date', 'asc')
.execute();
return rows.flatMap((row) => (row.date === null ? [] : [{ id: row.id, trip_id: row.trip_id, date: row.date }]));
}
/** The places of these trips that have a position, oldest first. */
async listPlacesWithPosition(tripIds: readonly number[]): Promise<MailIngestTripPlaceRow[]> {
if (tripIds.length === 0) return [];
const rows = await this.db()
.selectFrom('places')
.select(['trip_id', 'name', 'address', 'lat', 'lng'])
.where('trip_id', 'in', [...tripIds])
.where('lat', 'is not', null)
.where('lng', 'is not', null)
.orderBy('id', 'asc')
.limit(PLACES_PER_LOOKUP)
.execute();
return rows.flatMap((row) =>
row.lat === null || row.lng === null ? [] : [{ ...row, lat: row.lat, lng: row.lng }],
);
}
async findPerson(userId: number): Promise<MailIngestPersonRow | null> {
const row = await this.db()
.selectFrom('users')
.select(['id', 'username', 'email', 'role'])
.where('id', '=', userId)
.executeTakeFirst();
return row ?? null;
}
/** Whether the trip holds a booking an import stored under one of these sources and this key. */
async tripHasExternal(tripId: number, sources: readonly string[], externalId: string): Promise<boolean> {
const row = await this.db()
.selectFrom('reservations')
.select('id')
.where('trip_id', '=', tripId)
.where('external_source', 'in', [...sources])
.where('external_id', '=', externalId)
.executeTakeFirst();
return row !== undefined;
}
/**
* Whether the trip holds a booking that looks like this one: the same
* reference, or the same type starting in the same window.
*/
async tripHasSimilar(tripId: number, probe: MailIngestSimilarProbe): Promise<boolean> {
const { type, startFrom, startTo, confirmation } = probe;
const row = await this.db()
.selectFrom('reservations')
.select('id')
.where('trip_id', '=', tripId)
.where((eb) => {
const either: Expression<SqlBool>[] = [];
if (confirmation) either.push(eb('confirmation_number', '=', confirmation));
if (startFrom && startTo) {
either.push(
eb.and([
eb('type', '=', type),
eb('reservation_time', '>=', startFrom),
eb('reservation_time', '<=', startTo),
]),
);
}
// An empty list reads as false: a probe with neither names nothing.
return eb.or(either);
})
.executeTakeFirst();
return row !== undefined;
}
/** Whether a booking, a day plan entry or a stay still names the place. */
async placeInUse(placeId: number): Promise<boolean> {
const [booking, planned, stay] = await Promise.all([
this.db().selectFrom('reservations').select('id').where('place_id', '=', placeId).executeTakeFirst(),
this.db().selectFrom('day_assignments').select('id').where('place_id', '=', placeId).executeTakeFirst(),
this.db().selectFrom('day_accommodations').select('id').where('place_id', '=', placeId).executeTakeFirst(),
]);
return booking !== undefined || planned !== undefined || stay !== undefined;
}
/** How many payers the costs name: a cost someone settled with moves balances. */
async countPayers(budgetItemIds: readonly number[]): Promise<number> {
if (budgetItemIds.length === 0) return 0;
const row = await this.db()
.selectFrom('budget_item_payers')
.select((eb) => eb.fn.countAll<number>().as('n'))
.where('budget_item_id', 'in', [...budgetItemIds])
.executeTakeFirstOrThrow();
return Number(row.n);
}
}
@@ -0,0 +1,136 @@
import type { MailIngestCursor } from '../entities/MailIngestCursor.entity';
import type { DB } from '../kysely/db';
import type { DbTimestamp } from '../types';
import type { AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
/**
* What reads mail: an IMAP box, the TREK Cloud relay, or the processing
* pipeline itself; and the pause notice, whose good run is the pause it
* announced.
*/
type MailIngestCursorTransport = 'imap' | 'cloud' | 'pipeline' | 'notice';
/** One `mail_ingest_cursor` row as stored. */
interface MailIngestCursorRow {
id: number;
transport: string;
mailbox: string;
uid_validity: number | null;
last_uid: number | null;
last_ok_at: string | null;
last_error: string | null;
lease_owner: string | null;
lease_until: string | null;
}
const _mailIngestCursorRowKeys: AssertRowKeys<MailIngestCursorRow, MailIngestCursor> = true;
/** A reader's position after a good run; an IMAP reader names its box's uid validity and the last uid it took. */
interface MailIngestCursorPosition {
uidValidity?: number | null;
lastUid?: number | null;
}
type CursorKyselyDB = Pick<DB, 'mail_ingest_cursor'>;
/**
* `mail_ingest_cursor`: where each reader stands and who holds it. The lease
* is one conditional update, so of two processes on one database exactly one
* wins; a lease whose holder died runs out and the next run takes it.
*/
export class MailIngestCursorRepository extends TrekRepository<MailIngestCursor> {
private db() {
return this.kysely<CursorKyselyDB>();
}
/**
* Takes the reader's lease until `until` when it is free, run out at `now`,
* or already this owner's. The row is created on first use.
*
* @txIndependent the row is provisioned idempotently first; the lease itself
* is the one conditional update that decides the race.
*/
async acquireLease(
transport: MailIngestCursorTransport,
mailbox: string,
owner: string,
until: DbTimestamp,
now: DbTimestamp,
): Promise<boolean> {
await this.db()
.insertInto('mail_ingest_cursor')
.values({ transport, mailbox })
.onConflict((oc) => oc.columns(['transport', 'mailbox']).doNothing())
.execute();
const result = await this.db()
.updateTable('mail_ingest_cursor')
.set({ lease_owner: owner, lease_until: until })
.where('transport', '=', transport)
.where('mailbox', '=', mailbox)
.where((eb) => eb.or([eb('lease_until', 'is', null), eb('lease_until', '<', now), eb('lease_owner', '=', owner)]))
.executeTakeFirst();
return Number(result.numUpdatedRows) > 0;
}
/** Gives the lease back, if this owner still holds it. */
async releaseLease(transport: MailIngestCursorTransport, mailbox: string, owner: string): Promise<void> {
await this.db()
.updateTable('mail_ingest_cursor')
.set({ lease_owner: null, lease_until: null })
.where('transport', '=', transport)
.where('mailbox', '=', mailbox)
.where('lease_owner', '=', owner)
.execute();
}
/** A good run: its time, the reader's position where it has one, and no error. */
async recordOk(
transport: MailIngestCursorTransport,
mailbox: string,
at: DbTimestamp,
position: MailIngestCursorPosition = {},
): Promise<void> {
await this.db()
.updateTable('mail_ingest_cursor')
.set({
last_ok_at: at,
last_error: null,
...(position.uidValidity !== undefined && { uid_validity: position.uidValidity }),
...(position.lastUid !== undefined && { last_uid: position.lastUid }),
})
.where('transport', '=', transport)
.where('mailbox', '=', mailbox)
.execute();
}
/** Forgets the last good run, as if the reader had never run. */
async forgetOk(transport: MailIngestCursorTransport, mailbox: string): Promise<void> {
await this.db()
.updateTable('mail_ingest_cursor')
.set({ last_ok_at: null })
.where('transport', '=', transport)
.where('mailbox', '=', mailbox)
.execute();
}
/** A failed run, for the admin's status card; the position stays where the last good run left it. */
async recordError(transport: MailIngestCursorTransport, mailbox: string, error: string): Promise<void> {
await this.db()
.updateTable('mail_ingest_cursor')
.set({ last_error: error.slice(0, 500) })
.where('transport', '=', transport)
.where('mailbox', '=', mailbox)
.execute();
}
async findCursor(transport: MailIngestCursorTransport, mailbox: string): Promise<MailIngestCursorRow | null> {
const row = await this.db()
.selectFrom('mail_ingest_cursor')
.selectAll()
.where('transport', '=', transport)
.where('mailbox', '=', mailbox)
.executeTakeFirst();
return row ?? null;
}
}
@@ -0,0 +1,321 @@
import type { MailIngestMessages } from '../entities/MailIngestMessages.entity';
import type { DB } from '../kysely/db';
import type { DbTimestamp } from '../types';
import type { AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
/** One `mail_ingest_messages` row as stored, the encrypted mail included. */
export interface MailIngestMessageRow {
id: number;
transport: string;
message_id_hdr: string | null;
dedupe_hash: string;
address_id: number | null;
user_id: number;
trip_id: number | null;
from_addr: string | null;
from_verified: number;
auth_results: string | null;
subject: string | null;
received_at: string;
size: number;
raw_eml_enc: string | null;
raw_purged_at: string | null;
status: string;
reason: string | null;
hints: string | null;
attachments: string | null;
forwarding_code: string | null;
attempts: number;
next_attempt_at: string;
lease_until: string | null;
ai_used: number;
processed_at: string | null;
}
const _mailIngestMessageRowKeys: AssertRowKeys<MailIngestMessageRow, MailIngestMessages> = true;
/** A mail as the inbox lists it: everything but the stored mail and its sender's signature data. */
export type MailIngestMessageHead = Omit<MailIngestMessageRow, 'raw_eml_enc' | 'auth_results'>;
/** A mail as a transport hands it in, before anything has read it. */
interface MailIngestMessageInsert {
transport: string;
messageIdHdr: string | null;
dedupeHash: string;
addressId: number;
userId: number;
tripId: number | null;
size: number;
rawEnc: string;
receivedAt: DbTimestamp;
}
/** What the pipeline made of a mail, written once it is done with it. */
export interface MailIngestMessageOutcome {
status: 'processed' | 'discarded' | 'failed';
reason: string | null;
subject: string | null;
fromAddr: string | null;
fromVerified: boolean;
authResults: string | null;
hints: string | null;
attachments: string | null;
forwardingCode: string | null;
aiUsed: boolean;
processedAt: DbTimestamp;
}
type MessagesKyselyDB = Pick<DB, 'mail_ingest_messages' | 'mail_ingest_candidates'>;
/**
* `mail_ingest_messages`: every forwarded mail, from its arrival to its
* purge. A transport only ever inserts (idempotently, by `dedupe_hash`); the
* pipeline claims due rows one by one with a conditional update, so a mail is
* read by one run at a time, and a run that died lets its claim run out.
*/
export class MailIngestMessagesRepository extends TrekRepository<MailIngestMessages> {
private db() {
return this.kysely<MessagesKyselyDB>();
}
/** Stores a new mail, queued for now; null when the same mail is in already. */
async insertIfNew(row: MailIngestMessageInsert): Promise<number | null> {
const inserted = await this.db()
.insertInto('mail_ingest_messages')
.values({
transport: row.transport,
message_id_hdr: row.messageIdHdr,
dedupe_hash: row.dedupeHash,
address_id: row.addressId,
user_id: row.userId,
trip_id: row.tripId,
size: row.size,
raw_eml_enc: row.rawEnc,
received_at: row.receivedAt,
next_attempt_at: row.receivedAt,
})
.onConflict((oc) => oc.column('dedupe_hash').doNothing())
.returning('id')
.executeTakeFirst();
return inserted?.id ?? null;
}
async findIdByDedupeHash(dedupeHash: string): Promise<number | null> {
const row = await this.db()
.selectFrom('mail_ingest_messages')
.select('id')
.where('dedupe_hash', '=', dedupeHash)
.executeTakeFirst();
return row?.id ?? null;
}
async findById(id: number): Promise<MailIngestMessageRow | null> {
const row = await this.db().selectFrom('mail_ingest_messages').selectAll().where('id', '=', id).executeTakeFirst();
return row ?? null;
}
/** These mails without their content, for the inbox rows that name them. */
async listHeads(ids: readonly number[]): Promise<MailIngestMessageHead[]> {
if (ids.length === 0) return [];
return this.db()
.selectFrom('mail_ingest_messages')
.select([
'id',
'transport',
'message_id_hdr',
'dedupe_hash',
'address_id',
'user_id',
'trip_id',
'from_addr',
'from_verified',
'subject',
'received_at',
'size',
'raw_purged_at',
'status',
'reason',
'hints',
'attachments',
'forwarding_code',
'attempts',
'next_attempt_at',
'lease_until',
'ai_used',
'processed_at',
])
.where('id', 'in', [...ids])
.execute();
}
/** The mails that came in since `since`, counted by status and reason, for the admin's status card. */
async tallySince(since: DbTimestamp): Promise<Array<{ status: string; reason: string | null; n: number }>> {
const rows = await this.db()
.selectFrom('mail_ingest_messages')
.select((eb) => ['status', 'reason', eb.fn.countAll<number>().as('n')])
.where('received_at', '>=', since)
.groupBy(['status', 'reason'])
.execute();
return rows.map((row) => ({ status: row.status, reason: row.reason, n: Number(row.n) }));
}
/** How many mails, of everyone, an AI read since `since`. */
async countAllAiReadSince(since: DbTimestamp): Promise<number> {
const row = await this.db()
.selectFrom('mail_ingest_messages')
.select((eb) => eb.fn.countAll<number>().as('n'))
.where('ai_used', '=', 1)
.where('received_at', '>=', since)
.executeTakeFirstOrThrow();
return Number(row.n);
}
/** How many mails came in on the address since `since`, for its daily limit. */
async countForAddressSince(addressId: number, since: DbTimestamp): Promise<number> {
const row = await this.db()
.selectFrom('mail_ingest_messages')
.select((eb) => eb.fn.countAll<number>().as('n'))
.where('address_id', '=', addressId)
.where('received_at', '>=', since)
.executeTakeFirstOrThrow();
return Number(row.n);
}
/** How many of the person's mails an AI read since `since`, for their daily limit. */
async countAiReadSince(userId: number, since: DbTimestamp): Promise<number> {
const row = await this.db()
.selectFrom('mail_ingest_messages')
.select((eb) => eb.fn.countAll<number>().as('n'))
.where('user_id', '=', userId)
.where('ai_used', '=', 1)
.where('received_at', '>=', since)
.executeTakeFirstOrThrow();
return Number(row.n);
}
/**
* Claims up to `limit` mails that are due: queued and past their next try,
* or claimed by a run whose lease ran out. Each claim is one conditional
* update, so a mail another run took in between is skipped, never read twice.
*
* @txIndependent one claim per mail on purpose: each is complete on its own,
* and a mail claimed stays claimed even when the next one is taken first by
* another run.
*/
async claimDue(now: DbTimestamp, leaseUntil: DbTimestamp, limit: number): Promise<number[]> {
const due = await this.db()
.selectFrom('mail_ingest_messages')
.select('id')
.where((eb) =>
eb.or([
eb.and([eb('status', '=', 'queued'), eb('next_attempt_at', '<=', now)]),
eb.and([eb('status', '=', 'processing'), eb('lease_until', '<', now)]),
]),
)
.orderBy('next_attempt_at', 'asc')
.orderBy('id', 'asc')
.limit(limit)
.execute();
const won = await Promise.all(due.map(({ id }) => this.claim(id, now, leaseUntil)));
return due.flatMap(({ id }, i) => (won[i] ? [id] : []));
}
/** One mail's claim: it is still queued, or its last claim ran out at `now`. */
private async claim(id: number, now: DbTimestamp, leaseUntil: DbTimestamp): Promise<boolean> {
const result = await this.db()
.updateTable('mail_ingest_messages')
.set((eb) => ({ status: 'processing', lease_until: leaseUntil, attempts: eb('attempts', '+', 1) }))
.where('id', '=', id)
.where((eb) =>
eb.or([eb('status', '=', 'queued'), eb.and([eb('status', '=', 'processing'), eb('lease_until', '<', now)])]),
)
.executeTakeFirst();
return Number(result.numUpdatedRows) > 0;
}
/** Writes what the pipeline made of the mail and lets go of its claim. */
async finish(id: number, outcome: MailIngestMessageOutcome): Promise<void> {
await this.db()
.updateTable('mail_ingest_messages')
.set({
status: outcome.status,
reason: outcome.reason,
subject: outcome.subject,
from_addr: outcome.fromAddr,
from_verified: outcome.fromVerified ? 1 : 0,
auth_results: outcome.authResults,
hints: outcome.hints,
attachments: outcome.attachments,
forwarding_code: outcome.forwardingCode,
ai_used: outcome.aiUsed ? 1 : 0,
processed_at: outcome.processedAt,
lease_until: null,
})
.where('id', '=', id)
.execute();
}
/** Puts a mail whose reading failed back in the queue, to be tried again at `nextAttemptAt`. */
async retryLater(id: number, nextAttemptAt: DbTimestamp): Promise<void> {
await this.db()
.updateTable('mail_ingest_messages')
.set({ status: 'queued', next_attempt_at: nextAttemptAt, lease_until: null })
.where('id', '=', id)
.execute();
}
/**
* Drops the stored mail of every message that no longer needs it: one that
* came in before `hardCutoff`, or one done before `doneCutoff` that has no
* entry left waiting in the inbox (the ways out read the mail). Answers how
* many were purged.
*/
async purgeRaw(doneCutoff: DbTimestamp, hardCutoff: DbTimestamp, at: DbTimestamp): Promise<number> {
const result = await this.db()
.updateTable('mail_ingest_messages')
.set({ raw_eml_enc: null, raw_purged_at: at })
.where('raw_eml_enc', 'is not', null)
.where((eb) =>
eb.or([
eb('received_at', '<', hardCutoff),
eb.and([
eb('status', 'in', ['processed', 'discarded', 'failed']),
eb('processed_at', '<', doneCutoff),
eb.not(
eb.exists(
eb
.selectFrom('mail_ingest_candidates as c')
.select('c.id')
.whereRef('c.message_id', '=', 'mail_ingest_messages.id')
.where('c.resolution', '=', 'pending'),
),
),
]),
]),
)
.executeTakeFirst();
return Number(result.numUpdatedRows);
}
/** Deletes the mails that came in before `cutoff` and have no inbox entry left; answers how many went. */
async deleteSettledBefore(cutoff: DbTimestamp): Promise<number> {
const result = await this.db()
.deleteFrom('mail_ingest_messages')
.where('received_at', '<', cutoff)
.where('status', '!=', 'queued')
.where('status', '!=', 'processing')
.where((eb) =>
eb.not(
eb.exists(
eb
.selectFrom('mail_ingest_candidates as c')
.select('c.id')
.whereRef('c.message_id', '=', 'mail_ingest_messages.id'),
),
),
)
.executeTakeFirst();
return Number(result.numDeletedRows);
}
}
@@ -0,0 +1,50 @@
import type { MailIngestPrefs } from '../entities/MailIngestPrefs.entity';
import type { DB } from '../kysely/db';
import type { AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
/** One `mail_ingest_prefs` row as stored: 0/1 flags. */
interface MailIngestPrefsRow {
id: number;
user_id: number;
enabled: number;
ai_enabled: number;
auto_add: number;
}
const _mailIngestPrefsRowKeys: AssertRowKeys<MailIngestPrefsRow, MailIngestPrefs> = true;
/** The switches a write names; the others keep their value. */
export type MailIngestPrefsPatch = Partial<Pick<MailIngestPrefsRow, 'enabled' | 'ai_enabled' | 'auto_add'>>;
type PrefsKyselyDB = Pick<DB, 'mail_ingest_prefs'>;
/**
* `mail_ingest_prefs`: a person's switches for the mail import. A person
* without a row has every switch on, the column defaults, so only a change
* writes one.
*/
export class MailIngestPrefsRepository extends TrekRepository<MailIngestPrefs> {
private db() {
return this.kysely<PrefsKyselyDB>();
}
async findForUser(userId: number): Promise<MailIngestPrefsRow | null> {
const row = await this.db()
.selectFrom('mail_ingest_prefs')
.selectAll()
.where('user_id', '=', userId)
.executeTakeFirst();
return row ?? null;
}
/** Writes the named switches, creating the person's row with the defaults for the rest. */
async upsertForUser(userId: number, patch: MailIngestPrefsPatch): Promise<void> {
if (Object.keys(patch).length === 0) return;
await this.db()
.insertInto('mail_ingest_prefs')
.values({ user_id: userId, ...patch })
.onConflict((oc) => oc.column('user_id').doUpdateSet(patch))
.execute();
}
}
@@ -407,6 +407,12 @@ export class PackingItemsRepository extends TrekRepository<PackingItems> {
await this.nativeUpdate({ id }, { is_private, ...data, updated_at: currentTimestamp(platform) });
}
/** `removeContributor` on a Common item's owner (#3098): the item stays on the list, nobody's in particular. */
async clearOwner(id: number): Promise<void> {
const platform = this.getEntityManager().getPlatform();
await this.nativeUpdate({ id }, { owner: null, updated_at: currentTimestamp(platform) });
}
/** PK16 (`setItemSharing`'s replace-all) — `DELETE FROM packing_item_recipients WHERE item_id = ?`. */
async deleteRecipientsForItem(item_id: number): Promise<void> {
await this.db().deleteFrom('packing_item_recipients').where('item_id', '=', item_id).execute();
@@ -19,6 +19,11 @@ interface PlaceCountryRow {
country_code: string | null;
}
/** A place of a started trip, with the trip's last day (its end, or its start when it has none) for ordering by recency. */
export interface StartedTripPlaceCountryRow extends PlaceCountryRow {
trip_last_date: string | null;
}
type PlaceRegionsKyselyDB = Pick<DB, 'place_regions' | 'places' | 'trips' | 'trip_members'>;
/**
@@ -192,22 +197,32 @@ export class PlaceRegionsRepository extends TrekRepository<PlaceRegions> {
/**
* AT44 (`getTravelStats`) — `SELECT DISTINCT p.id, p.lat, p.lng, p.address,
* pr.country_code FROM places p JOIN trips t ON p.trip_id = t.id LEFT JOIN
* pr.country_code, COALESCE(t.end_date, t.start_date) AS trip_last_date
* FROM places p JOIN trips t ON p.trip_id = t.id LEFT JOIN
* trip_members tm ON t.id = tm.trip_id LEFT JOIN place_regions pr ON
* pr.place_id = p.id WHERE (t.user_id = ? OR tm.user_id = ?) AND
* COALESCE(t.start_date, t.end_date) IS NOT NULL AND COALESCE(t.start_date,
* t.end_date) <= ? ORDER BY p.id` — "only started trips count" (#1048).
* Every place comes back, a place without a cached region with a null
* country (#2875). `today` (UTC) is resolved by the caller once
* (`todayUtc()`) and bound here.
* (`todayUtc()`) and bound here. A place sits on one trip, so the trip's
* last day adds no row to the DISTINCT; the dashboard orders the countries
* by it (#2648).
*/
async listStartedTripPlaceCountriesForUser(userId: number, today: string): Promise<PlaceCountryRow[]> {
async listStartedTripPlaceCountriesForUser(userId: number, today: string): Promise<StartedTripPlaceCountryRow[]> {
return await this.db()
.selectFrom('places as p')
.innerJoin('trips as t', 't.id', 'p.trip_id')
.leftJoin('trip_members as tm', 'tm.trip_id', 't.id')
.leftJoin('place_regions as pr', 'pr.place_id', 'p.id')
.select(['p.id', 'p.lat', 'p.lng', 'p.address', 'pr.country_code'])
.select((eb) => [
'p.id',
'p.lat',
'p.lng',
'p.address',
'pr.country_code',
eb.fn.coalesce('t.end_date', 't.start_date').as('trip_last_date'),
])
.distinct()
.where((eb) => eb.or([eb('t.user_id', '=', userId), eb('tm.user_id', '=', userId)]))
.where((eb) => eb(eb.fn.coalesce('t.start_date', 't.end_date'), 'is not', null))
@@ -201,9 +201,12 @@ export class ReservationEndpointsRepository extends TrekRepository<ReservationEn
* = ?) AND e.role IN ('from', 'to') AND COALESCE(t.start_date, t.end_date)
* IS NOT NULL AND COALESCE(t.start_date, t.end_date) <= date('now') AND
* ${TRAVELER_OWNS}`. `today` resolved by the caller once (`todayUtc()`),
* the `TripsRepository.activeTrip`/`lastStartedTrip` precedent.
* the `TripsRepository.activeTrip`/`lastStartedTrip` precedent. The row also
* carries `COALESCE(t.end_date, t.start_date) AS trip_last_date`, by which
* the dashboard orders the countries (#2648); an endpoint sits on one trip,
* so it adds no row to the DISTINCT.
*/
async listOwnedEndpointsForUser(userId: number, today: string): Promise<TravelerOwnedEndpointRow[]> {
async listOwnedEndpointsForUser(userId: number, today: string): Promise<TravelerOwnedEndpointWithTripDateRow[]> {
const rows = await this.kysely<TravelerOwnedEndpointsWithTripsKyselyDB>()
.selectFrom('reservation_endpoints as e')
.innerJoin('reservations as r', 'r.id', 'e.reservation_id')
@@ -228,6 +231,7 @@ export class ReservationEndpointsRepository extends TrekRepository<ReservationEn
.else(eb.fn.coalesce('r.reservation_time', 'r.reservation_end_time'))
.end()
.as('fallback_time'),
eb.fn.coalesce('t.end_date', 't.start_date').as('trip_last_date'),
])
.distinct()
.where((eb) => eb.or([eb('t.user_id', '=', userId), eb('tm.user_id', '=', userId)]))
@@ -236,7 +240,7 @@ export class ReservationEndpointsRepository extends TrekRepository<ReservationEn
.where((eb) => eb(eb.fn.coalesce('t.start_date', 't.end_date'), '<=', today))
.where((eb) => travelerOwnsExpr(eb, userId))
.execute();
return rows as TravelerOwnedEndpointRow[];
return rows as TravelerOwnedEndpointWithTripDateRow[];
}
/**
@@ -318,6 +322,11 @@ export interface TravelerOwnedEndpointRow {
fallback_time: string | null;
}
/** AT45's projection: AT6's, plus the last day of the trip the endpoint is on. */
export interface TravelerOwnedEndpointWithTripDateRow extends TravelerOwnedEndpointRow {
trip_last_date: string | null;
}
/** {@link ReservationEndpointsRepository.listOwnedEndpointsForTrips}'s `reservation_endpoints`/`reservations`/`reservation_travelers` tables (`r` aliased for `travelerOwnsExpr`, R7). */
type TravelerOwnedEndpointsKyselyDB = ReservationTravelersOwnsKyselyDB &
Pick<DB, 'reservation_endpoints' | 'reservations'>;
@@ -6,8 +6,10 @@ import { concatKysely, startsWithIsoDateKysely, substringKysely } from '../diale
import { accommodationIdMatches } from './_shared/reservation-accommodation';
import { publicReservationExpr, publicStayExists, type ReservationVisibilityKyselyDB } from './_shared/reservation-visibility';
import type { DayAssignmentRow } from './day-assignment-rows';
import type { ReservationAllColumnsRow, ReservationJoinKyselyDB, ReservationJoinRow } from './reservation-rows';
import { TrekRepository } from './_shared/trek-repository';
import { passContextQuery, type PassContextDB } from './_shared/reservation-pass-context';
import { originColumnValues, type ReservationOriginColumns } from './_shared/reservation-origin-columns';
import { idByExternalQuery, joinedReservationQuery, type ReservationJoinDB } from './_shared/reservation-joined-query';
import type { DB } from '../kysely/db';
import { ROADTRIP_RESERVATION_TYPES } from '@trek/shared';
import type {
@@ -19,11 +21,12 @@ import type {
PublicApiUnplannedPlaceRow,
PublicApiUnscheduledReservationRow,
} from './reservation-public-api-rows';
import type { ReservationAllColumnsRow, ReservationJoinRow } from './reservation-rows';
// The row types moved to their own modules; re-exported so callers keep one import path.
// The reservation row shapes live in their own module; re-exported so callers keep one import path.
export type { ReservationAllColumnsRow, ReservationJoinRow } from './reservation-rows';
// The public API row types moved to their own module; re-exported so callers keep one import path.
export type {
ReservationAllColumnsRow,
ReservationJoinRow,
PublicApiAccommodationRow,
PublicApiScheduledReservationRow,
PublicApiUnplannedPlaceRow,
@@ -135,8 +138,8 @@ type CalendarReservationKyselyDB = Pick<DB, 'reservations' | 'places' | 'day_acc
/**
* CL4 (`CalendarService.buildTripCalendar`'s assignment read, for every dated
* day at once) — `SELECT da.*, p.name as place_name, p.address as
* place_address, p.lat as place_lat, p.lng as place_lng, p.duration_minutes
* as place_duration_minutes, COALESCE(da.assignment_time, p.place_time) as
* place_address, p.lat as place_lat, p.lng as place_lng, COALESCE(da.stay_minutes,
* p.duration_minutes) as place_duration_minutes, COALESCE(da.assignment_time, p.place_time) as
* effective_time, COALESCE(da.assignment_end_time, p.end_time) as
* effective_end_time FROM
* day_assignments da JOIN places p ON da.place_id = p.id WHERE da.day_id IN
@@ -342,33 +345,15 @@ export interface SharePublicAccommodationRow {
type SharePublicAccommodationKyselyDB = ReservationVisibilityKyselyDB & Pick<DB, 'day_accommodations' | 'places'>;
/**
* Plan 3h Task 4 (`AirportsService.backfillFlightEndpoints`, AIR1) —
* additive. The `reservations`/`reservation_endpoints` tables the
* `NOT EXISTS` guard reads.
*/
/** `AirportsService.backfillFlightEndpoints` (AIR1): the tables its `NOT EXISTS` guard reads. */
type FlightsMissingEndpointsKyselyDB = Pick<DB, 'reservations' | 'reservation_endpoints'>;
export class ReservationsRepository extends TrekRepository<Reservations> {
// For its Wallet pass (_shared/reservation-pass-context.ts).
findPassContext(id: number, tripId: number) { return passContextQuery(this.kysely<PassContextDB>(), id, tripId); }
private joinedQuery() {
const platform = this.getEntityManager().getPlatform();
return this.kysely<ReservationJoinKyselyDB>()
.selectFrom('reservations as r')
.leftJoin('days as d', 'd.id', 'r.day_id')
.leftJoin('places as p', 'p.id', 'r.place_id')
.leftJoin('day_accommodations as ap', (join) =>
join.on((eb) => accommodationIdMatches(platform, eb, 'r.accommodation_id', 'ap.id')),
)
.leftJoin('places as acc_p', 'acc_p.id', 'ap.place_id')
.selectAll('r')
.select([
'd.day_number as day_number',
'p.name as place_name',
'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',
]);
return joinedReservationQuery(this.kysely<ReservationJoinDB>(), this.getEntityManager().getPlatform());
}
/**
@@ -386,10 +371,15 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
/**
* RR1 (`ReservationsReadService.getReservationWithJoins`) — the SAME
* projection for one reservation, no `ORDER BY` (a single row).
* projection for one reservation, no `ORDER BY` (a single row), and only
* when it belongs to `trip_id`: every caller holds the trip it checked, so a
* booking id from another trip reads as missing rather than leaking its row.
*/
async findWithJoins(id: number | string): Promise<ReservationJoinRow | undefined> {
const row = await this.joinedQuery().where('r.id', '=', id as number).executeTakeFirst();
async findWithJoins(id: number | string, trip_id: number | string): Promise<ReservationJoinRow | undefined> {
const row = await this.joinedQuery()
.where('r.id', '=', id as number)
.where('r.trip_id', '=', trip_id as number)
.executeTakeFirst();
return row as ReservationJoinRow | undefined;
}
@@ -447,12 +437,16 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
* (trip_id, day_id, end_day_id, place_id, assignment_id, title,
* reservation_time, reservation_end_time, location, confirmation_number,
* notes, url, status, type, accommodation_id, metadata, needs_review)
* VALUES (?×17)`. `sync_enabled`/`ingest_state`/`day_plan_position`
* deliberately NOT named, so the column's own DB-level `DEFAULT` applies
* (`sync_enabled INTEGER DEFAULT 1`, `Migration20200101021800_…`;
* `ingest_state` `.default('live')`) — the caller has already resolved
* every value (the `|| null` coercions, `resolvedOrNull`, the numeric
* `accommodation_id` stringified for the TEXT column, R2).
* VALUES (?×17)`. `ingest_state`/`day_plan_position` deliberately NOT
* named, so the column's own DB-level `DEFAULT` applies (`ingest_state`
* `.default('live')`) — the caller has already resolved every value (the
* `|| null` coercions, `resolvedOrNull`, the numeric `accommodation_id`
* stringified for the TEXT column, R2).
*
* `external_source`/`external_id`/`sync_enabled` are named only when the
* caller passes them: an imported booking records where it came from, every
* other write leaves them to the column defaults as before (`sync_enabled
* INTEGER DEFAULT 1`, `Migration20200101021800_…`).
*/
async insertReservation(input: {
trip_id: number;
@@ -472,7 +466,7 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
accommodation_id: string | null;
metadata: string | null;
needs_review: number;
}): Promise<number> {
} & ReservationOriginColumns): Promise<number> {
return await this.insert({
trip: input.trip_id,
day: input.day_id,
@@ -491,9 +485,15 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
accommodation_id: input.accommodation_id,
metadata: input.metadata,
needs_review: input.needs_review,
...originColumnValues(input),
});
}
/** The booking an import already wrote into this trip under the same origin (_shared/reservation-joined-query.ts). */
findIdByExternal(trip_id: number, external_source: string, external_id: string): Promise<number | undefined> {
return idByExternalQuery(this.kysely<DB>(), trip_id, external_source, external_id);
}
/**
* RS41 (`ReservationsService.updateInTx`) — the 16-column `UPDATE
* reservations SET … WHERE id = ?`. The `PlacesRepository.updatePlace`/PL11
@@ -909,7 +909,7 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
'p.address as place_address',
'p.lat as place_lat',
'p.lng as place_lng',
'p.duration_minutes as place_duration_minutes',
eb.fn.coalesce('da.stay_minutes', 'p.duration_minutes').as('place_duration_minutes'),
eb.fn.coalesce('da.assignment_time', 'p.place_time').as('effective_time'),
eb.fn.coalesce('da.assignment_end_time', 'p.end_time').as('effective_end_time'),
])
+44 -16
View File
@@ -4,13 +4,14 @@ import { findOwnedByUser, listForOwner } from './_shared/owned-lookup';
import { toRow, type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
/** A `tags` row as the API emits it. */
/** A `tags` row as the API emits it. `trip_id` is null on a personal tag and names the trip on one of its own. */
export interface TagRow {
id: number;
user_id: number;
name: string;
color: string | null;
created_at: string | null;
trip_id: number | null;
}
const _tagRowKeys: AssertRowKeys<TagRow, Tags> = true;
@@ -45,6 +46,9 @@ export interface TagForPlaceRow {
*/
type PlaceTagsKyselyDB = Pick<DB, 'place_tags'>;
/** `tags` alone, for the reads that name their columns. */
type TagsKyselyDB = Pick<DB, 'tags'>;
/**
* `place_tags` joined to `places` for TP46 (`trips.service.ts::copy`'s
* place-tags read). The `trip_id` the caller passes stays `number | string`
@@ -97,11 +101,18 @@ export class TagsRepository extends TrekRepository<Tags> {
* `id` and the `defaultRaw` `created_at` the same way a legacy
* INSERT-then-reselect pair did.
*/
async createTag(input: { user_id: number; name: string; color: string }): Promise<TagRow> {
async createTag(input: {
user_id: number;
name: string;
color: string | null;
/** The trip the tag is for; left out, it is `user_id`'s personal one. */
trip_id?: number;
}): Promise<TagRow> {
const id = await this.insert({
user: input.user_id,
name: input.name,
color: input.color,
...(input.trip_id === undefined ? {} : { trip: input.trip_id }),
});
const inserted = await this.findOne({ id });
if (!inserted) {
@@ -193,22 +204,39 @@ export class TagsRepository extends TrekRepository<Tags> {
// ---------------------------------------------------------------------------
/**
* PL2 (`PlacesService.tagsOnTrip`) — `` SELECT id, user_id FROM tags WHERE
* id IN (${…}) ``, the ownership half of tag scoping: the caller
* (`tagsOnTrip`) intersects these rows' `user_id` against the trip's
* roster, and an id belonging to nobody on the roster drops silently.
* `$in` for the dynamic list (rule 17b).
* PL2 (`PlacesService.tagsOnTrip`) — `` SELECT id, user_id, trip_id FROM tags
* WHERE id IN (${…}) ``, what decides whether a trip may put a tag on a
* place: the caller keeps a trip's own tag for that trip and a personal one
* (`trip_id` null) while its `user_id` is on the roster, and every other id
* drops silently.
*/
async findByIds(ids: number[]): Promise<{ id: number; user_id: number }[]> {
async findByIds(ids: number[]): Promise<{ id: number; user_id: number; trip_id: number | null }[]> {
if (ids.length === 0) return [];
// `t.user` (unaliased, not separately joined) resolves to the physical
// `user_id` column and comes back keyed as `user_id` on the raw driver
// row — `TripsRepository.findAccessible`'s `.select(['t.id', 't.user',
// 't.currency'])` establishes the same shape.
return this.qb('t')
.select(['t.id', 't.user'])
.where({ id: { $in: ids } })
.execute<{ id: number; user_id: number }[]>('all', false);
return await this.kysely<TagsKyselyDB>()
.selectFrom('tags')
.select(['id', 'user_id', 'trip_id'])
.where('id', 'in', ids)
.execute();
}
// ---------------------------------------------------------------------------
// A trip's own tags (`trip_id` set): one list for everybody on the trip.
// ---------------------------------------------------------------------------
/** `SELECT * FROM tags WHERE trip_id = ? ORDER BY name ASC`: the trip's own tags, whoever created them. */
async listByTrip(tripId: number): Promise<TagRow[]> {
const tags = await this.find({ trip: tripId }, { orderBy: { name: 'asc' } });
return tags.map((tag) => toRow(tag) as TagRow);
}
/**
* `SELECT * FROM tags WHERE id = ? AND trip_id = ?`: one tag of the trip, or
* null for a personal tag and for another trip's, so a write scoped to a trip
* cannot reach either.
*/
async findByIdAndTrip(id: number, tripId: number): Promise<TagRow | null> {
const tag = await this.findOne({ id, trip: tripId });
return tag ? (toRow(tag) as TagRow) : null;
}
// ---------------------------------------------------------------------------
@@ -142,6 +142,46 @@ export class TrekPhotosRepository extends TrekRepository<TrekPhotos> {
return changed > 0;
}
/**
* Puts in the capture time and place a provider has just confirmed for this
* very photo, over whatever the row held (#3019: Synology rows that carry the
* next photo's). Unlike patchCaptureMetadata it replaces: the coordinates
* become the confirmed pair or none at all, while a missing time leaves the
* stored one, since every library photo has one and none is no correction.
* Answers whether the row changed.
*/
async replaceCaptureMetadata(
id: number,
taken_at: string | null,
lat: number | null,
lng: number | null,
): Promise<boolean> {
const row = await this.findOne({ id });
if (!row) return false;
const next = { taken_at: taken_at ?? row.taken_at ?? null, lat, lng };
if (next.taken_at === (row.taken_at ?? null) && next.lat === (row.lat ?? null) && next.lng === (row.lng ?? null)) {
return false;
}
await this.nativeUpdate({ id }, next);
return true;
}
/**
* One provider's photos after `afterId`, oldest first, `limit` at a time, with
* the user whose library each lives in: the pages a provider-wide repair walks.
*/
async listByProviderAfter(
provider: string,
afterId: number,
limit: number,
): Promise<Array<{ id: number; owner_id: number }>> {
const rows = await this.find(
{ provider, id: { $gt: afterId }, owner: { $ne: null }, asset_id: { $ne: null } },
{ orderBy: { id: 'asc' }, limit },
);
return rows.flatMap((row) => (row.owner ? [{ id: row.id, owner_id: row.owner.id }] : []));
}
/** PH11 — `DELETE FROM trek_photos WHERE id = ? AND provider != 'local'`; local photos are never auto-reclaimed here. */
async deleteNonLocal(id: number): Promise<number> {
return await this.nativeDelete({ id, provider: { $ne: 'local' } });
+11 -13
View File
@@ -1,5 +1,5 @@
import { QueryFlag } from '@mikro-orm/core';
import type { Trips } from '../entities/Trips.entity';
import type { TTripsCostsMode, Trips } from '../entities/Trips.entity';
import { coalesceParam, currentTimestamp, ilike, nowDateOffset } from '../dialect/sql-functions';
import type { AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
@@ -36,6 +36,7 @@ export interface TripRawRow {
created_at: string | null;
updated_at: string | null;
reminder_sent_for: string | null;
costs_mode: TTripsCostsMode;
}
const _tripRawRowKeys: AssertRowKeys<TripRawRow, Trips> = true;
@@ -544,7 +545,7 @@ export class TripsRepository extends TrekRepository<Trips> {
/**
* TP37 (`trips.service.ts::copy`'s INSERT) — `INSERT INTO trips (user_id,
* title, description, start_date, end_date, currency, cover_image,
* is_archived, reminder_days) VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?)`. A
* is_archived, reminder_days, costs_mode) VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, ?)`. A
* DIFFERENT column set from `insertTrip` (TP18, `create`'s own INSERT):
* this one also writes `cover_image` (verbatim from the source row) and
* `is_archived` as a hard-coded literal `0` — a copy is never archived,
@@ -563,6 +564,7 @@ export class TripsRepository extends TrekRepository<Trips> {
currency: string | null;
cover_image: string | null;
reminder_days: number;
costs_mode: TTripsCostsMode;
}): Promise<number> {
return await this.insert({
user: input.user_id,
@@ -574,13 +576,14 @@ export class TripsRepository extends TrekRepository<Trips> {
cover_image: input.cover_image,
is_archived: 0,
reminder_days: input.reminder_days,
costs_mode: input.costs_mode,
});
}
/**
* TP25 (`trips.service.ts::updateTrip`) — `UPDATE trips SET title=?,
* description=?, start_date=?, end_date=?, currency=?, is_archived=?,
* cover_image=?, reminder_days=?, updated_at=CURRENT_TIMESTAMP WHERE
* cover_image=?, reminder_days=?, costs_mode=?, updated_at=CURRENT_TIMESTAMP WHERE
* id=?`. The `||`/`!== undefined` pre-image fallbacks are the SERVICE's
* own (R5/§18.6 — this write stays OUTSIDE the days-regeneration
* transaction, unchanged); this takes the final, already-decided values
@@ -597,16 +600,11 @@ export class TripsRepository extends TrekRepository<Trips> {
* here would tempt a caller to paper over that with its own `?? 0`, the
* exact regression the review found.
*/
async updateTripRow(id: number, data: {
title: string;
description: string | null;
start_date: string | null;
end_date: string | null;
currency: string;
is_archived: number | null;
cover_image: string | null;
reminder_days: number;
}): Promise<void> {
async updateTripRow(
id: number,
data: Pick<TripRawRow, 'title' | 'description' | 'start_date' | 'end_date' | 'is_archived' | 'cover_image' | 'costs_mode'>
& { currency: string; reminder_days: number },
): Promise<void> {
const platform = this.getEntityManager().getPlatform();
await this.nativeUpdate({ id }, { ...data, updated_at: currentTimestamp(platform) });
}
@@ -817,9 +817,9 @@ export class UsersRepository extends TrekRepository<Users> {
/**
* `UPDATE users SET oidc_sub = ?, oidc_issuer = ? WHERE id = ?` (O5, the
* email-matched/unlinked/verified-email branch; O6, the provider-switch
* branch — identical statement, two call sites, no `updated_at`).
* branch; with nulls the admin's "Remove SSO link", #3065; no `updated_at`).
*/
async linkOidcIdentity(id: number, sub: string, issuer: string): Promise<void> {
async linkOidcIdentity(id: number, sub: string | null, issuer: string | null): Promise<void> {
await this.nativeUpdate({ id }, { oidc_sub: sub, oidc_issuer: issuer });
}
@@ -0,0 +1,62 @@
import type { DB } from '../../kysely/db';
import { accommodationIdMatches } from './reservation-accommodation';
import type { Platform } from '@mikro-orm/core';
import type { Kysely } from 'kysely';
/** The tables the joined booking projection reads. */
export type ReservationJoinDB = Pick<DB, 'reservations' | 'days' | 'places' | 'day_accommodations'>;
/**
* A booking with its day number, its place's name and its stay's place and
* times: the projection `ReservationsRepository.listForTrip` and
* `findWithJoins` narrow with their own `WHERE`. Kept out of the repository
* file, which is at its size baseline. `accommodation_id` is TEXT and `ap.id`
* INTEGER, so the stay is matched through accommodationIdMatches: SQLite
* coerces the bare comparison, Postgres refuses it.
*/
export function joinedReservationQuery(kysely: Kysely<ReservationJoinDB>, platform: Platform) {
return kysely
.selectFrom('reservations as r')
.leftJoin('days as d', 'd.id', 'r.day_id')
.leftJoin('places as p', 'p.id', 'r.place_id')
.leftJoin('day_accommodations as ap', (join) =>
join.on((eb) => accommodationIdMatches(platform, eb, 'r.accommodation_id', 'ap.id')),
)
.leftJoin('places as acc_p', 'acc_p.id', 'ap.place_id')
.selectAll('r')
.select([
'd.day_number as day_number',
'p.name as place_name',
'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',
'ap.check_in as accommodation_check_in',
'ap.check_in_end as accommodation_check_in_end',
'ap.check_out as accommodation_check_out',
]);
}
/**
* The booking an import already wrote into this trip under the same origin,
* or undefined: what `idx_reservations_external (external_source,
* external_id, trip_id)` would refuse, read before the write so a repeat
* import is reported instead of failing on the unique index
* (`ReservationsRepository.findIdByExternal`).
*/
export async function idByExternalQuery(
kysely: Kysely<Pick<DB, 'reservations'>>,
trip_id: number,
external_source: string,
external_id: string,
): Promise<number | undefined> {
const row = await kysely
.selectFrom('reservations')
.select(['id'])
.where('trip_id', '=', trip_id)
.where('external_source', '=', external_source)
.where('external_id', '=', external_id)
.executeTakeFirst();
return row?.id;
}
@@ -0,0 +1,21 @@
/**
* Where an imported booking came from and its key there, as the reservations
* table stores them. Named on an insert only when the caller passes them: an
* imported booking records its origin, every other write leaves the columns to
* their defaults (`sync_enabled INTEGER DEFAULT 1`). Kept out of
* Reservations.repository.ts, which is at its size baseline.
*/
export interface ReservationOriginColumns {
external_source?: string;
external_id?: string;
sync_enabled?: number;
}
/** The origin columns an insert names: only those the caller set. */
export function originColumnValues(input: ReservationOriginColumns): ReservationOriginColumns {
return {
...(input.external_source !== undefined && { external_source: input.external_source }),
...(input.external_id !== undefined && { external_id: input.external_id }),
...(input.sync_enabled !== undefined && { sync_enabled: input.sync_enabled }),
};
}
@@ -0,0 +1,46 @@
import type { DB } from '../../kysely/db';
import type { Kysely } from 'kysely';
/** The tables `passContextQuery` reads. */
export type PassContextDB = Pick<DB, 'reservations' | 'trips' | 'places' | 'day_accommodations'>;
/** What a booking's Wallet pass needs beyond the booking: where it is, and the trip's name. */
export interface ReservationPassContext {
trip_title: string | null;
place_lat: number | null;
place_lng: number | null;
place_name: string | null;
}
/**
* The trip's title and the place a booking is at (its own place, else its
* stay's), for its Apple Wallet pass (`ReservationsRepository.findPassContext`).
* Scoped to the trip, so a booking of another trip reads as none. Kept out of
* the repository file, which is at its size baseline.
*/
export async function passContextQuery(
kysely: Kysely<PassContextDB>,
id: number,
trip_id: number,
): Promise<ReservationPassContext | undefined> {
const row = await kysely
.selectFrom('reservations as r')
.innerJoin('trips as t', 't.id', 'r.trip_id')
.leftJoin('places as p', 'p.id', 'r.place_id')
// accommodation_id is TEXT; compared as a number so Postgres takes it as well as SQLite ("14" and "14.0" alike).
.leftJoin('day_accommodations as ap', (join) =>
join.on((eb) => eb(eb.cast<number>('r.accommodation_id', 'numeric'), '=', eb.ref('ap.id'))),
)
.leftJoin('places as acc_p', 'acc_p.id', 'ap.place_id')
.where('r.id', '=', id)
.where('r.trip_id', '=', trip_id)
.select([
't.title as trip_title',
(eb) => eb.fn.coalesce('p.lat', 'acc_p.lat').as('place_lat'),
(eb) => eb.fn.coalesce('p.lng', 'acc_p.lng').as('place_lng'),
(eb) => eb.fn.coalesce('p.name', 'acc_p.name').as('place_name'),
])
.executeTakeFirst();
return row as ReservationPassContext | undefined;
}
@@ -115,6 +115,8 @@ export interface DayAssignmentRow {
route_excluded: number;
/** MDT-02: the stage of a multi-day tour the day holds, by its starting stop's key; null for anything else. */
tour_stage_key: string | null;
/** #3092: how long the drive stands at this visit; null reads the place's `duration_minutes`. */
stay_minutes: number | null;
}
const _dayAssignmentRowKeys: AssertRowKeys<DayAssignmentRow, DayAssignments> = true;
@@ -172,6 +174,7 @@ export interface RoadtripVisitRow {
lng: number | null;
time: string | null;
end_time: string | null;
/** The visit's own stay where it has one (#3092), else the place's. */
duration_minutes: number | null;
end_day: number;
leg_transport_mode: string | null;
+9 -17
View File
@@ -1,10 +1,7 @@
/**
* The rows `ReservationsRepository` answers with for a whole reservation, and
* the Kysely tables its joined read binds: what a reservation is read as, kept
* apart from the statements that read it. The repository re-exports the row
* types, so callers keep importing them from there.
* The row shapes ReservationsRepository reads: every column of a reservation,
* and the joined projection the trip list and the single reads share.
*/
import type { DB } from '../kysely/db';
/** `SELECT *` — every scalar column of `Reservations`, RS35's shape. */
export interface ReservationAllColumnsRow {
@@ -41,12 +38,13 @@ export interface ReservationAllColumnsRow {
* RS18/RR1's shared joined projection — `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
* accommodation_start_day_id, ap.end_day_id as accommodation_end_day_id,
* ap.check_in/check_in_end/check_out as accommodation_check_in/_check_in_end/_check_out 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`. The service
* folds `accommodation_id` (`Math.trunc(Number(x))`), `day_positions`,
* `endpoints` and `travelers` on afterward.
* `endpoints` and `travelers` on afterward (unchanged from the legacy split).
*/
export interface ReservationJoinRow extends ReservationAllColumnsRow {
day_number: number | null;
@@ -55,14 +53,8 @@ export interface ReservationJoinRow extends ReservationAllColumnsRow {
accommodation_name: string | null;
accommodation_start_day_id: number | null;
accommodation_end_day_id: number | null;
/** The stay's own times, which a hotel booking's card falls back to. */
accommodation_check_in: string | null;
accommodation_check_in_end: string | null;
accommodation_check_out: string | null;
}
/**
* The tables the RS18/RR1 join binds (`ReservationsRepository.joinedQuery`).
* `reservations.accommodation_id` is a TEXT column with no foreign key to
* `day_accommodations`, so the QueryBuilder's relation joins cannot express
* `LEFT JOIN day_accommodations ap ON r.accommodation_id = ap.id`; the join
* is written in Kysely, as `DayAssignmentsRepository.effectiveStart` and
* `TripsRepository.tripSelectQuery` do.
*/
export type ReservationJoinKyselyDB = Pick<DB, 'reservations' | 'days' | 'places' | 'day_accommodations'>;