refactor(assignments): day assignments through repositories

This commit is contained in:
jubnl
2026-09-23 06:27:21 +02:00
parent d7f5bc64c1
commit f41da98df3
18 changed files with 1478 additions and 249 deletions
@@ -1,4 +1,110 @@
import type { AssignmentParticipants } from '../entities/AssignmentParticipants.entity';
import { coalesce } from '../dialect/sql-functions';
import { TrekRepository } from './_shared/trek-repository';
export class AssignmentParticipantsRepository extends TrekRepository<AssignmentParticipants> {}
/** One assignment's participant, from `QueryHelpersService.loadParticipantsByAssignmentIds` (QH3). */
export interface ParticipantForAssignmentRow {
assignment_id: number;
user_id: number;
username: string;
avatar: string | null;
}
/**
* One assignment's participant, from AS2/AS15/AS31
* (`AssignmentsService.getAssignmentWithPlace`/`getParticipants`/
* `setParticipants`) — narrower than `ParticipantForAssignmentRow` above
* (no `assignment_id` — the legacy statement never selects it) and with
* `COALESCE(display_name, username)` folded into `username`.
*/
export interface ParticipantRow {
user_id: number;
username: string;
avatar: string | null;
}
export class AssignmentParticipantsRepository extends TrekRepository<AssignmentParticipants> {
/**
* `SELECT ap.assignment_id, ap.user_id, u.username, u.avatar
* FROM assignment_participants ap JOIN users u ON ap.user_id = u.id
* WHERE ap.assignment_id IN (${…})` (`query-helpers.service.ts:83-86`, QH3).
*
* Deliberately **no** `COALESCE(display_name, username)` — unlike
* `AssignmentsService.getParticipants` (AS15), which does. The two
* participant projections genuinely disagree on the wire (plan3c inventory
* §1 QH3) and must stay that way; do not "fix" this one to match AS15.
*
* Empty `assignmentIds` short-circuits before any query, matching the
* legacy service method.
*/
async listForAssignments(assignmentIds: number[]): Promise<ParticipantForAssignmentRow[]> {
if (assignmentIds.length === 0) return [];
// `ap.assignment` selects the plain FK scalar as `assignment_id` (never
// separately joined here). `ap.user` IS separately joined (to `u`), so
// its id is pulled explicitly off the join instead (`u.id as user_id`)
// — see `PlaceRatingsRepository.listForPlaces`'s docstring for why
// selecting a relation property that is ALSO an active join's target
// renames the column onto the joined entity's own primary key instead.
return this.qb('ap')
.join('ap.user', 'u')
.select(['ap.assignment', 'u.id as user_id', 'u.username', 'u.avatar'])
.where({ 'ap.assignment': { $in: assignmentIds } })
.execute<ParticipantForAssignmentRow[]>('all', false);
}
// ---------------------------------------------------------------------------
// Plan 3c Task 3 (`AssignmentsService`) — appended after Task 1's own
// `listForAssignments` above, per this task's coordination note (this file
// may already carry Task 1's uncommitted method; both are kept, and the
// whole file is committed under Task 3's message, noted in its report).
// ---------------------------------------------------------------------------
/**
* AS2/AS15/AS31 (`AssignmentsService.getAssignmentWithPlace`/
* `getParticipants`/`setParticipants`'s post-write re-select) — `SELECT
* ap.user_id, COALESCE(u.display_name, u.username) AS username, u.avatar
* FROM assignment_participants ap JOIN users u ON ap.user_id = u.id WHERE
* ap.assignment_id = ?`. A SEPARATE method from `listForAssignments`
* (QH3) above — the inventory's §18.10 finding: the two participant
* projections genuinely disagree on the wire (this one COALESCEs
* `display_name` over `username`, QH3 does not) and must stay that way,
* never unified into one "shared row shaper". Also a NARROWER column set
* than QH3's own row: the legacy AS2/AS15/AS31 statement never selects
* `assignment_id` at all (unlike QH3, which does) — `ParticipantRow` below
* is deliberately its own type, not `ParticipantForAssignmentRow`, so a
* caller can never accidentally see a key this statement doesn't produce.
*/
async listWithDisplayName(assignment_id: number): Promise<ParticipantRow[]> {
const platform = this.getEntityManager().getPlatform();
return this.qb('ap')
.join('ap.user', 'u')
.select(['u.id as user_id', coalesce(platform, 'u.display_name', 'u.username').as('username'), 'u.avatar'])
.where({ 'ap.assignment': assignment_id })
.execute<ParticipantRow[]>('all', false);
}
/** AS29 — `DELETE FROM assignment_participants WHERE assignment_id = ?`. */
async deleteForAssignment(assignment_id: number): Promise<void> {
await this.nativeDelete({ assignment: assignment_id });
}
/**
* AS30 — `INSERT OR IGNORE INTO assignment_participants (assignment_id,
* user_id) VALUES (?, ?)`, run once per id. `upsertMany` with
* `onConflictAction: 'ignore'` on the table's real unique key
* (`UNIQUE(assignment_id, user_id)`,
* `Migration20200101002400_create_assignment_participants` — verified
* against the migration, not assumed), named by entity property
* (`assignment`/`user`, `OauthConsentsRepository.upsertGrant`'s precedent
* for a relation-backed `onConflictFields` list). The caller only ever
* passes a non-empty, already-roster-scoped array; the empty-array guard
* here is defensive, matching the service's own guard.
*/
async insertIgnore(assignment_id: number, user_ids: number[]): Promise<void> {
if (user_ids.length === 0) return;
await this.upsertMany(
user_ids.map((user_id) => ({ assignment: assignment_id, user: user_id })),
{ onConflictFields: ['assignment', 'user'], onConflictAction: 'ignore' },
);
}
}
@@ -1,6 +1,7 @@
import type { Platform } from '@mikro-orm/core';
import type { DayAssignments } from '../entities/DayAssignments.entity';
import { coalesce, columnRef } from '../dialect/sql-functions';
import { coalesce, columnIncrementedBy, columnRef } from '../dialect/sql-functions';
import { type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
/**
@@ -93,6 +94,74 @@ interface DayAssignmentsKyselyDB {
};
}
/**
* A `day_assignments` row exactly as `AS12` (`AssignmentsService
* .getAssignmentForTrip`) re-selects it — every scalar column of the entity
* (`da.*`), scoped by a two-hop join to `days` for the trip check (Task 3).
*/
export interface DayAssignmentRow {
id: number;
day_id: number;
place_id: number;
order_index: number | null;
notes: string | null;
reservation_status: string | null;
reservation_notes: string | null;
reservation_datetime: string | null;
created_at: string | null;
assignment_time: string | null;
assignment_end_time: string | null;
leg_transport_mode: string | null;
incoming_leg_transport_mode: string | null;
end_day: number;
accommodation_id: number | null;
}
const _dayAssignmentRowKeys: AssertRowKeys<DayAssignmentRow, DayAssignments> = true;
/** AS18's stop, exactly as `AssignmentsService.sortDayByTime`/`chronoOrder` read it. */
export interface DayStopRow {
id: number;
order_index: number | null;
effective_time: string | null;
located: number;
}
/**
* `day_assignments`/`places`/`day_accommodations`'s shape for AS16
* (`effectiveStart`) and AS18 (`listForTimeSort`), Kysely-typed the same way
* `DayAssignmentsKyselyDB` is above. There is no MikroORM relation from
* `DayAssignments` to `DayAccommodations` — `accommodation_id` is a plain
* `p.integer()` column on this entity, not a `manyToOne` (`day_accommodations`
* is Plan 3d's table; adding the relation means touching
* `src/db/entities/DayAssignments.entity.ts`, out of this task's scope) — so
* the QueryBuilder's relation-path `.join()` cannot express the LEFT JOIN at
* all, not just the correlated-subquery shape DY24 hit. Kysely joining the
* physical table name directly is the sanctioned next step down D3's
* escape-hatch order (`find/findOne → nativeUpdate → qb() → em.getKysely()`).
*/
interface AssignmentTimeSortKyselyDB {
day_assignments: {
id: number;
day_id: number;
place_id: number;
order_index: number | null;
assignment_time: string | null;
accommodation_id: number | null;
created_at: string | null;
};
places: {
id: number;
place_time: string | null;
lat: number | null;
lng: number | null;
};
day_accommodations: {
id: number;
check_in: string | null;
};
}
export class DayAssignmentsRepository extends TrekRepository<DayAssignments> {
/** The DY1/DY3/AS1/AS3 projection's SELECT list, shared by all three query shapes below. */
private assignmentWithPlaceSelect(platform: Platform) {
@@ -222,4 +291,222 @@ export class DayAssignmentsRepository extends TrekRepository<DayAssignments> {
.where('accommodation_id', '=', accommodation_id)
.execute();
}
// ---------------------------------------------------------------------------
// Plan 3c Task 3 (`AssignmentsService`) — appended after Task 2's own
// methods above, per this task's file-ownership rule.
// ---------------------------------------------------------------------------
/**
* AS9 (`assignmentExistsInDay`) — `SELECT da.id FROM day_assignments da
* JOIN days d ON da.day_id = d.id WHERE da.id = ? AND da.day_id = ? AND
* d.trip_id = ?`. Raw-bind (`number | string`, D4's T5 escape hatch,
* `TripsRepository.findAccessible`'s precedent): the legacy guard binds
* the route's raw params straight into the statement with no `Number()`/
* `toRowId` conversion of its own, so this must accept and bind exactly
* what it's handed, not coerce it first.
*/
async existsInDay(id: number | string, day_id: number | string, trip_id: number | string): Promise<boolean> {
const row = await this.qb('da')
.join('da.day', 'd')
.select(['da.id'])
.where('da.id = ? AND da.day_id = ? AND d.trip_id = ?', [id, day_id, trip_id])
.execute<{ id: number } | undefined>('get', false);
return !!row;
}
/**
* AS12 (`getAssignmentForTrip`) — `SELECT da.* FROM day_assignments da
* JOIN days d ON da.day_id = d.id WHERE da.id = ? AND d.trip_id = ?`.
* Same raw-bind seam as `existsInDay` above — every real caller
* (`AssignmentOpsController`, `AssignmentsMcp`, `ItineraryRpc`) hands this
* the route/tool id verbatim, and `ItineraryRpc.unassign` reads
* `existing.day_id` off the result, so this is a genuine re-select, not
* only an existence guard.
*/
async findInTrip(id: number | string, trip_id: number | string): Promise<DayAssignmentRow | undefined> {
const row = await this.qb('da')
.join('da.day', 'd')
.select(['da.*'])
.where('da.id = ? AND d.trip_id = ?', [id, trip_id])
.execute<DayAssignmentRow | undefined>('get', false);
return row ?? undefined;
}
/**
* AS6 (`createAssignment`'s append-position read) — `SELECT
* MAX(order_index) as max FROM day_assignments WHERE day_id = ?`, read as
* the highest row by an ordered `limit(1)` (`DaysRepository.maxDayNumber`'s
* precedent — SQLite sorts `NULL` last under `DESC`, so an all-NULL or
* empty table folds the same way `MAX()` ignoring every `NULL` does).
* Returns the raw nullable value, NOT folded to `0`/`-1` here: the
* service's explicit `maxOrder !== null ? maxOrder : -1` check (AS6's
* ruling) needs to tell "no rows" from a stored `0` order_index, which a
* `?? -1` fold would collapse identically — unlike `DaysRepository
* .maxDayNumber`, this repository method must NOT pre-fold the null case.
*/
async maxOrderIndex(day_id: number): Promise<number | null> {
const row = await this.qb('da')
.select('da.order_index')
.where({ day: day_id })
.orderBy({ order_index: 'desc' })
.limit(1)
.execute<{ order_index: number | null } | undefined>('get', false);
return row?.order_index ?? null;
}
/**
* AS7 — `UPDATE day_assignments SET order_index = order_index + 1 WHERE
* day_id = ? AND order_index >= ?`, a column-from-column update
* (`InviteTokensRepository.incrementUsedCount`'s `columnIncrementedBy`
* precedent — `nativeUpdate`'s `EntityData` shape doesn't accept a raw
* fragment value, so this goes through `qb().update()` instead).
*/
async shiftOrderFrom(day_id: number, from: number): Promise<void> {
const platform = this.getEntityManager().getPlatform();
await this.qb()
.update({ order_index: columnIncrementedBy(platform, 'order_index', 1) })
.where({ day: day_id, order_index: { $gte: from } })
.execute('run');
}
/**
* AS8 — `INSERT INTO day_assignments (day_id, place_id, order_index,
* notes, accommodation_id) VALUES (?, ?, ?, ?, ?)`. The caller passes
* already-decided values (the `notes || null`/`accommodationId ?? null`
* coercions and the clamped `orderIndex` stay in the service, the same
* split `DaysRepository.createDay`'s docstring describes) — `em.insert()`
* returns the generated PK (R6's `lastInsertRowid` replacement).
*/
async insertAssignment(input: {
day_id: number;
place_id: number;
order_index: number;
notes: string | null;
accommodation_id: number | null;
}): Promise<number> {
return await this.insert({
day: input.day_id,
place: input.place_id,
order_index: input.order_index,
notes: input.notes,
accommodation_id: input.accommodation_id,
});
}
/** AS10 — `DELETE FROM day_assignments WHERE id = ?`. */
async deleteById(id: number): Promise<void> {
await this.nativeDelete({ id });
}
/**
* AS11 (`reorderAssignments`, day-scoped: `UPDATE day_assignments SET
* order_index = ? WHERE id = ? AND day_id = ?`) and AS19
* (`sortDayByTime`'s per-row write, NOT day-scoped: `UPDATE
* day_assignments SET order_index = ? WHERE id = ?`) — one method, both
* signatures, per the inventory's ruling ("keep both signatures"):
* `day_id` omitted (`undefined`) reproduces AS19's unscoped statement.
*/
async setOrderIndex(id: number, day_id: number | undefined, order_index: number): Promise<void> {
const where = day_id !== undefined ? { id, day: day_id } : { id };
await this.nativeUpdate(where, { order_index });
}
/** AS13 (`moveAssignment`'s source-day read) — `SELECT day_id FROM day_assignments WHERE id = ?`. */
async getDayId(id: number): Promise<number | undefined> {
const platform = this.getEntityManager().getPlatform();
// `day_id` is `persist(false)` (the physical FK mirror of the `day`
// relation) — a bare `'da.day_id'` select hits the same trap
// `assignmentWithPlaceSelect`'s `category_id` comment documents;
// `columnRef` selects the literal physical column instead.
const row = await this.qb('da')
.select([columnRef(platform, 'da.day_id').as('day_id')])
.where({ id })
.execute<{ day_id: number } | undefined>('get', false);
return row?.day_id;
}
/** AS14 — `UPDATE day_assignments SET day_id = ?, order_index = ? WHERE id = ?`. */
async moveToDay(id: number, day_id: number, order_index: number): Promise<void> {
await this.nativeUpdate({ id }, { day: day_id, order_index });
}
/**
* AS16 (`updateTime`'s pre-write read) — `SELECT da.day_id,
* COALESCE(da.assignment_time, p.place_time, acc.check_in) AS start FROM
* day_assignments da JOIN places p ON da.place_id = p.id LEFT JOIN
* day_accommodations acc ON acc.id = da.accommodation_id WHERE da.id = ?`.
* Kysely (see `AssignmentTimeSortKyselyDB`'s docstring for why: no ORM
* relation to `day_accommodations` exists to `.join()` through).
*/
async effectiveStart(id: number): Promise<{ day_id: number; start: string | null } | undefined> {
const row = await this.kysely<AssignmentTimeSortKyselyDB>()
.selectFrom('day_assignments as da')
.innerJoin('places as p', 'p.id', 'da.place_id')
.leftJoin('day_accommodations as acc', 'acc.id', 'da.accommodation_id')
.select((eb) => ['da.day_id as day_id', eb.fn.coalesce('da.assignment_time', 'p.place_time', 'acc.check_in').as('start')])
.where('da.id', '=', id)
.executeTakeFirst();
return row as { day_id: number; start: string | null } | undefined;
}
/**
* AS17 — `UPDATE day_assignments SET assignment_time = ?, assignment_end_time = ? WHERE id = ?`.
* The falsy-clears-to-null coercion (`placeTime || null`) stays in the
* service (AS17's ruling); this writes the already-decided values.
*/
async setTimes(id: number, assignment_time: string | null, assignment_end_time: string | null): Promise<void> {
await this.nativeUpdate({ id }, { assignment_time, assignment_end_time });
}
/**
* AS18 (`sortDayByTime`'s day-wide read) — `SELECT da.id, da.order_index,
* COALESCE(da.assignment_time, p.place_time, acc.check_in) as
* effective_time, (p.lat IS NOT NULL AND p.lng IS NOT NULL) as located
* FROM day_assignments da JOIN places p ON da.place_id = p.id LEFT JOIN
* day_accommodations acc ON acc.id = da.accommodation_id WHERE da.day_id
* = ? ORDER BY da.order_index ASC, da.created_at ASC, da.id ASC`. Same
* Kysely escape hatch as `effectiveStart`. The computed boolean column is
* expressed with the expression builder's own comparison/`.and()`
* combinators — never the banned `sql` tag — and SQLite returns it as the
* same `0`/`1` integer the legacy raw statement did.
*/
async listForTimeSort(day_id: number): Promise<DayStopRow[]> {
const rows = await this.kysely<AssignmentTimeSortKyselyDB>()
.selectFrom('day_assignments as da')
.innerJoin('places as p', 'p.id', 'da.place_id')
.leftJoin('day_accommodations as acc', 'acc.id', 'da.accommodation_id')
.select((eb) => [
'da.id as id',
'da.order_index as order_index',
eb.fn.coalesce('da.assignment_time', 'p.place_time', 'acc.check_in').as('effective_time'),
eb.and([eb('p.lat', 'is not', null), eb('p.lng', 'is not', null)]).as('located'),
])
.where('da.day_id', '=', day_id)
.orderBy('da.order_index', 'asc')
.orderBy('da.created_at', 'asc')
.orderBy('da.id', 'asc')
.execute();
return rows as unknown as DayStopRow[];
}
/** AS24 — `UPDATE day_assignments SET end_day = ? WHERE id = ?`. */
async setEndDay(id: number, end_day: number): Promise<void> {
await this.nativeUpdate({ id }, { end_day });
}
/** AS25 — `UPDATE day_assignments SET notes = ? WHERE id = ?`. */
async setNotes(id: number, notes: string | null): Promise<void> {
await this.nativeUpdate({ id }, { notes });
}
/** AS26 — `UPDATE day_assignments SET leg_transport_mode = ? WHERE id = ?`. */
async setLegMode(id: number, mode: string | null): Promise<void> {
await this.nativeUpdate({ id }, { leg_transport_mode: mode });
}
/** AS27 — `UPDATE day_assignments SET incoming_leg_transport_mode = ? WHERE id = ?`. */
async setIncomingLegMode(id: number, mode: string | null): Promise<void> {
await this.nativeUpdate({ id }, { incoming_leg_transport_mode: mode });
}
}
@@ -178,4 +178,25 @@ export class DaysRepository extends TrekRepository<Days> {
.execute<DayIdAndNumberRow | undefined>('get', false);
return row ?? undefined;
}
// ---------------------------------------------------------------------------
// Plan 3c Task 3 (`AssignmentsService`) — appended per the task's own
// file-ownership rule ("additive methods on Days/Places repositories if
// needed").
// ---------------------------------------------------------------------------
/**
* AS4 (`AssignmentsService.dayExists`) — `SELECT id FROM days WHERE id = ?
* AND trip_id = ?`. Raw-bind (`number | string`, D4's T5 escape hatch,
* `TripsRepository.findAccessible`'s precedent): the legacy guard binds
* the route's raw params with no `Number()`/`toRowId` conversion of its
* own, so this must accept and bind exactly what it's handed.
*/
async existsInTrip(id: number | string, trip_id: number | string): Promise<boolean> {
const row = await this.qb('d')
.select(['d.id'])
.where('d.id = ? AND d.trip_id = ?', [id, trip_id])
.execute<{ id: number } | undefined>('get', false);
return !!row;
}
}
@@ -1,9 +1,15 @@
import { Module } from '@nestjs/common';
import { MikroOrmModule } from '@mikro-orm/nestjs';
import { JourneyDomainModule } from '../journey/journey-domain.module';
import { PermissionsModule } from '../permissions/permissions.module';
import { QueryHelpersModule } from '../query-helpers/query-helpers.module';
import { RealtimeModule } from '../realtime/realtime.module';
import { AssignmentsService } from './assignments.service';
import { DayAssignments } from '../../db/entities/DayAssignments.entity';
import { AssignmentParticipants } from '../../db/entities/AssignmentParticipants.entity';
import { Days } from '../../db/entities/Days.entity';
import { Places } from '../../db/entities/Places.entity';
import { TripMembers } from '../../db/entities/TripMembers.entity';
/**
* The assignments SERVICE, split from the controller/MCP/RPC surfaces (the
@@ -12,10 +18,25 @@ import { AssignmentsService } from './assignments.service';
* that stays off the DaysModule → PlacesModule → AssignmentsModule loop.
* That is what lets PlacesModule import this and places.mcp.ts inject the
* service, which retired assignments.bridge. Everything here is a leaf:
* none of the four imports reaches the days or places domains.
* none of the four service imports reaches the days or places domains.
*
* `MikroOrmModule.forFeature([DayAssignments, AssignmentParticipants, Days,
* Places, TripMembers])` registers `DayAssignmentsRepository`/
* `AssignmentParticipantsRepository`/`DaysRepository`/`PlacesRepository`/
* `TripMembersRepository` for `AssignmentsService`'s `@InjectRepository`
* constructor params (Plan 3c Task 3) — the entity classes only, not the
* `DaysModule`/`PlacesModule` modules themselves, so the loop this module's
* docstring already avoids stays avoided (`DaysModule`'s own precedent for
* pulling in `Trips` the same way).
*/
@Module({
imports: [PermissionsModule, QueryHelpersModule, JourneyDomainModule, RealtimeModule],
imports: [
PermissionsModule,
QueryHelpersModule,
JourneyDomainModule,
RealtimeModule,
MikroOrmModule.forFeature([DayAssignments, AssignmentParticipants, Days, Places, TripMembers]),
],
providers: [AssignmentsService],
exports: [AssignmentsService],
})
+169 -134
View File
@@ -1,4 +1,5 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@mikro-orm/nestjs';
import { chronoOrder, type RoadtripVia, type TrekWsPayload, type TrekWsTripEventName } from '@trek/shared';
import { isEmptyReanchoring, reanchorByStopOrder, type AnchoredVia } from '@trek/shared/roadtrip';
import { RealtimeService } from '../realtime/realtime.service';
@@ -6,20 +7,23 @@ import { DatabaseService, type TripAccess } from '../database/database.service';
import { PermissionsService } from '../permissions/permissions.service';
import { QueryHelpersService } from '../query-helpers/query-helpers.service';
import { formatAssignmentWithPlace } from '../common/rowShape';
import type { AssignmentRow, DayAssignment, User, Participant } from '../../types';
import type { User } from '../../types';
import { JourneyDomainService } from '../journey/journey-domain.service';
import { UnitOfWork } from '../database/unit-of-work';
import { toRowId } from '../common/row-id';
import { DayAssignments } from '../../db/entities/DayAssignments.entity';
import type { DayAssignmentsRepository, DayStopRow } from '../../db/repositories/DayAssignments.repository';
import { AssignmentParticipants } from '../../db/entities/AssignmentParticipants.entity';
import type { AssignmentParticipantsRepository } from '../../db/repositories/AssignmentParticipants.repository';
import { Days } from '../../db/entities/Days.entity';
import type { DaysRepository } from '../../db/repositories/Days.repository';
import { Places } from '../../db/entities/Places.entity';
import type { PlacesRepository } from '../../db/repositories/Places.repository';
import { TripMembers } from '../../db/entities/TripMembers.entity';
import type { TripMembersRepository } from '../../db/repositories/TripMembers.repository';
type Trip = TripAccess;
/** One stop of a day as the time sort reads it. */
interface DayStopRow {
id: number;
order_index: number;
effective_time: string | null;
located: number;
}
/**
* What saving a time changed besides the stop itself, so each caller can tell the
* trip. `reordered` carries the day's whole order and `vias` the day's re-pinned
@@ -56,6 +60,26 @@ function sortMinutes(time: string | null): number | null {
* QueryHelpersService (shared with the day, share and place services).
* Every consumer injects this class (assignments.bridge.ts is deleted —
* PlacesMcp injects it from AssignmentsDomainModule now).
*
* The day-assignment/participant SQL now lives in `DayAssignmentsRepository`/
* `AssignmentParticipantsRepository` (Plan 3c Task 3, consuming Task 2's
* `findWithPlaceAndCategory`/`listForDay` projection unchanged for AS1/AS3);
* AS20–AS23 (`roadtrip_vias`) stay raw on `DatabaseService`, `// ASn — Plan
* 3d` marked — that table belongs to Plan 3d. AS5 (`placeExists`) is the one
* exception to "SQL lives in a repository method": `Places.repository.ts`
* was another task's exclusive, actively-edited file this session (never
* touched here), so the equivalent one-line `qb()` raw-condition read is
* inlined below rather than added as a `PlacesRepository` method — flagged
* in the task report for a follow-up to move it once that file is free.
*
* Assignment ids arriving from a route/tool are an **affinity seam** for the
* mutation methods (`toRowId(id)!`, program rule 15) — every real call site
* only ever reaches a mutation downstream of its own gate check in the same
* request (`assignmentExistsInDay`/`getAssignmentForTrip`, both of which
* stay on the legacy raw-bind seam themselves, matching `TripsRepository
* .findAccessible`'s documented `number | string` pass-through), so the
* non-null assertion is dead-code-safe, the same shape `DaysService` already
* uses for its own single `getDay` gate.
*/
@Injectable()
export class AssignmentsService {
@@ -66,6 +90,11 @@ export class AssignmentsService {
private readonly queryHelpers: QueryHelpersService,
private readonly journey: JourneyDomainService,
private readonly uow: UnitOfWork,
@InjectRepository(DayAssignments) private readonly dayAssignmentsRepo: DayAssignmentsRepository,
@InjectRepository(AssignmentParticipants) private readonly assignmentParticipantsRepo: AssignmentParticipantsRepository,
@InjectRepository(Days) private readonly daysRepo: DaysRepository,
@InjectRepository(Places) private readonly placesRepo: PlacesRepository,
@InjectRepository(TripMembers) private readonly tripMembersRepo: TripMembersRepository,
) {}
async verifyTripAccess(tripId: string | number, userId: number) {
@@ -97,19 +126,9 @@ export class AssignmentsService {
* the moved row back in exactly this shape.
*/
async getAssignmentWithPlace(assignmentId: number | bigint) {
const a = this.dbs.get<AssignmentRow>(`
SELECT da.*, p.id as place_id, p.name as place_name, p.description as place_description,
p.lat, p.lng, p.address, p.category_id, p.price, p.currency as place_currency,
COALESCE(da.assignment_time, p.place_time) as place_time,
COALESCE(da.assignment_end_time, p.end_time) as end_time,
p.duration_minutes, p.notes as place_notes,
p.image_url, p.transport_mode, p.google_place_id, p.google_ftid, p.osm_id, p.amap_poi_id, p.website, p.phone, p.stop_type, p.fill_percent,
c.name as category_name, c.color as category_color, c.icon as category_icon
FROM day_assignments da
JOIN places p ON da.place_id = p.id
LEFT JOIN categories c ON p.category_id = c.id
WHERE da.id = ?
`, assignmentId);
// AS1 — `DayAssignmentsRepository.findWithPlaceAndCategory`, Task 2's
// projection, consumed unchanged.
const a = await this.dayAssignmentsRepo.findWithPlaceAndCategory(Number(assignmentId));
if (!a) return null;
@@ -117,41 +136,36 @@ export class AssignmentsService {
// one wire shape regardless of which read path produced it.
const tags = (await this.queryHelpers.loadTagsByPlaceIds([a.place_id], { compact: true }))[a.place_id] || [];
const participants = this.dbs.all<Participant>(`
SELECT ap.user_id, COALESCE(u.display_name, u.username) AS username, u.avatar
FROM assignment_participants ap
JOIN users u ON ap.user_id = u.id
WHERE ap.assignment_id = ?
`, a.id);
// AS2 — `AssignmentParticipantsRepository.listWithDisplayName`
// (COALESCE(display_name, username), unlike QH3's raw username).
const participants = await this.assignmentParticipantsRepo.listWithDisplayName(a.id);
// The same shaper the list path uses. It was spelled out here as a third hand-kept
// copy of the place shape, and the copy silently dropped `stop_type`: the optimistic
// row the client had drawn as a fuel stop was replaced, a beat later, by this answer
// without it — so a petrol station turned into an ordinary numbered place while you
// watched.
//
// `formatAssignmentWithPlace` is typed on `AssignmentWithPlaceRow` directly
// (Plan 3c Task 2 review, "For Task 3" §6.3) — no cast needed here.
return formatAssignmentWithPlace(a, tags, participants);
}
async listDayAssignments(dayId: string | number) {
const assignments = this.dbs.all<AssignmentRow>(`
SELECT da.*, p.id as place_id, p.name as place_name, p.description as place_description,
p.lat, p.lng, p.address, p.category_id, p.price, p.currency as place_currency,
COALESCE(da.assignment_time, p.place_time) as place_time,
COALESCE(da.assignment_end_time, p.end_time) as end_time,
p.duration_minutes, p.notes as place_notes,
p.image_url, p.transport_mode, p.google_place_id, p.google_ftid, p.osm_id, p.amap_poi_id, p.website, p.phone, p.stop_type, p.fill_percent,
c.name as category_name, c.color as category_color, c.icon as category_icon
FROM day_assignments da
JOIN places p ON da.place_id = p.id
LEFT JOIN categories c ON p.category_id = c.id
WHERE da.day_id = ?
ORDER BY da.order_index ASC, da.created_at ASC
`, dayId);
// AS3 — `DayAssignmentsRepository.listForDay`, Task 2's projection (the
// same statement text DY1 uses), consumed unchanged. `toRowId`, not a
// bare `Number()` (Task 2 review point 7): the repository takes a real
// number and the sole caller (`DayAssignmentsController.list`) already
// gates on `dayExists` in the same request.
const assignments = await this.dayAssignmentsRepo.listForDay(toRowId(dayId)!);
const placeIds = [...new Set(assignments.map(a => a.place_id))];
const tagsByPlaceId = await this.queryHelpers.loadTagsByPlaceIds(placeIds, { compact: true });
const assignmentIds = assignments.map(a => a.id);
// QH3 (`QueryHelpersService.loadParticipantsByAssignmentIds`) — deliberately
// WITHOUT the COALESCE `getAssignmentWithPlace`/`getParticipants` apply
// (inventory §18.10); unchanged from before this conversion.
const participantsByAssignment = await this.queryHelpers.loadParticipantsByAssignmentIds(assignmentIds);
return assignments.map(a => {
@@ -159,12 +173,25 @@ export class AssignmentsService {
});
}
/** AS4 — `DaysRepository.existsInTrip`. Raw-bind pass-through, unchanged. */
async dayExists(dayId: string | number, tripId: string | number) {
return !!this.dbs.get('SELECT id FROM days WHERE id = ? AND trip_id = ?', dayId, tripId);
return await this.daysRepo.existsInTrip(dayId, tripId);
}
/**
* AS5 — `SELECT id FROM places WHERE id = ? AND trip_id = ?`. `Places
* .repository.ts` was another task's exclusive, actively-edited file this
* session (see the class docstring) — inlined here as the one exception to
* "SQL lives in a repository method" rather than adding a method there.
* Same raw-bind seam as `dayExists`/`DayAssignmentsRepository.existsInDay`.
*/
async placeExists(placeId: unknown, tripId: string | number) {
return !!this.dbs.get('SELECT id FROM places WHERE id = ? AND trip_id = ?', placeId, tripId);
const row = await this.placesRepo
.qb('p')
.select(['p.id'])
.where('p.id = ? AND p.trip_id = ?', [placeId, tripId])
.execute<{ id: number } | undefined>('get', false);
return !!row;
}
/**
@@ -175,73 +202,82 @@ export class AssignmentsService {
* from a place the traveller added, so it draws the hotel a second time.
*/
async createAssignment(dayId: string | number, placeId: unknown, notes?: string | null, opts: { accommodationId?: number; orderIndex?: number } = {}) {
const result = await this.uow.transactional(async () => {
const maxOrder = this.dbs.get<{ max: number | null }>('SELECT MAX(order_index) as max FROM day_assignments WHERE day_id = ?', dayId)!;
const end = (maxOrder.max !== null ? maxOrder.max : -1) + 1;
// Downstream of the caller's own dayExists/placeExists gate in the same
// request (every real call site), so the non-null assertion is
// dead-code-safe — the class docstring's affinity-seam note.
const dayIdNum = toRowId(dayId)!;
const placeIdNum = toRowId(placeId)!;
const insertedId = await this.uow.transactional(async () => {
// AS6 — the explicit null check (not `||`) is load-bearing: a stored 0
// order_index must survive, which `maxOrder || -1` would not.
const maxOrder = await this.dayAssignmentsRepo.maxOrderIndex(dayIdNum);
const end = (maxOrder !== null ? maxOrder : -1) + 1;
// Somewhere in the middle when the caller says so, which means everything from
// there on moves down. The end is still the default and still what every caller
// but one asks for.
const orderIndex = opts.orderIndex !== undefined ? Math.max(0, Math.min(opts.orderIndex, end)) : end;
if (orderIndex < end) {
this.dbs.run('UPDATE day_assignments SET order_index = order_index + 1 WHERE day_id = ? AND order_index >= ?', dayId, orderIndex);
await this.dayAssignmentsRepo.shiftOrderFrom(dayIdNum, orderIndex); // AS7
}
return this.dbs.run(
'INSERT INTO day_assignments (day_id, place_id, order_index, notes, accommodation_id) VALUES (?, ?, ?, ?, ?)',
dayId, placeId, orderIndex, notes || null, opts.accommodationId ?? null
);
});
return await this.getAssignmentWithPlace(result.lastInsertRowid);
}
async assignmentExistsInDay(id: string | number, dayId: string | number, tripId: string | number) {
return !!this.dbs.get(
'SELECT da.id FROM day_assignments da JOIN days d ON da.day_id = d.id WHERE da.id = ? AND da.day_id = ? AND d.trip_id = ?',
id, dayId, tripId
);
}
async deleteAssignment(id: string | number): Promise<void> {
this.dbs.run('DELETE FROM day_assignments WHERE id = ?', id);
}
async reorderAssignments(dayId: string | number, orderedIds: number[]): Promise<void> {
const update = this.dbs.prepare('UPDATE day_assignments SET order_index = ? WHERE id = ? AND day_id = ?');
await this.uow.transactional(async () => {
orderedIds.forEach((id: number, index: number) => {
update.run(index, id, dayId);
return await this.dayAssignmentsRepo.insertAssignment({ // AS8
day_id: dayIdNum,
place_id: placeIdNum,
order_index: orderIndex,
notes: notes || null,
accommodation_id: opts.accommodationId ?? null,
});
});
return await this.getAssignmentWithPlace(insertedId);
}
/** AS9 — `DayAssignmentsRepository.existsInDay`. Raw-bind pass-through, unchanged. */
async assignmentExistsInDay(id: string | number, dayId: string | number, tripId: string | number) {
return await this.dayAssignmentsRepo.existsInDay(id, dayId, tripId);
}
/** AS10 — `DayAssignmentsRepository.deleteById`. */
async deleteAssignment(id: string | number): Promise<void> {
await this.dayAssignmentsRepo.deleteById(toRowId(id)!);
}
/**
* AS11 — `DayAssignmentsRepository.setOrderIndex`, day-scoped, one row per
* id, sequentially and in the legacy's own order (not `Promise.all` — the
* program's transaction-ordering rule).
*/
async reorderAssignments(dayId: string | number, orderedIds: number[]): Promise<void> {
const dayIdNum = toRowId(dayId)!;
await this.uow.transactional(async () => {
for (const [index, id] of orderedIds.entries()) {
await this.dayAssignmentsRepo.setOrderIndex(id, dayIdNum, index);
}
});
}
/** AS12 — `DayAssignmentsRepository.findInTrip`. Raw-bind pass-through, unchanged. */
async getAssignmentForTrip(id: string | number, tripId: string | number) {
return this.dbs.get<DayAssignment>(`
SELECT da.* FROM day_assignments da
JOIN days d ON da.day_id = d.id
WHERE da.id = ? AND d.trip_id = ?
`, id, tripId);
return await this.dayAssignmentsRepo.findInTrip(id, tripId);
}
async moveAssignment(id: string | number, newDayId: unknown, orderIndex: number | null | undefined) {
const idNum = toRowId(id)!;
// The source day comes from the row, not the caller — callers can't lie
// about (or race on) where the assignment was.
const oldDayId = await this.uow.transactional(async () => {
const row = this.dbs.get<{ day_id: number }>('SELECT day_id FROM day_assignments WHERE id = ?', id);
this.dbs.run('UPDATE day_assignments SET day_id = ?, order_index = ? WHERE id = ?', newDayId, orderIndex ?? 0, id);
return row?.day_id;
const dayId = await this.dayAssignmentsRepo.getDayId(idNum); // AS13
await this.dayAssignmentsRepo.moveToDay(idNum, toRowId(newDayId)!, orderIndex ?? 0); // AS14
return dayId;
});
const updated = await this.getAssignmentWithPlace(Number(id));
const updated = await this.getAssignmentWithPlace(idNum);
return { assignment: updated, oldDayId };
}
/** AS15 — `AssignmentParticipantsRepository.listWithDisplayName`, the same AS2/AS31 statement. */
async getParticipants(assignmentId: string | number) {
return this.dbs.all(`
SELECT ap.user_id, COALESCE(u.display_name, u.username) AS username, u.avatar
FROM assignment_participants ap
JOIN users u ON ap.user_id = u.id
WHERE ap.assignment_id = ?
`, assignmentId);
return await this.assignmentParticipantsRepo.listWithDisplayName(toRowId(assignmentId)!);
}
/**
@@ -258,19 +294,15 @@ export class AssignmentsService {
* same.
*/
async updateTime(id: string | number, placeTime: unknown, endTime: unknown): Promise<AssignmentTimeUpdate> {
const idNum = toRowId(id)!;
const sorted = await this.uow.transactional(async () => {
const stored = this.dbs.get<{ day_id: number; start: string | null }>(`
SELECT da.day_id, COALESCE(da.assignment_time, p.place_time, acc.check_in) AS start
FROM day_assignments da
JOIN places p ON da.place_id = p.id
LEFT JOIN day_accommodations acc ON acc.id = da.accommodation_id
WHERE da.id = ?
`, id);
// AS16 — the three-way COALESCE, via Kysely (no ORM relation to
// `day_accommodations` — see `DayAssignmentsRepository`'s docstring).
const stored = await this.dayAssignmentsRepo.effectiveStart(idNum);
// Falsy times (null, undefined, '') all clear the override — an empty
// string is a clear, not a stored value.
this.dbs.run('UPDATE day_assignments SET assignment_time = ?, assignment_end_time = ? WHERE id = ?',
placeTime || null, endTime || null, id);
// string is a clear, not a stored value. AS17.
await this.dayAssignmentsRepo.setTimes(idNum, (placeTime as string | null | undefined) || null, (endTime as string | null | undefined) || null);
// Only a start that moved sorts. An end is a label. A start sent again as it
// stood (the place form saving an End, the stay dialog taking one off, an MCP
@@ -286,7 +318,7 @@ export class AssignmentsService {
const vias = sorted?.viasMoved ? { dayId: sorted.dayId, vias: await this.listDayVias(sorted.dayId) } : null;
return {
assignment: await this.getAssignmentWithPlace(Number(id)),
assignment: await this.getAssignmentWithPlace(idNum),
reordered: sorted ? { dayId: sorted.dayId, orderedIds: sorted.orderedIds } : null,
vias,
};
@@ -302,15 +334,9 @@ export class AssignmentsService {
// counted as untimed and stayed wherever it had been dropped, so pinning an
// afternoon stop sorted that one and left the hotel sitting in front of or
// behind it by accident.
const rows = this.dbs.all<DayStopRow>(`
SELECT da.id, da.order_index, COALESCE(da.assignment_time, p.place_time, acc.check_in) as effective_time,
(p.lat IS NOT NULL AND p.lng IS NOT NULL) as located
FROM day_assignments da
JOIN places p ON da.place_id = p.id
LEFT JOIN day_accommodations acc ON acc.id = da.accommodation_id
WHERE da.day_id = ?
ORDER BY da.order_index ASC, da.created_at ASC, da.id ASC
`, dayId);
//
// AS18 — `DayAssignmentsRepository.listForTimeSort`, via Kysely.
const rows = await this.dayAssignmentsRepo.listForTimeSort(dayId);
const sorted = chronoOrder(rows, row => sortMinutes(row.effective_time));
if (sorted.every((row, i) => row === rows[i])) return null;
@@ -319,11 +345,12 @@ export class AssignmentsService {
// goes out as a list of ids and every client numbers it by position, so keys kept
// with their gaps would put the day notes and bookings that sort between stops in
// one place for the writer, who reads the day back, and in another for everyone
// else. Only a stop whose key changes is written.
const update = this.dbs.prepare('UPDATE day_assignments SET order_index = ? WHERE id = ?');
sorted.forEach((row, i) => {
if (row.order_index !== i) update.run(i, row.id);
});
// else. Only a stop whose key changes is written. AS19 — no day scoping,
// unlike AS11's `reorderAssignments` (`setOrderIndex`'s `day_id` left
// `undefined`), sequentially and in the legacy's own order.
for (const [i, row] of sorted.entries()) {
if (row.order_index !== i) await this.dayAssignmentsRepo.setOrderIndex(row.id, undefined, i);
}
return { dayId, orderedIds: sorted.map(row => row.id), viasMoved: await this.reanchorVias(dayId, rows, sorted) };
}
@@ -352,13 +379,16 @@ export class AssignmentsService {
// is right for a stop the sort made last and wrong for one that was last already.
const lastAt = previousIds.length - 1;
const seam = previousIds[lastAt] === nextIds[lastAt] ? lastAt : null;
// AS20 — Plan 3d (`roadtrip_vias`)
const vias = this.dbs.all<AnchoredVia>('SELECT id, after_order_index, lat, lng FROM roadtrip_vias WHERE day_id = ?', dayId)
.filter(via => via.after_order_index !== seam);
const plan = reanchorByStopOrder(vias, previousIds, nextIds);
for (const viaId of plan.remove) {
// AS21 — Plan 3d
this.dbs.run('DELETE FROM roadtrip_vias WHERE id = ? AND day_id = ?', viaId, dayId);
}
for (const via of plan.vias) {
// AS22 — Plan 3d
this.dbs.run('UPDATE roadtrip_vias SET after_order_index = ? WHERE id = ? AND day_id = ?', via.after_order_index, via.id, dayId);
}
return !isEmptyReanchoring(plan);
@@ -367,6 +397,9 @@ export class AssignmentsService {
/**
* The day's vias in the shape the road trip routes broadcast them. RoadtripService
* has this query too, but its module imports this one, so it cannot be injected here.
*
* AS23 — Plan 3d (`roadtrip_vias`): a deliberate duplicate of RoadtripService's
* own query, per the legacy docstring's own note — do not dedupe.
*/
private async listDayVias(dayId: number): Promise<RoadtripVia[]> {
return this.dbs.all<RoadtripVia>(
@@ -378,9 +411,11 @@ export class AssignmentsService {
);
}
/** AS24 — `DayAssignmentsRepository.setEndDay`. */
async setEndDay(id: string | number, endDay: boolean) {
this.dbs.run('UPDATE day_assignments SET end_day = ? WHERE id = ?', endDay ? 1 : 0, id);
return await this.getAssignmentWithPlace(Number(id));
const idNum = toRowId(id)!;
await this.dayAssignmentsRepo.setEndDay(idNum, endDay ? 1 : 0);
return await this.getAssignmentWithPlace(idNum);
}
/**
@@ -389,33 +424,36 @@ export class AssignmentsService {
* invisible in the app. Falsy notes ('' or null) clear the column, the same
* `notes || null` normalisation createAssignment applies. No auto-sort and no
* journey reconcile: the note affects neither the day order nor the skeleton
* mirror (same as the transport-mode writes).
* mirror (same as the transport-mode writes). AS25.
*/
async updateNotes(id: string | number, notes: string | null | undefined) {
this.dbs.run('UPDATE day_assignments SET notes = ? WHERE id = ?', notes || null, id);
return await this.getAssignmentWithPlace(Number(id));
const idNum = toRowId(id)!;
await this.dayAssignmentsRepo.setNotes(idNum, notes || null);
return await this.getAssignmentWithPlace(idNum);
}
/**
* Set the travel mode of the leg leaving this stop (#1281). null clears the
* override so the leg falls back to the day's default_transport_mode. This is
* sticky by design: changing the whole-day default never touches a leg that
* carries its own explicit mode.
* carries its own explicit mode. AS26.
*/
async setLegTransportMode(id: string | number, mode: string | null) {
this.dbs.run('UPDATE day_assignments SET leg_transport_mode = ? WHERE id = ?', mode ?? null, id);
return await this.getAssignmentWithPlace(Number(id));
const idNum = toRowId(id)!;
await this.dayAssignmentsRepo.setLegMode(idNum, mode ?? null);
return await this.getAssignmentWithPlace(idNum);
}
/**
* Set the travel mode of the leg arriving at this stop (#1281 boundary legs).
* Mirrors setLegTransportMode but targets incoming_leg_transport_mode; inert
* when the previous timeline element is a place (the column is only read for
* non-place origins like a booking arrival or a morning hotel departure).
* non-place origins like a booking arrival or a morning hotel departure). AS27.
*/
async setIncomingLegTransportMode(id: string | number, mode: string | null) {
this.dbs.run('UPDATE day_assignments SET incoming_leg_transport_mode = ? WHERE id = ?', mode ?? null, id);
return await this.getAssignmentWithPlace(Number(id));
const idNum = toRowId(id)!;
await this.dayAssignmentsRepo.setIncomingLegMode(idNum, mode ?? null);
return await this.getAssignmentWithPlace(idNum);
}
/**
@@ -426,21 +464,18 @@ export class AssignmentsService {
* the request would strand a trip whose membership changed underneath it.
*/
async setParticipants(assignmentId: string | number, userIds: number[], tripId: string | number) {
const roster = await this.dbs.rosterUserIds(tripId);
const idNum = toRowId(assignmentId)!;
// AS28 — `TripMembersRepository.rosterUserIds`; off-roster ids drop silently.
const roster = await this.tripMembersRepo.rosterUserIds(tripId);
const scoped = userIds.filter(id => roster.has(id));
await this.uow.transactional(async () => {
this.dbs.run('DELETE FROM assignment_participants WHERE assignment_id = ?', assignmentId);
await this.assignmentParticipantsRepo.deleteForAssignment(idNum); // AS29
if (scoped.length > 0) {
const insert = this.dbs.prepare('INSERT OR IGNORE INTO assignment_participants (assignment_id, user_id) VALUES (?, ?)');
for (const userId of scoped) insert.run(assignmentId, userId);
await this.assignmentParticipantsRepo.insertIgnore(idNum, scoped); // AS30 — `upsertMany`/`onConflictAction: 'ignore'`
}
});
return this.dbs.all(`
SELECT ap.user_id, COALESCE(u.display_name, u.username) AS username, u.avatar
FROM assignment_participants ap
JOIN users u ON ap.user_id = u.id
WHERE ap.assignment_id = ?
`, assignmentId);
// AS31
return await this.assignmentParticipantsRepo.listWithDisplayName(idNum);
}
}
+18 -3
View File
@@ -1,4 +1,5 @@
import type { AssignmentRow, Tag, Participant } from '../../types';
import type { Tag, Participant } from '../../types';
import type { AssignmentWithPlaceRow } from '../../db/repositories/DayAssignments.repository';
import type { PlaceRatingRow } from '../query-helpers/query-helpers.service';
/**
@@ -8,8 +9,22 @@ import type { PlaceRatingRow } from '../query-helpers/query-helpers.service';
* free functions too.
*/
/** Reshape a flat assignment+place DB row into the nested API response shape with embedded place, tags, and participants. */
export function formatAssignmentWithPlace(a: AssignmentRow, tags: Partial<Tag>[], participants: Participant[]) {
/**
* Reshape a flat assignment+place DB row into the nested API response shape with
* embedded place, tags, and participants.
*
* Typed on `AssignmentWithPlaceRow` (`DayAssignmentsRepository`'s own DY1/DY3/
* AS1/AS3 projection row) — Plan 3c Task 2 review, "For Task 3" §6.3: the
* legacy `types.ts#AssignmentRow` narrows several columns to non-null that
* the physical projection genuinely returns nullable (rule 16), and Task 2
* bridged the gap with a documented `as unknown as AssignmentRow` cast at
* its one call site rather than widen the type. Every real call site
* (`DaysService.list`, `AssignmentsService.getAssignmentWithPlace`/
* `listDayAssignments`) passes this same repository row, so typing the
* parameter on it directly removes all three casts in one change instead of
* adding a fourth.
*/
export function formatAssignmentWithPlace(a: AssignmentWithPlaceRow, tags: Partial<Tag>[], participants: Participant[]) {
return {
id: a.id,
day_id: a.day_id,
+7 -6
View File
@@ -6,7 +6,7 @@ import { DatabaseService, type TripAccess } from '../database/database.service';
import { PermissionsService } from '../permissions/permissions.service';
import { QueryHelpersService } from '../query-helpers/query-helpers.service';
import { formatAssignmentWithPlace } from '../common/rowShape';
import type { AssignmentRow, User } from '../../types';
import type { User } from '../../types';
import { UnitOfWork } from '../database/unit-of-work';
import { toRowId } from '../common/row-id';
import { Days } from '../../db/entities/Days.entity';
@@ -193,11 +193,12 @@ export class DaysService {
const assignmentsByDayId: Record<number, ReturnType<typeof formatAssignmentWithPlace>[]> = {};
for (const a of allAssignments) {
if (!assignmentsByDayId[a.day_id]) assignmentsByDayId[a.day_id] = [];
// The repository row is honestly nullable per column (rule 16); `AssignmentRow`
// (types.ts) narrows some of those to non-null the same way the legacy
// `this.db.all<AssignmentRow>(...)` cast already trusted unchecked — same trust
// boundary, moved from the raw-SQL generic to this call site.
assignmentsByDayId[a.day_id].push(formatAssignmentWithPlace(a as unknown as AssignmentRow, tagsByPlaceId[a.place_id] || [], participantsByAssignment[a.id] || []));
// Plan 3c Task 2 review, "For Task 3" §6.3: `formatAssignmentWithPlace`
// is now typed on the repository's own `AssignmentWithPlaceRow` (rule
// 16's honestly-nullable columns), so no cast is needed here — the
// `as unknown as AssignmentRow` this line used to carry moved to
// `rowShape.ts`'s parameter type instead, once, for every call site.
assignmentsByDayId[a.day_id].push(formatAssignmentWithPlace(a, tagsByPlaceId[a.place_id] || [], participantsByAssignment[a.id] || []));
}
const allNotes = await this.dayNotesRepo.listByDayIds(dayIds);