mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-04 01:44:13 +00:00
refactor(packing): packing items, bags and templates through repositories
This commit is contained in:
@@ -1,4 +1,253 @@
|
||||
import type { PackingBags } from '../entities/PackingBags.entity';
|
||||
import { type AssertRowKeys } from './_shared/rows';
|
||||
import { TrekRepository } from './_shared/trek-repository';
|
||||
import { presenceSet } from './_shared/presence-set';
|
||||
|
||||
export class PackingBagsRepository extends TrekRepository<PackingBags> {}
|
||||
/** A bare `packing_bags` row — every scalar column, incl. the two `persist(false)` relation mirrors (`trip_id`, `user_id`). */
|
||||
export interface PackingBagRow {
|
||||
id: number;
|
||||
trip_id: number;
|
||||
name: string;
|
||||
color: string;
|
||||
weight_limit_grams: number | null;
|
||||
sort_order: number | null;
|
||||
created_at: string | null;
|
||||
user_id: number | null;
|
||||
}
|
||||
|
||||
const _packingBagRowKeys: AssertRowKeys<PackingBagRow, PackingBags> = true;
|
||||
|
||||
/** PK46's assignee-joined projection (`updateBag`'s re-select). */
|
||||
export interface PackingBagWithAssigneeRow extends PackingBagRow {
|
||||
assigned_username: string | null;
|
||||
}
|
||||
|
||||
/** PK40's member-with-user projection (`setBagMembers`'s re-select). */
|
||||
export interface PackingBagMemberWithUserRow {
|
||||
user_id: number;
|
||||
username: string;
|
||||
avatar: string | null;
|
||||
}
|
||||
|
||||
/** PK36's trip-wide member projection (`decorateBags`). */
|
||||
export interface PackingBagMemberForTripRow {
|
||||
bag_id: number;
|
||||
user_id: number;
|
||||
username: string;
|
||||
avatar: string | null;
|
||||
}
|
||||
|
||||
interface PackingBagsKyselyDB {
|
||||
packing_bags: PackingBagRow;
|
||||
packing_bag_members: { bag_id: number; user_id: number };
|
||||
users: { id: number; username: string; display_name: string | null; avatar: string | null };
|
||||
}
|
||||
|
||||
/** The insert-only shape for `insertMinimal` (PK32) — `id`/`created_at` are autoincrement/`DEFAULT CURRENT_TIMESTAMP` and omitted, matching the legacy 3-column list. */
|
||||
interface PackingBagsMinimalInsertKyselyDB {
|
||||
packing_bags: { trip_id: number | string; name: string; color: string };
|
||||
}
|
||||
|
||||
/** The insert-only shape for `insertBag` (PK42/TP67) — a distinct, wider column set from {@link PackingBagsMinimalInsertKyselyDB}'s. */
|
||||
interface PackingBagsInsertKyselyDB {
|
||||
packing_bags: { trip_id: number | string; name: string; color: string; sort_order: number | null; weight_limit_grams: number | null };
|
||||
}
|
||||
|
||||
/**
|
||||
* `packing_bags` — bags themselves, plus (this class's own relation, no
|
||||
* separate entity of its own — the `TagsRepository.place_tags`/
|
||||
* `PackingItemsRepository`'s own `packing_item_recipients` precedent) the
|
||||
* `packing_bag_members` pivot (`PackingBags.entity.ts`'s
|
||||
* `packing_bag_members: () => p.manyToMany(Users)
|
||||
* .pivotTable('packing_bag_members')...`, no `.pivotEntity(...)` — no
|
||||
* entity of its own, so no standalone `PackingBagMembersRepository` can be
|
||||
* registered; its read/write methods live here instead, reached through
|
||||
* `this.kysely()`). Kysely throughout: `trip_id`/`user_id` are both
|
||||
* `persist(false)` relation mirrors.
|
||||
*/
|
||||
export class PackingBagsRepository extends TrekRepository<PackingBags> {
|
||||
private db() {
|
||||
return this.kysely<PackingBagsKyselyDB>();
|
||||
}
|
||||
|
||||
/**
|
||||
* PK24 (`bagInTrip`)/PK25 (`bagForCloner`)/PK37 (`setBagMembers`'s
|
||||
* guard)/PK44 (`updateBag`'s guard)/PK47 (`deleteBag`'s guard) — `SELECT
|
||||
* id FROM packing_bags WHERE id = ? AND trip_id = ?` (PK24/37/44/47) /
|
||||
* `SELECT user_id FROM packing_bags WHERE id = ? AND trip_id = ?` (PK25)
|
||||
* — the SAME `WHERE` clause, five call sites, two narrower legacy
|
||||
* projections. One full-row method serves all five (rule 23's "narrow
|
||||
* read-model per statement" is about DISTINCT projections, not about
|
||||
* reproducing an accidental column subset when a caller only reads one
|
||||
* or two fields off it) — `bagInTrip` checks truthiness, `bagForCloner`
|
||||
* reads `.user_id`, the three guards check truthiness too.
|
||||
*/
|
||||
async findInTrip(id: number | string, trip_id: number | string): Promise<PackingBagRow | undefined> {
|
||||
return await this.db().selectFrom('packing_bags').selectAll().where('id', '=', id as number).where('trip_id', '=', trip_id as number).executeTakeFirst();
|
||||
}
|
||||
|
||||
/** PK30 (`bulkImport`'s bag-by-name resolution) — `SELECT id FROM packing_bags WHERE trip_id = ? AND name = ?`. */
|
||||
async byNameInTrip(trip_id: number | string, name: string): Promise<{ id: number } | undefined> {
|
||||
return await this.db().selectFrom('packing_bags').select('id').where('trip_id', '=', trip_id as number).where('name', '=', name).executeTakeFirst();
|
||||
}
|
||||
|
||||
/** PK31 (`bulkImport`, picks the next `BAG_COLORS` entry) — `SELECT COUNT(*) as c FROM packing_bags WHERE trip_id = ?`. */
|
||||
async countForTrip(trip_id: number | string): Promise<number> {
|
||||
const row = await this.db().selectFrom('packing_bags').select((eb) => eb.fn.countAll<number>().as('c')).where('trip_id', '=', trip_id as number).executeTakeFirst();
|
||||
return row?.c ?? 0;
|
||||
}
|
||||
|
||||
/** PK41 (`createBag`) — `SELECT MAX(sort_order) as max FROM packing_bags WHERE trip_id = ?`. */
|
||||
async maxSortOrder(trip_id: number | string): Promise<number | null> {
|
||||
const row = await this.db().selectFrom('packing_bags').select((eb) => eb.fn.max('sort_order').as('max')).where('trip_id', '=', trip_id as number).executeTakeFirst();
|
||||
return row?.max ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* PK32 (`bulkImport`'s bag auto-create) — `INSERT INTO packing_bags
|
||||
* (trip_id, name, color) VALUES (?, ?, ?)`. `sort_order`/`weight_limit_grams`/
|
||||
* `user_id` take their SQL-level `DEFAULT`s (`0`/`NULL`/`NULL`,
|
||||
* `Migration20200101003900_create_packing_bags.ts`) by omission — unlike
|
||||
* `packing_items.updated_at` (`PackingItemsRepository.insertItem`'s
|
||||
* docstring), every column this table's own `INSERT`s omit has a genuine
|
||||
* SQL-level `DEFAULT`, so a plain Kysely insert reproduces the legacy
|
||||
* statement exactly with no MikroORM write-path detour needed. Returns
|
||||
* the new row's id.
|
||||
*/
|
||||
async insertMinimal(trip_id: number | string, name: string, color: string): Promise<number> {
|
||||
const result = await this.kysely<PackingBagsMinimalInsertKyselyDB>().insertInto('packing_bags').values({ trip_id, name, color }).executeTakeFirstOrThrow();
|
||||
return Number(result.insertId);
|
||||
}
|
||||
|
||||
/**
|
||||
* PK42 (`createBag`) — `INSERT INTO packing_bags (trip_id, name, color,
|
||||
* sort_order, weight_limit_grams) VALUES (?×5)`, a distinct, wider column
|
||||
* set from {@link insertMinimal}'s. Returns the new row's id.
|
||||
*/
|
||||
async insertBag(row: { trip_id: number | string; name: string; color: string; sort_order: number | null; weight_limit_grams: number | null }): Promise<number> {
|
||||
const result = await this.kysely<PackingBagsInsertKyselyDB>().insertInto('packing_bags').values(row).executeTakeFirstOrThrow();
|
||||
return Number(result.insertId);
|
||||
}
|
||||
|
||||
/** PK43 (`createBag`'s post-insert re-select) — `SELECT * FROM packing_bags WHERE id = ?`. */
|
||||
async findById(id: number | string): Promise<PackingBagRow | undefined> {
|
||||
return await this.db().selectFrom('packing_bags').selectAll().where('id', '=', id as number).executeTakeFirst();
|
||||
}
|
||||
|
||||
/**
|
||||
* PK45 (`updateBag`) — the 4-column presence/COALESCE `UPDATE
|
||||
* packing_bags SET name = COALESCE(?, name), color = COALESCE(?, color),
|
||||
* weight_limit_grams = CASE WHEN ? THEN ? ELSE weight_limit_grams END,
|
||||
* user_id = CASE WHEN ? THEN ? ELSE user_id END WHERE id = ?`
|
||||
* (`_shared/presence-set.ts`, the same idiom PK13's docstring names).
|
||||
* `name`/`color` keep the legacy `COALESCE(?, col)` truthy-wins
|
||||
* semantics (`present = !!value`); `weight_limit_grams`/`user_id` are
|
||||
* true presence sentinels, already resolved by the SERVICE
|
||||
* (`assignUser`'s roster check, the bodyKeys presence protocol).
|
||||
*/
|
||||
async update(id: number | string, write: {
|
||||
name?: readonly [present: boolean, value: string | null];
|
||||
color?: readonly [present: boolean, value: string | null];
|
||||
weight_limit_grams?: readonly [present: boolean, value: number | null];
|
||||
user_id?: readonly [present: boolean, value: number | null];
|
||||
}): Promise<void> {
|
||||
const data = presenceSet<{ name: string; color: string; weight_limit_grams: number | null; user_id: number | null }>(write);
|
||||
await this.db().updateTable('packing_bags').set(data).where('id', '=', id as number).execute();
|
||||
}
|
||||
|
||||
/** PK46 (`updateBag`'s re-select) — `SELECT b.*, COALESCE(u.display_name, u.username) as assigned_username FROM packing_bags b LEFT JOIN users u ON b.user_id = u.id WHERE b.id = ?`. */
|
||||
async findWithAssignee(id: number | string): Promise<PackingBagWithAssigneeRow | undefined> {
|
||||
return await this.db()
|
||||
.selectFrom('packing_bags as b')
|
||||
.leftJoin('users as u', 'u.id', 'b.user_id')
|
||||
.selectAll('b')
|
||||
.select((eb) => eb.fn.coalesce('u.display_name', 'u.username').as('assigned_username'))
|
||||
.where('b.id', '=', id as number)
|
||||
.executeTakeFirst();
|
||||
}
|
||||
|
||||
/** PK48 (`deleteBag`) — `DELETE FROM packing_bags WHERE id = ?`. */
|
||||
async delete(id: number | string): Promise<void> {
|
||||
await this.nativeDelete({ id: id as number });
|
||||
}
|
||||
|
||||
/** PK35 (`decorateBags`) — `SELECT * FROM packing_bags WHERE trip_id = ? ORDER BY sort_order, id`. */
|
||||
async listForTrip(trip_id: number | string): Promise<PackingBagRow[]> {
|
||||
return await this.db().selectFrom('packing_bags').selectAll().where('trip_id', '=', trip_id as number).orderBy('sort_order', 'asc').orderBy('id', 'asc').execute();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// `packing_bag_members` — see the class docstring for why these live here.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* PK36 (`decorateBags`) — `SELECT bm.bag_id, bm.user_id, COALESCE(u.display_name,
|
||||
* u.username) AS username, u.avatar FROM packing_bag_members bm JOIN users u
|
||||
* JOIN packing_bags b ON bm.bag_id = b.id WHERE b.trip_id = ?`.
|
||||
*/
|
||||
async listMembersForTrip(trip_id: number | string): Promise<PackingBagMemberForTripRow[]> {
|
||||
return await this.db()
|
||||
.selectFrom('packing_bag_members as bm')
|
||||
.innerJoin('users as u', 'u.id', 'bm.user_id')
|
||||
.innerJoin('packing_bags as b', 'b.id', 'bm.bag_id')
|
||||
.select(['bm.bag_id', 'bm.user_id', (eb) => eb.fn.coalesce('u.display_name', 'u.username').as('username'), 'u.avatar'])
|
||||
.where('b.trip_id', '=', trip_id as number)
|
||||
.execute();
|
||||
}
|
||||
|
||||
/** PK26 (`bagForCloner`) — `SELECT user_id FROM packing_bag_members WHERE bag_id = ?`. */
|
||||
async listMemberIdsForBag(bag_id: number): Promise<number[]> {
|
||||
const rows = await this.db().selectFrom('packing_bag_members').select('user_id').where('bag_id', '=', bag_id).execute();
|
||||
return rows.map((r) => r.user_id);
|
||||
}
|
||||
|
||||
/** PK40 (`setBagMembers`'s post-write re-select) — `SELECT bm.user_id, COALESCE(u.display_name, u.username) AS username, u.avatar FROM packing_bag_members bm JOIN users u ON bm.user_id = u.id WHERE bm.bag_id = ?`. */
|
||||
async listMembersWithUserForBag(bag_id: number): Promise<PackingBagMemberWithUserRow[]> {
|
||||
return await this.db()
|
||||
.selectFrom('packing_bag_members as bm')
|
||||
.innerJoin('users as u', 'u.id', 'bm.user_id')
|
||||
.select(['bm.user_id', (eb) => eb.fn.coalesce('u.display_name', 'u.username').as('username'), 'u.avatar'])
|
||||
.where('bm.bag_id', '=', bag_id)
|
||||
.execute();
|
||||
}
|
||||
|
||||
/** PK38 (`setBagMembers`'s replace-all) — `DELETE FROM packing_bag_members WHERE bag_id = ?`. */
|
||||
async deleteMembersForBag(bag_id: number): Promise<void> {
|
||||
await this.db().deleteFrom('packing_bag_members').where('bag_id', '=', bag_id).execute();
|
||||
}
|
||||
|
||||
/**
|
||||
* PK39 (`setBagMembers`) — `INSERT OR IGNORE INTO packing_bag_members
|
||||
* (bag_id, user_id) VALUES (?, ?)`, the legacy `prepare(...).run(...)`
|
||||
* loop. Kysely `ON CONFLICT DO NOTHING` on the pivot's real composite
|
||||
* `PRIMARY KEY (bag_id, user_id)` (`Migration20200101012100_add_quantity_to_packing_items_user_id
|
||||
* .ts:23-29`) — no entity mapping (this class docstring), so
|
||||
* `em.upsert`/`upsertMany` cannot target it. The caller roster-scopes
|
||||
* the ids before calling; the empty-array guard here is defensive.
|
||||
*/
|
||||
async insertMembersIgnore(bag_id: number, user_ids: number[]): Promise<void> {
|
||||
if (user_ids.length === 0) return;
|
||||
await this.db()
|
||||
.insertInto('packing_bag_members')
|
||||
.values(user_ids.map((user_id) => ({ bag_id, user_id })))
|
||||
.onConflict((oc) => oc.columns(['bag_id', 'user_id']).doNothing())
|
||||
.execute();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Plan 3e Task 3 (`TripsService.copy`, TP66-69) — additive.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* TP66 (`trips.service.ts::copy`'s bags read) — `SELECT * FROM
|
||||
* packing_bags WHERE trip_id = ?`. Deliberately NOT {@link listForTrip}
|
||||
* (PK35) — that method's `ORDER BY sort_order, id` is a DIFFERENT
|
||||
* statement from this one's plain, unordered legacy text; reusing it here
|
||||
* would risk reordering the copy loop relative to a trip whose bags were
|
||||
* reordered after creation. TP67 (the insert half) reuses {@link insertBag}
|
||||
* directly — same column set, called once per row.
|
||||
*/
|
||||
async listAllForTrip(trip_id: number | string): Promise<PackingBagRow[]> {
|
||||
return await this.db().selectFrom('packing_bags').selectAll().where('trip_id', '=', trip_id as number).execute();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,77 @@
|
||||
import type { PackingCategoryAssignees } from '../entities/PackingCategoryAssignees.entity';
|
||||
import { TrekRepository } from './_shared/trek-repository';
|
||||
|
||||
export class PackingCategoryAssigneesRepository extends TrekRepository<PackingCategoryAssignees> {}
|
||||
/** PK58/PK61's joined projection. */
|
||||
export interface PackingCategoryAssigneeRow {
|
||||
category_name: string;
|
||||
user_id: number;
|
||||
username: string;
|
||||
avatar: string | null;
|
||||
}
|
||||
|
||||
interface PackingCategoryAssigneesKyselyDB {
|
||||
packing_category_assignees: { id: number; trip_id: number; category_name: string; user_id: number };
|
||||
users: { id: number; username: string; display_name: string | null; avatar: string | null };
|
||||
}
|
||||
|
||||
/**
|
||||
* `packing_category_assignees` — who is "on the hook" for a packing
|
||||
* category. A surrogate `id` PK plus a `(trip, category_name, user)`
|
||||
* unique index (§16), unlike `packing_item_contributors`'s genuine
|
||||
* composite PK — `upsertMany` with `onConflictAction: 'ignore'` on that
|
||||
* unique index is the `AssignmentParticipantsRepository.insertIgnore`
|
||||
* shape, not the composite-key `em.upsert` form
|
||||
* `PackingItemContributorsRepository` needs.
|
||||
*/
|
||||
export class PackingCategoryAssigneesRepository extends TrekRepository<PackingCategoryAssignees> {
|
||||
/**
|
||||
* PK58 (`getCategoryAssignees`) — `SELECT pca.category_name, pca.user_id,
|
||||
* COALESCE(u.display_name, u.username) AS username, u.avatar FROM
|
||||
* packing_category_assignees pca JOIN users u ON pca.user_id = u.id
|
||||
* WHERE pca.trip_id = ?`.
|
||||
*/
|
||||
async listForTrip(trip_id: number | string): Promise<PackingCategoryAssigneeRow[]> {
|
||||
return await this.kysely<PackingCategoryAssigneesKyselyDB>()
|
||||
.selectFrom('packing_category_assignees as pca')
|
||||
.innerJoin('users as u', 'u.id', 'pca.user_id')
|
||||
.select(['pca.category_name', 'pca.user_id', (eb) => eb.fn.coalesce('u.display_name', 'u.username').as('username'), 'u.avatar'])
|
||||
.where('pca.trip_id', '=', trip_id as number)
|
||||
.execute();
|
||||
}
|
||||
|
||||
/** PK59 (`updateCategoryAssignees`'s replace-all) — `DELETE FROM packing_category_assignees WHERE trip_id = ? AND category_name = ?`. */
|
||||
async deleteForCategory(trip_id: number | string, category_name: string): Promise<void> {
|
||||
await this.nativeDelete({ trip: trip_id as number, category_name });
|
||||
}
|
||||
|
||||
/**
|
||||
* PK60 (`updateCategoryAssignees`) — `INSERT OR IGNORE INTO
|
||||
* packing_category_assignees (trip_id, category_name, user_id) VALUES
|
||||
* (?, ?, ?)`, the legacy `prepare(...).run(...)` loop. `upsertMany` with
|
||||
* `onConflictAction: 'ignore'` on the entity's real unique index
|
||||
* (`UNIQUE(trip_id, category_name, user_id)`,
|
||||
* `Migration20200101003700_create_packing_category_assignees.ts:9`),
|
||||
* named by entity property (`trip`/`user`, the
|
||||
* `AssignmentParticipantsRepository.insertIgnore` precedent). The caller
|
||||
* roster-scopes the ids before calling; the empty-array guard here is
|
||||
* defensive.
|
||||
*/
|
||||
async insertIgnore(trip_id: number | string, category_name: string, user_ids: number[]): Promise<void> {
|
||||
if (user_ids.length === 0) return;
|
||||
await this.upsertMany(
|
||||
user_ids.map((user_id) => ({ trip: trip_id as number, category_name, user: user_id })),
|
||||
{ onConflictFields: ['trip', 'category_name', 'user'], onConflictAction: 'ignore' },
|
||||
);
|
||||
}
|
||||
|
||||
/** PK61 (`updateCategoryAssignees`'s post-write re-select) — `SELECT pca.user_id, COALESCE(u.display_name, u.username) AS username, u.avatar FROM packing_category_assignees pca JOIN users u ON pca.user_id = u.id WHERE pca.trip_id = ? AND pca.category_name = ?`. */
|
||||
async listForCategory(trip_id: number | string, category_name: string): Promise<Omit<PackingCategoryAssigneeRow, 'category_name'>[]> {
|
||||
return await this.kysely<PackingCategoryAssigneesKyselyDB>()
|
||||
.selectFrom('packing_category_assignees as pca')
|
||||
.innerJoin('users as u', 'u.id', 'pca.user_id')
|
||||
.select(['pca.user_id', (eb) => eb.fn.coalesce('u.display_name', 'u.username').as('username'), 'u.avatar'])
|
||||
.where('pca.trip_id', '=', trip_id as number)
|
||||
.where('pca.category_name', '=', category_name)
|
||||
.execute();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,77 @@
|
||||
import type { PackingItemContributors } from '../entities/PackingItemContributors.entity';
|
||||
import { TrekRepository } from './_shared/trek-repository';
|
||||
|
||||
export class PackingItemContributorsRepository extends TrekRepository<PackingItemContributors> {}
|
||||
/** PK3's contributor projection (`enrichItems`). */
|
||||
export interface PackingItemContributorRow {
|
||||
item_id: number;
|
||||
user_id: number;
|
||||
status: string;
|
||||
username: string;
|
||||
}
|
||||
|
||||
interface PackingItemContributorsKyselyDB {
|
||||
packing_item_contributors: { item_id: number; user_id: number; status: string; created_at: string | null };
|
||||
users: { id: number; username: string; display_name: string | null };
|
||||
}
|
||||
|
||||
/**
|
||||
* `packing_item_contributors` — "I can bring that too" co-contributors on a
|
||||
* Common item (#858). Unlike `packing_item_recipients`/`packing_bag_members`
|
||||
* (folded onto `PackingItemsRepository`/`PackingBagsRepository` — see their
|
||||
* class docstrings), this pivot HAS its own entity
|
||||
* (`PackingItemContributors.entity.ts`, `.pivotEntity(...)`-declared on
|
||||
* `PackingItems`) with a genuine composite primary key (`item` + `user`,
|
||||
* both `.primary()` — R5, confirmed against
|
||||
* `Migration20200101022900_three_tier_packing_sharing.ts:23-30`'s own
|
||||
* `PRIMARY KEY (item_id, user_id)`), the only join table in this cluster
|
||||
* shaped that way (every sibling uses a surrogate `id` PK + a `uniques`
|
||||
* array instead). So it gets a normal, entity-backed repository, and its
|
||||
* writes use the composite-key form of `em.upsert`/`nativeDelete` (the
|
||||
* conflict/match target is the two-column PK, not a synthetic id) — the
|
||||
* `ReservationDayPositionsRepository`/`ReservationDayPositions.entity.ts`
|
||||
* precedent for a genuine composite-PK relation table.
|
||||
*/
|
||||
export class PackingItemContributorsRepository extends TrekRepository<PackingItemContributors> {
|
||||
/**
|
||||
* PK3 (`enrichItems`'s contributor read) — `SELECT c.item_id, c.user_id,
|
||||
* c.status, COALESCE(u.display_name, u.username) AS username FROM
|
||||
* packing_item_contributors c JOIN users u ON u.id = c.user_id WHERE
|
||||
* c.item_id IN (${…})`. Kysely: `item_id` is `persist(false)` (the
|
||||
* physical mirror of the composite-PK `item` relation).
|
||||
*/
|
||||
async listForItems(item_ids: number[]): Promise<PackingItemContributorRow[]> {
|
||||
if (item_ids.length === 0) return [];
|
||||
return await this.kysely<PackingItemContributorsKyselyDB>()
|
||||
.selectFrom('packing_item_contributors as c')
|
||||
.innerJoin('users as u', 'u.id', 'c.user_id')
|
||||
.select(['c.item_id', 'c.user_id', 'c.status', (eb) => eb.fn.coalesce('u.display_name', 'u.username').as('username')])
|
||||
.where('c.item_id', 'in', item_ids)
|
||||
.execute();
|
||||
}
|
||||
|
||||
/**
|
||||
* PK20 (`addContributor`) — `INSERT OR IGNORE INTO
|
||||
* packing_item_contributors (item_id, user_id, status) VALUES (?, ?,
|
||||
* 'accepted')`. `em.upsert` with the composite-PK conflict target
|
||||
* (`onConflictFields: ['item', 'user']`, the entity's real `PRIMARY KEY
|
||||
* (item_id, user_id)` — R5/§16, NOT a synthetic-id workaround), named by
|
||||
* entity property (the `AssignmentParticipantsRepository.insertIgnore`
|
||||
* precedent).
|
||||
*/
|
||||
async insertIgnore(item_id: number, user_id: number): Promise<void> {
|
||||
await this.upsert(
|
||||
{ item: item_id, user: user_id, status: 'accepted' },
|
||||
{ onConflictFields: ['item', 'user'], onConflictAction: 'ignore' },
|
||||
);
|
||||
}
|
||||
|
||||
/** PK18 (`setItemSharing`'s leaving-Common cleanup) — `DELETE FROM packing_item_contributors WHERE item_id = ?`. */
|
||||
async deleteForItem(item_id: number): Promise<void> {
|
||||
await this.nativeDelete({ item: item_id });
|
||||
}
|
||||
|
||||
/** PK22 (`removeContributor`) — `DELETE FROM packing_item_contributors WHERE item_id = ? AND user_id = ?`, the composite-PK match target. */
|
||||
async deleteOne(item_id: number, user_id: number): Promise<void> {
|
||||
await this.nativeDelete({ item: item_id, user: user_id });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,446 @@
|
||||
import type { PackingItems } from '../entities/PackingItems.entity';
|
||||
import { currentTimestamp } from '../dialect/sql-functions';
|
||||
import { type AssertRowKeys } from './_shared/rows';
|
||||
import { TrekRepository } from './_shared/trek-repository';
|
||||
import { presenceSet } from './_shared/presence-set';
|
||||
import { packingVisibleToActorExpr, type PackingVisibilityKyselyDB } from './_shared/packing-visibility';
|
||||
|
||||
export class PackingItemsRepository extends TrekRepository<PackingItems> {}
|
||||
/** A bare `packing_items` row — every scalar column, incl. the three `persist(false)` relation mirrors (`trip_id`, `bag_id`, `owner_id`) — the program-wide trap this class goes through Kysely throughout to avoid. */
|
||||
export interface PackingItemRow {
|
||||
id: number;
|
||||
trip_id: number;
|
||||
name: string;
|
||||
checked: number | null;
|
||||
category: string | null;
|
||||
sort_order: number | null;
|
||||
created_at: string | null;
|
||||
weight_grams: number | null;
|
||||
bag_id: number | null;
|
||||
quantity: number;
|
||||
updated_at: string | null;
|
||||
is_private: number;
|
||||
owner_id: number | null;
|
||||
}
|
||||
|
||||
const _packingItemRowKeys: AssertRowKeys<PackingItemRow, PackingItems> = true;
|
||||
|
||||
/** PK2's recipient projection (`enrichItems`). */
|
||||
export interface PackingItemRecipientRow {
|
||||
item_id: number;
|
||||
user_id: number;
|
||||
username: string;
|
||||
}
|
||||
|
||||
/** PK54's privacy-filtered export projection (`saveAsTemplate`) — name/category only. */
|
||||
export interface PackingItemExportRow {
|
||||
name: string;
|
||||
category: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* `packing_items`'s own Kysely shape, extended from `_shared/packing-visibility.ts`'s
|
||||
* `PackingVisibilityKyselyDB` (Task 0, R1) — `PackingItemRow` is a structural
|
||||
* superset of that file's narrower `{id, is_private, owner_id}` requirement,
|
||||
* so `packingVisibleToActorExpr` type-checks directly against a query built
|
||||
* from this interface (the `CalendarStayKyselyDB extends
|
||||
* ReservationVisibilityKyselyDB` precedent, `Reservations.repository.ts`).
|
||||
*/
|
||||
interface PackingItemsKyselyDB extends PackingVisibilityKyselyDB {
|
||||
packing_items: PackingItemRow;
|
||||
packing_item_recipients: { item_id: number; user_id: number };
|
||||
users: { id: number; username: string; display_name: string | null };
|
||||
}
|
||||
|
||||
/**
|
||||
* `packing_items` — the checklist rows themselves, plus (this class's own
|
||||
* relation, no separate entity of its own — §16/the `TagsRepository
|
||||
* .place_tags` precedent) the `packing_item_recipients` pivot. Kysely
|
||||
* throughout: `trip_id`/`bag_id`/`owner_id` are all `persist(false)`
|
||||
* relation mirrors (§16), the program-wide bare-`select` drop trap
|
||||
* `TripFilesRepository`'s class docstring names.
|
||||
*
|
||||
* **`packing_item_recipients` lives here, not on its own
|
||||
* `PackingItemRecipientsRepository`.** The inventory's own proposal (§2's
|
||||
* "Proposed repositories") expected a standalone class, but the pivot has
|
||||
* NO MikroORM entity of its own (`PackingItems.entity.ts`'s
|
||||
* `packing_item_recipients: () => p.manyToMany(Users)
|
||||
* .pivotTable('packing_item_recipients')...` — no `.pivotEntity(...)`,
|
||||
* unlike `packing_item_contributors`'s) — `TrekRepository`/`@InjectRepository`
|
||||
* both require a mapped entity to construct a repository at all, so a
|
||||
* separate class cannot be registered. Exactly the `Places.place_tags` ↔
|
||||
* `TagsRepository` shape (`Tags.repository.ts`'s own class docstring): the
|
||||
* pivot's read/write methods live on the repository of the entity that
|
||||
* declares the owning side of the relation (`PackingItems`), reached
|
||||
* through `this.kysely()` (D3's sanctioned escape hatch for a table with no
|
||||
* entity mapping). Flagged as a deviation from the inventory's proposal in
|
||||
* the task-3 report, not a defect.
|
||||
*/
|
||||
export class PackingItemsRepository extends TrekRepository<PackingItems> {
|
||||
private db() {
|
||||
return this.kysely<PackingItemsKyselyDB>();
|
||||
}
|
||||
|
||||
/**
|
||||
* PK1 (`enrichItems`'s owner-name read) — legacy: `SELECT id, username
|
||||
* FROM users WHERE id IN (SELECT owner_id FROM packing_items WHERE id IN
|
||||
* (${…}))`. The caller (`PackingService.enrichItems`) already holds every
|
||||
* item's own `owner_id` (it just read the rows) — the inner subquery's
|
||||
* whole job is producing that same distinct owner-id set, so it collapses
|
||||
* to a plain `id IN (?)` over `users` once the service derives the ids in
|
||||
* JS from the rows it already has (rule 23: a typed condition over a
|
||||
* known list, not a nested dynamic subquery) — same result set, one fewer
|
||||
* round trip through `packing_items`.
|
||||
*/
|
||||
async listOwnersForIds(owner_ids: number[]): Promise<{ id: number; username: string }[]> {
|
||||
if (owner_ids.length === 0) return [];
|
||||
return await this.db().selectFrom('users').select(['id', 'username']).where('id', 'in', owner_ids).execute();
|
||||
}
|
||||
|
||||
/**
|
||||
* PK2 (`enrichItems`'s recipient read) — `SELECT r.item_id, r.user_id,
|
||||
* COALESCE(u.display_name, u.username) AS username FROM
|
||||
* packing_item_recipients r JOIN users u ON u.id = r.user_id WHERE
|
||||
* r.item_id IN (${…})`.
|
||||
*/
|
||||
async listRecipientsForItems(item_ids: number[]): Promise<PackingItemRecipientRow[]> {
|
||||
if (item_ids.length === 0) return [];
|
||||
return await this.db()
|
||||
.selectFrom('packing_item_recipients as r')
|
||||
.innerJoin('users as u', 'u.id', 'r.user_id')
|
||||
.select(['r.item_id', 'r.user_id', (eb) => eb.fn.coalesce('u.display_name', 'u.username').as('username')])
|
||||
.where('r.item_id', 'in', item_ids)
|
||||
.execute();
|
||||
}
|
||||
|
||||
/** PK4 (`listItems`'s no-viewer branch) — `SELECT * FROM packing_items WHERE trip_id = ? ORDER BY sort_order ASC, created_at ASC`, unfiltered — only for genuinely viewer-less internal reads. */
|
||||
async listForTrip(trip_id: number | string): Promise<PackingItemRow[]> {
|
||||
return await this.db().selectFrom('packing_items').selectAll().where('trip_id', '=', trip_id as number).orderBy('sort_order', 'asc').orderBy('created_at', 'asc').execute();
|
||||
}
|
||||
|
||||
/**
|
||||
* PK5 (`listItems`'s viewer-filtered branch, T5) — `SELECT * FROM
|
||||
* packing_items WHERE trip_id = ? AND (${VISIBLE_TO_ACTOR}) ORDER BY
|
||||
* sort_order ASC, created_at ASC`. **Security-critical (#858
|
||||
* three-tier sharing)** — built directly on Task 0's shared
|
||||
* `packingVisibleToActorExpr` predicate (`_shared/packing-visibility.ts`),
|
||||
* never a re-spelled fragment (R1).
|
||||
*/
|
||||
async listVisibleToActor(trip_id: number | string, actorId: number): Promise<PackingItemRow[]> {
|
||||
return await this.db()
|
||||
.selectFrom('packing_items')
|
||||
.selectAll()
|
||||
.where('trip_id', '=', trip_id as number)
|
||||
.where((eb) => packingVisibleToActorExpr(eb, actorId))
|
||||
.orderBy('sort_order', 'asc')
|
||||
.orderBy('created_at', 'asc')
|
||||
.execute();
|
||||
}
|
||||
|
||||
/** PK6 (`getItemPrivacy`) — `SELECT is_private, owner_id FROM packing_items WHERE id = ? AND trip_id = ?`. */
|
||||
async getPrivacy(id: number | string, trip_id: number | string): Promise<{ is_private: number; owner_id: number | null } | undefined> {
|
||||
return await this.db().selectFrom('packing_items').select(['is_private', 'owner_id']).where('id', '=', id as number).where('trip_id', '=', trip_id as number).executeTakeFirst();
|
||||
}
|
||||
|
||||
/** PK7/PK28/PK51 (`createItem`/`bulkImport`/`applyTemplate`) — `SELECT MAX(sort_order) as max FROM packing_items WHERE trip_id = ?`, one method, three call sites. */
|
||||
async maxSortOrder(trip_id: number | string): Promise<number | null> {
|
||||
const row = await this.db().selectFrom('packing_items').select((eb) => eb.fn.max('sort_order').as('max')).where('trip_id', '=', trip_id as number).executeTakeFirst();
|
||||
return row?.max ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* PK8 (`createItem`) / PK29 (`bulkImport`'s per-row loop) — the same
|
||||
* 11-column `INSERT INTO packing_items (trip_id, name, checked, category,
|
||||
* sort_order, quantity, weight_grams, bag_id, is_private, owner_id,
|
||||
* updated_at) VALUES (?×10, CURRENT_TIMESTAMP)` (the two legacy statements
|
||||
* differ only in column ORDER, not in the column set or bound values — one
|
||||
* method, both call sites, called once per row for `bulkImport`'s loop
|
||||
* exactly as the legacy `stmt.run(...)` was). Returns the new row's id.
|
||||
*
|
||||
* **MikroORM's own `insert()`, not Kysely** (unlike every read above): the
|
||||
* legacy statement binds `updated_at` to the literal SQL keyword
|
||||
* `CURRENT_TIMESTAMP` (the column carries no SQL-level `DEFAULT` of its
|
||||
* own, `Migration20200101022400_optimistic_concurrency_token_for_offline_conflict_detection.ts`),
|
||||
* and `currentTimestamp(platform)`'s `RawQueryFragment` is a MikroORM-only
|
||||
* construct — handed into a Kysely statement it stringifies to a literal
|
||||
* `?` and the statement fails at execution (`sql-functions.ts`'s own
|
||||
* Plan 3d Task 0 review note, H1/L1). Every `currentTimestamp(platform)`
|
||||
* call in this program goes through a MikroORM write path
|
||||
* (`nativeUpdate`/`upsert`/`insert`), never Kysely's `.set()`/`.values()` —
|
||||
* `bag`/`owner` are the relation property names for the `bag_id`/`owner_id`
|
||||
* `persist(false)` mirrors (`ReservationsRepository.updateReservation`'s
|
||||
* `day`/`place` precedent).
|
||||
*/
|
||||
async insertItem(row: {
|
||||
trip_id: number | string; name: string; checked: number; category: string; sort_order: number;
|
||||
quantity: number; weight_grams: number | null; bag_id: number | null; is_private: number; owner_id: number | null;
|
||||
}): Promise<number> {
|
||||
const platform = this.getEntityManager().getPlatform();
|
||||
const id = await this.insert({
|
||||
trip: row.trip_id,
|
||||
name: row.name,
|
||||
checked: row.checked,
|
||||
category: row.category,
|
||||
sort_order: row.sort_order,
|
||||
quantity: row.quantity,
|
||||
weight_grams: row.weight_grams,
|
||||
bag: row.bag_id,
|
||||
is_private: row.is_private,
|
||||
owner: row.owner_id,
|
||||
updated_at: currentTimestamp(platform),
|
||||
});
|
||||
return Number(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* PK52 (`applyTemplate`'s per-row loop) — `INSERT INTO packing_items
|
||||
* (trip_id, name, checked, category, sort_order, is_private, owner_id,
|
||||
* updated_at) VALUES (?, ?, 0, ?, ?, ?, ?, CURRENT_TIMESTAMP)` — a distinct,
|
||||
* narrower column set from {@link insertItem} (`checked` is always 0;
|
||||
* `weight_grams`/`bag_id` take their SQL defaults — `NULL`; `quantity`
|
||||
* takes its SQL default — 1). MikroORM's own `insert()`, same reason as
|
||||
* {@link insertItem}'s docstring. Returns the new row's id.
|
||||
*/
|
||||
async insertFromTemplate(row: { trip_id: number | string; name: string; category: string; sort_order: number; is_private: number; owner_id: number | null }): Promise<number> {
|
||||
const platform = this.getEntityManager().getPlatform();
|
||||
const id = await this.insert({
|
||||
trip: row.trip_id,
|
||||
name: row.name,
|
||||
checked: 0,
|
||||
category: row.category,
|
||||
sort_order: row.sort_order,
|
||||
is_private: row.is_private,
|
||||
owner: row.owner_id,
|
||||
updated_at: currentTimestamp(platform),
|
||||
});
|
||||
return Number(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* PK9 (`createItem`)/PK17 (`setItemSharing`) — `INSERT OR IGNORE INTO
|
||||
* packing_item_recipients (item_id, user_id) VALUES (?, ?)`, the legacy
|
||||
* `prepare(...).run(...)` loop, same text at both call sites. Kysely
|
||||
* `ON CONFLICT DO NOTHING` on the pivot's real composite `PRIMARY KEY
|
||||
* (item_id, user_id)` (`Migration20200101022900_three_tier_packing_sharing
|
||||
* .ts:17-21`) — the table has no entity mapping (this class docstring),
|
||||
* so `em.upsert`/`upsertMany` cannot target it. The caller
|
||||
* roster-scopes and excludes the owner before calling; the empty-array
|
||||
* guard here is defensive, matching every other batch-write method in
|
||||
* this program.
|
||||
*/
|
||||
async insertRecipientsIgnore(item_id: number, user_ids: number[]): Promise<void> {
|
||||
if (user_ids.length === 0) return;
|
||||
await this.db()
|
||||
.insertInto('packing_item_recipients')
|
||||
.values(user_ids.map((user_id) => ({ item_id, user_id })))
|
||||
.onConflict((oc) => oc.columns(['item_id', 'user_id']).doNothing())
|
||||
.execute();
|
||||
}
|
||||
|
||||
/** PK10/PK14/PK19/PK21/PK23/PK33/PK53 — `SELECT * FROM packing_items WHERE id = ?`, the shared post-write re-select text, seven call sites. */
|
||||
async findById(id: number | string): Promise<PackingItemRow | undefined> {
|
||||
return await this.db().selectFrom('packing_items').selectAll().where('id', '=', id as number).executeTakeFirst();
|
||||
}
|
||||
|
||||
/**
|
||||
* PK11 (`getItemInTrip`, T1) — `SELECT * FROM packing_items WHERE id = ?
|
||||
* AND trip_id = ? AND (${VISIBLE_TO_ACTOR})`. **The single
|
||||
* highest-blast-radius conversion in the whole plan (§17 surprise 2)** —
|
||||
* six call sites (`updateItem`, `setItemSharing`, `addContributor`,
|
||||
* `removeContributor`, `cloneItem`, `deleteItem`), all routed through
|
||||
* Task 0's shared `packingVisibleToActorExpr` predicate, never a
|
||||
* re-spelled fragment. A missing actor id returns `undefined` without
|
||||
* querying (matching the legacy JS-level guard — "a missing actor denies
|
||||
* too, rather than falling through unfiltered").
|
||||
*/
|
||||
async findVisibleInTrip(id: number | string, trip_id: number | string, actorId: number | undefined): Promise<PackingItemRow | undefined> {
|
||||
if (actorId == null) return undefined;
|
||||
return await this.db()
|
||||
.selectFrom('packing_items')
|
||||
.selectAll()
|
||||
.where('id', '=', id as number)
|
||||
.where('trip_id', '=', trip_id as number)
|
||||
.where((eb) => packingVisibleToActorExpr(eb, actorId))
|
||||
.executeTakeFirst();
|
||||
}
|
||||
|
||||
/**
|
||||
* PK13 (`updateItem`, T3) — the 8-column presence-sentinel `UPDATE
|
||||
* packing_items SET name = COALESCE(?, name), checked = CASE WHEN ? IS
|
||||
* NOT NULL THEN ? ELSE checked END, category = COALESCE(?, category),
|
||||
* weight_grams = CASE WHEN ? THEN ? ELSE weight_grams END, bag_id = CASE
|
||||
* WHEN ? THEN ? ELSE bag_id END, quantity = CASE WHEN ? THEN ? ELSE
|
||||
* quantity END, is_private = CASE WHEN ? THEN ? ELSE is_private END,
|
||||
* owner_id = CASE WHEN ? THEN ? ELSE owner_id END, updated_at =
|
||||
* CURRENT_TIMESTAMP WHERE id = ?` (`_shared/presence-set.ts`, R11 — Task
|
||||
* 2's landed shape, copied here rather than re-derived). `name`/`category`
|
||||
* keep the legacy `COALESCE(?, col)` truthy-wins semantics (the service
|
||||
* passes `present = !!value`, matching `data.name || null`'s
|
||||
* fall-through-on-falsy exactly); every other column is a true presence
|
||||
* sentinel (`present = bodyKeys.includes(...)`), and `owner_id`'s
|
||||
* presence is the claim-owner-on-privatize flag. `updated_at` is NOT
|
||||
* gated by presence — the legacy statement always stamps it, unlike
|
||||
* `BudgetItemsRepository.update`'s early-return guard (budget's row has
|
||||
* no `updated_at` column at all).
|
||||
*/
|
||||
async update(id: number | string, write: {
|
||||
name?: readonly [present: boolean, value: string | null];
|
||||
checked?: readonly [present: boolean, value: number];
|
||||
category?: readonly [present: boolean, value: string | null];
|
||||
weight_grams?: readonly [present: boolean, value: number | null];
|
||||
bag_id?: readonly [present: boolean, value: number | null];
|
||||
quantity?: readonly [present: boolean, value: number];
|
||||
is_private?: readonly [present: boolean, value: number];
|
||||
owner_id?: readonly [present: boolean, value: number | null];
|
||||
}): Promise<void> {
|
||||
const platform = this.getEntityManager().getPlatform();
|
||||
const data = presenceSet<{
|
||||
name: string | null; checked: number; category: string | null; weight_grams: number | null;
|
||||
bag: number | null; quantity: number; is_private: number; owner: number | null;
|
||||
}>({
|
||||
name: write.name,
|
||||
checked: write.checked,
|
||||
category: write.category,
|
||||
weight_grams: write.weight_grams,
|
||||
bag: write.bag_id,
|
||||
quantity: write.quantity,
|
||||
is_private: write.is_private,
|
||||
owner: write.owner_id,
|
||||
});
|
||||
await this.nativeUpdate({ id: id as number }, { ...data, updated_at: currentTimestamp(platform) });
|
||||
}
|
||||
|
||||
/**
|
||||
* PK15 (`setItemSharing`) — `UPDATE packing_items SET is_private = ?,
|
||||
* owner_id = COALESCE(owner_id, ?), updated_at = CURRENT_TIMESTAMP WHERE
|
||||
* id = ?`. The service resolves the `COALESCE(owner_id, ?)` keep-if-set
|
||||
* semantics: `owner_id` is passed only when the pre-image's `owner_id` was
|
||||
* `null` (an unowned legacy item being claimed), otherwise omitted so the
|
||||
* column is left untouched — the same presence-object shape as
|
||||
* {@link update}, one key.
|
||||
*/
|
||||
async updateSharing(id: number | string, is_private: number, claimOwnerId?: number): Promise<void> {
|
||||
const platform = this.getEntityManager().getPlatform();
|
||||
const data = presenceSet<{ owner: number }>({ owner: claimOwnerId !== undefined ? [true, claimOwnerId] : undefined });
|
||||
await this.nativeUpdate({ id: id as number }, { is_private, ...data, updated_at: currentTimestamp(platform) });
|
||||
}
|
||||
|
||||
/** PK16 (`setItemSharing`'s replace-all) — `DELETE FROM packing_item_recipients WHERE item_id = ?`. */
|
||||
async deleteRecipientsForItem(item_id: number): Promise<void> {
|
||||
await this.db().deleteFrom('packing_item_recipients').where('item_id', '=', item_id).execute();
|
||||
}
|
||||
|
||||
/** PK27 (`deleteItem`) — `DELETE FROM packing_items WHERE id = ?`. */
|
||||
async delete(id: number | string): Promise<void> {
|
||||
await this.nativeDelete({ id: id as number });
|
||||
}
|
||||
|
||||
/**
|
||||
* PK34 (`bagWeightTotals`, T6) — `SELECT bag_id, SUM(COALESCE(weight_grams,
|
||||
* 0) * COALESCE(quantity, 1)) AS total FROM packing_items WHERE trip_id = ?
|
||||
* GROUP BY bag_id`. **Deliberately NOT built on {@link listVisibleToActor}/
|
||||
* {@link findVisibleInTrip}** (§17 surprise 10) — this aggregate crosses
|
||||
* the privacy boundary on purpose (the sum includes every item in the
|
||||
* trip, private ones included; only the resulting integer is exposed,
|
||||
* never a name/category/owner) to keep a shared bag's weight-limit warning
|
||||
* accurate for every member, not just what the viewer can see. A shared
|
||||
* helper that accidentally unified this with the visibility-filtered reads
|
||||
* would silently ADD a privacy filter here — the opposite failure mode
|
||||
* from PK5/PK11's.
|
||||
*/
|
||||
async bagWeightTotals(trip_id: number | string): Promise<{ bag_id: number | null; total: number | null }[]> {
|
||||
return await this.db()
|
||||
.selectFrom('packing_items')
|
||||
.select((eb) => {
|
||||
// `COALESCE(weight_grams, 0) * COALESCE(quantity, 1)`
|
||||
const lineWeight = eb(eb.fn.coalesce('weight_grams', eb.val(0)), '*', eb.fn.coalesce('quantity', eb.val(1)));
|
||||
return ['bag_id', eb.fn.sum<number>(lineWeight).as('total')];
|
||||
})
|
||||
.where('trip_id', '=', trip_id as number)
|
||||
.groupBy('bag_id')
|
||||
.execute();
|
||||
}
|
||||
|
||||
/**
|
||||
* PK54 (`saveAsTemplate`) — `SELECT name, category FROM packing_items
|
||||
* WHERE trip_id = ? AND (is_private = 0 OR owner_id = ?) ORDER BY
|
||||
* sort_order ASC`. **Security-critical, its own two-arm predicate — NOT
|
||||
* `packingVisibleToActorExpr`/`packingVisibleToActorCondition`.** A
|
||||
* template is a durable, shareable artifact, so it may only capture what
|
||||
* the actor's own list contains: Common items plus the actor's own
|
||||
* (Personal or Shared) items. The three-arm `VISIBLE_TO_ACTOR` predicate
|
||||
* additionally admits items the actor is merely a RECIPIENT of — reusing
|
||||
* it here would let a recipient publish someone else's Shared item into a
|
||||
* template neither of them wrote, an over-broad capture the legacy
|
||||
* statement never allowed (matches `PlacesService`'s own-list-only
|
||||
* trip-copy filter, PK54's own note).
|
||||
*/
|
||||
async listExportable(trip_id: number | string, userId: number): Promise<PackingItemExportRow[]> {
|
||||
return await this.db()
|
||||
.selectFrom('packing_items')
|
||||
.select(['name', 'category'])
|
||||
.where('trip_id', '=', trip_id as number)
|
||||
.where((eb) => eb.or([eb('is_private', '=', 0), eb('owner_id', '=', userId)]))
|
||||
.orderBy('sort_order', 'asc')
|
||||
.execute();
|
||||
}
|
||||
|
||||
/** PK62 (`reorderItems`, looped inside its transaction) — `UPDATE packing_items SET sort_order = ? WHERE id = ? AND trip_id = ?`. */
|
||||
async setSortOrder(id: number, trip_id: number | string, sort_order: number): Promise<void> {
|
||||
await this.nativeUpdate({ id, trip: trip_id as number }, { sort_order });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Plan 3e Task 3 (`TripsService.copy`, TP66-69) — additive.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* TP68 (`trips.service.ts::copy`'s packing-items read) — `SELECT * FROM
|
||||
* packing_items WHERE trip_id = ? AND (is_private = 0 OR owner_id = ?)`.
|
||||
* **Security-sensitive: the privacy filter** (matches PK54/`listExportable`'s
|
||||
* own-list-only rule — the copier may carry over the Common list plus
|
||||
* their own items, never a recipient's or another member's restricted
|
||||
* item). A distinct method from `listExportable`: this one is the FULL
|
||||
* row (the copy loop reads `bag_id`/`weight_grams`/`owner_id` off it,
|
||||
* `listExportable`'s narrower `{name, category}` projection is
|
||||
* `saveAsTemplate`'s own shape) and carries no `ORDER BY` (the legacy
|
||||
* statement has none, unlike `listExportable`'s `sort_order ASC`).
|
||||
*/
|
||||
async listOwnListForCopy(trip_id: number | string, userId: number): Promise<PackingItemRow[]> {
|
||||
return await this.db()
|
||||
.selectFrom('packing_items')
|
||||
.selectAll()
|
||||
.where('trip_id', '=', trip_id as number)
|
||||
.where((eb) => eb.or([eb('is_private', '=', 0), eb('owner_id', '=', userId)]))
|
||||
.execute();
|
||||
}
|
||||
|
||||
/**
|
||||
* TP69 (`trips.service.ts::copy`'s packing-items insert, looped) —
|
||||
* `INSERT INTO packing_items (trip_id, name, checked, category,
|
||||
* sort_order, weight_grams, bag_id, is_private, owner_id, updated_at)
|
||||
* VALUES (?, ?, 0, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)` — a distinct
|
||||
* column set from {@link insertItem}/{@link insertFromTemplate}
|
||||
* (`checked` is always 0; `quantity` takes its SQL default — 1, matching
|
||||
* the legacy statement's own omission of it). MikroORM's own `insert()`,
|
||||
* same reason as {@link insertItem}'s docstring (a hand-set
|
||||
* `CURRENT_TIMESTAMP`, not a SQL-level column default). Restricted items
|
||||
* stay restricted, owned by the copier; recipient rows are not carried
|
||||
* over (the caller's own note, unchanged).
|
||||
*/
|
||||
async insertCopy(row: { trip_id: number | string; name: string; category: string | null; sort_order: number | null; weight_grams: number | null; bag_id: number | null; is_private: number; owner_id: number | null }): Promise<number> {
|
||||
const platform = this.getEntityManager().getPlatform();
|
||||
const id = await this.insert({
|
||||
trip: row.trip_id,
|
||||
name: row.name,
|
||||
checked: 0,
|
||||
category: row.category,
|
||||
sort_order: row.sort_order,
|
||||
weight_grams: row.weight_grams,
|
||||
bag: row.bag_id,
|
||||
is_private: row.is_private,
|
||||
owner: row.owner_id,
|
||||
updated_at: currentTimestamp(platform),
|
||||
});
|
||||
return Number(id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,72 @@
|
||||
import type { PackingTemplateCategories } from '../entities/PackingTemplateCategories.entity';
|
||||
import { type AssertRowKeys } from './_shared/rows';
|
||||
import { TrekRepository } from './_shared/trek-repository';
|
||||
|
||||
export class PackingTemplateCategoriesRepository extends TrekRepository<PackingTemplateCategories> {}
|
||||
/** A bare `packing_template_categories` row — every scalar column, incl. the `persist(false)` `template_id` relation mirror. */
|
||||
export interface PackingTemplateCategoryRow {
|
||||
id: number;
|
||||
template_id: number;
|
||||
name: string;
|
||||
sort_order: number;
|
||||
}
|
||||
|
||||
const _packingTemplateCategoryRowKeys: AssertRowKeys<PackingTemplateCategoryRow, PackingTemplateCategories> = true;
|
||||
|
||||
interface PackingTemplateCategoriesKyselyDB {
|
||||
packing_template_categories: PackingTemplateCategoryRow;
|
||||
}
|
||||
|
||||
/** The insert-only shape for `insertCategory` (PK56/PK77) — `id` is autoincrement and omitted. */
|
||||
interface PackingTemplateCategoriesInsertKyselyDB {
|
||||
packing_template_categories: { template_id: number | string; name: string; sort_order: number };
|
||||
}
|
||||
|
||||
/** `packing_template_categories` — the middle tier of the packing template tree. Kysely throughout: `template_id` is `persist(false)`. */
|
||||
export class PackingTemplateCategoriesRepository extends TrekRepository<PackingTemplateCategories> {
|
||||
private db() {
|
||||
return this.kysely<PackingTemplateCategoriesKyselyDB>();
|
||||
}
|
||||
|
||||
/** PK66 (`getPackingTemplate`) — `SELECT * FROM packing_template_categories WHERE template_id = ? ORDER BY sort_order, id`. */
|
||||
async listForTemplate(template_id: number | string): Promise<PackingTemplateCategoryRow[]> {
|
||||
return await this.db().selectFrom('packing_template_categories').selectAll().where('template_id', '=', template_id as number).orderBy('sort_order', 'asc').orderBy('id', 'asc').execute();
|
||||
}
|
||||
|
||||
/**
|
||||
* PK56 (`saveAsTemplate`'s per-category loop)/PK77 (`createTemplateCategory`)
|
||||
* — the same `INSERT INTO packing_template_categories (template_id, name,
|
||||
* sort_order) VALUES (?, ?, ?)`, one method, both call sites. Returns the
|
||||
* new row's id. Named `insertCategory`, not `insert` — the latter collides
|
||||
* with `TrekRepository`/`EntityRepository`'s own same-named method.
|
||||
*/
|
||||
async insertCategory(template_id: number | string, name: string, sort_order: number): Promise<number> {
|
||||
const result = await this.kysely<PackingTemplateCategoriesInsertKyselyDB>().insertInto('packing_template_categories').values({ template_id, name, sort_order }).executeTakeFirstOrThrow();
|
||||
return Number(result.insertId);
|
||||
}
|
||||
|
||||
/** PK76 (`createTemplateCategory`) — `SELECT MAX(sort_order) as max FROM packing_template_categories WHERE template_id = ?`. */
|
||||
async maxSortOrder(template_id: number | string): Promise<number | null> {
|
||||
const row = await this.db().selectFrom('packing_template_categories').select((eb) => eb.fn.max('sort_order').as('max')).where('template_id', '=', template_id as number).executeTakeFirst();
|
||||
return row?.max ?? null;
|
||||
}
|
||||
|
||||
/** PK78/PK81 — `SELECT * FROM packing_template_categories WHERE id = ?`, same text at two call sites (`createTemplateCategory`'s re-select, `updateTemplateCategory`'s re-select). */
|
||||
async findById(id: number | string): Promise<PackingTemplateCategoryRow | undefined> {
|
||||
return await this.db().selectFrom('packing_template_categories').selectAll().where('id', '=', id as number).executeTakeFirst();
|
||||
}
|
||||
|
||||
/** PK79/PK82 — `SELECT * FROM packing_template_categories WHERE id = ? AND template_id = ?`, the scope-check text at two call sites (`updateTemplateCategory`, `deleteTemplateCategory`). */
|
||||
async findInTemplate(id: number | string, template_id: number | string): Promise<PackingTemplateCategoryRow | undefined> {
|
||||
return await this.db().selectFrom('packing_template_categories').selectAll().where('id', '=', id as number).where('template_id', '=', template_id as number).executeTakeFirst();
|
||||
}
|
||||
|
||||
/** PK80 (`updateTemplateCategory`) — `UPDATE packing_template_categories SET name = ? WHERE id = ?`. */
|
||||
async updateName(id: number | string, name: string): Promise<void> {
|
||||
await this.db().updateTable('packing_template_categories').set({ name }).where('id', '=', id as number).execute();
|
||||
}
|
||||
|
||||
/** PK83 (`deleteTemplateCategory`) — `DELETE FROM packing_template_categories WHERE id = ?`. */
|
||||
async delete(id: number | string): Promise<void> {
|
||||
await this.nativeDelete({ id: id as number });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,119 @@
|
||||
import type { PackingTemplateItems } from '../entities/PackingTemplateItems.entity';
|
||||
import { type AssertRowKeys } from './_shared/rows';
|
||||
import { TrekRepository } from './_shared/trek-repository';
|
||||
|
||||
export class PackingTemplateItemsRepository extends TrekRepository<PackingTemplateItems> {}
|
||||
/** A bare `packing_template_items` row — every scalar column, incl. the `persist(false)` `category_id` relation mirror. */
|
||||
export interface PackingTemplateItemRow {
|
||||
id: number;
|
||||
category_id: number;
|
||||
name: string;
|
||||
sort_order: number;
|
||||
}
|
||||
|
||||
const _packingTemplateItemRowKeys: AssertRowKeys<PackingTemplateItemRow, PackingTemplateItems> = true;
|
||||
|
||||
/** PK50's apply-template projection (`applyTemplate`). */
|
||||
export interface PackingTemplateApplyRow {
|
||||
name: string;
|
||||
category: string;
|
||||
}
|
||||
|
||||
interface PackingTemplateItemsKyselyDB {
|
||||
packing_template_items: PackingTemplateItemRow;
|
||||
packing_template_categories: { id: number; template_id: number; name: string; sort_order: number };
|
||||
}
|
||||
|
||||
/** The insert-only shape for `insertTemplateItem` (PK57/PK86) — `id` is autoincrement and omitted. */
|
||||
interface PackingTemplateItemsInsertKyselyDB {
|
||||
packing_template_items: { category_id: number | string; name: string; sort_order: number };
|
||||
}
|
||||
|
||||
/** `packing_template_items` — the leaf tier of the packing template tree. Kysely throughout: `category_id` is `persist(false)`. */
|
||||
export class PackingTemplateItemsRepository extends TrekRepository<PackingTemplateItems> {
|
||||
private db() {
|
||||
return this.kysely<PackingTemplateItemsKyselyDB>();
|
||||
}
|
||||
|
||||
/**
|
||||
* PK50 (`applyTemplate`) — `SELECT ti.name, tc.name as category FROM
|
||||
* packing_template_items ti JOIN packing_template_categories tc ON
|
||||
* ti.category_id = tc.id WHERE tc.template_id = ? ORDER BY tc.sort_order,
|
||||
* ti.sort_order`.
|
||||
*/
|
||||
async listForApply(template_id: number | string): Promise<PackingTemplateApplyRow[]> {
|
||||
return await this.db()
|
||||
.selectFrom('packing_template_items as ti')
|
||||
.innerJoin('packing_template_categories as tc', 'tc.id', 'ti.category_id')
|
||||
.select(['ti.name', 'tc.name as category'])
|
||||
.where('tc.template_id', '=', template_id as number)
|
||||
.orderBy('tc.sort_order', 'asc')
|
||||
.orderBy('ti.sort_order', 'asc')
|
||||
.execute();
|
||||
}
|
||||
|
||||
/**
|
||||
* PK67 (`getPackingTemplate`) — `SELECT ti.* FROM packing_template_items
|
||||
* ti JOIN packing_template_categories tc ON ti.category_id = tc.id WHERE
|
||||
* tc.template_id = ? ORDER BY ti.sort_order, ti.id`.
|
||||
*/
|
||||
async listForTemplate(template_id: number | string): Promise<PackingTemplateItemRow[]> {
|
||||
return await this.db()
|
||||
.selectFrom('packing_template_items as ti')
|
||||
.innerJoin('packing_template_categories as tc', 'tc.id', 'ti.category_id')
|
||||
.selectAll('ti')
|
||||
.where('tc.template_id', '=', template_id as number)
|
||||
.orderBy('ti.sort_order', 'asc')
|
||||
.orderBy('ti.id', 'asc')
|
||||
.execute();
|
||||
}
|
||||
|
||||
/**
|
||||
* PK57 (`saveAsTemplate`'s per-item loop)/PK86 (`createTemplateItem`) —
|
||||
* the same `INSERT INTO packing_template_items (category_id, name,
|
||||
* sort_order) VALUES (?, ?, ?)`, one method, both call sites. Returns the
|
||||
* new row's id. Named `insertTemplateItem`, not `insert` — the latter
|
||||
* collides with `TrekRepository`/`EntityRepository`'s own same-named
|
||||
* method.
|
||||
*/
|
||||
async insertTemplateItem(category_id: number | string, name: string, sort_order: number): Promise<number> {
|
||||
const result = await this.kysely<PackingTemplateItemsInsertKyselyDB>().insertInto('packing_template_items').values({ category_id, name, sort_order }).executeTakeFirstOrThrow();
|
||||
return Number(result.insertId);
|
||||
}
|
||||
|
||||
/** PK85 (`createTemplateItem`) — `SELECT MAX(sort_order) as max FROM packing_template_items WHERE category_id = ?`. */
|
||||
async maxSortOrder(category_id: number | string): Promise<number | null> {
|
||||
const row = await this.db().selectFrom('packing_template_items').select((eb) => eb.fn.max('sort_order').as('max')).where('category_id', '=', category_id as number).executeTakeFirst();
|
||||
return row?.max ?? null;
|
||||
}
|
||||
|
||||
/** PK87/PK89 — `SELECT * FROM packing_template_items WHERE id = ?`, same text at two call sites (`createTemplateItem`'s re-select, `updateTemplateItem`'s re-select). */
|
||||
async findById(id: number | string): Promise<PackingTemplateItemRow | undefined> {
|
||||
return await this.db().selectFrom('packing_template_items').selectAll().where('id', '=', id as number).executeTakeFirst();
|
||||
}
|
||||
|
||||
/**
|
||||
* PK63 (`scopedTemplateItem`) — `SELECT ti.* FROM packing_template_items
|
||||
* ti JOIN packing_template_categories tc ON ti.category_id = tc.id WHERE
|
||||
* ti.id = ? AND tc.template_id = ?`, the template-scoping guard shared by
|
||||
* `updateTemplateItem` and `deleteTemplateItem` (two call sites).
|
||||
*/
|
||||
async findScoped(id: number | string, template_id: number | string): Promise<PackingTemplateItemRow | undefined> {
|
||||
return await this.db()
|
||||
.selectFrom('packing_template_items as ti')
|
||||
.innerJoin('packing_template_categories as tc', 'tc.id', 'ti.category_id')
|
||||
.selectAll('ti')
|
||||
.where('ti.id', '=', id as number)
|
||||
.where('tc.template_id', '=', template_id as number)
|
||||
.executeTakeFirst();
|
||||
}
|
||||
|
||||
/** PK88 (`updateTemplateItem`) — `UPDATE packing_template_items SET name = ? WHERE id = ?`. */
|
||||
async updateName(id: number | string, name: string): Promise<void> {
|
||||
await this.db().updateTable('packing_template_items').set({ name }).where('id', '=', id as number).execute();
|
||||
}
|
||||
|
||||
/** PK90 (`deleteTemplateItem`) — `DELETE FROM packing_template_items WHERE id = ?`. */
|
||||
async delete(id: number | string): Promise<void> {
|
||||
await this.nativeDelete({ id: id as number });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,140 @@
|
||||
import type { PackingTemplates } from '../entities/PackingTemplates.entity';
|
||||
import { type AssertRowKeys } from './_shared/rows';
|
||||
import { TrekRepository } from './_shared/trek-repository';
|
||||
|
||||
export class PackingTemplatesRepository extends TrekRepository<PackingTemplates> {}
|
||||
/** A bare `packing_templates` row — every scalar column, incl. the `persist(false)` `created_by` relation mirror. */
|
||||
export interface PackingTemplateRow {
|
||||
id: number;
|
||||
name: string;
|
||||
created_by: number;
|
||||
created_at: string | null;
|
||||
}
|
||||
|
||||
const _packingTemplateRowKeys: AssertRowKeys<PackingTemplateRow, PackingTemplates> = true;
|
||||
|
||||
/** PK49's trip-member listing row (`listTemplates`). */
|
||||
export interface PackingTemplateSummaryRow {
|
||||
id: number;
|
||||
name: string;
|
||||
item_count: number;
|
||||
}
|
||||
|
||||
/** PK64's admin listing row (`listPackingTemplates`). */
|
||||
export interface PackingTemplateAdminRow extends PackingTemplateRow {
|
||||
created_by_name: string;
|
||||
item_count: number;
|
||||
category_count: number;
|
||||
}
|
||||
|
||||
interface PackingTemplatesKyselyDB {
|
||||
packing_templates: PackingTemplateRow;
|
||||
packing_template_categories: { id: number; template_id: number; name: string; sort_order: number };
|
||||
packing_template_items: { id: number; category_id: number; name: string; sort_order: number };
|
||||
users: { id: number; username: string };
|
||||
}
|
||||
|
||||
/** The insert-only shape for `insertTemplate` (PK55/PK68) — `id`/`created_at` are autoincrement/`DEFAULT CURRENT_TIMESTAMP` and omitted. */
|
||||
interface PackingTemplatesInsertKyselyDB {
|
||||
packing_templates: { name: string; created_by: number };
|
||||
}
|
||||
|
||||
/**
|
||||
* `packing_templates` — the top level of the (admin-managed) packing
|
||||
* template tree. Kysely throughout: `created_by` is `persist(false)` (the
|
||||
* physical mirror of the `createdByRef` relation).
|
||||
*/
|
||||
export class PackingTemplatesRepository extends TrekRepository<PackingTemplates> {
|
||||
private db() {
|
||||
return this.kysely<PackingTemplatesKyselyDB>();
|
||||
}
|
||||
|
||||
/**
|
||||
* PK49 (`listTemplates`, the trip-member read) — `SELECT pt.id, pt.name,
|
||||
* (SELECT COUNT(*) FROM packing_template_items ti JOIN
|
||||
* packing_template_categories tc ON ti.category_id = tc.id WHERE
|
||||
* tc.template_id = pt.id) as item_count FROM packing_templates pt ORDER
|
||||
* BY pt.created_at DESC`. The correlated `COUNT` subquery re-expressed as
|
||||
* a join inside the correlated subquery itself (same shape,
|
||||
* `Trips.repository.ts`'s `day_count`/`place_count` precedent for a
|
||||
* correlated scalar count).
|
||||
*/
|
||||
async listWithItemCount(): Promise<PackingTemplateSummaryRow[]> {
|
||||
return await this.db()
|
||||
.selectFrom('packing_templates as pt')
|
||||
.select((eb) => [
|
||||
'pt.id',
|
||||
'pt.name',
|
||||
eb
|
||||
.selectFrom('packing_template_items as ti')
|
||||
.innerJoin('packing_template_categories as tc', 'tc.id', 'ti.category_id')
|
||||
.select((eb2) => eb2.fn.countAll<number>().as('c'))
|
||||
.whereRef('tc.template_id', '=', 'pt.id')
|
||||
.as('item_count'),
|
||||
])
|
||||
.orderBy('pt.created_at', 'desc')
|
||||
.execute();
|
||||
}
|
||||
|
||||
/**
|
||||
* PK64 (`listPackingTemplates`, the admin listing) — `SELECT pt.*,
|
||||
* u.username as created_by_name, (correlated item COUNT), (correlated
|
||||
* category COUNT) FROM packing_templates pt JOIN users u ON pt.created_by
|
||||
* = u.id ORDER BY pt.created_at DESC`.
|
||||
*/
|
||||
async listAdmin(): Promise<PackingTemplateAdminRow[]> {
|
||||
return await this.db()
|
||||
.selectFrom('packing_templates as pt')
|
||||
.innerJoin('users as u', 'u.id', 'pt.created_by')
|
||||
.selectAll('pt')
|
||||
.select((eb) => [
|
||||
'u.username as created_by_name',
|
||||
eb
|
||||
.selectFrom('packing_template_items as ti')
|
||||
.innerJoin('packing_template_categories as tc', 'tc.id', 'ti.category_id')
|
||||
.select((eb2) => eb2.fn.countAll<number>().as('c'))
|
||||
.whereRef('tc.template_id', '=', 'pt.id')
|
||||
.as('item_count'),
|
||||
eb
|
||||
.selectFrom('packing_template_categories as tc2')
|
||||
.select((eb2) => eb2.fn.countAll<number>().as('c'))
|
||||
.whereRef('tc2.template_id', '=', 'pt.id')
|
||||
.as('category_count'),
|
||||
])
|
||||
.orderBy('pt.created_at', 'desc')
|
||||
.execute();
|
||||
}
|
||||
|
||||
/**
|
||||
* PK65/PK69/PK70/PK72/PK73 — `SELECT * FROM packing_templates WHERE id =
|
||||
* ?`, the SAME text at five call sites (`getPackingTemplate`,
|
||||
* `createPackingTemplate`'s post-insert re-select,
|
||||
* `updatePackingTemplate`'s existence check and post-write re-select,
|
||||
* `deletePackingTemplate`'s existence check). One method, five sites.
|
||||
*/
|
||||
async findById(id: number | string): Promise<PackingTemplateRow | undefined> {
|
||||
return await this.db().selectFrom('packing_templates').selectAll().where('id', '=', id as number).executeTakeFirst();
|
||||
}
|
||||
|
||||
/**
|
||||
* PK55 (`saveAsTemplate`)/PK68 (`createPackingTemplate`) — the same
|
||||
* `INSERT INTO packing_templates (name, created_by) VALUES (?, ?)`, one
|
||||
* method, both call sites. Returns the new row's id. Named `insertTemplate`,
|
||||
* not `insert` — the latter collides with `TrekRepository`/`EntityRepository`'s
|
||||
* own same-named method (a different signature; `BudgetItemsRepository
|
||||
* .insertItem`'s precedent).
|
||||
*/
|
||||
async insertTemplate(name: string, created_by: number): Promise<number> {
|
||||
const result = await this.kysely<PackingTemplatesInsertKyselyDB>().insertInto('packing_templates').values({ name, created_by }).executeTakeFirstOrThrow();
|
||||
return Number(result.insertId);
|
||||
}
|
||||
|
||||
/** PK71 (`updatePackingTemplate`) — `UPDATE packing_templates SET name = ? WHERE id = ?`. */
|
||||
async updateName(id: number | string, name: string): Promise<void> {
|
||||
await this.db().updateTable('packing_templates').set({ name }).where('id', '=', id as number).execute();
|
||||
}
|
||||
|
||||
/** PK74 (`deletePackingTemplate`) — `DELETE FROM packing_templates WHERE id = ?`. */
|
||||
async delete(id: number | string): Promise<void> {
|
||||
await this.nativeDelete({ id: id as number });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -173,7 +173,10 @@ export class PackingController {
|
||||
throw new HttpException({ error: 'Item not found' }, 404);
|
||||
}
|
||||
// Scope the delete to the people who could see it (owner + recipients, #858).
|
||||
this.packing.emitToViewers(tripId, 'packing:deleted', { itemId: Number(id) }, deleted as PackingItemRow, socketId);
|
||||
// `deleted` is already a concretely-typed `PackingItemRow` (Plan 3e Task 3's
|
||||
// `PackingItemsRepository`, via `PackingService.deleteItem`'s return type) —
|
||||
// no cast needed, unlike `updated` above (that one's inferred as `unknown`).
|
||||
this.packing.emitToViewers(tripId, 'packing:deleted', { itemId: Number(id) }, deleted, socketId);
|
||||
this.packing.broadcastBagTotals(tripId);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
||||
import { PackingController } from './packing.controller';
|
||||
import { AdminPackingTemplatesController } from './admin-packing-templates.controller';
|
||||
import { PackingMcp } from './packing.mcp';
|
||||
@@ -12,12 +13,26 @@ import { AuthModule } from '../auth/auth.module';
|
||||
import { AddonsModule } from '../addons/addons.module';
|
||||
import { NotificationsModule } from '../notifications/notifications.module';
|
||||
import { McpSharedModule } from '../mcp-shared/mcp-shared.module';
|
||||
import { PackingItems } from '../../db/entities/PackingItems.entity';
|
||||
import { PackingItemContributors } from '../../db/entities/PackingItemContributors.entity';
|
||||
import { PackingBags } from '../../db/entities/PackingBags.entity';
|
||||
import { PackingCategoryAssignees } from '../../db/entities/PackingCategoryAssignees.entity';
|
||||
import { PackingTemplates } from '../../db/entities/PackingTemplates.entity';
|
||||
import { PackingTemplateCategories } from '../../db/entities/PackingTemplateCategories.entity';
|
||||
import { PackingTemplateItems } from '../../db/entities/PackingTemplateItems.entity';
|
||||
import { Trips } from '../../db/entities/Trips.entity';
|
||||
|
||||
/** Packing domain (S2 — Phase 2 trip sub-domain). Registered in AppModule.
|
||||
* Exports PackingService for in-container consumers (TripsService bundle,
|
||||
* PackingRpc). */
|
||||
@Module({
|
||||
imports: [McpSharedModule, NotificationsModule, PermissionsModule, AuthModule, RealtimeModule, PluginGuardsModule, AddonsModule, AuditModule],
|
||||
imports: [
|
||||
// The nine packing-owned tables (Plan 3e Task 3) plus `Trips` (additive —
|
||||
// `PackingService.notifyTagged`'s PK91 `getTitle` read only, the same
|
||||
// "registered here only for one read, never the owning module" shape
|
||||
// `CollabModule`'s own forFeature list documents).
|
||||
MikroOrmModule.forFeature([PackingItems, PackingItemContributors, PackingBags, PackingCategoryAssignees, PackingTemplates, PackingTemplateCategories, PackingTemplateItems, Trips]),
|
||||
McpSharedModule, NotificationsModule, PermissionsModule, AuthModule, RealtimeModule, PluginGuardsModule, AddonsModule, AuditModule],
|
||||
controllers: [PackingController, AdminPackingTemplatesController],
|
||||
providers: [PackingService, PackingMcp, PackingRpc],
|
||||
exports: [PackingService],
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import type { TrekWsPayload, TrekWsTripEventName } from '@trek/shared';
|
||||
import { RealtimeService } from '../realtime/realtime.service';
|
||||
import { PermissionsService } from '../permissions/permissions.service';
|
||||
@@ -8,6 +9,22 @@ import type { User } from '../../types';
|
||||
import { DatabaseService, type TripAccess } from '../database/database.service';
|
||||
import { NotificationsService } from '../notifications/notifications.service';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
import { PackingItems } from '../../db/entities/PackingItems.entity';
|
||||
import type { PackingItemsRepository, PackingItemRow } from '../../db/repositories/PackingItems.repository';
|
||||
import { PackingItemContributors } from '../../db/entities/PackingItemContributors.entity';
|
||||
import type { PackingItemContributorsRepository } from '../../db/repositories/PackingItemContributors.repository';
|
||||
import { PackingBags } from '../../db/entities/PackingBags.entity';
|
||||
import type { PackingBagsRepository, PackingBagMemberForTripRow } from '../../db/repositories/PackingBags.repository';
|
||||
import { PackingCategoryAssignees } from '../../db/entities/PackingCategoryAssignees.entity';
|
||||
import type { PackingCategoryAssigneesRepository } from '../../db/repositories/PackingCategoryAssignees.repository';
|
||||
import { PackingTemplates } from '../../db/entities/PackingTemplates.entity';
|
||||
import type { PackingTemplatesRepository } from '../../db/repositories/PackingTemplates.repository';
|
||||
import { PackingTemplateCategories } from '../../db/entities/PackingTemplateCategories.entity';
|
||||
import type { PackingTemplateCategoriesRepository } from '../../db/repositories/PackingTemplateCategories.repository';
|
||||
import { PackingTemplateItems } from '../../db/entities/PackingTemplateItems.entity';
|
||||
import type { PackingTemplateItemsRepository } from '../../db/repositories/PackingTemplateItems.repository';
|
||||
import { Trips } from '../../db/entities/Trips.entity';
|
||||
import type { TripsRepository } from '../../db/repositories/Trips.repository';
|
||||
|
||||
/** Privacy fields stamped on a packing item (#858). */
|
||||
type PrivacyFields = { is_private?: number; owner_id?: number | null };
|
||||
@@ -44,15 +61,23 @@ interface ImportItem {
|
||||
const BAG_COLORS = ['#6366f1', '#ec4899', '#f97316', '#10b981', '#06b6d4', '#8b5cf6', '#ef4444', '#f59e0b', '#3b82f6', '#84cc16', '#d946ef', '#14b8a6', '#f43f5e', '#a855f7', '#eab308', '#64748b'];
|
||||
|
||||
/**
|
||||
* Packing domain service — owns the packing SQL (moved from the legacy
|
||||
* services/packingService.ts: the bodyKeys sentinel protocol on the updates,
|
||||
* the #858 three-tier sharing model and the post-write re-selects). Trip
|
||||
* access, the 'packing_edit' permission and the WebSocket broadcast keep their
|
||||
* legacy call paths. Post-migration fixes over the legacy code: a single
|
||||
* 'Other' category default, bodyKeys-gated weight_limit_grams (explicit null
|
||||
* Packing domain service — owns the packing business logic (the bodyKeys
|
||||
* sentinel protocol on the updates, the #858 three-tier sharing model and
|
||||
* the post-write re-selects); the SQL itself lives in the nine `Packing*`
|
||||
* repositories (Plan 3e Task 3) this class is built on. Trip access, the
|
||||
* 'packing_edit' permission and the WebSocket broadcast keep their legacy
|
||||
* call paths. Post-migration fixes over the legacy code: a single 'Other'
|
||||
* category default, bodyKeys-gated weight_limit_grams (explicit null
|
||||
* clears it), and transactions around every multi-statement write. The
|
||||
* remaining non-Nest consumer went with the legacy MCP prompts registrar, and
|
||||
* packing.bridge.ts was deleted with it.
|
||||
*
|
||||
* **The per-actor visibility guard (#858, `PackingItemsRepository
|
||||
* .findVisibleInTrip`) is this domain's entire security model** — Task 0's
|
||||
* shared `packingVisibleToActorExpr` predicate
|
||||
* (`_shared/packing-visibility.ts`), consumed here rather than re-derived
|
||||
* (R1). `PackingService.getItemInTrip` no longer exists on this class: every
|
||||
* call site below calls the repository method directly.
|
||||
*/
|
||||
@Injectable()
|
||||
export class PackingService {
|
||||
@@ -62,6 +87,14 @@ export class PackingService {
|
||||
private readonly realtime: RealtimeService,
|
||||
private readonly notifications: NotificationsService,
|
||||
private readonly uow: UnitOfWork,
|
||||
@InjectRepository(PackingItems) private readonly itemsRepo: PackingItemsRepository,
|
||||
@InjectRepository(PackingItemContributors) private readonly contributorsRepo: PackingItemContributorsRepository,
|
||||
@InjectRepository(PackingBags) private readonly bagsRepo: PackingBagsRepository,
|
||||
@InjectRepository(PackingCategoryAssignees) private readonly categoryAssigneesRepo: PackingCategoryAssigneesRepository,
|
||||
@InjectRepository(PackingTemplates) private readonly templatesRepo: PackingTemplatesRepository,
|
||||
@InjectRepository(PackingTemplateCategories) private readonly templateCategoriesRepo: PackingTemplateCategoriesRepository,
|
||||
@InjectRepository(PackingTemplateItems) private readonly templateItemsRepo: PackingTemplateItemsRepository,
|
||||
@InjectRepository(Trips) private readonly tripsRepo: TripsRepository,
|
||||
) {}
|
||||
|
||||
async verifyTripAccess(tripId: string | number, userId: number) {
|
||||
@@ -173,27 +206,19 @@ export class PackingService {
|
||||
private async enrichItems(items: any[]): Promise<any[]> {
|
||||
if (items.length === 0) return items;
|
||||
const ids = items.map(i => i.id);
|
||||
const placeholders = ids.map(() => '?').join(',');
|
||||
const ownerIds = [...new Set(items.map(i => i.owner_id).filter((id): id is number => id != null))];
|
||||
|
||||
const owners = this.db.all<{ id: number; username: string }>(`SELECT id, username FROM users WHERE id IN (SELECT owner_id FROM packing_items WHERE id IN (${placeholders}))`, ...ids);
|
||||
const owners = await this.itemsRepo.listOwnersForIds(ownerIds);
|
||||
const ownerName = new Map(owners.map(o => [o.id, o.username]));
|
||||
|
||||
const recipientRows = this.db.all<{ item_id: number; user_id: number; username: string }>(`
|
||||
SELECT r.item_id, r.user_id, COALESCE(u.display_name, u.username) AS username
|
||||
FROM packing_item_recipients r JOIN users u ON u.id = r.user_id
|
||||
WHERE r.item_id IN (${placeholders})
|
||||
`, ...ids);
|
||||
const recipientRows = await this.itemsRepo.listRecipientsForItems(ids);
|
||||
const recipientsByItem = new Map<number, { user_id: number; username: string }[]>();
|
||||
for (const r of recipientRows) {
|
||||
if (!recipientsByItem.has(r.item_id)) recipientsByItem.set(r.item_id, []);
|
||||
recipientsByItem.get(r.item_id)!.push({ user_id: r.user_id, username: r.username });
|
||||
}
|
||||
|
||||
const contributorRows = this.db.all<{ item_id: number; user_id: number; status: string; username: string }>(`
|
||||
SELECT c.item_id, c.user_id, c.status, COALESCE(u.display_name, u.username) AS username
|
||||
FROM packing_item_contributors c JOIN users u ON u.id = c.user_id
|
||||
WHERE c.item_id IN (${placeholders})
|
||||
`, ...ids);
|
||||
const contributorRows = await this.contributorsRepo.listForItems(ids);
|
||||
const contributorsByItem = new Map<number, { user_id: number; username: string; status: string }[]>();
|
||||
for (const c of contributorRows) {
|
||||
if (!contributorsByItem.has(c.item_id)) contributorsByItem.set(c.item_id, []);
|
||||
@@ -215,29 +240,14 @@ export class PackingService {
|
||||
// returned — every current caller (trip summary, offline bundle, prompts,
|
||||
// resources, plugin host) passes the viewer; omit it only for genuinely
|
||||
// viewer-less internal reads.
|
||||
let rows: any[];
|
||||
if (userId == null) {
|
||||
rows = this.db.all(
|
||||
'SELECT * FROM packing_items WHERE trip_id = ? ORDER BY sort_order ASC, created_at ASC',
|
||||
tripId
|
||||
);
|
||||
} else {
|
||||
rows = this.db.all(`
|
||||
SELECT * FROM packing_items
|
||||
WHERE trip_id = ?
|
||||
AND (is_private = 0
|
||||
OR owner_id = ?
|
||||
OR EXISTS (SELECT 1 FROM packing_item_recipients r WHERE r.item_id = packing_items.id AND r.user_id = ?))
|
||||
ORDER BY sort_order ASC, created_at ASC
|
||||
`, tripId, userId, userId);
|
||||
}
|
||||
const rows: PackingItemRow[] = userId == null ? await this.itemsRepo.listForTrip(tripId) : await this.itemsRepo.listVisibleToActor(tripId, userId);
|
||||
return await this.enrichItems(rows);
|
||||
}
|
||||
|
||||
/** Reads an item's current privacy fields (#858) before an update, so the
|
||||
* controller can detect a public↔private transition and route the broadcast. */
|
||||
async getItemPrivacy(tripId: string | number, id: string | number): Promise<PrivacyFields | undefined> {
|
||||
return this.db.get<PrivacyFields>('SELECT is_private, owner_id FROM packing_items WHERE id = ? AND trip_id = ?', id, tripId);
|
||||
return await this.itemsRepo.getPrivacy(id, tripId);
|
||||
}
|
||||
|
||||
/** Maps the three-tier visibility (#858) onto the stored is_private flag. */
|
||||
@@ -252,27 +262,34 @@ export class PackingService {
|
||||
ownerId?: number,
|
||||
) {
|
||||
if (data.bag_id != null && !(await this.bagInTrip(tripId, data.bag_id))) return { invalidBag: true } as const;
|
||||
const maxOrder = this.db.get<{ max: number | null }>('SELECT MAX(sort_order) as max FROM packing_items WHERE trip_id = ?', tripId)!;
|
||||
const sortOrder = (maxOrder.max !== null ? maxOrder.max : -1) + 1;
|
||||
const maxOrder = await this.itemsRepo.maxSortOrder(tripId);
|
||||
const sortOrder = (maxOrder !== null ? maxOrder : -1) + 1;
|
||||
const qty = Math.max(1, Math.min(999, Number(data.quantity) || 1));
|
||||
const isPrivate = this.visibilityToPrivate(data.visibility, data.is_private);
|
||||
|
||||
const itemId = await this.uow.transactional(async () => {
|
||||
const result = this.db.run(
|
||||
'INSERT INTO packing_items (trip_id, name, checked, category, sort_order, quantity, weight_grams, bag_id, is_private, owner_id, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)',
|
||||
tripId, data.name, data.checked ? 1 : 0, data.category || 'Other', sortOrder, qty, data.weight_grams ?? null, data.bag_id ?? null, isPrivate, ownerId ?? null
|
||||
);
|
||||
const id = Number(result.lastInsertRowid);
|
||||
const id = await this.itemsRepo.insertItem({
|
||||
trip_id: tripId,
|
||||
name: data.name,
|
||||
checked: data.checked ? 1 : 0,
|
||||
category: data.category || 'Other',
|
||||
sort_order: sortOrder,
|
||||
quantity: qty,
|
||||
weight_grams: data.weight_grams ?? null,
|
||||
bag_id: data.bag_id ?? null,
|
||||
is_private: isPrivate,
|
||||
owner_id: ownerId ?? null,
|
||||
});
|
||||
// "Shared with specific people" — record the recipients it covers.
|
||||
if (data.visibility === 'shared' && Array.isArray(data.recipient_ids)) {
|
||||
const ins = this.db.prepare('INSERT OR IGNORE INTO packing_item_recipients (item_id, user_id) VALUES (?, ?)');
|
||||
const roster = await this.tripRosterIds(tripId);
|
||||
for (const uid of data.recipient_ids) if (uid !== ownerId && roster.has(uid)) ins.run(id, uid);
|
||||
const recipients = data.recipient_ids.filter(uid => uid !== ownerId && roster.has(uid));
|
||||
await this.itemsRepo.insertRecipientsIgnore(id, recipients);
|
||||
}
|
||||
return id;
|
||||
});
|
||||
|
||||
return (await this.enrichItems([this.db.get('SELECT * FROM packing_items WHERE id = ?', itemId)]))[0];
|
||||
return (await this.enrichItems([await this.itemsRepo.findById(itemId)]))[0];
|
||||
}
|
||||
|
||||
async updateItem(
|
||||
@@ -285,13 +302,13 @@ export class PackingService {
|
||||
): Promise<unknown | UpdateConflict | null> {
|
||||
// Was a trip-scoped lookup, which let any member with packing_edit write to
|
||||
// another member's restricted item (and read it back off the response).
|
||||
const item = await this.getItemInTrip(tripId, id, actingUserId);
|
||||
const item = await this.itemsRepo.findVisibleInTrip(id, tripId, actingUserId);
|
||||
if (!item) return null;
|
||||
|
||||
// Optimistic concurrency (#1135): reject a stale offline overwrite. Absent
|
||||
// token => unconditional update (back-compat with older clients).
|
||||
if (ifMatch !== undefined && item.updated_at != null && String(item.updated_at) !== ifMatch) {
|
||||
return { conflict: true, server: this.db.get('SELECT * FROM packing_items WHERE id = ?', id) };
|
||||
return { conflict: true, server: await this.itemsRepo.findById(id) };
|
||||
}
|
||||
|
||||
// A non-null bag about to be bound must belong to this trip (#2154) — the
|
||||
@@ -304,71 +321,22 @@ export class PackingService {
|
||||
// the visibility filter still has someone to match (#858).
|
||||
const claimOwner = bodyKeys.includes('is_private') && !!data.is_private && item.owner_id == null && actingUserId != null;
|
||||
|
||||
this.db.run(`
|
||||
UPDATE packing_items SET
|
||||
name = COALESCE(?, name),
|
||||
checked = CASE WHEN ? IS NOT NULL THEN ? ELSE checked END,
|
||||
category = COALESCE(?, category),
|
||||
weight_grams = CASE WHEN ? THEN ? ELSE weight_grams END,
|
||||
bag_id = CASE WHEN ? THEN ? ELSE bag_id END,
|
||||
quantity = CASE WHEN ? THEN ? ELSE quantity END,
|
||||
is_private = CASE WHEN ? THEN ? ELSE is_private END,
|
||||
owner_id = CASE WHEN ? THEN ? ELSE owner_id END,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ?
|
||||
`,
|
||||
data.name || null,
|
||||
data.checked !== undefined ? 1 : null,
|
||||
data.checked ? 1 : 0,
|
||||
data.category || null,
|
||||
bodyKeys.includes('weight_grams') ? 1 : 0,
|
||||
data.weight_grams ?? null,
|
||||
bodyKeys.includes('bag_id') ? 1 : 0,
|
||||
data.bag_id ?? null,
|
||||
bodyKeys.includes('quantity') ? 1 : 0,
|
||||
Math.max(1, Math.min(999, Number(data.quantity) || 1)),
|
||||
bodyKeys.includes('is_private') ? 1 : 0,
|
||||
data.is_private ? 1 : 0,
|
||||
claimOwner ? 1 : 0,
|
||||
actingUserId ?? null,
|
||||
id
|
||||
);
|
||||
await this.itemsRepo.update(id, {
|
||||
name: [!!data.name, data.name || null],
|
||||
checked: [data.checked !== undefined, data.checked ? 1 : 0],
|
||||
category: [!!data.category, data.category || null],
|
||||
weight_grams: [bodyKeys.includes('weight_grams'), data.weight_grams ?? null],
|
||||
bag_id: [bodyKeys.includes('bag_id'), data.bag_id ?? null],
|
||||
quantity: [bodyKeys.includes('quantity'), Math.max(1, Math.min(999, Number(data.quantity) || 1))],
|
||||
is_private: [bodyKeys.includes('is_private'), data.is_private ? 1 : 0],
|
||||
owner_id: [claimOwner, actingUserId ?? null],
|
||||
});
|
||||
|
||||
return (await this.enrichItems([this.db.get('SELECT * FROM packing_items WHERE id = ?', id)]))[0];
|
||||
return (await this.enrichItems([await this.itemsRepo.findById(id)]))[0];
|
||||
}
|
||||
|
||||
// ── Three-tier sharing (#858): recipients, contributors, clone ───────────────
|
||||
|
||||
/**
|
||||
* The one visibility rule (#858), as a SQL fragment: Common belongs to the whole
|
||||
* trip, a restricted item belongs to its owner and to the people it was shared
|
||||
* with. Binds the actor id twice.
|
||||
*/
|
||||
private static readonly VISIBLE_TO_ACTOR = `(
|
||||
is_private = 0
|
||||
OR owner_id = ?
|
||||
OR EXISTS (SELECT 1 FROM packing_item_recipients r WHERE r.item_id = packing_items.id AND r.user_id = ?)
|
||||
)`;
|
||||
|
||||
/**
|
||||
* Loads an item scoped to its trip AND to what the actor may see.
|
||||
*
|
||||
* Trip membership used to be the whole check here, so any member holding
|
||||
* packing_edit could reach another member's Personal or Shared item by id
|
||||
* through update, delete, clone or the contributor routes. It resolves through
|
||||
* the visibility rule now, and an item the actor may not see comes back
|
||||
* undefined — deliberately indistinguishable from one that does not exist, so
|
||||
* these routes cannot be used to probe for ids. A missing actor denies too,
|
||||
* rather than falling through unfiltered.
|
||||
*/
|
||||
private async getItemInTrip(tripId: string | number, id: string | number, actorId: number | undefined) {
|
||||
if (actorId == null) return undefined;
|
||||
return this.db.get<{ id: number; owner_id: number | null; is_private: number; name: string; category: string | null; quantity: number; weight_grams: number | null; bag_id: number | null; updated_at?: string | null }>(
|
||||
`SELECT * FROM packing_items WHERE id = ? AND trip_id = ? AND ${PackingService.VISIBLE_TO_ACTOR}`,
|
||||
id, tripId, actorId, actorId,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-set who a "shared with specific people" item covers, and its visibility tier.
|
||||
* Only the owner (bringer) may change this; a non-owner caller is rejected with null.
|
||||
@@ -380,47 +348,50 @@ export class PackingService {
|
||||
visibility: PackingVisibility,
|
||||
recipientIds: number[],
|
||||
) {
|
||||
const item = await this.getItemInTrip(tripId, id, actingUserId);
|
||||
const item = await this.itemsRepo.findVisibleInTrip(id, tripId, actingUserId);
|
||||
if (!item) return null;
|
||||
// The owner controls sharing; an unowned legacy item is claimed by the actor.
|
||||
if (item.owner_id != null && item.owner_id !== actingUserId) return { forbidden: true as const };
|
||||
|
||||
await this.uow.transactional(async () => {
|
||||
this.db.run('UPDATE packing_items SET is_private = ?, owner_id = COALESCE(owner_id, ?), updated_at = CURRENT_TIMESTAMP WHERE id = ?',
|
||||
this.visibilityToPrivate(visibility), actingUserId, id);
|
||||
this.db.run('DELETE FROM packing_item_recipients WHERE item_id = ?', id);
|
||||
// COALESCE(owner_id, ?) at the SQL level kept the existing owner if one was
|
||||
// set; passing the claim only when the pre-image had none reproduces that
|
||||
// exactly (nothing else touches owner_id inside this same transaction).
|
||||
const claimOwnerId = item.owner_id == null ? actingUserId : undefined;
|
||||
await this.itemsRepo.updateSharing(id, this.visibilityToPrivate(visibility), claimOwnerId);
|
||||
await this.itemsRepo.deleteRecipientsForItem(Number(id));
|
||||
if (visibility === 'shared') {
|
||||
const ins = this.db.prepare('INSERT OR IGNORE INTO packing_item_recipients (item_id, user_id) VALUES (?, ?)');
|
||||
const owner = item.owner_id ?? actingUserId;
|
||||
const roster = await this.tripRosterIds(tripId);
|
||||
for (const uid of recipientIds) if (uid !== owner && roster.has(uid)) ins.run(id, uid);
|
||||
const recipients = recipientIds.filter(uid => uid !== owner && roster.has(uid));
|
||||
await this.itemsRepo.insertRecipientsIgnore(Number(id), recipients);
|
||||
}
|
||||
// Leaving the Common tier drops any co-contributors (they only apply to Common).
|
||||
if (visibility !== 'common') this.db.run('DELETE FROM packing_item_contributors WHERE item_id = ?', id);
|
||||
if (visibility !== 'common') await this.contributorsRepo.deleteForItem(Number(id));
|
||||
});
|
||||
return (await this.enrichItems([this.db.get('SELECT * FROM packing_items WHERE id = ?', id)]))[0];
|
||||
return (await this.enrichItems([await this.itemsRepo.findById(id)]))[0];
|
||||
}
|
||||
|
||||
/** "I can bring that too" — adds the user as a co-contributor on a Common item. */
|
||||
async addContributor(tripId: string | number, id: string | number, userId: number) {
|
||||
const item = await this.getItemInTrip(tripId, id, userId);
|
||||
const item = await this.itemsRepo.findVisibleInTrip(id, tripId, userId);
|
||||
if (!item || item.is_private !== 0) return null; // co-contribution is a Common-list concept
|
||||
if (item.owner_id === userId) return null; // the bringer is already covering it
|
||||
this.db.run("INSERT OR IGNORE INTO packing_item_contributors (item_id, user_id, status) VALUES (?, ?, 'accepted')", id, userId);
|
||||
return (await this.enrichItems([this.db.get('SELECT * FROM packing_items WHERE id = ?', id)]))[0];
|
||||
await this.contributorsRepo.insertIgnore(Number(id), userId);
|
||||
return (await this.enrichItems([await this.itemsRepo.findById(id)]))[0];
|
||||
}
|
||||
|
||||
async removeContributor(tripId: string | number, id: string | number, userId: number) {
|
||||
const item = await this.getItemInTrip(tripId, id, userId);
|
||||
const item = await this.itemsRepo.findVisibleInTrip(id, tripId, userId);
|
||||
if (!item) return null;
|
||||
this.db.run('DELETE FROM packing_item_contributors WHERE item_id = ? AND user_id = ?', id, userId);
|
||||
return (await this.enrichItems([this.db.get('SELECT * FROM packing_items WHERE id = ?', id)]))[0];
|
||||
await this.contributorsRepo.deleteOne(Number(id), userId);
|
||||
return (await this.enrichItems([await this.itemsRepo.findById(id)]))[0];
|
||||
}
|
||||
|
||||
/** True when the bag exists AND belongs to the trip — the referenced-id rule
|
||||
* the FK cannot enforce (it only checks existence). */
|
||||
private async bagInTrip(tripId: string | number, bagId: number): Promise<boolean> {
|
||||
return !!this.db.get('SELECT id FROM packing_bags WHERE id = ? AND trip_id = ?', bagId, tripId);
|
||||
return !!(await this.bagsRepo.findInTrip(bagId, tripId));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -430,12 +401,12 @@ export class PackingService {
|
||||
*/
|
||||
private async bagForCloner(tripId: string | number, bagId: number | null, userId: number): Promise<number | null> {
|
||||
if (bagId == null) return null;
|
||||
const bag = this.db.get<{ user_id: number | null }>('SELECT user_id FROM packing_bags WHERE id = ? AND trip_id = ?', bagId, tripId);
|
||||
const bag = await this.bagsRepo.findInTrip(bagId, tripId);
|
||||
if (!bag) return null;
|
||||
if (bag.user_id === userId) return bagId;
|
||||
const members = this.db.all<{ user_id: number }>('SELECT user_id FROM packing_bag_members WHERE bag_id = ?', bagId);
|
||||
if (bag.user_id == null && members.length === 0) return bagId; // shared bag, nobody's in particular
|
||||
return members.some(m => m.user_id === userId) ? bagId : null;
|
||||
const memberIds = await this.bagsRepo.listMemberIdsForBag(bagId);
|
||||
if (bag.user_id == null && memberIds.length === 0) return bagId; // shared bag, nobody's in particular
|
||||
return memberIds.some(uid => uid === userId) ? bagId : null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -444,7 +415,7 @@ export class PackingService {
|
||||
* every traveller was the whole complaint in #207.
|
||||
*/
|
||||
async cloneItem(tripId: string | number, id: string | number, userId: number) {
|
||||
const item = await this.getItemInTrip(tripId, id, userId);
|
||||
const item = await this.itemsRepo.findVisibleInTrip(id, tripId, userId);
|
||||
if (!item) return null;
|
||||
return await this.createItem(tripId, {
|
||||
name: item.name,
|
||||
@@ -461,20 +432,19 @@ export class PackingService {
|
||||
// delete broadcast at the owner when the item was private (#858).
|
||||
// Scoped to what the actor may see: trip membership alone used to be enough
|
||||
// to delete another member's restricted item.
|
||||
const item = await this.getItemInTrip(tripId, id, actingUserId);
|
||||
const item = await this.itemsRepo.findVisibleInTrip(id, tripId, actingUserId);
|
||||
if (!item) return null;
|
||||
|
||||
this.db.run('DELETE FROM packing_items WHERE id = ?', id);
|
||||
await this.itemsRepo.delete(id);
|
||||
return item;
|
||||
}
|
||||
|
||||
// ── Bulk Import ────────────────────────────────────────────────────────────
|
||||
|
||||
async bulkImport(tripId: string | number, items: ImportItem[], ownerId?: number) {
|
||||
const maxOrder = this.db.get<{ max: number | null }>('SELECT MAX(sort_order) as max FROM packing_items WHERE trip_id = ?', tripId)!;
|
||||
let sortOrder = (maxOrder.max !== null ? maxOrder.max : -1) + 1;
|
||||
const maxOrder = await this.itemsRepo.maxSortOrder(tripId);
|
||||
let sortOrder = (maxOrder !== null ? maxOrder : -1) + 1;
|
||||
|
||||
const stmt = this.db.prepare('INSERT INTO packing_items (trip_id, name, checked, category, weight_grams, bag_id, sort_order, quantity, is_private, owner_id, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)');
|
||||
const created: any[] = [];
|
||||
|
||||
await this.uow.transactional(async () => {
|
||||
@@ -484,22 +454,32 @@ export class PackingService {
|
||||
const weight = item.weight_grams ? Number.parseInt(String(item.weight_grams)) || null : null;
|
||||
|
||||
// Resolve bag by name if provided
|
||||
let bagId = null;
|
||||
let bagId: number | null = null;
|
||||
if (item.bag?.trim()) {
|
||||
const bagName = item.bag.trim();
|
||||
const existing = this.db.get<{ id: number }>('SELECT id FROM packing_bags WHERE trip_id = ? AND name = ?', tripId, bagName);
|
||||
const existing = await this.bagsRepo.byNameInTrip(tripId, bagName);
|
||||
if (existing) {
|
||||
bagId = existing.id;
|
||||
} else {
|
||||
const bagCount = this.db.get<{ c: number }>('SELECT COUNT(*) as c FROM packing_bags WHERE trip_id = ?', tripId)!.c;
|
||||
const newBag = this.db.run('INSERT INTO packing_bags (trip_id, name, color) VALUES (?, ?, ?)', tripId, bagName, BAG_COLORS[bagCount % BAG_COLORS.length]);
|
||||
bagId = newBag.lastInsertRowid;
|
||||
const bagCount = await this.bagsRepo.countForTrip(tripId);
|
||||
bagId = await this.bagsRepo.insertMinimal(tripId, bagName, BAG_COLORS[bagCount % BAG_COLORS.length]);
|
||||
}
|
||||
}
|
||||
|
||||
const qty = Math.max(1, Math.min(999, Number(item.quantity) || 1));
|
||||
const result = stmt.run(tripId, item.name.trim(), checked, item.category?.trim() || 'Other', weight, bagId, sortOrder++, qty, item.is_private ? 1 : 0, ownerId ?? null);
|
||||
created.push(this.db.get('SELECT * FROM packing_items WHERE id = ?', result.lastInsertRowid));
|
||||
const newId = await this.itemsRepo.insertItem({
|
||||
trip_id: tripId,
|
||||
name: item.name.trim(),
|
||||
checked,
|
||||
category: item.category?.trim() || 'Other',
|
||||
sort_order: sortOrder++,
|
||||
quantity: qty,
|
||||
weight_grams: weight,
|
||||
bag_id: bagId,
|
||||
is_private: item.is_private ? 1 : 0,
|
||||
owner_id: ownerId ?? null,
|
||||
});
|
||||
created.push(await this.itemsRepo.findById(newId));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -521,18 +501,15 @@ export class PackingService {
|
||||
* So the sum is computed here, over EVERY row, and only integers cross the
|
||||
* wire. A member learns that a bag is heavier than the items they can see —
|
||||
* never a name, category, quantity or owner. That is a deliberate, bounded
|
||||
* disclosure and the point of the issue.
|
||||
* disclosure and the point of the issue. `PackingItemsRepository.bagWeightTotals`
|
||||
* is a genuinely separate, unfiltered aggregate — never built on the
|
||||
* visibility-filtered reads (§17 surprise 10).
|
||||
*
|
||||
* Keyed by bag id, with the unassigned pile under `null` — the same shape the
|
||||
* "no bag" row on every packing surface needs.
|
||||
*/
|
||||
private async bagWeightTotals(tripId: string | number): Promise<Map<number | null, number>> {
|
||||
const rows = this.db.all<{ bag_id: number | null; total: number | null }>(`
|
||||
SELECT bag_id, SUM(COALESCE(weight_grams, 0) * COALESCE(quantity, 1)) AS total
|
||||
FROM packing_items
|
||||
WHERE trip_id = ?
|
||||
GROUP BY bag_id
|
||||
`, tripId);
|
||||
const rows = await this.itemsRepo.bagWeightTotals(tripId);
|
||||
return new Map(rows.map(r => [r.bag_id, r.total ?? 0]));
|
||||
}
|
||||
|
||||
@@ -559,15 +536,9 @@ export class PackingService {
|
||||
}
|
||||
|
||||
private async decorateBags(tripId: string | number, totals: Map<number | null, number>) {
|
||||
const bags = this.db.all<any>('SELECT * FROM packing_bags WHERE trip_id = ? ORDER BY sort_order, id', tripId);
|
||||
const members = this.db.all<{ bag_id: number; user_id: number; username: string; avatar: string | null }>(`
|
||||
SELECT bm.bag_id, bm.user_id, COALESCE(u.display_name, u.username) AS username, u.avatar
|
||||
FROM packing_bag_members bm
|
||||
JOIN users u ON bm.user_id = u.id
|
||||
JOIN packing_bags b ON bm.bag_id = b.id
|
||||
WHERE b.trip_id = ?
|
||||
`, tripId);
|
||||
const membersByBag = new Map<number, typeof members>();
|
||||
const bags = await this.bagsRepo.listForTrip(tripId);
|
||||
const members = await this.bagsRepo.listMembersForTrip(tripId);
|
||||
const membersByBag = new Map<number, PackingBagMemberForTripRow[]>();
|
||||
for (const m of members) {
|
||||
if (!membersByBag.has(m.bag_id)) membersByBag.set(m.bag_id, []);
|
||||
membersByBag.get(m.bag_id)!.push(m);
|
||||
@@ -590,29 +561,29 @@ export class PackingService {
|
||||
}
|
||||
|
||||
async setBagMembers(tripId: string | number, bagId: string | number, userIds: number[]) {
|
||||
const bag = this.db.get('SELECT * FROM packing_bags WHERE id = ? AND trip_id = ?', bagId, tripId);
|
||||
const bag = await this.bagsRepo.findInTrip(bagId, tripId);
|
||||
if (!bag) return null;
|
||||
await this.uow.transactional(async () => {
|
||||
this.db.run('DELETE FROM packing_bag_members WHERE bag_id = ?', bagId);
|
||||
const ins = this.db.prepare('INSERT OR IGNORE INTO packing_bag_members (bag_id, user_id) VALUES (?, ?)');
|
||||
await this.bagsRepo.deleteMembersForBag(Number(bagId));
|
||||
// Only real trip members may be bag members — never write an arbitrary account id.
|
||||
const roster = await this.tripRosterIds(tripId);
|
||||
for (const uid of userIds) if (roster.has(uid)) ins.run(bagId, uid);
|
||||
const members = userIds.filter(uid => roster.has(uid));
|
||||
await this.bagsRepo.insertMembersIgnore(Number(bagId), members);
|
||||
});
|
||||
const rows = this.db.all<{ user_id: number; username: string; avatar: string | null }>(`
|
||||
SELECT bm.user_id, COALESCE(u.display_name, u.username) AS username, u.avatar
|
||||
FROM packing_bag_members bm JOIN users u ON bm.user_id = u.id
|
||||
WHERE bm.bag_id = ?
|
||||
`, bagId);
|
||||
const rows = await this.bagsRepo.listMembersWithUserForBag(Number(bagId));
|
||||
return rows.map(m => ({ ...m, avatar: avatarUrl(m) }));
|
||||
}
|
||||
|
||||
async createBag(tripId: string | number, data: { name: string; color?: string; weight_limit_grams?: number | null }) {
|
||||
const maxOrder = this.db.get<{ max: number | null }>('SELECT MAX(sort_order) as max FROM packing_bags WHERE trip_id = ?', tripId)!;
|
||||
const result = this.db.run('INSERT INTO packing_bags (trip_id, name, color, sort_order, weight_limit_grams) VALUES (?, ?, ?, ?, ?)',
|
||||
tripId, data.name.trim(), data.color || '#6366f1', (maxOrder.max ?? -1) + 1, data.weight_limit_grams ?? null
|
||||
);
|
||||
return this.db.get('SELECT * FROM packing_bags WHERE id = ?', result.lastInsertRowid);
|
||||
const maxOrder = await this.bagsRepo.maxSortOrder(tripId);
|
||||
const newId = await this.bagsRepo.insertBag({
|
||||
trip_id: tripId,
|
||||
name: data.name.trim(),
|
||||
color: data.color || '#6366f1',
|
||||
sort_order: (maxOrder ?? -1) + 1,
|
||||
weight_limit_grams: data.weight_limit_grams ?? null,
|
||||
});
|
||||
return await this.bagsRepo.findById(newId);
|
||||
}
|
||||
|
||||
async updateBag(
|
||||
@@ -621,35 +592,27 @@ export class PackingService {
|
||||
data: { name?: string; color?: string; weight_limit_grams?: number | null; user_id?: number | null },
|
||||
bodyKeys?: string[]
|
||||
) {
|
||||
const bag = this.db.get('SELECT * FROM packing_bags WHERE id = ? AND trip_id = ?', bagId, tripId);
|
||||
const bag = await this.bagsRepo.findInTrip(bagId, tripId);
|
||||
if (!bag) return null;
|
||||
|
||||
// A bag may only be assigned to a real trip member; an off-roster id becomes unassigned.
|
||||
const assignUser = data.user_id != null && (await this.tripRosterIds(tripId)).has(data.user_id) ? data.user_id : null;
|
||||
// weight_limit_grams follows the bodyKeys presence protocol like user_id:
|
||||
// an omitted key leaves the limit unchanged, an explicit null clears it.
|
||||
this.db.run(`UPDATE packing_bags SET
|
||||
name = COALESCE(?, name),
|
||||
color = COALESCE(?, color),
|
||||
weight_limit_grams = CASE WHEN ? THEN ? ELSE weight_limit_grams END,
|
||||
user_id = CASE WHEN ? THEN ? ELSE user_id END
|
||||
WHERE id = ?`,
|
||||
data.name?.trim() || null,
|
||||
data.color || null,
|
||||
bodyKeys?.includes('weight_limit_grams') ? 1 : 0,
|
||||
data.weight_limit_grams ?? null,
|
||||
bodyKeys?.includes('user_id') ? 1 : 0,
|
||||
assignUser,
|
||||
bagId
|
||||
);
|
||||
return this.db.get('SELECT b.*, COALESCE(u.display_name, u.username) as assigned_username FROM packing_bags b LEFT JOIN users u ON b.user_id = u.id WHERE b.id = ?', bagId);
|
||||
await this.bagsRepo.update(bagId, {
|
||||
name: [!!data.name?.trim(), data.name?.trim() || null],
|
||||
color: [!!data.color, data.color || null],
|
||||
weight_limit_grams: [!!bodyKeys?.includes('weight_limit_grams'), data.weight_limit_grams ?? null],
|
||||
user_id: [!!bodyKeys?.includes('user_id'), assignUser],
|
||||
});
|
||||
return await this.bagsRepo.findWithAssignee(bagId);
|
||||
}
|
||||
|
||||
async deleteBag(tripId: string | number, bagId: string | number): Promise<boolean> {
|
||||
const bag = this.db.get('SELECT * FROM packing_bags WHERE id = ? AND trip_id = ?', bagId, tripId);
|
||||
const bag = await this.bagsRepo.findInTrip(bagId, tripId);
|
||||
if (!bag) return false;
|
||||
|
||||
this.db.run('DELETE FROM packing_bags WHERE id = ?', bagId);
|
||||
await this.bagsRepo.delete(bagId);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -661,12 +624,7 @@ export class PackingService {
|
||||
* under /api/admin/packing-templates.
|
||||
*/
|
||||
async listTemplates() {
|
||||
return this.db.all<{ id: number; name: string; item_count: number }>(`
|
||||
SELECT pt.id, pt.name,
|
||||
(SELECT COUNT(*) FROM packing_template_items ti JOIN packing_template_categories tc ON ti.category_id = tc.id WHERE tc.template_id = pt.id) as item_count
|
||||
FROM packing_templates pt
|
||||
ORDER BY pt.created_at DESC
|
||||
`);
|
||||
return await this.templatesRepo.listWithItemCount();
|
||||
}
|
||||
|
||||
// ── Apply Template ─────────────────────────────────────────────────────────
|
||||
@@ -677,28 +635,22 @@ export class PackingService {
|
||||
visibility: 'common' | 'personal' = 'common',
|
||||
ownerId?: number,
|
||||
) {
|
||||
const templateItems = this.db.all<{ name: string; category: string }>(`
|
||||
SELECT ti.name, tc.name as category
|
||||
FROM packing_template_items ti
|
||||
JOIN packing_template_categories tc ON ti.category_id = tc.id
|
||||
WHERE tc.template_id = ?
|
||||
ORDER BY tc.sort_order, ti.sort_order
|
||||
`, templateId);
|
||||
const templateItems = await this.templateItemsRepo.listForApply(templateId);
|
||||
|
||||
if (templateItems.length === 0) return null;
|
||||
|
||||
const maxOrder = this.db.get<{ max: number | null }>('SELECT MAX(sort_order) as max FROM packing_items WHERE trip_id = ?', tripId)!;
|
||||
let sortOrder = (maxOrder.max !== null ? maxOrder.max : -1) + 1;
|
||||
const maxOrder = await this.itemsRepo.maxSortOrder(tripId);
|
||||
let sortOrder = (maxOrder !== null ? maxOrder : -1) + 1;
|
||||
const isPrivate = ownerId != null ? this.visibilityToPrivate(visibility) : 0;
|
||||
const owner = isPrivate ? ownerId! : null;
|
||||
|
||||
const insert = this.db.prepare('INSERT INTO packing_items (trip_id, name, checked, category, sort_order, is_private, owner_id, updated_at) VALUES (?, ?, 0, ?, ?, ?, ?, CURRENT_TIMESTAMP)');
|
||||
const added: any[] = [];
|
||||
await this.uow.transactional(async () => {
|
||||
for (const ti of templateItems) {
|
||||
const result = insert.run(tripId, ti.name, ti.category, sortOrder++, isPrivate, owner);
|
||||
const item = this.db.get('SELECT * FROM packing_items WHERE id = ?', result.lastInsertRowid);
|
||||
added.push(item);
|
||||
const newId = await this.itemsRepo.insertFromTemplate({
|
||||
trip_id: tripId, name: ti.name, category: ti.category, sort_order: sortOrder++, is_private: isPrivate, owner_id: owner,
|
||||
});
|
||||
added.push(await this.itemsRepo.findById(newId));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -711,30 +663,26 @@ export class PackingService {
|
||||
// A template is a durable, shareable artifact, so it may only capture what is
|
||||
// the actor's to publish: the Common list plus their own items. It used to
|
||||
// take every row in the trip, restricted ones included.
|
||||
const items = this.db.all<{ name: string; category: string }>(
|
||||
'SELECT name, category FROM packing_items WHERE trip_id = ? AND (is_private = 0 OR owner_id = ?) ORDER BY sort_order ASC',
|
||||
tripId, userId,
|
||||
);
|
||||
const items = await this.itemsRepo.listExportable(tripId, userId);
|
||||
|
||||
if (items.length === 0) return null;
|
||||
|
||||
const categories = [...new Set(items.map(i => i.category || 'Other'))];
|
||||
|
||||
const templateId = await this.uow.transactional(async () => {
|
||||
const result = this.db.run('INSERT INTO packing_templates (name, created_by) VALUES (?, ?)', templateName, userId);
|
||||
const id = result.lastInsertRowid;
|
||||
const id = await this.templatesRepo.insertTemplate(templateName, userId);
|
||||
|
||||
const catIdMap = new Map<string, number | bigint>();
|
||||
const catIdMap = new Map<string, number>();
|
||||
for (let i = 0; i < categories.length; i++) {
|
||||
const catResult = this.db.run('INSERT INTO packing_template_categories (template_id, name, sort_order) VALUES (?, ?, ?)', id, categories[i], i);
|
||||
catIdMap.set(categories[i], catResult.lastInsertRowid);
|
||||
const catId = await this.templateCategoriesRepo.insertCategory(id, categories[i], i);
|
||||
catIdMap.set(categories[i], catId);
|
||||
}
|
||||
|
||||
const itemsByCategory = new Map<string, number>();
|
||||
for (const item of items) {
|
||||
const catId = catIdMap.get(item.category || 'Other')!;
|
||||
const order = itemsByCategory.get(item.category || 'Other') || 0;
|
||||
this.db.run('INSERT INTO packing_template_items (category_id, name, sort_order) VALUES (?, ?, ?)', catId, item.name, order);
|
||||
await this.templateItemsRepo.insertTemplateItem(catId, item.name, order);
|
||||
itemsByCategory.set(item.category || 'Other', order + 1);
|
||||
}
|
||||
return id;
|
||||
@@ -746,12 +694,7 @@ export class PackingService {
|
||||
// ── Category Assignees ─────────────────────────────────────────────────────
|
||||
|
||||
async getCategoryAssignees(tripId: string | number) {
|
||||
const rows = this.db.all<{ category_name: string; user_id: number; username: string; avatar: string | null }>(`
|
||||
SELECT pca.category_name, pca.user_id, COALESCE(u.display_name, u.username) AS username, u.avatar
|
||||
FROM packing_category_assignees pca
|
||||
JOIN users u ON pca.user_id = u.id
|
||||
WHERE pca.trip_id = ?
|
||||
`, tripId);
|
||||
const rows = await this.categoryAssigneesRepo.listForTrip(tripId);
|
||||
|
||||
// Group by category
|
||||
const assignees: Record<string, { user_id: number; username: string; avatar: string | null }[]> = {};
|
||||
@@ -765,33 +708,27 @@ export class PackingService {
|
||||
|
||||
async updateCategoryAssignees(tripId: string | number, categoryName: string, userIds: number[] | undefined) {
|
||||
await this.uow.transactional(async () => {
|
||||
this.db.run('DELETE FROM packing_category_assignees WHERE trip_id = ? AND category_name = ?', tripId, categoryName);
|
||||
await this.categoryAssigneesRepo.deleteForCategory(tripId, categoryName);
|
||||
|
||||
if (Array.isArray(userIds) && userIds.length > 0) {
|
||||
const insert = this.db.prepare('INSERT OR IGNORE INTO packing_category_assignees (trip_id, category_name, user_id) VALUES (?, ?, ?)');
|
||||
// Same rule as setBagMembers: only people on this trip may be assigned.
|
||||
const roster = await this.tripRosterIds(tripId);
|
||||
for (const uid of userIds) if (roster.has(uid)) insert.run(tripId, categoryName, uid);
|
||||
const scoped = userIds.filter(uid => roster.has(uid));
|
||||
await this.categoryAssigneesRepo.insertIgnore(tripId, categoryName, scoped);
|
||||
}
|
||||
});
|
||||
|
||||
const updated = this.db.all<{ user_id: number; username: string; avatar: string | null }>(`
|
||||
SELECT pca.user_id, COALESCE(u.display_name, u.username) AS username, u.avatar
|
||||
FROM packing_category_assignees pca
|
||||
JOIN users u ON pca.user_id = u.id
|
||||
WHERE pca.trip_id = ? AND pca.category_name = ?
|
||||
`, tripId, categoryName);
|
||||
const updated = await this.categoryAssigneesRepo.listForCategory(tripId, categoryName);
|
||||
return updated.map(m => ({ ...m, avatar: avatarUrl(m) }));
|
||||
}
|
||||
|
||||
// ── Reorder ────────────────────────────────────────────────────────────────
|
||||
|
||||
async reorderItems(tripId: string | number, orderedIds: number[]): Promise<void> {
|
||||
const update = this.db.prepare('UPDATE packing_items SET sort_order = ? WHERE id = ? AND trip_id = ?');
|
||||
await this.uow.transactional(async () => {
|
||||
orderedIds.forEach((id, index) => {
|
||||
update.run(index, id, tripId);
|
||||
});
|
||||
for (const [index, id] of orderedIds.entries()) {
|
||||
await this.itemsRepo.setSortOrder(id, tripId, index);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -811,56 +748,36 @@ export class PackingService {
|
||||
// path param entirely; since the 2026-08 quirk fix they scope through
|
||||
// packing_template_categories like the sibling category routes do.
|
||||
|
||||
/** An item looked up through its category, so :templateId actually scopes it. */
|
||||
private async scopedTemplateItem(templateId: string, itemId: string) {
|
||||
return this.db.get(`
|
||||
SELECT ti.* FROM packing_template_items ti
|
||||
JOIN packing_template_categories tc ON ti.category_id = tc.id
|
||||
WHERE ti.id = ? AND tc.template_id = ?
|
||||
`, itemId, templateId);
|
||||
}
|
||||
|
||||
async listPackingTemplates() {
|
||||
return this.db.all(`
|
||||
SELECT pt.*, u.username as created_by_name,
|
||||
(SELECT COUNT(*) FROM packing_template_items ti JOIN packing_template_categories tc ON ti.category_id = tc.id WHERE tc.template_id = pt.id) as item_count,
|
||||
(SELECT COUNT(*) FROM packing_template_categories WHERE template_id = pt.id) as category_count
|
||||
FROM packing_templates pt
|
||||
JOIN users u ON pt.created_by = u.id
|
||||
ORDER BY pt.created_at DESC
|
||||
`);
|
||||
return await this.templatesRepo.listAdmin();
|
||||
}
|
||||
|
||||
async getPackingTemplate(id: string) {
|
||||
const template = this.db.get('SELECT * FROM packing_templates WHERE id = ?', id);
|
||||
const template = await this.templatesRepo.findById(id);
|
||||
if (!template) return { error: 'Template not found', status: 404 };
|
||||
const categories = this.db.all('SELECT * FROM packing_template_categories WHERE template_id = ? ORDER BY sort_order, id', id);
|
||||
const items = this.db.all(`
|
||||
SELECT ti.* FROM packing_template_items ti
|
||||
JOIN packing_template_categories tc ON ti.category_id = tc.id
|
||||
WHERE tc.template_id = ? ORDER BY ti.sort_order, ti.id
|
||||
`, id);
|
||||
const categories = await this.templateCategoriesRepo.listForTemplate(id);
|
||||
const items = await this.templateItemsRepo.listForTemplate(id);
|
||||
return { template, categories, items };
|
||||
}
|
||||
|
||||
async createPackingTemplate(name: string, createdBy: number) {
|
||||
if (!name?.trim()) return { error: 'Name is required', status: 400 };
|
||||
const result = this.db.run('INSERT INTO packing_templates (name, created_by) VALUES (?, ?)', name.trim(), createdBy);
|
||||
const template = this.db.get('SELECT * FROM packing_templates WHERE id = ?', result.lastInsertRowid);
|
||||
const newId = await this.templatesRepo.insertTemplate(name.trim(), createdBy);
|
||||
const template = await this.templatesRepo.findById(newId);
|
||||
return { template };
|
||||
}
|
||||
|
||||
async updatePackingTemplate(id: string, data: { name?: string }) {
|
||||
const template = this.db.get('SELECT * FROM packing_templates WHERE id = ?', id);
|
||||
const template = await this.templatesRepo.findById(id);
|
||||
if (!template) return { error: 'Template not found', status: 404 };
|
||||
if (data.name?.trim()) this.db.run('UPDATE packing_templates SET name = ? WHERE id = ?', data.name.trim(), id);
|
||||
return { template: this.db.get('SELECT * FROM packing_templates WHERE id = ?', id) };
|
||||
if (data.name?.trim()) await this.templatesRepo.updateName(id, data.name.trim());
|
||||
return { template: await this.templatesRepo.findById(id) };
|
||||
}
|
||||
|
||||
async deletePackingTemplate(id: string) {
|
||||
const template = this.db.get<{ name?: string }>('SELECT * FROM packing_templates WHERE id = ?', id);
|
||||
const template = await this.templatesRepo.findById(id);
|
||||
if (!template) return { error: 'Template not found', status: 404 };
|
||||
this.db.run('DELETE FROM packing_templates WHERE id = ?', id);
|
||||
await this.templatesRepo.delete(id);
|
||||
return { name: template.name };
|
||||
}
|
||||
|
||||
@@ -868,25 +785,25 @@ export class PackingService {
|
||||
|
||||
async createTemplateCategory(templateId: string, name: string) {
|
||||
if (!name?.trim()) return { error: 'Category name is required', status: 400 };
|
||||
const template = this.db.get('SELECT * FROM packing_templates WHERE id = ?', templateId);
|
||||
const template = await this.templatesRepo.findById(templateId);
|
||||
if (!template) return { error: 'Template not found', status: 404 };
|
||||
const maxOrder = this.db.get<{ max: number | null }>('SELECT MAX(sort_order) as max FROM packing_template_categories WHERE template_id = ?', templateId)!;
|
||||
const result = this.db.run('INSERT INTO packing_template_categories (template_id, name, sort_order) VALUES (?, ?, ?)', templateId, name.trim(), (maxOrder.max ?? -1) + 1);
|
||||
return { category: this.db.get('SELECT * FROM packing_template_categories WHERE id = ?', result.lastInsertRowid) };
|
||||
const maxOrder = await this.templateCategoriesRepo.maxSortOrder(templateId);
|
||||
const newId = await this.templateCategoriesRepo.insertCategory(templateId, name.trim(), (maxOrder ?? -1) + 1);
|
||||
return { category: await this.templateCategoriesRepo.findById(newId) };
|
||||
}
|
||||
|
||||
async updateTemplateCategory(templateId: string, catId: string, data: { name?: string }) {
|
||||
const cat = this.db.get('SELECT * FROM packing_template_categories WHERE id = ? AND template_id = ?', catId, templateId);
|
||||
const cat = await this.templateCategoriesRepo.findInTemplate(catId, templateId);
|
||||
if (!cat) return { error: 'Category not found', status: 404 };
|
||||
if (data.name?.trim())
|
||||
this.db.run('UPDATE packing_template_categories SET name = ? WHERE id = ?', data.name.trim(), catId);
|
||||
return { category: this.db.get('SELECT * FROM packing_template_categories WHERE id = ?', catId) };
|
||||
await this.templateCategoriesRepo.updateName(catId, data.name.trim());
|
||||
return { category: await this.templateCategoriesRepo.findById(catId) };
|
||||
}
|
||||
|
||||
async deleteTemplateCategory(templateId: string, catId: string) {
|
||||
const cat = this.db.get('SELECT * FROM packing_template_categories WHERE id = ? AND template_id = ?', catId, templateId);
|
||||
const cat = await this.templateCategoriesRepo.findInTemplate(catId, templateId);
|
||||
if (!cat) return { error: 'Category not found', status: 404 };
|
||||
this.db.run('DELETE FROM packing_template_categories WHERE id = ?', catId);
|
||||
await this.templateCategoriesRepo.delete(catId);
|
||||
return {};
|
||||
}
|
||||
|
||||
@@ -894,25 +811,25 @@ export class PackingService {
|
||||
|
||||
async createTemplateItem(templateId: string, catId: string, name: string) {
|
||||
if (!name?.trim()) return { error: 'Item name is required', status: 400 };
|
||||
const cat = this.db.get('SELECT * FROM packing_template_categories WHERE id = ? AND template_id = ?', catId, templateId);
|
||||
const cat = await this.templateCategoriesRepo.findInTemplate(catId, templateId);
|
||||
if (!cat) return { error: 'Category not found', status: 404 };
|
||||
const maxOrder = this.db.get<{ max: number | null }>('SELECT MAX(sort_order) as max FROM packing_template_items WHERE category_id = ?', catId)!;
|
||||
const result = this.db.run('INSERT INTO packing_template_items (category_id, name, sort_order) VALUES (?, ?, ?)', catId, name.trim(), (maxOrder.max ?? -1) + 1);
|
||||
return { item: this.db.get('SELECT * FROM packing_template_items WHERE id = ?', result.lastInsertRowid) };
|
||||
const maxOrder = await this.templateItemsRepo.maxSortOrder(catId);
|
||||
const newId = await this.templateItemsRepo.insertTemplateItem(catId, name.trim(), (maxOrder ?? -1) + 1);
|
||||
return { item: await this.templateItemsRepo.findById(newId) };
|
||||
}
|
||||
|
||||
async updateTemplateItem(templateId: string, itemId: string, data: { name?: string }) {
|
||||
const item = await this.scopedTemplateItem(templateId, itemId);
|
||||
const item = await this.templateItemsRepo.findScoped(itemId, templateId);
|
||||
if (!item) return { error: 'Item not found', status: 404 };
|
||||
if (data.name?.trim())
|
||||
this.db.run('UPDATE packing_template_items SET name = ? WHERE id = ?', data.name.trim(), itemId);
|
||||
return { item: this.db.get('SELECT * FROM packing_template_items WHERE id = ?', itemId) };
|
||||
await this.templateItemsRepo.updateName(itemId, data.name.trim());
|
||||
return { item: await this.templateItemsRepo.findById(itemId) };
|
||||
}
|
||||
|
||||
async deleteTemplateItem(templateId: string, itemId: string) {
|
||||
const item = await this.scopedTemplateItem(templateId, itemId);
|
||||
const item = await this.templateItemsRepo.findScoped(itemId, templateId);
|
||||
if (!item) return { error: 'Item not found', status: 404 };
|
||||
this.db.run('DELETE FROM packing_template_items WHERE id = ?', itemId);
|
||||
await this.templateItemsRepo.delete(itemId);
|
||||
return {};
|
||||
}
|
||||
|
||||
@@ -923,13 +840,13 @@ export class PackingService {
|
||||
// nothing the module graph does not already give — NotificationsModule
|
||||
// reaches nothing in this direction — and it hid the edge while handing the
|
||||
// send a second NotificationsService built outside the container.
|
||||
const tripInfo = this.db.get<{ title: string }>('SELECT title FROM trips WHERE id = ?', tripId);
|
||||
const tripTitle = await this.tripsRepo.getTitle(tripId);
|
||||
this.notifications.send({
|
||||
event: 'packing_tagged',
|
||||
actorId: actor.id,
|
||||
scope: 'trip',
|
||||
targetId: Number(tripId),
|
||||
params: { trip: tripInfo?.title || 'Untitled', actor: actor.email, category, tripId: String(tripId) },
|
||||
params: { trip: tripTitle || 'Untitled', actor: actor.email, category, tripId: String(tripId) },
|
||||
}).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,6 +20,9 @@ import { BudgetItems } from '../../db/entities/BudgetItems.entity';
|
||||
import { BudgetItemMembers } from '../../db/entities/BudgetItemMembers.entity';
|
||||
import { BudgetItemPayers } from '../../db/entities/BudgetItemPayers.entity';
|
||||
import { BudgetCategoryOrder } from '../../db/entities/BudgetCategoryOrder.entity';
|
||||
import { PackingBags } from '../../db/entities/PackingBags.entity';
|
||||
import { PackingItems } from '../../db/entities/PackingItems.entity';
|
||||
import { TodoItems } from '../../db/entities/TodoItems.entity';
|
||||
import { MAX_TRIP_DAYS, tripSpanDays, type ActiveTrip, type TrekWsPayload, type TrekWsTripEventName } from '@trek/shared';
|
||||
import { RealtimeService } from '../realtime/realtime.service';
|
||||
import { PermissionsService } from '../permissions/permissions.service';
|
||||
@@ -271,6 +274,24 @@ export class TripsService {
|
||||
return this.em.getRepository(BudgetCategoryOrder);
|
||||
}
|
||||
|
||||
// Plan 3e Task 3 (packing) — TP66-69 only (the packing-family rows of
|
||||
// `copy`'s 14 survivors). Same `this.em.getRepository(...)` pattern as
|
||||
// every getter above.
|
||||
private get packingBagsRepo() {
|
||||
return this.em.getRepository(PackingBags);
|
||||
}
|
||||
|
||||
private get packingItemsRepo() {
|
||||
return this.em.getRepository(PackingItems);
|
||||
}
|
||||
|
||||
// Plan 3e Task 4 (todo) — TP72-73 only (the todo-family rows of `copy`'s
|
||||
// 14 survivors). Same `this.em.getRepository(...)` pattern as every
|
||||
// getter above.
|
||||
private get todoItemsRepo() {
|
||||
return this.em.getRepository(TodoItems);
|
||||
}
|
||||
|
||||
async canAccessTrip(tripId: string | number, userId: number) {
|
||||
const access = await this.em.getRepository(Trips).findAccessible(tripId, userId);
|
||||
return access as { user_id: number } | null | undefined;
|
||||
@@ -880,15 +901,15 @@ export class TripsService {
|
||||
if (newItemId) await this.budgetItemPayersRepo.insertIgnore({ budget_item_id: newItemId, user_id: bp.user_id, amount: bp.amount ?? 0 });
|
||||
}
|
||||
|
||||
const oldBags = this.db.prepare('SELECT * FROM packing_bags WHERE trip_id = ?').all(sourceTripId) as any[]; // TP66 — Plan 3e
|
||||
const bagMap = new Map<number, number | bigint>();
|
||||
const insertBag = this.db.prepare(`
|
||||
INSERT INTO packing_bags (trip_id, name, color, weight_limit_grams, sort_order)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
`);
|
||||
// TP66 — Plan 3e Task 3, converted.
|
||||
const oldBags = await this.packingBagsRepo.listAllForTrip(sourceTripId);
|
||||
const bagMap = new Map<number, number>();
|
||||
for (const bag of oldBags) {
|
||||
const r = insertBag.run(newTripId, bag.name, bag.color, bag.weight_limit_grams, bag.sort_order); // TP67 — Plan 3e
|
||||
bagMap.set(bag.id, r.lastInsertRowid);
|
||||
// TP67 — Plan 3e Task 3, converted (`insertBag`, PK42's own column set).
|
||||
const newBagId = await this.packingBagsRepo.insertBag({
|
||||
trip_id: newTripId, name: bag.name, color: bag.color, sort_order: bag.sort_order, weight_limit_grams: bag.weight_limit_grams,
|
||||
});
|
||||
bagMap.set(bag.id, newBagId);
|
||||
}
|
||||
|
||||
// Only what the copier may carry over: the Common list plus their own items.
|
||||
@@ -897,18 +918,16 @@ export class TripsService {
|
||||
// Shared item reappeared in the copy as a Common item visible to everyone.
|
||||
// A restricted item stays restricted, and it stays owned by the copier —
|
||||
// recipient rows are not carried over, and the copy has its own roster.
|
||||
const oldPacking = this.db.prepare(
|
||||
'SELECT * FROM packing_items WHERE trip_id = ? AND (is_private = 0 OR owner_id = ?)'
|
||||
).all(sourceTripId, newOwnerId) as any[]; // TP68 — Plan 3e (security-sensitive: the privacy filter)
|
||||
const insertPacking = this.db.prepare(`
|
||||
INSERT INTO packing_items (trip_id, name, checked, category, sort_order, weight_grams, bag_id, is_private, owner_id, updated_at)
|
||||
VALUES (?, ?, 0, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
|
||||
`);
|
||||
// TP68 — Plan 3e Task 3, converted (security-sensitive: the privacy filter).
|
||||
const oldPacking = await this.packingItemsRepo.listOwnListForCopy(sourceTripId, newOwnerId);
|
||||
for (const p of oldPacking) {
|
||||
const isPrivate = p.is_private ? 1 : 0;
|
||||
insertPacking.run(newTripId, p.name, p.category, p.sort_order, p.weight_grams,
|
||||
p.bag_id ? (bagMap.get(p.bag_id) ?? null) : null,
|
||||
isPrivate, isPrivate ? newOwnerId : null); // TP69 — Plan 3e
|
||||
// TP69 — Plan 3e Task 3, converted.
|
||||
await this.packingItemsRepo.insertCopy({
|
||||
trip_id: newTripId, name: p.name, category: p.category, sort_order: p.sort_order, weight_grams: p.weight_grams,
|
||||
bag_id: p.bag_id ? (bagMap.get(p.bag_id) ?? null) : null,
|
||||
is_private: isPrivate, owner_id: isPrivate ? newOwnerId : null,
|
||||
});
|
||||
}
|
||||
|
||||
const oldNotes = await this.dayNotesRepo.listByTrip(sourceTripId); // TP70
|
||||
@@ -921,13 +940,14 @@ export class TripsService {
|
||||
}
|
||||
}
|
||||
|
||||
const oldTodos = this.db.prepare('SELECT * FROM todo_items WHERE trip_id = ?').all(sourceTripId) as any[]; // TP72 — Plan 3e
|
||||
const insertTodo = this.db.prepare(`
|
||||
INSERT INTO todo_items (trip_id, name, checked, category, sort_order, due_date, description, assigned_user_id, priority)
|
||||
VALUES (?, ?, 0, ?, ?, ?, ?, NULL, ?)
|
||||
`);
|
||||
// TP72 — Plan 3e Task 4, converted.
|
||||
const oldTodos = await this.todoItemsRepo.listAllForTrip(sourceTripId);
|
||||
for (const t of oldTodos) {
|
||||
insertTodo.run(newTripId, t.name, t.category, t.sort_order, t.due_date, t.description, t.priority); // TP73 — Plan 3e
|
||||
// TP73 — Plan 3e Task 4, converted (`assigned_user_id` deliberately not carried over).
|
||||
await this.todoItemsRepo.insertCopy({
|
||||
trip_id: newTripId, name: t.name, category: t.category, sort_order: t.sort_order,
|
||||
due_date: t.due_date, description: t.description, priority: t.priority,
|
||||
});
|
||||
}
|
||||
|
||||
// TP74 — Plan 3e Task 2, converted.
|
||||
|
||||
@@ -139,6 +139,12 @@ import {
|
||||
createTestCollabMessageReactionsRepo, createTestCollabNotesRepo, createTestCollabPollsRepo,
|
||||
createTestCollabPollVotesRepo, createTestCollabLinksRepo, createTestCollabMessagesRepo,
|
||||
} from './collab-repos';
|
||||
import {
|
||||
createTestPackingItemsRepo, createTestPackingItemContributorsRepo, createTestPackingBagsRepo,
|
||||
createTestPackingCategoryAssigneesRepo, createTestPackingTemplatesRepo, createTestPackingTemplateCategoriesRepo,
|
||||
createTestPackingTemplateItemsRepo,
|
||||
} from './packing-repos';
|
||||
import { createTestTodoItemsRepo, createTestTodoCategoryAssigneesRepo } from './todo-repos';
|
||||
import { AppSettings } from '../../src/db/entities/AppSettings.entity';
|
||||
import { AuditLog } from '../../src/db/entities/AuditLog.entity';
|
||||
import { Users } from '../../src/db/entities/Users.entity';
|
||||
@@ -207,8 +213,13 @@ export async function createMcpTestRegistry(): Promise<McpRegistry> {
|
||||
await createTestReservationEndpointsRepo(dbService.connection),
|
||||
await createTestDayAccommodationsRepo(dbService.connection),
|
||||
);
|
||||
const todoService = new TodoService(dbService, permissionsService, realtimeService, await createTestUnitOfWork(dbService.connection));
|
||||
const packingService = new PackingService(dbService, permissionsService, realtimeService, notificationsStub(), await createTestUnitOfWork(dbService.connection));
|
||||
const todoService = new TodoService(dbService, permissionsService, realtimeService, await createTestUnitOfWork(dbService.connection), await createTestTodoItemsRepo(dbService.connection), await createTestTodoCategoryAssigneesRepo(dbService.connection));
|
||||
const packingService = new PackingService(
|
||||
dbService, permissionsService, realtimeService, notificationsStub(), await createTestUnitOfWork(dbService.connection),
|
||||
await createTestPackingItemsRepo(dbService.connection), await createTestPackingItemContributorsRepo(dbService.connection), await createTestPackingBagsRepo(dbService.connection),
|
||||
await createTestPackingCategoryAssigneesRepo(dbService.connection), await createTestPackingTemplatesRepo(dbService.connection), await createTestPackingTemplateCategoriesRepo(dbService.connection),
|
||||
await createTestPackingTemplateItemsRepo(dbService.connection), await createTestTripsRepo(dbService.connection),
|
||||
);
|
||||
const collabService = new CollabService(
|
||||
dbService, permissionsService, realtimeService, notificationsStub(), generalStorage, new RateLimitService(), await createTestUnitOfWork(dbService.connection),
|
||||
await createTestCollabMessageReactionsRepo(dbService.connection), await createTestCollabNotesRepo(dbService.connection), await createTestCollabPollsRepo(dbService.connection),
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import type Database from 'better-sqlite3';
|
||||
import { sharedTestOrm } from './test-uow';
|
||||
import { PackingItems } from '../../src/db/entities/PackingItems.entity';
|
||||
import type { PackingItemsRepository } from '../../src/db/repositories/PackingItems.repository';
|
||||
import { PackingItemContributors } from '../../src/db/entities/PackingItemContributors.entity';
|
||||
import type { PackingItemContributorsRepository } from '../../src/db/repositories/PackingItemContributors.repository';
|
||||
import { PackingBags } from '../../src/db/entities/PackingBags.entity';
|
||||
import type { PackingBagsRepository } from '../../src/db/repositories/PackingBags.repository';
|
||||
import { PackingCategoryAssignees } from '../../src/db/entities/PackingCategoryAssignees.entity';
|
||||
import type { PackingCategoryAssigneesRepository } from '../../src/db/repositories/PackingCategoryAssignees.repository';
|
||||
import { PackingTemplates } from '../../src/db/entities/PackingTemplates.entity';
|
||||
import type { PackingTemplatesRepository } from '../../src/db/repositories/PackingTemplates.repository';
|
||||
import { PackingTemplateCategories } from '../../src/db/entities/PackingTemplateCategories.entity';
|
||||
import type { PackingTemplateCategoriesRepository } from '../../src/db/repositories/PackingTemplateCategories.repository';
|
||||
import { PackingTemplateItems } from '../../src/db/entities/PackingTemplateItems.entity';
|
||||
import type { PackingTemplateItemsRepository } from '../../src/db/repositories/PackingTemplateItems.repository';
|
||||
|
||||
/**
|
||||
* Plan 3e Task 3 (`PackingService`) test-only repository factories, bound to
|
||||
* a suite's own better-sqlite3 handle via the SAME memoised `sharedTestOrm`
|
||||
* `test-uow.ts` exports — required so a repository built here and a
|
||||
* `UnitOfWork` built from `createTestUnitOfWork` (that file) resolve the
|
||||
* IDENTICAL context-resolving `EntityManager` (the `files-repos.ts`/
|
||||
* `collab-repos.ts` precedent this file otherwise copies verbatim: a
|
||||
* repository from a SECOND, independent ORM instance would write outside the
|
||||
* open transaction).
|
||||
*
|
||||
* A NEW file rather than an addition to `test-uow.ts`, same reasoning
|
||||
* `files-repos.ts`/`collab-repos.ts`'s own docstrings give for themselves.
|
||||
* `TripsRepository` already has its own `createTestTripsRepo` in
|
||||
* `test-uow.ts` (Plan 3c Task 0b) and is reused directly from there — only
|
||||
* the seven packing-owned repositories are new here.
|
||||
*/
|
||||
export function createTestPackingItemsRepo(db: Database.Database): Promise<PackingItemsRepository> {
|
||||
return sharedTestOrm(db).then((t) => t.repo(PackingItems));
|
||||
}
|
||||
|
||||
export function createTestPackingItemContributorsRepo(db: Database.Database): Promise<PackingItemContributorsRepository> {
|
||||
return sharedTestOrm(db).then((t) => t.repo(PackingItemContributors));
|
||||
}
|
||||
|
||||
export function createTestPackingBagsRepo(db: Database.Database): Promise<PackingBagsRepository> {
|
||||
return sharedTestOrm(db).then((t) => t.repo(PackingBags));
|
||||
}
|
||||
|
||||
export function createTestPackingCategoryAssigneesRepo(db: Database.Database): Promise<PackingCategoryAssigneesRepository> {
|
||||
return sharedTestOrm(db).then((t) => t.repo(PackingCategoryAssignees));
|
||||
}
|
||||
|
||||
export function createTestPackingTemplatesRepo(db: Database.Database): Promise<PackingTemplatesRepository> {
|
||||
return sharedTestOrm(db).then((t) => t.repo(PackingTemplates));
|
||||
}
|
||||
|
||||
export function createTestPackingTemplateCategoriesRepo(db: Database.Database): Promise<PackingTemplateCategoriesRepository> {
|
||||
return sharedTestOrm(db).then((t) => t.repo(PackingTemplateCategories));
|
||||
}
|
||||
|
||||
export function createTestPackingTemplateItemsRepo(db: Database.Database): Promise<PackingTemplateItemsRepository> {
|
||||
return sharedTestOrm(db).then((t) => t.repo(PackingTemplateItems));
|
||||
}
|
||||
@@ -95,6 +95,12 @@ import {
|
||||
createTestCollabMessageReactionsRepo, createTestCollabNotesRepo, createTestCollabPollsRepo,
|
||||
createTestCollabPollVotesRepo, createTestCollabLinksRepo, createTestCollabMessagesRepo,
|
||||
} from './collab-repos';
|
||||
import {
|
||||
createTestPackingItemsRepo, createTestPackingItemContributorsRepo, createTestPackingBagsRepo,
|
||||
createTestPackingCategoryAssigneesRepo, createTestPackingTemplatesRepo, createTestPackingTemplateCategoriesRepo,
|
||||
createTestPackingTemplateItemsRepo,
|
||||
} from './packing-repos';
|
||||
import { createTestTodoItemsRepo, createTestTodoCategoryAssigneesRepo } from './todo-repos';
|
||||
|
||||
/**
|
||||
* Hand-wired counterpart of the PluginsModule DI graph for no-Nest tests
|
||||
@@ -116,8 +122,13 @@ export async function createPluginRpcHostFactory(dbs: DatabaseService): Promise<
|
||||
const budget = new BudgetService(dbs, permissions, exchangeRates, realtime, await createTestUnitOfWork(dbs.connection), ...(await budgetRepoArgs(dbs.connection)));
|
||||
const addons = await createTestAddonsService(dbs.connection, dbs);
|
||||
const queryHelpers = new QueryHelpersService(await createTestTagsRepo(dbs.connection), await createTestPlaceRatingsRepo(dbs.connection), await createTestAssignmentParticipantsRepo(dbs.connection));
|
||||
const todos = new TodoService(dbs, permissions, realtime, await createTestUnitOfWork(dbs.connection));
|
||||
const packing = new PackingService(dbs, permissions, realtime, notificationsStub(), await createTestUnitOfWork(dbs.connection));
|
||||
const todos = new TodoService(dbs, permissions, realtime, await createTestUnitOfWork(dbs.connection), await createTestTodoItemsRepo(dbs.connection), await createTestTodoCategoryAssigneesRepo(dbs.connection));
|
||||
const packing = new PackingService(
|
||||
dbs, permissions, realtime, notificationsStub(), await createTestUnitOfWork(dbs.connection),
|
||||
await createTestPackingItemsRepo(dbs.connection), await createTestPackingItemContributorsRepo(dbs.connection), await createTestPackingBagsRepo(dbs.connection),
|
||||
await createTestPackingCategoryAssigneesRepo(dbs.connection), await createTestPackingTemplatesRepo(dbs.connection), await createTestPackingTemplateCategoriesRepo(dbs.connection),
|
||||
await createTestPackingTemplateItemsRepo(dbs.connection), await createTestTripsRepo(dbs.connection),
|
||||
);
|
||||
// Plan 3e Task 1 (files): FilesService now also takes uow + the repositories
|
||||
// its R2 transactions and R12 cross-object trip-scoping guard need.
|
||||
const files = new FilesService(
|
||||
|
||||
@@ -89,6 +89,15 @@ import { AddonsService } from '../../../src/nest/addons/addons.service';
|
||||
import { notificationsStub } from '../../helpers/notifications';
|
||||
import { createTestUnitOfWork, createTestAppSettingsRepo, createTestTripsRepo, createTestTripMembersRepo, sharedTestOrm, createTestPlacesRepo } from '../../helpers/test-uow';
|
||||
import { budgetRepoArgs } from '../../helpers/budget-repos';
|
||||
import {
|
||||
createTestPackingItemsRepo,
|
||||
createTestPackingItemContributorsRepo,
|
||||
createTestPackingBagsRepo,
|
||||
createTestPackingCategoryAssigneesRepo,
|
||||
createTestPackingTemplatesRepo,
|
||||
createTestPackingTemplateCategoriesRepo,
|
||||
createTestPackingTemplateItemsRepo,
|
||||
} from '../../helpers/packing-repos';
|
||||
import type { EntityManager } from '@mikro-orm/core';
|
||||
|
||||
// The trip-summary prompt moved to the DI-discovered TripsMcp — its cases below
|
||||
@@ -142,7 +151,21 @@ beforeAll(async () => {
|
||||
addonsStub,
|
||||
promptGuards,
|
||||
);
|
||||
promptPackingService = new PackingService(promptDbs(), new PermissionsService(await createTestAppSettingsRepo(promptDbs().connection), await createTestUnitOfWork(promptDbs().connection)), new RealtimeService(), notificationsStub(), await createTestUnitOfWork(promptDbs().connection));
|
||||
promptPackingService = new PackingService(
|
||||
promptDbs(),
|
||||
new PermissionsService(await createTestAppSettingsRepo(promptDbs().connection), await createTestUnitOfWork(promptDbs().connection)),
|
||||
new RealtimeService(),
|
||||
notificationsStub(),
|
||||
await createTestUnitOfWork(promptDbs().connection),
|
||||
await createTestPackingItemsRepo(promptDbs().connection),
|
||||
await createTestPackingItemContributorsRepo(promptDbs().connection),
|
||||
await createTestPackingBagsRepo(promptDbs().connection),
|
||||
await createTestPackingCategoryAssigneesRepo(promptDbs().connection),
|
||||
await createTestPackingTemplatesRepo(promptDbs().connection),
|
||||
await createTestPackingTemplateCategoriesRepo(promptDbs().connection),
|
||||
await createTestPackingTemplateItemsRepo(promptDbs().connection),
|
||||
await createTestTripsRepo(promptDbs().connection),
|
||||
);
|
||||
packingMcp = new PackingMcp(promptPackingService, authStub, addonsStub, promptGuards);
|
||||
budgetMcp = new BudgetMcp(
|
||||
new BudgetService(promptDbs(), new PermissionsService(await createTestAppSettingsRepo(promptDbs().connection), await createTestUnitOfWork(promptDbs().connection)), new ExchangeRatesService(), new RealtimeService(), await createTestUnitOfWork(promptDbs().connection), ...(await budgetRepoArgs(promptDbs().connection))),
|
||||
|
||||
@@ -67,7 +67,16 @@ import { PackingService, isInvalidBagRef } from '../../../src/nest/packing/packi
|
||||
const bridgeListItems = (tripId: string | number, viewerId?: number) => svc.listItems(tripId, viewerId);
|
||||
import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
|
||||
import { notificationsStub } from '../../helpers/notifications';
|
||||
import { createTestUnitOfWork, createTestDatabaseService } from '../../helpers/test-uow';
|
||||
import { createTestUnitOfWork, createTestDatabaseService, createTestTripsRepo } from '../../helpers/test-uow';
|
||||
import {
|
||||
createTestPackingItemsRepo,
|
||||
createTestPackingItemContributorsRepo,
|
||||
createTestPackingBagsRepo,
|
||||
createTestPackingCategoryAssigneesRepo,
|
||||
createTestPackingTemplatesRepo,
|
||||
createTestPackingTemplateCategoriesRepo,
|
||||
createTestPackingTemplateItemsRepo,
|
||||
} from '../../helpers/packing-repos';
|
||||
|
||||
let svc: PackingService;
|
||||
|
||||
@@ -76,7 +85,21 @@ let svc: PackingService;
|
||||
beforeAll(async () => {
|
||||
createTables(testDb);
|
||||
runMigrations(testDb);
|
||||
svc = new PackingService(await createTestDatabaseService(testDb), permissionsStub, new RealtimeService(), notificationsStub(send), await createTestUnitOfWork(testDb));
|
||||
svc = new PackingService(
|
||||
await createTestDatabaseService(testDb),
|
||||
permissionsStub,
|
||||
new RealtimeService(),
|
||||
notificationsStub(send),
|
||||
await createTestUnitOfWork(testDb),
|
||||
await createTestPackingItemsRepo(testDb),
|
||||
await createTestPackingItemContributorsRepo(testDb),
|
||||
await createTestPackingBagsRepo(testDb),
|
||||
await createTestPackingCategoryAssigneesRepo(testDb),
|
||||
await createTestPackingTemplatesRepo(testDb),
|
||||
await createTestPackingTemplateCategoriesRepo(testDb),
|
||||
await createTestPackingTemplateItemsRepo(testDb),
|
||||
await createTestTripsRepo(testDb),
|
||||
);
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
|
||||
@@ -98,6 +98,12 @@ import {
|
||||
createTestCollabMessageReactionsRepo, createTestCollabNotesRepo, createTestCollabPollsRepo,
|
||||
createTestCollabPollVotesRepo, createTestCollabLinksRepo, createTestCollabMessagesRepo,
|
||||
} from '../../helpers/collab-repos';
|
||||
import {
|
||||
createTestPackingItemsRepo, createTestPackingItemContributorsRepo, createTestPackingBagsRepo,
|
||||
createTestPackingCategoryAssigneesRepo, createTestPackingTemplatesRepo, createTestPackingTemplateCategoriesRepo,
|
||||
createTestPackingTemplateItemsRepo,
|
||||
} from '../../helpers/packing-repos';
|
||||
import { createTestTodoItemsRepo, createTestTodoCategoryAssigneesRepo } from '../../helpers/todo-repos';
|
||||
|
||||
// Real sibling services over the same in-memory DB — the aggregation runs the
|
||||
// actual SQL of every domain it fans out to, so a shape change downstream shows
|
||||
@@ -162,7 +168,12 @@ beforeAll(async () => {
|
||||
const buildReadModel = async (tripsRepo: TripsRepository, roster: TripMembersService = membersSvc) =>
|
||||
new TripReadModelService(
|
||||
tripsRepo, roster, daysSvc, accommodationsSvc, budgetSvc,
|
||||
new PackingService(dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), notificationsStub(), await createTestUnitOfWork(dbs().connection)),
|
||||
new PackingService(
|
||||
dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), notificationsStub(), await createTestUnitOfWork(dbs().connection),
|
||||
await createTestPackingItemsRepo(dbs().connection), await createTestPackingItemContributorsRepo(dbs().connection), await createTestPackingBagsRepo(dbs().connection),
|
||||
await createTestPackingCategoryAssigneesRepo(dbs().connection), await createTestPackingTemplatesRepo(dbs().connection), await createTestPackingTemplateCategoriesRepo(dbs().connection),
|
||||
await createTestPackingTemplateItemsRepo(dbs().connection), await createTestTripsRepo(dbs().connection),
|
||||
),
|
||||
new ReservationsService(dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), budgetSvc, new RealtimeService(), notificationsStub(), new ReservationsReadService(await createTestReservationsRepo(dbs().connection), await createTestReservationEndpointsRepo(dbs().connection), await createTestReservationTravelersRepo(dbs().connection)), await accommodationsOver(dbs()), await createTestUnitOfWork(dbs().connection), await createTestReservationsRepo(dbs().connection), await createTestReservationEndpointsRepo(dbs().connection), await createTestReservationTravelersRepo(dbs().connection), await createTestReservationDayPositionsRepo(dbs().connection), await createTestDayAccommodationsRepo(dbs().connection), await createTestDaysRepo(dbs().connection), await createTestPlacesRepo(dbs().connection), await createTestDayAssignmentsRepo(dbs().connection), await createTestTripMembersRepo(dbs().connection), await createTestUsersRepo(dbs().connection), await createTestTripsRepo(dbs().connection), await createTestBudgetItemsRepo(dbs().connection)),
|
||||
new CollabService(
|
||||
dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), notificationsStub(), makeStorageFixture('').storage, new RateLimitService(), await createTestUnitOfWork(dbs().connection),
|
||||
@@ -171,7 +182,10 @@ const buildReadModel = async (tripsRepo: TripsRepository, roster: TripMembersSer
|
||||
await createTestTripsRepo(dbs().connection),
|
||||
),
|
||||
placesSvc,
|
||||
new TodoService(dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), await createTestUnitOfWork(dbs().connection)),
|
||||
new TodoService(
|
||||
dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), await createTestUnitOfWork(dbs().connection),
|
||||
await createTestTodoItemsRepo(dbs().connection), await createTestTodoCategoryAssigneesRepo(dbs().connection),
|
||||
),
|
||||
new FilesService(
|
||||
dbs(),
|
||||
new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)),
|
||||
|
||||
@@ -107,6 +107,12 @@ import {
|
||||
createTestCollabMessageReactionsRepo, createTestCollabNotesRepo, createTestCollabPollsRepo,
|
||||
createTestCollabPollVotesRepo, createTestCollabLinksRepo, createTestCollabMessagesRepo,
|
||||
} from '../../helpers/collab-repos';
|
||||
import {
|
||||
createTestPackingItemsRepo, createTestPackingItemContributorsRepo, createTestPackingBagsRepo,
|
||||
createTestPackingCategoryAssigneesRepo, createTestPackingTemplatesRepo, createTestPackingTemplateCategoriesRepo,
|
||||
createTestPackingTemplateItemsRepo,
|
||||
} from '../../helpers/packing-repos';
|
||||
import { createTestTodoItemsRepo, createTestTodoCategoryAssigneesRepo } from '../../helpers/todo-repos';
|
||||
|
||||
// Real sibling services over the same in-memory DB — updateTrip's date-shift
|
||||
// resyncs and the summary/bundle aggregation run their actual SQL.
|
||||
@@ -209,7 +215,12 @@ beforeAll(async () => {
|
||||
membersSvc = new TripMembersService(dbs(), budgetSvc, new UserCleanupService(dbs(), budgetSvc, await createTestUnitOfWork(dbs().connection), await createTestUsersRepo(dbs().connection), await createTestBudgetItemsRepo(dbs().connection)), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), notificationsStub(), await createTestUnitOfWork(dbs().connection), await createTestTripsRepo(dbs().connection), await createTestTripMembersRepo(dbs().connection), await createTestUsersRepo(dbs().connection));
|
||||
readModelSvc = new TripReadModelService(
|
||||
await createTestTripsRepo(dbs().connection), membersSvc, daysSvc, accommodationsSvc, budgetSvc,
|
||||
new PackingService(dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), notificationsStub(), await createTestUnitOfWork(dbs().connection)),
|
||||
new PackingService(
|
||||
dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), notificationsStub(), await createTestUnitOfWork(dbs().connection),
|
||||
await createTestPackingItemsRepo(dbs().connection), await createTestPackingItemContributorsRepo(dbs().connection), await createTestPackingBagsRepo(dbs().connection),
|
||||
await createTestPackingCategoryAssigneesRepo(dbs().connection), await createTestPackingTemplatesRepo(dbs().connection), await createTestPackingTemplateCategoriesRepo(dbs().connection),
|
||||
await createTestPackingTemplateItemsRepo(dbs().connection), await createTestTripsRepo(dbs().connection),
|
||||
),
|
||||
new ReservationsService(dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), budgetSvc, new RealtimeService(), notificationsStub(), new ReservationsReadService(await createTestReservationsRepo(dbs().connection), await createTestReservationEndpointsRepo(dbs().connection), await createTestReservationTravelersRepo(dbs().connection)), accommodationsSvc, await createTestUnitOfWork(dbs().connection), await createTestReservationsRepo(dbs().connection), await createTestReservationEndpointsRepo(dbs().connection), await createTestReservationTravelersRepo(dbs().connection), await createTestReservationDayPositionsRepo(dbs().connection), await createTestDayAccommodationsRepo(dbs().connection), await createTestDaysRepo(dbs().connection), await createTestPlacesRepo(dbs().connection), await createTestDayAssignmentsRepo(dbs().connection), await createTestTripMembersRepo(dbs().connection), await createTestUsersRepo(dbs().connection), await createTestTripsRepo(dbs().connection), await createTestBudgetItemsRepo(dbs().connection)),
|
||||
new CollabService(
|
||||
dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), notificationsStub(), coversFx.storage, new RateLimitService(), await createTestUnitOfWork(dbs().connection),
|
||||
@@ -218,7 +229,10 @@ beforeAll(async () => {
|
||||
await createTestTripsRepo(dbs().connection),
|
||||
),
|
||||
placesSvc,
|
||||
new TodoService(dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), await createTestUnitOfWork(dbs().connection)),
|
||||
new TodoService(
|
||||
dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), await createTestUnitOfWork(dbs().connection),
|
||||
await createTestTodoItemsRepo(dbs().connection), await createTestTodoCategoryAssigneesRepo(dbs().connection),
|
||||
),
|
||||
new FilesService(
|
||||
dbs(),
|
||||
new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)),
|
||||
|
||||
@@ -32,7 +32,10 @@ type Item = { id: number; name?: string; is_private?: number; owner_id?: number
|
||||
*/
|
||||
function build(opts: { canEdit?: boolean; before?: Item | undefined; updated?: Item | null } = {}) {
|
||||
const realtime = { broadcast: vi.fn() } as unknown as RealtimeService & { broadcast: ReturnType<typeof vi.fn> };
|
||||
const packing = new PackingService({} as never, {} as never, realtime, notificationsStub(), {} as never);
|
||||
const packing = new PackingService(
|
||||
{} as never, {} as never, realtime, notificationsStub(), {} as never,
|
||||
{} as never, {} as never, {} as never, {} as never, {} as never, {} as never, {} as never, {} as never,
|
||||
);
|
||||
const data = {
|
||||
listItems: vi.fn(() => [{ id: 70, name: 'Socks' }]),
|
||||
// The bodies here are the boring fixture; the item writes are typed as Item so a
|
||||
|
||||
@@ -72,6 +72,15 @@ import {
|
||||
sharedTestOrm,
|
||||
} from '../../helpers/test-uow';
|
||||
import { createTestBudgetItemsRepo } from '../../helpers/files-repos';
|
||||
import {
|
||||
createTestPackingItemsRepo,
|
||||
createTestPackingItemContributorsRepo,
|
||||
createTestPackingBagsRepo,
|
||||
createTestPackingCategoryAssigneesRepo,
|
||||
createTestPackingTemplatesRepo,
|
||||
createTestPackingTemplateCategoriesRepo,
|
||||
createTestPackingTemplateItemsRepo,
|
||||
} from '../../helpers/packing-repos';
|
||||
|
||||
const dbs = new DatabaseService(testDb);
|
||||
const realtime = new RealtimeService();
|
||||
@@ -101,7 +110,21 @@ beforeAll(async () => {
|
||||
vi.spyOn(dbs, 'isOwner').mockImplementation((...a) => real.isOwner(...a));
|
||||
vi.spyOn(dbs, 'rosterUserIds').mockImplementation((...a) => real.rosterUserIds(...a));
|
||||
vi.spyOn(dbs, 'getPlaceWithTags').mockImplementation((...a) => real.getPlaceWithTags(...a));
|
||||
packing = new PackingService(dbs, new PermissionsService(await createTestAppSettingsRepo(dbs.connection), await createTestUnitOfWork(dbs.connection)), realtime, notificationsStub(), await createTestUnitOfWork(dbs.connection));
|
||||
packing = new PackingService(
|
||||
dbs,
|
||||
new PermissionsService(await createTestAppSettingsRepo(dbs.connection), await createTestUnitOfWork(dbs.connection)),
|
||||
realtime,
|
||||
notificationsStub(),
|
||||
await createTestUnitOfWork(dbs.connection),
|
||||
await createTestPackingItemsRepo(dbs.connection),
|
||||
await createTestPackingItemContributorsRepo(dbs.connection),
|
||||
await createTestPackingBagsRepo(dbs.connection),
|
||||
await createTestPackingCategoryAssigneesRepo(dbs.connection),
|
||||
await createTestPackingTemplatesRepo(dbs.connection),
|
||||
await createTestPackingTemplateCategoriesRepo(dbs.connection),
|
||||
await createTestPackingTemplateItemsRepo(dbs.connection),
|
||||
await createTestTripsRepo(dbs.connection),
|
||||
);
|
||||
places = new PlacesService(
|
||||
dbs,
|
||||
new PermissionsService(await createTestAppSettingsRepo(dbs.connection), await createTestUnitOfWork(dbs.connection)),
|
||||
|
||||
Reference in New Issue
Block a user