mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-10-23 07:26:30 +00:00
de8caa81a2
* base entities
* update deps
* fix date as string
* rename entities
* migrations + seeders
* feat(db): DbTimestampType keeps DATETIME columns as the CURRENT_TIMESTAMP text
* feat(db): discover entities from an explicit list instead of a glob
* test(db): createTestOrm binds an ORM to a suite's own SQLite handle
* feat(db): dialect helper is the one place SQL functions are spelled
* test(db): dialect helper refuses malformed column references and day counts
* feat(db): snake_case entity shape and the first three repositories (Days, DayNotes, Trips)
* fix(db): repositories mirror the statement's column set and guard their row types
* feat(db): request-context and unit-of-work helpers for the ORM, with concurrency tests
* test(server): integration suites boot on the migrated schema snapshot
* test(server): snapshot harness keeps the legacy id semantics
* fix(test): route MikroORM's dynamic imports through vitest from the setup file, not the ORM config
* test(db): coverage ratchet entries for the ORM foundation
* test(server): websocket suites boot on the migrated schema snapshot
* test(server): coverage's uncovered-file pass goes through the SWC transform
* fix(db): dialect helpers dispatch on the platform; lint gate for the repository layer
* test(server): ORM suites open the schema snapshot; RESET_TABLES derived from the schema
* chore(server): promise safety net and sweep tooling for the async migration
* refactor(realtime, systemNotices, addons, airports, audit, categories, permissions, query-helpers, tags, transit, trip-membership): async DB-touching methods; transactions through UnitOfWork
* fix(server): observe every promise the async sweep left unobserved (timer, handshake, plugin-runtime test)
* test(doc-sync): unit suites await the methods the async sweep made async
* refactor(atlas, school-holidays, settings): async DB-touching methods; transactions through UnitOfWork
* chore(server): lint rule refusing a Promise used as a plain value, and the misses it found
* test(server): suites await the methods Task 1's forced edits made async
* refactor(budget, common, day-notes, days): async DB-touching methods; transactions through UnitOfWork
* test(oauth): controller suite awaits the async service
* chore(server): db-call-graph --unawaited lists calls to async methods whose result is used without await
* refactor(llm-parse, mcp-shared, oauth, place-shadow, route-usage, storage, todo, trip-invite): async DB-touching methods; transactions through UnitOfWork
* refactor(plugins): async DB-touching methods; transactions through UnitOfWork
* chore(server): db-call-graph --sync stops its transitive walk at an async callee
* chore(plugins): drop gate-only asyncs; observe the scheduler's rejection; async event-sink stub
* refactor(notifications, place-photos, backup): async DB-touching methods; transactions through UnitOfWork
* refactor(auth, files): async DB-touching methods; transactions through UnitOfWork
* test(server): suites await the methods earlier sweep groups made async
* refactor(tokens): async DB-touching methods; the auth token handlers await them
* test(files): upload filters fail closed on an excluded or unresolvable type
* refactor(collab, collections, maps): async DB-touching methods; transactions through UnitOfWork
* refactor(memories, photos, packing, share): async DB-touching methods; transactions through UnitOfWork
* chore(server): lint rule also refuses a Promise handed to expect() without resolves/rejects
* refactor(vacay, admin, doc-sync): async DB-touching methods; transactions through UnitOfWork
* fix(vacay): type the loop accumulators the async sweep introduced
* refactor(journey, oidc, place-enrichment, tokens, trip-members): async DB-touching methods; transactions through UnitOfWork
* fix(server): the journey hooks are awaited by their callers, not detached
* refactor(assignments, public-api, accommodations, places): async DB-touching methods; transactions through UnitOfWork
* refactor(trips): rewrite AccommodationsService.createAccommodation .bind alias
Recipe R4 trap named in the Task 12 brief: a .bind alias of an
AssignmentsService/AccommodationsService method is typed any and hides a
missing await from tsc and the promise lint rules. createAccommodation
belongs to this task's group, so rewritten as an arrow forwarding to the
method instead of a bound reference.
* refactor(assignments): drop the unused Trip type alias
* refactor(reservations, booking-import, calendar, integrations, roadtrip): async DB-touching methods; transactions through UnitOfWork
* refactor(roadtrip, reservations): return await on transactional; document the single-flight promises
* refactor(trip-read-model, trips, feeds): async DB-touching methods; transactions through UnitOfWork
* refactor(server): remove DatabaseService.transaction — every transaction runs through UnitOfWork
* refactor(trips, feeds): drop added return annotations; no double await on the feed guard
* fix(server): phase 1 review follow-ups — awaited returns, logged upload-filter rejections, covered handshake/notice branches, call-graph gate in CI, dead test imports
* fix(server): upload filters answer multer once on a throwing callback; positive call-graph gate test
* test(db): entity metadata must match the migrated schema; fix the four drifts it found
* feat(db): primary-relation entities proven (BudgetCategoryOrder, VacayUserSettings)
* test(db): parity gate also holds declared pivot entities; per-field column types; missing-set ratchets both ways
* test(db): numeric ids for the primary-relation spike
* feat(db): re-runnable entity generator encoding the snake_case/DbTimestampType rules
* fix(db): generator guard rails — validation cannot mask hidden()/index loss; typed JSON; loud failures
* fix(db): generator keeps NOT NULL boolean defaults; fails if a JSON interface import survives
* refactor(db): every entity in the snake_case shape; document-sync entities added; one repository per entity
* fix(db): no NaN class-field initialisers; entity generator --check gate in CI; parity normaliser keeps literal case
* chore(db): entity --check reports stray files; class-field census is a ratchet; migrate-encryption typechecked
* feat(db): AppSettings and Users repositories; forFeature wiring pattern
* refactor(permissions): permission flags through AppSettingsRepository
* fix(server): boot-time settings read runs inside an explicit ORM request context
* refactor(audit): audit log writes through AuditLogRepository
* fix(db): PK reads refresh past the identity map; typed owned-lookup generics; e2e ORM module mirrors production config
* docs(db): owned-lookup call-site convention; refresh side effect; e2e ORM module spread notes
* fix(audit): audit rows are native inserts, not a unit-of-work flush; closed test ORMs
* fix(server): non-HTTP entrypoints run inside an ORM request context; permission loads fail closed on context errors
* refactor(categories, tags): repositories replace raw SQL
* refactor(addons): addon catalog and photo providers through repositories
* fix(db): generator captures inline UNIQUE constraints
SqliteSchemaHelper.getIndexes() drops every unnamed sqlite_autoindex_
entry before entity-generator ever sees it, so a table-level
UNIQUE(...) constraint with no separate named CREATE UNIQUE INDEX
(settings' UNIQUE(user_id, key) among ~40 others) never reached the
generated entity's uniques: metadata. Adds a general
RULE9_addImplicitUniqueConstraints (skips a column set identical to
the table's own primary key — AppSettings.key/Addons.id noise) fed by
a PRAGMA index_list/index_info scan, and regenerates every entity.
* chore(addons): well-known gate wraps only the addon read in a request context; drop unused test factories
* fix(platform): well-known gate tolerates a synchronous addon read from the context helper
* fix(db): PK lookups inside patch refresh past the identity map; corrected identity-map notes
* refactor(settings): user and instance settings through repositories
SettingsRepository (getForUser/upsertForUser/getOne/deleteForUser) replaces
the per-user settings table's raw SQL; SettingsService drops DatabaseService
entirely. instance-api-keys.ts's readInstanceApiKey/writeInstanceApiKey/
resolveApiKey take an explicit AppSettingsRepository/UsersRepository instead
of a raw connection.
An earlier version resolved those two repositories itself from the active
MikroORM request context, so none of its six callers needed to change. That
worked in production and e2e (always inside a real request) but broke
service construction in plain unit tests across every calling domain
(addons, auth x2, maps, transit, unsplash - 185 failures on a full run),
since none of them wrap a request context. Each of those six services now
injects its own AppSettingsRepository/UsersRepository and passes them
through explicitly, matching how every other converted repository in this
migration is consumed; their own SQL is untouched (outside Plan 3a).
* test(server): harness constructors follow the Task 5 repository signatures; one test ORM per handle in the plugin host
* fix(db): generator names relation properties in captured UNIQUE constraints
* fix(settings): drop dead wiring and the speculative deleteForUser; strict row assertions
* fix(server): plan 3a review follow-ups — fail closed without an ORM at every choke point; seam and D5 ratchet tests; dead method and DDL copies removed
* fix(server): plan 3a re-review follow-ups — plugin boot activation and the airports backfill inside a request context; the supervisor answers the child before failing closed; BOOT-SWEEP-001 drives the real boot hooks; ws adapter seam pinned
* feat(db): generated entities declare their repository type; test casts dropped
* fix(server): plan 3a re-review 2 follow-ups — absent-ORM boot branch pinned; airports boot hook never rejects; BOOT-SWEEP-001 asserts the seven routes; duplicate comment removed
* feat(server): pre-init photo route and WS handshake run in a request context; InviteTokensRepository
* refactor(auth): users table through UsersRepository; JWT and MFA lookups repository-backed
* refactor(tokens): MCP and API tokens through McpTokensRepository
* refactor(auth): passkeys and registration invites through repositories
* fix(db): row-out repository reads bypass the identity map — stale write-back over nativeUpdate at flush; insertUser via em.insert; settings round-trip pinned
* fix(server): non-numeric route ids answer the legacy not-found, never NaN (tokens, categories, tags); mint path back to two statements; identity-map regression pinned
* refactor(oauth): OAuth server tables through repositories
OauthClientsRepository/OauthTokensRepository/OauthConsentsRepository
replace OauthService's raw SQL (OA1-OA33). revokeChain's recursive CTE
and the oauth_clients join (its FK actually targets client_id, not the
row id the generated relation assumes) go through em.getKysely();
OA19's chain revoke is one nativeUpdate($in); OA12's consent grant is
em.upsert on the (client, user) unique key. revokeAllForUser built now
for Task 5. Every row-out read is disableIdentityMap: true; inserts go
through em.insert.
* fix(auth): non-numeric passkey and invite ids answer the legacy 404, never NaN; invite join type pinned
* fix(db): generator emits the referenced column for non-PK foreign keys; OAuth client joins through the relation; FK parity un-skipped
* refactor(db): TrekRepository base — every repository path validates the request context and reads bypass the identity map by default
* refactor(auth): AuthService and account cleanup through repositories
* refactor(oidc): OIDC identities and settings through repositories
* fix(auth): invite validation keeps expires_at null on the wire; password transaction scopes and reset-token burn pinned
* fix(server): plan 3b close-out — case folding on both sides for identifier lookups (non-ASCII login regression); coverage ratchet restored; repository scaffold and instanceof ratchet on TrekRepository; D-shape tests load-bearing
* refactor(server): trip-access primitives async at every caller
* refactor(trips): trip access through TripsRepository; demo seed in a request context; dialect helpers for the trips cluster
* refactor(days): days and day notes through repositories
* refactor(assignments): day assignments through repositories
* refactor(server): trip-membership, place-shadow, place-enrichment, place-photos and query helpers through repositories
* refactor(trip-members): membership, guests and the trip read model through repositories
* refactor(places): places, tags, ratings and place images through repositories
* fix(server): place-shadow source counts ordered in SQL; identity-map ratchets load-bearing; photo-cache race pinned
* refactor(places): import paths through repositories
* refactor(trips): trips through repositories
* fix(server): trip ids parsed once at the gate for places and assignments; NUL-safe value quoting on the SQLite platform; places parity tests completed
* refactor(trips): trip copy through repositories for the owned tables
* fix(server): plan 3c close-out — non-finite ids bound as NULL, trip id parsed once at every places/days/ws gate
Platform: NulSafeSqlitePlatform now renders a bound NaN as NULL and
+/-Infinity as 9e999/-9e999, matching better-sqlite3's own legacy binding
(rule 22 extension) — the program-wide fail-safe for any caller that still
passes an unguarded Number(untrusted) into a converted statement.
PlacesService.verifyTripAccess and RealtimeGateway.handleJoin stop doing
that: verifyTripAccess parses once with toRowId and threads the parsed id
through create/import/bulk/rating/export.gpx (deleting the seven
toRowId(tripId) ?? -1 sites), and handleJoin gets a Number.isFinite guard.
DaysService gets the same treatment across list/create/getDay/reorder/
insert/resyncAccommodationDays, closing the gap where a hex-spelled trip id
could renumber a real trip's days while the raw-bind inverted-accommodation
guard silently matched nothing.
DatabaseService.getTripTitle is deleted; PlacesService injects
TripsRepository directly and calls getTitle itself.
Template/cheap-item cleanup: DayAssignmentsRepository.listForTimeSort uses
$castTo instead of an unknown bridge; the duplicated TagRow interface in
Places.repository.ts is now imported from Tags.repository.ts;
AssignmentWithPlaceRow extends the guarded DayAssignmentRow instead of
restating its columns; PlaceShadowPicksRepository.totals drops its
unreachable ??-fallback branch; Places.repository.ts's updatePlace types
the NOT NULL name column as string; trip-members.service.ts's
transferOwnership threads one parsed trip id through all three writes and
corrects two stale "raw-bind seam" docstrings that were actually Number()
seams; a dead canAccessTrip mock is removed from reservations.e2e.test.ts.
Tests: the 23 new no-explicit-any warnings in TRIP-SVC-069 are typed
(lint back to 2416); HTTP and WS regression coverage for the non-finite
and non-canonical id shapes across places/days routes, mutation-proved;
TRIP-JOIN-005 asserts the exact concurrent-join settlement instead of
>= 1; a new tests/unit/db/transaction-yield.test.ts pins rule 24's
measured transaction-yield/dirty-read/nested-BEGIN behaviour.
* test(server): plan 3c close-out — copy-source full-row parity, Kysely rollback proofs, identity-map relabels, trips e2e on the snapshot DB
* fix(server): plan 3c close-out — days create/insert answer the guard 404 for non-canonical trip ids instead of 500; exact settlement and cross-request yield ratchets
* feat(server): plan 3d groundwork — dialect helpers, visibility predicate, feed and cron context ratchets
* refactor(roadtrip): roadtrip tables through repositories
* refactor(reservations): reservations, endpoints and travelers through repositories
* refactor(feeds): ICS feed tokens and anonymous feeds through repositories
* refactor(accommodations): stays through repositories inside the existing transactions
* test(server): plan 3d — MCP test helper constructors follow the accommodations and days services
* refactor(trips): trip copy through repositories for the roadtrip, accommodation and reservation tables
* refactor(calendar): calendar reads and reservation visibility through one predicate
* feat(server): plan 3e groundwork — packing visibility predicate, memories access-gate audit
* fix(server): plan 3d close-out — legacy text shape for stored accommodation ids restores the date-change restamp; reservation ids parsed once at the gate; parity tests for the reservation repositories
* refactor(photos): trek photos, memories access and cache sweeps through repositories
* refactor(files): trip files and file links through repositories, with transactions added
* test(server): plan 3e — hand-built FilesService, FilesRpc and AllowedFileTypesService calls follow the repository constructors
* refactor(memories): unified, immich and synology photo sync through repositories
* refactor(collab): notes, polls, messages and links through repositories
* refactor(budget): budget items, members, payers and settlements through repositories
* refactor(todo): todo items through repositories
* refactor(packing): packing items, bags and templates through repositories
* feat(server): plan 3f groundwork — systemNotices DI shape, TRAVELER_OWNS predicate, ntfy/storage-health specs, composite-PK pins
* refactor(school-holidays): country and region catalog through repositories
* refactor(notifications): in-app notifications and channel preferences through repositories
* refactor(notifications): reminder crons, mailer, ntfy and webhook transports through repositories
* fix(server): plan 3e close-out — repository registrations restore the boot; packing assignee and bag updates parse and no-op as legacy; coverage and scoping ratchets for the budget, packing and collab repositories
* refactor(vacay): vacation plans, entries, shares and holiday calendars through repositories
* refactor(system-notices): notice dismissals through a Nest provider and repository
* refactor(atlas): visited countries, regions and bucket list through repositories
* feat(server): plan 3g groundwork — GALLERY_CHRONOLOGICAL_ORDER Kysely ordering, unixEpochToIsoKysely helper, composite-PK DDL pins, JB5/R7 confirmations
* refactor(journey): journey and trip access control, CRUD and the trip-sync engine through repositories
* feat(server): plan 3h groundwork — date-offset dialect helpers, entity/repository fitness confirmations, pre-init and encryption pattern confirmations, survivor re-grep
* fix(server): plan 3f close-out — ntfy operator-scope test on the live send path; vacay date-offset and shift-order parity; todo reminder window; coverage and parity ratchets for the atlas and vacay repositories
* refactor(journey): journey stats, entries, photos, contributors and suggestions through repositories
* refactor(journey): public share links, TREK Studio books and the journal facades through repositories
* refactor(collections): access model, hydration, export/import and list CRUD through repositories
* refactor(server): journey-table survivors in trips, photos, memories, auth-cleanup and plugin-contributions through repositories
* refactor(integrations): dawarich connection, sync, tracks and review-flow through repositories
* refactor(collections): saved places, copy-to-trip, labels and invitations through repositories
* refactor(integrations,booking-import,airports,maps,route-usage): airtrail, booking import, airport backfill, maps cache and route-usage counters through repositories
* refactor(doc-sync): connections, reconciler and controller-SQL relocation through repositories
* test(integrations): add AirTrail saveSettings tx-asymmetry ratchet (Plan 3h Task 4 addendum)
* fix(server): plan 3g close-out — transactional book first-save, skeleton reconcile and share-link create; unknown-key entry patches are no-ops again; parity and authorization pins for the journey repositories
* feat(server): plan 3i groundwork — AuditLogRepository's reserved methods, the demo connection-swap spike, repository-fitness confirmations
* feat(server): plan 3j groundwork — scheduler onto CronRegistrarService, SDK-contract confirmation, repository fitness
* refactor(storage): backend/category config and usage stats through AppSettingsRepository; fix the seed-file test race and the shared-replica migration-flip gap
* refactor(share): public share links, the pre-init photo fallback, and collection-places survivors through repositories
* feat(server): plan 3j — the withCamelCase utility, unwired, pending a contract decision
* refactor(admin): user CRUD, stats, audit log, version check and addon config through repositories
* test(admin): pin createUser's pre-existing non-transactional uniqueness-check race (AD2-4)
* refactor(plugins): the trip-write role gate through a repository, in isolation
* refactor(demo,backup): seed and reset through DemoRepository, live-connection backup statements through MaintenanceRepository, isDemoUserId through an injected DemoService
* fix(server): plan 3h close-out — new-value-wins COALESCE restores stay/reservation propagation; doc-sync state filter truthiness; request-context and parity ratchets for share, doc-sync and the integrations
* refactor(plugins): runtime lifecycle, config CRUD and the uninstall cascade through repositories
* fix(server): plan 3i close-out — DemoModule imported where its service is consumed (e2e restored); admin addons list selects the provider relation; saveDemoBaseline awaited; backup tests on the maintenance repository
* refactor(plugins): outbound OAuth tokens and per-user plugin settings through repositories
* refactor(plugins): install-time gates, the capability-audit hash chain and the registry through repositories
* refactor(plugins): contribution-hook controllers, the small plugin controllers and the plugins-table survivors through repositories
* test(server): plan 4 — collapse mcp tool test harnesses onto the ORM snapshot
* test(server): plan 4 — collapse nest service test harnesses onto the ORM snapshot
* fix(server): plan 3j close-out — serialized audit-chain appends, atomic metadata and scheduler limits, rollback and race proofs for the plugin repositories
* refactor(server): plan 4 — convert the program's orphaned raw-SQL callers
* fix(server): plan 4 — un-skip PARITY-009 (FK deleteRule and index-name parity)
* refactor(server): plan 4 — inline canAccessTrip/isOwner off DatabaseService (trip-domain services)
* refactor(server): plan 4 — inline canAccessTrip/isOwner off DatabaseService (plugins + MCP surfaces)
* fix(server): plan 4 — RULE12 paren-count scanner ignores string literals
The entity generator's RULE12_fixGarbledCheckExpressions CHECK-expression
paren-balance scanner counted every `(`/`)` character regardless of
whether it fell inside a single-quoted SQL string literal. A CHECK
expression like `status IN ('confirmed)', 'tentative')` has a literal `)`
inside its first string value; the scanner would hit depth 0 at that
in-string character and truncate the expression, losing its own real
closing paren. The scanner now tracks single-quote string state (handling
the doubled `''` SQLite escape) and skips parens while inside one.
Latent-bug fix — no shipped entity's CHECK expression has hit this shape
yet (3d's ledger: "nothing affected today").
* refactor(server): plan 4 — unify the trip-access predicate's Kysely copies
TripsRepository.findForViewer/listForUser/activeTrip each hand-wrote the
identical trip-access boolean (t.user_id = ? OR m.user_id IS NOT NULL)
through the Kysely expression builder. Task 7's security review (M1)
evaluated a shared helper and set it aside for time, falling back to the
TRIPREPO-041 cross-method parity test as a regression guard instead.
Extracted the boolean into one generic helper, tripAccessExpr
(_shared/trip-access.ts), following the reservation-visibility.ts
publicReservationExpr precedent: fully generic over <DB, TB> since the
predicate has no correlated subquery, so it composes across
TripSelectKyselyDB and ActiveTripKyselyDB without needing a narrower
fixed-alias shape. The LEFT JOIN itself stays hand-written at each call
site — tripSelectQuery's own docstring already explains why a shared join
helper can't be typed across these differently-joined outer queries.
feeds.service.ts and memories-access.service.ts no longer duplicate this
predicate at all (Task 2's facade-inline sweep already converted both onto
TripsRepository.findAccessible/getFeedTokenIfReachable/
listReachableActiveTrips, which read through the canonical MikroORM
QueryBuilder form, accessibleTripsQuery) — the remaining duplication this
task closes is the three Kysely copies inside this file.
TRIPREPO-041 (64/64 in the file) stays green as the unification's own
regression guard.
* fix(server): plan 4 — trek_photo_cache_meta.cache_key NOT NULL
The column was a bare TEXT PRIMARY KEY, which SQLite does not implicitly
make NOT NULL (unlike an INTEGER PRIMARY KEY rowid alias). Every writer
(TrekPhotoCacheMetaRepository.upsertMeta, the table's only INSERT path)
has always bound a real string — 3e's R5 confirmed this. Appends a new
migration rebuilding the table with cache_key NOT NULL (SQLite has no
ALTER COLUMN, so this follows the same rebuild recipe
Migration20200101020000 uses in the opposite direction) and updates the
entity/generated metadata to match. Schema tightening, not a behaviour
change.
* refactor(server): plan 4 — retire the safely-convertible string-form where conditions (rule 23)
Places.repository.ts's existsInTrip/findInTrip/findRaw/reclaimInputs/
listByTripAndIds and Trips.repository.ts's findPublicForShare all took a
raw `.where('col = ?', [v])` string condition even though their id/trip_id
parameters were already plain `number` (or, for findPublicForShare,
narrowed to `number` here after confirming its one caller,
share.service.ts#getSharedTripData, only ever passes a number sourced
from a Kysely-typed share_tokens row, never an unconverted URL param) —
converted all six to MikroORM's typed `.where({...})` filter object.
The remaining raw string-form conditions in src/db/repositories/** are
NOT converted here: they are the `number | string` raw-bind seam
findAccessible/isOwner's own docstrings describe (trip_id/id threaded
through unconverted from req.params), which structurally requires the
deferred guard-level single toRowId parse to land first — narrowing any
of those methods' signatures now would either break the '0x10'/'007' id
parity those docstrings warn about, or duplicate the deferred item's own
work ahead of it landing.
* refactor(server): plan 4 — trek-photos.repository.ts finishes its rename
3e Task 6 renamed the CLASS (TrekPhotosRepository -> TrekPhotoRegistrationService,
since the name collided with the generated ORM TrekPhotos.repository.ts) but
left the FILE and its test file's names unchanged. Renames both to
trek-photo-registration.service.ts / .test.ts.
The old path is kept as a thin re-export stub (the src/websocket.ts shape)
rather than repointed at every one of its ~20 importers in this pass: several
of those files sit in two sibling tasks' exclusively-owned windows on this
shared branch (Task 3's budget/packing/todo/accommodations/places ripple,
reached through tests/helpers/plugin-host.ts and mcp-test-controllers.ts;
Task 5c's held-back tests/unit/services/{trekPhotoMedia,conflictUpdate}.test.ts)
and are off limits here. Flagged for a follow-up once those tasks land: delete
the stub and repoint every remaining importer at ./trek-photo-registration.service.
* fix(server): plan 4 — plugin discovery's delete+reinsert pairs are atomic
install/discovery.ts#upsert refreshed a plugin's actions and settings-field
descriptors as two independent delete-then-reinsert pairs (DI5-DI8) with no
transaction spanning either pair, let alone both: a crash between a delete
and its own reinsert left that plugin with an EMPTY actions or
settings-field set until the next discovery run, instead of its previous
still-valid rows. Wraps both pairs in one uow.transactional, so a discovery
refresh for a plugin's descriptors is now all-or-nothing.
Deliberate behaviour change, named for the user per the task brief.
DiscoveryRepos grows a UnitOfWork; PluginRegistryService (the other
production caller, registry.service.ts) picks it up the same @Optional()
way PluginRuntimeService already does, with the same guard-throw. Updates
the two hand-constructed test call sites that actually exercise discovery
(discovery.test.ts, registry.test.ts) to pass a real UnitOfWork.
* refactor(server): plan 4 — facade inline sweep part B (rosterUserIds/getPlaceWithTags)
Inline DatabaseService.rosterUserIds onto TripMembersRepository.rosterUserIds
directly in budget.service.ts, budget.mcp.ts and todo.service.ts, and
DatabaseService.getPlaceWithTags onto PlacesRepository.findWithTagsAndRatings
in accommodations.service.ts (placesRepo was already injected there).
BudgetService/BudgetMcp/TodoService collapse their constructors, dropping
the now-fully-unused DatabaseService param (budget.module.ts/todo.module.ts
register TripMembers on forFeature). PackingService keeps DatabaseService as
a vestigial param behind an optional TripMembersRepository with a fallback
in tripRosterIds: an in-flight Task 5c file
(tests/unit/services/conflictUpdate.test.ts) hand-constructs PackingService
positionally without the new repository, so its arity cannot change this
task; the fallback keeps that file's DatabaseService.rosterUserIds spy
working until Task 4 drops the param with the class itself.
* test(server): plan 4 — constructor ripple for the rosterUserIds/getPlaceWithTags inline
Hand-built BudgetService/BudgetMcp/TodoService call sites drop the removed
DatabaseService constructor arg (budgetRepoArgs() now appends a
TripMembersRepository so most spread call sites need no other change);
budget.service.test.ts's rosterHas() helper and svc() factory move from a
spied DatabaseService to a stubbed TripMembersRepository. The
AccommodationsService helper (tests/helpers/accommodations-service.ts) and
its two direct callers drop the same arg. PackingService call sites are
untouched (its new param is optional, so every existing hand-built instance
still resolves rosterUserIds through the DatabaseService fallback).
* fix(server): plan 4 — thread the discovery UnitOfWork through PluginRuntimeService too
Complements the just-landed discovery atomicity fix (DiscoveryRepos.uow):
PluginRuntimeService's own discoveryRepos getter still built the bundle
without a uow field. Threads its already-injected, @Optional() uow through
so its own onApplicationBootstrap/reload/dev-link discovery calls also get
the transactional DI5-DI8 refresh, not just PluginRegistryService's.
No throwing guard here, unlike PluginRegistryService's: several hand-built
partial-DI-graph test instances of this class (boot-registry-order.test.ts,
in a sibling task's held file window) construct it with uow omitted and
exercise onApplicationBootstrap's discovery call directly. Discovery must
never refuse outright just because a test built a partial graph, so it
degrades to the pre-existing untransacted sequence when uow is absent
(DiscoveryRepos.uow's own docstring covers this), the same "boot must
never block app init" defensiveness this file already applies elsewhere.
* fix(server): plan 4 — guard-level single parse: verify + correct the overclaiming verifyTripAccess docstring (L-2)
TripAccessGuard/TripOwnerGuard already parse :tripId exactly once
(Number(), guarded by Number.isFinite) and hand the resolved TripAccess
row to the handler via request[TRIP_REQUEST_KEY], TripOwnerGuard reusing
TripAccessGuard's own lookup when both are on the same route rather than
re-querying — verified by reading both guards directly, no change needed
there.
PlacesService.verifyTripAccess's own docstring separately claimed its
returned `tid` gets "returned... for every downstream call to reuse
(never re-parsing)" (3c's Task 9 review, L-2, carried to Plan 4). Reading
every call site (not assumed) shows this is false: `.tid` has exactly one
reader (PlacesController.requireTrip itself), which discards it — none of
requireTrip's 13 callers read `.tid` off the trip it returns; each passes
the original raw tripId string on to the write/read method it calls next,
which toRowId-parses it again itself. That second parse cannot be
eliminated by this gate alone: the same service methods are called
directly by places.mcp.ts too, an entry point with no requireTrip gate at
all (its own numeric tripId is re-stringified, String(tripId), to call
them), so each method owns its own id validation regardless of entry
point. Threading `tid` all the way through would mean giving every one of
~15 methods a second, number-only call shape for the REST path alone to
use — a real refactor, out of this docstring fix's own scope. Corrected
the docstring to say so plainly instead of repeating the false claim.
* refactor(server): plan 4 — relocate JS7/10/13/14 off the journey-share fallback stub
JourneyShareTokensRepository's own JS7/JS10/JS13/JS14 Kysely reads were a
3g Task 3 fallback (Task 2's JourneyPhotosRepository/JourneyEntriesRepository/
JourneyEntryPhotosRepository were still mid-flight). Now that those
repositories are stable, relocate: JS7/JS10 (photo/asset validation joins)
onto JourneyPhotosRepository (already injected into JourneyShareService as
photosRepo, no constructor change); JS13 (public entry list) onto
JourneyEntriesRepository.listPublicEntries; JS14 (public per-entry photo
read) onto JourneyEntryPhotosRepository.listForPublicJourney, deduped
against that repository's own JP_COLUMNS select list instead of a
hand-duplicated copy. JourneyShareService gains two new @InjectRepository
params (both already registered in journey-domain.module.ts's forFeature),
rippled through mcp-test-controllers.ts and journey-share.service.test.ts
(P04/P05 parity tests now pin the new homes).
* refactor(server): plan 4 — document unreachable ?? default arms after single-row aggregates
3f Task 7's fix wave flagged a cluster of `row?.x ?? default` arms after
unqualified, ungrouped aggregate reads (MAX/COUNT/COALESCE(SUM,0)) as
"same class as OauthClients:147" but left them unexamined per-site. Decided
per site: document, don't delete — TypeScript still types
executeTakeFirst()'s result as `| undefined` even though SQL guarantees
exactly one row for these unqualified aggregates, so the optional chain
can't be removed without a non-null assertion (worse, not safer). Six
sites: JourneyEntries.repository.ts (maxSortOrderForDate JG42,
countStatsPlaces JG67), JourneyEntryPhotos.repository.ts
(maxSortOrderForEntry JG91), JourneyPhotos.repository.ts (maxSortOrder
JG88/JG99), VacayEntries.repository.ts (sumFraction VC1, sumCompFraction
VC2). No behavior change — comments only.
* refactor(server): plan 4 — unify the two user-data-erasure enqueue paths
UserCleanupService.erasePluginUserData (the account-deletion transaction's
own UC2/UC3 enqueue) and PluginRuntimeService.enqueueUserErasure (the
emitUserDeleted sink's post-commit enqueue) independently walked the
identical SELECT id, permissions FROM plugins + JSON.parse + hook:user-data
filter + INSERT OR IGNORE — and both genuinely run for every account
deletion, since every emitUserDeleted call site (auth.service.ts,
admin.service.ts, trip-members.service.ts's guest removal) fires
immediately after deleteUserCompletely.
Extracted the shared filter into enqueueHookUserDataErasures
(nest/plugins/user-erasure-enqueue.ts) and pointed both call sites at it.
UC2/UC3 also come off DatabaseService onto PluginsRepository/
PluginUserErasureQueueRepository in the same change (they were the last
raw statements standing in the way of sharing one implementation) — this
narrows the Plan 3b Task 5 "stays raw, owned by Plan 3j" ruling to UC1
only (plugin_user_config/plugin_oauth_tokens/plugin_oauth_state), which
still stays raw, unaffected. UserCleanupService's orphan-data-directory
scan (a plugin uninstalled with data retained) has no equivalent on the
enqueueUserErasure side and stays there, now via the same repository.
Both enqueue calls still run per deletion (INSERT OR IGNORE keeps this
idempotent) — this unifies the IMPLEMENTATION, not the call count; not
touching the emitUserDeleted event-sink wiring itself was a deliberate,
smaller-blast-radius choice for this task.
* refactor(server): plan 4 — narrow TripMembersRepository.remove/TripsRepository.setOwner to number
Both accepted trip_id: number | string per 3c's carry note (their "stays
loose for other callers" reasoning), pending the guard-level single parse
landing first. Re-checked every caller directly: setOwner's one production
caller (trip-members.service.ts#transferOwnership) already passes trip.id,
a real number resolved earlier in the same transaction; remove's callers
are trips.rpc.ts (num(), already a validated number), trips.mcp.ts (Zod-
typed tool input, already a number) and TripMembersController.removeMember
(the one genuine raw-string caller, :id off the route with no class-level
TripAccessGuard on this controller by design).
TripMembersController.removeMember now parses :id once (toRowId, not
Number() — rule 15's NaN-into-SQL trap) and threads the parsed number to
both its own access check and removeMember, instead of passing the raw
string through twice. TripMembersService.removeMember and both repository
methods narrow to number accordingly; setOwner's WHERE also moves off its
raw-bind escape hatch onto nativeUpdate now that trip_id is typed, and
remove's trip_id half moves onto a typed .where({ trip: trip_id }) filter
(user_id keeps its own raw bind — a different, still-live NaN-safety seam,
unrelated to this narrowing).
TRIPREPO-018 and TMEMREPO-023, which pinned the retired string-bind seam
on setOwner/remove, no longer typecheck against the narrowed signatures
and are removed with an explanatory comment in their place.
* refactor(server): plan 4 — U6 gate-level id parsing for todo item ids
Rule 21's carry from 3e Task 8's review: TodoController.update/.remove
passed the raw :id route string all the way to TodoItemsRepository,
relying on SQLite's column-affinity CAST to match it instead of a typed
filter. Parse :id ONCE at the controller (toRowId, matching Task 8a's
TripAccessGuard/removeMember shape), 404 on a non-canonical id, and thread
the number down through TodoService.updateItem/deleteItem into
TodoItemsRepository.findInTrip/existsInTrip/update/deleteById, all
narrowed from number | string to number. todo.rpc.ts's num()-derived
todoId no longer needs its String() wrapper. tripId stays string | number
— a separate, already-accepted carry (23c292f2f). Two new e2e tests pin
the non-numeric-id 404 at the gate.
* test(server): plan 4 — full-key parity tests for ShareTokensRepository (3h L4)
3h L4's carry: ShareTokensRepository (SH1-SH6/SH17/UC6) had zero tests.
17 cases pinning every read against the legacy statement run raw on the
same connection — findRawByTrip/findTokenByTrip with every nullable
column both null and set, findValidByToken/findTripAndShareMapByToken/
findTripIdByToken's shared token+expiry predicate (valid, future-expiry,
past-expiry, unknown token), plus insertNew/updateFlagsByTrip/deleteByTrip/
deleteByCreator's write correctness (deleteByCreator's cross-trip erasure
kept distinct from deleteByTrip's single-trip scope, per the repository's
own docstring). The listPublicForShare family (the other half of 3h L4)
is a separate, larger carry — not in this file.
* test(server): plan 4 — full-key parity for Reservations share/public-api reads (3d carry)
Task 8b-2 item 1 (partial): the 8 share.service.ts/public-api.service.ts
reads on ReservationsRepository flagged by the 3d Task 7 review as having
no repository-level toEqual(<legacy raw>) coverage (listEndpointsForShare,
listDayPositionsForShare, listPublicForShare, listPublicAccommodationsForShare,
listScheduledForPublicApi, listUnscheduledForPublicApi,
listAccommodationsForPublicApi, listUnplannedPlacesForPublicApi). 12 new
cases against the legacy statement run raw on the same connection.
* test(server): plan 4 — concurrency pins for boundaries-upsert and token-mint races (3d carry)
Task 8b-2 item 2: R7's two remaining un-transacted-statement races flagged
by the 3d Task 7 review (L4) but never pinned — RoadtripDayBoundariesService
.save's belongs-check-then-upsert, and FeedsService.generateTripToken's
read-then-write. Both tests pin today's actual outcome (an atomic ON
CONFLICT upsert survives cleanly; the token mint has a last-write-wins
loser) with the same concurrent-request-shape Promise.all/allSettled
pattern roadtrip.service.test.ts's existing R7 vias pin uses. Not a fix.
* test(server): plan 4 — full-key parity for Days/DayAssignments/Places roadtrip reads (3d carry)
Task 8b-2 item 1 (remainder): the 3 non-share/public-api reads from the 3d
Task 7 review's missing-parity list — DaysRepository.listPlanDays (RPL1),
DayAssignmentsRepository.listRoadtripVisits (RPL2, the correlated-subquery
LEFT JOIN), and PlacesRepository.isTrackInTrip (RT13, the review's
"findTrackInTrip" — the actual method name). Completes the 11-file carry
together with 434113937's 8 share/public-api reads.
* test(server): plan 4 — dedupe overlapping listPlanDays/isTrackInTrip parity blocks
235f03665 landed two versions of the same DaysRepository.listPlanDays and
PlacesRepository.isTrackInTrip parity coverage side by side (a merge
artifact from concurrent work on the same carry item). Keeps one block per
method, drops the duplicate describe/it blocks and their colliding test ids.
* test(server): plan 4 — budget calc suite onto real repositories (3e carry)
* test(server): plan 4 — at-rest encryption pins for AirTrail/doc-sync/webhook secrets (3h L3)
Task 8b-2 item 4: the three credential columns the 3h Task 7 review flagged
as having no at-rest pin — users.airtrail_api_key (AirtrailService#saveSettings),
document_connections.secrets (DocSyncConfigService's whole-secret-map
column), and trip_document_links.webhook_secret (createLink's per-binding
mint). Each test saves through the real service, reads the raw column via
better-sqlite3, asserts it is enc:v1:-prefixed ciphertext that never
contains the plaintext, and asserts the service's own decrypt path rounds
it back to the original value.
* test(server): plan 4 — at-rest encryption pins for AirTrail/doc-sync secrets (3h L3 carry)
Task 8b-2 item 4: the 3h Task 7 review's L3 finding ("users.airtrail_api_key
has no at-rest pin", "document_connections.secrets ... has no enc:v1: check",
"trip_document_links.webhook_secret - no at-rest pin"). Three targets, each
proven by reading the raw column and asserting the stored value is
enc:v1:-prefixed ciphertext that round-trips, never the plaintext:
UsersRepository.setAirtrailSettingsWithKey/getAirtrailConnRow at the
repository layer, AirtrailService.saveSettings/getAirtrailCredentials at the
service layer, and DocSyncConfigService's connection secrets map plus
createLink's webhook secret.
* test(server): plan 4 — drop duplicate AirTrail encryption repository test
Task 8b-2 item 4 follow-up: 6965869dd already covers
UsersRepository.setAirtrailSettingsWithKey/getAirtrailConnRow's at-rest
ciphertext at the service layer (airtrail.service.test.ts's
AIRTRAIL-SVC-ENC-001/002) plus the doc-sync secrets/webhook pins
(DOCSYNC-ENC-001/002); this repository-level file duplicated the same
AirTrail assertion a second time.
* test(server): plan 4 — atlas read-model parity remainder (3f L6 carry)
Task 8b-2 item 3 (atlas half): full-key toEqual(<legacy raw>) coverage for
the atlas read models the 3f Task 7 review's L6 finding listed as missing
(minus AT1/TRAVELER_OWNS-consumer, already landed) — AT2 (Places.
listForTripIds), AT3/AT28 (PlaceRegions.listCountryCodesForPlaceIds/
listForPlaceIds), AT5/AT10/AT43 (VisitedCountries.listCodesForUser/
listForUser), AT21/AT24/AT25 (VisitedRegions.listForUser/
listRegionCodesForCountry/findCountryCode), AT22 (HiddenRegions.listForUser),
AT23/AT40/AT44 (PlaceRegions.listDistinctRegionCodesForCountryAndPlaces/
countPlacesByCountryForTrip/listVisitedCountryCodesForUser), AT30/33/34
(BucketList.listForUser/findById/findForUser), AT41 (Places.
listAddressesForUser), AT42 (Trips.countTripsAndDaysForUser). New standalone
files for HiddenRegions/VisitedCountries/VisitedRegions/PlaceRegions, which
had none. AT6/45/46 (the TRAVELER_OWNS endpoint reads) are proven on ids
only by the existing consumer test — full-row parity for those three is
NOT done here (carried forward, same as the review's own open item).
* test(server): plan 4 — vacay read-model parity remainder (3f L6 carry)
Task 8b-2 item 3 (vacay half): full-key toEqual(<legacy raw>) coverage for
the vacay read models the 3f Task 7 review's L6 finding listed as missing
(minus VC81/82, already landed) — VacayPlans.findByOwner/findById (the
getPlanData/getStats composite's own plan read), VacayYears.listForPlan
(listYears), VacayCompanyHolidays.listForPlan (the company-holidays list),
VacayHolidayCalendars.listForPlan/findById (holiday-calendar reads),
VacayUserSettings.findForUser (user year settings), VacayUserYears.
findForYear (getStats rows, including the NULL vacation_days case the
review named explicitly), and VacayPlanMembers.listAvailableForFusion/
listPendingForPlan/listPendingForUser (the fusion and share pickers). Seven
new standalone files — only VacayShares had a repository-level test before
this. getSharedCalendars itself is a service-level composite over these
same reads plus VacayCompanyHolidays.listDatesForRange (already exercised
elsewhere); its own dedicated test is NOT added here.
* test(server): plan 4 — full-key parity for PackingItemsRepository.listPublicForShare (3h L4)
Task 8b-4a: no repository-level toEqual(<legacy raw>) coverage existed for
the share.service.ts SH13 read. Seeds Common items with every nullable
column both null and set, plus Personal and Shared-with-people items on
both sides of the is_private/owner/recipient predicate, and proves only
the Common tier surfaces.
* test(server): plan 4 — full-key parity for BudgetItemsRepository.listPublicForShare (3h L4)
Task 8b-4a: no repository-level toEqual(<legacy raw>) coverage existed for
the share.service.ts SH14 read. Seeds two items — every nullable column
set and every nullable column null — plus a foreign-trip item, and proves
the ORDER BY category ASC shape (unlike BG72's listAllForTrip, which has
none).
* test(server): plan 4 — full-key parity for CollabMessagesRepository.listPublicForShare (3h L4)
Task 8b-4a: no repository-level toEqual(<legacy raw>) coverage existed for
the share.service.ts SH16 read. Seeds a root message, a reply (reply_to
set), a deleted message (must be excluded) and a foreign-trip message, and
proves the narrower username/avatar-only join shape (no reply_text/
reply_username, unlike joinedQuery).
* test(server): plan 4 — full-key parity for PlacesRepository.listPublicForShare (3h L4)
Task 8b-4a: no repository-level toEqual(<legacy raw>) coverage existed for
the share.service.ts SH12 read. Seeds a categorised place with every
nullable column set and an uncategorised place with every nullable column
null, plus a foreign-trip place, and proves the named 20-column allow-list
never leaks an owner-only column (reservation_status, google_place_id,
…).
* test(server): plan 4 — full-key parity for DayAssignmentsRepository.listPublicForShare (3h L4)
Task 8b-4a: no repository-level toEqual(<legacy raw>) coverage existed for
the SH9 read. Seeds assignments across multiple days (one excluded day_id
never leaks in), every nullable place/assignment column both null and
set, and proves the six owner-only columns SharePublicAssignmentRow omits
(google_place_id, google_ftid, osm_id, amap_poi_id, stop_type,
fill_percent) never appear on the row at all.
* test(server): plan 4 — collapse remaining test harnesses; triage legacy migration tests
* test(server): plan 4 — todo controller test expects the gate-parsed item id (U6 follow-up)
* fix(server): add the missing numbered migration for the booked-night reseat step (#242)
reseatBookedNights (legacy step 242) was never invoked from any shipped
MikroORM migration -- only from the retired db/migrations.ts array --
so an install upgrading through the numbered chain never got the
one-time reorder. Adds Migration20200101040300, which calls the frozen
function through the native better-sqlite3 handle so it runs inside
the migration's own transaction.
orm-driver.ts's BoundSqliteConnection now also captures that handle
onto the field SqliteConnection.getNativeClient() reads, which its
createKyselyDialect() override previously left unset -- needed for
this migration (and any future one) to reach it in production, not
just under the bare test driver.
RESEAT-009 moves off the legacy createTables+runMigrations builder
onto the real Migrator via tests/helpers/migration-step.ts, plus a
new fresh-install guard (RESEAT-011).
* test(server): plan 4 — swap 4 of 5 straggler nest test harnesses off legacy schema builder
day-notes.service.test.ts, public-api-scopes.test.ts,
registration-invites.service.test.ts, trip-invite.service.test.ts onto
createSnapshotTestDb() via the async vi.mock idiom (5a/5b/5c precedent),
dropping their own hand-rolled createTables()+runMigrations() harness.
trip-invite.service.test.ts and registration-invites.service.test.ts
also drop their now-redundant DatabaseService wrapper (its .connection
was always just the same test db handle). expect( assertions unchanged.
user-cleanup.service.test.ts held back: its constructor call was
updated to match UserCleanupService's new EntityManager-based shape,
but deleteUserCompletely() now deadlocks against a real UnitOfWork
(reproduced in isolation, independent of this test file -- see the
report), which looks like a genuine bug in erasePluginUserData's new
MaintenanceRepository(em) call versus UnitOfWork.transactional(), not
a test-harness problem.
* test(server): plan 4 — move auto-backup.test.ts and demo-reset-path.test.ts off createTestDb()
Both build a schema db while 'fs'/'node:fs' are mocked (wholesale in
auto-backup.test.ts, selectively spied in demo-reset-path.test.ts) for
their own archiver/filesystem assertions, which broke
createSnapshotTestDb()'s read of the schema snapshot through
schema-snapshot.ts's own fs import.
auto-backup.test.ts: fs is mocked wholesale, so the snapshot db is now
built via a small helper that points fsMock's three calls at the real
filesystem (fetched through vi.importActual, bypassing the mock) just
long enough to build the db, before the test installs its own
existsSync stub -- never touching schema-snapshot.ts itself.
demo-reset-path.test.ts: fs.existsSync is selectively spied to answer
only for the baseline path, so the db is now built before that spy is
installed instead of after.
* test(server): plan 4 — retire the legacy-runner-only migration hygiene checks
migration-hygiene.test.ts deleted outright: every block in it (the
destructive-op allowlist, the empty-catch guard, the full-chain smoke)
scans or runs the legacy db/migrations.ts array being deleted this
plan, never the numbered src/db/migrations/*.ts chain, so there is
nothing in it to carry forward.
leg-mode-incoming.test.ts: deleted its first describe block (the
legacy-runner column-add + replay-safety smoke, also against
db/migrations.ts); the read-path parity block, already on the modern
createSnapshotTestDb() harness, is untouched.
* chore(server): delete the legacy schema/migration/seed builders
MikroORM's migrations are the only schema source now, including for
tests: src/db/schema.ts, src/db/migrations.ts and src/db/seeds.ts are
gone, along with tests/unit/db/schema-parity.test.ts (the parity gate
that guarded them, already red on 8a's cache_key NOT NULL) and
createTestDb() + its now-dead imports out of tests/helpers/test-db.ts
(its last two callers moved onto createSnapshotTestDb() this plan).
Their three entries drop from eslint.config.mjs's better-sqlite3
allow-list -- the files they exempted no longer exist.
Ruling 7's frozen files (migration-utils.ts, reseat-booked-nights.ts,
document-provider-seed.ts) and every numbered migration in
src/db/migrations/ are untouched.
Precondition grep (server/tests + server/src, from the task brief) is
now empty:
grep -rlE "from ['\"].*db/schema['\"]|from ['\"].*db/migrations['\"]|from ['\"].*db/seeds['\"]" server/tests server/src --include="*.ts"
* docs: plan 4 — the repository layer is the only data access path
DatabaseService/DatabaseModule are gone; queries go through repositories
(server/src/db/repositories/) and UnitOfWork (server/src/nest/database/
unit-of-work.ts) for transactions. MikroORM's migrations are the only
schema source, including for tests — the hand-kept schema.ts/migrations.ts/
seeds.ts test builders and their parity test are deleted. Documents the
db/database.ts (connection only) / db/orm-driver.ts (bound driver) /
UnitOfWork / repository shape, withRequestContext for non-HTTP entrypoints,
the better-sqlite3 ESLint restriction, and the entity generator (gen:entities/
check:entities) as the schema-parity guard. Corrects two stale nest/README.md
mentions (realtime.gateway.ts's now-repository constructor, the BE-Phase 1
trip-access bullet) and marks the legacy src/services/ migration recipe as a
historical changelog rather than current guidance.
* refactor(server): plan 4 — drop the 13 vestigial DatabaseService params/getters
Removes the now-dead DatabaseService injection (or private get db() getter)
from addons.service.ts, trips.service.ts, trip-invite.mcp.ts,
place-photo-cache.service.ts, trek-photo-registration.service.ts,
categories.mcp.ts, journey-domain.service.ts, plugins.service.ts,
plugin-runtime.service.ts, plugin-mcp-tools.service.ts, places.service.ts
and packing.service.ts — every one of them was fully repository-backed
already (Task 2/3's facade inline sweep), just still carrying the param.
PackingService's TripMembersRepository is required now (the
this.db.rosterUserIds fallback is gone with it) and PluginRuntimeService's
uow is no longer @Optional() — both moved ahead of the optional
registry?/hostFactory? params, since TypeScript refuses a required
parameter after an optional one; install/discovery.ts's DiscoveryRepos.uow
is required to match, and its upsert() always runs the descriptor
refresh inside one transaction instead of falling back to an
un-transacted sequence.
user-cleanup.service.ts's UC1 (the one genuinely live raw site, Plan 3b's
"stays raw" plugin-table trio) moves off DatabaseService onto a new
MaintenanceRepository.deletePluginUserData method — the rule-4-permitted
connection.execute() home, built from a directly-injected EntityManager.
Threads the active UnitOfWork.transactional's transaction context through
execute()'s ctx param: without it, a raw connection.execute() call issued
from inside deleteUserCompletely's open transaction contends for the same
single-connection checkout the transaction already holds and deadlocks
(never released, since the transaction is itself awaiting the call).
tests/unit/db/transaction-yield.test.ts's probe B already pinned this
exact hazard class for a raw better-sqlite3 statement; this is the same
mechanism reached through the ORM's connection pool instead.
nest/photos/trek-photos.repository.ts (the Plan 4 Task 8a re-export shim)
is deleted, with every importer repointed to trek-photo-registration.service
directly. The ~7 files that only imported the TripAccess/PlaceWithTags
type re-export from database.service.ts now import them from
Trips.repository.ts/Places.repository.ts directly, the actual single source.
* refactor(server): plan 4 — delete DatabaseService, DatabaseModule and database.tokens.ts
Grep gate confirmed zero src/ importers of DatabaseService left outside
these three files (Task 1/2/3's earlier conversions + this task's own
vestigial-param sweep). Deletes database.service.ts, database.module.ts
and database.tokens.ts, drops DatabaseModule from app.module.ts's imports
and the five other modules that still listed it
(accommodations/calendar/doc-sync/feeds/trip-members) — none of them had
a live DatabaseService injection left, so the import was already dead.
OrmModule is the module that survives DatabaseModule's deletion, per the
Phase 0 ledger's own ruling; untouched.
db/database.ts's `db` Proxy export itself stays, deliberately: ~190 test
files' vi.mock('…/db/database', …) factories return a { db: <mock
handle>, … } shape, and their own `import { db as testDb } from
'…/db/database'` is typed against this file's real exports regardless of
the runtime mock — vi.mock swaps the module at runtime, but tsc resolves
the import statically. Deleting the export would fail typecheck:tests
across the whole suite for a test-harness idiom this task's file set
doesn't own (Track B's territory). src/ has zero remaining importers, so
the ESLint no-restricted-imports gate this task also shrinks still holds
this file to its permanent allow-list entry either way.
* test(server): plan 4 — repoint the test suite off the deleted DatabaseService/DatabaseModule
Mechanical follow-through of the previous two commits across ~110 test
files:
- The 41 tests/e2e/*.e2e.test.ts suites composed DatabaseModule into their
partial Test.createTestingModule graphs; the import and the array entry
are dropped (nothing in any composed domain module injected
DatabaseService any more, so the entry was already dead weight).
- The shared test helpers (mcp-test-controllers.ts, plugin-host.ts,
accommodations-service.ts, notifications.ts, test-addons.ts,
test-uow.ts) each held a DatabaseService/DatabaseService-shaped param
used only for its raw better-sqlite3 handle; every one now takes that
handle directly, and every constructor call site the helpers make
(PackingService, PlacesService, JourneyDomainService,
PlacePhotoCacheService, TrekPhotoRegistrationService, TripsService,
UserCleanupService, AddonsService, PluginsService, PluginRuntimeService)
drops the removed param and, where PluginRuntimeService's uow is
involved, reorders it ahead of the optional registry?/hostFactory?
params to match the real constructor.
- ~60 further unit/integration test files hand-constructed one or more of
those same services directly; same fix, file by file. Four of them
(memories-access.service.test.ts, places.directions.test.ts,
places.service.test.ts, unified-memories.service.test.ts) also drop a
vi.spyOn(DatabaseService.prototype | instance, 'canAccessTrip' | 'isOwner'
| 'rosterUserIds' | 'getPlaceWithTags') spy left over from when those
methods delegated through DatabaseService — dead now that the services
read the owning repository directly.
- database-service.test.ts and database-service.delegation.test.ts tested
DatabaseService directly and are deleted with it.
- tests/unit/db/transaction-yield.test.ts's probe B, which pinned a raw
DatabaseService statement's dirty-read behaviour inside an open
transaction (rule 24), now issues the same raw better-sqlite3
statement directly against the shared test handle — the exact shape
DatabaseService.get/run used to wrap (this.conn.prepare(sql).get/run(),
bypassing MikroORM/Kysely entirely) — so the hazard it documents is
unchanged. Verified still green.
No expect(...) assertion changed in any file; only construction/import
plumbing. typecheck, typecheck:tests and the full touched-file run
(101 files / 2668 tests) are green, plus the compiled boot
(bootstrap.test.ts + boot-sweeps-request-context.test.ts) and one real
e2e boot file (trips.e2e.test.ts).
tests/unit/nest/user-cleanup.service.test.ts is deliberately NOT in this
commit — see the next one.
* test(server): plan 4 — finish user-cleanup.service.test.ts's harness swap; regression-test the UC1 transactional deadlock fix
This file arrived already modified and unstaged in the shared tree —
Task 6 (the parallel legacy-schema-deletion task) had swapped its DB
harness onto createSnapshotTestDb() and updated the UserCleanupService
construction to this task's new EntityManager-first shape while landing
its own commits. Finished here: USER-CLEANUP-005 ("survives a slim
schema without the plugin tables") passed a fake `{} as unknown as
EntityManager`, which doesn't reach the real UC1 path any more (the
previous raw DatabaseService.run swallowed everything in a try/catch
regardless); it now builds a real EntityManager bound to the slim
handle via sharedTestOrm(slim), so the per-statement query against the
missing plugin_user_config/plugin_oauth_tokens/plugin_oauth_state
tables is what's actually being proven caught, not a construction-time
throw.
USER-CLEANUP-006 through -010 (deleteUserCompletely, all of them
exercising UC1 inside the real uow.transactional wrap) are the
regression test for the previous commit's deadlock fix in
user-cleanup.service.ts/MaintenanceRepository.ts: before that fix, every
one of these hung and timed out. Green now, verified directly.
* chore(server): plan 4 — shrink the better-sqlite3 ESLint allow-list
Per ruling 6: database.service.ts's entry comes off (the file is
deleted). The five plugin entries (plugin-route-normalize.ts,
plugin-host-state.ts, install/discovery.ts, settings-defaults.ts,
signature-status.ts) come off too — re-verified none of the five import
better-sqlite3 or DatabaseService any more (3j's own conversion). The
src/demo/** blanket entry was already gone (3i's own task landed it).
reseat-booked-nights.ts and document-provider-seed.ts stay, with the
`// TODO(plan 4)` comment corrected: they're frozen forever (ruling 7),
invoked from inside numbered, already-shipped MikroORM migrations, never
Plan 4's or any future plan's to touch.
Permanent allow-list after this commit: src/db/database.ts,
src/db/orm-driver.ts, src/db/durability.ts (the driver homes),
src/nest/plugins/host/plugin-data.service.ts (3j's R-out-of-scope — a
plugin's own sqlite file is never TREK's schema), src/nest/backup/backup.impl.ts
(3i's R1, exactly the untrusted-upload-file probe), src/db/reseat-booked-nights.ts
and src/db/document-provider-seed.ts (frozen forever). src/db/{schema,migrations,seeds}.ts
entries were already removed by Task 6 when it deleted those files.
0 new lint errors; warning count unchanged at 2123 (well under the 2247
lean-gate ceiling) — every file the shrink touches was already fully
converted.
* refactor(server): plan 4 — U6 gate-level id parsing for budget item/settlement ids
Rule 21's 3e carry, same discipline 218f75d0f applied to todo: every
:id/:settlementId/:userId route param in BudgetController is parsed ONCE at
the gate with toRowId, matching the legacy affinity-seam "not found" outcome
for a malformed id on each route (404 'Budget item not found'/'Settlement
not found', except toggleMemberPaid — the one legacy handler that never
404'd an unknown item/member either, so a malformed id there skips the write
and keeps the same 200 { member } + Number(id)/Number(userId) broadcast
shape it always had).
The parsed numbers thread down through BudgetService's update/updateMembers/
setPayers/toggleMemberPaid/remove/updateSettlement/deleteSettlement (and
their updateBudgetItem/deleteBudgetItem/setItemPayers/getBudgetItem/
applySettlementUpdate/getSettlement internals) into BudgetItemsRepository's
getCurrency/findInTrip/existsInTrip/findForDelete/findById/update/deleteById
and BudgetSettlementsRepository's findWithUsers/findGuard/update/deleteById,
all narrowed from number | string to number; trip_id stays loose, a
separate, already-accepted carry. costs.rpc.ts's num()-derived itemId no
longer needs its String() wrapper on the update/delete calls; budget.mcp.ts
was already Zod-typed to number throughout. Two new e2e tests pin the
non-numeric-id 404 at the gate; controller/service unit tests cover the
narrowed call args and the toggleMemberPaid malformed-id parity case.
* refactor(server): plan 4 — U6 gate-level id parsing for packing item/bag/template ids
Rule 21's 3e carry, same discipline 218f75d0f applied to todo: every
:id/:bagId/:templateId/:userId route param in PackingController is parsed
ONCE at the gate with toRowId, matching the legacy affinity-seam "not found"
outcome for a malformed id on the routes with a pre-ORM Express precedent
(update/remove -> 'Item not found', updateBag/deleteBag/setBagMembers ->
'Bag not found', applyTemplate -> 'Template not found or empty').
#858's sharing/contributors routes (setSharing/clone/addContributor/
removeContributor) are native Nest code with no pre-ORM precedent (landed in
7eabf6066, after the migration) — a malformed id there just 404s the same
way an unknown one already does. removeContributor's :userId used to reach
contributorsRepo.deleteOne through a bare Number.parseInt(), the exact
NaN-into-SQL trap row-id.ts documents; it now parses through toRowId too.
The parsed numbers thread down through PackingService's updateItem/
setItemSharing/addContributor/removeContributor/cloneItem/deleteItem/
getItemPrivacy/updateBag/deleteBag/setBagMembers/applyTemplate, all narrowed
from number | string to number; tripId stays loose, a separate,
already-accepted carry. PackingItemsRepository's getPrivacy/findVisibleInTrip/
update/updateSharing/delete/findById, PackingBagsRepository's findInTrip/
update/findWithAssignee/delete and PackingTemplateItemsRepository.listForApply
narrow the same way. packing.rpc.ts's num()-derived itemId/bagId no longer
need their String() wrappers on the update/delete/updateBag/deleteBag/
setBagMembers calls; packing.mcp.ts was already Zod-typed to number
throughout. Two new e2e tests pin the non-numeric-id 404 at the gate;
controller/rpc unit tests cover the narrowed call args and the
removeContributor malformed-userId parity case.
AdminPackingTemplatesController (/api/admin/packing-templates) is out of
scope — a separate admin-gated surface with its own string-typed template
CRUD, not part of this trip-scoped controller's :id chain.
* test(server): plan 4 review — three pins catch up with the gate-parsed ids and the cache_key NOT NULL (M1–M3)
* fix(server): boot baselines legacy-runner installs before running MikroORM migrations (B1)
An install the retired positional runner migrated has a schema_version row
and no mikro_orm_migrations rows, so its first boot on this branch replayed
all 244 migrations over an already-migrated schema: eight refuse the boot,
and the replay-safe ones overwrite user data (step 26 rewrites every
day_assignments.assignment_time).
runSchemaBootstrap now records the baseline plus every migration whose
"Legacy migration step N" docstring is <= schema_version as executed, in one
transaction through the migrator's own storage, before the ordinary run
applies the rest. The step map is derived from the discovered migrations'
source, never hand-kept, and anything unmappable (a newer or malformed
schema_version, a duplicated, missing or out-of-order step) refuses the boot.
* test(server): boot the app on three legacy-runner fixtures to pin the B1 baseline
SQL dumps of databases the retired runner itself built: schema_version 205
(main at fa406b708), 242 (417d0445b, the runner's last commit) and 82
(v2.9.14, so seven of the eight non-replay-safe migrations still lie ahead
and run for the first time). Each gets canary rows: user-set assignment
times and a booked night.
buildApp() on each asserts the baseline and the applied rest in order, the
assignment times untouched, the booked-night reseat run exactly once on 205
and 82 and not at all on 242, schema_version kept, no half-built *_new
table, a schema identical to a fresh install's, and an idempotent re-run.
* refactor(server): demo-reset reads the live path off getRawConnection, not the db Proxy (m1)
demo-reset.ts was the one src/ consumer of the db Proxy left, reached
through a runtime require that a grep on `from` misses. It now imports
closeDb/getRawConnection/reinitialize statically, the way backup.impl.ts
does, so the Proxy genuinely has no src/ importer (the claim in database.ts
and server/CLAUDE.md now holds). The path test mocks the module with vi.mock
instead of teaching Node's require loader to answer for a .ts file.
* test(server): renumber the duplicate ASSIGNREPO/PLACEREPO test ids Plan 4 introduced (m3)
ASSIGNREPO-031/032 (the legacy-statement parity pair) become 034/035, and
the later PLACEREPO-030..038 block becomes 053..061, the next free ids, so
each id names one test again. No test body changes.
* refactor(server): derive the two restated public row types instead of copying their columns (m4)
JourneyPublicEntryPhotoRow restated JourneyPublicGalleryRow's nineteen
columns with only the parent key changed; it is now that row with
journey_id swapped for entry_id. PublicApiAssignedPlaceRow and its Kysely
table shape restated PlaceRow's columns; both now Pick them off PlaceRow.
Types only. The review's CPD method over Plan 4's new src lines drops from
about 3.4% to 0.64%.
* test(server): full-key parity for TripsRepository.findPublicForShare and VacaySharesRepository.listAvailableForShare (m5)
Neither read had any test reference. Each is now pinned with
toEqual(<legacy statement run raw on the same connection>), the
listPublicForShare family shape: SH7 on a filled and a NULL-heavy trip plus
a missing id (TRIPREPO-067/068), and VC90 over one world exercising every
exclusion (caller, guest, existing share, plan owner, accepted member) and
a missing plan.
* fix(server): the legacy baseline runs createTables() instead of marking it, atomically with the run (N1)
The legacy runner ran the running release's createTables() on every boot
before its pending steps, and about 30 tables exist only there. Marking the
baseline migration as executed left installs older than those tables (below
legacy step 68) failing with "no such table: photo_provider_fields" and, since
the rows were committed before the run, stuck half-baselined for every later
boot.
Only steps 1..N are recorded now, so the baseline's IF NOT EXISTS DDL runs
first, as the legacy boot did. The rows are logged inside the same
transaction as migrator.up({ transaction }), so a failed first boot records
nothing and the next boot baselines again.
A v66 fixture (the runner at 5be2e9b26) boots: 66 recorded, 178 applied,
canaries kept. Its two schema differences from a fresh install
(users.immich_access_token, reservations.accommodation_id INTEGER) come
from the legacy chain itself and are pinned as carried.
* fix(deps): sync the lockfiles with the bumped manifests and follow lucide's icon renames
feat/orm raised react to ^19.3.0 and several plugin-sdk dependencies without
regenerating the lockfiles, so npm ci failed on every CI job. The root
overrides now pin react 19.3.0, both lockfiles are regenerated with npm 11,
and the tests that select lucide icons by their old class names use the
current ones. Two tests cover the Immich prefs reads and the boot restore
branch that the coverage thresholds were missing.
* ci: give the server lint step an 8 GB heap for the type-aware rules
* test(server): keep the no-promise-as-value rule tester out of single-run mode on CI
With CI=true typescript-eslint infers single-run mode, builds the program
from the fixture file on disk and ignores the code each case passes in, so
all 24 invalid cases reported nothing on the runner. Both testers now set
disallowAutomaticSingleRunInference.
* refactor(server): name the new migrations after the first seven words of their purpose, like the rest
* fix(server): keep tsx a production dependency so image key rotation can load it
* test(server): re-pin the repositories branch floor at the measured 89.83%
* test(planner): keep the sidebar fixtures on past dates so the jump to today never fires in jsdom
* test(server): keep console output for failing tests only and teach Nest's logger LOG_LEVEL
* test(client): keep console output for failing tests only and answer the health probe
* test(client): drop the health handler, it races the admin page's first load
* chore(sonar): assert explicitly in two e2e cases, Number.NaN, and ignore S2187 on the legacy-upgrade fixtures
---------
Co-authored-by: Maurice <mauriceboe@icloud.com>
1832 lines
92 KiB
TypeScript
1832 lines
92 KiB
TypeScript
/**
|
|
* Unit tests for CalendarService. The cases moved 1:1 out of
|
|
* tests/unit/nest/trips.service.test.ts together with the code they cover
|
|
* (TRIP-SVC-001..002b, 020..027 and 048); the identifiers are unchanged so the
|
|
* diff shows a move rather than a rewrite, and the assertions still pin the
|
|
* emitted ICS byte for byte. Uses a real in-memory SQLite DB so the SQL runs.
|
|
*/
|
|
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
|
|
|
|
// ── DB setup ──────────────────────────────────────────────
|
|
|
|
vi.mock('../../../src/db/database', async () => {
|
|
|
|
const { createSnapshotTestDb } = await import('../../helpers/db-mock');
|
|
const db = createSnapshotTestDb();
|
|
const mock = {
|
|
db,
|
|
closeDb: () => {},
|
|
reinitialize: () => {},
|
|
getPlaceWithTags: () => null,
|
|
canAccessTrip: (tripId: any, userId: number) =>
|
|
db.prepare(`
|
|
SELECT t.id, t.user_id FROM trips t
|
|
LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ?
|
|
WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)
|
|
`).get(userId, tripId, userId),
|
|
isOwner: (tripId: any, userId: number) =>
|
|
!!db.prepare('SELECT id FROM trips WHERE id = ? AND user_id = ?').get(tripId, userId),
|
|
};
|
|
return mock;
|
|
});
|
|
|
|
|
|
vi.mock('../../../src/config', () => ({
|
|
JWT_SECRET: 'test-secret',
|
|
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
|
|
updateJwtSecret: () => {},
|
|
}));
|
|
const { broadcast } = vi.hoisted(() => ({ broadcast: vi.fn() }));
|
|
vi.mock('../../../src/websocket', () => ({ broadcast }));
|
|
|
|
import { db as testDb } from '../../../src/db/database';
|
|
import { resetTestDb } from '../../helpers/test-db';
|
|
import { createUser, createTrip, createReservation, createPlace, createDay, createDayAssignment, createDayNote } from '../../helpers/factories';
|
|
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
|
|
import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
|
|
import { ReservationsService } from '../../../src/nest/reservations/reservations.service';
|
|
import { ReservationsReadService } from '../../../src/nest/reservations/reservations-read.service';
|
|
import { BudgetService } from '../../../src/nest/budget/budget.service';
|
|
import { ExchangeRatesService } from '../../../src/nest/budget/exchange-rates.service';
|
|
import { CalendarService, foldICS } from '../../../src/nest/calendar/calendar.service';
|
|
import { CalendarModule } from '../../../src/nest/calendar/calendar.module';
|
|
import { expectRegisteredProvider } from '../../helpers/module-providers';
|
|
import { notificationsStub } from '../../helpers/notifications';
|
|
import { accommodationsOver } from '../../helpers/accommodations-service';
|
|
import { createTestUnitOfWork, createTestAppSettingsRepo, createTestReservationsRepo, createTestReservationEndpointsRepo, createTestReservationTravelersRepo, createTestReservationDayPositionsRepo, createTestDayAccommodationsRepo, createTestDaysRepo, createTestDayNotesRepo, createTestPlacesRepo, createTestDayAssignmentsRepo, createTestTripMembersRepo, createTestUsersRepo, createTestTripsRepo } from '../../helpers/test-uow';
|
|
import { createTestBudgetItemsRepo } from '../../helpers/files-repos';
|
|
import { budgetRepoArgs } from '../../helpers/budget-repos';
|
|
|
|
// Named `svc` so the moved cases below read exactly as they did on TripsService.
|
|
let budgetSvc: BudgetService;
|
|
let svc: CalendarService;
|
|
beforeAll(async () => {
|
|
budgetSvc = new BudgetService(new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), new ExchangeRatesService(), new RealtimeService(), await createTestUnitOfWork(testDb), ...(await budgetRepoArgs(testDb)));
|
|
svc = new CalendarService(
|
|
new ReservationsService(new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), budgetSvc, new RealtimeService(), notificationsStub(), new ReservationsReadService(await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb), await createTestReservationTravelersRepo(testDb)), await accommodationsOver(testDb), await createTestUnitOfWork(testDb), await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb), await createTestReservationTravelersRepo(testDb), await createTestReservationDayPositionsRepo(testDb), await createTestDayAccommodationsRepo(testDb), await createTestDaysRepo(testDb), await createTestPlacesRepo(testDb), await createTestDayAssignmentsRepo(testDb), await createTestTripMembersRepo(testDb), await createTestUsersRepo(testDb), await createTestTripsRepo(testDb), await createTestBudgetItemsRepo(testDb)),
|
|
await createTestTripsRepo(testDb), await createTestDaysRepo(testDb), await createTestDayNotesRepo(testDb), await createTestReservationsRepo(testDb),
|
|
);
|
|
});
|
|
|
|
beforeEach(() => {
|
|
resetTestDb(testDb);
|
|
});
|
|
|
|
afterAll(() => {
|
|
testDb.close();
|
|
});
|
|
|
|
describe('exportICS', () => {
|
|
it('TRIP-SVC-001: returns VCALENDAR wrapper', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, {
|
|
title: 'My Vacation',
|
|
start_date: '2025-06-01',
|
|
end_date: '2025-06-07',
|
|
});
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('BEGIN:VCALENDAR');
|
|
expect(ics).toContain('END:VCALENDAR');
|
|
});
|
|
|
|
it('TRIP-SVC-002: trip with start_date + end_date includes all-day VEVENT', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, {
|
|
title: 'Summer Holiday',
|
|
start_date: '2025-06-01',
|
|
end_date: '2025-06-07',
|
|
});
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('DTSTART;VALUE=DATE:20250601');
|
|
// DTEND is exclusive — the day *after* the last day, or the trip loses a day.
|
|
expect(ics).toContain('DTEND;VALUE=DATE:20250608');
|
|
expect(ics).toContain('SUMMARY:Summer Holiday');
|
|
});
|
|
|
|
describe('#1453 all-day DTEND is timezone-independent', () => {
|
|
const originalTz = process.env.TZ;
|
|
|
|
afterAll(() => {
|
|
process.env.TZ = originalTz;
|
|
});
|
|
|
|
// The old code did `new Date(date + 'T00:00:00')` — no Z, so parsed as *server-local*
|
|
// midnight — then setDate(+1) and .toISOString(). East of Greenwich that round-trip
|
|
// lands a day early, and since DTEND is exclusive the trip's last day was dropped.
|
|
// Only invisible in CI because containers default to TZ=UTC.
|
|
for (const tz of ['Europe/Berlin', 'Asia/Tokyo', 'Pacific/Kiritimati', 'America/New_York', 'UTC']) {
|
|
it(`TRIP-SVC-002b: DTEND is the day after the last day under TZ=${tz}`, async () => {
|
|
process.env.TZ = tz;
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, {
|
|
title: 'TZ Trip',
|
|
start_date: '2026-03-28',
|
|
end_date: '2026-03-30',
|
|
});
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('DTSTART;VALUE=DATE:20260328');
|
|
expect(ics).toContain('DTEND;VALUE=DATE:20260331');
|
|
});
|
|
}
|
|
|
|
it('TRIP-SVC-002c: a per-day all-day summary event has the same exclusive DTEND', async () => {
|
|
process.env.TZ = 'Asia/Tokyo';
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Day Note Trip' });
|
|
const day = createDay(testDb, trip.id, { date: '2026-03-30', day_number: 1 });
|
|
createDayNote(testDb, day.id, trip.id, { text: 'Pack the bags' });
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('DTSTART;VALUE=DATE:20260330');
|
|
expect(ics).toContain('DTEND;VALUE=DATE:20260331');
|
|
});
|
|
});
|
|
|
|
it('TRIP-SVC-003: reservation with full datetime (includes T) → DTSTART without VALUE=DATE', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Paris Trip' });
|
|
const reservation = createReservation(testDb, trip.id, {
|
|
title: 'Morning Flight',
|
|
type: 'flight',
|
|
});
|
|
testDb
|
|
.prepare('UPDATE reservations SET reservation_time=? WHERE id=?')
|
|
.run('2025-06-02T09:00', reservation.id);
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('DTSTART:20250602T090000');
|
|
expect(ics).not.toContain('DTSTART;VALUE=DATE');
|
|
});
|
|
|
|
it('TRIP-SVC-004: reservation with date-only → DTSTART;VALUE=DATE', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Paris Trip' });
|
|
const reservation = createReservation(testDb, trip.id, {
|
|
title: 'Hotel Check-in',
|
|
type: 'hotel',
|
|
});
|
|
testDb
|
|
.prepare('UPDATE reservations SET reservation_time=? WHERE id=?')
|
|
.run('2025-06-02', reservation.id);
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('DTSTART;VALUE=DATE:20250602');
|
|
});
|
|
|
|
it('TRIP-SVC-005: reservation metadata with flight info appears in DESCRIPTION', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Paris Trip' });
|
|
const reservation = createReservation(testDb, trip.id, {
|
|
title: 'CDG to JFK',
|
|
type: 'flight',
|
|
});
|
|
testDb
|
|
.prepare('UPDATE reservations SET reservation_time=?, metadata=? WHERE id=?')
|
|
.run(
|
|
'2025-06-02T09:00',
|
|
JSON.stringify({
|
|
airline: 'Air Test',
|
|
flight_number: 'AT100',
|
|
departure_airport: 'CDG',
|
|
arrival_airport: 'JFK',
|
|
}),
|
|
reservation.id
|
|
);
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('Airline: Air Test');
|
|
expect(ics).toContain('Flight: AT100');
|
|
});
|
|
|
|
it('TRIP-SVC-006: special characters in title are escaped', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Trip; First, Best' });
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('Trip\\; First\\, Best');
|
|
});
|
|
|
|
it('TRIP-SVC-007: throws NotFoundError for non-existent trip', async () => {
|
|
await expect(svc.exportICS(99999)).rejects.toThrow();
|
|
});
|
|
|
|
it('TRIP-SVC-008: returns a filename derived from trip title', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'My Trip 2025' });
|
|
|
|
const { filename } = await svc.exportICS(trip.id);
|
|
|
|
expect(filename).toMatch(/My.Trip.2025\.ics/);
|
|
});
|
|
|
|
// JS \s admitted U+3000 (and \v/\f) into the filename, and Node's header
|
|
// validation then threw ERR_INVALID_CHAR on the export route (#2165).
|
|
it('TRIP-SVC-008b: ideographic whitespace in the title folds to _ in the filename', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: '沖縄 4泊5日' });
|
|
|
|
expect((await svc.exportICS(trip.id)).filename).toBe('___4_5_.ics');
|
|
});
|
|
|
|
it('TRIP-SVC-008c: vertical tab and form feed fold too', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'A\vB\fC' });
|
|
|
|
expect((await svc.exportICS(trip.id)).filename).toBe('A_B_C.ics');
|
|
});
|
|
|
|
it('TRIP-SVC-009: reservation with end time includes DTEND', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Paris Trip' });
|
|
const reservation = createReservation(testDb, trip.id, {
|
|
title: 'Afternoon Tour',
|
|
type: 'activity',
|
|
});
|
|
testDb
|
|
.prepare('UPDATE reservations SET reservation_time=?, reservation_end_time=? WHERE id=?')
|
|
.run('2025-06-02T14:00', '2025-06-02T16:00', reservation.id);
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('DTEND:20250602T160000');
|
|
});
|
|
|
|
it('TRIP-SVC-024: flight with endpoint times but no reservation_time is included', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Paris Trip' });
|
|
const reservation = createReservation(testDb, trip.id, {
|
|
title: 'CDG → JFK',
|
|
type: 'flight',
|
|
});
|
|
// Confirmed flights store times per endpoint, never as reservation_time.
|
|
testDb.prepare('UPDATE reservations SET reservation_time=NULL, reservation_end_time=NULL WHERE id=?').run(reservation.id);
|
|
const insertEp = testDb.prepare(
|
|
'INSERT INTO reservation_endpoints (reservation_id, role, sequence, name, code, lat, lng, timezone, local_time, local_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
|
|
);
|
|
insertEp.run(reservation.id, 'from', 0, 'Paris CDG', 'CDG', 49.0, 2.5, 'Europe/Paris', '09:00', '2025-06-02');
|
|
insertEp.run(reservation.id, 'to', 1, 'New York JFK', 'JFK', 40.6, -73.8, 'America/New_York', '12:00', '2025-06-02');
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('SUMMARY:CDG → JFK');
|
|
// Departure endpoint zone drives DTSTART, arrival zone drives DTEND, so the
|
|
// subscriber sees TREK's zones instead of their own (#1453).
|
|
expect(ics).toContain('DTSTART;TZID=Europe/Paris:20250602T090000');
|
|
expect(ics).toContain('DTEND;TZID=America/New_York:20250602T120000');
|
|
expect(ics).not.toContain('DTSTART:20250602T090000');
|
|
// Each referenced zone gets a VTIMEZONE definition.
|
|
expect(ics).toContain('BEGIN:VTIMEZONE\r\nTZID:Europe/Paris');
|
|
expect(ics).toContain('BEGIN:VTIMEZONE\r\nTZID:America/New_York');
|
|
expect(ics).toContain('Route: CDG → JFK');
|
|
});
|
|
|
|
it('TRIP-SVC-024a: a flight that also carries reservation_time still uses per-side endpoint zones', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Paris Trip' });
|
|
const reservation = createReservation(testDb, trip.id, {
|
|
title: 'CDG → JFK',
|
|
type: 'flight',
|
|
});
|
|
// TransportModal stamps reservation_time/_end_time (departure/arrival) alongside
|
|
// the endpoints. That branch's only zone is the linked place — a flight has none —
|
|
// so it floated both ends in the subscribed feed; endpoints must win (#1453).
|
|
testDb.prepare('UPDATE reservations SET reservation_time=?, reservation_end_time=? WHERE id=?')
|
|
.run('2025-06-02T09:00', '2025-06-02T12:00', reservation.id);
|
|
const insertEp = testDb.prepare(
|
|
'INSERT INTO reservation_endpoints (reservation_id, role, sequence, name, code, lat, lng, timezone, local_time, local_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
|
|
);
|
|
insertEp.run(reservation.id, 'from', 0, 'Paris CDG', 'CDG', 49.0, 2.5, 'Europe/Paris', '09:00', '2025-06-02');
|
|
insertEp.run(reservation.id, 'to', 1, 'New York JFK', 'JFK', 40.6, -73.8, 'America/New_York', '12:00', '2025-06-02');
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('DTSTART;TZID=Europe/Paris:20250602T090000');
|
|
expect(ics).toContain('DTEND;TZID=America/New_York:20250602T120000');
|
|
// The bug was a floating DTSTART/DTEND (no TZID) from the reservation_time branch.
|
|
expect(ics).not.toContain('DTSTART:20250602T090000');
|
|
expect(ics).not.toContain('DTEND:20250602T120000');
|
|
});
|
|
|
|
it('TRIP-SVC-024c: a one-sided transport keeps the multi-day DTEND from reservation_end_time', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Rental Trip' });
|
|
const reservation = createReservation(testDb, trip.id, { title: 'Rental car', type: 'car_rental' });
|
|
// An imported rental geocodes the pickup only, so there is no second endpoint
|
|
// to carry the return. Before the endpoint branch took precedence, the return
|
|
// came from reservation_end_time; it still has to.
|
|
testDb.prepare('UPDATE reservations SET reservation_time=?, reservation_end_time=? WHERE id=?')
|
|
.run('2025-06-02T10:00', '2025-06-09T10:00', reservation.id);
|
|
testDb.prepare(
|
|
'INSERT INTO reservation_endpoints (reservation_id, role, sequence, name, code, lat, lng, timezone, local_time, local_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
|
|
).run(reservation.id, 'from', 0, 'Berlin', null, 52.5, 13.4, 'Europe/Berlin', '10:00', '2025-06-02');
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('DTSTART;TZID=Europe/Berlin:20250602T100000');
|
|
expect(ics).toContain('DTEND;TZID=Europe/Berlin:20250609T100000');
|
|
});
|
|
|
|
it('TRIP-SVC-024d: an untimed arrival endpoint still takes its DTEND from reservation_end_time', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Train Trip' });
|
|
const reservation = createReservation(testDb, trip.id, { title: 'ICE 1234', type: 'train' });
|
|
testDb.prepare('UPDATE reservations SET reservation_time=?, reservation_end_time=? WHERE id=?')
|
|
.run('2025-06-02T08:00', '2025-06-02T14:30', reservation.id);
|
|
const insertEp = testDb.prepare(
|
|
'INSERT INTO reservation_endpoints (reservation_id, role, sequence, name, code, lat, lng, timezone, local_time, local_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
|
|
);
|
|
insertEp.run(reservation.id, 'from', 0, 'Berlin Hbf', null, 52.5, 13.4, 'Europe/Berlin', '08:00', '2025-06-02');
|
|
// The destination was added without a clock — the arrival time only exists
|
|
// on the reservation itself.
|
|
insertEp.run(reservation.id, 'to', 1, 'Wien Hbf', null, 48.2, 16.4, 'Europe/Vienna', null, '2025-06-02');
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('DTSTART;TZID=Europe/Berlin:20250602T080000');
|
|
expect(ics).toContain('DTEND;TZID=Europe/Berlin:20250602T143000');
|
|
});
|
|
|
|
it('TRIP-SVC-024e: a lone timed endpoint without reservation_end_time stays a DTSTART', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Ferry Trip' });
|
|
const reservation = createReservation(testDb, trip.id, { title: 'Ferry', type: 'ferry' });
|
|
testDb.prepare('UPDATE reservations SET reservation_time=?, reservation_end_time=NULL WHERE id=?')
|
|
.run('2025-06-02T07:00', reservation.id);
|
|
testDb.prepare(
|
|
'INSERT INTO reservation_endpoints (reservation_id, role, sequence, name, code, lat, lng, timezone, local_time, local_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
|
|
).run(reservation.id, 'from', 0, 'Dover', null, 51.1, 1.3, 'Europe/London', '07:00', '2025-06-02');
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('DTSTART;TZID=Europe/London:20250602T070000');
|
|
// Nothing to end it with, so no DTEND may be invented (the trip's own all-day
|
|
// DTEND is VALUE=DATE, hence the narrower match).
|
|
expect(ics).not.toContain('DTEND;TZID=');
|
|
});
|
|
|
|
it('TRIP-SVC-024b: an invalid endpoint timezone degrades to floating time instead of crashing the export', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Bad TZ Trip' });
|
|
const reservation = createReservation(testDb, trip.id, { title: 'CDG → JFK', type: 'flight' });
|
|
testDb.prepare('UPDATE reservations SET reservation_time=NULL, reservation_end_time=NULL WHERE id=?').run(reservation.id);
|
|
const insertEp = testDb.prepare(
|
|
'INSERT INTO reservation_endpoints (reservation_id, role, sequence, name, code, lat, lng, timezone, local_time, local_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
|
|
);
|
|
// A stored/plugin-written timezone can be any string; it must never reach Intl.
|
|
// The bogus zone takes precedence over the coordinates (first.timezone || resolveZone).
|
|
insertEp.run(reservation.id, 'from', 0, 'Paris CDG', 'CDG', 49.0, 2.5, 'Not/AZone', '09:00', '2025-06-02');
|
|
insertEp.run(reservation.id, 'to', 1, 'New York JFK', 'JFK', 40.6, -73.8, 'garbage', '12:00', '2025-06-02');
|
|
|
|
const ics = (await svc.exportICS(trip.id)).ics;
|
|
// Falls back to a floating local time (no TZID) and never emits a bogus VTIMEZONE.
|
|
expect(ics).toContain('DTSTART:20250602T090000');
|
|
expect(ics).not.toContain('TZID=Not/AZone');
|
|
expect(ics).not.toContain('garbage');
|
|
});
|
|
|
|
it('TRIP-SVC-025: flight endpoint with no local_date is skipped (relative Day-N trips)', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Relative Trip' });
|
|
const reservation = createReservation(testDb, trip.id, {
|
|
title: 'Timeless Flight',
|
|
type: 'flight',
|
|
});
|
|
testDb.prepare('UPDATE reservations SET reservation_time=NULL WHERE id=?').run(reservation.id);
|
|
testDb.prepare(
|
|
'INSERT INTO reservation_endpoints (reservation_id, role, sequence, name, code, lat, lng, timezone, local_time, local_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
|
|
).run(reservation.id, 'from', 0, 'Origin', 'AAA', 1.0, 1.0, null, '09:00', null);
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).not.toContain('SUMMARY:Timeless Flight');
|
|
});
|
|
|
|
it('TRIP-SVC-026: timed assignment gets a TZID derived from the place coordinates', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Tokyo Trip' });
|
|
const day = createDay(testDb, trip.id, { date: '2025-06-02' });
|
|
// Tokyo coordinates → Asia/Tokyo via tz-lookup.
|
|
const place = createPlace(testDb, trip.id, { name: 'Senso-ji', lat: 35.7148, lng: 139.7967 });
|
|
const assignment = createDayAssignment(testDb, day.id, place.id);
|
|
testDb
|
|
.prepare('UPDATE day_assignments SET assignment_time=? WHERE id=?')
|
|
.run('09:00', assignment.id);
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('DTSTART;TZID=Asia/Tokyo:20250602T090000');
|
|
expect(ics).toContain('BEGIN:VTIMEZONE\r\nTZID:Asia/Tokyo');
|
|
expect(ics).not.toContain('DTSTART:20250602T090000');
|
|
});
|
|
|
|
it('CAL-011: a reservation_time with seconds is kept as is and a date-only end time emits no DTEND', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Second Precision' });
|
|
const reservation = createReservation(testDb, trip.id, { title: 'Guided Walk', type: 'activity' });
|
|
// Importers write both shapes: "…T14:00" (padded to seconds) and "…T14:00:00"
|
|
// (already 15 chars). Padding the second one again would produce a 17-char
|
|
// value that no client parses.
|
|
testDb
|
|
.prepare('UPDATE reservations SET reservation_time=?, reservation_end_time=? WHERE id=?')
|
|
.run('2025-06-02T14:00:00', '2025-06-03', reservation.id);
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('DTSTART:20250602T140000');
|
|
// The end value carries no clock time, so it cannot be a DTEND for a timed
|
|
// event; emitting the bare "20250603" would make the event span a nonsense
|
|
// range instead of being left open.
|
|
expect(ics).not.toContain('DTEND');
|
|
});
|
|
|
|
it('CAL-012: reservations with no placeable time are dropped instead of emitting a broken VEVENT', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Timeless' });
|
|
// Relative "Day N" trips store a clock time without a date; there is nothing
|
|
// to anchor it to, so the reservation must not reach the calendar at all.
|
|
const timeOnly = createReservation(testDb, trip.id, { title: 'Floating Dinner', type: 'restaurant' });
|
|
testDb.prepare('UPDATE reservations SET reservation_time=? WHERE id=?').run('19:30', timeOnly.id);
|
|
// A transport row whose endpoints were never imported has no fallback time either.
|
|
const noEndpoints = createReservation(testDb, trip.id, { title: 'Endpointless Train', type: 'transport' });
|
|
testDb.prepare('UPDATE reservations SET reservation_time=NULL WHERE id=?').run(noEndpoints.id);
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).not.toContain('SUMMARY:Floating Dinner');
|
|
expect(ics).not.toContain('SUMMARY:Endpointless Train');
|
|
// The trip itself has no dates and no days, so dropping both reservations
|
|
// leaves an event-free calendar rather than a partially filled one.
|
|
expect(ics).not.toContain('BEGIN:VEVENT');
|
|
});
|
|
|
|
it('CAL-013: endpoints without a stored timezone fall back to their coordinates', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'No Stored Zone' });
|
|
const reservation = createReservation(testDb, trip.id, { title: 'CDG to JFK', type: 'flight' });
|
|
testDb.prepare('UPDATE reservations SET reservation_time=NULL WHERE id=?').run(reservation.id);
|
|
const insertEp = testDb.prepare(
|
|
'INSERT INTO reservation_endpoints (reservation_id, role, sequence, name, code, lat, lng, timezone, local_time, local_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
|
|
);
|
|
// Endpoints created before the importer learned to store IANA zones have only
|
|
// coordinates. Without the lookup fallback both ends would go floating and the
|
|
// subscriber would see the flight in their own zone (#1453).
|
|
insertEp.run(reservation.id, 'from', 0, 'Paris CDG', 'CDG', 49.0, 2.5, null, '09:00', '2025-06-02');
|
|
insertEp.run(reservation.id, 'to', 1, 'New York JFK', 'JFK', 40.6, -73.8, null, '12:00', '2025-06-02');
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('DTSTART;TZID=Europe/Paris:20250602T090000');
|
|
expect(ics).toContain('DTEND;TZID=America/New_York:20250602T120000');
|
|
});
|
|
|
|
it('CAL-014: a single-endpoint transport emits DTSTART only', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'One Way' });
|
|
const reservation = createReservation(testDb, trip.id, { title: 'Airport Transfer', type: 'transport' });
|
|
testDb.prepare('UPDATE reservations SET reservation_time=NULL WHERE id=?').run(reservation.id);
|
|
// Only the departure was imported. Using it for DTEND as well would emit a
|
|
// zero-length event; leaving DTEND out lets clients apply their default duration.
|
|
testDb.prepare(
|
|
'INSERT INTO reservation_endpoints (reservation_id, role, sequence, name, code, lat, lng, timezone, local_time, local_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
|
|
).run(reservation.id, 'from', 0, 'Paris CDG', 'CDG', 49.0, 2.5, 'Europe/Paris', '09:00', '2025-06-02');
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('DTSTART;TZID=Europe/Paris:20250602T090000');
|
|
expect(ics).not.toContain('DTEND');
|
|
});
|
|
|
|
it('CAL-015: a timed assignment carries its notes and address into DESCRIPTION and LOCATION', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Guided Day' });
|
|
const day = createDay(testDb, trip.id, { date: '2025-06-02' });
|
|
const place = createPlace(testDb, trip.id, { name: 'Louvre', lat: 48.8606, lng: 2.3376 });
|
|
testDb.prepare("UPDATE places SET address = 'Rue de Rivoli' WHERE id = ?").run(place.id);
|
|
const withNotes = createDayAssignment(testDb, day.id, place.id, { notes: 'meet the guide' });
|
|
testDb.prepare('UPDATE day_assignments SET assignment_time=? WHERE id=?').run('09:00', withNotes.id);
|
|
const withoutNotes = createDayAssignment(testDb, day.id, place.id);
|
|
testDb.prepare('UPDATE day_assignments SET assignment_time=? WHERE id=?').run('11:00', withoutNotes.id);
|
|
|
|
const ics = (await svc.exportICS(trip.id)).ics.replace(/\r\n /g, '');
|
|
|
|
// Notes come first and the address is appended on its own line; dropping the
|
|
// separator would glue them into one unreadable run.
|
|
expect(ics).toContain('DESCRIPTION:meet the guide\\nRue de Rivoli');
|
|
// Without notes the address must start the description rather than a stray newline.
|
|
expect(ics).toContain('DESCRIPTION:Rue de Rivoli\r\n');
|
|
expect(ics).toContain('LOCATION:Rue de Rivoli');
|
|
});
|
|
|
|
it('CAL-016: a day without a date is skipped and a titled day uses its own title', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Mixed Days' });
|
|
// Days of a relative "Day N" trip have no date; they cannot be placed on a
|
|
// calendar, and emitting them produced a VEVENT with an empty DTSTART.
|
|
const ghost = createDay(testDb, trip.id, { title: 'Ghost Day' });
|
|
createDayNote(testDb, ghost.id, trip.id, { text: 'never exported' });
|
|
const named = createDay(testDb, trip.id, { date: '2025-06-02', title: 'Museum Day' });
|
|
const place = createPlace(testDb, trip.id, { name: 'Bare Spot' });
|
|
createDayAssignment(testDb, named.id, place.id);
|
|
|
|
const ics = (await svc.exportICS(trip.id)).ics.replace(/\r\n /g, '');
|
|
|
|
expect(ics).not.toContain('Ghost Day');
|
|
expect(ics).not.toContain('never exported');
|
|
// A day with a title must not be renamed to "Day <n>".
|
|
expect(ics).toContain('SUMMARY:Museum Day');
|
|
// No address and no notes → the bullet stays bare, with no empty "()" or dash.
|
|
expect(ics).toContain('DESCRIPTION:• Bare Spot\r\n');
|
|
});
|
|
|
|
it('CAL-017: a reservation with no type, metadata or notes emits no empty DESCRIPTION', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Bare' });
|
|
const reservation = createReservation(testDb, trip.id, { title: 'Bare Booking', type: 'hotel' });
|
|
// Rows imported before `type` became mandatory still exist in prod. An empty
|
|
// DESCRIPTION line is invalid enough for some clients to reject the file.
|
|
testDb
|
|
.prepare('UPDATE reservations SET type=NULL, reservation_time=? WHERE id=?')
|
|
.run('2025-06-02', reservation.id);
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('SUMMARY:Bare Booking');
|
|
expect(ics).not.toContain('DESCRIPTION');
|
|
});
|
|
|
|
it('CAL-018: flight metadata with only one airport emits only that side of the route', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Half Routes' });
|
|
const inbound = createReservation(testDb, trip.id, { title: 'Inbound', type: 'flight' });
|
|
const outbound = createReservation(testDb, trip.id, { title: 'Outbound', type: 'flight' });
|
|
const setMeta = testDb.prepare('UPDATE reservations SET reservation_time=?, metadata=? WHERE id=?');
|
|
// A hand-entered flight often has one airport only; the missing side must be
|
|
// left out instead of printing "To: undefined".
|
|
setMeta.run('2025-06-02T09:00', JSON.stringify({ arrival_airport: 'JFK' }), inbound.id);
|
|
setMeta.run('2025-06-09T09:00', JSON.stringify({ departure_airport: 'CDG' }), outbound.id);
|
|
|
|
const ics = (await svc.exportICS(trip.id)).ics.replace(/\r\n /g, '');
|
|
|
|
expect(ics).toContain('DESCRIPTION:Type: flight\\nTo: JFK\r\n');
|
|
expect(ics).toContain('DESCRIPTION:Type: flight\\nFrom: CDG\r\n');
|
|
});
|
|
|
|
it('CAL-019: legs and endpoints without names produce no Route line', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Nameless' });
|
|
const legs = createReservation(testDb, trip.id, { title: 'Codeless Legs', type: 'flight' });
|
|
// Multi-leg metadata whose legs carry no airports would otherwise render
|
|
// "Route: " with nothing after it.
|
|
testDb.prepare('UPDATE reservations SET reservation_time=?, metadata=? WHERE id=?')
|
|
.run('2025-06-02T09:00', JSON.stringify({ legs: [{}, {}] }), legs.id);
|
|
const ferry = createReservation(testDb, trip.id, { title: 'Nameless Ferry', type: 'transport' });
|
|
testDb.prepare('UPDATE reservations SET reservation_time=NULL WHERE id=?').run(ferry.id);
|
|
const insertEp = testDb.prepare(
|
|
'INSERT INTO reservation_endpoints (reservation_id, role, sequence, name, code, lat, lng, timezone, local_time, local_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
|
|
);
|
|
// Same for endpoints with neither a code nor a name: the derived route would
|
|
// collapse to a single arrow between two blanks.
|
|
insertEp.run(ferry.id, 'from', 0, '', null, 1.0, 1.0, null, null, '2025-06-03');
|
|
insertEp.run(ferry.id, 'to', 1, '', null, 1.1, 1.1, null, null, '2025-06-03');
|
|
|
|
const ics = (await svc.exportICS(trip.id)).ics.replace(/\r\n /g, '');
|
|
|
|
expect(ics).toContain('SUMMARY:Codeless Legs');
|
|
expect(ics).toContain('SUMMARY:Nameless Ferry');
|
|
expect(ics).not.toContain('Route:');
|
|
});
|
|
|
|
it('CAL-043: a segment with its own booking reference gets its own Confirmation line (#1943)', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Layover' });
|
|
const flight = createReservation(testDb, trip.id, { title: 'FRA to HND', type: 'flight' });
|
|
testDb.prepare('UPDATE reservations SET reservation_time=?, confirmation_number=?, metadata=? WHERE id=?').run(
|
|
'2025-06-02T09:00', 'BOOK1',
|
|
JSON.stringify({ legs: [
|
|
{ from: 'FRA', to: 'BER', confirmation_number: 'ABC123' },
|
|
{ from: 'BER', to: 'HND', confirmation_number: 'XYZ789' },
|
|
] }),
|
|
flight.id,
|
|
);
|
|
|
|
const ics = (await svc.exportICS(trip.id)).ics.replace(/\r\n /g, '');
|
|
|
|
expect(ics).toContain(
|
|
'DESCRIPTION:Type: flight\\nConfirmation: BOOK1\\nRoute: FRA → BER → HND'
|
|
+ '\\nConfirmation FRA-BER: ABC123\\nConfirmation BER-HND: XYZ789\r\n'
|
|
);
|
|
});
|
|
|
|
it('CAL-044: a multi-leg flight without per-segment references reads exactly as before', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Layover' });
|
|
const flight = createReservation(testDb, trip.id, { title: 'FRA to HND', type: 'flight' });
|
|
testDb.prepare('UPDATE reservations SET reservation_time=?, confirmation_number=?, metadata=? WHERE id=?').run(
|
|
'2025-06-02T09:00', 'BOOK1',
|
|
JSON.stringify({ legs: [{ from: 'FRA', to: 'BER' }, { from: 'BER', to: 'HND' }] }),
|
|
flight.id,
|
|
);
|
|
|
|
const ics = (await svc.exportICS(trip.id)).ics.replace(/\r\n /g, '');
|
|
|
|
// Byte parity for every feed that exists today: the description ends after
|
|
// the route line, so no subscriber sees a changed event.
|
|
expect(ics).toContain('DESCRIPTION:Type: flight\\nConfirmation: BOOK1\\nRoute: FRA → BER → HND\r\n');
|
|
});
|
|
|
|
it('CAL-045: a connecting flight with times on every leg becomes one event per leg (#2389)', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Layover' });
|
|
const d1 = createDay(testDb, trip.id, { date: '2025-06-02' });
|
|
const d2 = createDay(testDb, trip.id, { date: '2025-06-03' });
|
|
const flight = createReservation(testDb, trip.id, { title: 'FRA to HND', type: 'flight' });
|
|
testDb.prepare('UPDATE reservations SET reservation_time=?, confirmation_number=?, metadata=? WHERE id=?').run(
|
|
'2025-06-02T09:00', 'BOOK1',
|
|
JSON.stringify({ legs: [
|
|
{ from: 'FRA', to: 'BER', airline: 'LH', flight_number: '1', dep_day_id: d1.id, dep_time: '09:00', arr_day_id: d1.id, arr_time: '10:10' },
|
|
{ from: 'BER', to: 'HND', airline: 'LH', flight_number: '2', confirmation_number: 'SEG2', dep_day_id: d1.id, dep_time: '12:30', arr_day_id: d2.id, arr_time: '07:45' },
|
|
] }),
|
|
flight.id,
|
|
);
|
|
|
|
const ics = (await svc.exportICS(trip.id)).ics.replace(/\r\n /g, '');
|
|
|
|
expect(ics).toContain(`UID:trek-res-leg1-${flight.id}@trek`);
|
|
expect(ics).toContain(`UID:trek-res-leg2-${flight.id}@trek`);
|
|
expect(ics).not.toContain(`UID:trek-res-${flight.id}@trek`);
|
|
expect(ics).toContain('DTSTART:20250602T090000\r\nDTEND:20250602T101000\r\nSUMMARY:FRA to HND: FRA → BER');
|
|
// The second leg lands the next morning, and its own reference rides along.
|
|
expect(ics).toContain('DTSTART:20250602T123000\r\nDTEND:20250603T074500\r\nSUMMARY:FRA to HND: BER → HND');
|
|
expect(ics).toContain('DESCRIPTION:LH 2\\nConfirmation: SEG2\\nLeg 2 of 2\\nType: flight');
|
|
expect(ics).toContain('LOCATION:BER\r\n');
|
|
});
|
|
|
|
it('CAL-1807: a cruise with ports of call is one event per sailing', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Baltic' });
|
|
const d1 = createDay(testDb, trip.id, { date: '2025-06-02' });
|
|
const d2 = createDay(testDb, trip.id, { date: '2025-06-03' });
|
|
const cruise = createReservation(testDb, trip.id, { title: 'Baltic cruise', type: 'cruise' });
|
|
testDb.prepare('UPDATE reservations SET reservation_time=?, metadata=? WHERE id=?').run(
|
|
'2025-06-02T17:00',
|
|
JSON.stringify({ legs: [
|
|
{ from: 'Kiel', to: 'Tallinn', dep_day_id: d1.id, dep_time: '17:00', arr_day_id: d2.id, arr_time: '09:00' },
|
|
{ from: 'Tallinn', to: 'Kiel', dep_day_id: d2.id, dep_time: '18:00', arr_day_id: d2.id, arr_time: '23:00' },
|
|
] }),
|
|
cruise.id,
|
|
);
|
|
const ics = (await svc.exportICS(trip.id)).ics.replace(/\r\n /g, '');
|
|
expect(ics).toContain('SUMMARY:Baltic cruise: Kiel → Tallinn');
|
|
expect(ics).toContain('SUMMARY:Baltic cruise: Tallinn → Kiel');
|
|
expect(ics).toContain(`UID:trek-res-leg2-${cruise.id}@trek`);
|
|
});
|
|
|
|
it('CAL-2389b: legs take their zones and names from one endpoint per airport (#2389)', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Layover' });
|
|
const d1 = createDay(testDb, trip.id, { date: '2025-06-02' });
|
|
const flight = createReservation(testDb, trip.id, { title: 'Via Frankfurt', type: 'flight' });
|
|
testDb.prepare('UPDATE reservations SET reservation_time=?, metadata=? WHERE id=?').run(
|
|
'2025-06-02T09:00',
|
|
JSON.stringify({ legs: [
|
|
{ dep_day_id: d1.id, dep_time: '09:00', arr_day_id: d1.id, arr_time: '10:00' },
|
|
{ dep_day_id: d1.id, dep_time: '12:00', arr_day_id: d1.id, arr_time: '15:00' },
|
|
] }),
|
|
flight.id,
|
|
);
|
|
const insertEp = testDb.prepare(
|
|
'INSERT INTO reservation_endpoints (reservation_id, role, sequence, name, code, lat, lng, timezone, local_time, local_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
|
|
);
|
|
insertEp.run(flight.id, 'from', 0, 'Paris CDG', 'CDG', 49.0, 2.5, 'Europe/Paris', '09:00', '2025-06-02');
|
|
// No stored zone here: it is worked out from the coordinates.
|
|
insertEp.run(flight.id, 'stop', 1, 'Frankfurt', 'FRA', 50.03, 8.57, null, '12:00', '2025-06-02');
|
|
insertEp.run(flight.id, 'to', 2, 'London LHR', 'LHR', 51.47, -0.45, 'Europe/London', '15:00', '2025-06-02');
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('DTSTART;TZID=Europe/Paris:20250602T090000');
|
|
expect(ics).toContain('DTEND;TZID=Europe/Berlin:20250602T100000');
|
|
expect(ics).toContain('DTSTART;TZID=Europe/Berlin:20250602T120000');
|
|
expect(ics).toContain('DTEND;TZID=Europe/London:20250602T150000');
|
|
expect(ics).toContain('SUMMARY:Via Frankfurt: CDG → FRA');
|
|
expect(ics).toContain('SUMMARY:Via Frankfurt: FRA → LHR');
|
|
});
|
|
|
|
it('CAL-046: a leg without a departure clock keeps the single event', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Layover' });
|
|
const d1 = createDay(testDb, trip.id, { date: '2025-06-02' });
|
|
const flight = createReservation(testDb, trip.id, { title: 'FRA to HND', type: 'flight' });
|
|
testDb.prepare('UPDATE reservations SET reservation_time=?, metadata=? WHERE id=?').run(
|
|
'2025-06-02T09:00',
|
|
JSON.stringify({ legs: [
|
|
{ from: 'FRA', to: 'BER', dep_day_id: d1.id, dep_time: '09:00' },
|
|
{ from: 'BER', to: 'HND', dep_day_id: d1.id },
|
|
] }),
|
|
flight.id,
|
|
);
|
|
|
|
const ics = (await svc.exportICS(trip.id)).ics;
|
|
expect(ics).toContain(`UID:trek-res-${flight.id}@trek`);
|
|
expect(ics).not.toContain('res-leg');
|
|
});
|
|
|
|
it('CAL-020: an empty trip title falls back for SUMMARY, X-WR-CALNAME and the filename', async () => {
|
|
const { user } = createUser(testDb);
|
|
// The title is only NOT NULL, not non-empty; an empty one used to produce
|
|
// "SUMMARY:" and a filename of ".ics".
|
|
const trip = createTrip(testDb, user.id, { title: '', start_date: '2025-06-01', end_date: '2025-06-02' });
|
|
|
|
const { ics, filename } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('X-WR-CALNAME:TREK Trip');
|
|
expect(ics).toContain('SUMMARY:Trip');
|
|
expect(filename).toBe('trek-trip.ics');
|
|
});
|
|
|
|
it('CAL-021: a corrupt day date degrades the VTIMEZONE offset instead of throwing', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Corrupt Date' });
|
|
// days.date is free-form TEXT; a legacy/imported row can hold a date that no
|
|
// parser accepts. The representative date reaches Intl through the VTIMEZONE
|
|
// fallback, and Intl throws a RangeError on an invalid Date — which would take
|
|
// the whole export (and the trip's slot in the all-trips feed) down with it.
|
|
const day = createDay(testDb, trip.id, { date: '2025-13-45' });
|
|
const place = createPlace(testDb, trip.id, { name: 'Senso-ji', lat: 35.7148, lng: 139.7967 });
|
|
const assignment = createDayAssignment(testDb, day.id, place.id);
|
|
testDb.prepare('UPDATE day_assignments SET assignment_time=? WHERE id=?').run('09:00', assignment.id);
|
|
|
|
const ics = (await svc.exportICS(trip.id)).ics;
|
|
|
|
expect(ics).toContain('DTSTART;TZID=Asia/Tokyo:20251345T090000');
|
|
expect(ics).toContain('BEGIN:VTIMEZONE\r\nTZID:Asia/Tokyo');
|
|
expect(ics).toContain('TZOFFSETFROM:+0000');
|
|
expect(ics).toContain('TZOFFSETTO:+0000');
|
|
});
|
|
|
|
it('CAL-022: the timezone cache stays correct after it hits its 1000-entry bound', async () => {
|
|
const { user } = createUser(testDb);
|
|
const bulkTrip = createTrip(testDb, user.id, { title: 'Cache Filler' });
|
|
const realTrip = createTrip(testDb, user.id, { title: 'After The Bound' });
|
|
|
|
const insertRes = testDb.prepare('INSERT INTO reservations (trip_id, title, type, reservation_time) VALUES (?, ?, ?, NULL)');
|
|
const insertEp = testDb.prepare(
|
|
'INSERT INTO reservation_endpoints (reservation_id, role, sequence, name, code, lat, lng, timezone, local_time, local_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
|
|
);
|
|
// Endpoint timezones are free-form strings written by importers and plugins, so
|
|
// the validity cache is keyed by attacker-ish input and has to be bounded. Push
|
|
// it past the bound in one export.
|
|
testDb.transaction(() => {
|
|
for (let i = 0; i < 1010; i++) {
|
|
const resId = insertRes.run(bulkTrip.id, `Bulk ${i}`, 'transport').lastInsertRowid as number;
|
|
insertEp.run(resId, 'from', 0, `Stop ${i}`, null, 49.0, 2.5, `Bogus/Zone-${i}`, '09:00', '2025-06-02');
|
|
}
|
|
})();
|
|
|
|
const bulk = (await svc.exportICS(bulkTrip.id)).ics;
|
|
// Every one of them has to reach the zone check — otherwise the bound is never
|
|
// approached and this case would pass without exercising anything.
|
|
expect(bulk).toContain('SUMMARY:Bulk 0');
|
|
expect(bulk).toContain('SUMMARY:Bulk 1009');
|
|
expect(bulk).toContain('DTSTART:20250602T090000');
|
|
expect(bulk).not.toContain('TZID=Bogus/Zone-0:');
|
|
|
|
const reservation = createReservation(testDb, realTrip.id, { title: 'CDG to JFK', type: 'flight' });
|
|
testDb.prepare('UPDATE reservations SET reservation_time=NULL WHERE id=?').run(reservation.id);
|
|
insertEp.run(reservation.id, 'from', 0, 'Paris CDG', 'CDG', 49.0, 2.5, 'Europe/Paris', '09:00', '2025-06-02');
|
|
|
|
// Clearing the cache must make later zones be re-checked. A regression that
|
|
// evicted by writing `false` instead would silently strip the TZID from every
|
|
// export after the thousandth distinct zone string.
|
|
const { ics } = await svc.exportICS(realTrip.id);
|
|
expect(ics).toContain('DTSTART;TZID=Europe/Paris:20250602T090000');
|
|
expect(ics).toContain('BEGIN:VTIMEZONE\r\nTZID:Europe/Paris');
|
|
});
|
|
|
|
it('CAL-032: an all-day booking with an end date spans the whole range', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Festival Trip' });
|
|
const reservation = createReservation(testDb, trip.id, { title: 'Music Festival', type: 'event' });
|
|
// A date-only start/end pair is what the booking import writes for an all-day
|
|
// multi-day event. Without a DTEND the RFC reads the event as a single day, so
|
|
// the booking collapsed onto its first day (#1869).
|
|
testDb
|
|
.prepare('UPDATE reservations SET reservation_time=?, reservation_end_time=? WHERE id=?')
|
|
.run('2026-08-26', '2026-08-30', reservation.id);
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
// DTEND is exclusive, so the day after the last day of the booking.
|
|
expect(ics).toContain('DTSTART;VALUE=DATE:20260826\r\nDTEND;VALUE=DATE:20260831');
|
|
});
|
|
|
|
it('CAL-033: a timed end time on an all-day booking still yields a VALUE=DATE DTEND', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Mixed Precision' });
|
|
const reservation = createReservation(testDb, trip.id, { title: 'Cottage', type: 'other' });
|
|
// Mixing DTSTART;VALUE=DATE with a date-time DTEND violates RFC 5545 §3.8.2.2
|
|
// (both ends must share a value type), so only the date part may be used.
|
|
testDb
|
|
.prepare('UPDATE reservations SET reservation_time=?, reservation_end_time=? WHERE id=?')
|
|
.run('2026-08-26', '2026-08-30T11:00', reservation.id);
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('DTSTART;VALUE=DATE:20260826\r\nDTEND;VALUE=DATE:20260831');
|
|
expect(ics).not.toContain('DTEND:20260830T110000');
|
|
});
|
|
|
|
it('CAL-034: an end date before the start date emits no DTEND', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Backwards' });
|
|
const reservation = createReservation(testDb, trip.id, { title: 'Swapped Dates', type: 'event' });
|
|
// Clients either drop an event whose DTEND precedes its DTSTART or render it
|
|
// with zero duration; leaving the end out keeps the single-day fallback.
|
|
testDb
|
|
.prepare('UPDATE reservations SET reservation_time=?, reservation_end_time=? WHERE id=?')
|
|
.run('2026-08-26', '2026-08-20', reservation.id);
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('DTSTART;VALUE=DATE:20260826');
|
|
expect(ics).not.toContain('DTEND');
|
|
});
|
|
|
|
it('CAL-035: a clock-only end time on an all-day booking emits no DTEND', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Half Timed' });
|
|
const reservation = createReservation(testDb, trip.id, { title: 'Workshop', type: 'other' });
|
|
// Relative "Day N" trips store a bare clock time; there is no date to anchor it
|
|
// to, so it cannot become the end of an all-day range.
|
|
testDb
|
|
.prepare('UPDATE reservations SET reservation_time=?, reservation_end_time=? WHERE id=?')
|
|
.run('2026-08-26', '11:00', reservation.id);
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('DTSTART;VALUE=DATE:20260826');
|
|
expect(ics).not.toContain('DTEND');
|
|
});
|
|
});
|
|
|
|
// ── Accommodations in the feed (#1586) ───────────────────────────────────────
|
|
|
|
describe('accommodations', () => {
|
|
/** A stay with its linked hotel reservation, the shape createAccommodation writes. */
|
|
const createStay = (
|
|
tripId: number,
|
|
opts: {
|
|
start: string | null;
|
|
end?: string | null;
|
|
check_in?: string | null;
|
|
check_in_end?: string | null;
|
|
check_out?: string | null;
|
|
title?: string;
|
|
withReservation?: boolean;
|
|
lat?: number;
|
|
lng?: number;
|
|
address?: string | null;
|
|
confirmation?: string;
|
|
notes?: string;
|
|
location?: string;
|
|
},
|
|
) => {
|
|
const place = createPlace(testDb, tripId, {
|
|
name: opts.title ?? 'Hotel Bellevue',
|
|
lat: opts.lat ?? 48.8566,
|
|
lng: opts.lng ?? 2.3522,
|
|
});
|
|
testDb.prepare('UPDATE places SET address = ? WHERE id = ?')
|
|
.run(opts.address === undefined ? '1 Rue de Rivoli' : opts.address, place.id);
|
|
const startDay = createDay(testDb, tripId, { date: opts.start ?? undefined });
|
|
const endDay = opts.end === undefined
|
|
? startDay
|
|
: createDay(testDb, tripId, { date: opts.end ?? undefined });
|
|
const stayId = testDb.prepare(`
|
|
INSERT INTO day_accommodations (trip_id, place_id, start_day_id, end_day_id, check_in, check_in_end, check_out)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
`).run(
|
|
tripId, place.id, startDay.id, endDay.id,
|
|
opts.check_in ?? null, opts.check_in_end ?? null, opts.check_out ?? null,
|
|
).lastInsertRowid as number;
|
|
|
|
if (opts.withReservation !== false) {
|
|
testDb.prepare(`
|
|
INSERT INTO reservations (trip_id, day_id, title, reservation_time, status, type, accommodation_id,
|
|
confirmation_number, notes, location)
|
|
VALUES (?, ?, ?, ?, 'confirmed', 'hotel', ?, ?, ?, ?)
|
|
`).run(
|
|
tripId, startDay.id, opts.title ?? 'Hotel Bellevue', opts.start, String(stayId),
|
|
opts.confirmation ?? null, opts.notes ?? null, opts.location ?? null,
|
|
);
|
|
}
|
|
return { stayId, placeId: place.id };
|
|
};
|
|
|
|
it('CAL-025: a stay covers every night as one all-day event, not just the arrival day', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Paris' });
|
|
createStay(trip.id, { start: '2026-07-07', end: '2026-07-12' });
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
// DTEND is exclusive, so the day after checkout.
|
|
expect(ics).toContain('DTSTART;VALUE=DATE:20260707\r\nDTEND;VALUE=DATE:20260713');
|
|
expect(ics).toContain('SUMMARY:Hotel Bellevue');
|
|
});
|
|
|
|
it('CAL-025b: a stay that records both ends of its clock drops the all-day block (#2136)', async () => {
|
|
// The two markers already say when to arrive and when to leave, which is the
|
|
// part a subscriber can act on. Keeping the block as well buries the week
|
|
// under a bar that repeats what the markers say.
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Paris' });
|
|
createStay(trip.id, {
|
|
start: '2026-07-07', end: '2026-07-12',
|
|
check_in: '15:00', check_out: '11:00',
|
|
});
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).not.toContain('DTSTART;VALUE=DATE:20260707\r\nDTEND;VALUE=DATE:20260713');
|
|
expect(ics).toContain('SUMMARY:Check-in: Hotel Bellevue');
|
|
expect(ics).toContain('SUMMARY:Check-out: Hotel Bellevue');
|
|
// With the block gone the markers are the booking's whole representation, so
|
|
// they carry the hand-over default hour instead of being points.
|
|
expect(ics).toContain('DTEND;TZID=Europe/Paris:20260707T160000');
|
|
expect(ics).toContain('DTEND;TZID=Europe/Paris:20260712T120000');
|
|
});
|
|
|
|
it('CAL-025d: a second room on the same stay keeps its block, since no marker names it', async () => {
|
|
// The markers are emitted once per stay and titled from its lowest-id
|
|
// booking, so dropping every block would leave the second one with nothing.
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Paris' });
|
|
const { stayId } = createStay(trip.id, {
|
|
start: '2026-07-07', end: '2026-07-12',
|
|
check_in: '15:00', check_out: '11:00',
|
|
});
|
|
const day = testDb.prepare('SELECT id FROM days WHERE trip_id = ? ORDER BY id ASC LIMIT 1').get(trip.id) as { id: number };
|
|
testDb.prepare(`
|
|
INSERT INTO reservations (trip_id, day_id, title, reservation_time, status, type, accommodation_id)
|
|
VALUES (?, ?, 'Bellevue second room', NULL, 'confirmed', 'hotel', ?)
|
|
`).run(trip.id, day.id, String(stayId));
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('SUMMARY:Bellevue second room');
|
|
expect(ics).toContain('SUMMARY:Check-in: Hotel Bellevue');
|
|
});
|
|
|
|
it('CAL-025e: the markers of a fully timed stay carry what the dropped block said (#2136)', async () => {
|
|
// Losing the block must not lose the confirmation number and the notes with
|
|
// it, the same handover the split window bookings do (#2068).
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Paris' });
|
|
createStay(trip.id, {
|
|
start: '2026-07-07', end: '2026-07-12',
|
|
check_in: '15:00', check_out: '11:00',
|
|
confirmation: 'HTL-77291', notes: 'Key box code 4711',
|
|
});
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
const unfolded = ics.replaceAll('\r\n ', '');
|
|
const descriptions = unfolded.split('\r\n').filter(l => l.startsWith('DESCRIPTION:Type: hotel'));
|
|
expect(descriptions).toHaveLength(2);
|
|
expect(descriptions[0]).toContain('Confirmation: HTL-77291');
|
|
expect(descriptions[0]).toContain('Key box code 4711');
|
|
});
|
|
|
|
it('CAL-025f: a stay whose place has no address takes the booking location instead', async () => {
|
|
// place_id is nullable (ON DELETE SET NULL) and an address is optional, so
|
|
// without the fallback the only two events left name no address at all.
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Paris' });
|
|
createStay(trip.id, {
|
|
start: '2026-07-07', end: '2026-07-12',
|
|
check_in: '15:00', check_out: '11:00',
|
|
address: null, location: '12 Hotel Street',
|
|
});
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics.match(/LOCATION:12 Hotel Street/g)).toHaveLength(2);
|
|
});
|
|
|
|
it('CAL-025g: a stay that keeps its block does not repeat the description on its markers', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Paris' });
|
|
createStay(trip.id, {
|
|
start: '2026-07-07', end: '2026-07-12',
|
|
check_in: '15:00', confirmation: 'HTL-77291',
|
|
});
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
// The block is still emitted and still says it; saying it a second time on
|
|
// the check-in marker would change a feed that already went out.
|
|
const unfolded = ics.replaceAll('\r\n ', '');
|
|
expect(unfolded.split('\r\n').filter(l => l.startsWith('DESCRIPTION:Type: hotel'))).toHaveLength(1);
|
|
});
|
|
|
|
it('CAL-025c: knowing only one end keeps the block, since nothing else carries the other', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Paris' });
|
|
createStay(trip.id, { start: '2026-07-07', end: '2026-07-12', check_in: '15:00' });
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('DTSTART;VALUE=DATE:20260707\r\nDTEND;VALUE=DATE:20260713');
|
|
expect(ics).toContain('SUMMARY:Check-in: Hotel Bellevue');
|
|
expect(ics).not.toContain('SUMMARY:Check-out');
|
|
});
|
|
|
|
it('CAL-026: check-in and check-out become their own timed events in the stay zone', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Paris' });
|
|
createStay(trip.id, {
|
|
start: '2026-07-07', end: '2026-07-12',
|
|
check_in: '15:00', check_in_end: '22:00', check_out: '11:00',
|
|
});
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('SUMMARY:Check-in: Hotel Bellevue');
|
|
expect(ics).toContain('DTSTART;TZID=Europe/Paris:20260707T150000');
|
|
expect(ics).toContain('DTEND;TZID=Europe/Paris:20260707T220000');
|
|
expect(ics).toContain('SUMMARY:Check-out: Hotel Bellevue');
|
|
expect(ics).toContain('DTSTART;TZID=Europe/Paris:20260712T110000');
|
|
expect(ics).toContain('LOCATION:1 Rue de Rivoli');
|
|
expect(ics).toContain('BEGIN:VTIMEZONE\r\nTZID:Europe/Paris');
|
|
});
|
|
|
|
it('CAL-026b: a check-in without an until-clock reads as one hour, not a point (#2136)', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Paris' });
|
|
createStay(trip.id, { start: '2026-07-07', end: '2026-07-12', check_in: '15:00' });
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
// Reporter variant 2: the lone timed end becomes a one-hour slot AND the
|
|
// all-day block stays, since it is the only carrier of the other end's date.
|
|
expect(ics).toContain('DTSTART;TZID=Europe/Paris:20260707T150000');
|
|
expect(ics).toContain('DTEND;TZID=Europe/Paris:20260707T160000');
|
|
expect(ics).toContain('DTSTART;VALUE=DATE:20260707\r\nDTEND;VALUE=DATE:20260713');
|
|
});
|
|
|
|
it('CAL-026c: the check-out marker carries the same default hour', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Paris' });
|
|
createStay(trip.id, { start: '2026-07-07', end: '2026-07-12', check_out: '11:00' });
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('DTSTART;TZID=Europe/Paris:20260712T110000');
|
|
expect(ics).toContain('DTEND;TZID=Europe/Paris:20260712T120000');
|
|
});
|
|
|
|
it('CAL-026d: a late check-out rolls the DTEND over midnight', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Paris' });
|
|
createStay(trip.id, { start: '2026-07-07', end: '2026-07-12', check_out: '23:30' });
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
// Without the day shift the DTEND would land before its DTSTART, and clients
|
|
// drop an event whose end precedes its start.
|
|
expect(ics).toContain('DTSTART;TZID=Europe/Paris:20260712T233000');
|
|
expect(ics).toContain('DTEND;TZID=Europe/Paris:20260713T003000');
|
|
});
|
|
|
|
it('CAL-026e: a check-in window that ends before it starts runs past midnight (#2136)', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Paris' });
|
|
createStay(trip.id, {
|
|
start: '2026-07-07', end: '2026-07-12',
|
|
check_in: '22:00', check_in_end: '02:00', check_out: '11:00',
|
|
});
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
// A late-arrival window, and nothing on the way in (REST, MCP, plugin SDK)
|
|
// orders the two clocks. Emitted as recorded the DTEND precedes the DTSTART,
|
|
// clients drop the event, and since the block is gone the arrival is gone.
|
|
expect(ics).toContain('DTSTART;TZID=Europe/Paris:20260707T220000');
|
|
expect(ics).toContain('DTEND;TZID=Europe/Paris:20260708T020000');
|
|
});
|
|
|
|
it('CAL-027: a stay without times emits the all-day range and nothing else', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Paris' });
|
|
createStay(trip.id, { start: '2026-07-07', end: '2026-07-12' });
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).not.toContain('Check-in');
|
|
expect(ics).not.toContain('Check-out');
|
|
});
|
|
|
|
it('CAL-028: a stay whose end day lost its date falls back to the arrival day', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Paris' });
|
|
createStay(trip.id, { start: '2026-07-07', end: null, check_out: '11:00' });
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('DTSTART;VALUE=DATE:20260707\r\nDTEND;VALUE=DATE:20260708');
|
|
expect(ics).toContain('SUMMARY:Check-out: Hotel Bellevue');
|
|
expect(ics).toContain('DTSTART;TZID=Europe/Paris:20260707T110000');
|
|
});
|
|
|
|
it('CAL-029: a stay with no reservation still contributes its check-in event', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Paris' });
|
|
createStay(trip.id, { start: '2026-07-07', end: '2026-07-09', check_in: '15:00', withReservation: false });
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('SUMMARY:Check-in: Hotel Bellevue');
|
|
// No stay event without a reservation to carry it — the accommodation itself
|
|
// has no title, notes or confirmation of its own to show.
|
|
expect(ics).not.toContain('DTEND;VALUE=DATE:20260710');
|
|
});
|
|
|
|
it('CAL-030: a hotel reservation without a stay keeps its old single-day event', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Paris' });
|
|
const reservation = createReservation(testDb, trip.id, { title: 'Airbnb', type: 'hotel' });
|
|
testDb.prepare('UPDATE reservations SET reservation_time=? WHERE id=?').run('2026-07-07', reservation.id);
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('DTSTART;VALUE=DATE:20260707');
|
|
expect(ics).not.toContain('DTEND;VALUE=DATE');
|
|
});
|
|
|
|
it('CAL-031: a dateless stay is skipped instead of emitting a broken event', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Someday' });
|
|
createStay(trip.id, { start: null, end: null, check_in: '15:00', check_out: '11:00' });
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).not.toContain('Check-in');
|
|
expect(ics).not.toContain('Check-out');
|
|
expect(ics).not.toContain('DTSTART;VALUE=DATE:');
|
|
});
|
|
|
|
it('CAL-036: two bookings on one stay emit the check-in/check-out markers once', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Paris' });
|
|
const { stayId } = createStay(trip.id, {
|
|
start: '2026-07-07', end: '2026-07-12', check_in: '15:00', check_out: '11:00',
|
|
});
|
|
// Nothing stops a second booking from pointing at the same accommodation. The
|
|
// markers are keyed by the stay, so joining the reservations in fanned the stay
|
|
// out into two VEVENTs carrying the same UID, and clients then show whichever
|
|
// one they saw last (#1869).
|
|
testDb.prepare(`
|
|
INSERT INTO reservations (trip_id, title, reservation_time, status, type, accommodation_id)
|
|
VALUES (?, 'Bellevue second room', NULL, 'confirmed', 'hotel', ?)
|
|
`).run(trip.id, String(stayId));
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics.match(/UID:trek-checkin-\d+@trek/g)).toHaveLength(1);
|
|
expect(ics.match(/UID:trek-checkout-\d+@trek/g)).toHaveLength(1);
|
|
// The lowest booking id names the markers, so the title cannot flip between
|
|
// exports. The second booking keeps its own event (its UID is its own).
|
|
expect(ics).toContain('SUMMARY:Check-in: Hotel Bellevue\r\n');
|
|
expect(ics).not.toContain('Check-in: Bellevue second room');
|
|
expect(ics).toContain('SUMMARY:Bellevue second room');
|
|
});
|
|
|
|
it('CAL-060: the stop a booking puts on its check-in day does not list the hotel a second time', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Paris' });
|
|
const { stayId, placeId } = createStay(trip.id, { start: '2026-07-07', end: '2026-07-12' });
|
|
const stay = testDb.prepare('SELECT start_day_id FROM day_accommodations WHERE id = ?')
|
|
.get(stayId) as { start_day_id: number };
|
|
// The stop a booked night puts on its check-in day, so the route can reach
|
|
// the hotel. It belongs to the stay, not to the day's plan, and the stay
|
|
// block already carries the hotel.
|
|
testDb.prepare('INSERT INTO day_assignments (day_id, place_id, order_index, accommodation_id) VALUES (?, ?, 0, ?)')
|
|
.run(stay.start_day_id, placeId, stayId);
|
|
// A place the traveller planned by hand on the same day stays on it.
|
|
const museum = createPlace(testDb, trip.id, { name: 'Louvre' });
|
|
createDayAssignment(testDb, stay.start_day_id, museum.id);
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('DTSTART;VALUE=DATE:20260707\r\nDTEND;VALUE=DATE:20260713');
|
|
expect(ics.match(/Hotel Bellevue/g)).toHaveLength(1);
|
|
expect(ics).toContain('• Louvre');
|
|
expect(ics).not.toContain('• Hotel Bellevue');
|
|
});
|
|
});
|
|
|
|
// ── Car rental pickup/drop-off in the feed (#1721) ──────────────────────────
|
|
|
|
describe('car rentals', () => {
|
|
const insertEndpoint = (
|
|
reservationId: number,
|
|
role: string,
|
|
sequence: number,
|
|
name: string,
|
|
lat: number,
|
|
lng: number,
|
|
timezone: string | null,
|
|
local_time: string | null,
|
|
local_date: string | null,
|
|
) => {
|
|
testDb.prepare(
|
|
'INSERT INTO reservation_endpoints (reservation_id, role, sequence, name, code, lat, lng, timezone, local_time, local_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
|
|
).run(reservationId, role, sequence, name, null, lat, lng, timezone, local_time, local_date);
|
|
};
|
|
|
|
it('CAL-037: a rental with from/to endpoints produces a pickup and a drop-off event at the right local times and zones', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Road Trip' });
|
|
const reservation = createReservation(testDb, trip.id, { title: 'Hertz Rental', type: 'car' });
|
|
testDb.prepare('UPDATE reservations SET reservation_time=NULL, reservation_end_time=NULL, location=? WHERE id=?')
|
|
.run('Hertz Downtown', reservation.id);
|
|
insertEndpoint(reservation.id, 'from', 0, 'Paris Office', 48.8566, 2.3522, 'Europe/Paris', '09:00', '2026-07-07');
|
|
insertEndpoint(reservation.id, 'to', 1, 'Berlin Office', 52.5, 13.4, 'Europe/Berlin', '10:30', '2026-07-14');
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('SUMMARY:Pickup: Hertz Rental');
|
|
expect(ics).toContain('DTSTART;TZID=Europe/Paris:20260707T090000');
|
|
expect(ics).toContain('SUMMARY:Drop-off: Hertz Rental');
|
|
expect(ics).toContain('DTSTART;TZID=Europe/Berlin:20260714T103000');
|
|
expect(ics).toContain('LOCATION:Hertz Downtown');
|
|
expect(ics).toContain('BEGIN:VTIMEZONE\r\nTZID:Europe/Paris');
|
|
expect(ics).toContain('BEGIN:VTIMEZONE\r\nTZID:Europe/Berlin');
|
|
});
|
|
|
|
it('CAL-038: role-less endpoints fall back to first/last by sequence', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Road Trip' });
|
|
const reservation = createReservation(testDb, trip.id, { title: 'Avis Rental', type: 'car' });
|
|
testDb.prepare('UPDATE reservations SET reservation_time=NULL, reservation_end_time=NULL WHERE id=?').run(reservation.id);
|
|
// Neither endpoint carries a from/to role — an older import shape.
|
|
insertEndpoint(reservation.id, 'stop', 0, 'Paris Office', 48.8566, 2.3522, 'Europe/Paris', '09:00', '2026-07-07');
|
|
insertEndpoint(reservation.id, 'stop', 1, 'Berlin Office', 52.5, 13.4, 'Europe/Berlin', '10:30', '2026-07-14');
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('SUMMARY:Pickup: Avis Rental');
|
|
expect(ics).toContain('DTSTART;TZID=Europe/Paris:20260707T090000');
|
|
expect(ics).toContain('SUMMARY:Drop-off: Avis Rental');
|
|
expect(ics).toContain('DTSTART;TZID=Europe/Berlin:20260714T103000');
|
|
});
|
|
|
|
it('CAL-039: a rental with only reservation_time/reservation_end_time still produces both events', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Road Trip' });
|
|
const place = createPlace(testDb, trip.id, { name: 'Rental Desk', lat: 48.8566, lng: 2.3522 });
|
|
const reservation = createReservation(testDb, trip.id, { title: 'Budget Rental', type: 'car' });
|
|
testDb.prepare('UPDATE reservations SET reservation_time=?, reservation_end_time=?, place_id=? WHERE id=?')
|
|
.run('2026-07-07T09:00', '2026-07-14T10:30', place.id, reservation.id);
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('SUMMARY:Pickup: Budget Rental');
|
|
expect(ics).toContain('DTSTART;TZID=Europe/Paris:20260707T090000');
|
|
expect(ics).toContain('SUMMARY:Drop-off: Budget Rental');
|
|
expect(ics).toContain('DTSTART;TZID=Europe/Paris:20260714T103000');
|
|
});
|
|
|
|
it('CAL-040: a rental with a single endpoint does not emit a bogus second event', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Road Trip' });
|
|
const reservation = createReservation(testDb, trip.id, { title: 'Sixt Rental', type: 'car' });
|
|
testDb.prepare('UPDATE reservations SET reservation_time=NULL, reservation_end_time=NULL WHERE id=?').run(reservation.id);
|
|
// Only the pickup was geocoded — the common shape for a partially-imported
|
|
// booking. The lone endpoint must not be reused as the drop-off too.
|
|
insertEndpoint(reservation.id, 'from', 0, 'Paris Office', 48.8566, 2.3522, 'Europe/Paris', '09:00', '2026-07-07');
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('SUMMARY:Pickup: Sixt Rental');
|
|
expect(ics).not.toContain('Drop-off');
|
|
});
|
|
|
|
it('CAL-041: a rental with no usable clock emits no window events and its existing behaviour is unchanged', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Road Trip' });
|
|
const reservation = createReservation(testDb, trip.id, { title: 'Untimed Rental', type: 'car' });
|
|
testDb.prepare('UPDATE reservations SET reservation_time=NULL, reservation_end_time=NULL WHERE id=?').run(reservation.id);
|
|
// A date but no clock — the pre-existing "untimed transport" all-day
|
|
// fallback still applies and must be unaffected by the new marker events.
|
|
insertEndpoint(reservation.id, 'from', 0, 'Paris Office', 48.8566, 2.3522, 'Europe/Paris', null, '2026-07-07');
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).not.toContain('Pickup');
|
|
expect(ics).not.toContain('Drop-off');
|
|
expect(ics).toContain('SUMMARY:Untimed Rental');
|
|
expect(ics).toContain('DTSTART;VALUE=DATE:20260707');
|
|
});
|
|
|
|
it('CAL-042: a clock that already carries seconds keeps its zone', async () => {
|
|
// The booking import stores what KItinerary hands it, which is "10:00:00".
|
|
// fmtDateTime's time-only branch appended "00" regardless, so the value came
|
|
// out 17 characters long, dtLine refused to attach the TZID and the event
|
|
// went out floating — the #1453 regression by another route.
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Road Trip' });
|
|
const reservation = createReservation(testDb, trip.id, { title: 'Seconds Rental', type: 'car' });
|
|
testDb.prepare('UPDATE reservations SET reservation_time=?, reservation_end_time=? WHERE id=?')
|
|
.run('2026-07-07T09:00:00', '18:30:00', reservation.id);
|
|
insertEndpoint(reservation.id, 'from', 0, 'Paris Office', 48.8566, 2.3522, 'Europe/Paris', '09:00:00', '2026-07-07');
|
|
insertEndpoint(reservation.id, 'to', 1, 'Lyon Office', 45.764, 4.8357, 'Europe/Paris', '18:30:00', '2026-07-07');
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('DTSTART;TZID=Europe/Paris:20260707T090000');
|
|
expect(ics).toContain('DTSTART;TZID=Europe/Paris:20260707T183000');
|
|
// No 17-character value anywhere: that is what silently drops the zone.
|
|
expect(ics).not.toMatch(/DTSTART[^\r\n]*\d{8}T\d{8}/);
|
|
});
|
|
|
|
// ── Window bookings: two hand-overs, not one block (#2068) ─────────────────
|
|
|
|
it('CAL-045: multi-day parking becomes a drop-off and a pick-up instead of one block', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Road Trip' });
|
|
const parking = createReservation(testDb, trip.id, { title: 'Airport P4', type: 'parking' });
|
|
testDb.prepare('UPDATE reservations SET reservation_time=?, reservation_end_time=? WHERE id=?')
|
|
.run('2026-07-01T06:30', '2026-07-10T22:15', parking.id);
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
// The two hand-overs, an hour each. Parking is dropped off first.
|
|
expect(ics).toContain('SUMMARY:Drop-off: Airport P4');
|
|
expect(ics).toContain('DTSTART:20260701T063000');
|
|
expect(ics).toContain('DTEND:20260701T073000');
|
|
expect(ics).toContain('SUMMARY:Pickup: Airport P4');
|
|
expect(ics).toContain('DTSTART:20260710T221500');
|
|
expect(ics).toContain('DTEND:20260710T231500');
|
|
// And the block across the ten days in between is gone.
|
|
expect(ics).not.toContain('SUMMARY:Airport P4\r\n');
|
|
expect(ics).not.toContain('DTEND:20260710T221500');
|
|
});
|
|
|
|
it('CAL-046: a same-day parking is one sitting and keeps its single event', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Road Trip' });
|
|
const parking = createReservation(testDb, trip.id, { title: 'Garage', type: 'parking' });
|
|
testDb.prepare('UPDATE reservations SET reservation_time=?, reservation_end_time=? WHERE id=?')
|
|
.run('2026-07-01T08:00', '2026-07-01T18:30', parking.id);
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('SUMMARY:Garage\r\n');
|
|
expect(ics).toContain('DTSTART:20260701T080000');
|
|
expect(ics).toContain('DTEND:20260701T183000');
|
|
expect(ics).not.toContain('Drop-off: Garage');
|
|
expect(ics).not.toContain('Pickup: Garage');
|
|
});
|
|
|
|
it('CAL-047: a rental typed with days but no clock finally reaches the feed', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Road Trip' });
|
|
const first = createDay(testDb, trip.id, { date: '2026-07-03' });
|
|
const last = createDay(testDb, trip.id, { date: '2026-07-08' });
|
|
const rental = createReservation(testDb, trip.id, { title: 'Sixt', type: 'car' });
|
|
// The planner writes reservation_time = NULL when the optional time pickers
|
|
// are left blank, which is what made this booking invisible.
|
|
testDb.prepare('UPDATE reservations SET reservation_time=NULL, reservation_end_time=NULL, day_id=?, end_day_id=? WHERE id=?')
|
|
.run(first.id, last.id, rental.id);
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('SUMMARY:Pickup: Sixt');
|
|
expect(ics).toContain('DTSTART;VALUE=DATE:20260703');
|
|
expect(ics).toContain('SUMMARY:Drop-off: Sixt');
|
|
expect(ics).toContain('DTSTART;VALUE=DATE:20260708');
|
|
});
|
|
|
|
it('CAL-048: a split rental keeps its zones and everything the block used to say', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Road Trip' });
|
|
const rental = createReservation(testDb, trip.id, { title: 'Hertz', type: 'car' });
|
|
testDb.prepare('UPDATE reservations SET reservation_time=NULL, reservation_end_time=NULL, confirmation_number=?, location=? WHERE id=?')
|
|
.run('HZ-4471', 'Hertz Downtown', rental.id);
|
|
insertEndpoint(rental.id, 'from', 0, 'Paris Office', 48.8566, 2.3522, 'Europe/Paris', '09:00', '2026-07-07');
|
|
insertEndpoint(rental.id, 'to', 1, 'Berlin Office', 52.5, 13.4, 'Europe/Berlin', '10:30', '2026-07-14');
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('DTSTART;TZID=Europe/Paris:20260707T090000');
|
|
expect(ics).toContain('DTEND;TZID=Europe/Paris:20260707T100000');
|
|
expect(ics).toContain('DTSTART;TZID=Europe/Berlin:20260714T103000');
|
|
expect(ics).toContain('DTEND;TZID=Europe/Berlin:20260714T113000');
|
|
// Dropping the block must not drop what it said: both hand-overs carry it.
|
|
// Long lines are folded at 75 octets, so unfold before reading them.
|
|
const unfolded = ics.replaceAll('\r\n ', '');
|
|
const descriptions = unfolded.split('\r\n').filter(l => l.startsWith('DESCRIPTION:Type: car'));
|
|
expect(descriptions).toHaveLength(2);
|
|
expect(descriptions[0]).toContain('Confirmation: HZ-4471');
|
|
expect(descriptions[0]).toContain('Route: Paris Office → Berlin Office');
|
|
});
|
|
|
|
// #1453 — the block is the only carrier of the return time when just one side
|
|
// was geocoded, so a one-sided rental must keep it.
|
|
it('CAL-049: a one-sided rental keeps its block rather than losing the return', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Road Trip' });
|
|
const place = createPlace(testDb, trip.id, { name: 'Rental Desk', lat: 48.8566, lng: 2.3522 });
|
|
const rental = createReservation(testDb, trip.id, { title: 'Avis', type: 'car' });
|
|
testDb.prepare('UPDATE reservations SET reservation_time=?, reservation_end_time=?, place_id=? WHERE id=?')
|
|
.run('2026-07-02T10:00', '2026-07-09T10:00', place.id, rental.id);
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
// Both sides resolve off reservation_time/-_end_time, so this one does split,
|
|
// and the return keeps the pickup's zone instead of floating.
|
|
expect(ics).toContain('DTSTART;TZID=Europe/Paris:20260702T100000');
|
|
expect(ics).toContain('DTSTART;TZID=Europe/Paris:20260709T100000');
|
|
expect(ics).not.toMatch(/DTSTART:20260709T100000/);
|
|
});
|
|
|
|
it('CAL-050: a rental with only a pickup endpoint is left exactly as it was', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Road Trip' });
|
|
const rental = createReservation(testDb, trip.id, { title: 'Solo', type: 'car' });
|
|
testDb.prepare('UPDATE reservations SET reservation_time=NULL, reservation_end_time=NULL WHERE id=?').run(rental.id);
|
|
insertEndpoint(rental.id, 'from', 0, 'Paris Office', 48.8566, 2.3522, 'Europe/Paris', '09:00', '2026-07-07');
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('SUMMARY:Solo\r\n');
|
|
expect(ics).toContain('SUMMARY:Pickup: Solo');
|
|
expect(ics).not.toContain('Drop-off');
|
|
});
|
|
|
|
it('CAL-051: any transport pinned to days without a clock reaches the feed too', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Road Trip' });
|
|
const first = createDay(testDb, trip.id, { date: '2026-07-03' });
|
|
const last = createDay(testDb, trip.id, { date: '2026-07-04' });
|
|
const bus = createReservation(testDb, trip.id, { title: 'Night Bus', type: 'bus' });
|
|
testDb.prepare('UPDATE reservations SET reservation_time=NULL, reservation_end_time=NULL, day_id=?, end_day_id=? WHERE id=?')
|
|
.run(first.id, last.id, bus.id);
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
// Not a window booking, so it stays one block — it just exists now.
|
|
expect(ics).toContain('SUMMARY:Night Bus');
|
|
expect(ics).toContain('DTSTART;VALUE=DATE:20260703');
|
|
expect(ics).toContain('DTEND;VALUE=DATE:20260705');
|
|
expect(ics).not.toContain('Pickup: Night Bus');
|
|
});
|
|
|
|
it('CAL-052: a split rental whose endpoints carry no zone falls back to their coordinates', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Road Trip' });
|
|
const rental = createReservation(testDb, trip.id, { title: 'Europcar', type: 'car' });
|
|
testDb.prepare('UPDATE reservations SET reservation_time=NULL, reservation_end_time=NULL WHERE id=?').run(rental.id);
|
|
// An older import that geocoded both ends but stored no IANA zone.
|
|
insertEndpoint(rental.id, 'from', 0, 'Paris Office', 48.8566, 2.3522, null, '09:00', '2026-07-07');
|
|
insertEndpoint(rental.id, 'to', 1, 'Berlin Office', 52.5, 13.4, null, '10:30', '2026-07-14');
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('DTSTART;TZID=Europe/Paris:20260707T090000');
|
|
expect(ics).toContain('DTSTART;TZID=Europe/Berlin:20260714T103000');
|
|
});
|
|
|
|
// reservation_end_time is frequently a bare clock next to the booking's own
|
|
// date, which puts both hand-overs on the same day — so it is one sitting.
|
|
it('CAL-053: a bare end clock resolves against the start date rather than splitting', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Road Trip' });
|
|
const parking = createReservation(testDb, trip.id, { title: 'Street Bay', type: 'parking' });
|
|
testDb.prepare('UPDATE reservations SET reservation_time=?, reservation_end_time=? WHERE id=?')
|
|
.run('2026-07-01T08:00', '18:30', parking.id);
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('SUMMARY:Street Bay\r\n');
|
|
expect(ics).not.toContain('Drop-off: Street Bay');
|
|
expect(ics).not.toContain('Pickup: Street Bay');
|
|
});
|
|
|
|
it('CAL-054: an unsplit rental with a day but no clock emits no hand-over of its own', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Road Trip' });
|
|
const day = createDay(testDb, trip.id, { date: '2026-07-03' });
|
|
const rental = createReservation(testDb, trip.id, { title: 'Dayless', type: 'car' });
|
|
// A day but no end day and no clock: one side resolves, and it has no time,
|
|
// so there is nothing to place — the all-day block carries it instead.
|
|
testDb.prepare('UPDATE reservations SET reservation_time=NULL, reservation_end_time=NULL, day_id=?, end_day_id=NULL WHERE id=?')
|
|
.run(day.id, rental.id);
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('SUMMARY:Dayless\r\n');
|
|
expect(ics).toContain('DTSTART;VALUE=DATE:20260703');
|
|
expect(ics).not.toContain('Pickup: Dayless');
|
|
expect(ics).not.toContain('Drop-off: Dayless');
|
|
});
|
|
});
|
|
|
|
describe('staged bookings', () => {
|
|
/** A stay plus, optionally, the bookings that point at it. */
|
|
const stayWith = (tripId: number, states: Array<{ state: string; title: string }>) => {
|
|
const place = createPlace(testDb, tripId, { name: 'Hotel Bellevue', lat: 48.8566, lng: 2.3522 });
|
|
const startDay = createDay(testDb, tripId, { date: '2026-09-01' });
|
|
const endDay = createDay(testDb, tripId, { date: '2026-09-04' });
|
|
const stayId = testDb.prepare(`
|
|
INSERT INTO day_accommodations (trip_id, place_id, start_day_id, end_day_id, check_in, check_out)
|
|
VALUES (?, ?, ?, ?, '15:00', '11:00')
|
|
`).run(tripId, place.id, startDay.id, endDay.id).lastInsertRowid as number;
|
|
|
|
for (const s of states) {
|
|
testDb.prepare(`
|
|
INSERT INTO reservations (trip_id, day_id, title, reservation_time, status, type, accommodation_id, ingest_state)
|
|
VALUES (?, ?, ?, '2026-09-01T15:00', 'confirmed', 'hotel', ?, ?)
|
|
`).run(tripId, startDay.id, s.title, String(stayId), s.state);
|
|
}
|
|
return { stayId, placeId: place.id };
|
|
};
|
|
|
|
it('CAL-055: a staged booking is left out of the calendar, confirmation number included', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Kyoto' });
|
|
const day = createDay(testDb, trip.id, { date: '2026-09-01' });
|
|
const staged = createReservation(testDb, trip.id, { title: 'Parked Flight', type: 'flight', day_id: day.id });
|
|
testDb.prepare(`UPDATE reservations SET ingest_state='staged', reservation_time='2026-09-01T08:00',
|
|
confirmation_number='ABC123' WHERE id=?`).run(staged.id);
|
|
const live = createReservation(testDb, trip.id, { title: 'Booked Flight', type: 'flight', day_id: day.id });
|
|
testDb.prepare("UPDATE reservations SET reservation_time='2026-09-01T12:00' WHERE id=?").run(live.id);
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('SUMMARY:Booked Flight');
|
|
expect(ics).not.toContain('Parked Flight');
|
|
// The number rides in the DESCRIPTION, not the SUMMARY, so search the whole document.
|
|
expect(ics).not.toContain('ABC123');
|
|
});
|
|
|
|
it('CAL-056: a booking created before the column existed still exports', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Lisbon' });
|
|
const day = createDay(testDb, trip.id, { date: '2026-09-02' });
|
|
// No ingest_state named on the insert: exactly what every writer does today,
|
|
// and what the ALTER backfilled onto every pre-existing row.
|
|
const old = createReservation(testDb, trip.id, { title: 'Legacy Booking', type: 'flight', day_id: day.id });
|
|
testDb.prepare("UPDATE reservations SET reservation_time='2026-09-02T09:00' WHERE id=?").run(old.id);
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('SUMMARY:Legacy Booking');
|
|
});
|
|
|
|
it('CAL-057: an accommodation whose only booking is staged emits no stay, check-in or check-out', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Osaka' });
|
|
stayWith(trip.id, [{ state: 'staged', title: 'Parked Hotel' }]);
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).not.toContain('Parked Hotel');
|
|
expect(ics).not.toMatch(/UID:trek-checkin-\d+@trek/);
|
|
expect(ics).not.toMatch(/UID:trek-checkout-\d+@trek/);
|
|
});
|
|
|
|
it('CAL-058: an accommodation with no linked booking at all still emits its stay', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Nara' });
|
|
// The regression this pins: a plain EXISTS(live) instead of
|
|
// NOT EXISTS(any) OR EXISTS(live) would drop every hand-added hotel out of
|
|
// trips that are shared today.
|
|
stayWith(trip.id, []);
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('Hotel Bellevue');
|
|
expect(ics).toMatch(/UID:trek-checkin-\d+@trek/);
|
|
});
|
|
|
|
it('CAL-059: a stay with both a staged and a live booking takes its title from the live one', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Kobe' });
|
|
// The staged row gets the lower id, so the subquery's ORDER BY r.id ASC
|
|
// would pick it without the predicate.
|
|
stayWith(trip.id, [{ state: 'staged', title: 'Parked Name' }, { state: 'live', title: 'Real Name' }]);
|
|
|
|
const { ics } = await svc.exportICS(trip.id);
|
|
|
|
expect(ics).toContain('Real Name');
|
|
expect(ics).not.toContain('Parked Name');
|
|
});
|
|
});
|
|
|
|
describe('folded quirk branches', () => {
|
|
it('TRIP-SVC-048: exportICS renders untimed/notes all-day summaries, multi-leg routes, endpoint routes and train/location fields', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, { title: 'Branchy' });
|
|
const day = createDay(testDb, trip.id, { date: '2025-06-02' });
|
|
const place = createPlace(testDb, trip.id, { name: 'Untimed Spot' });
|
|
testDb.prepare("UPDATE places SET address = '1 Rue Test' WHERE id = ?").run(place.id);
|
|
const assignment = createDayAssignment(testDb, day.id, place.id);
|
|
testDb.prepare("UPDATE day_assignments SET notes = 'bring hat' WHERE id = ?").run(assignment.id);
|
|
createDayNote(testDb, day.id, trip.id, { text: 'timed note', time: '10:00' });
|
|
createDayNote(testDb, day.id, trip.id, { text: 'plain note' });
|
|
|
|
// Multi-leg flight metadata → Route: A → B → C, plus train + notes + location.
|
|
const flight = createReservation(testDb, trip.id, { title: 'Legs', type: 'flight' });
|
|
testDb.prepare('UPDATE reservations SET reservation_time=?, metadata=?, notes=?, location=?, confirmation_number=? WHERE id=?').run(
|
|
'2025-06-02T09:00',
|
|
JSON.stringify({ legs: [{ from: 'FRA', to: 'BER' }, { to: 'HND' }], train_number: 'ICE 100' }),
|
|
'window seat', 'Gate 4', 'ABC123', flight.id,
|
|
);
|
|
// Endpoint-derived route (no route metadata) with a date-only endpoint fallback.
|
|
const transport = createReservation(testDb, trip.id, { title: 'Ferry', type: 'transport' });
|
|
testDb.prepare('UPDATE reservations SET reservation_time=NULL WHERE id=?').run(transport.id);
|
|
const insertEp = testDb.prepare(
|
|
'INSERT INTO reservation_endpoints (reservation_id, role, sequence, name, code, lat, lng, timezone, local_time, local_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
|
|
);
|
|
insertEp.run(transport.id, 'from', 0, 'Pier A', null, 1.0, 1.0, null, null, '2025-06-03');
|
|
insertEp.run(transport.id, 'to', 1, 'Pier B', 'PB', 1.1, 1.1, null, null, '2025-06-03');
|
|
|
|
// Unfold the RFC 5545 75-octet folding so substring assertions see whole lines.
|
|
const ics = (await svc.exportICS(trip.id)).ics.replace(/\r\n /g, '');
|
|
|
|
expect(ics).toContain('SUMMARY:Day 1');
|
|
expect(ics).toContain('• Untimed Spot (1 Rue Test) — bring hat');
|
|
expect(ics).toContain('Notes:\\n10:00 — timed note\\n• plain note');
|
|
expect(ics).toContain('Route: FRA → BER → HND');
|
|
expect(ics).toContain('Train: ICE 100');
|
|
expect(ics).toContain('Confirmation: ABC123');
|
|
expect(ics).toContain('window seat');
|
|
expect(ics).toContain('LOCATION:Gate 4');
|
|
// Date-only endpoint → all-day DTSTART for the transport.
|
|
expect(ics).toContain('SUMMARY:Ferry');
|
|
expect(ics).toContain('DTSTART;VALUE=DATE:20250603');
|
|
});
|
|
});
|
|
|
|
// foldICS is the last thing that touches the bytes of both the download and the
|
|
// feed, and it is exported, so it is pinned directly instead of through a trip.
|
|
describe('foldICS', () => {
|
|
// Physical lines are measured in octets, so the split points below are byte
|
|
// offsets, not character offsets.
|
|
const octets = (s: string) => Buffer.from(s, 'utf8').length;
|
|
const unfold = (s: string) => s.replace(/\r\n /g, '');
|
|
|
|
it('CAL-023: lines up to 75 octets are untouched and longer ones fold at 75 then 74', async () => {
|
|
const short = 'SUMMARY:' + 'a'.repeat(67); // exactly 75 octets
|
|
expect(foldICS(short)).toBe(short);
|
|
|
|
const long = 'SUMMARY:' + 'a'.repeat(200);
|
|
const physical = foldICS(long).split('\r\n');
|
|
expect(physical[0]).toHaveLength(75);
|
|
// Continuation lines spend one octet on the leading space, so they carry 74
|
|
// payload octets — budgeting 75 there produces 76-octet lines that strict
|
|
// validators reject.
|
|
expect(physical[1].startsWith(' ')).toBe(true);
|
|
expect(physical[1]).toHaveLength(75);
|
|
expect(unfold(foldICS(long))).toBe(long);
|
|
});
|
|
|
|
it('CAL-024: a two-byte codepoint straddling the 75th octet is not split', async () => {
|
|
// The fold boundary lands inside "é": without the backoff the two halves are
|
|
// decoded separately and the title arrives as U+FFFD in every client.
|
|
const line = 'DESCRIPTION:' + 'é'.repeat(60);
|
|
expect(octets(line)).toBeGreaterThan(75);
|
|
|
|
const folded = foldICS(line);
|
|
|
|
expect(folded).not.toContain('\uFFFD');
|
|
expect(unfold(folded)).toBe(line);
|
|
for (const part of folded.split('\r\n')) expect(octets(part)).toBeLessThanOrEqual(75);
|
|
});
|
|
|
|
it('CAL-025: a four-byte codepoint backs the split off by more than one octet', async () => {
|
|
// An emoji needs the backoff to run several times before it reaches a lead
|
|
// byte; stopping after a single step still cuts the sequence.
|
|
const line = 'SUMMARY:' + '🎌'.repeat(40);
|
|
|
|
const folded = foldICS(line);
|
|
|
|
expect(folded).not.toContain('\uFFFD');
|
|
expect(unfold(folded)).toBe(line);
|
|
for (const part of folded.split('\r\n')) expect(octets(part)).toBeLessThanOrEqual(75);
|
|
});
|
|
|
|
it('CAL-026: folding is applied per content line, so short lines around a long one survive', async () => {
|
|
const ics = 'BEGIN:VEVENT\r\nSUMMARY:' + 'ü'.repeat(80) + '\r\nEND:VEVENT';
|
|
|
|
const folded = foldICS(ics);
|
|
|
|
expect(folded.startsWith('BEGIN:VEVENT\r\n')).toBe(true);
|
|
expect(folded.endsWith('\r\nEND:VEVENT')).toBe(true);
|
|
expect(unfold(folded)).toBe(ics);
|
|
});
|
|
});
|
|
|
|
// The snapshot below was taken from the implementation as it stood when the code
|
|
// moved out of TripsService, before the calendar grew a structured model. It is
|
|
// the parity net for any change to how the calendar is assembled: the 20 cases
|
|
// above pin individual lines, this one pins the whole document including the
|
|
// order of the VTIMEZONE blocks and the folding.
|
|
describe('serialised output', () => {
|
|
it('CAL-010: a trip with a zoned assignment, a note day and a flight serialises byte for byte', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id, {
|
|
title: 'Golden Trip',
|
|
description: 'Line one',
|
|
start_date: '2026-05-01',
|
|
end_date: '2026-05-01',
|
|
});
|
|
const day = createDay(testDb, trip.id, { date: '2026-05-01' });
|
|
// The factories insert only the columns they model; every other column is set
|
|
// afterwards with an explicit UPDATE, the way the cases above do it. This case
|
|
// sets none, so the place has no address and the flight no reservation_time,
|
|
// and the snapshot was recorded from exactly that data: the assignment carries
|
|
// no LOCATION, and the flight is dropped from the export for having no
|
|
// placeable time.
|
|
const place = createPlace(testDb, trip.id, { name: 'Tokyo Tower', lat: 35.6586, lng: 139.7454 });
|
|
const assignment = createDayAssignment(testDb, day.id, place.id);
|
|
testDb.prepare('UPDATE day_assignments SET assignment_time=?, assignment_end_time=? WHERE id=?')
|
|
.run('09:00', '10:30', assignment.id);
|
|
createDayNote(testDb, day.id, trip.id, { text: 'Bring the tickets', time: '08:00' });
|
|
createReservation(testDb, trip.id, { title: 'NH 203', type: 'flight' });
|
|
|
|
// DTSTAMP is the wall clock and the UID numbers are autoincrement state shared
|
|
// with every case above, so both are normalised: this pins the document, not
|
|
// the minute it ran in or its position in the file.
|
|
const ics = (await svc.exportICS(trip.id)).ics
|
|
.replace(/DTSTAMP:\d{8}T\d{6}Z/g, 'DTSTAMP:<stamp>')
|
|
.replace(/UID:trek-([a-z]+)-\d+@trek/g, 'UID:trek-$1-<n>@trek');
|
|
|
|
expect(ics).toMatchInlineSnapshot(`
|
|
"BEGIN:VCALENDAR
|
|
VERSION:2.0
|
|
PRODID:-//TREK//Travel Planner//EN
|
|
CALSCALE:GREGORIAN
|
|
METHOD:PUBLISH
|
|
X-WR-CALNAME:Golden Trip
|
|
BEGIN:VTIMEZONE
|
|
TZID:Asia/Tokyo
|
|
BEGIN:STANDARD
|
|
DTSTART:19700101T000000
|
|
TZOFFSETFROM:+0900
|
|
TZOFFSETTO:+0900
|
|
TZNAME:Asia/Tokyo
|
|
END:STANDARD
|
|
END:VTIMEZONE
|
|
BEGIN:VEVENT
|
|
UID:trek-trip-<n>@trek
|
|
DTSTAMP:<stamp>
|
|
DTSTART;VALUE=DATE:20260501
|
|
DTEND;VALUE=DATE:20260502
|
|
SUMMARY:Golden Trip
|
|
DESCRIPTION:Line one
|
|
END:VEVENT
|
|
BEGIN:VEVENT
|
|
UID:trek-assign-<n>@trek
|
|
DTSTAMP:<stamp>
|
|
DTSTART;TZID=Asia/Tokyo:20260501T090000
|
|
DTEND;TZID=Asia/Tokyo:20260501T103000
|
|
SUMMARY:Tokyo Tower
|
|
END:VEVENT
|
|
BEGIN:VEVENT
|
|
UID:trek-day-<n>@trek
|
|
DTSTAMP:<stamp>
|
|
DTSTART;VALUE=DATE:20260501
|
|
DTEND;VALUE=DATE:20260502
|
|
SUMMARY:Day 2
|
|
DESCRIPTION:Notes:\\n08:00 — Bring the tickets
|
|
END:VEVENT
|
|
END:VCALENDAR
|
|
"
|
|
`);
|
|
});
|
|
});
|
|
|
|
describe('CalendarService wiring', () => {
|
|
it('CAL-001: the module registers the service, so injection cannot silently fail', async () => {
|
|
expectRegisteredProvider(CalendarModule, CalendarService);
|
|
const exports = Reflect.getMetadata('exports', CalendarModule) as unknown[];
|
|
expect(Array.isArray(exports)).toBe(true);
|
|
expect(exports).toEqual(expect.arrayContaining([CalendarService]));
|
|
});
|
|
});
|