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
@@ -31,6 +31,7 @@ export class DayAssignments {
accommodation_id?: number | null;
route_excluded: number & Opt = 0;
tour_stage_key?: string | null;
stay_minutes?: number | null;
assignment_participants_collection = new Collection<AssignmentParticipants>(this);
file_links_collection = new Collection<FileLinks>(this);
reservations_collection = new Collection<Reservations>(this);
@@ -70,6 +71,7 @@ export const DayAssignmentsSchema = defineEntity({
accommodation_id: p.integer().nullable().index('idx_day_assignments_accommodation_id'),
route_excluded: p.integer().default(0),
tour_stage_key: p.text().nullable(),
stay_minutes: p.integer().nullable(),
assignment_participants_collection: () => p.oneToMany(AssignmentParticipants).mappedBy('assignment').hidden(),
file_links_collection: () => p.oneToMany(FileLinks).mappedBy('assignment').hidden(),
reservations_collection: () => p.oneToMany(Reservations).mappedBy('assignment').hidden(),
@@ -0,0 +1,65 @@
import { EntityRepositoryType, type Opt, PrimaryKeyProp, defineEntity, p } from '@mikro-orm/core';
import { FlightLiveStatesRepository } from '../repositories/FlightLiveStates.repository';
import { DbTimestampType } from '../types';
export class FlightLiveStates {
[EntityRepositoryType]?: FlightLiveStatesRepository;
[PrimaryKeyProp]?: ['callsign', 'service_date', 'origin', 'destination'];
callsign!: string;
service_date!: string;
origin!: string;
destination!: string;
phase: string & Opt = 'scheduled';
departed_at?: string | null;
landed_at?: string | 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?: string | null;
last_seen_at?: string | null;
fetched_at?: string | null;
next_poll_at?: string | null;
fail_count: number & Opt = 0;
departed_notified: number & Opt = 0;
landed_notified: number & Opt = 0;
delay_notified: number & Opt = 0;
}
export const FlightLiveStatesSchema = defineEntity({
class: FlightLiveStates,
repository: () => FlightLiveStatesRepository,
properties: {
callsign: p.text().primary(),
service_date: p.text().primary(),
origin: p.text().primary(),
destination: p.text().primary(),
phase: p.text().default('scheduled'),
departed_at: p.type(DbTimestampType).nullable(),
landed_at: p.type(DbTimestampType).nullable(),
lat: p.double().nullable(),
lng: p.double().nullable(),
altitude_ft: p.double().nullable(),
ground_speed_kt: p.double().nullable(),
track_deg: p.double().nullable(),
vertical_rate_fpm: p.double().nullable(),
on_ground: p.integer().nullable(),
registration: p.text().nullable(),
aircraft_type: p.text().nullable(),
source: p.text().nullable(),
first_seen_at: p.type(DbTimestampType).nullable(),
last_seen_at: p.type(DbTimestampType).nullable(),
fetched_at: p.type(DbTimestampType).nullable(),
next_poll_at: p.type(DbTimestampType).nullable(),
fail_count: p.integer().default(0),
departed_notified: p.integer().default(0),
landed_notified: p.integer().default(0),
delay_notified: p.integer().default(0),
},
});
@@ -0,0 +1,43 @@
import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { MailIngestAddressesRepository } from '../repositories/MailIngestAddresses.repository';
import { DbTimestampType } from '../types';
import { MailIngestMessages } from './MailIngestMessages.entity';
import { Trips } from './Trips.entity';
import { Users } from './Users.entity';
export class MailIngestAddresses {
[EntityRepositoryType]?: MailIngestAddressesRepository;
id!: number & Opt;
token_hash!: string;
token_enc!: string;
user!: Ref<Users>;
user_id!: number;
trip?: Ref<Trips> | null;
trip_id?: number | null;
created_at!: string & Opt;
revoked_at?: string | null;
last_used_at?: string | null;
mail_ingest_messages_collection = new Collection<MailIngestMessages>(this);
}
export const MailIngestAddressesSchema = defineEntity({
class: MailIngestAddresses,
repository: () => MailIngestAddressesRepository,
indexes: [
{ name: 'idx_mail_ingest_addresses_user', properties: ['user_id', 'trip_id'] },
],
uniques: [{ properties: ['token_hash'] }],
properties: {
id: p.integer().primary(),
token_hash: p.text(),
token_enc: p.text(),
user: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden(),
user_id: p.integer().persist(false),
trip: () => p.manyToOne(Trips).ref().deleteRule('cascade').nullable().hidden().index('idx_mail_ingest_addresses_trip'),
trip_id: p.integer().nullable().persist(false).index('idx_mail_ingest_addresses_trip'),
created_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
revoked_at: p.type(DbTimestampType).nullable(),
last_used_at: p.type(DbTimestampType).nullable(),
mail_ingest_messages_collection: () => p.oneToMany(MailIngestMessages).mappedBy('address').hidden(),
},
});
@@ -0,0 +1,81 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { MailIngestCandidatesRepository } from '../repositories/MailIngestCandidates.repository';
import { DbTimestampType } from '../types';
import { MailIngestMessages } from './MailIngestMessages.entity';
import { Trips } from './Trips.entity';
import { Users } from './Users.entity';
export class MailIngestCandidates {
[EntityRepositoryType]?: MailIngestCandidatesRepository;
id!: number & Opt;
message!: Ref<MailIngestMessages>;
message_id!: number;
user!: Ref<Users>;
user_id!: number;
position: number & Opt = 0;
item_json?: string | null;
source?: string | null;
checks_json?: string | null;
uncertain_fields?: string | null;
match_json?: string | null;
suggestedTrip?: Ref<Trips> | null;
suggested_trip_id?: number | null;
dedupe_key?: string | null;
content_hash?: string | null;
resolution: string & Opt = 'pending';
reason?: string | null;
resolvedTrip?: Ref<Trips> | 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 & Opt;
}
export const MailIngestCandidatesSchema = defineEntity({
class: MailIngestCandidates,
repository: () => MailIngestCandidatesRepository,
indexes: [
{
name: 'idx_mail_ingest_candidates_resolved',
properties: ['resolved_trip_id', 'content_hash'],
},
{
name: 'idx_mail_ingest_candidates_user',
properties: ['user_id', 'resolution'],
},
{
name: 'idx_mail_ingest_candidates_message',
properties: ['message_id', 'position'],
},
],
properties: {
id: p.integer().primary(),
message: () => p.manyToOne(MailIngestMessages).ref().deleteRule('cascade').hidden(),
message_id: p.integer().persist(false),
user: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden(),
user_id: p.integer().persist(false),
position: p.integer().default(0),
item_json: p.text().nullable(),
source: p.text().nullable(),
checks_json: p.text().nullable(),
uncertain_fields: p.text().nullable(),
match_json: p.text().nullable(),
suggestedTrip: () => p.manyToOne(Trips).ref().nullable().hidden().index('idx_mail_ingest_candidates_suggested'),
suggested_trip_id: p.integer().nullable().persist(false).index('idx_mail_ingest_candidates_suggested'),
dedupe_key: p.text().nullable(),
content_hash: p.text().nullable(),
resolution: p.text().default('pending'),
reason: p.text().nullable(),
resolvedTrip: () => p.manyToOne(Trips).ref().nullable().hidden(),
resolved_trip_id: p.integer().nullable().persist(false),
created_ids_json: p.text().nullable(),
attach_error: p.text().nullable(),
resolved_by: p.integer().nullable(),
resolved_at: p.type(DbTimestampType).nullable(),
undo_until: p.type(DbTimestampType).nullable(),
created_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
},
});
@@ -0,0 +1,33 @@
import { EntityRepositoryType, type Opt, defineEntity, p } from '@mikro-orm/core';
import { MailIngestCursorRepository } from '../repositories/MailIngestCursor.repository';
import { DbTimestampType } from '../types';
export class MailIngestCursor {
[EntityRepositoryType]?: MailIngestCursorRepository;
id!: number & Opt;
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;
}
export const MailIngestCursorSchema = defineEntity({
class: MailIngestCursor,
repository: () => MailIngestCursorRepository,
uniques: [{ properties: ['transport', 'mailbox'] }],
properties: {
id: p.integer().primary(),
transport: p.text(),
mailbox: p.text(),
uid_validity: p.integer().nullable(),
last_uid: p.integer().nullable(),
last_ok_at: p.type(DbTimestampType).nullable(),
last_error: p.text().nullable(),
lease_owner: p.text().nullable(),
lease_until: p.type(DbTimestampType).nullable(),
},
});
@@ -0,0 +1,91 @@
import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { MailIngestMessagesRepository } from '../repositories/MailIngestMessages.repository';
import { DbTimestampType } from '../types';
import { MailIngestAddresses } from './MailIngestAddresses.entity';
import { MailIngestCandidates } from './MailIngestCandidates.entity';
import { Trips } from './Trips.entity';
import { Users } from './Users.entity';
export class MailIngestMessages {
[EntityRepositoryType]?: MailIngestMessagesRepository;
id!: number & Opt;
transport!: string;
message_id_hdr?: string | null;
dedupe_hash!: string;
address?: Ref<MailIngestAddresses> | null;
address_id?: number | null;
user!: Ref<Users>;
user_id!: number;
trip?: Ref<Trips> | null;
trip_id?: number | null;
from_addr?: string | null;
from_verified: number & Opt = 0;
auth_results?: string | null;
subject?: string | null;
received_at!: string & Opt;
size!: number;
raw_eml_enc?: string | null;
raw_purged_at?: string | null;
status: string & Opt = 'queued';
reason?: string | null;
hints?: string | null;
attachments?: string | null;
forwarding_code?: string | null;
attempts: number & Opt = 0;
next_attempt_at!: string & Opt;
lease_until?: string | null;
ai_used: number & Opt = 0;
processed_at?: string | null;
mail_ingest_candidates_collection = new Collection<MailIngestCandidates>(this);
}
export const MailIngestMessagesSchema = defineEntity({
class: MailIngestMessages,
repository: () => MailIngestMessagesRepository,
indexes: [
{
name: 'idx_mail_ingest_messages_address',
properties: ['address_id', 'received_at'],
},
{
name: 'idx_mail_ingest_messages_user',
properties: ['user_id', 'received_at'],
},
{
name: 'idx_mail_ingest_messages_due',
properties: ['status', 'next_attempt_at'],
},
],
uniques: [{ properties: ['dedupe_hash'] }],
properties: {
id: p.integer().primary(),
transport: p.text(),
message_id_hdr: p.text().nullable(),
dedupe_hash: p.text(),
address: () => p.manyToOne(MailIngestAddresses).ref().nullable().hidden(),
address_id: p.integer().nullable().persist(false),
user: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden(),
user_id: p.integer().persist(false),
trip: () => p.manyToOne(Trips).ref().nullable().hidden().index('idx_mail_ingest_messages_trip'),
trip_id: p.integer().nullable().persist(false).index('idx_mail_ingest_messages_trip'),
from_addr: p.text().nullable(),
from_verified: p.integer().default(0),
auth_results: p.text().nullable(),
subject: p.text().nullable(),
received_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
size: p.integer(),
raw_eml_enc: p.text().nullable(),
raw_purged_at: p.type(DbTimestampType).nullable(),
status: p.text().default('queued'),
reason: p.text().nullable(),
hints: p.text().nullable(),
attachments: p.text().nullable(),
forwarding_code: p.text().nullable(),
attempts: p.integer().default(0),
next_attempt_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
lease_until: p.type(DbTimestampType).nullable(),
ai_used: p.integer().default(0),
processed_at: p.type(DbTimestampType).nullable(),
mail_ingest_candidates_collection: () => p.oneToMany(MailIngestCandidates).mappedBy('message').hidden(),
},
});
@@ -0,0 +1,27 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { MailIngestPrefsRepository } from '../repositories/MailIngestPrefs.repository';
import { Users } from './Users.entity';
export class MailIngestPrefs {
[EntityRepositoryType]?: MailIngestPrefsRepository;
id!: number & Opt;
user!: Ref<Users>;
user_id!: number;
enabled: number & Opt = 1;
ai_enabled: number & Opt = 1;
auto_add: number & Opt = 1;
}
export const MailIngestPrefsSchema = defineEntity({
class: MailIngestPrefs,
repository: () => MailIngestPrefsRepository,
uniques: [{ properties: ['user'] }],
properties: {
id: p.integer().primary(),
user: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden(),
user_id: p.integer().persist(false),
enabled: p.integer().default(1),
ai_enabled: p.integer().default(1),
auto_add: p.integer().default(1),
},
});
+5
View File
@@ -3,6 +3,7 @@ import { TagsRepository } from '../repositories/Tags.repository';
import { DbTimestampType } from '../types';
import { CollectionPlaces } from './CollectionPlaces.entity';
import { Places } from './Places.entity';
import { Trips } from './Trips.entity';
import { Users } from './Users.entity';
export class Tags {
@@ -13,6 +14,8 @@ export class Tags {
name!: string;
color?: string | null = '#10b981';
created_at?: string | null;
trip?: Ref<Trips> | null;
trip_id?: number | null;
collection_place_tags_inverse = new Collection<CollectionPlaces>(this);
place_tags_inverse = new Collection<Places>(this);
}
@@ -27,6 +30,8 @@ export const TagsSchema = defineEntity({
name: p.text(),
color: p.text().nullable(),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
trip: () => p.manyToOne(Trips).ref().deleteRule('cascade').nullable().hidden().index('idx_tags_trip_id'),
trip_id: p.integer().nullable().persist(false).index('idx_tags_trip_id'),
collection_place_tags_inverse: () => p.manyToMany(CollectionPlaces).mappedBy('collection_place_tags').hidden(),
place_tags_inverse: () => p.manyToMany(Places).mappedBy('place_tags').hidden(),
},
+23
View File
@@ -19,6 +19,9 @@ import { DocumentSyncItems } from './DocumentSyncItems.entity';
import { InviteTokens } from './InviteTokens.entity';
import { JourneyEntries } from './JourneyEntries.entity';
import { JourneyTrips } from './JourneyTrips.entity';
import { MailIngestAddresses } from './MailIngestAddresses.entity';
import { MailIngestCandidates } from './MailIngestCandidates.entity';
import { MailIngestMessages } from './MailIngestMessages.entity';
import { PackingBags } from './PackingBags.entity';
import { PackingCategoryAssignees } from './PackingCategoryAssignees.entity';
import { PackingItems } from './PackingItems.entity';
@@ -28,6 +31,7 @@ import { Reservations } from './Reservations.entity';
import { RoadtripDayBoundaries } from './RoadtripDayBoundaries.entity';
import { RoadtripPreferences } from './RoadtripPreferences.entity';
import { ShareTokens } from './ShareTokens.entity';
import { Tags } from './Tags.entity';
import { TodoCategoryAssignees } from './TodoCategoryAssignees.entity';
import { TodoItems } from './TodoItems.entity';
import { TourDrafts } from './TourDrafts.entity';
@@ -58,6 +62,7 @@ export class Trips {
created_at?: string | null;
updated_at?: string | null;
reminder_sent_for?: string | null;
costs_mode: TTripsCostsMode & Opt = TripsCostsMode.SPLIT;
assistant_attachments_collection = new Collection<AssistantAttachments>(this);
assistant_threads_collection = new Collection<AssistantThreads>(this);
budget_category_order_collection = new Collection<BudgetCategoryOrder>(this);
@@ -76,6 +81,10 @@ export class Trips {
invite_tokens_collection = new Collection<InviteTokens>(this);
journey_entries_collection = new Collection<JourneyEntries>(this);
journey_trips_collection = new Collection<JourneyTrips>(this);
mail_ingest_addresses_collection = new Collection<MailIngestAddresses>(this);
mail_ingest_candidates_collection = new Collection<MailIngestCandidates>(this);
mail_ingest_candidates_collection1 = new Collection<MailIngestCandidates>(this);
mail_ingest_messages_collection = new Collection<MailIngestMessages>(this);
packing_bags_collection = new Collection<PackingBags>(this);
packing_category_assignees_collection = new Collection<PackingCategoryAssignees>(this);
packing_items_collection = new Collection<PackingItems>(this);
@@ -85,6 +94,7 @@ export class Trips {
roadtrip_day_boundaries_collection = new Collection<RoadtripDayBoundaries>(this);
roadtrip_preferences_collection = new Collection<RoadtripPreferences>(this);
share_tokens_collection = new Collection<ShareTokens>(this);
tags_collection = new Collection<Tags>(this);
todo_category_assignees_collection = new Collection<TodoCategoryAssignees>(this);
todo_items_collection = new Collection<TodoItems>(this);
tour_drafts_collection = new Collection<TourDrafts>(this);
@@ -98,6 +108,13 @@ export class Trips {
trip_photos_collection = new Collection<TripPhotos>(this);
}
export const TripsCostsMode = {
SPLIT: 'split',
TOTALS: 'totals',
} as const;
export type TTripsCostsMode = (typeof TripsCostsMode)[keyof typeof TripsCostsMode];
export const TripsSchema = defineEntity({
class: Trips,
repository: () => TripsRepository,
@@ -124,6 +141,7 @@ export const TripsSchema = defineEntity({
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`).index('idx_trips_created_at'),
updated_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
reminder_sent_for: p.text().nullable(),
costs_mode: p.enum(() => TripsCostsMode).default('split'),
assistant_attachments_collection: () => p.oneToMany(AssistantAttachments).mappedBy('trip').hidden(),
assistant_threads_collection: () => p.oneToMany(AssistantThreads).mappedBy('trip').hidden(),
budget_category_order_collection: () => p.oneToMany(BudgetCategoryOrder).mappedBy('trip').hidden(),
@@ -142,6 +160,10 @@ export const TripsSchema = defineEntity({
invite_tokens_collection: () => p.oneToMany(InviteTokens).mappedBy('trip').hidden(),
journey_entries_collection: () => p.oneToMany(JourneyEntries).mappedBy('sourceTrip').hidden(),
journey_trips_collection: () => p.oneToMany(JourneyTrips).mappedBy('trip').hidden(),
mail_ingest_addresses_collection: () => p.oneToMany(MailIngestAddresses).mappedBy('trip').hidden(),
mail_ingest_candidates_collection: () => p.oneToMany(MailIngestCandidates).mappedBy('suggestedTrip').hidden(),
mail_ingest_candidates_collection1: () => p.oneToMany(MailIngestCandidates).mappedBy('resolvedTrip').hidden(),
mail_ingest_messages_collection: () => p.oneToMany(MailIngestMessages).mappedBy('trip').hidden(),
packing_bags_collection: () => p.oneToMany(PackingBags).mappedBy('trip').hidden(),
packing_category_assignees_collection: () => p.oneToMany(PackingCategoryAssignees).mappedBy('trip').hidden(),
packing_items_collection: () => p.oneToMany(PackingItems).mappedBy('trip').hidden(),
@@ -151,6 +173,7 @@ export const TripsSchema = defineEntity({
roadtrip_day_boundaries_collection: () => p.oneToMany(RoadtripDayBoundaries).mappedBy('trip').hidden(),
roadtrip_preferences_collection: () => p.oneToMany(RoadtripPreferences).mappedBy('trip').hidden(),
share_tokens_collection: () => p.oneToMany(ShareTokens).mappedBy('trip').hidden(),
tags_collection: () => p.oneToMany(Tags).mappedBy('trip').hidden(),
todo_category_assignees_collection: () => p.oneToMany(TodoCategoryAssignees).mappedBy('trip').hidden(),
todo_items_collection: () => p.oneToMany(TodoItems).mappedBy('trip').hidden(),
tour_drafts_collection: () => p.oneToMany(TourDrafts).mappedBy('trip').hidden(),
+12
View File
@@ -39,6 +39,10 @@ import { JourneyRecordedDays } from './JourneyRecordedDays.entity';
import { JourneyRecordingPrep } from './JourneyRecordingPrep.entity';
import { JourneyShareTokens } from './JourneyShareTokens.entity';
import { Journeys } from './Journeys.entity';
import { MailIngestAddresses } from './MailIngestAddresses.entity';
import { MailIngestCandidates } from './MailIngestCandidates.entity';
import { MailIngestMessages } from './MailIngestMessages.entity';
import { MailIngestPrefs } from './MailIngestPrefs.entity';
import { McpTokens } from './McpTokens.entity';
import { NotificationChannelPreferences } from './NotificationChannelPreferences.entity';
import { Notifications } from './Notifications.entity';
@@ -176,6 +180,10 @@ export class Users {
journey_recording_prep_collection = new Collection<JourneyRecordingPrep>(this);
journey_share_tokens_collection = new Collection<JourneyShareTokens>(this);
journeys_collection = new Collection<Journeys>(this);
mail_ingest_addresses_collection = new Collection<MailIngestAddresses>(this);
mail_ingest_candidates_collection = new Collection<MailIngestCandidates>(this);
mail_ingest_messages_collection = new Collection<MailIngestMessages>(this);
mail_ingest_prefs_collection = new Collection<MailIngestPrefs>(this);
mcp_tokens_collection = new Collection<McpTokens>(this);
notification_channel_preferences_collection = new Collection<NotificationChannelPreferences>(this);
notifications_collection = new Collection<Notifications>(this);
@@ -335,6 +343,10 @@ export const UsersSchema = defineEntity({
journey_recording_prep_collection: () => p.oneToMany(JourneyRecordingPrep).mappedBy('user').hidden(),
journey_share_tokens_collection: () => p.oneToMany(JourneyShareTokens).mappedBy('createdByRef').hidden(),
journeys_collection: () => p.oneToMany(Journeys).mappedBy('user').hidden(),
mail_ingest_addresses_collection: () => p.oneToMany(MailIngestAddresses).mappedBy('user').hidden(),
mail_ingest_candidates_collection: () => p.oneToMany(MailIngestCandidates).mappedBy('user').hidden(),
mail_ingest_messages_collection: () => p.oneToMany(MailIngestMessages).mappedBy('user').hidden(),
mail_ingest_prefs_collection: () => p.oneToMany(MailIngestPrefs).mappedBy('user').hidden(),
mcp_tokens_collection: () => p.oneToMany(McpTokens).mappedBy('user').hidden(),
notification_channel_preferences_collection: () => p.oneToMany(NotificationChannelPreferences).mappedBy('user').hidden(),
notifications_collection: () => p.oneToMany(Notifications).mappedBy('sender').hidden(),
+12
View File
@@ -40,6 +40,7 @@ import { DocumentProvidersSchema } from './DocumentProviders.entity';
import { DocumentSyncItemsSchema } from './DocumentSyncItems.entity';
import { FerrataTilesSchema } from './FerrataTiles.entity';
import { FileLinksSchema } from './FileLinks.entity';
import { FlightLiveStatesSchema } from './FlightLiveStates.entity';
import { GoogleApiUsageSchema } from './GoogleApiUsage.entity';
import { GooglePlacePhotoMetaSchema } from './GooglePlacePhotoMeta.entity';
import { HiddenCountriesSchema } from './HiddenCountries.entity';
@@ -58,6 +59,11 @@ import { JourneyRecordingPrepSchema } from './JourneyRecordingPrep.entity';
import { JourneyShareTokensSchema } from './JourneyShareTokens.entity';
import { JourneyTripsSchema } from './JourneyTrips.entity';
import { JourneysSchema } from './Journeys.entity';
import { MailIngestAddressesSchema } from './MailIngestAddresses.entity';
import { MailIngestCandidatesSchema } from './MailIngestCandidates.entity';
import { MailIngestCursorSchema } from './MailIngestCursor.entity';
import { MailIngestMessagesSchema } from './MailIngestMessages.entity';
import { MailIngestPrefsSchema } from './MailIngestPrefs.entity';
import { McpTokensSchema } from './McpTokens.entity';
import { MigrationsSchema } from './Migrations.entity';
import { NotificationChannelPreferencesSchema } from './NotificationChannelPreferences.entity';
@@ -209,6 +215,7 @@ export const ALL_ENTITIES: readonly EntitySchema[] = [
DocumentSyncItemsSchema,
FerrataTilesSchema,
FileLinksSchema,
FlightLiveStatesSchema,
GoogleApiUsageSchema,
GooglePlacePhotoMetaSchema,
HiddenCountriesSchema,
@@ -227,6 +234,11 @@ export const ALL_ENTITIES: readonly EntitySchema[] = [
JourneyShareTokensSchema,
JourneyTripsSchema,
JourneysSchema,
MailIngestAddressesSchema,
MailIngestCandidatesSchema,
MailIngestCursorSchema,
MailIngestMessagesSchema,
MailIngestPrefsSchema,
McpTokensSchema,
MigrationsSchema,
NotificationChannelPreferencesSchema,
+83
View File
@@ -6,8 +6,15 @@ import {
assistantChangePreviewWriteSchema,
assistantMessagePartWriteSchema,
assistantStoredPartsSchema,
bookingImportPreviewItemSchema,
ferrataSchema,
hikingPreferencesSchema,
mailIngestAttachmentSchema,
mailIngestCheckResultSchema,
mailIngestCheckSchema,
mailIngestFieldSchema,
mailIngestHintSchema,
mailIngestSuggestedTripSchema,
obstacleSnapshotSchema,
paddleGeometrySchema,
paddleLockSchema,
@@ -26,9 +33,15 @@ import {
type DawarichTrackSegment,
type AssistantChangePreview,
type AssistantMessagePart,
type BookingImportPreviewItem,
type Ferrata,
type GeometryPoint,
type HikingPreferences,
type MailIngestAttachment,
type MailIngestCheck,
type MailIngestCheckResult,
type MailIngestField,
type MailIngestHint,
type ObstacleSnapshot,
type PaddleGeometry,
type PaddleLock,
@@ -531,3 +544,73 @@ export const PLACE_DETAILS_CACHE_PAYLOAD: JsonColumn<Record<string, unknown> | n
schema: z.record(z.string(), z.unknown()).nullable(),
fallback: () => null,
};
// ── The booking mail import (mail-ingest) ──────────────────────────────────
/** The booking read from a mail, as the inbox and the form show it; null for an entry that stands for the mail. */
export const MAIL_INGEST_ITEM: JsonColumn<BookingImportPreviewItem | null> = {
column: 'mail_ingest_candidates.item_json',
schema: bookingImportPreviewItemSchema.nullable(),
fallback: () => null,
};
/** The server's checks on the booking, by name. A broken row reads as none run. */
export const MAIL_INGEST_CHECKS: JsonColumn<Partial<Record<MailIngestCheck, MailIngestCheckResult>>> = {
column: 'mail_ingest_candidates.checks_json',
schema: z.partialRecord(mailIngestCheckSchema, mailIngestCheckResultSchema),
fallback: () => ({}),
};
/** The fields of the booking marked for a second look. */
export const MAIL_INGEST_UNCERTAIN_FIELDS: JsonColumn<MailIngestField[]> = {
column: 'mail_ingest_candidates.uncertain_fields',
schema: z.array(mailIngestFieldSchema),
fallback: () => [],
};
const mailIngestMatchSchema = z.object({
/** A change or cancellation of an earlier booking rather than a new one. */
kind: z.enum(['new_booking', 'change', 'cancellation']),
/** The trip the AI proposed to create when none fits; never created on its own. */
suggested_new_trip: mailIngestSuggestedTripSchema.nullable(),
});
type MailIngestMatch = z.infer<typeof mailIngestMatchSchema>;
/** How the booking was matched to a trip, past the suggested trip's own column. */
export const MAIL_INGEST_MATCH: JsonColumn<MailIngestMatch> = {
column: 'mail_ingest_candidates.match_json',
schema: mailIngestMatchSchema,
fallback: () => ({ kind: 'new_booking', suggested_new_trip: null }),
};
const idList = z.array(z.number().int().positive());
const mailIngestCreatedSchema = z.object({
reservation_ids: idList,
place_ids: idList,
budget_item_ids: idList,
file_ids: idList,
/** The booking as it was written, to tell an edit since then. */
fingerprint: z.string().nullable(),
});
export type MailIngestCreated = z.infer<typeof mailIngestCreatedSchema>;
/** What adding the booking created, for its undo. A broken row undoes nothing. */
export const MAIL_INGEST_CREATED: JsonColumn<MailIngestCreated> = {
column: 'mail_ingest_candidates.created_ids_json',
schema: mailIngestCreatedSchema,
fallback: () => ({ reservation_ids: [], place_ids: [], budget_item_ids: [], file_ids: [], fingerprint: null }),
};
/** What the inbox notes about a mail without holding it back. */
export const MAIL_INGEST_HINTS: JsonColumn<MailIngestHint[]> = {
column: 'mail_ingest_messages.hints',
schema: z.array(mailIngestHintSchema),
fallback: () => [],
};
/** The attachments a mail carried that a booking travels in, without their bytes. */
export const MAIL_INGEST_ATTACHMENTS: JsonColumn<MailIngestAttachment[]> = {
column: 'mail_ingest_messages.attachments',
schema: z.array(mailIngestAttachmentSchema),
fallback: () => [],
};
@@ -20,4 +20,5 @@ export interface DayAssignmentsTable {
accommodation_id: InsertOptional<number | null>;
route_excluded: InsertOptional<number>;
tour_stage_key: InsertOptional<string | null>;
stay_minutes: InsertOptional<number | null>;
}
@@ -0,0 +1,31 @@
// Generated by scripts/generate-db-types.ts from the migrated schema. Do not edit by hand:
// change the migration, then run `npm run gen:db-types`.
import type { InsertOptional } from './columns';
export interface FlightLiveStatesTable {
callsign: string;
service_date: string;
origin: string;
destination: string;
phase: InsertOptional<string>;
departed_at: InsertOptional<string | null>;
landed_at: InsertOptional<string | null>;
lat: InsertOptional<number | null>;
lng: InsertOptional<number | null>;
altitude_ft: InsertOptional<number | null>;
ground_speed_kt: InsertOptional<number | null>;
track_deg: InsertOptional<number | null>;
vertical_rate_fpm: InsertOptional<number | null>;
on_ground: InsertOptional<number | null>;
registration: InsertOptional<string | null>;
aircraft_type: InsertOptional<string | null>;
source: InsertOptional<string | null>;
first_seen_at: InsertOptional<string | null>;
last_seen_at: InsertOptional<string | null>;
fetched_at: InsertOptional<string | null>;
next_poll_at: InsertOptional<string | null>;
fail_count: InsertOptional<number>;
departed_notified: InsertOptional<number>;
landed_notified: InsertOptional<number>;
delay_notified: InsertOptional<number>;
}
@@ -0,0 +1,14 @@
// Generated by scripts/generate-db-types.ts from the migrated schema. Do not edit by hand:
// change the migration, then run `npm run gen:db-types`.
import type { InsertOptional } from './columns';
export interface MailIngestAddressesTable {
id: InsertOptional<number>;
token_hash: string;
token_enc: string;
user_id: number;
trip_id: InsertOptional<number | null>;
created_at: InsertOptional<string>;
revoked_at: InsertOptional<string | null>;
last_used_at: InsertOptional<string | null>;
}
@@ -0,0 +1,27 @@
// Generated by scripts/generate-db-types.ts from the migrated schema. Do not edit by hand:
// change the migration, then run `npm run gen:db-types`.
import type { InsertOptional } from './columns';
export interface MailIngestCandidatesTable {
id: InsertOptional<number>;
message_id: number;
user_id: number;
position: InsertOptional<number>;
item_json: InsertOptional<string | null>;
source: InsertOptional<string | null>;
checks_json: InsertOptional<string | null>;
uncertain_fields: InsertOptional<string | null>;
match_json: InsertOptional<string | null>;
suggested_trip_id: InsertOptional<number | null>;
dedupe_key: InsertOptional<string | null>;
content_hash: InsertOptional<string | null>;
resolution: InsertOptional<string>;
reason: InsertOptional<string | null>;
resolved_trip_id: InsertOptional<number | null>;
created_ids_json: InsertOptional<string | null>;
attach_error: InsertOptional<string | null>;
resolved_by: InsertOptional<number | null>;
resolved_at: InsertOptional<string | null>;
undo_until: InsertOptional<string | null>;
created_at: InsertOptional<string>;
}
@@ -0,0 +1,15 @@
// Generated by scripts/generate-db-types.ts from the migrated schema. Do not edit by hand:
// change the migration, then run `npm run gen:db-types`.
import type { InsertOptional } from './columns';
export interface MailIngestCursorTable {
id: InsertOptional<number>;
transport: string;
mailbox: string;
uid_validity: InsertOptional<number | null>;
last_uid: InsertOptional<number | null>;
last_ok_at: InsertOptional<string | null>;
last_error: InsertOptional<string | null>;
lease_owner: InsertOptional<string | null>;
lease_until: InsertOptional<string | null>;
}
@@ -0,0 +1,31 @@
// Generated by scripts/generate-db-types.ts from the migrated schema. Do not edit by hand:
// change the migration, then run `npm run gen:db-types`.
import type { InsertOptional } from './columns';
export interface MailIngestMessagesTable {
id: InsertOptional<number>;
transport: string;
message_id_hdr: InsertOptional<string | null>;
dedupe_hash: string;
address_id: InsertOptional<number | null>;
user_id: number;
trip_id: InsertOptional<number | null>;
from_addr: InsertOptional<string | null>;
from_verified: InsertOptional<number>;
auth_results: InsertOptional<string | null>;
subject: InsertOptional<string | null>;
received_at: InsertOptional<string>;
size: number;
raw_eml_enc: InsertOptional<string | null>;
raw_purged_at: InsertOptional<string | null>;
status: InsertOptional<string>;
reason: InsertOptional<string | null>;
hints: InsertOptional<string | null>;
attachments: InsertOptional<string | null>;
forwarding_code: InsertOptional<string | null>;
attempts: InsertOptional<number>;
next_attempt_at: InsertOptional<string>;
lease_until: InsertOptional<string | null>;
ai_used: InsertOptional<number>;
processed_at: InsertOptional<string | null>;
}
@@ -0,0 +1,11 @@
// Generated by scripts/generate-db-types.ts from the migrated schema. Do not edit by hand:
// change the migration, then run `npm run gen:db-types`.
import type { InsertOptional } from './columns';
export interface MailIngestPrefsTable {
id: InsertOptional<number>;
user_id: number;
enabled: InsertOptional<number>;
ai_enabled: InsertOptional<number>;
auto_add: InsertOptional<number>;
}
+1
View File
@@ -8,4 +8,5 @@ export interface TagsTable {
name: string;
color: InsertOptional<string | null>;
created_at: InsertOptional<string | null>;
trip_id: InsertOptional<number | null>;
}
+1
View File
@@ -17,4 +17,5 @@ export interface TripsTable {
created_at: InsertOptional<string | null>;
updated_at: InsertOptional<string | null>;
reminder_sent_for: InsertOptional<string | null>;
costs_mode: InsertOptional<string>;
}
+12
View File
@@ -43,6 +43,7 @@ import type { DocumentProvidersTable } from './DocumentProviders.table';
import type { DocumentSyncItemsTable } from './DocumentSyncItems.table';
import type { FerrataTilesTable } from './FerrataTiles.table';
import type { FileLinksTable } from './FileLinks.table';
import type { FlightLiveStatesTable } from './FlightLiveStates.table';
import type { GoogleApiUsageTable } from './GoogleApiUsage.table';
import type { GooglePlacePhotoMetaTable } from './GooglePlacePhotoMeta.table';
import type { HiddenCountriesTable } from './HiddenCountries.table';
@@ -61,6 +62,11 @@ import type { JourneyRecordingPrepTable } from './JourneyRecordingPrep.table';
import type { JourneyShareTokensTable } from './JourneyShareTokens.table';
import type { JourneyTripsTable } from './JourneyTrips.table';
import type { JourneysTable } from './Journeys.table';
import type { MailIngestAddressesTable } from './MailIngestAddresses.table';
import type { MailIngestCandidatesTable } from './MailIngestCandidates.table';
import type { MailIngestCursorTable } from './MailIngestCursor.table';
import type { MailIngestMessagesTable } from './MailIngestMessages.table';
import type { MailIngestPrefsTable } from './MailIngestPrefs.table';
import type { McpTokensTable } from './McpTokens.table';
import type { MigrationsTable } from './Migrations.table';
import type { NotificationChannelPreferencesTable } from './NotificationChannelPreferences.table';
@@ -218,6 +224,7 @@ export interface DB {
document_sync_items: DocumentSyncItemsTable;
ferrata_tiles: FerrataTilesTable;
file_links: FileLinksTable;
flight_live_states: FlightLiveStatesTable;
google_api_usage: GoogleApiUsageTable;
google_place_photo_meta: GooglePlacePhotoMetaTable;
hidden_countries: HiddenCountriesTable;
@@ -236,6 +243,11 @@ export interface DB {
journey_share_tokens: JourneyShareTokensTable;
journey_trips: JourneyTripsTable;
journeys: JourneysTable;
mail_ingest_addresses: MailIngestAddressesTable;
mail_ingest_candidates: MailIngestCandidatesTable;
mail_ingest_cursor: MailIngestCursorTable;
mail_ingest_messages: MailIngestMessagesTable;
mail_ingest_prefs: MailIngestPrefsTable;
mcp_tokens: McpTokensTable;
migrations: MigrationsTable;
notification_channel_preferences: NotificationChannelPreferencesTable;
@@ -0,0 +1,15 @@
import { Migration } from '@mikro-orm/migrations';
/**
* A chat message deleted before this release kept its text in the row; only the
* client hid it. Deleting now blanks the text with the flag
* (`CollabMessagesRepository.softDelete`), and this clears what older deletes
* left behind. The row itself stays for the "message deleted" placeholder.
*/
export class Migration20200101046370_a_deleted_chat_message_keeps_no_text extends Migration {
override name = 'Migration20200101046370_a_deleted_chat_message_keeps_no_text';
override up(): void {
this.addSql("UPDATE collab_messages SET text = '' WHERE deleted = 1 AND text != ''");
}
}
@@ -0,0 +1,111 @@
import { Migration } from '@mikro-orm/migrations';
interface RegionRow {
id: number;
user_id: number;
region_code: string;
region_name: string;
}
/** The 26 counties the Atlas now ships for Ireland: ISO 3166-2:IE code, name, province. */
const COUNTIES: ReadonlyArray<readonly [code: string, name: string, province: string]> = [
['IE-CW', 'Carlow', 'IE-L'],
['IE-D', 'Dublin', 'IE-L'],
['IE-KE', 'Kildare', 'IE-L'],
['IE-KK', 'Kilkenny', 'IE-L'],
['IE-LS', 'Laois', 'IE-L'],
['IE-LD', 'Longford', 'IE-L'],
['IE-LH', 'Louth', 'IE-L'],
['IE-MH', 'Meath', 'IE-L'],
['IE-OY', 'Offaly', 'IE-L'],
['IE-WH', 'Westmeath', 'IE-L'],
['IE-WX', 'Wexford', 'IE-L'],
['IE-WW', 'Wicklow', 'IE-L'],
['IE-CE', 'Clare', 'IE-M'],
['IE-CO', 'Cork', 'IE-M'],
['IE-KY', 'Kerry', 'IE-M'],
['IE-LK', 'Limerick', 'IE-M'],
['IE-TA', 'Tipperary', 'IE-M'],
['IE-WD', 'Waterford', 'IE-M'],
['IE-G', 'Galway', 'IE-C'],
['IE-LM', 'Leitrim', 'IE-C'],
['IE-MO', 'Mayo', 'IE-C'],
['IE-RN', 'Roscommon', 'IE-C'],
['IE-SO', 'Sligo', 'IE-C'],
['IE-CN', 'Cavan', 'IE-U'],
['IE-DL', 'Donegal', 'IE-U'],
['IE-MN', 'Monaghan', 'IE-U'],
];
/** "County Dublin", "Co. Dublin" and "dublin" all name Dublin. */
const countyKey = (name: string): string =>
name
.trim()
.toLowerCase()
.replace(/^(county|co\.?)\s+/, '');
/**
* Ireland gained its counties (#2922).
*
* geoBoundaries has no county layer for Ireland, so the Atlas showed the four
* provinces (IE-C, IE-L, IE-M, IE-U) next to a UK of counties. The bundle now ships
* Tailte Éireann's 26 counties under their ISO 3166-2:IE codes. What exists already:
*
* `place_regions` is a re-derivable cache full of province rows that nothing would
* ever re-derive, so Ireland's rows are cleared and come back as counties on the next
* Atlas load, as Great Britain's did when it gained its counties.
*
* `visited_regions` holds what a user marked by hand. A marked province stays as it
* is: which of its counties the user saw is not ours to guess. A row whose name is a
* county under another code (a Natural Earth or geocoder code from older versions)
* takes the county's code, and is dropped where the user already holds that county.
*
* `hidden_regions` remembers a region the user switched off. A hidden province hid
* every place in it, so each of its counties is hidden in its place; the province row
* stays and keeps hiding a marked province.
*
* `bucket_list` is a wish, not a polygon, and is left alone.
*/
export class Migration20200101046380_ireland_gained_its_counties extends Migration {
override name = 'Migration20200101046380_ireland_gained_its_counties';
override async up(): Promise<void> {
await this.execute(`DELETE FROM place_regions WHERE UPPER(COALESCE(country_code, '')) = 'IE'`);
// Queued in order, run after the reads below: the codes come from the table
// above and the row ids from the database, nothing a user typed.
for (const [code, , province] of COUNTIES) {
this.addSql(
`INSERT INTO hidden_regions (user_id, region_code, country_code)
SELECT h.user_id, '${code}', h.country_code FROM hidden_regions h
WHERE h.region_code = '${province}' AND UPPER(h.country_code) = 'IE'
AND NOT EXISTS (SELECT 1 FROM hidden_regions x WHERE x.user_id = h.user_id AND x.region_code = '${code}')`,
);
}
const rows = (await this.execute(
`SELECT id, user_id, region_code, region_name FROM visited_regions
WHERE UPPER(COALESCE(country_code, '')) = 'IE' ORDER BY id`,
)) as RegionRow[];
const counties = new Map(COUNTIES.map(([code, name]) => [countyKey(name), { code, name }]));
const countyCodes = new Set(COUNTIES.map(([code]) => code));
const held = new Set(rows.map((r) => `${r.user_id}|${r.region_code}`));
for (const row of rows) {
if (countyCodes.has(row.region_code)) continue;
const county = counties.get(countyKey(row.region_name || ''));
if (!county) continue;
const target = `${row.user_id}|${county.code}`;
const id = Number(row.id);
if (!Number.isInteger(id)) continue;
if (held.has(target)) {
this.addSql(`DELETE FROM visited_regions WHERE id = ${id}`);
} else {
this.addSql(
`UPDATE visited_regions SET region_code = '${county.code}', region_name = '${county.name}' WHERE id = ${id}`,
);
held.add(target);
}
}
}
}
@@ -0,0 +1,24 @@
import { addColumnIfMissing } from '../migration-utils';
import { Migration } from '@mikro-orm/migrations';
/**
* A trip can keep its costs as totals only (#1714): who paid, the shares and
* settling up are left out of Costs, for travellers who track what a trip costs
* but never split it.
*
* `costs_mode` is 'split' (what every trip did so far) or 'totals'. 'split' as
* the default keeps this from being a breaking change: SQLite fills every
* existing row with it on the ALTER, so every trip looks as it did before.
*/
export class Migration20200101046390_a_trip_can_keep_its_costs_as_totals_only extends Migration {
override name = 'Migration20200101046390_a_trip_can_keep_its_costs_as_totals_only';
override async up(): Promise<void> {
await addColumnIfMissing(
this,
'trips',
'costs_mode',
`costs_mode TEXT NOT NULL DEFAULT 'split' CHECK (costs_mode IN ('split', 'totals'))`,
);
}
}
@@ -0,0 +1,51 @@
import { Migration } from '@mikro-orm/migrations';
/**
* Live flight status: what the open ADS-B feeds last said about one flight on
* one day, keyed by the callsign it transmits, its local departure date and
* its two airports. A through flight keeps one flight number over two sectors
* (FRA to BOM to SIN as LH 754 on one day), and each sector has a state of its own.
* One row serves every trip that booked the same flight, so the feeds are asked
* once per flight, not once per traveller. Next to the derived state sit the
* poll's bookkeeping (when to ask next, how often it failed) and whether each
* notification already went out, so a departure is announced once.
*
* No foreign key: the row describes a flight in the air, not a booking, and is
* found again from the bookings by its key.
*/
export class Migration20200101046400_a_booked_flight_shows_where_it_is extends Migration {
override name = 'Migration20200101046400_a_booked_flight_shows_where_it_is';
override up(): void {
this.addSql(`
CREATE TABLE IF NOT EXISTS flight_live_states (
callsign TEXT NOT NULL,
service_date TEXT NOT NULL,
origin TEXT NOT NULL,
destination TEXT NOT NULL,
phase TEXT NOT NULL DEFAULT 'scheduled',
departed_at DATETIME,
landed_at DATETIME,
lat REAL,
lng REAL,
altitude_ft REAL,
ground_speed_kt REAL,
track_deg REAL,
vertical_rate_fpm REAL,
on_ground INTEGER,
registration TEXT,
aircraft_type TEXT,
source TEXT,
first_seen_at DATETIME,
last_seen_at DATETIME,
fetched_at DATETIME,
next_poll_at DATETIME,
fail_count INTEGER NOT NULL DEFAULT 0,
departed_notified INTEGER NOT NULL DEFAULT 0,
landed_notified INTEGER NOT NULL DEFAULT 0,
delay_notified INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (callsign, service_date, origin, destination)
)
`);
}
}
@@ -0,0 +1,163 @@
import { Migration } from '@mikro-orm/migrations';
/**
* A person forwards a booking mail to an address of their own, and TREK adds
* the booking to the matching trip, or keeps it in an inbox with a reason.
*
* `mail_ingest_addresses` holds one row per forwarding address: the person's
* own (`trip_id` null) or one for a single trip, which belongs to the member
* who made it (`user_id`). The token is stored twice: its sha256 for the
* lookup, and encrypted so its owner can see the address again. A renewed or
* revoked address keeps its row with `revoked_at` set, so a mail to it is
* recognised and refused.
*
* `mail_ingest_prefs` holds a person's switches (import, AI reading, adding
* on its own or asking first); without a row every switch is on.
*
* `mail_ingest_cursor` is the position and the lease of a reader: an IMAP box
* by (uid_validity, last_uid), and the processing pipeline itself, so two
* processes on one database never read the same mail at once.
*
* `mail_ingest_messages` holds each mail as it arrived, encrypted
* (`raw_eml_enc`) until the retention job purges it, with what the
* pipeline made of it. `dedupe_hash` keeps a mail delivered twice from
* being read twice.
*
* `mail_ingest_candidates` holds each booking read from a mail, the server's
* checks on it, the trip it went to or was suggested for, and what became of
* it: the ids it created (for the undo, open until `undo_until`), or why it
* waits in the inbox.
*
* Every row goes with its person; a trip that goes clears its references, so
* the inbox entry stays and can be filed elsewhere. Every foreign key leads
* an index.
*/
export class Migration20200101046410_a_forwarded_booking_mail_lands_in_its_trip extends Migration {
override name = 'Migration20200101046410_a_forwarded_booking_mail_lands_in_its_trip';
override up(): void {
this.addSql(`
CREATE TABLE IF NOT EXISTS mail_ingest_addresses (
id INTEGER PRIMARY KEY,
token_hash TEXT NOT NULL,
token_enc TEXT NOT NULL,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
trip_id INTEGER REFERENCES trips(id) ON DELETE CASCADE,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
revoked_at DATETIME,
last_used_at DATETIME,
UNIQUE(token_hash)
)
`);
this.addSql('CREATE INDEX IF NOT EXISTS idx_mail_ingest_addresses_user ON mail_ingest_addresses(user_id, trip_id)');
this.addSql('CREATE INDEX IF NOT EXISTS idx_mail_ingest_addresses_trip ON mail_ingest_addresses(trip_id)');
this.addSql(`
CREATE TABLE IF NOT EXISTS mail_ingest_prefs (
id INTEGER PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
enabled INTEGER NOT NULL DEFAULT 1,
ai_enabled INTEGER NOT NULL DEFAULT 1,
auto_add INTEGER NOT NULL DEFAULT 1,
UNIQUE(user_id)
)
`);
this.addSql(`
CREATE TABLE IF NOT EXISTS mail_ingest_cursor (
id INTEGER PRIMARY KEY,
transport TEXT NOT NULL CHECK(transport IN ('imap', 'cloud', 'pipeline')),
mailbox TEXT NOT NULL,
uid_validity INTEGER,
last_uid INTEGER,
last_ok_at DATETIME,
last_error TEXT,
lease_owner TEXT,
lease_until DATETIME,
UNIQUE(transport, mailbox)
)
`);
this.addSql(`
CREATE TABLE IF NOT EXISTS mail_ingest_messages (
id INTEGER PRIMARY KEY,
transport TEXT NOT NULL CHECK(transport IN ('imap', 'webhook', 'cloud', 'upload')),
message_id_hdr TEXT,
dedupe_hash TEXT NOT NULL,
address_id INTEGER REFERENCES mail_ingest_addresses(id) ON DELETE SET NULL,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
trip_id INTEGER REFERENCES trips(id) ON DELETE SET NULL,
from_addr TEXT,
from_verified INTEGER NOT NULL DEFAULT 0,
auth_results TEXT,
subject TEXT,
received_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
size INTEGER NOT NULL,
raw_eml_enc TEXT,
raw_purged_at DATETIME,
status TEXT NOT NULL DEFAULT 'queued'
CHECK(status IN ('queued', 'processing', 'processed', 'discarded', 'failed')),
reason TEXT,
hints TEXT,
attachments TEXT,
forwarding_code TEXT,
attempts INTEGER NOT NULL DEFAULT 0,
next_attempt_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
lease_until DATETIME,
ai_used INTEGER NOT NULL DEFAULT 0,
processed_at DATETIME,
UNIQUE(dedupe_hash)
)
`);
this.addSql(
'CREATE INDEX IF NOT EXISTS idx_mail_ingest_messages_due ON mail_ingest_messages(status, next_attempt_at)',
);
this.addSql(
'CREATE INDEX IF NOT EXISTS idx_mail_ingest_messages_user ON mail_ingest_messages(user_id, received_at)',
);
this.addSql(
'CREATE INDEX IF NOT EXISTS idx_mail_ingest_messages_address ON mail_ingest_messages(address_id, received_at)',
);
this.addSql('CREATE INDEX IF NOT EXISTS idx_mail_ingest_messages_trip ON mail_ingest_messages(trip_id)');
this.addSql(`
CREATE TABLE IF NOT EXISTS mail_ingest_candidates (
id INTEGER PRIMARY KEY,
message_id INTEGER NOT NULL REFERENCES mail_ingest_messages(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
position INTEGER NOT NULL DEFAULT 0,
item_json TEXT,
source TEXT CHECK(source IN ('ai', 'kitinerary', 'json_ld', 'ics', 'pkpass', 'text')),
checks_json TEXT,
uncertain_fields TEXT,
match_json TEXT,
suggested_trip_id INTEGER REFERENCES trips(id) ON DELETE SET NULL,
dedupe_key TEXT,
content_hash TEXT,
resolution TEXT NOT NULL DEFAULT 'pending'
CHECK(resolution IN ('pending', 'auto_applied', 'applied', 'filed', 'discarded', 'duplicate', 'conflict',
'undone')),
reason TEXT,
resolved_trip_id INTEGER REFERENCES trips(id) ON DELETE SET NULL,
created_ids_json TEXT,
attach_error TEXT,
resolved_by INTEGER,
resolved_at DATETIME,
undo_until DATETIME,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
)
`);
this.addSql(
'CREATE INDEX IF NOT EXISTS idx_mail_ingest_candidates_message ON mail_ingest_candidates(message_id, position)',
);
this.addSql(
'CREATE INDEX IF NOT EXISTS idx_mail_ingest_candidates_user ON mail_ingest_candidates(user_id, resolution)',
);
this.addSql(
'CREATE INDEX IF NOT EXISTS idx_mail_ingest_candidates_suggested ON mail_ingest_candidates(suggested_trip_id)',
);
this.addSql(
'CREATE INDEX IF NOT EXISTS idx_mail_ingest_candidates_resolved ON mail_ingest_candidates(resolved_trip_id, content_hash)',
);
}
}
@@ -0,0 +1,20 @@
import { addColumnIfMissing } from '../migration-utils';
import { Migration } from '@mikro-orm/migrations';
/**
* #3092: how long the drive stands at a stop belongs to the visit, not to the
* place. A place planned twice on one road trip day (once to stop, once only to
* steer the route past it) could not be given two different stays, because the
* only value was `places.duration_minutes`.
*
* `stay_minutes` is the visit's own length. It stays null on every existing row,
* and a null visit keeps reading the place's `duration_minutes`, so a trip
* planned before this step drives exactly as it did.
*/
export class Migration20200101046420_a_visit_keeps_its_own_stay extends Migration {
override name = 'Migration20200101046420_a_visit_keeps_its_own_stay';
override async up(): Promise<void> {
await addColumnIfMissing(this, 'day_assignments', 'stay_minutes', 'stay_minutes INTEGER');
}
}
@@ -0,0 +1,44 @@
import { Migration } from '@mikro-orm/migrations';
/**
* The hourly job that tells every forwarding address holder once that the mail
* import is paused keeps its "already told" mark and its lease in
* `mail_ingest_cursor`, as the `notice` reader. The CHECK from
* Migration20200101046410 only knew `imap`, `cloud` and `pipeline`, so taking
* that lease failed on the insert (an `ON CONFLICT DO NOTHING` does not cover a
* CHECK) and nobody was ever told.
*
* SQLite cannot change a CHECK in place, so the table is rebuilt with `notice`
* added. No table points at `mail_ingest_cursor` and it has no index of its own
* beyond the `UNIQUE(transport, mailbox)`, so it is copied, dropped and renamed
* on its own. Every row keeps its id, position and lease.
*/
export class Migration20200101046430_a_paused_mail_import_can_tell_its_address_holders extends Migration {
override name = 'Migration20200101046430_a_paused_mail_import_can_tell_its_address_holders';
override up(): void {
this.addSql(`
CREATE TABLE mail_ingest_cursor_new (
id INTEGER PRIMARY KEY,
transport TEXT NOT NULL CHECK(transport IN ('imap', 'cloud', 'pipeline', 'notice')),
mailbox TEXT NOT NULL,
uid_validity INTEGER,
last_uid INTEGER,
last_ok_at DATETIME,
last_error TEXT,
lease_owner TEXT,
lease_until DATETIME,
UNIQUE(transport, mailbox)
)
`);
this.addSql(`
INSERT INTO mail_ingest_cursor_new (
id, transport, mailbox, uid_validity, last_uid, last_ok_at, last_error, lease_owner, lease_until
)
SELECT id, transport, mailbox, uid_validity, last_uid, last_ok_at, last_error, lease_owner, lease_until
FROM mail_ingest_cursor
`);
this.addSql('DROP TABLE mail_ingest_cursor');
this.addSql('ALTER TABLE mail_ingest_cursor_new RENAME TO mail_ingest_cursor');
}
}
@@ -0,0 +1,21 @@
import { addColumnIfMissing } from '../migration-utils';
import { Migration } from '@mikro-orm/migrations';
/**
* A tag can belong to a trip. Every tag used to be one person's: a place of a
* shared trip carried labels only their owner could list, pick again or rename,
* and a co-traveller had to make their own tag of the same name.
*
* A tag with `trip_id` set is the trip's own. Every member reads it, anyone who
* may edit the trip's places may change it, and it goes when the trip goes.
* `user_id` keeps who created it. The column stays null on every existing row,
* which leaves those what they were: personal tags.
*/
export class Migration20200101046440_a_trip_owns_its_tags extends Migration {
override name = 'Migration20200101046440_a_trip_owns_its_tags';
override async up(): Promise<void> {
await addColumnIfMissing(this, 'tags', 'trip_id', 'trip_id INTEGER REFERENCES trips(id) ON DELETE CASCADE');
this.addSql('CREATE INDEX IF NOT EXISTS idx_tags_trip_id ON tags (trip_id)');
}
}
@@ -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'>;