style: format server and shared with prettier

A mechanical prettier --write over server/src, server/tests, server/scripts
and shared/src with the workspaces' .prettierrc; nothing but layout and
import order changes, and every file keeps the same set of imports. shared
is formatted throughout and its format baseline is empty. The server
baseline keeps the 35 files that Prettier would grow past their lint:size
limit (they need a split first, which is not a formatting change), and the
generated entity files stay as their generator writes them.
This commit is contained in:
Maurice
2026-10-10 21:23:37 +02:00
parent f4e518b2df
commit 724c88c201
1978 changed files with 78448 additions and 39347 deletions
+26 -9
View File
@@ -1,6 +1,25 @@
import {
isKnownPlatform,
isPostgres,
isSqlite,
PG_ISO_DATE_PREFIX,
PG_TIMESTAMP_FORMAT,
PG_UTC_NOW,
pgTimestampText,
unsupported,
} from './platform';
import type { Platform } from '@mikro-orm/core';
import { sql, type Expression, type ExpressionBuilder, type ExpressionWrapper, type RawBuilder, type ReferenceExpression, type SqlBool, type StringReference } from 'kysely';
import { isKnownPlatform, isPostgres, isSqlite, PG_ISO_DATE_PREFIX, PG_TIMESTAMP_FORMAT, PG_UTC_NOW, pgTimestampText, unsupported } from './platform';
import {
sql,
type Expression,
type ExpressionBuilder,
type ExpressionWrapper,
type RawBuilder,
type ReferenceExpression,
type SqlBool,
type StringReference,
} from 'kysely';
/**
* The Kysely-expression half of the dialect layer: the twins of the MikroORM
@@ -83,9 +102,8 @@ export function substringKysely<DB, TB extends keyof DB>(
throw new Error(`sql-functions: substringKysely needs a non-negative integer length, got ${length}`);
}
if (isKnownPlatform(platform)) {
const args: ReferenceExpression<DB, TB>[] = length === undefined
? [ref, eb.val(start)]
: [ref, eb.val(start), eb.val(length)];
const args: ReferenceExpression<DB, TB>[] =
length === undefined ? [ref, eb.val(start)] : [ref, eb.val(start), eb.val(length)];
return eb.fn<string>('substr', args);
}
return unsupported(platform);
@@ -93,9 +111,7 @@ export function substringKysely<DB, TB extends keyof DB>(
/** A part of a `concatKysely()` expression — a column reference, a bound value, or a nested Kysely `Expression<string>` (composes freely, unlike `concat()`'s MikroORM `RawQueryFragment` form). */
export type KyselyConcatPart<DB, TB extends keyof DB> =
| { column: StringReference<DB, TB> }
| { value: string }
| { expression: Expression<string> };
{ column: StringReference<DB, TB> } | { value: string } | { expression: Expression<string> };
/**
* The Kysely-expression twin of {@link concat}: `<part> || <part> || …`,
@@ -116,7 +132,8 @@ export function concatKysely<DB, TB extends keyof DB>(
throw new Error(`sql-functions: concatKysely needs at least two parts, got ${parts.length}`);
}
if (!isKnownPlatform(platform)) return unsupported(platform);
const value = (text: string): Expression<string> => (isPostgres(platform) ? eb.cast<string>(eb.val(text), 'text') : eb.val(text));
const value = (text: string): Expression<string> =>
isPostgres(platform) ? eb.cast<string>(eb.val(text), 'text') : eb.val(text);
const operand = (part: KyselyConcatPart<DB, TB>): Expression<string> =>
'column' in part ? eb.ref(part.column).$castTo<string>() : 'value' in part ? value(part.value) : part.expression;
let acc: Expression<string> = operand(parts[0]!);
+44 -9
View File
@@ -1,5 +1,14 @@
import {
isKnownPlatform,
isPostgres,
isSqlite,
PG_ISO_DATE_PREFIX,
PG_UTC_NOW,
pgDateText,
pgTimestampText,
unsupported,
} from './platform';
import { raw, type Platform, type RawQueryFragment } from '@mikro-orm/core';
import { isKnownPlatform, isPostgres, isSqlite, PG_ISO_DATE_PREFIX, PG_UTC_NOW, pgDateText, pgTimestampText, unsupported } from './platform';
/**
* The only place a repository may spell a database function.
@@ -232,7 +241,11 @@ export function coalesce(platform: Platform, ref: string, fallbackRef: string):
* anywhere a plain `RawQueryFragment` is expected, a strict widening with no
* behaviour change (the function body is untouched).
*/
export function coalesceParam(platform: Platform, ref: string, value: string | number | null): RawQueryFragment & symbol {
export function coalesceParam(
platform: Platform,
ref: string,
value: string | number | null,
): RawQueryFragment & symbol {
if (isKnownPlatform(platform)) return raw(`COALESCE(${column(ref)}, ?)`, [value]);
return unsupported(platform);
}
@@ -256,7 +269,11 @@ export function coalesceParam(platform: Platform, ref: string, value: string | n
* columns exactly as they were before, since `coalesceParam`'s `COALESCE(col,
* ?)` always preferred the non-null existing value).
*/
export function coalesceOverride(platform: Platform, value: string | number | null, ref: string): RawQueryFragment & symbol {
export function coalesceOverride(
platform: Platform,
value: string | number | null,
ref: string,
): RawQueryFragment & symbol {
if (isKnownPlatform(platform)) return raw(`COALESCE(?, ${column(ref)})`, [value]);
return unsupported(platform);
}
@@ -334,8 +351,15 @@ export function maxOf(platform: Platform, ref: string, aliasName: string): RawQu
* time regardless of this function's own escaping; callers must guard a
* non-finite `value` before calling.)
*/
export function caseWhenEquals(platform: Platform, ref: string, value: number, whenTrue: string, whenFalse: string): RawQueryFragment {
if (isKnownPlatform(platform)) return raw(`CASE WHEN ${column(ref)} = ? THEN ? ELSE ? END`, [value, whenTrue, whenFalse]);
export function caseWhenEquals(
platform: Platform,
ref: string,
value: number,
whenTrue: string,
whenFalse: string,
): RawQueryFragment {
if (isKnownPlatform(platform))
return raw(`CASE WHEN ${column(ref)} = ? THEN ? ELSE ? END`, [value, whenTrue, whenFalse]);
return unsupported(platform);
}
@@ -537,7 +561,9 @@ export function castInteger(platform: Platform, ref: string): RawQueryFragment &
export function dayDistance(platform: Platform, ref: string, isoDate: string): RawQueryFragment & symbol {
if (isSqlite(platform)) return raw(`ABS(JULIANDAY(${column(ref)}) - JULIANDAY(?))`, [isoDate]);
if (isPostgres(platform)) {
return raw(`ABS(EXTRACT(EPOCH FROM (CAST(${column(ref)} AS timestamp) - CAST(? AS timestamp))) / 86400)`, [isoDate]);
return raw(`ABS(EXTRACT(EPOCH FROM (CAST(${column(ref)} AS timestamp) - CAST(? AS timestamp))) / 86400)`, [
isoDate,
]);
}
return unsupported(platform);
}
@@ -779,9 +805,19 @@ export function foundAgainState(platform: Platform, stateRef: string, fileIdRef:
* the fragment has two value slots and `raw()` binds positionally. SQLite's
* null-safe `IS` is `IS NOT DISTINCT FROM` on Postgres.
*/
export function coalesceOverrideWhileSame(platform: Platform, value: number | null, ref: string, keyRef: string, keyValue: string): RawQueryFragment {
export function coalesceOverrideWhileSame(
platform: Platform,
value: number | null,
ref: string,
keyRef: string,
keyValue: string,
): RawQueryFragment {
if (isSqlite(platform)) {
return raw(`CASE WHEN ${column(keyRef)} IS ? THEN COALESCE(?, ${column(ref)}) ELSE COALESCE(?, 0) END`, [keyValue, value, value]);
return raw(`CASE WHEN ${column(keyRef)} IS ? THEN COALESCE(?, ${column(ref)}) ELSE COALESCE(?, 0) END`, [
keyValue,
value,
value,
]);
}
if (isPostgres(platform)) {
const sql = `CASE WHEN ${column(keyRef)} IS NOT DISTINCT FROM ? THEN COALESCE(?, ${column(ref)}) ELSE COALESCE(?, 0) END`;
@@ -790,7 +826,6 @@ export function coalesceOverrideWhileSame(platform: Platform, value: number | nu
return unsupported(platform);
}
// ---------------------------------------------------------------------------
// Tours (#2586): `DayAssignmentsRepository`'s assignment projection carries a
// place's route geometry only when the place is a Tour, so the day list never
-1
View File
@@ -1,4 +1,3 @@
/**
* The five document providers and the fields their connection form asks for.
*
+3 -2
View File
@@ -1,7 +1,8 @@
import type Database from 'better-sqlite3';
import { readEnv } from '../app-config';
import { synchronousName } from '../app-config/parsers';
import type Database from 'better-sqlite3';
export interface ActiveDurability {
journalMode: string;
synchronous: string;
@@ -24,7 +25,7 @@ export interface ActiveDurability {
*/
export function applyDurabilityPragmas(db: Database.Database): ActiveDurability {
const { journalMode, synchronous, durabilityWarnings } = readEnv().db;
durabilityWarnings.forEach(warning => console.warn(`[DB] ${warning}`));
durabilityWarnings.forEach((warning) => console.warn(`[DB] ${warning}`));
db.exec(`PRAGMA journal_mode = ${journalMode}`);
db.exec(`PRAGMA synchronous = ${synchronous}`);
+9 -2
View File
@@ -31,8 +31,15 @@ export async function ensureEmailCaseIndex(connection: Connection): Promise<void
}
await connection.transactional(async (trx) => {
await connection.execute('CREATE UNIQUE INDEX IF NOT EXISTS idx_users_email_lower ON users (lower(email))', [], 'run', trx);
await connection.execute(
'CREATE UNIQUE INDEX IF NOT EXISTS idx_users_email_lower ON users (lower(email))',
[],
'run',
trx,
);
await connection.execute('DELETE FROM app_settings WHERE key = ?', [PENDING_KEY], 'run', trx);
});
console.log('[DB] Every account has its own email address now; created the case-insensitive unique index on users.email');
console.log(
'[DB] Every account has its own email address now; created the case-insensitive unique index on users.email',
);
}
+4 -2
View File
@@ -1,8 +1,8 @@
import { knownMigrationNames, unknownMigrations } from './known-migrations';
import type { Connection, MigrationInfo } from '@mikro-orm/core';
import type { Migrator } from '@mikro-orm/migrations';
import fs from 'node:fs';
import { knownMigrationNames, unknownMigrations } from './known-migrations';
/**
* Upgrading an install the retired hand-written runner migrated.
@@ -175,7 +175,9 @@ async function withoutToursSteps(connection: Connection, version: number): Promi
`SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'tour_types'`,
);
if (table.length === 0) return version;
console.log(`[DB] schema_version ${version} was written by the pre-ORM Tours branch; baselining to upstream step ${toursLine}`);
console.log(
`[DB] schema_version ${version} was written by the pre-ORM Tours branch; baselining to upstream step ${toursLine}`,
);
return toursLine;
}
@@ -36,6 +36,8 @@ export class Migration20200101040200_trek_photo_cache_meta_cache_key_not_null ex
this.addSql(`ALTER TABLE trek_photo_cache_meta_new RENAME TO trek_photo_cache_meta`);
this.addSql(`CREATE INDEX IF NOT EXISTS idx_trek_photo_cache_meta_fetched_at ON trek_photo_cache_meta (fetched_at)`);
this.addSql(
`CREATE INDEX IF NOT EXISTS idx_trek_photo_cache_meta_fetched_at ON trek_photo_cache_meta (fetched_at)`,
);
}
}
@@ -1,6 +1,6 @@
import { reseatBookedNights } from '../reseat-booked-nights';
import { Migration } from '@mikro-orm/migrations';
import type { SqliteConnection } from '@mikro-orm/sqlite';
import { reseatBookedNights } from '../reseat-booked-nights';
/**
* Legacy migration step 242 (`db/migrations.ts`).
@@ -1,5 +1,5 @@
import { Migration } from '@mikro-orm/migrations';
import { addColumnIfMissing, tableExists } from '../migration-utils';
import { Migration } from '@mikro-orm/migrations';
/**
* Tours: a facet on `places` for hikes and other single-day routes.
@@ -54,10 +54,16 @@ export class Migration20200101042200_an_index_on_every_foreign_key extends Migra
this.addSql('CREATE INDEX IF NOT EXISTS idx_collab_message_reactions_user_id ON collab_message_reactions(user_id)');
this.addSql('CREATE INDEX IF NOT EXISTS idx_invite_tokens_trip_id ON invite_tokens(trip_id)');
this.addSql('CREATE INDEX IF NOT EXISTS idx_invite_tokens_created_by ON invite_tokens(created_by)');
this.addSql('CREATE INDEX IF NOT EXISTS idx_packing_category_assignees_user_id ON packing_category_assignees(user_id)');
this.addSql(
'CREATE INDEX IF NOT EXISTS idx_packing_category_assignees_user_id ON packing_category_assignees(user_id)',
);
this.addSql('CREATE INDEX IF NOT EXISTS idx_packing_templates_created_by ON packing_templates(created_by)');
this.addSql('CREATE INDEX IF NOT EXISTS idx_packing_template_categories_template_id ON packing_template_categories(template_id)');
this.addSql('CREATE INDEX IF NOT EXISTS idx_packing_template_items_category_id ON packing_template_items(category_id)');
this.addSql(
'CREATE INDEX IF NOT EXISTS idx_packing_template_categories_template_id ON packing_template_categories(template_id)',
);
this.addSql(
'CREATE INDEX IF NOT EXISTS idx_packing_template_items_category_id ON packing_template_items(category_id)',
);
this.addSql('CREATE INDEX IF NOT EXISTS idx_packing_bags_user_id ON packing_bags(user_id)');
this.addSql('CREATE INDEX IF NOT EXISTS idx_packing_bags_trip_id ON packing_bags(trip_id)');
this.addSql('CREATE INDEX IF NOT EXISTS idx_bucket_list_user_id ON bucket_list(user_id)');
@@ -84,22 +90,38 @@ export class Migration20200101042200_an_index_on_every_foreign_key extends Migra
this.addSql('CREATE INDEX IF NOT EXISTS idx_day_accommodations_place_id ON day_accommodations(place_id)');
this.addSql('CREATE INDEX IF NOT EXISTS idx_journey_photos_photo_id ON journey_photos(photo_id)');
this.addSql('CREATE INDEX IF NOT EXISTS idx_budget_item_payers_user_id ON budget_item_payers(user_id)');
this.addSql('CREATE INDEX IF NOT EXISTS idx_budget_settlements_created_by_user_id ON budget_settlements(created_by_user_id)');
this.addSql(
'CREATE INDEX IF NOT EXISTS idx_budget_settlements_created_by_user_id ON budget_settlements(created_by_user_id)',
);
this.addSql('CREATE INDEX IF NOT EXISTS idx_budget_settlements_to_user_id ON budget_settlements(to_user_id)');
this.addSql('CREATE INDEX IF NOT EXISTS idx_budget_settlements_from_user_id ON budget_settlements(from_user_id)');
this.addSql('CREATE INDEX IF NOT EXISTS idx_packing_item_contributors_user_id ON packing_item_contributors(user_id)');
this.addSql(
'CREATE INDEX IF NOT EXISTS idx_packing_item_contributors_user_id ON packing_item_contributors(user_id)',
);
this.addSql('CREATE INDEX IF NOT EXISTS idx_trip_invite_tokens_created_by ON trip_invite_tokens(created_by)');
this.addSql('CREATE INDEX IF NOT EXISTS idx_journey_books_updated_by ON journey_books(updated_by)');
this.addSql('CREATE INDEX IF NOT EXISTS idx_journey_books_created_by ON journey_books(created_by)');
this.addSql('CREATE INDEX IF NOT EXISTS idx_collab_links_user_id ON collab_links(user_id)');
this.addSql('CREATE INDEX IF NOT EXISTS idx_dawarich_visit_suggestions_matched_bucket_list_item_id ON dawarich_visit_suggestions(matched_bucket_list_item_id)');
this.addSql('CREATE INDEX IF NOT EXISTS idx_dawarich_visit_suggestions_accepted_bucket_list_item_id ON dawarich_visit_suggestions(accepted_bucket_list_item_id)');
this.addSql('CREATE INDEX IF NOT EXISTS idx_dawarich_visit_suggestions_accepted_place_id ON dawarich_visit_suggestions(accepted_place_id)');
this.addSql(
'CREATE INDEX IF NOT EXISTS idx_dawarich_visit_suggestions_matched_bucket_list_item_id ON dawarich_visit_suggestions(matched_bucket_list_item_id)',
);
this.addSql(
'CREATE INDEX IF NOT EXISTS idx_dawarich_visit_suggestions_accepted_bucket_list_item_id ON dawarich_visit_suggestions(accepted_bucket_list_item_id)',
);
this.addSql(
'CREATE INDEX IF NOT EXISTS idx_dawarich_visit_suggestions_accepted_place_id ON dawarich_visit_suggestions(accepted_place_id)',
);
this.addSql('CREATE INDEX IF NOT EXISTS idx_document_connections_provider_id ON document_connections(provider_id)');
this.addSql('CREATE INDEX IF NOT EXISTS idx_trip_document_links_created_by ON trip_document_links(created_by)');
this.addSql('CREATE INDEX IF NOT EXISTS idx_trip_document_links_connection_id ON trip_document_links(connection_id)');
this.addSql(
'CREATE INDEX IF NOT EXISTS idx_trip_document_links_connection_id ON trip_document_links(connection_id)',
);
this.addSql('CREATE INDEX IF NOT EXISTS idx_document_sync_items_file_id ON document_sync_items(file_id)');
this.addSql('CREATE INDEX IF NOT EXISTS idx_roadtrip_day_boundaries_to_assignment_id ON roadtrip_day_boundaries(to_assignment_id)');
this.addSql('CREATE INDEX IF NOT EXISTS idx_roadtrip_day_boundaries_from_assignment_id ON roadtrip_day_boundaries(from_assignment_id)');
this.addSql(
'CREATE INDEX IF NOT EXISTS idx_roadtrip_day_boundaries_to_assignment_id ON roadtrip_day_boundaries(to_assignment_id)',
);
this.addSql(
'CREATE INDEX IF NOT EXISTS idx_roadtrip_day_boundaries_from_assignment_id ON roadtrip_day_boundaries(from_assignment_id)',
);
}
}
@@ -1,5 +1,5 @@
import { Migration } from '@mikro-orm/migrations';
import { columnNames } from '../migration-utils';
import { Migration } from '@mikro-orm/migrations';
/**
* `tour_types` holds every key the shared `tourTypeKeySchema` accepts. Only
+1 -1
View File
@@ -97,7 +97,7 @@ import { SqlitePlatform } from '@mikro-orm/sql';
export class NulSafeSqlitePlatform extends SqlitePlatform {
override escape(value: unknown): string {
if (typeof value === 'string' && value.includes('\u0000')) {
const literals = value.split('\u0000').map(part => super.escape(part));
const literals = value.split('\u0000').map((part) => super.escape(part));
return `(${literals.join(' || char(0) || ')})`;
}
if (typeof value === 'number' && !Number.isFinite(value)) {
+1 -1
View File
@@ -1,8 +1,8 @@
import { getRawConnection } from './database';
import { NulSafeSqlitePlatform } from './nul-safe-sqlite-platform';
import type { Configuration } from '@mikro-orm/core';
import type { SqlitePlatform } from '@mikro-orm/sql';
import { SqliteConnection, SqliteDriver } from '@mikro-orm/sqlite';
import { NulSafeSqlitePlatform } from './nul-safe-sqlite-platform';
import type Database from 'better-sqlite3';
import { SqliteDialect, SqliteDriver as KyselySqliteDriver, type Dialect, type SqliteDialectConfig } from 'kysely';
+8 -2
View File
@@ -1,9 +1,9 @@
import mikroOrmConfig from '../mikro-orm.config';
import { withRequestContext } from '../nest/database/request-context';
import { runDemoSeed } from './database';
import { ensureEmailCaseIndex } from './email-case-index';
import { migrateToHead, NO_SAFETY_NET } from './legacy-baseline';
import { preMigrateSnapshot } from './pre-migrate-snapshot';
import { withRequestContext } from '../nest/database/request-context';
import type { AnyEntity, EntityClass, EntityManager, EntitySchema, IDatabaseDriver, MikroORM } from '@mikro-orm/core';
import type { Migrator } from '@mikro-orm/migrations';
import { MikroORM as SqliteMikroORM } from '@mikro-orm/sqlite';
@@ -45,7 +45,13 @@ export async function runSchemaBootstrap(orm: AnyOrm, { snapshot = true }: { sna
// what it already has is recorded in the same transaction as the run, or the
// run would replay the whole history over it (see legacy-baseline.ts). Every
// other database just gets its pending migrations.
await migrateToHead(connection, migrator, undefined, undefined, snapshot ? preMigrateSnapshot(connection) : NO_SAFETY_NET);
await migrateToHead(
connection,
migrator,
undefined,
undefined,
snapshot ? preMigrateSnapshot(connection) : NO_SAFETY_NET,
);
// The one index a migration may have had to defer (see email-case-index.ts).
await ensureEmailCaseIndex(connection);
@@ -1,5 +1,5 @@
import type { AssignmentParticipants } from '../entities/AssignmentParticipants.entity';
import { coalesce, columnRef } from '../dialect/sql-functions';
import type { AssignmentParticipants } from '../entities/AssignmentParticipants.entity';
import { TrekRepository } from './_shared/trek-repository';
/** One assignment's participant, from `QueryHelpersService.loadParticipantsByAssignmentIds` (QH3). */
@@ -1,7 +1,7 @@
import { AuditLog } from '../entities/AuditLog.entity';
import type { DB } from '../kysely/db';
import { type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
/**
* An `audit_log` row as the API emits it (Plan 3i's `admin.service.ts`
@@ -105,7 +105,17 @@ export class AuditLogRepository extends TrekRepository<AuditLog> {
return await this.kysely<AuditLogKyselyDB>()
.selectFrom('audit_log as a')
.leftJoin('users as u', 'u.id', 'a.user_id')
.select(['a.id', 'a.created_at', 'a.user_id', 'u.username', 'u.email as user_email', 'a.action', 'a.resource', 'a.details', 'a.ip'])
.select([
'a.id',
'a.created_at',
'a.user_id',
'u.username',
'u.email as user_email',
'a.action',
'a.resource',
'a.details',
'a.ip',
])
.orderBy('a.id', 'desc')
.limit(limit)
.offset(offset)
@@ -1,8 +1,8 @@
import { lowerTrim, lowerTrimParam } from '../dialect/sql-functions';
import type { BucketList } from '../entities/BucketList.entity';
import type { DB } from '../kysely/db';
import { presenceSet } from './_shared/presence-set';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
/** `bucket_list` — every scalar column, `AT30`/`AT33`/`AT34`'s `SELECT *` shape. */
export interface BucketListRow {
@@ -67,7 +67,12 @@ export class BucketListRepository extends TrekRepository<BucketList> {
/** AT30 (`bucketList`) — `SELECT * FROM bucket_list WHERE user_id = ? ORDER BY created_at DESC`. */
async listForUser(userId: number): Promise<BucketListRow[]> {
return await this.readDb().selectFrom('bucket_list').selectAll().where('user_id', '=', userId).orderBy('created_at', 'desc').execute();
return await this.readDb()
.selectFrom('bucket_list')
.selectAll()
.where('user_id', '=', userId)
.orderBy('created_at', 'desc')
.execute();
}
/**
@@ -128,18 +133,31 @@ export class BucketListRepository extends TrekRepository<BucketList> {
target_date: string | null;
region_code: string | null;
}): Promise<number> {
const inserted = await this.insertDb().insertInto('bucket_list').values(row).returning('id').executeTakeFirstOrThrow();
const inserted = await this.insertDb()
.insertInto('bucket_list')
.values(row)
.returning('id')
.executeTakeFirstOrThrow();
return inserted.id;
}
/** AT33 (`createBucketItem`'s post-insert re-select, NOT user-scoped — the legacy statement's own shape) — `SELECT * FROM bucket_list WHERE id = ?`. */
async findById(id: number | string): Promise<BucketListRow | undefined> {
return await this.readDb().selectFrom('bucket_list').selectAll().where('id', '=', id as number).executeTakeFirst();
return await this.readDb()
.selectFrom('bucket_list')
.selectAll()
.where('id', '=', id as number)
.executeTakeFirst();
}
/** AT34/AT36/AT37 (`updateBucketItem`'s guard, its post-update re-select, `deleteBucketItem`'s guard — identical text, three call sites) — `SELECT * FROM bucket_list WHERE id = ? AND user_id = ?`. */
async findForUser(id: number | string, userId: number): Promise<BucketListRow | undefined> {
return await this.readDb().selectFrom('bucket_list').selectAll().where('id', '=', id as number).where('user_id', '=', userId).executeTakeFirst();
return await this.readDb()
.selectFrom('bucket_list')
.selectAll()
.where('id', '=', id as number)
.where('user_id', '=', userId)
.executeTakeFirst();
}
/**
@@ -181,12 +199,21 @@ export class BucketListRepository extends TrekRepository<BucketList> {
target_date: string | null;
}>(write);
if (Object.keys(data).length === 0) return;
await this.writeDb().updateTable('bucket_list').set(data).where('id', '=', id as number).where('user_id', '=', userId).execute();
await this.writeDb()
.updateTable('bucket_list')
.set(data)
.where('id', '=', id as number)
.where('user_id', '=', userId)
.execute();
}
/** AT38 (`deleteBucketItem`) — `DELETE FROM bucket_list WHERE id = ? AND user_id = ?`. */
async deleteForUser(id: number | string, userId: number): Promise<void> {
await this.writeDb().deleteFrom('bucket_list').where('id', '=', id as number).where('user_id', '=', userId).execute();
await this.writeDb()
.deleteFrom('bucket_list')
.where('id', '=', id as number)
.where('user_id', '=', userId)
.execute();
}
// ---------------------------------------------------------------------------
@@ -216,7 +243,9 @@ export class BucketListRepository extends TrekRepository<BucketList> {
* created_at DESC, id DESC`. The boolean-expression `ORDER BY` key is
* portable SQL — no dialect helper needed.
*/
async listForScan(userId: number): Promise<{ id: number; name: string; lat: number | null; lng: number | null; visited_at: string | null }[]> {
async listForScan(
userId: number,
): Promise<{ id: number; name: string; lat: number | null; lng: number | null; visited_at: string | null }[]> {
return await this.readDb()
.selectFrom('bucket_list')
.select(['id', 'name', 'lat', 'lng', 'visited_at'])
@@ -1,6 +1,6 @@
import type { BudgetCategoryOrder } from '../entities/BudgetCategoryOrder.entity';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
type BudgetCategoryOrderKyselyDB = Pick<DB, 'budget_category_order'>;
@@ -1,7 +1,7 @@
import type { BudgetItemMembers } from '../entities/BudgetItemMembers.entity';
import type { DB } from '../kysely/db';
import { type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
/** A bare `budget_item_members` row — every scalar column, incl. the two `persist(false)` relation mirrors. */
export interface BudgetItemMemberRow {
@@ -43,7 +43,13 @@ export class BudgetItemMembersRepository extends TrekRepository<BudgetItemMember
return await this.kysely<BudgetItemMembersKyselyDB>()
.selectFrom('budget_item_members as bm')
.innerJoin('users as u', 'u.id', 'bm.user_id')
.select(['bm.user_id', 'bm.paid', 'bm.amount', (eb) => eb.fn.coalesce('u.display_name', 'u.username').as('username'), 'u.avatar'])
.select([
'bm.user_id',
'bm.paid',
'bm.amount',
(eb) => eb.fn.coalesce('u.display_name', 'u.username').as('username'),
'u.avatar',
])
.where('bm.budget_item_id', '=', budget_item_id)
.execute();
}
@@ -54,7 +60,14 @@ export class BudgetItemMembersRepository extends TrekRepository<BudgetItemMember
return await this.kysely<BudgetItemMembersKyselyDB>()
.selectFrom('budget_item_members as bm')
.innerJoin('users as u', 'u.id', 'bm.user_id')
.select(['bm.budget_item_id', 'bm.user_id', 'bm.paid', 'bm.amount', (eb) => eb.fn.coalesce('u.display_name', 'u.username').as('username'), 'u.avatar'])
.select([
'bm.budget_item_id',
'bm.user_id',
'bm.paid',
'bm.amount',
(eb) => eb.fn.coalesce('u.display_name', 'u.username').as('username'),
'u.avatar',
])
.where('bm.budget_item_id', 'in', budget_item_ids)
.execute();
}
@@ -79,12 +92,22 @@ export class BudgetItemMembersRepository extends TrekRepository<BudgetItemMember
}
/** BG73 (`calculateSettlement`'s member read) — the `budget_item_id IN (SELECT id FROM budget_items WHERE trip_id = ?)` subquery, re-expressed as a join (rule 23) — same result set. No `paid` column — unlike {@link listForItem}, this legacy statement never selected it. */
async listForTripWithUsers(trip_id: number | string): Promise<{ budget_item_id: number; user_id: number; amount: number | null; username: string; avatar: string | null }[]> {
async listForTripWithUsers(
trip_id: number | string,
): Promise<
{ budget_item_id: number; user_id: number; amount: number | null; username: string; avatar: string | null }[]
> {
return await this.kysely<BudgetItemMembersKyselyDB & Pick<DB, 'budget_items'>>()
.selectFrom('budget_item_members as bm')
.innerJoin('budget_items as b', 'b.id', 'bm.budget_item_id')
.innerJoin('users as u', 'u.id', 'bm.user_id')
.select(['bm.budget_item_id', 'bm.user_id', 'bm.amount', (eb) => eb.fn.coalesce('u.display_name', 'u.username').as('username'), 'u.avatar'])
.select([
'bm.budget_item_id',
'bm.user_id',
'bm.amount',
(eb) => eb.fn.coalesce('u.display_name', 'u.username').as('username'),
'u.avatar',
])
.where('b.trip_id', '=', trip_id as number)
.execute();
}
@@ -96,12 +119,21 @@ export class BudgetItemMembersRepository extends TrekRepository<BudgetItemMember
* bm.budget_item_id = bi.id JOIN users u ON bm.user_id = u.id WHERE
* bi.trip_id = ?`. Like {@link listForTripWithUsers}, plus `paid`.
*/
async listForTripWithUsersAndPaid(trip_id: number | string): Promise<(BudgetItemMemberWithUserRow & { budget_item_id: number })[]> {
async listForTripWithUsersAndPaid(
trip_id: number | string,
): Promise<(BudgetItemMemberWithUserRow & { budget_item_id: number })[]> {
return await this.kysely<BudgetItemMembersKyselyDB & Pick<DB, 'budget_items'>>()
.selectFrom('budget_item_members as bm')
.innerJoin('budget_items as bi', 'bi.id', 'bm.budget_item_id')
.innerJoin('users as u', 'u.id', 'bm.user_id')
.select(['bm.budget_item_id', 'bm.user_id', 'bm.amount', 'bm.paid', (eb) => eb.fn.coalesce('u.display_name', 'u.username').as('username'), 'u.avatar'])
.select([
'bm.budget_item_id',
'bm.user_id',
'bm.amount',
'bm.paid',
(eb) => eb.fn.coalesce('u.display_name', 'u.username').as('username'),
'u.avatar',
])
.where('bi.trip_id', '=', trip_id as number)
.execute();
}
@@ -114,12 +146,15 @@ export class BudgetItemMembersRepository extends TrekRepository<BudgetItemMember
.distinct()
.where('user_id', '=', user_id)
.execute();
return rows.map(r => r.budget_item_id);
return rows.map((r) => r.budget_item_id);
}
/** BG65 — `DELETE FROM budget_item_members WHERE user_id = ?`. */
async deleteForUser(user_id: number): Promise<void> {
await this.kysely<BudgetItemMembersKyselyDB>().deleteFrom('budget_item_members').where('user_id', '=', user_id).execute();
await this.kysely<BudgetItemMembersKyselyDB>()
.deleteFrom('budget_item_members')
.where('user_id', '=', user_id)
.execute();
}
/** BG66 (`removeUserFromBudgetItems`'s per-item recount, looped) — `SELECT COUNT(*) AS count FROM budget_item_members WHERE budget_item_id = ?`. */
@@ -133,11 +168,19 @@ export class BudgetItemMembersRepository extends TrekRepository<BudgetItemMember
}
/** BG70 (`toggleMemberPaid`'s re-select) — `SELECT bm.user_id, bm.paid, COALESCE(u.display_name, u.username) AS username, u.avatar FROM budget_item_members bm JOIN users u WHERE bm.budget_item_id = ? AND bm.user_id = ?`. No `amount` column — unlike {@link listForItem}, this legacy statement never selected it. */
async findMemberWithUser(budget_item_id: number, user_id: number): Promise<{ user_id: number; paid: number; username: string; avatar: string | null } | undefined> {
async findMemberWithUser(
budget_item_id: number,
user_id: number,
): Promise<{ user_id: number; paid: number; username: string; avatar: string | null } | undefined> {
return await this.kysely<BudgetItemMembersKyselyDB>()
.selectFrom('budget_item_members as bm')
.innerJoin('users as u', 'u.id', 'bm.user_id')
.select(['bm.user_id', 'bm.paid', (eb) => eb.fn.coalesce('u.display_name', 'u.username').as('username'), 'u.avatar'])
.select([
'bm.user_id',
'bm.paid',
(eb) => eb.fn.coalesce('u.display_name', 'u.username').as('username'),
'u.avatar',
])
.where('bm.budget_item_id', '=', budget_item_id)
.where('bm.user_id', '=', user_id)
.executeTakeFirst();
@@ -155,7 +198,10 @@ export class BudgetItemMembersRepository extends TrekRepository<BudgetItemMember
/** BG35/BG38/BG59 — `DELETE FROM budget_item_members WHERE budget_item_id = ?` (replace-all before a re-insert). */
async deleteForItem(budget_item_id: number): Promise<void> {
await this.kysely<BudgetItemMembersKyselyDB>().deleteFrom('budget_item_members').where('budget_item_id', '=', budget_item_id).execute();
await this.kysely<BudgetItemMembersKyselyDB>()
.deleteFrom('budget_item_members')
.where('budget_item_id', '=', budget_item_id)
.execute();
}
/**
@@ -168,10 +214,20 @@ export class BudgetItemMembersRepository extends TrekRepository<BudgetItemMember
* with no `amount` column at all — `paid`/`amount` default here to the
* 0/`NULL` shape the omitting call sites bound literally).
*/
async insertIgnore(row: { budget_item_id: number; user_id: number; paid?: number; amount?: number | null }): Promise<void> {
async insertIgnore(row: {
budget_item_id: number;
user_id: number;
paid?: number;
amount?: number | null;
}): Promise<void> {
await this.kysely<BudgetItemMembersWriteKyselyDB>()
.insertInto('budget_item_members')
.values({ budget_item_id: row.budget_item_id, user_id: row.user_id, paid: row.paid ?? 0, amount: row.amount ?? null })
.values({
budget_item_id: row.budget_item_id,
user_id: row.user_id,
paid: row.paid ?? 0,
amount: row.amount ?? null,
})
.onConflict((oc) => oc.doNothing())
.execute();
}
@@ -1,7 +1,7 @@
import type { BudgetItemPayers } from '../entities/BudgetItemPayers.entity';
import type { DB } from '../kysely/db';
import { type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
/** A bare `budget_item_payers` row — every scalar column, incl. the two `persist(false)` relation mirrors. */
export interface BudgetItemPayerRow {
@@ -38,7 +38,12 @@ export class BudgetItemPayersRepository extends TrekRepository<BudgetItemPayers>
return await this.kysely<BudgetItemPayersKyselyDB>()
.selectFrom('budget_item_payers as bp')
.innerJoin('users as u', 'u.id', 'bp.user_id')
.select(['bp.user_id', 'bp.amount', (eb) => eb.fn.coalesce('u.display_name', 'u.username').as('username'), 'u.avatar'])
.select([
'bp.user_id',
'bp.amount',
(eb) => eb.fn.coalesce('u.display_name', 'u.username').as('username'),
'u.avatar',
])
.where('bp.budget_item_id', '=', budget_item_id)
.execute();
}
@@ -49,7 +54,13 @@ export class BudgetItemPayersRepository extends TrekRepository<BudgetItemPayers>
return await this.kysely<BudgetItemPayersKyselyDB>()
.selectFrom('budget_item_payers as bp')
.innerJoin('users as u', 'u.id', 'bp.user_id')
.select(['bp.budget_item_id', 'bp.user_id', 'bp.amount', (eb) => eb.fn.coalesce('u.display_name', 'u.username').as('username'), 'u.avatar'])
.select([
'bp.budget_item_id',
'bp.user_id',
'bp.amount',
(eb) => eb.fn.coalesce('u.display_name', 'u.username').as('username'),
'u.avatar',
])
.where('bp.budget_item_id', 'in', budget_item_ids)
.execute();
}
@@ -65,19 +76,30 @@ export class BudgetItemPayersRepository extends TrekRepository<BudgetItemPayers>
}
/** BG74 (`calculateSettlement`'s payer read) — the `budget_item_id IN (SELECT id FROM budget_items WHERE trip_id = ?)` subquery, re-expressed as a join (rule 23) — same result set. */
async listForTripWithUsers(trip_id: number | string): Promise<(BudgetItemPayerWithUserRow & { budget_item_id: number })[]> {
async listForTripWithUsers(
trip_id: number | string,
): Promise<(BudgetItemPayerWithUserRow & { budget_item_id: number })[]> {
return await this.kysely<BudgetItemPayersKyselyDB & Pick<DB, 'budget_items'>>()
.selectFrom('budget_item_payers as bp')
.innerJoin('budget_items as b', 'b.id', 'bp.budget_item_id')
.innerJoin('users as u', 'u.id', 'bp.user_id')
.select(['bp.budget_item_id', 'bp.user_id', 'bp.amount', (eb) => eb.fn.coalesce('u.display_name', 'u.username').as('username'), 'u.avatar'])
.select([
'bp.budget_item_id',
'bp.user_id',
'bp.amount',
(eb) => eb.fn.coalesce('u.display_name', 'u.username').as('username'),
'u.avatar',
])
.where('b.trip_id', '=', trip_id as number)
.execute();
}
/** BG4 — `DELETE FROM budget_item_payers WHERE budget_item_id = ?` (replace-all before a re-insert). */
async deleteForItem(budget_item_id: number): Promise<void> {
await this.kysely<BudgetItemPayersKyselyDB>().deleteFrom('budget_item_payers').where('budget_item_id', '=', budget_item_id).execute();
await this.kysely<BudgetItemPayersKyselyDB>()
.deleteFrom('budget_item_payers')
.where('budget_item_id', '=', budget_item_id)
.execute();
}
/** BG5/TP65 — `INSERT OR IGNORE INTO budget_item_payers (budget_item_id, user_id, amount) VALUES (?,?,?)`, one row per call (the legacy `prepare(...).run(...)` loop). */
@@ -1,9 +1,9 @@
import type { BudgetItems } from '../entities/BudgetItems.entity';
import { columnRef } from '../dialect/sql-functions';
import type { BudgetItems } from '../entities/BudgetItems.entity';
import type { DB } from '../kysely/db';
import { presenceSet } from './_shared/presence-set';
import { type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
import { presenceSet } from './_shared/presence-set';
import type { DB } from '../kysely/db';
/** A bare `budget_items` row — every scalar column, incl. the four `persist(false)` relation mirrors (the program-wide trap this class goes through Kysely to avoid). */
export interface BudgetItemRow {
@@ -56,7 +56,10 @@ export interface BudgetItemMoneyRow {
exchange_rate: number;
}
type BudgetKyselyDB = Pick<DB, 'budget_items' | 'budget_item_members' | 'budget_category_order' | 'users' | 'trip_files' | 'file_links'>;
type BudgetKyselyDB = Pick<
DB,
'budget_items' | 'budget_item_members' | 'budget_category_order' | 'users' | 'trip_files' | 'file_links'
>;
/**
* The table `create` (BG25) inserts into. It binds the legacy column list:
@@ -101,7 +104,9 @@ export class BudgetItemsRepository extends TrekRepository<BudgetItems> {
async listWithCategoryOrder(trip_id: number | string): Promise<BudgetItemRow[]> {
return await this.kysely<BudgetKyselyDB>()
.selectFrom('budget_items as bi')
.leftJoin('budget_category_order as bco', (join) => join.onRef('bco.trip_id', '=', 'bi.trip_id').onRef('bco.category', '=', 'bi.category'))
.leftJoin('budget_category_order as bco', (join) =>
join.onRef('bco.trip_id', '=', 'bi.trip_id').onRef('bco.category', '=', 'bi.category'),
)
.selectAll('bi')
.where('bi.trip_id', '=', trip_id as number)
.orderBy((eb) => eb.fn.coalesce('bco.sort_order', eb.val(999999)), 'asc')
@@ -111,33 +116,64 @@ export class BudgetItemsRepository extends TrekRepository<BudgetItems> {
/** BG14 — `SELECT currency FROM budget_items WHERE id = ? AND trip_id = ?`. `id: number` (Plan 4 Task 8b, U6 — the program's gate-level id parsing carry: its one caller, `freezeForeignRate`, is only reached with `BudgetController.update`'s `toRowId`-parsed id). */
async getCurrency(id: number, trip_id: number | string): Promise<string | null | undefined> {
const row = await this.kysely<BudgetKyselyDB>().selectFrom('budget_items').select('currency').where('id', '=', id).where('trip_id', '=', trip_id as number).executeTakeFirst();
const row = await this.kysely<BudgetKyselyDB>()
.selectFrom('budget_items')
.select('currency')
.where('id', '=', id)
.where('trip_id', '=', trip_id as number)
.executeTakeFirst();
return row?.currency;
}
/** BG31/BG32/BG57 — `SELECT * FROM budget_items WHERE id = ? AND trip_id = ?`, the full-row trip-scoping guard. `id: number`, same Plan 4 Task 8b narrowing as {@link getCurrency}; `trip_id` stays `number | string`, a separate, still-accepted carry. */
async findInTrip(id: number, trip_id: number | string): Promise<BudgetItemRow | undefined> {
return await this.kysely<BudgetKyselyDB>().selectFrom('budget_items').selectAll().where('id', '=', id).where('trip_id', '=', trip_id as number).executeTakeFirst();
return await this.kysely<BudgetKyselyDB>()
.selectFrom('budget_items')
.selectAll()
.where('id', '=', id)
.where('trip_id', '=', trip_id as number)
.executeTakeFirst();
}
/** BG50/BG68 — `SELECT id FROM budget_items WHERE id = ? AND trip_id = ?`, the id-only trip-scoping guard. `id: number`, same Plan 4 Task 8b narrowing as {@link getCurrency}. */
async existsInTrip(id: number, trip_id: number | string): Promise<{ id: number } | undefined> {
return await this.kysely<BudgetKyselyDB>().selectFrom('budget_items').select('id').where('id', '=', id).where('trip_id', '=', trip_id as number).executeTakeFirst();
return await this.kysely<BudgetKyselyDB>()
.selectFrom('budget_items')
.select('id')
.where('id', '=', id)
.where('trip_id', '=', trip_id as number)
.executeTakeFirst();
}
/** BG52 (`deleteBudgetItem`'s pre-image) — `SELECT id, reservation_id FROM budget_items WHERE id = ? AND trip_id = ?`. `id: number`, same Plan 4 Task 8b narrowing as {@link getCurrency}. */
async findForDelete(id: number, trip_id: number | string): Promise<{ id: number; reservation_id: number | null } | undefined> {
return await this.kysely<BudgetKyselyDB>().selectFrom('budget_items').select(['id', 'reservation_id']).where('id', '=', id).where('trip_id', '=', trip_id as number).executeTakeFirst();
async findForDelete(
id: number,
trip_id: number | string,
): Promise<{ id: number; reservation_id: number | null } | undefined> {
return await this.kysely<BudgetKyselyDB>()
.selectFrom('budget_items')
.select(['id', 'reservation_id'])
.where('id', '=', id)
.where('trip_id', '=', trip_id as number)
.executeTakeFirst();
}
/** BG30/BG49/BG51/BG63 — `SELECT * FROM budget_items WHERE id = ?`, the post-write re-select (no trip filter — the caller already knows `id` is in-scope, having just written it). `id: number`, same Plan 4 Task 8b narrowing as {@link getCurrency}. */
async findById(id: number): Promise<BudgetItemRow | undefined> {
return await this.kysely<BudgetKyselyDB>().selectFrom('budget_items').selectAll().where('id', '=', id).executeTakeFirst();
return await this.kysely<BudgetKyselyDB>()
.selectFrom('budget_items')
.selectAll()
.where('id', '=', id)
.executeTakeFirst();
}
/** BG21 — `SELECT MAX(sort_order) as max FROM budget_items WHERE trip_id = ?`. */
async maxSortOrder(trip_id: number | string): Promise<number | null> {
const row = await this.kysely<BudgetKyselyDB>().selectFrom('budget_items').select((eb) => eb.fn.max('sort_order').as('max')).where('trip_id', '=', trip_id as number).executeTakeFirst();
const row = await this.kysely<BudgetKyselyDB>()
.selectFrom('budget_items')
.select((eb) => eb.fn.max('sort_order').as('max'))
.where('trip_id', '=', trip_id as number)
.executeTakeFirst();
return row?.max ?? null;
}
@@ -149,11 +185,26 @@ export class BudgetItemsRepository extends TrekRepository<BudgetItems> {
* different signature: an unpersisted-entity builder, not an INSERT).
*/
async insertItem(row: {
trip_id: number | string; category: string; name: string; total_price: number; currency: string | null;
exchange_rate: number; persons: number | null; days: number | null; note: string | null; ticket_json: string | null;
sort_order: number; expense_date: string | null; reservation_id: number | null; place_id: number | null;
trip_id: number | string;
category: string;
name: string;
total_price: number;
currency: string | null;
exchange_rate: number;
persons: number | null;
days: number | null;
note: string | null;
ticket_json: string | null;
sort_order: number;
expense_date: string | null;
reservation_id: number | null;
place_id: number | null;
}): Promise<number> {
const inserted = await this.kysely<BudgetItemsInsertKyselyDB>().insertInto('budget_items').values({ ...row, trip_id: row.trip_id as number }).returning('id').executeTakeFirstOrThrow();
const inserted = await this.kysely<BudgetItemsInsertKyselyDB>()
.insertInto('budget_items')
.values({ ...row, trip_id: row.trip_id as number })
.returning('id')
.executeTakeFirstOrThrow();
return inserted.id;
}
@@ -166,11 +217,26 @@ export class BudgetItemsRepository extends TrekRepository<BudgetItems> {
* column survives a copy unexamined, matching legacy exactly).
*/
async insertCopy(row: {
trip_id: number | string; category: string; name: string; total_price: number; persons: number | null; days: number | null;
note: string | null; sort_order: number | null; reservation_id: number | null; currency: string | null;
exchange_rate: number; expense_date: string | null; ticket_json: string | null; paid_by_user_id: number | null;
trip_id: number | string;
category: string;
name: string;
total_price: number;
persons: number | null;
days: number | null;
note: string | null;
sort_order: number | null;
reservation_id: number | null;
currency: string | null;
exchange_rate: number;
expense_date: string | null;
ticket_json: string | null;
paid_by_user_id: number | null;
}): Promise<number> {
const inserted = await this.kysely<BudgetItemsCopyInsertKyselyDB>().insertInto('budget_items').values({ ...row, trip_id: row.trip_id as number }).returning('id').executeTakeFirstOrThrow();
const inserted = await this.kysely<BudgetItemsCopyInsertKyselyDB>()
.insertInto('budget_items')
.values({ ...row, trip_id: row.trip_id as number })
.returning('id')
.executeTakeFirstOrThrow();
return inserted.id;
}
@@ -185,25 +251,38 @@ export class BudgetItemsRepository extends TrekRepository<BudgetItems> {
* column is a true presence sentinel (`present = data.field !== undefined`).
*/
/** `id: number` — same Plan 4 Task 8b (U6) narrowing as {@link getCurrency} (its one caller, `updateBudgetItem`, is only reached with a `toRowId`-parsed id). */
async update(id: number, write: {
category?: readonly [present: boolean, value: string];
name?: readonly [present: boolean, value: string];
total_price?: readonly [present: boolean, value: number];
currency?: readonly [present: boolean, value: string | null];
exchange_rate?: readonly [present: boolean, value: number];
persons?: readonly [present: boolean, value: number | null];
days?: readonly [present: boolean, value: number | null];
note?: readonly [present: boolean, value: string | null];
ticket_json?: readonly [present: boolean, value: string | null];
sort_order?: readonly [present: boolean, value: number];
expense_date?: readonly [present: boolean, value: string | null];
reservation_id?: readonly [present: boolean, value: number | null];
place_id?: readonly [present: boolean, value: number | null];
}): Promise<void> {
async update(
id: number,
write: {
category?: readonly [present: boolean, value: string];
name?: readonly [present: boolean, value: string];
total_price?: readonly [present: boolean, value: number];
currency?: readonly [present: boolean, value: string | null];
exchange_rate?: readonly [present: boolean, value: number];
persons?: readonly [present: boolean, value: number | null];
days?: readonly [present: boolean, value: number | null];
note?: readonly [present: boolean, value: string | null];
ticket_json?: readonly [present: boolean, value: string | null];
sort_order?: readonly [present: boolean, value: number];
expense_date?: readonly [present: boolean, value: string | null];
reservation_id?: readonly [present: boolean, value: number | null];
place_id?: readonly [present: boolean, value: number | null];
},
): Promise<void> {
const data = presenceSet<{
category: string; name: string; total_price: number; currency: string | null; exchange_rate: number;
persons: number | null; days: number | null; note: string | null; ticket_json: string | null;
sort_order: number; expense_date: string | null; reservation_id: number | null; place_id: number | null;
category: string;
name: string;
total_price: number;
currency: string | null;
exchange_rate: number;
persons: number | null;
days: number | null;
note: string | null;
ticket_json: string | null;
sort_order: number;
expense_date: string | null;
reservation_id: number | null;
place_id: number | null;
}>(write);
if (Object.keys(data).length === 0) return;
await this.kysely<BudgetKyselyDB>().updateTable('budget_items').set(data).where('id', '=', id).execute();
@@ -211,17 +290,30 @@ export class BudgetItemsRepository extends TrekRepository<BudgetItems> {
/** BG6/BG34 — `UPDATE budget_items SET total_price = ? WHERE id = ?`. */
async setTotalPrice(id: number | string, total_price: number): Promise<void> {
await this.kysely<BudgetKyselyDB>().updateTable('budget_items').set({ total_price }).where('id', '=', id as number).execute();
await this.kysely<BudgetKyselyDB>()
.updateTable('budget_items')
.set({ total_price })
.where('id', '=', id as number)
.execute();
}
/** BG37/BG40/BG61/BG62 — `UPDATE budget_items SET persons = ? WHERE id = ?` (`persons: null` is BG62's clear branch). */
async setPersons(id: number | string, persons: number | null): Promise<void> {
await this.kysely<BudgetKyselyDB>().updateTable('budget_items').set({ persons }).where('id', '=', id as number).execute();
await this.kysely<BudgetKyselyDB>()
.updateTable('budget_items')
.set({ persons })
.where('id', '=', id as number)
.execute();
}
/** BG83 (`reorderItems`, looped) — `UPDATE budget_items SET sort_order = ? WHERE id = ? AND trip_id = ?`. */
async setSortOrder(id: number | string, trip_id: number | string, sort_order: number): Promise<void> {
await this.kysely<BudgetKyselyDB>().updateTable('budget_items').set({ sort_order }).where('id', '=', id as number).where('trip_id', '=', trip_id as number).execute();
await this.kysely<BudgetKyselyDB>()
.updateTable('budget_items')
.set({ sort_order })
.where('id', '=', id as number)
.where('trip_id', '=', trip_id as number)
.execute();
}
/** BG53 — `DELETE FROM budget_items WHERE id = ?` (no trip scoping in the statement itself — relies on the caller's prior {@link findForDelete} gate, matching legacy). `id: number`, same Plan 4 Task 8b narrowing as {@link getCurrency}. */
@@ -237,7 +329,11 @@ export class BudgetItemsRepository extends TrekRepository<BudgetItems> {
/** BG72 (`calculateSettlement`) — `SELECT * FROM budget_items WHERE trip_id = ?`. */
async listAllForTrip(trip_id: number | string): Promise<BudgetItemRow[]> {
return await this.kysely<BudgetKyselyDB>().selectFrom('budget_items').selectAll().where('trip_id', '=', trip_id as number).execute();
return await this.kysely<BudgetKyselyDB>()
.selectFrom('budget_items')
.selectAll()
.where('trip_id', '=', trip_id as number)
.execute();
}
/**
@@ -246,7 +342,12 @@ export class BudgetItemsRepository extends TrekRepository<BudgetItems> {
* (unlike BG72's `listAllForTrip` above, which has no `ORDER BY`).
*/
async listPublicForShare(trip_id: number | string): Promise<BudgetItemRow[]> {
return await this.kysely<BudgetKyselyDB>().selectFrom('budget_items').selectAll().where('trip_id', '=', trip_id as number).orderBy('category', 'asc').execute();
return await this.kysely<BudgetKyselyDB>()
.selectFrom('budget_items')
.selectAll()
.where('trip_id', '=', trip_id as number)
.orderBy('category', 'asc')
.execute();
}
/**
@@ -277,7 +378,9 @@ export class BudgetItemsRepository extends TrekRepository<BudgetItems> {
.where('currency', 'is not', null)
.where('currency', '!=', '')
.where((eb) => eb(eb.fn<string>('upper', ['currency']), '!=', trip_currency))
.where((eb) => eb.or([eb('exchange_rate', 'is', null), eb('exchange_rate', '<=', 0), eb('exchange_rate', '=', 1)]))
.where((eb) =>
eb.or([eb('exchange_rate', 'is', null), eb('exchange_rate', '<=', 0), eb('exchange_rate', '=', 1)]),
)
.limit(1)
.executeTakeFirst();
return row !== undefined;
@@ -300,9 +403,11 @@ export class BudgetItemsRepository extends TrekRepository<BudgetItems> {
.where('currency', 'is not', null)
.where('currency', '!=', '')
.where((eb) => eb(eb.fn<string>('upper', ['currency']), '!=', trip_currency))
.where((eb) => eb.or([eb('exchange_rate', 'is', null), eb('exchange_rate', '<=', 0), eb('exchange_rate', '=', 1)]))
.where((eb) =>
eb.or([eb('exchange_rate', 'is', null), eb('exchange_rate', '<=', 0), eb('exchange_rate', '=', 1)]),
)
.execute();
return rows.map(r => r.cur);
return rows.map((r) => r.cur);
}
/** BG91's `budget_items` half (`freezeMissingRates`) — `SELECT id FROM budget_items WHERE trip_id = ? AND UPPER(currency) = ? AND (exchange_rate IS NULL OR exchange_rate <= 0 OR exchange_rate = 1)`. */
@@ -312,9 +417,11 @@ export class BudgetItemsRepository extends TrekRepository<BudgetItems> {
.select('id')
.where('trip_id', '=', trip_id as number)
.where((eb) => eb(eb.fn<string>('upper', ['currency']), '=', currency))
.where((eb) => eb.or([eb('exchange_rate', 'is', null), eb('exchange_rate', '<=', 0), eb('exchange_rate', '=', 1)]))
.where((eb) =>
eb.or([eb('exchange_rate', 'is', null), eb('exchange_rate', '<=', 0), eb('exchange_rate', '=', 1)]),
)
.execute();
return rows.map(r => r.id);
return rows.map((r) => r.id);
}
/** BG92's `budget_items` half (`freezeMissingRates`) — `UPDATE budget_items SET exchange_rate = ? WHERE trip_id = ? AND UPPER(currency) = ? AND (exchange_rate IS NULL OR exchange_rate <= 0 OR exchange_rate = 1)`, the compare-and-set write. */
@@ -324,12 +431,17 @@ export class BudgetItemsRepository extends TrekRepository<BudgetItems> {
.set({ exchange_rate })
.where('trip_id', '=', trip_id as number)
.where((eb) => eb(eb.fn<string>('upper', ['currency']), '=', currency))
.where((eb) => eb.or([eb('exchange_rate', 'is', null), eb('exchange_rate', '<=', 0), eb('exchange_rate', '=', 1)]))
.where((eb) =>
eb.or([eb('exchange_rate', 'is', null), eb('exchange_rate', '<=', 0), eb('exchange_rate', '=', 1)]),
)
.execute();
}
/** BG93 (`resyncReservationPrice`) — `SELECT total_price, currency FROM budget_items WHERE trip_id = ? AND reservation_id = ? ORDER BY id`, every expense linked to one booking (#2084). */
async listLinkedToReservation(trip_id: number | string, reservation_id: number): Promise<{ total_price: number | null; currency: string | null }[]> {
async listLinkedToReservation(
trip_id: number | string,
reservation_id: number,
): Promise<{ total_price: number | null; currency: string | null }[]> {
return await this.kysely<BudgetKyselyDB>()
.selectFrom('budget_items')
.select(['total_price', 'currency'])
@@ -351,13 +463,24 @@ export class BudgetItemsRepository extends TrekRepository<BudgetItems> {
/** BG18's `budget_items` half — `SELECT DISTINCT currency AS cur FROM budget_items WHERE trip_id = ? AND currency IS NOT NULL`. */
async listDistinctCurrencies(trip_id: number | string): Promise<string[]> {
const rows = await this.kysely<BudgetKyselyDB>().selectFrom('budget_items').select('currency').distinct().where('trip_id', '=', trip_id as number).where('currency', 'is not', null).execute();
return rows.map(r => r.currency as string);
const rows = await this.kysely<BudgetKyselyDB>()
.selectFrom('budget_items')
.select('currency')
.distinct()
.where('trip_id', '=', trip_id as number)
.where('currency', 'is not', null)
.execute();
return rows.map((r) => r.currency as string);
}
/** BG19's `budget_items` half — `UPDATE budget_items SET exchange_rate = ? WHERE trip_id = ? AND currency = ?`. */
async setExchangeRateForCurrency(trip_id: number | string, currency: string, exchange_rate: number): Promise<void> {
await this.kysely<BudgetKyselyDB>().updateTable('budget_items').set({ exchange_rate }).where('trip_id', '=', trip_id as number).where('currency', '=', currency).execute();
await this.kysely<BudgetKyselyDB>()
.updateTable('budget_items')
.set({ exchange_rate })
.where('trip_id', '=', trip_id as number)
.where('currency', '=', currency)
.execute();
}
// ---------------------------------------------------------------------------
@@ -408,7 +531,11 @@ export class BudgetItemsRepository extends TrekRepository<BudgetItems> {
/** BG8 (`unlinkReceipts`) — `UPDATE file_links SET budget_item_id = NULL WHERE id = ?`. */
async clearLinkBudgetRef(link_id: number): Promise<void> {
await this.kysely<BudgetKyselyDB>().updateTable('file_links').set({ budget_item_id: null }).where('id', '=', link_id).execute();
await this.kysely<BudgetKyselyDB>()
.updateTable('file_links')
.set({ budget_item_id: null })
.where('id', '=', link_id)
.execute();
}
/** BG9 (`unlinkReceipts`) — `DELETE FROM file_links WHERE id = ?`. */
@@ -438,7 +565,11 @@ export class BudgetItemsRepository extends TrekRepository<BudgetItems> {
/** BG46 (`updateBudgetItem`'s `adopt`) — `UPDATE file_links SET budget_item_id = ? WHERE id = ?`, re-parenting a spare link row instead of inserting a duplicate. */
async adoptSpareLink(link_id: number, budget_item_id: number | string): Promise<void> {
await this.kysely<BudgetKyselyDB>().updateTable('file_links').set({ budget_item_id: budget_item_id as number }).where('id', '=', link_id).execute();
await this.kysely<BudgetKyselyDB>()
.updateTable('file_links')
.set({ budget_item_id: budget_item_id as number })
.where('id', '=', link_id)
.execute();
}
/** BG47 — `SELECT 1 FROM file_links WHERE file_id = ? AND budget_item_id = ?`, the "already this item's receipt" short-circuit. */
@@ -454,7 +585,13 @@ export class BudgetItemsRepository extends TrekRepository<BudgetItems> {
/** BG48 — `SELECT id FROM file_links WHERE file_id = ? AND budget_item_id IS NULL LIMIT 1` (`spare`), drives {@link adoptSpareLink}'s adopt-vs-insert branch. */
async findSpareLink(file_id: number): Promise<{ id: number } | undefined> {
return await this.kysely<BudgetKyselyDB>().selectFrom('file_links').select('id').where('file_id', '=', file_id).where('budget_item_id', 'is', null).limit(1).executeTakeFirst();
return await this.kysely<BudgetKyselyDB>()
.selectFrom('file_links')
.select('id')
.where('file_id', '=', file_id)
.where('budget_item_id', 'is', null)
.limit(1)
.executeTakeFirst();
}
// ---------------------------------------------------------------------------
@@ -470,7 +607,11 @@ export class BudgetItemsRepository extends TrekRepository<BudgetItems> {
* them all.
*/
async listIdsByReservation(reservation_id: number): Promise<{ id: number }[]> {
return await this.kysely<BudgetKyselyDB>().selectFrom('budget_items').select('id').where('reservation_id', '=', reservation_id).execute();
return await this.kysely<BudgetKyselyDB>()
.selectFrom('budget_items')
.select('id')
.where('reservation_id', '=', reservation_id)
.execute();
}
/** PL15 (`linkedExpenseIds`) — `SELECT id FROM budget_items WHERE trip_id = ? AND place_id IN (dynamic)`. */
@@ -482,17 +623,29 @@ export class BudgetItemsRepository extends TrekRepository<BudgetItems> {
.where('trip_id', '=', trip_id as number)
.where('place_id', 'in', place_ids as number[])
.execute();
return rows.map(r => r.id);
return rows.map((r) => r.id);
}
/** PL18/PL22 — `DELETE FROM budget_items WHERE trip_id = ? AND place_id = ?`. */
async deleteForPlace(trip_id: number | string, place_id: number | string): Promise<void> {
await this.kysely<BudgetKyselyDB>().deleteFrom('budget_items').where('trip_id', '=', trip_id as number).where('place_id', '=', place_id as number).execute();
await this.kysely<BudgetKyselyDB>()
.deleteFrom('budget_items')
.where('trip_id', '=', trip_id as number)
.where('place_id', '=', place_id as number)
.execute();
}
/** RS52/RS53 — `SELECT id FROM budget_items WHERE trip_id = ? AND reservation_id = ?`. */
async findIdByReservationInTrip(trip_id: number | string, reservation_id: number | string): Promise<{ id: number } | undefined> {
return await this.kysely<BudgetKyselyDB>().selectFrom('budget_items').select('id').where('trip_id', '=', trip_id as number).where('reservation_id', '=', reservation_id as number).executeTakeFirst();
async findIdByReservationInTrip(
trip_id: number | string,
reservation_id: number | string,
): Promise<{ id: number } | undefined> {
return await this.kysely<BudgetKyselyDB>()
.selectFrom('budget_items')
.select('id')
.where('trip_id', '=', trip_id as number)
.where('reservation_id', '=', reservation_id as number)
.executeTakeFirst();
}
/**
@@ -502,7 +655,10 @@ export class BudgetItemsRepository extends TrekRepository<BudgetItems> {
* all, the type change re-files each one still on the derived category, and
* the price field is left alone once more than one is linked.
*/
async listIdAndCategoryByReservation(trip_id: number | string, reservation_id: number | string): Promise<{ id: number; category: string }[]> {
async listIdAndCategoryByReservation(
trip_id: number | string,
reservation_id: number | string,
): Promise<{ id: number; category: string }[]> {
return await this.kysely<BudgetKyselyDB>()
.selectFrom('budget_items')
.select(['id', 'category'])
@@ -514,11 +670,19 @@ export class BudgetItemsRepository extends TrekRepository<BudgetItems> {
/** RS54 — `UPDATE budget_items SET reservation_id = ? WHERE id = ?` (binds the reservation id verbatim — a string in the legacy call site, matching parity). */
async setReservationId(id: number | string, reservation_id: number | string): Promise<void> {
await this.kysely<BudgetKyselyDB>().updateTable('budget_items').set({ reservation_id: reservation_id as number }).where('id', '=', id as number).execute();
await this.kysely<BudgetKyselyDB>()
.updateTable('budget_items')
.set({ reservation_id: reservation_id as number })
.where('id', '=', id as number)
.execute();
}
/** UC5 (`UserCleanupService.cleanupUserReferences`) — `UPDATE budget_items SET paid_by_user_id = NULL WHERE paid_by_user_id = ?`. */
async clearPaidByUser(user_id: number): Promise<void> {
await this.kysely<BudgetKyselyDB>().updateTable('budget_items').set({ paid_by_user_id: null }).where('paid_by_user_id', '=', user_id).execute();
await this.kysely<BudgetKyselyDB>()
.updateTable('budget_items')
.set({ paid_by_user_id: null })
.where('paid_by_user_id', '=', user_id)
.execute();
}
}
@@ -1,8 +1,8 @@
import type { BudgetSettlements } from '../entities/BudgetSettlements.entity';
import type { DB } from '../kysely/db';
import { presenceSet } from './_shared/presence-set';
import { type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
import { presenceSet } from './_shared/presence-set';
import type { DB } from '../kysely/db';
/** A bare `budget_settlements` row — every scalar column, incl. the `persist(false)` relation mirrors. */
export interface BudgetSettlementRow {
@@ -50,10 +50,21 @@ export class BudgetSettlementsRepository extends TrekRepository<BudgetSettlement
.innerJoin('users as fu', 'fu.id', 's.from_user_id')
.innerJoin('users as tu', 'tu.id', 's.to_user_id')
.select([
's.id', 's.trip_id', 's.from_user_id', 's.to_user_id', 's.amount', 's.currency', 's.exchange_rate',
's.created_at', 's.settled_at', 's.note', 's.created_by_user_id',
(eb) => eb.fn.coalesce('fu.display_name', 'fu.username').as('from_username'), 'fu.avatar as from_avatar',
(eb) => eb.fn.coalesce('tu.display_name', 'tu.username').as('to_username'), 'tu.avatar as to_avatar',
's.id',
's.trip_id',
's.from_user_id',
's.to_user_id',
's.amount',
's.currency',
's.exchange_rate',
's.created_at',
's.settled_at',
's.note',
's.created_by_user_id',
(eb) => eb.fn.coalesce('fu.display_name', 'fu.username').as('from_username'),
'fu.avatar as from_avatar',
(eb) => eb.fn.coalesce('tu.display_name', 'tu.username').as('to_username'),
'tu.avatar as to_avatar',
]);
}
@@ -98,14 +109,28 @@ export class BudgetSettlementsRepository extends TrekRepository<BudgetSettlement
* `insert` — collides with `TrekRepository`'s own same-named method.
*/
async insertSettlement(row: {
trip_id: number | string; from_user_id: number; to_user_id: number; amount: number;
currency: string | null; exchange_rate: number; settled_at: string | null; note: string | null; created_by_user_id: number | null;
trip_id: number | string;
from_user_id: number;
to_user_id: number;
amount: number;
currency: string | null;
exchange_rate: number;
settled_at: string | null;
note: string | null;
created_by_user_id: number | null;
}): Promise<number> {
const inserted = await this.kysely<BudgetSettlementsWriteKyselyDB>()
.insertInto('budget_settlements')
.values({
trip_id: row.trip_id as number, from_user_id: row.from_user_id, to_user_id: row.to_user_id, amount: row.amount,
currency: row.currency, exchange_rate: row.exchange_rate, settled_at: row.settled_at, note: row.note, created_by_user_id: row.created_by_user_id,
trip_id: row.trip_id as number,
from_user_id: row.from_user_id,
to_user_id: row.to_user_id,
amount: row.amount,
currency: row.currency,
exchange_rate: row.exchange_rate,
settled_at: row.settled_at,
note: row.note,
created_by_user_id: row.created_by_user_id,
})
.returning('id')
.executeTakeFirstOrThrow();
@@ -119,14 +144,24 @@ export class BudgetSettlementsRepository extends TrekRepository<BudgetSettlement
* shape `BudgetItemsRepository.update` (BG33) lands.
*/
/** `id: number`, same Plan 4 Task 8b narrowing as {@link findWithUsers} (its one caller, `applySettlementUpdate`, is only reached with a `toRowId`-parsed id). */
async update(id: number, write: {
from_user_id: number; to_user_id: number; amount: number;
currency?: [present: boolean, value: string | null];
exchange_rate?: [present: boolean, value: number];
settled_at?: [present: boolean, value: string | null];
note?: [present: boolean, value: string | null];
}): Promise<void> {
const data = presenceSet<{ currency: string | null; exchange_rate: number; settled_at: string | null; note: string | null }>({
async update(
id: number,
write: {
from_user_id: number;
to_user_id: number;
amount: number;
currency?: [present: boolean, value: string | null];
exchange_rate?: [present: boolean, value: number];
settled_at?: [present: boolean, value: string | null];
note?: [present: boolean, value: string | null];
},
): Promise<void> {
const data = presenceSet<{
currency: string | null;
exchange_rate: number;
settled_at: string | null;
note: string | null;
}>({
currency: write.currency,
exchange_rate: write.exchange_rate,
settled_at: write.settled_at,
@@ -177,7 +212,7 @@ export class BudgetSettlementsRepository extends TrekRepository<BudgetSettlement
.where('trip_id', '=', trip_id as number)
.where('currency', 'is not', null)
.execute();
return rows.map(r => r.currency as string);
return rows.map((r) => r.currency as string);
}
/**
@@ -196,9 +231,11 @@ export class BudgetSettlementsRepository extends TrekRepository<BudgetSettlement
.where('currency', 'is not', null)
.where('currency', '!=', '')
.where((eb) => eb(eb.fn<string>('upper', ['currency']), '!=', trip_currency))
.where((eb) => eb.or([eb('exchange_rate', 'is', null), eb('exchange_rate', '<=', 0), eb('exchange_rate', '=', 1)]))
.where((eb) =>
eb.or([eb('exchange_rate', 'is', null), eb('exchange_rate', '<=', 0), eb('exchange_rate', '=', 1)]),
)
.execute();
return rows.map(r => r.cur);
return rows.map((r) => r.cur);
}
/** BG91's `budget_settlements` half (`freezeMissingRates`) — `SELECT id FROM budget_settlements WHERE trip_id = ? AND UPPER(currency) = ? AND (exchange_rate IS NULL OR exchange_rate <= 0 OR exchange_rate = 1)`. */
@@ -208,9 +245,11 @@ export class BudgetSettlementsRepository extends TrekRepository<BudgetSettlement
.select('id')
.where('trip_id', '=', trip_id as number)
.where((eb) => eb(eb.fn<string>('upper', ['currency']), '=', currency))
.where((eb) => eb.or([eb('exchange_rate', 'is', null), eb('exchange_rate', '<=', 0), eb('exchange_rate', '=', 1)]))
.where((eb) =>
eb.or([eb('exchange_rate', 'is', null), eb('exchange_rate', '<=', 0), eb('exchange_rate', '=', 1)]),
)
.execute();
return rows.map(r => r.id);
return rows.map((r) => r.id);
}
/** BG92's `budget_settlements` half (`freezeMissingRates`) — `UPDATE budget_settlements SET exchange_rate = ? WHERE trip_id = ? AND UPPER(currency) = ? AND (exchange_rate IS NULL OR exchange_rate <= 0 OR exchange_rate = 1)`, the compare-and-set write. */
@@ -220,7 +259,9 @@ export class BudgetSettlementsRepository extends TrekRepository<BudgetSettlement
.set({ exchange_rate })
.where('trip_id', '=', trip_id as number)
.where((eb) => eb(eb.fn<string>('upper', ['currency']), '=', currency))
.where((eb) => eb.or([eb('exchange_rate', 'is', null), eb('exchange_rate', '<=', 0), eb('exchange_rate', '=', 1)]))
.where((eb) =>
eb.or([eb('exchange_rate', 'is', null), eb('exchange_rate', '<=', 0), eb('exchange_rate', '=', 1)]),
)
.execute();
}
@@ -40,9 +40,7 @@ export class CategoriesRepository extends TrekRepository<Categories> {
* `ORDER BY` in the legacy statement — none added here.
*/
async listIdName(): Promise<{ id: number; name: string }[]> {
return this.qb('c')
.select(['c.id', 'c.name'])
.execute<{ id: number; name: string }[]>('all', false);
return this.qb('c').select(['c.id', 'c.name']).execute<{ id: number; name: string }[]>('all', false);
}
/**
@@ -1,8 +1,8 @@
import type { CollabLinks } from '../entities/CollabLinks.entity';
import { currentTimestamp } from '../dialect/sql-functions';
import type { CollabLinks } from '../entities/CollabLinks.entity';
import type { DB } from '../kysely/db';
import { type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
/** A bare `collab_links` row — every scalar column of the entity, incl. the two `persist(false)` relation mirrors (`trip_id`, `user_id`). */
export interface CollabLinkRow {
@@ -47,17 +47,38 @@ export class CollabLinksRepository extends TrekRepository<CollabLinks> {
* `string | number` id via `toRowId` before calling (rule 15).
*/
async listForTrip(trip_id: number): Promise<CollabLinkJoinRow[]> {
return await this.joinedQuery().where('l.trip_id', '=', trip_id).orderBy('l.pinned', 'desc').orderBy('l.created_at', 'desc').execute();
return await this.joinedQuery()
.where('l.trip_id', '=', trip_id)
.orderBy('l.pinned', 'desc')
.orderBy('l.created_at', 'desc')
.execute();
}
/** CB39 (`updateLink`'s trip-scoping guard) — `SELECT * FROM collab_links WHERE id = ? AND trip_id = ?`. Full row: the falsy-coercion update (CB40) needs the pre-image to fall back onto. */
async findInTrip(id: number, trip_id: number): Promise<CollabLinkRow | undefined> {
return await this.kysely<CollabLinksKyselyDB>().selectFrom('collab_links').selectAll().where('id', '=', id).where('trip_id', '=', trip_id).executeTakeFirst();
return await this.kysely<CollabLinksKyselyDB>()
.selectFrom('collab_links')
.selectAll()
.where('id', '=', id)
.where('trip_id', '=', trip_id)
.executeTakeFirst();
}
/** CB37 (`createLink`) — `INSERT INTO collab_links (trip_id, user_id, title, url, pinned) VALUES (?×5)`. The service trims `title`/`url` before calling (matching the legacy inline `.trim()`). Returns the new row's id. */
async insertLink(row: { trip_id: number | string; user_id: number; title: string; url: string; pinned: number }): Promise<number> {
return await this.insert({ trip: row.trip_id, user: row.user_id, title: row.title, url: row.url, pinned: row.pinned });
async insertLink(row: {
trip_id: number | string;
user_id: number;
title: string;
url: string;
pinned: number;
}): Promise<number> {
return await this.insert({
trip: row.trip_id,
user: row.user_id,
title: row.title,
url: row.url,
pinned: row.pinned,
});
}
/**
@@ -75,7 +96,10 @@ export class CollabLinksRepository extends TrekRepository<CollabLinks> {
*/
async update(id: number, trip_id: number, write: { title: string; url: string; pinned: number }): Promise<void> {
const platform = this.getEntityManager().getPlatform();
await this.nativeUpdate({ id, trip: trip_id }, { title: write.title, url: write.url, pinned: write.pinned, updated_at: currentTimestamp(platform) });
await this.nativeUpdate(
{ id, trip: trip_id },
{ title: write.title, url: write.url, pinned: write.pinned, updated_at: currentTimestamp(platform) },
);
}
/** CB38/CB41 (`createLink`'s post-insert re-select, `updateLink`'s post-write re-select) — `SELECT l.*, u.username FROM collab_links l JOIN users u ON u.id = l.user_id WHERE l.id = ?`, same text at both call sites. */
@@ -1,8 +1,8 @@
import type { CollabMessages } from '../entities/CollabMessages.entity';
import type { DB } from '../kysely/db';
import type { TripFileRow } from './TripFiles.repository';
import { type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
/** A bare `collab_messages` row — every scalar column of the entity, incl. the three `persist(false)` mirrors (`trip_id`, `user_id`, `reply_to`). */
export interface CollabMessageRow {
@@ -142,12 +142,23 @@ export class CollabMessagesRepository extends TrekRepository<CollabMessages> {
* .deleteMessage` docstring for how that pre-existing gap is preserved.
*/
async findInTrip(id: number, trip_id: number): Promise<CollabMessageRow | undefined> {
return await this.kysely<CollabMessagesKyselyDB>().selectFrom('collab_messages').selectAll().where('id', '=', id).where('trip_id', '=', trip_id).executeTakeFirst();
return await this.kysely<CollabMessagesKyselyDB>()
.selectFrom('collab_messages')
.selectAll()
.where('id', '=', id)
.where('trip_id', '=', trip_id)
.executeTakeFirst();
}
/** CB47 (`createMessage`'s reply-target validation) — `SELECT id FROM collab_messages WHERE id = ? AND trip_id = ? AND deleted = 0`. A soft-deleted message is gone as far as anyone replying is concerned. */
async findActiveInTrip(id: number, trip_id: number): Promise<{ id: number } | undefined> {
return await this.kysely<CollabMessagesKyselyDB>().selectFrom('collab_messages').select(['id']).where('id', '=', id).where('trip_id', '=', trip_id).where('deleted', '=', 0).executeTakeFirst();
return await this.kysely<CollabMessagesKyselyDB>()
.selectFrom('collab_messages')
.select(['id'])
.where('id', '=', id)
.where('trip_id', '=', trip_id)
.where('deleted', '=', 0)
.executeTakeFirst();
}
/** CB44 (`countMessages`) — `SELECT COUNT(*) as cnt FROM collab_messages WHERE trip_id = ?`. */
@@ -156,7 +167,12 @@ export class CollabMessagesRepository extends TrekRepository<CollabMessages> {
}
/** CB48 (`createMessage`, inside its transaction) — `INSERT INTO collab_messages (trip_id, user_id, text, reply_to) VALUES (?×4)`. Returns the new row's id. */
async insertMessage(trip_id: number | string, user_id: number, text: string, reply_to: number | null): Promise<number> {
async insertMessage(
trip_id: number | string,
user_id: number,
text: string,
reply_to: number | null,
): Promise<number> {
return await this.insert({ trip: trip_id, user: user_id, text, reply_to });
}
@@ -188,7 +204,15 @@ export class CollabMessagesRepository extends TrekRepository<CollabMessages> {
* `INSERT INTO trip_files (trip_id, message_id, filename, original_name,
* file_size, mime_type, uploaded_by) VALUES (?×7)`.
*/
async insertAttachmentForMessage(row: { trip_id: number | string; message_id: number | string; filename: string; original_name: string; file_size: number; mime_type: string; uploaded_by: number }): Promise<void> {
async insertAttachmentForMessage(row: {
trip_id: number | string;
message_id: number | string;
filename: string;
original_name: string;
file_size: number;
mime_type: string;
uploaded_by: number;
}): Promise<void> {
await this.kysely<MessageAttachmentInsertKyselyDB>()
.insertInto('trip_files')
.values({
@@ -205,11 +229,20 @@ export class CollabMessagesRepository extends TrekRepository<CollabMessages> {
/** CB52 (`deleteMessage`'s pre-tx storage-cleanup list) — `SELECT filename FROM trip_files WHERE message_id = ? AND trip_id = ?`, run BEFORE the transaction (the legacy ordering). */
async listFilenamesForMessage(message_id: number, trip_id: number): Promise<{ filename: string }[]> {
return await this.kysely<MessageAttachmentsKyselyDB>().selectFrom('trip_files').select(['filename']).where('message_id', '=', message_id).where('trip_id', '=', trip_id).execute();
return await this.kysely<MessageAttachmentsKyselyDB>()
.selectFrom('trip_files')
.select(['filename'])
.where('message_id', '=', message_id)
.where('trip_id', '=', trip_id)
.execute();
}
/** CB53 (`deleteMessage`, inside its transaction, before CB54) — `DELETE FROM trip_files WHERE message_id = ? AND trip_id = ?`. */
async deleteAttachmentsForMessage(message_id: number, trip_id: number): Promise<void> {
await this.kysely<MessageAttachmentsKyselyDB>().deleteFrom('trip_files').where('message_id', '=', message_id).where('trip_id', '=', trip_id).execute();
await this.kysely<MessageAttachmentsKyselyDB>()
.deleteFrom('trip_files')
.where('message_id', '=', message_id)
.where('trip_id', '=', trip_id)
.execute();
}
}
@@ -1,9 +1,9 @@
import type { CollabNotes } from '../entities/CollabNotes.entity';
import { currentTimestamp } from '../dialect/sql-functions';
import type { CollabNotes } from '../entities/CollabNotes.entity';
import type { DB } from '../kysely/db';
import type { TripFileRow } from './TripFiles.repository';
import { type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
/** A bare `collab_notes` row — every scalar column of the entity, incl. the two `persist(false)` relation mirrors (`trip_id`, `user_id`). */
export interface CollabNoteRow {
@@ -98,12 +98,21 @@ export class CollabNotesRepository extends TrekRepository<CollabNotes> {
* this query at all.
*/
async listForTrip(trip_id: number): Promise<CollabNoteJoinRow[]> {
return await this.joinedQuery().where('n.trip_id', '=', trip_id).orderBy('n.pinned', 'desc').orderBy('n.updated_at', 'desc').execute();
return await this.joinedQuery()
.where('n.trip_id', '=', trip_id)
.orderBy('n.pinned', 'desc')
.orderBy('n.updated_at', 'desc')
.execute();
}
/** CB10/CB13/CB17 (`updateNote`/`deleteNote`/`addNoteFile`'s shared trip-scoping guard) — `SELECT * FROM collab_notes WHERE id = ? AND trip_id = ?`, same text at all three call sites. */
async findInTrip(id: number, trip_id: number): Promise<CollabNoteRow | undefined> {
return await this.kysely<CollabNotesKyselyDB>().selectFrom('collab_notes').selectAll().where('id', '=', id).where('trip_id', '=', trip_id).executeTakeFirst();
return await this.kysely<CollabNotesKyselyDB>()
.selectFrom('collab_notes')
.selectAll()
.where('id', '=', id)
.where('trip_id', '=', trip_id)
.executeTakeFirst();
}
/** CB9/CB12 (`createNote`'s post-insert re-select, `updateNote`'s post-write re-select) — `SELECT n.*, u.username, u.avatar FROM collab_notes n JOIN users u ON n.user_id = u.id WHERE n.id = ?`, no trip filter (the caller already knows `id` is in-scope, having just written it). */
@@ -117,7 +126,16 @@ export class CollabNotesRepository extends TrekRepository<CollabNotes> {
}
/** CB8 (`createNote`) — `INSERT INTO collab_notes (trip_id, user_id, title, content, category, color, website, pinned) VALUES (?×8)`. The service resolves the `|| null`/`|| 'General'`/`|| '#6366f1'` defaults before calling (D2's split). Returns the new row's id. */
async insertNote(row: { trip_id: number | string; user_id: number; title: string; content: string | null; category: string; color: string; website: string | null; pinned: number }): Promise<number> {
async insertNote(row: {
trip_id: number | string;
user_id: number;
title: string;
content: string | null;
category: string;
color: string;
website: string | null;
pinned: number;
}): Promise<number> {
return await this.insert({
trip: row.trip_id,
user: row.user_id,
@@ -150,17 +168,30 @@ export class CollabNotesRepository extends TrekRepository<CollabNotes> {
* `CASE` helper, and this class docstring records that choice for
* whichever task reads it next.
*/
async update(id: number, write: { title: string; content: string | null; category: string | null; color: string | null; pinned: number | null; website: string | null }): Promise<void> {
async update(
id: number,
write: {
title: string;
content: string | null;
category: string | null;
color: string | null;
pinned: number | null;
website: string | null;
},
): Promise<void> {
const platform = this.getEntityManager().getPlatform();
await this.nativeUpdate({ id }, {
title: write.title,
content: write.content,
category: write.category,
color: write.color,
pinned: write.pinned,
website: write.website,
updated_at: currentTimestamp(platform),
});
await this.nativeUpdate(
{ id },
{
title: write.title,
content: write.content,
category: write.category,
color: write.color,
pinned: write.pinned,
website: write.website,
updated_at: currentTimestamp(platform),
},
);
}
/** CB16 (`deleteNote`, inside its transaction, after CB15's attachment sweep) — `DELETE FROM collab_notes WHERE id = ?`. */
@@ -191,7 +222,11 @@ export class CollabNotesRepository extends TrekRepository<CollabNotes> {
/** CB14 (`deleteNote`'s pre-tx storage-cleanup list) — `SELECT id, filename FROM trip_files WHERE note_id = ?`, run BEFORE the transaction (the legacy ordering: the storage deletes happen outside/before the DB transaction). */
async listFilenamesForNote(note_id: number): Promise<{ id: number; filename: string }[]> {
return await this.kysely<NoteAttachmentsKyselyDB>().selectFrom('trip_files').select(['id', 'filename']).where('note_id', '=', note_id).execute();
return await this.kysely<NoteAttachmentsKyselyDB>()
.selectFrom('trip_files')
.select(['id', 'filename'])
.where('note_id', '=', note_id)
.execute();
}
/** CB15 (`deleteNote`, inside its transaction, before CB16) — `DELETE FROM trip_files WHERE note_id = ?`. */
@@ -206,10 +241,24 @@ export class CollabNotesRepository extends TrekRepository<CollabNotes> {
* supported engine answers, unlike `InsertResult.insertId`) for CB19's
* re-select.
*/
async insertAttachmentForNote(row: { trip_id: number | string; note_id: number | string; filename: string; original_name: string; file_size: number; mime_type: string }): Promise<number> {
async insertAttachmentForNote(row: {
trip_id: number | string;
note_id: number | string;
filename: string;
original_name: string;
file_size: number;
mime_type: string;
}): Promise<number> {
const inserted = await this.kysely<NoteAttachmentInsertKyselyDB>()
.insertInto('trip_files')
.values({ trip_id: row.trip_id as number, note_id: row.note_id as number, filename: row.filename, original_name: row.original_name, file_size: row.file_size, mime_type: row.mime_type })
.values({
trip_id: row.trip_id as number,
note_id: row.note_id as number,
filename: row.filename,
original_name: row.original_name,
file_size: row.file_size,
mime_type: row.mime_type,
})
.returning('id')
.executeTakeFirstOrThrow();
return inserted.id;
@@ -217,7 +266,11 @@ export class CollabNotesRepository extends TrekRepository<CollabNotes> {
/** CB19 (`addNoteFile`'s re-select, immediately after {@link insertAttachmentForNote}) — `SELECT * FROM trip_files WHERE id = ?`, unscoped (the caller just wrote this exact id). */
async findAttachmentById(id: number): Promise<TripFileRow | undefined> {
return await this.kysely<NoteAttachmentsKyselyDB>().selectFrom('trip_files').selectAll().where('id', '=', id).executeTakeFirst();
return await this.kysely<NoteAttachmentsKyselyDB>()
.selectFrom('trip_files')
.selectAll()
.where('id', '=', id)
.executeTakeFirst();
}
/**
@@ -1,7 +1,7 @@
import type { CollabPolls } from '../entities/CollabPolls.entity';
import type { DB } from '../kysely/db';
import { type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
/** A bare `collab_polls` row — every scalar column of the entity, incl. the two `persist(false)` relation mirrors (`trip_id`, `user_id`). */
export interface CollabPollRow {
@@ -45,7 +45,12 @@ export class CollabPollsRepository extends TrekRepository<CollabPolls> {
/** CB25 (`listPolls`) — `SELECT id FROM collab_polls WHERE trip_id = ? ORDER BY created_at DESC`. */
async listIdsForTrip(trip_id: number): Promise<number[]> {
const rows = await this.kysely<CollabPollsKyselyDB>().selectFrom('collab_polls').select(['id']).where('trip_id', '=', trip_id).orderBy('created_at', 'desc').execute();
const rows = await this.kysely<CollabPollsKyselyDB>()
.selectFrom('collab_polls')
.select(['id'])
.where('trip_id', '=', trip_id)
.orderBy('created_at', 'desc')
.execute();
return rows.map((r) => r.id);
}
@@ -55,12 +60,31 @@ export class CollabPollsRepository extends TrekRepository<CollabPolls> {
* text at all three call sites.
*/
async findInTrip(id: number, trip_id: number): Promise<CollabPollRow | undefined> {
return await this.kysely<CollabPollsKyselyDB>().selectFrom('collab_polls').selectAll().where('id', '=', id).where('trip_id', '=', trip_id).executeTakeFirst();
return await this.kysely<CollabPollsKyselyDB>()
.selectFrom('collab_polls')
.selectAll()
.where('id', '=', id)
.where('trip_id', '=', trip_id)
.executeTakeFirst();
}
/** CB26 (`createPoll`) — `INSERT INTO collab_polls (trip_id, user_id, question, options, multiple, deadline) VALUES (?×6)`. Returns the new row's id. */
async insertPoll(row: { trip_id: number | string; user_id: number; question: string; options: string; multiple: number; deadline: string | null }): Promise<number> {
return await this.insert({ trip: row.trip_id, user: row.user_id, question: row.question, options: row.options, multiple: row.multiple, deadline: row.deadline });
async insertPoll(row: {
trip_id: number | string;
user_id: number;
question: string;
options: string;
multiple: number;
deadline: string | null;
}): Promise<number> {
return await this.insert({
trip: row.trip_id,
user: row.user_id,
question: row.question,
options: row.options,
multiple: row.multiple,
deadline: row.deadline,
});
}
/** CB33 (`closePoll`) — `UPDATE collab_polls SET closed = 1 WHERE id = ?`. */
@@ -1,7 +1,7 @@
import type { CollectionLabels } from '../entities/CollectionLabels.entity';
import { lower, lowerParam } from '../dialect/sql-functions';
import { TrekRepository } from './_shared/trek-repository';
import type { CollectionLabels } from '../entities/CollectionLabels.entity';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
/** `collection_labels` — `loadLabelsByCollection`'s (CL7) shape. */
export interface CollectionLabelRow {
@@ -61,7 +61,11 @@ export class CollectionLabelsRepository extends TrekRepository<CollectionLabels>
/** CL20 (`insertImportedLabel`) — `INSERT INTO collection_labels (collection_id, name, color, sort_order) VALUES (?,?,?,?)`. Returns the new row's id. Dup text also `createLabel` (Task 2's own call site). */
async insertLabel(row: { collection_id: number; name: string; color: string; sort_order: number }): Promise<number> {
const inserted = await this.kysely<CollectionLabelsInsertKyselyDB>().insertInto('collection_labels').values(row).returning('id').executeTakeFirstOrThrow();
const inserted = await this.kysely<CollectionLabelsInsertKyselyDB>()
.insertInto('collection_labels')
.values(row)
.returning('id')
.executeTakeFirstOrThrow();
return inserted.id;
}
@@ -78,7 +82,11 @@ export class CollectionLabelsRepository extends TrekRepository<CollectionLabels>
* applies here exactly as it does to a bare `.select([...])`.
*/
async collectionIdOf(labelId: number): Promise<number | undefined> {
const row = await this.db_().selectFrom('collection_labels').select('collection_id').where('id', '=', labelId).executeTakeFirst();
const row = await this.db_()
.selectFrom('collection_labels')
.select('collection_id')
.where('id', '=', labelId)
.executeTakeFirst();
return row?.collection_id;
}
@@ -122,7 +130,10 @@ export class CollectionLabelsRepository extends TrekRepository<CollectionLabels>
}
/** CL76 (`updateLabel`) — the allow-listed dynamic `UPDATE collection_labels SET ... WHERE id=?`. No `updated_at` stamp — the table has no such column, and the legacy statement never wrote one. */
async updateFields(labelId: number, write: Partial<{ name: string; color: string; sort_order: number }>): Promise<void> {
async updateFields(
labelId: number,
write: Partial<{ name: string; color: string; sort_order: number }>,
): Promise<void> {
if (Object.keys(write).length === 0) return;
await this.nativeUpdate({ id: labelId }, write);
}
@@ -1,6 +1,6 @@
import type { CollectionMembers } from '../entities/CollectionMembers.entity';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
/** `buildMembers`'s owner row — `collections` joined to `users` (CL12). */
export interface CollectionOwnerMemberRow {
@@ -108,7 +108,10 @@ export class CollectionMembersRepository extends TrekRepository<CollectionMember
// -------------------------------------------------------------------------
/** CL80 (`sendInvite`) — `SELECT id, status FROM collection_members WHERE collection_id=? AND user_id=?` (dup/pending guard). */
async findByCollectionAndUser(collectionId: number, userId: number): Promise<{ id: number; status: string } | undefined> {
async findByCollectionAndUser(
collectionId: number,
userId: number,
): Promise<{ id: number; status: string } | undefined> {
const row = await this.findOne({ collection: collectionId, user: userId }, { fields: ['id', 'status'] });
return row ?? undefined;
}
@@ -1,6 +1,6 @@
import type { CollectionPlaceRatings } from '../entities/CollectionPlaceRatings.entity';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
/**
* `collection_place_ratings` (Plan 3h Task 2, part B — #1435's per-voter
@@ -1,8 +1,8 @@
import type { CollectionPlaces } from '../entities/CollectionPlaces.entity';
import { currentTimestamp } from '../dialect/sql-functions';
import type { CollectionPlaces } from '../entities/CollectionPlaces.entity';
import type { DB } from '../kysely/db';
import type { CollectionPlaceRow } from './Collections.repository';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
/**
* `collection_places` (Plan 3h Task 2, part B — saved places CRUD, dedup,
@@ -196,7 +196,10 @@ export class CollectionPlacesRepository extends TrekRepository<CollectionPlaces>
/** CL50 (`updatePlace`'s move branch, TX, dup text also `setPlaceLabels`) — `DELETE FROM collection_place_labels WHERE collection_place_id=?`. Pivot table, Kysely. */
async deleteLabelAssignments(collectionPlaceId: number): Promise<void> {
await this.db_().deleteFrom('collection_place_labels').where('collection_place_id', '=', collectionPlaceId).execute();
await this.db_()
.deleteFrom('collection_place_labels')
.where('collection_place_id', '=', collectionPlaceId)
.execute();
}
// ---------------------------------------------------------------------
@@ -256,7 +259,14 @@ export class CollectionPlacesRepository extends TrekRepository<CollectionPlaces>
async matchingByTripSource(
collectionIds: number[],
tripId: number,
place: { id: number; lat: number | null; lng: number | null; google_place_id: string | null; google_ftid: string | null; osm_id: string | null },
place: {
id: number;
lat: number | null;
lng: number | null;
google_place_id: string | null;
google_ftid: string | null;
osm_id: string | null;
},
tolerance: number,
): Promise<{ id: number }[]> {
if (collectionIds.length === 0) return [];
@@ -309,8 +319,23 @@ export class CollectionPlacesRepository extends TrekRepository<CollectionPlaces>
return await this.db_()
.selectFrom('collection_places')
.select([
'id', 'collection_id', 'name', 'description', 'lat', 'lng', 'address', 'category_id', 'price', 'currency',
'notes', 'image_url', 'google_place_id', 'google_ftid', 'osm_id', 'website', 'phone',
'id',
'collection_id',
'name',
'description',
'lat',
'lng',
'address',
'category_id',
'price',
'currency',
'notes',
'image_url',
'google_place_id',
'google_ftid',
'osm_id',
'website',
'phone',
])
.where('id', '=', id)
.executeTakeFirst();
@@ -322,7 +347,11 @@ export class CollectionPlacesRepository extends TrekRepository<CollectionPlaces>
/** CL67 (`copyToTrip`, loop, TX) — `SELECT tag_id FROM collection_place_tags WHERE collection_place_id=?`. Pivot table, Kysely. */
async tagIdsFor(collectionPlaceId: number): Promise<number[]> {
const rows = await this.db_().selectFrom('collection_place_tags').select('tag_id').where('collection_place_id', '=', collectionPlaceId).execute();
const rows = await this.db_()
.selectFrom('collection_place_tags')
.select('tag_id')
.where('collection_place_id', '=', collectionPlaceId)
.execute();
return rows.map((r) => r.tag_id);
}
@@ -433,7 +462,12 @@ export class CollectionPlacesRepository extends TrekRepository<CollectionPlaces>
* `PlacesRepository.existsByImageUrl` for its own table.
*/
async existsByImageUrl(imageUrl: string): Promise<boolean> {
const row = await this.db_().selectFrom('collection_places').select('id').where('image_url', '=', imageUrl).limit(1).executeTakeFirst();
const row = await this.db_()
.selectFrom('collection_places')
.select('id')
.where('image_url', '=', imageUrl)
.limit(1)
.executeTakeFirst();
return !!row;
}
@@ -1,7 +1,7 @@
import type { Collections } from '../entities/Collections.entity';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
import { dbNow } from '../types';
import { TrekRepository } from './_shared/trek-repository';
/** `collections` — every scalar column, `getCollectionRow`'s (CL14) `SELECT *` shape. */
export interface CollectionRow {
@@ -145,7 +145,11 @@ export class CollectionsRepository extends TrekRepository<Collections> {
/** CL5 (`ownerOf`) — `SELECT owner_id FROM collections WHERE id=?`. */
async ownerId(id: number): Promise<number | undefined> {
const row = await this.readDb().selectFrom('collections').select('owner_id').where('id', '=', id).executeTakeFirst();
const row = await this.readDb()
.selectFrom('collections')
.select('owner_id')
.where('id', '=', id)
.executeTakeFirst();
return row?.owner_id;
}
@@ -189,7 +193,11 @@ export class CollectionsRepository extends TrekRepository<Collections> {
links: string | null;
sort_order: number;
}): Promise<number> {
const inserted = await this.insertDb().insertInto('collections').values(row).returning('id').executeTakeFirstOrThrow();
const inserted = await this.insertDb()
.insertInto('collections')
.values(row)
.returning('id')
.executeTakeFirstOrThrow();
return inserted.id;
}
@@ -215,18 +223,30 @@ export class CollectionsRepository extends TrekRepository<Collections> {
}>,
): Promise<void> {
if (Object.keys(write).length === 0) return;
await this.readDb().updateTable('collections').set({ ...write, updated_at: dbNow() }).where('id', '=', id).execute();
await this.readDb()
.updateTable('collections')
.set({ ...write, updated_at: dbNow() })
.where('id', '=', id)
.execute();
}
/** CL31 (`setCollectionCover`) — `SELECT cover_image FROM collections WHERE id=?`. */
async coverImage(id: number): Promise<string | null | undefined> {
const row = await this.readDb().selectFrom('collections').select('cover_image').where('id', '=', id).executeTakeFirst();
const row = await this.readDb()
.selectFrom('collections')
.select('cover_image')
.where('id', '=', id)
.executeTakeFirst();
return row?.cover_image;
}
/** CL32 (`setCollectionCover`) — `UPDATE collections SET cover_image=?, updated_at=<dbNow()> WHERE id=?`. */
async setCoverImage(id: number, coverUrl: string | null): Promise<void> {
await this.readDb().updateTable('collections').set({ cover_image: coverUrl, updated_at: dbNow() }).where('id', '=', id).execute();
await this.readDb()
.updateTable('collections')
.set({ cover_image: coverUrl, updated_at: dbNow() })
.where('id', '=', id)
.execute();
}
/** CL35 (`deleteCollection`) — `DELETE FROM collections WHERE id=?` (CASCADE drops members + places + tags). */
@@ -269,11 +289,35 @@ export class CollectionsRepository extends TrekRepository<Collections> {
.selectFrom('collection_places as cp')
.leftJoin('categories as c', 'c.id', 'cp.category_id')
.select([
'cp.id', 'cp.collection_id', 'cp.owner_id', 'cp.saved_by', 'cp.name', 'cp.description', 'cp.lat', 'cp.lng',
'cp.address', 'cp.category_id', 'cp.price', 'cp.currency', 'cp.notes', 'cp.image_url', 'cp.google_place_id',
'cp.google_ftid', 'cp.osm_id', 'cp.website', 'cp.phone', 'cp.status', 'cp.source_trip_id', 'cp.source_place_id',
'cp.links', 'cp.sort_order', 'cp.created_at', 'cp.updated_at',
'c.name as category_name', 'c.color as category_color', 'c.icon as category_icon',
'cp.id',
'cp.collection_id',
'cp.owner_id',
'cp.saved_by',
'cp.name',
'cp.description',
'cp.lat',
'cp.lng',
'cp.address',
'cp.category_id',
'cp.price',
'cp.currency',
'cp.notes',
'cp.image_url',
'cp.google_place_id',
'cp.google_ftid',
'cp.osm_id',
'cp.website',
'cp.phone',
'cp.status',
'cp.source_trip_id',
'cp.source_place_id',
'cp.links',
'cp.sort_order',
'cp.created_at',
'cp.updated_at',
'c.name as category_name',
'c.color as category_color',
'c.icon as category_icon',
])
.where('cp.id', '=', id)
.executeTakeFirst();
@@ -290,11 +334,35 @@ export class CollectionsRepository extends TrekRepository<Collections> {
.selectFrom('collection_places as cp')
.leftJoin('categories as c', 'c.id', 'cp.category_id')
.select([
'cp.id', 'cp.collection_id', 'cp.owner_id', 'cp.saved_by', 'cp.name', 'cp.description', 'cp.lat', 'cp.lng',
'cp.address', 'cp.category_id', 'cp.price', 'cp.currency', 'cp.notes', 'cp.image_url', 'cp.google_place_id',
'cp.google_ftid', 'cp.osm_id', 'cp.website', 'cp.phone', 'cp.status', 'cp.source_trip_id', 'cp.source_place_id',
'cp.links', 'cp.sort_order', 'cp.created_at', 'cp.updated_at',
'c.name as category_name', 'c.color as category_color', 'c.icon as category_icon',
'cp.id',
'cp.collection_id',
'cp.owner_id',
'cp.saved_by',
'cp.name',
'cp.description',
'cp.lat',
'cp.lng',
'cp.address',
'cp.category_id',
'cp.price',
'cp.currency',
'cp.notes',
'cp.image_url',
'cp.google_place_id',
'cp.google_ftid',
'cp.osm_id',
'cp.website',
'cp.phone',
'cp.status',
'cp.source_trip_id',
'cp.source_place_id',
'cp.links',
'cp.sort_order',
'cp.created_at',
'cp.updated_at',
'c.name as category_name',
'c.color as category_color',
'c.icon as category_icon',
])
.where('cp.collection_id', '=', collectionId)
.orderBy('cp.sort_order')
@@ -304,7 +372,11 @@ export class CollectionsRepository extends TrekRepository<Collections> {
/** CL11 (`collectionIdOfPlace`) — `SELECT collection_id FROM collection_places WHERE id=?`. */
async collectionIdOfPlace(placeId: number): Promise<number | undefined> {
const row = await this.placesReadDb().selectFrom('collection_places').select('collection_id').where('id', '=', placeId).executeTakeFirst();
const row = await this.placesReadDb()
.selectFrom('collection_places')
.select('collection_id')
.where('id', '=', placeId)
.executeTakeFirst();
return row?.collection_id;
}
@@ -396,7 +468,11 @@ export class CollectionsRepository extends TrekRepository<Collections> {
links: string | null;
sort_order: number;
}): Promise<number> {
const inserted = await this.placesWriteDb().insertInto('collection_places').values(row).returning('id').executeTakeFirstOrThrow();
const inserted = await this.placesWriteDb()
.insertInto('collection_places')
.values(row)
.returning('id')
.executeTakeFirstOrThrow();
return inserted.id;
}
@@ -418,14 +494,23 @@ export class CollectionsRepository extends TrekRepository<Collections> {
.selectFrom('collection_places')
.select(['id', 'name'])
.where('collection_id', '=', collectionId)
.where((eb) => eb.or([eb('google_place_id', '=', externalId), eb('google_ftid', '=', externalId), eb('osm_id', '=', externalId)]))
.where((eb) =>
eb.or([
eb('google_place_id', '=', externalId),
eb('google_ftid', '=', externalId),
eb('osm_id', '=', externalId),
]),
)
.orderBy('id', 'asc')
.limit(1)
.executeTakeFirst();
}
/** CL26 (`findDuplicateCollectionPlace`, name branch) — `SELECT id,name FROM collection_places WHERE collection_id=? AND lower(trim(name))=? ORDER BY id ASC LIMIT 1`. `normalizedName` is already `lower(trim(...))`-shaped by the caller (`_shared/../dialect/sql-functions.ts`'s `lowerTrim`/`lowerTrimParam` precedent). */
async findDuplicateByName(collectionId: number, normalizedName: string): Promise<{ id: number; name: string } | undefined> {
async findDuplicateByName(
collectionId: number,
normalizedName: string,
): Promise<{ id: number; name: string } | undefined> {
return await this.placesReadDb()
.selectFrom('collection_places')
.select(['id', 'name'])
@@ -60,7 +60,17 @@ export class DawarichConnectionsRepository extends TrekRepository<DawarichConnec
*/
async findRow(userId: number): Promise<DawarichConnectionRow | null> {
const row = await this.qb('c')
.select(['c.user', 'c.url', 'c.api_key', 'c.allow_insecure_tls', 'c.sync_enabled', 'c.last_sync_at', 'c.last_sync_state', 'c.last_sync_error', 'c.capabilities'])
.select([
'c.user',
'c.url',
'c.api_key',
'c.allow_insecure_tls',
'c.sync_enabled',
'c.last_sync_at',
'c.last_sync_state',
'c.last_sync_error',
'c.capabilities',
])
.where({ user: userId })
.execute<DawarichConnectionRow | undefined>('get', false);
return row ?? null;
@@ -109,7 +119,10 @@ export class DawarichConnectionsRepository extends TrekRepository<DawarichConnec
* conflict and default to NULL/`'never'` on a genuine INSERT, matching the
* legacy statement's own column list exactly.
*/
async upsertConnection(userId: number, data: { url: string | null; allowInsecureTls: boolean; syncEnabled: boolean }): Promise<void> {
async upsertConnection(
userId: number,
data: { url: string | null; allowInsecureTls: boolean; syncEnabled: boolean },
): Promise<void> {
const platform = this.getEntityManager().getPlatform();
await this.upsert(
{
@@ -119,7 +132,11 @@ export class DawarichConnectionsRepository extends TrekRepository<DawarichConnec
sync_enabled: data.syncEnabled ? 1 : 0,
updated_at: currentTimestamp(platform),
},
{ onConflictFields: ['user'], onConflictAction: 'merge', onConflictMergeFields: ['url', 'allow_insecure_tls', 'sync_enabled', 'updated_at'] },
{
onConflictFields: ['user'],
onConflictAction: 'merge',
onConflictMergeFields: ['url', 'allow_insecure_tls', 'sync_enabled', 'updated_at'],
},
);
}
@@ -139,7 +156,10 @@ export class DawarichConnectionsRepository extends TrekRepository<DawarichConnec
* NULL, last_sync_at = NULL WHERE user_id = ?`.
*/
async resetSyncState(userId: number): Promise<void> {
await this.nativeUpdate({ user: userId }, { capabilities: null, last_sync_state: 'never', last_sync_error: null, last_sync_at: null });
await this.nativeUpdate(
{ user: userId },
{ capabilities: null, last_sync_state: 'never', last_sync_error: null, last_sync_at: null },
);
}
/**
@@ -151,7 +171,10 @@ export class DawarichConnectionsRepository extends TrekRepository<DawarichConnec
* UPDATE with five `SET` clauses).
*/
async clearForRemovedUrl(userId: number): Promise<void> {
await this.nativeUpdate({ user: userId }, { api_key: null, capabilities: null, last_sync_state: 'never', last_sync_error: null, last_sync_at: null });
await this.nativeUpdate(
{ user: userId },
{ api_key: null, capabilities: null, last_sync_state: 'never', last_sync_error: null, last_sync_at: null },
);
}
/**
@@ -168,7 +191,10 @@ export class DawarichConnectionsRepository extends TrekRepository<DawarichConnec
/** DWC10 — `storeCapabilities`: `UPDATE dawarich_connections SET capabilities = ?, updated_at = CURRENT_TIMESTAMP WHERE user_id = ?`. */
async storeCapabilities(userId: number, capabilitiesJson: string): Promise<void> {
const platform = this.getEntityManager().getPlatform();
await this.nativeUpdate({ user: userId }, { capabilities: capabilitiesJson, updated_at: currentTimestamp(platform) });
await this.nativeUpdate(
{ user: userId },
{ capabilities: capabilitiesJson, updated_at: currentTimestamp(platform) },
);
}
/**
@@ -177,11 +203,19 @@ export class DawarichConnectionsRepository extends TrekRepository<DawarichConnec
* CURRENT_TIMESTAMP WHERE user_id = ?`. **NON-HTTP ENTRYPOINT** — called
* after every cron sync.
*/
async recordSyncResult(userId: number, data: { lastSyncAt: string; state: string; error: string | null }): Promise<void> {
async recordSyncResult(
userId: number,
data: { lastSyncAt: string; state: string; error: string | null },
): Promise<void> {
const platform = this.getEntityManager().getPlatform();
await this.nativeUpdate(
{ user: userId },
{ last_sync_at: data.lastSyncAt, last_sync_state: data.state, last_sync_error: data.error, updated_at: currentTimestamp(platform) },
{
last_sync_at: data.lastSyncAt,
last_sync_state: data.state,
last_sync_error: data.error,
updated_at: currentTimestamp(platform),
},
);
}
@@ -1,8 +1,8 @@
import { coalesceParam, columnRef } from '../dialect/sql-functions';
import type { DawarichVisitSuggestions } from '../entities/DawarichVisitSuggestions.entity';
import type { DB } from '../kysely/db';
import { type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
/** `dawarich_visit_suggestions` — every scalar column, DWS6/DSY3's `SELECT *` shape. */
export interface SuggestionRow {
@@ -1,8 +1,8 @@
import type { DayAccommodations } from '../entities/DayAccommodations.entity';
import { coalesceOverride, columnRef } from '../dialect/sql-functions';
import type { DayAccommodations } from '../entities/DayAccommodations.entity';
import type { DB } from '../kysely/db';
import { type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
/**
* A `day_accommodations` row exactly as AC34 (`AccommodationsService
@@ -103,7 +103,12 @@ export class DayAccommodationsRepository extends TrekRepository<DayAccommodation
* raw fragment value (`DayAssignmentsRepository.shiftOrderFrom`'s
* precedent).
*/
async patchTimes(id: number, check_in: string | null, check_in_end: string | null, check_out: string | null): Promise<void> {
async patchTimes(
id: number,
check_in: string | null,
check_in_end: string | null,
check_out: string | null,
): Promise<void> {
const platform = this.getEntityManager().getPlatform();
await this.qb()
.update({
@@ -156,22 +161,28 @@ export class DayAccommodationsRepository extends TrekRepository<DayAccommodation
* verbatim (the `PlacesRepository.updatePlace`/PL11 precedent: no SQL-side
* COALESCE here, the legacy statement itself has none for these columns).
*/
async updateFromBooking(id: number, write: {
place_id: number | null;
start_day_id: number;
end_day_id: number;
check_in: string | null;
check_out: string | null;
confirmation: string | null;
}): Promise<void> {
await this.nativeUpdate({ id }, {
place: write.place_id,
startDay: write.start_day_id,
endDay: write.end_day_id,
check_in: write.check_in,
check_out: write.check_out,
confirmation: write.confirmation,
});
async updateFromBooking(
id: number,
write: {
place_id: number | null;
start_day_id: number;
end_day_id: number;
check_in: string | null;
check_out: string | null;
confirmation: string | null;
},
): Promise<void> {
await this.nativeUpdate(
{ id },
{
place: write.place_id,
startDay: write.start_day_id,
endDay: write.end_day_id,
check_in: write.check_in,
check_out: write.check_out,
confirmation: write.confirmation,
},
);
}
/** RS47 — `DELETE FROM day_accommodations WHERE id = ? AND trip_id = ?`, run AFTER `accommodations.dropStayStops` (ordering load-bearing, kept in the service). `id`/`trip_id: number` (typed filter, program rule 23; rule 21 — the SAME `toRowId`-parsed trip id `existsInTrip`'s gate read used). */
@@ -216,7 +227,14 @@ export class DayAccommodationsRepository extends TrekRepository<DayAccommodation
// means an unqualified `id` key is ambiguous between `a.id` and `p.id`.
return await this.qb('a')
.leftJoin('a.place', 'p')
.select(['a.*', 'p.name as place_name', 'p.address as place_address', 'p.image_url as place_image', 'p.lat as place_lat', 'p.lng as place_lng'])
.select([
'a.*',
'p.name as place_name',
'p.address as place_address',
'p.image_url as place_image',
'p.lat as place_lat',
'p.lng as place_lng',
])
.where({ 'a.id': id })
.execute<DayAccommodationWithPlaceRow | undefined>('get', false);
}
@@ -307,26 +325,32 @@ export class DayAccommodationsRepository extends TrekRepository<DayAccommodation
* (note: NO `|| null` here, unlike AC30 — the legacy statement itself has
* none for these columns, so `''` is stored as `''`).
*/
async updateStay(id: number, write: {
place_id: number | null;
start_day_id: number;
end_day_id: number;
check_in: string | null;
check_in_end: string | null;
check_out: string | null;
confirmation: string | null;
notes: string | null;
}): Promise<void> {
await this.nativeUpdate({ id }, {
place: write.place_id,
startDay: write.start_day_id,
endDay: write.end_day_id,
check_in: write.check_in,
check_in_end: write.check_in_end,
check_out: write.check_out,
confirmation: write.confirmation,
notes: write.notes,
});
async updateStay(
id: number,
write: {
place_id: number | null;
start_day_id: number;
end_day_id: number;
check_in: string | null;
check_in_end: string | null;
check_out: string | null;
confirmation: string | null;
notes: string | null;
},
): Promise<void> {
await this.nativeUpdate(
{ id },
{
place: write.place_id,
startDay: write.start_day_id,
endDay: write.end_day_id,
check_in: write.check_in,
check_in_end: write.check_in_end,
check_out: write.check_out,
confirmation: write.confirmation,
notes: write.notes,
},
);
}
/**
@@ -364,10 +388,17 @@ export class DayAccommodationsRepository extends TrekRepository<DayAccommodation
* `RoadtripDayBoundariesRepository` trap, Task 1's report), so both go
* through `columnRef`.
*/
async listForResync(trip_id: number): Promise<{ id: number; start_day_id: number; end_day_id: number; check_in: string | null }[]> {
async listForResync(
trip_id: number,
): Promise<{ id: number; start_day_id: number; end_day_id: number; check_in: string | null }[]> {
const platform = this.getEntityManager().getPlatform();
return await this.qb('a')
.select(['a.id', columnRef(platform, 'a.start_day_id').as('start_day_id'), columnRef(platform, 'a.end_day_id').as('end_day_id'), 'a.check_in'])
.select([
'a.id',
columnRef(platform, 'a.start_day_id').as('start_day_id'),
columnRef(platform, 'a.end_day_id').as('end_day_id'),
'a.check_in',
])
.where({ trip: trip_id })
.execute<{ id: number; start_day_id: number; end_day_id: number; check_in: string | null }[]>('all', false);
}
@@ -419,10 +450,7 @@ export class DayAccommodationsRepository extends TrekRepository<DayAccommodation
* own `findInTrip` projection), reused here rather than declared again.
*/
async listAllForTrip(trip_id: number): Promise<DayAccommodationRow[]> {
return await this.qb('a')
.select(['a.*'])
.where({ trip: trip_id })
.execute<DayAccommodationRow[]>('all', false);
return await this.qb('a').select(['a.*']).where({ trip: trip_id }).execute<DayAccommodationRow[]>('all', false);
}
// ---------------------------------------------------------------------------
@@ -1,7 +1,7 @@
import type { DayNotes } from '../entities/DayNotes.entity';
import type { DB } from '../kysely/db';
import { toRow, type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
export interface DayNoteRow {
id: number;
@@ -87,10 +87,7 @@ export class DayNotesRepository extends TrekRepository<DayNotes> {
* relies on read order).
*/
async listByTrip(trip_id: number | string): Promise<DayNoteRow[]> {
return await this.qb('n')
.select(['n.*'])
.where('n.trip_id = ?', [trip_id])
.execute<DayNoteRow[]>('all', false);
return await this.qb('n').select(['n.*']).where('n.trip_id = ?', [trip_id]).execute<DayNoteRow[]>('all', false);
}
/**
@@ -145,7 +142,11 @@ export class DayNotesRepository extends TrekRepository<DayNotes> {
* AND day_id = ? AND trip_id = ?`. Same raw-bind seam as
* {@link listByDayAndTrip}.
*/
async findByIdDayTrip(id: number | string, day_id: number | string, trip_id: number | string): Promise<DayNoteRow | undefined> {
async findByIdDayTrip(
id: number | string,
day_id: number | string,
trip_id: number | string,
): Promise<DayNoteRow | undefined> {
return await this.qb('n')
.select(['n.*'])
.where('n.id = ? AND n.day_id = ? AND n.trip_id = ?', [id, day_id, trip_id])
@@ -160,29 +161,32 @@ export class DayNotesRepository extends TrekRepository<DayNotes> {
* already resolves each one's `fields.x !== undefined ? fields.x :
* current.x` fallback, same shape as `createNote`'s docstring).
*/
async updateNote(id: number | string, fields: {
text: string;
time: string | null;
icon: string | null;
sort_order: number | null;
color: string | null;
}): Promise<DayNoteRow | undefined> {
async updateNote(
id: number | string,
fields: {
text: string;
time: string | null;
icon: string | null;
sort_order: number | null;
color: string | null;
},
): Promise<DayNoteRow | undefined> {
await this.qb('n')
.update({ text: fields.text, time: fields.time, icon: fields.icon, sort_order: fields.sort_order, color: fields.color })
.update({
text: fields.text,
time: fields.time,
icon: fields.icon,
sort_order: fields.sort_order,
color: fields.color,
})
.where('n.id = ?', [id])
.execute('run');
return await this.qb('n')
.select(['n.*'])
.where('n.id = ?', [id])
.execute<DayNoteRow | undefined>('get', false);
return await this.qb('n').select(['n.*']).where('n.id = ?', [id]).execute<DayNoteRow | undefined>('get', false);
}
/** `day-notes.service.ts::remove` — `DELETE FROM day_notes WHERE id = ?`. */
async deleteById(id: number | string): Promise<void> {
await this.qb('n')
.delete()
.where('n.id = ?', [id])
.execute('run');
await this.qb('n').delete().where('n.id = ?', [id]).execute('run');
}
/**
@@ -1,8 +1,8 @@
import type { Days } from '../entities/Days.entity';
import { columnRef } from '../dialect/sql-functions';
import type { Days } from '../entities/Days.entity';
import type { DB } from '../kysely/db';
import { toRow, type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
/** A `days` row as the API emits it. */
export interface DayRow {
@@ -317,10 +317,12 @@ export class DaysRepository extends TrekRepository<Days> {
.selectFrom('days as d')
.select(['d.id', 'd.day_number', 'd.date'])
.select((eb) =>
eb.or([
eb.exists(eb.selectFrom('day_assignments as da').select('da.id').whereRef('da.day_id', '=', 'd.id')),
eb.exists(eb.selectFrom('day_notes as dn').select('dn.id').whereRef('dn.day_id', '=', 'd.id')),
]).as('has_plan_items'),
eb
.or([
eb.exists(eb.selectFrom('day_assignments as da').select('da.id').whereRef('da.day_id', '=', 'd.id')),
eb.exists(eb.selectFrom('day_notes as dn').select('dn.id').whereRef('dn.day_id', '=', 'd.id')),
])
.as('has_plan_items'),
)
.where('d.trip_id', '=', trip_id)
.orderBy('d.day_number', 'asc')
+97 -16
View File
@@ -1,16 +1,24 @@
import type { EntityManager } from '@mikro-orm/core';
import type { SqlEntityManager } from '@mikro-orm/sql';
import { Users } from '../entities/Users.entity';
import type { NewAdminUserRow } from './Users.repository';
import { currentTimestampKysely } from '../dialect/kysely-functions';
import { AppSettings } from '../entities/AppSettings.entity';
import { Trips } from '../entities/Trips.entity';
import { currentTimestampKysely } from '../dialect/kysely-functions';
import { Users } from '../entities/Users.entity';
import type { DB } from '../kysely/db';
import type { NewAdminUserRow } from './Users.repository';
import type { EntityManager } from '@mikro-orm/core';
import type { SqlEntityManager } from '@mikro-orm/sql';
/** The tables the example-trip seed writes through Kysely. */
type DemoSeedKyselyDB = Pick<
DB,
'trip_members' | 'trips' | 'days' | 'places' | 'day_assignments' | 'packing_items' | 'budget_items' | 'reservations' | 'day_notes'
| 'trip_members'
| 'trips'
| 'days'
| 'places'
| 'day_assignments'
| 'packing_items'
| 'budget_items'
| 'reservations'
| 'day_notes'
>;
/** DMR1's projection (`resetDemoUser`'s pre-close credential read). */
@@ -165,7 +173,14 @@ export class DemoRepository {
}
/** DMS7 — `INSERT INTO trips (user_id, title, description, start_date, end_date, currency) VALUES (?, ?, ?, ?, ?, ?)`. Returns the generated trip id. */
async insertTrip(userId: number, title: string, description: string, startDate: string, endDate: string, currency: string): Promise<number> {
async insertTrip(
userId: number,
title: string,
description: string,
startDate: string,
endDate: string,
currency: string,
): Promise<number> {
const inserted = await this.kysely()
.insertInto('trips')
.values({ user_id: userId, title, description, start_date: startDate, end_date: endDate, currency })
@@ -186,11 +201,37 @@ export class DemoRepository {
/** DMS9 — the 13-column `places` insert (see {@link NewDemoPlaceRow}). Returns the generated place id. */
async insertPlace(row: NewDemoPlaceRow): Promise<number> {
const [trip_id, name, lat, lng, address, category_id, place_time, duration_minutes, notes, image_url, google_place_id, website, phone] = row;
const [
trip_id,
name,
lat,
lng,
address,
category_id,
place_time,
duration_minutes,
notes,
image_url,
google_place_id,
website,
phone,
] = row;
const inserted = await this.kysely()
.insertInto('places')
.values({
trip_id, name, lat, lng, address, category_id, place_time, duration_minutes, notes, image_url, google_place_id, website, phone,
trip_id,
name,
lat,
lng,
address,
category_id,
place_time,
duration_minutes,
notes,
image_url,
google_place_id,
website,
phone,
})
.returning('id')
.executeTakeFirstOrThrow();
@@ -199,20 +240,43 @@ export class DemoRepository {
/** DMS10 — `INSERT INTO day_assignments (day_id, place_id, order_index) VALUES (?, ?, ?)`. */
async insertDayAssignment(dayId: number, placeId: number, orderIndex: number): Promise<void> {
await this.kysely().insertInto('day_assignments').values({ day_id: dayId, place_id: placeId, order_index: orderIndex }).execute();
await this.kysely()
.insertInto('day_assignments')
.values({ day_id: dayId, place_id: placeId, order_index: orderIndex })
.execute();
}
/** DMS11 — `INSERT INTO packing_items (trip_id, name, checked, category, sort_order, updated_at) VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`. */
async insertPackingItem(tripId: number, name: string, checked: number, category: string, sortOrder: number): Promise<void> {
async insertPackingItem(
tripId: number,
name: string,
checked: number,
category: string,
sortOrder: number,
): Promise<void> {
const platform = this.em.getPlatform();
await this.kysely()
.insertInto('packing_items')
.values({ trip_id: tripId, name, checked, category, sort_order: sortOrder, updated_at: currentTimestampKysely(platform) })
.values({
trip_id: tripId,
name,
checked,
category,
sort_order: sortOrder,
updated_at: currentTimestampKysely(platform),
})
.execute();
}
/** DMS12 — `INSERT INTO budget_items (trip_id, category, name, total_price, persons, note) VALUES (?, ?, ?, ?, ?, ?)`. */
async insertBudgetItem(tripId: number, category: string, name: string, totalPrice: number, persons: number, note: string | null): Promise<void> {
async insertBudgetItem(
tripId: number,
category: string,
name: string,
totalPrice: number,
persons: number,
note: string | null,
): Promise<void> {
await this.kysely()
.insertInto('budget_items')
.values({ trip_id: tripId, category, name, total_price: totalPrice, persons, note })
@@ -238,13 +302,27 @@ export class DemoRepository {
await this.kysely()
.insertInto('reservations')
.values({
trip_id: tripId, day_id: dayId, title, reservation_time: reservationTime, confirmation_number: confirmationNumber, status, type, location,
trip_id: tripId,
day_id: dayId,
title,
reservation_time: reservationTime,
confirmation_number: confirmationNumber,
status,
type,
location,
})
.execute();
}
/** DMS14 — `INSERT INTO day_notes (day_id, trip_id, text, time, icon, sort_order) VALUES (?, ?, ?, ?, ?, ?)`. */
async insertDayNote(dayId: number, tripId: number, text: string, time: string, icon: string, sortOrder: number): Promise<void> {
async insertDayNote(
dayId: number,
tripId: number,
text: string,
time: string,
icon: string,
sortOrder: number,
): Promise<void> {
await this.kysely()
.insertInto('day_notes')
.values({ day_id: dayId, trip_id: tripId, text, time, icon, sort_order: sortOrder })
@@ -265,7 +343,10 @@ export class DemoRepository {
async getAdminCredentials(email: string): Promise<DemoAdminCredentialsRow | null> {
const row = await this.em
.getRepository(Users)
.findOne({ email }, { fields: ['password_hash', 'maps_api_key', 'openweather_api_key', 'unsplash_api_key', 'avatar'] });
.findOne(
{ email },
{ fields: ['password_hash', 'maps_api_key', 'openweather_api_key', 'unsplash_api_key', 'avatar'] },
);
return row
? {
password_hash: row.password_hash,
@@ -1,8 +1,8 @@
import { currentTimestamp, coalesceOverride } from '../dialect/sql-functions';
import type { DocumentConnections } from '../entities/DocumentConnections.entity';
import type { DB } from '../kysely/db';
import { type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
/**
* A bare `document_connections` row. `secrets` is opaque encrypted TEXT here
@@ -72,7 +72,13 @@ export class DocumentConnectionsRepository extends TrekRepository<DocumentConnec
*/
async updateConnection(
id: number,
data: { base_url: string; secrets: string | null; settings: string; allow_insecure_tls: number; owner_user_id: number },
data: {
base_url: string;
secrets: string | null;
settings: string;
allow_insecure_tls: number;
owner_user_id: number;
},
): Promise<void> {
const platform = this.getEntityManager().getPlatform();
await this.nativeUpdate(
@@ -156,15 +162,12 @@ export class DocumentConnectionsRepository extends TrekRepository<DocumentConnec
.selectFrom('document_connections as c')
.select('c.id')
.where((eb) =>
eb(
'c.owner_user_id',
'not in',
(qb) =>
qb
.selectFrom('trip_members as tm')
.select('tm.user_id')
.whereRef('tm.trip_id', '=', 'c.trip_id')
.union(qb.selectFrom('trips as t').select('t.user_id').whereRef('t.id', '=', 'c.trip_id')),
eb('c.owner_user_id', 'not in', (qb) =>
qb
.selectFrom('trip_members as tm')
.select('tm.user_id')
.whereRef('tm.trip_id', '=', 'c.trip_id')
.union(qb.selectFrom('trips as t').select('t.user_id').whereRef('t.id', '=', 'c.trip_id')),
),
)
.execute();
@@ -67,7 +67,12 @@ export class DocumentProvidersRepository extends TrekRepository<DocumentProvider
{ enabled: 1 },
{ fields: ['id', 'name', 'description', 'icon'], orderBy: { sort_order: 'asc' } },
);
return rows.map((r) => ({ id: r.id as string, name: r.name, description: r.description ?? null, icon: r.icon ?? null }));
return rows.map((r) => ({
id: r.id as string,
name: r.name,
description: r.description ?? null,
icon: r.icon ?? null,
}));
}
// ---------------------------------------------------------------------
@@ -1,10 +1,10 @@
import type { EntityData } from '@mikro-orm/core';
import { coalesceOverride, currentTimestamp, foundAgainState, nowPlusSeconds } from '../dialect/sql-functions';
import { currentTimestampKysely, nowPlusSecondsKysely } from '../dialect/kysely-functions';
import { coalesceOverride, currentTimestamp, foundAgainState, nowPlusSeconds } from '../dialect/sql-functions';
import type { DocumentSyncItems } from '../entities/DocumentSyncItems.entity';
import type { DB } from '../kysely/db';
import { type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
import type { EntityData } from '@mikro-orm/core';
/** A bare `document_sync_items` row (every scalar column). */
export interface DocumentSyncItemRow {
@@ -98,7 +98,10 @@ export class DocumentSyncItemsRepository extends TrekRepository<DocumentSyncItem
// ── applyAction's eight state-machine UPDATEs (DS2-DS12) ──────────────────
/** DS2 (`applyAction` 'relocate') — `UPDATE ... SET remote_id=?, remote_version=?, remote_size=COALESCE(?,remote_size), remote_modified_at=COALESCE(?,remote_modified_at), ${FOUND_AGAIN}, last_seen_at=CURRENT_TIMESTAMP WHERE id=?`. */
async applyRelocate(id: number, data: { remote_id: string; remote_version: string; remote_size: number | null; remote_modified_at: string | null }): Promise<void> {
async applyRelocate(
id: number,
data: { remote_id: string; remote_version: string; remote_size: number | null; remote_modified_at: string | null },
): Promise<void> {
const platform = this.getEntityManager().getPlatform();
await this.nativeUpdate(
{ id },
@@ -152,7 +155,14 @@ export class DocumentSyncItemsRepository extends TrekRepository<DocumentSyncItem
/** DS7 (`applyAction` 'mark_remote_missing') — `UPDATE ... SET state='remote_missing', remote_missing_at=CURRENT_TIMESTAMP, last_seen_at=CURRENT_TIMESTAMP WHERE id=?`. */
async markRemoteMissing(id: number): Promise<void> {
const platform = this.getEntityManager().getPlatform();
await this.nativeUpdate({ id }, { state: 'remote_missing', remote_missing_at: currentTimestamp(platform), last_seen_at: currentTimestamp(platform) });
await this.nativeUpdate(
{ id },
{
state: 'remote_missing',
remote_missing_at: currentTimestamp(platform),
last_seen_at: currentTimestamp(platform),
},
);
}
/**
@@ -201,7 +211,14 @@ export class DocumentSyncItemsRepository extends TrekRepository<DocumentSyncItem
const platform = this.getEntityManager().getPlatform();
await this.nativeUpdate(
{ id },
{ state: 'pending', remote_id: null, remote_version: null, remote_trashed_at: null, error_code: null, last_seen_at: currentTimestamp(platform) },
{
state: 'pending',
remote_id: null,
remote_version: null,
remote_trashed_at: null,
error_code: null,
last_seen_at: currentTimestamp(platform),
},
);
}
@@ -214,7 +231,13 @@ export class DocumentSyncItemsRepository extends TrekRepository<DocumentSyncItem
/** DS12 (`applyAction` 'touch') — the most-used state-machine action: `UPDATE ... SET last_seen_at=CURRENT_TIMESTAMP, remote_version=COALESCE(?,remote_version), remote_name=COALESCE(?,remote_name), remote_id=COALESCE(?,remote_id), remote_size=COALESCE(?,remote_size), remote_modified_at=COALESCE(?,remote_modified_at), ${FOUND_AGAIN} WHERE id=?`. */
async applyTouch(
id: number,
data: { remote_version: string | null; remote_name: string | null; remote_id: string | null; remote_size: number | null; remote_modified_at: string | null },
data: {
remote_version: string | null;
remote_name: string | null;
remote_id: string | null;
remote_size: number | null;
remote_modified_at: string | null;
},
): Promise<void> {
const platform = this.getEntityManager().getPlatform();
await this.nativeUpdate(
@@ -235,13 +258,21 @@ export class DocumentSyncItemsRepository extends TrekRepository<DocumentSyncItem
// ── Reads ───────────────────────────────────────────────────────────────
/** DS13 (`pull`'s pre-image read) — `SELECT file_id, remote_name, content_sha256 FROM document_sync_items WHERE id=?`. */
async findPairing(id: number): Promise<{ file_id: number | null; remote_name: string | null; content_sha256: string | null } | undefined> {
async findPairing(
id: number,
): Promise<{ file_id: number | null; remote_name: string | null; content_sha256: string | null } | undefined> {
const row = await this.kysely<DocumentSyncItemsKyselyDB>()
.selectFrom('document_sync_items')
.select(['file_id', 'remote_name', 'content_sha256'])
.where('id', '=', id)
.executeTakeFirst();
return row ? { file_id: row.file_id ?? null, remote_name: row.remote_name ?? null, content_sha256: row.content_sha256 ?? null } : undefined;
return row
? {
file_id: row.file_id ?? null,
remote_name: row.remote_name ?? null,
content_sha256: row.content_sha256 ?? null,
}
: undefined;
}
/**
@@ -261,8 +292,21 @@ export class DocumentSyncItemsRepository extends TrekRepository<DocumentSyncItem
const rows = await this.kysely<DocumentSyncItemsKyselyDB>()
.selectFrom('document_sync_items')
.select([
'id', 'file_id', 'trek_doc_uid', 'remote_id', 'remote_version', 'remote_name', 'remote_size', 'remote_modified_at',
'content_sha256', 'pushed_sha256', 'state', 'attempts', 'next_attempt_at', 'remote_missing_at', 'remote_trashed_at',
'id',
'file_id',
'trek_doc_uid',
'remote_id',
'remote_version',
'remote_name',
'remote_size',
'remote_modified_at',
'content_sha256',
'pushed_sha256',
'state',
'attempts',
'next_attempt_at',
'remote_missing_at',
'remote_trashed_at',
])
.where('link_id', '=', linkId)
.execute();
@@ -309,7 +353,11 @@ export class DocumentSyncItemsRepository extends TrekRepository<DocumentSyncItem
/** DS22 (`upsertItem`'s read-before-write attempt counter) — `SELECT attempts FROM document_sync_items WHERE id=?`. */
async getAttempts(id: number): Promise<number | undefined> {
const row = await this.kysely<DocumentSyncItemsKyselyDB>().selectFrom('document_sync_items').select('attempts').where('id', '=', id).executeTakeFirst();
const row = await this.kysely<DocumentSyncItemsKyselyDB>()
.selectFrom('document_sync_items')
.select('attempts')
.where('id', '=', id)
.executeTakeFirst();
return row?.attempts;
}
@@ -374,7 +422,8 @@ export class DocumentSyncItemsRepository extends TrekRepository<DocumentSyncItem
content_sha256: coalesceOverride(platform, patch.content_sha256, 'content_sha256'),
pushed_sha256: coalesceOverride(platform, patch.pushed_sha256, 'pushed_sha256'),
attempts: patch.attempts,
next_attempt_at: patch.next_attempt_after_seconds !== null ? nowPlusSeconds(platform, patch.next_attempt_after_seconds) : null,
next_attempt_at:
patch.next_attempt_after_seconds !== null ? nowPlusSeconds(platform, patch.next_attempt_after_seconds) : null,
remote_missing_at: null,
last_seen_at: currentTimestamp(platform),
};
@@ -444,7 +493,9 @@ export class DocumentSyncItemsRepository extends TrekRepository<DocumentSyncItem
error_code: data.error_code,
attempts: data.attempts,
next_attempt_at:
data.next_attempt_after_seconds !== null ? nowPlusSecondsKysely(platform, eb, data.next_attempt_after_seconds) : null,
data.next_attempt_after_seconds !== null
? nowPlusSecondsKysely(platform, eb, data.next_attempt_after_seconds)
: null,
synced_at: data.synced_now ? currentTimestampKysely(platform) : null,
last_seen_at: currentTimestampKysely(platform),
}))
@@ -456,9 +507,12 @@ export class DocumentSyncItemsRepository extends TrekRepository<DocumentSyncItem
state: (eb) => eb.ref('excluded.state'),
error_code: (eb) => eb.ref('excluded.error_code'),
file_id: (eb) => eb.fn.coalesce(eb.ref('excluded.file_id'), eb.ref('document_sync_items.file_id')),
remote_version: (eb) => eb.fn.coalesce(eb.ref('excluded.remote_version'), eb.ref('document_sync_items.remote_version')),
content_sha256: (eb) => eb.fn.coalesce(eb.ref('excluded.content_sha256'), eb.ref('document_sync_items.content_sha256')),
pushed_sha256: (eb) => eb.fn.coalesce(eb.ref('excluded.pushed_sha256'), eb.ref('document_sync_items.pushed_sha256')),
remote_version: (eb) =>
eb.fn.coalesce(eb.ref('excluded.remote_version'), eb.ref('document_sync_items.remote_version')),
content_sha256: (eb) =>
eb.fn.coalesce(eb.ref('excluded.content_sha256'), eb.ref('document_sync_items.content_sha256')),
pushed_sha256: (eb) =>
eb.fn.coalesce(eb.ref('excluded.pushed_sha256'), eb.ref('document_sync_items.pushed_sha256')),
last_seen_at: () => currentTimestampKysely(platform),
}),
)
@@ -470,7 +524,10 @@ export class DocumentSyncItemsRepository extends TrekRepository<DocumentSyncItem
/** DS27 (`renameRemoteTo`) — `UPDATE ... SET remote_name=?, remote_version=?, last_seen_at=CURRENT_TIMESTAMP WHERE id=?`. No `FOUND_AGAIN` — a distinct, simpler shape from DS3 (both rename the same two columns, but only DS3's caller is inside the reconciler's state machine). */
async setRemoteName(id: number, data: { remote_name: string; remote_version: string }): Promise<void> {
const platform = this.getEntityManager().getPlatform();
await this.nativeUpdate({ id }, { remote_name: data.remote_name, remote_version: data.remote_version, last_seen_at: currentTimestamp(platform) });
await this.nativeUpdate(
{ id },
{ remote_name: data.remote_name, remote_version: data.remote_version, last_seen_at: currentTimestamp(platform) },
);
}
/** DS28 (`resolveConflict`'s pre-image read) — `SELECT * FROM document_sync_items WHERE id=?`. */
@@ -511,7 +568,14 @@ export class DocumentSyncItemsRepository extends TrekRepository<DocumentSyncItem
return await this.kysely<DocumentSyncItemsKyselyDB>()
.selectFrom('document_sync_items as i')
.leftJoin('trip_files as f', 'f.id', 'i.file_id')
.select(['i.id', 'i.state', 'i.error_code', 'i.remote_name', 'i.remote_missing_at', 'f.original_name as file_name'])
.select([
'i.id',
'i.state',
'i.error_code',
'i.remote_name',
'i.remote_missing_at',
'f.original_name as file_name',
])
.where('i.trip_id', '=', tripId)
.where('i.state', 'in', [...ISSUE_STATES])
.orderBy('i.id', 'desc')
@@ -548,7 +612,9 @@ export class DocumentSyncItemsRepository extends TrekRepository<DocumentSyncItem
.sum<number>(
eb
.case()
.when(eb.and([eb('file_id', 'is not', null), eb('remote_id', 'is not', null), eb('state', '=', 'synced')]))
.when(
eb.and([eb('file_id', 'is not', null), eb('remote_id', 'is not', null), eb('state', '=', 'synced')]),
)
.then(1)
.else(0)
.end(),
@@ -571,7 +637,16 @@ export class DocumentSyncItemsRepository extends TrekRepository<DocumentSyncItem
.end(),
)
.as('atProvider'),
eb.fn.sum<number>(eb.case().when(eb('state', '=', 'remote_missing')).then(1).else(0).end()).as('missing'),
eb.fn
.sum<number>(
eb
.case()
.when(eb('state', '=', 'remote_missing'))
.then(1)
.else(0)
.end(),
)
.as('missing'),
])
.where('trip_id', '=', tripId)
.groupBy('link_id')
@@ -590,7 +665,12 @@ export class DocumentSyncItemsRepository extends TrekRepository<DocumentSyncItem
* stay three methods, the WHERE/LIMIT shapes are not identical).
*/
async listForTripByState(tripId: number, state: string): Promise<DocumentSyncItemWithFileRow[]> {
return await this.itemsWithFileQuery().where('i.trip_id', '=', tripId).where('i.state', '=', state).orderBy('i.id', 'desc').limit(500).execute();
return await this.itemsWithFileQuery()
.where('i.trip_id', '=', tripId)
.where('i.state', '=', state)
.orderBy('i.id', 'desc')
.limit(500)
.execute();
}
/** DSCTRL5 (`DocSyncController.items`, unfiltered) — same as {@link listForTripByState} minus the state predicate. */
@@ -1,7 +1,7 @@
import type { FileLinks } from '../entities/FileLinks.entity';
import type { DB } from '../kysely/db';
import { type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
/** A bare `file_links` row — every scalar column of the entity, incl. its five `persist(false)` relation mirrors. */
export interface FileLinkRow {
@@ -77,7 +77,13 @@ export class FileLinksRepository extends TrekRepository<FileLinks> {
* legacy sites (FL10/FL13 pass only `budget_item_id`; FL24 passes any
* combination the caller supplies) — one method, not three.
*/
async insertIgnore(row: { file_id: number; reservation_id?: number | null; assignment_id?: number | null; place_id?: number | null; budget_item_id?: number | null }): Promise<void> {
async insertIgnore(row: {
file_id: number;
reservation_id?: number | null;
assignment_id?: number | null;
place_id?: number | null;
budget_item_id?: number | null;
}): Promise<void> {
await this.kysely<FileLinksWriteKyselyDB>()
.insertInto('file_links')
.values({
@@ -111,7 +117,11 @@ export class FileLinksRepository extends TrekRepository<FileLinks> {
/** FL25 (`createFileLink`'s bare re-select) — `SELECT * FROM file_links WHERE file_id = ?`. */
async listForFile(file_id: number): Promise<FileLinkRow[]> {
return await this.kysely<FileLinksKyselyDB>().selectFrom('file_links').selectAll().where('file_id', '=', file_id).execute();
return await this.kysely<FileLinksKyselyDB>()
.selectFrom('file_links')
.selectAll()
.where('file_id', '=', file_id)
.execute();
}
/** FL27 (`FilesService.getFileLinks`) — `SELECT fl.*, r.title as reservation_title FROM file_links fl LEFT JOIN reservations r ON fl.reservation_id = r.id WHERE fl.file_id = ?`. */
@@ -1,8 +1,8 @@
import type { GoogleApiUsage } from '../entities/GoogleApiUsage.entity';
import { nowDateOffset } from '../dialect/sql-functions';
import type { GoogleApiUsage } from '../entities/GoogleApiUsage.entity';
import type { DB } from '../kysely/db';
import type { AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
/** A `google_api_usage` row: Google API calls counted per UTC day (#1582). */
export interface GoogleApiUsageRow {
@@ -1,6 +1,6 @@
import type { HiddenCountries } from '../entities/HiddenCountries.entity';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
type HiddenCountriesKyselyDB = Pick<DB, 'hidden_countries'>;
@@ -17,7 +17,11 @@ export class HiddenCountriesRepository extends TrekRepository<HiddenCountries> {
/** AT11 (`getHiddenCountries`) — `SELECT country_code FROM hidden_countries WHERE user_id = ?`. */
async listForUser(userId: number): Promise<string[]> {
const rows = await this.db().selectFrom('hidden_countries').select('country_code').where('user_id', '=', userId).execute();
const rows = await this.db()
.selectFrom('hidden_countries')
.select('country_code')
.where('user_id', '=', userId)
.execute();
return rows.map((r) => r.country_code);
}
@@ -32,6 +36,10 @@ export class HiddenCountriesRepository extends TrekRepository<HiddenCountries> {
/** AT13/AT20 (`markCountry`'s and `markRegion`'s "lift a prior removal" delete — identical text, two call sites) — `DELETE FROM hidden_countries WHERE user_id = ? AND country_code = ?`. */
async unhide(userId: number, countryCode: string): Promise<void> {
await this.db().deleteFrom('hidden_countries').where('user_id', '=', userId).where('country_code', '=', countryCode).execute();
await this.db()
.deleteFrom('hidden_countries')
.where('user_id', '=', userId)
.where('country_code', '=', countryCode)
.execute();
}
}
@@ -1,6 +1,6 @@
import type { HiddenRegions } from '../entities/HiddenRegions.entity';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
type HiddenRegionsKyselyDB = Pick<DB, 'hidden_regions'>;
@@ -18,7 +18,11 @@ export class HiddenRegionsRepository extends TrekRepository<HiddenRegions> {
/** AT22 (`getHiddenRegions`) — `SELECT region_code FROM hidden_regions WHERE user_id = ?`. */
async listForUser(userId: number): Promise<string[]> {
const rows = await this.db().selectFrom('hidden_regions').select('region_code').where('user_id', '=', userId).execute();
const rows = await this.db()
.selectFrom('hidden_regions')
.select('region_code')
.where('user_id', '=', userId)
.execute();
return rows.map((r) => r.region_code);
}
@@ -33,6 +37,10 @@ export class HiddenRegionsRepository extends TrekRepository<HiddenRegions> {
/** AT18 (`markRegion`, inside its transaction) — `DELETE FROM hidden_regions WHERE user_id = ? AND region_code = ?`. */
async unhide(userId: number, regionCode: string): Promise<void> {
await this.db().deleteFrom('hidden_regions').where('user_id', '=', userId).where('region_code', '=', regionCode).execute();
await this.db()
.deleteFrom('hidden_regions')
.where('user_id', '=', userId)
.where('region_code', '=', regionCode)
.execute();
}
}
@@ -19,11 +19,13 @@ export class IdempotencyKeysRepository extends TrekRepository<IdempotencyKeys> {
* response_body FROM idempotency_keys WHERE key = ? AND user_id = ? AND
* method = ? AND path = ?`.
*/
async findResponse(key: string, userId: number, method: string, path: string): Promise<IdempotencyResponseRow | null> {
const row = await this.findOne(
{ key, user: userId, method, path },
{ fields: ['status_code', 'response_body'] },
);
async findResponse(
key: string,
userId: number,
method: string,
path: string,
): Promise<IdempotencyResponseRow | null> {
const row = await this.findOne({ key, user: userId, method, path }, { fields: ['status_code', 'response_body'] });
return row ? { status_code: row.status_code, response_body: row.response_body } : null;
}
@@ -1,6 +1,6 @@
import { columnIncrementedBy, columnRef } from '../dialect/sql-functions';
import type { InviteTokens } from '../entities/InviteTokens.entity';
import { toRow, type AssertRowKeys } from './_shared/rows';
import { columnIncrementedBy, columnRef } from '../dialect/sql-functions';
import { TrekRepository } from './_shared/trek-repository';
/** An `invite_tokens` row as the API emits it. */
@@ -84,7 +84,11 @@ export class JourneyBooksRepository extends TrekRepository<JourneyBooks> {
* means a conflict — the service re-reads via {@link findById} for the
* `{conflict}` response, it does not throw.
*/
async casUpdate(id: number, baseVersion: number, data: { title: string; document: string; updatedBy: number }): Promise<number> {
async casUpdate(
id: number,
baseVersion: number,
data: { title: string; document: string; updatedBy: number },
): Promise<number> {
const platform = this.getEntityManager().getPlatform();
return await this.nativeUpdate(
{ id, version: baseVersion },
@@ -1,6 +1,6 @@
import type { JourneyContributors } from '../entities/JourneyContributors.entity';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
/** JG18's contributor-list row (`getJourneyFull`) — the junction plus the joined username/avatar. */
export interface JourneyContributorListRow {
@@ -1,7 +1,7 @@
import type { JourneyEntry } from '../../types';
import type { JourneyEntries } from '../entities/JourneyEntries.entity';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
/** JG55's wider reconciliation projection (`reconcileTripSkeletons`) — a distinct column set from JG35's dedup-key-only read. */
export interface ReconcileEntryRow {
@@ -42,7 +42,10 @@ export interface PhotoPlacementRow {
}
/** The `trek_photos`/`journey_photos`/`journey_entry_photos`/`journey_entries`/`journeys` tables {@link JourneyEntriesRepository.listPhotoPlacementCandidates} reads. */
type PhotoPlacementKyselyDB = Pick<DB, 'trek_photos' | 'journey_photos' | 'journey_entry_photos' | 'journey_entries' | 'journeys'>;
type PhotoPlacementKyselyDB = Pick<
DB,
'trek_photos' | 'journey_photos' | 'journey_entry_photos' | 'journey_entries' | 'journeys'
>;
/** `journey_entry_photos`, read cross-table (no `JourneyEntryPhotosRepository` yet — Task 2's own; the two `hasPhotos` guards in Part A only ever check existence). */
type JourneyEntryPhotosExistsKyselyDB = Pick<DB, 'journey_entry_photos'>;
@@ -200,7 +203,10 @@ export class JourneyEntriesRepository extends TrekRepository<JourneyEntries> {
* "fixed" into a redundant one.
*/
async detachAllFilledForTrip(tripId: number): Promise<void> {
await this.nativeUpdate({ sourceTrip: tripId }, { sourcePlace: null, sourceTrip: null, source_assignment_id: null });
await this.nativeUpdate(
{ sourceTrip: tripId },
{ sourcePlace: null, sourceTrip: null, source_assignment_id: null },
);
}
/**
@@ -214,7 +220,10 @@ export class JourneyEntriesRepository extends TrekRepository<JourneyEntries> {
}
/** JG35 — `syncTripPlaces`'s existing-skeleton dedup-key read: `SELECT source_place_id, source_assignment_id FROM journey_entries WHERE journey_id = ? AND source_trip_id = ?`. */
async listSourceKeysForTrip(journeyId: number, tripId: number): Promise<{ source_place_id: number; source_assignment_id: number | null }[]> {
async listSourceKeysForTrip(
journeyId: number,
tripId: number,
): Promise<{ source_place_id: number; source_assignment_id: number | null }[]> {
return await this.qb('je')
.select(['je.sourcePlace', 'je.source_assignment_id'])
.where({ journey: journeyId, sourceTrip: tripId })
@@ -323,7 +332,13 @@ export class JourneyEntriesRepository extends TrekRepository<JourneyEntries> {
/** JG47/JG59 — the location-only silent update (`onPlaceUpdated`'s filled-entry branch, `reconcileTripSkeletons`'s stale-filled-entry branch), one statement text. */
async updateLocationOnly(
id: number,
patch: { location_name: string; location_lat: number | null; location_lng: number | null; country_code: string | null; updated_at: number },
patch: {
location_name: string;
location_lat: number | null;
location_lng: number | null;
country_code: string | null;
updated_at: number;
},
): Promise<void> {
await this.nativeUpdate({ id }, patch);
}
@@ -390,7 +405,17 @@ export class JourneyEntriesRepository extends TrekRepository<JourneyEntries> {
*/
async listStatsRows(journeyId: number): Promise<StatsEntryRow[]> {
return await this.qb('je')
.select(['je.id', 'je.title', 'je.location_name', 'je.location_lat', 'je.location_lng', 'je.entry_date', 'je.sourceTrip', 'je.sourcePlace', 'je.stats_excluded'])
.select([
'je.id',
'je.title',
'je.location_name',
'je.location_lat',
'je.location_lng',
'je.entry_date',
'je.sourceTrip',
'je.sourcePlace',
'je.stats_excluded',
])
.where({ journey: journeyId, dismissed: 0 })
.orderBy({ entry_date: 'asc', sort_order: 'asc', id: 'asc' })
.execute<StatsEntryRow[]>('all', false);
@@ -431,7 +456,15 @@ export class JourneyEntriesRepository extends TrekRepository<JourneyEntries> {
.innerJoin('places as p', 'p.trip_id', 'jt.trip_id')
.leftJoin('day_assignments as da', 'da.place_id', 'p.id')
.leftJoin('days as d', 'd.id', 'da.day_id')
.select((eb) => ['p.id', 'p.name', 'p.lat', 'p.lng', 'p.trip_id as tripId', eb.fn.min<string | null>('d.date').as('day'), eb.fn.min<number | null>('da.order_index').as('ord')])
.select((eb) => [
'p.id',
'p.name',
'p.lat',
'p.lng',
'p.trip_id as tripId',
eb.fn.min<string | null>('d.date').as('day'),
eb.fn.min<number | null>('da.order_index').as('ord'),
])
.where('jt.journey_id', '=', journeyId)
.groupBy('p.id')
.orderBy((eb) => eb(eb.fn.min<string | null>('d.date'), 'is', null), 'asc')
@@ -466,7 +499,9 @@ export class JourneyEntriesRepository extends TrekRepository<JourneyEntries> {
* (r.country_code)` filter and the `.toUpperCase()` call both stay in the
* SERVICE, matching the legacy code's own JS-side handling.
*/
async listCachedCountriesForPlaceIds(placeIds: number[]): Promise<{ place_id: number; country_code: string | null }[]> {
async listCachedCountriesForPlaceIds(
placeIds: number[],
): Promise<{ place_id: number; country_code: string | null }[]> {
const out: { place_id: number; country_code: string | null }[] = [];
for (let i = 0; i < placeIds.length; i += 400) {
// M4 (task-5-review.md) — `chunk` can never be empty here: the loop
@@ -597,7 +632,18 @@ export class JourneyEntriesRepository extends TrekRepository<JourneyEntries> {
/** JG85 — `deleteEntry`'s revert-to-skeleton write (a filled, trip-sourced entry is "deleted" by reverting it, not removed — {@link deleteById} (JG50/61/86) is the true hard delete, for entries with no trip origin). */
async revertToSkeleton(id: number, updatedAt: number): Promise<void> {
await this.nativeUpdate({ id }, { type: 'skeleton', story: null, mood: null, weather: null, pros_cons: null, visibility: 'private', updated_at: updatedAt });
await this.nativeUpdate(
{ id },
{
type: 'skeleton',
story: null,
mood: null,
weather: null,
pros_cons: null,
visibility: 'private',
updated_at: updatedAt,
},
);
}
/** JG87 — `promoteSkeletonIfNeeded`'s write: `UPDATE journey_entries SET type = ?, updated_at = ? WHERE id = ?`, called only when the entry is still a skeleton (the SERVICE's own `if (entry.type !== 'skeleton') return;` guard, unchanged). */
@@ -1,17 +1,33 @@
import type { JourneyPhoto } from '../../types';
import type { JourneyEntryPhotos } from '../entities/JourneyEntryPhotos.entity';
import type { DB } from '../kysely/db';
import type { JourneyPublicGalleryRow } from './JourneyShareTokens.repository';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
/** The `journey_entry_photos`/`journey_photos`/`trek_photos`/`journey_entries` tables the `JP_SELECT`/`JP_JOIN`-shaped reads read. */
type JourneyPhotoJoinKyselyDB = Pick<DB, 'journey_entry_photos' | 'journey_photos' | 'trek_photos' | 'journey_entries'>;
/** `JP_SELECT`'s exact column list (`journey-domain.service.ts`'s module const), aliased `jep`/`gp`/`tp` — shared by every `JP_SELECT`/`JP_JOIN`-shaped read below. */
const JP_COLUMNS = [
'gp.id', 'jep.entry_id', 'gp.photo_id', 'gp.caption', 'jep.sort_order', 'gp.shared', 'gp.created_at',
'tp.provider', 'tp.asset_id', 'tp.owner_id', 'tp.file_path', 'tp.thumbnail_path', 'tp.width', 'tp.height',
'tp.media_type', 'tp.duration_ms', 'tp.taken_at', 'tp.lat', 'tp.lng',
'gp.id',
'jep.entry_id',
'gp.photo_id',
'gp.caption',
'jep.sort_order',
'gp.shared',
'gp.created_at',
'tp.provider',
'tp.asset_id',
'tp.owner_id',
'tp.file_path',
'tp.thumbnail_path',
'tp.width',
'tp.height',
'tp.media_type',
'tp.duration_ms',
'tp.taken_at',
'tp.lat',
'tp.lng',
] as const;
/**
@@ -1,11 +1,12 @@
import type { Platform } from '@mikro-orm/core';
import type { ExpressionBuilder } from 'kysely';
import type { GalleryPhoto } from '../../types';
import type { JourneyPhotos } from '../entities/JourneyPhotos.entity';
import { concatKysely, unixEpochToIsoKysely } from '../dialect/kysely-functions';
import type { JourneyPhotos } from '../entities/JourneyPhotos.entity';
import type { DB } from '../kysely/db';
import { type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
import type { Platform } from '@mikro-orm/core';
import type { ExpressionBuilder } from 'kysely';
/** `SELECT * FROM journey_photos WHERE id = ?`'s row (JG105) — every scalar column of the entity. */
export interface JourneyPhotoFullRow {
@@ -24,7 +25,10 @@ export interface JourneyPhotoFullRow {
const _journeyPhotoFullRowKeys: AssertRowKeys<JourneyPhotoFullRow, JourneyPhotos> = true;
/** The `journey_photos`/`trek_photos`/`journey_entry_photos`/`journey_entries` tables the gallery reads (JG19/JG101/JG102, `galleryChronologicalOrderExpr`) read. */
type GalleryKyselyDB = Pick<DB, 'journey_photos' | 'trek_photos' | 'journey_entry_photos' | 'journey_entries' | 'journeys'>;
type GalleryKyselyDB = Pick<
DB,
'journey_photos' | 'trek_photos' | 'journey_entry_photos' | 'journey_entries' | 'journeys'
>;
/** JS7 (Plan 4 Task 8b relocation) — the public photo-validation join's row (`journey_photos` + `trek_photos`). */
export interface JourneyPublicPhotoValidationRow {
@@ -41,9 +45,25 @@ export interface JourneyPublicAssetValidationRow {
/** `GALLERY_SELECT`'s exact column list (`journey-domain.service.ts`'s module const), aliased `gp`/`tp` — shared by every gallery-shaped read below. */
const GALLERY_COLUMNS = [
'gp.id', 'gp.journey_id', 'gp.photo_id', 'gp.caption', 'gp.shared', 'gp.sort_order', 'gp.created_at',
'tp.provider', 'tp.asset_id', 'tp.owner_id', 'tp.file_path', 'tp.thumbnail_path', 'tp.width', 'tp.height',
'tp.media_type', 'tp.duration_ms', 'tp.taken_at', 'tp.lat', 'tp.lng',
'gp.id',
'gp.journey_id',
'gp.photo_id',
'gp.caption',
'gp.shared',
'gp.sort_order',
'gp.created_at',
'tp.provider',
'tp.asset_id',
'tp.owner_id',
'tp.file_path',
'tp.thumbnail_path',
'tp.width',
'tp.height',
'tp.media_type',
'tp.duration_ms',
'tp.taken_at',
'tp.lat',
'tp.lng',
] as const;
/**
@@ -63,7 +83,10 @@ const GALLERY_COLUMNS = [
*/
function galleryChronologicalOrderExpr(
platform: Platform,
eb: ExpressionBuilder<GalleryKyselyDB & { gp: GalleryKyselyDB['journey_photos']; tp: GalleryKyselyDB['trek_photos'] }, 'gp' | 'tp'>,
eb: ExpressionBuilder<
GalleryKyselyDB & { gp: GalleryKyselyDB['journey_photos']; tp: GalleryKyselyDB['trek_photos'] },
'gp' | 'tp'
>,
) {
return eb.fn.coalesce(
eb.fn<string | null>('nullif', [eb.ref('tp.taken_at'), eb.val('')]),
@@ -78,7 +101,12 @@ function galleryChronologicalOrderExpr(
eb2,
{ column: 'je.entry_date' },
{ value: 'T' },
{ expression: eb2.fn.coalesce(eb2.fn<string | null>('nullif', [eb2.ref('je.entry_time'), eb2.val('')]), eb2.val('00:00')) },
{
expression: eb2.fn.coalesce(
eb2.fn<string | null>('nullif', [eb2.ref('je.entry_time'), eb2.val('')]),
eb2.val('00:00'),
),
},
),
)
.as('min_dt'),
@@ -147,7 +175,10 @@ export class JourneyPhotosRepository extends TrekRepository<JourneyPhotos> {
* already converted onto `TripPhotosRepository.existsForPhoto`).
*/
async existsForPhoto(photoId: number): Promise<boolean> {
const row = await this.qb('gp').select(['gp.id']).where({ photo: photoId }).execute<{ id: number } | undefined>('get', false);
const row = await this.qb('gp')
.select(['gp.id'])
.where({ photo: photoId })
.execute<{ id: number } | undefined>('get', false);
return !!row;
}
@@ -205,7 +236,10 @@ export class JourneyPhotosRepository extends TrekRepository<JourneyPhotos> {
* fallback stub from 3g Task 3 (this repository was still mid-flight when
* that task landed) — relocated here now that it is stable.
*/
async findGalleryPhotoForValidation(photoId: number, journeyId: number): Promise<JourneyPublicPhotoValidationRow | undefined> {
async findGalleryPhotoForValidation(
photoId: number,
journeyId: number,
): Promise<JourneyPublicPhotoValidationRow | undefined> {
return await this.kysely<GalleryKyselyDB>()
.selectFrom('journey_photos as gp')
.innerJoin('trek_photos as tkp', 'tkp.id', 'gp.photo_id')
@@ -227,7 +261,10 @@ export class JourneyPhotosRepository extends TrekRepository<JourneyPhotos> {
* resolves `ownerId`. Relocated the same way as {@link
* findGalleryPhotoForValidation}/JS7.
*/
async findAssetForValidation(assetId: string, journeyId: number): Promise<JourneyPublicAssetValidationRow | undefined> {
async findAssetForValidation(
assetId: string,
journeyId: number,
): Promise<JourneyPublicAssetValidationRow | undefined> {
return await this.kysely<GalleryKyselyDB>()
.selectFrom('journey_photos as gp')
.innerJoin('trek_photos as tkp', 'tkp.id', 'gp.photo_id')
@@ -323,10 +360,7 @@ export class JourneyPhotosRepository extends TrekRepository<JourneyPhotos> {
/** JG105 — `deleteGalleryPhoto`'s pre-delete read: `SELECT * FROM journey_photos WHERE id = ?`. */
async findFull(id: number): Promise<JourneyPhotoFullRow | undefined> {
return await this.qb('gp')
.select(['gp.*'])
.where({ id })
.execute<JourneyPhotoFullRow | undefined>('get', false);
return await this.qb('gp').select(['gp.*']).where({ id }).execute<JourneyPhotoFullRow | undefined>('get', false);
}
/** JG108 — `setPhotoProvider`'s `trek_photos.id` resolution: `SELECT photo_id FROM journey_photos WHERE id = ?`. Relation property (`gp.photo`), not the shadow column — see {@link findScopeById}'s docstring. */
@@ -114,7 +114,10 @@ export class JourneyShareTokensRepository extends TrekRepository<JourneyShareTok
/** JS4 — `getJourneyShareLink`: `SELECT * FROM journey_share_tokens WHERE journey_id = ?`. */
async findByJourneyId(journeyId: number): Promise<JourneyShareTokenRow | undefined> {
return await this.qb('jst').select(['jst.*']).where({ journey: journeyId }).execute<JourneyShareTokenRow | undefined>('get', false);
return await this.qb('jst')
.select(['jst.*'])
.where({ journey: journeyId })
.execute<JourneyShareTokenRow | undefined>('get', false);
}
/** JS5 — `deleteJourneyShareLink`: `DELETE FROM journey_share_tokens WHERE journey_id = ?`. */
@@ -146,7 +149,10 @@ export class JourneyShareTokensRepository extends TrekRepository<JourneyShareTok
/** JS11 — `getPublicJourney`'s entrypoint read: `SELECT * FROM journey_share_tokens WHERE token = ?`. Exact-match only (R4), same as {@link findAccessByToken}. */
async findByToken(token: string): Promise<JourneyShareTokenRow | undefined> {
return await this.qb('jst').select(['jst.*']).where({ token }).execute<JourneyShareTokenRow | undefined>('get', false);
return await this.qb('jst')
.select(['jst.*'])
.where({ token })
.execute<JourneyShareTokenRow | undefined>('get', false);
}
// JS7/JS10 — `validateShareTokenForPhoto`'s/`validateShareTokenForAsset`'s
@@ -1,6 +1,6 @@
import type { JourneyTrips } from '../entities/JourneyTrips.entity';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
/** JG17's trip-link row (`getJourneyFull`) — the junction plus the joined trip summary and its place count. */
export interface JourneyTripLinkRow {
@@ -126,7 +126,17 @@ export class JourneyTripsRepository extends TrekRepository<JourneyTrips> {
.selectFrom('places as p')
.innerJoin('day_assignments as da', 'da.place_id', 'p.id')
.innerJoin('days as d', 'd.id', 'da.day_id')
.select(['p.id', 'p.name', 'p.address', 'p.lat', 'p.lng', 'p.place_time', 'da.id as assignment_id', 'd.date as day_date', 'da.assignment_time'])
.select([
'p.id',
'p.name',
'p.address',
'p.lat',
'p.lng',
'p.place_time',
'da.id as assignment_id',
'd.date as day_date',
'da.assignment_time',
])
.where('p.trip_id', '=', tripId)
.orderBy('d.day_number', 'asc')
.orderBy('da.order_index', 'asc')
@@ -140,7 +150,17 @@ export class JourneyTripsRepository extends TrekRepository<JourneyTrips> {
.selectFrom('places as p')
.innerJoin('day_assignments as da', 'da.place_id', 'p.id')
.innerJoin('days as d', 'd.id', 'da.day_id')
.select(['p.id', 'p.name', 'p.address', 'p.lat', 'p.lng', 'p.place_time', 'da.id as assignment_id', 'd.date as day_date', 'da.assignment_time'])
.select([
'p.id',
'p.name',
'p.address',
'p.lat',
'p.lng',
'p.place_time',
'da.id as assignment_id',
'd.date as day_date',
'da.assignment_time',
])
.where('p.id', '=', placeId)
.orderBy('d.day_number', 'asc')
.orderBy('da.order_index', 'asc')
@@ -1,6 +1,6 @@
import type { Journeys } from '../entities/Journeys.entity';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
/**
* `SELECT * FROM journeys WHERE id = ?`'s row — every scalar column the
@@ -41,7 +41,10 @@ export interface JourneyListRow extends JourneyRow {
}
/** The `journeys`/`journey_contributors`/`journey_entries`/`journey_photos`/`journey_trips`/`trips` tables {@link JourneysRepository.listForUser} reads. */
type JourneyListKyselyDB = Pick<DB, 'journeys' | 'journey_contributors' | 'journey_entries' | 'journey_photos' | 'journey_trips' | 'trips'>;
type JourneyListKyselyDB = Pick<
DB,
'journeys' | 'journey_contributors' | 'journey_entries' | 'journey_photos' | 'journey_trips' | 'trips'
>;
/** The `journeys`/`journey_contributors` tables {@link JourneysRepository.listRecipientUserIds} reads. */
type JourneyRecipientsKyselyDB = Pick<DB, 'journeys' | 'journey_contributors'>;
@@ -130,7 +133,9 @@ export class JourneysRepository extends TrekRepository<Journeys> {
async listForUser(user_id: number): Promise<JourneyListRow[]> {
const rows = await this.kysely<JourneyListKyselyDB>()
.selectFrom('journeys as j')
.leftJoin('journey_contributors as jc', (join) => join.onRef('jc.journey_id', '=', 'j.id').on('jc.user_id', '=', user_id))
.leftJoin('journey_contributors as jc', (join) =>
join.onRef('jc.journey_id', '=', 'j.id').on('jc.user_id', '=', user_id),
)
.selectAll('j')
.select((eb) => [
eb
@@ -171,7 +176,13 @@ export class JourneysRepository extends TrekRepository<Journeys> {
}
/** JG9 — `createJourney`'s INSERT: `(user_id, title, subtitle, status, created_at, updated_at)`, `status` hard-coded `'active'` like the legacy statement. */
async insertJourney(data: { user_id: number; title: string; subtitle: string | null; created_at: number; updated_at: number }): Promise<number> {
async insertJourney(data: {
user_id: number;
title: string;
subtitle: string | null;
created_at: number;
updated_at: number;
}): Promise<number> {
return await this.insert({
user: data.user_id,
title: data.title,
@@ -105,7 +105,9 @@ export class MaintenanceRepository {
for (const table of ['plugin_user_config', 'plugin_oauth_tokens', 'plugin_oauth_state']) {
try {
await this.em.getConnection().execute(`DELETE FROM ${table} WHERE user_id = ?`, [userId], 'run', ctx);
} catch { /* table absent (slim schema) */ }
} catch {
/* table absent (slim schema) */
}
}
}
}
@@ -1,6 +1,6 @@
import { columnRef, currentTimestamp } from '../dialect/sql-functions';
import { McpTokens } from '../entities/McpTokens.entity';
import type { AssertRowKeys } from './_shared/rows';
import { columnRef, currentTimestamp } from '../dialect/sql-functions';
import { TrekRepository } from './_shared/trek-repository';
/**
@@ -312,7 +312,15 @@ export class McpTokensRepository extends TrekRepository<McpTokens> {
const platform = this.getEntityManager().getPlatform();
const rows = await this.qb('t')
.innerJoin('t.user', 'u')
.select(['t.id', 't.name', 't.token_prefix', 't.created_at', 't.last_used_at', columnRef(platform, 't.user_id'), 'u.username'])
.select([
't.id',
't.name',
't.token_prefix',
't.created_at',
't.last_used_at',
columnRef(platform, 't.user_id'),
'u.username',
])
.orderBy({ 't.created_at': 'desc' })
.execute<McpTokenWithUsernameRow[]>('all', false);
return rows.map((row) => ({
@@ -1,7 +1,7 @@
import type { Notifications } from '../entities/Notifications.entity';
import type { DB } from '../kysely/db';
import { type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
/**
* A bare `notifications` row — every scalar column of the entity, incl. the
@@ -178,7 +178,11 @@ export class NotificationsRepository extends TrekRepository<Notifications> {
/** NT7/NT9/NT19 — `SELECT * FROM notifications WHERE id = ?`, full row incl. the persist(false) mirrors. */
async findById(id: number): Promise<NotificationRow | undefined> {
return await this.kysely<NotificationsKyselyDB>().selectFrom('notifications').selectAll().where('id', '=', id).executeTakeFirst();
return await this.kysely<NotificationsKyselyDB>()
.selectFrom('notifications')
.selectAll()
.where('id', '=', id)
.executeTakeFirst();
}
/** NT19 — `respond`'s recipient-scoped initial read: `SELECT * FROM notifications WHERE id = ? AND recipient_id = ?`. */
@@ -192,7 +196,12 @@ export class NotificationsRepository extends TrekRepository<Notifications> {
}
/** NT10 — `listInApp`'s joined page read, `unreadOnly` toggling the extra `is_read = 0` predicate (the legacy statement's two dynamic-WHERE variants). */
async listForRecipient(recipientId: number, limit: number, offset: number, unreadOnly: boolean): Promise<NotificationJoinRow[]> {
async listForRecipient(
recipientId: number,
limit: number,
offset: number,
unreadOnly: boolean,
): Promise<NotificationJoinRow[]> {
let q = this.joinedQuery().where('n.recipient_id', '=', recipientId);
if (unreadOnly) q = q.where('n.is_read', '=', 0);
return await q.orderBy('n.created_at', 'desc').limit(limit).offset(offset).execute();
@@ -15,10 +15,10 @@ export interface OauthClientRow {
name: string;
client_id: string;
client_secret_hash: string;
redirect_uris: string; // JSON array
redirect_uris: string; // JSON array
allowed_scopes: string; // JSON array
created_at: string | null;
is_public: number; // 0 | 1
is_public: number; // 0 | 1
created_via: string;
allows_client_credentials: number; // 0 | 1
}
@@ -129,7 +129,18 @@ export class OauthClientsRepository extends TrekRepository<OauthClients> {
const rows = await this.find(
{ user: userId },
{
fields: ['id', 'user', 'name', 'client_id', 'redirect_uris', 'allowed_scopes', 'created_at', 'is_public', 'created_via', 'allows_client_credentials'],
fields: [
'id',
'user',
'name',
'client_id',
'redirect_uris',
'allowed_scopes',
'created_at',
'is_public',
'created_via',
'allows_client_credentials',
],
orderBy: { created_at: 'desc' },
},
);
@@ -213,7 +224,18 @@ export class OauthClientsRepository extends TrekRepository<OauthClients> {
const row = await this.findOne(
{ id },
{
fields: ['id', 'user', 'name', 'client_id', 'redirect_uris', 'allowed_scopes', 'created_at', 'is_public', 'created_via', 'allows_client_credentials'],
fields: [
'id',
'user',
'name',
'client_id',
'redirect_uris',
'allowed_scopes',
'created_at',
'is_public',
'created_via',
'allows_client_credentials',
],
},
);
return row
@@ -247,10 +269,7 @@ export class OauthClientsRepository extends TrekRepository<OauthClients> {
* unscoped read.
*/
async findOwned(id: string, userId: number): Promise<OauthClientOwnedRow | null> {
const row = await this.findOne(
{ id, user: userId },
{ fields: ['id', 'client_id', 'is_public'] },
);
const row = await this.findOne({ id, user: userId }, { fields: ['id', 'client_id', 'is_public'] });
return row ? { id: row.id as string, client_id: row.client_id, is_public: row.is_public } : null;
}
@@ -288,7 +307,14 @@ export class OauthClientsRepository extends TrekRepository<OauthClients> {
{ fields: ['client_id', 'name', 'redirect_uris', 'allowed_scopes', 'is_public', 'created_via'] },
);
return row
? { client_id: row.client_id, name: row.name, redirect_uris: row.redirect_uris, allowed_scopes: row.allowed_scopes, is_public: row.is_public, created_via: row.created_via }
? {
client_id: row.client_id,
name: row.name,
redirect_uris: row.redirect_uris,
allowed_scopes: row.allowed_scopes,
is_public: row.is_public,
created_via: row.created_via,
}
: null;
}
@@ -309,7 +335,9 @@ export class OauthClientsRepository extends TrekRepository<OauthClients> {
{ client_id: clientId },
{ fields: ['client_id', 'client_secret_hash', 'is_public'] },
);
return row ? { client_id: row.client_id, client_secret_hash: row.client_secret_hash, is_public: row.is_public } : null;
return row
? { client_id: row.client_id, client_secret_hash: row.client_secret_hash, is_public: row.is_public }
: null;
}
// ---------------------------------------------------------------------
@@ -1,5 +1,5 @@
import { OauthConsents } from '../entities/OauthConsents.entity';
import { currentTimestamp } from '../dialect/sql-functions';
import { OauthConsents } from '../entities/OauthConsents.entity';
import { type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
@@ -52,10 +52,7 @@ export class OauthConsentsRepository extends TrekRepository<OauthConsents> {
* method (same rule `upsertGrant` below follows for `#upsert`).
*/
async findScopes(clientId: string, userId: number): Promise<{ scopes: string } | null> {
const row = await this.findOne(
{ client: clientId, user: userId },
{ fields: ['scopes'] },
);
const row = await this.findOne({ client: clientId, user: userId }, { fields: ['scopes'] });
return row ? { scopes: row.scopes } : null;
}
@@ -1,9 +1,9 @@
import { OauthTokens } from '../entities/OauthTokens.entity';
import { type AssertRowKeys } from './_shared/rows';
import { columnRef, currentTimestamp } from '../dialect/sql-functions';
import { TrekRepository } from './_shared/trek-repository';
import { OauthTokens } from '../entities/OauthTokens.entity';
import type { DB } from '../kysely/db';
import type { DbTimestamp } from '../types';
import { type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
/**
* The Kysely-side table shape `em.getKysely()` needs for `collectChainIds`'s
@@ -259,9 +259,15 @@ export class OauthTokensRepository extends TrekRepository<OauthTokens> {
const row = await this.qb('ot')
.innerJoin('ot.user', 'u')
.select([
'ot.scopes', 'ot.audience', 'ot.revoked_at', 'ot.access_token_expires_at',
columnRef(platform, 'ot.user_id'), columnRef(platform, 'ot.client_id'),
'u.username', 'u.email', 'u.role',
'ot.scopes',
'ot.audience',
'ot.revoked_at',
'ot.access_token_expires_at',
columnRef(platform, 'ot.user_id'),
columnRef(platform, 'ot.client_id'),
'u.username',
'u.email',
'u.role',
])
.where({ 'ot.access_token_hash': hash })
.execute<OauthTokenWithUserRow | undefined>('get', false);
@@ -327,11 +333,13 @@ export class OauthTokensRepository extends TrekRepository<OauthTokens> {
async collectChainIds(rootId: number): Promise<number[]> {
const rows = await this.kysely<OauthTokensKyselyDB>()
.withRecursive('chain', (db) =>
db.selectFrom('oauth_tokens')
db
.selectFrom('oauth_tokens')
.select('id')
.where('id', '=', rootId)
.unionAll((eb) =>
eb.selectFrom('oauth_tokens as ot2')
eb
.selectFrom('oauth_tokens as ot2')
.innerJoin('chain as c', 'c.id', 'ot2.parent_token_id')
.select('ot2.id'),
),
@@ -364,7 +372,10 @@ export class OauthTokensRepository extends TrekRepository<OauthTokens> {
.deleteFrom('oauth_tokens')
.where('refresh_token_expires_at', '<', cutoff)
.where('id', 'not in', (eb) =>
eb.selectFrom('oauth_tokens as child').select('child.parent_token_id').where('child.parent_token_id', 'is not', null),
eb
.selectFrom('oauth_tokens as child')
.select('child.parent_token_id')
.where('child.parent_token_id', 'is not', null),
)
.executeTakeFirst();
const deleted = Number(result.numDeletedRows ?? 0);
@@ -433,7 +444,9 @@ export class OauthTokensRepository extends TrekRepository<OauthTokens> {
async findByRefreshTokenHash(hash: string): Promise<OauthTokenRefreshRow | null> {
const row = await this.findOne(
{ refresh_token_hash: hash },
{ fields: ['id', 'client', 'user', 'scopes', 'audience', 'refresh_token_expires_at', 'revoked_at', 'parentToken'] },
{
fields: ['id', 'client', 'user', 'scopes', 'audience', 'refresh_token_expires_at', 'revoked_at', 'parentToken'],
},
);
return row
? {
@@ -548,7 +561,11 @@ export class OauthTokensRepository extends TrekRepository<OauthTokens> {
'ot.refresh_token_expires_at',
'ot.created_at',
])
.where({ 'ot.user_id': userId, 'ot.revoked_at': null, 'ot.refresh_token_expires_at': { $gt: currentTimestamp(platform) } })
.where({
'ot.user_id': userId,
'ot.revoked_at': null,
'ot.refresh_token_expires_at': { $gt: currentTimestamp(platform) },
})
.orderBy({ 'ot.created_at': 'desc' })
.execute<OauthSessionRow[]>('all', false);
return rows.map((row) => ({
@@ -1,8 +1,8 @@
import type { PackingBags } from '../entities/PackingBags.entity';
import type { DB } from '../kysely/db';
import { presenceSet } from './_shared/presence-set';
import { type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
import { presenceSet } from './_shared/presence-set';
import type { DB } from '../kysely/db';
/** A bare `packing_bags` row — every scalar column, incl. the two `persist(false)` relation mirrors (`trip_id`, `user_id`). */
export interface PackingBagRow {
@@ -80,23 +80,41 @@ export class PackingBagsRepository extends TrekRepository<PackingBags> {
* still-accepted carry.
*/
async findInTrip(id: number, trip_id: number | string): Promise<PackingBagRow | undefined> {
return await this.db().selectFrom('packing_bags').selectAll().where('id', '=', id).where('trip_id', '=', trip_id as number).executeTakeFirst();
return await this.db()
.selectFrom('packing_bags')
.selectAll()
.where('id', '=', id)
.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();
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();
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();
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;
}
@@ -112,7 +130,11 @@ export class PackingBagsRepository extends TrekRepository<PackingBags> {
* the new row's id.
*/
async insertMinimal(trip_id: number | string, name: string, color: string): Promise<number> {
const inserted = await this.kysely<PackingBagsMinimalInsertKyselyDB>().insertInto('packing_bags').values({ trip_id: trip_id as number, name, color }).returning('id').executeTakeFirstOrThrow();
const inserted = await this.kysely<PackingBagsMinimalInsertKyselyDB>()
.insertInto('packing_bags')
.values({ trip_id: trip_id as number, name, color })
.returning('id')
.executeTakeFirstOrThrow();
return inserted.id;
}
@@ -121,14 +143,28 @@ export class PackingBagsRepository extends TrekRepository<PackingBags> {
* 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 inserted = await this.kysely<PackingBagsInsertKyselyDB>().insertInto('packing_bags').values({ ...row, trip_id: row.trip_id as number }).returning('id').executeTakeFirstOrThrow();
async insertBag(row: {
trip_id: number | string;
name: string;
color: string;
sort_order: number | null;
weight_limit_grams: number | null;
}): Promise<number> {
const inserted = await this.kysely<PackingBagsInsertKyselyDB>()
.insertInto('packing_bags')
.values({ ...row, trip_id: row.trip_id as number })
.returning('id')
.executeTakeFirstOrThrow();
return inserted.id;
}
/** 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();
return await this.db()
.selectFrom('packing_bags')
.selectAll()
.where('id', '=', id as number)
.executeTakeFirst();
}
/**
@@ -148,13 +184,21 @@ export class PackingBagsRepository extends TrekRepository<PackingBags> {
* (`:222`) and `TodoItems` (`:125`) already carry.
*/
/** `id: number`, same Plan 4 Task 8b (U6) narrowing as {@link findInTrip} (its one caller, `updateBag`, is only reached with a `toRowId`-parsed/Zod-typed id). */
async update(id: number, 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);
async update(
id: number,
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);
if (Object.keys(data).length === 0) return;
await this.db().updateTable('packing_bags').set(data).where('id', '=', id).execute();
}
@@ -177,7 +221,13 @@ export class PackingBagsRepository extends TrekRepository<PackingBags> {
/** 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();
return await this.db()
.selectFrom('packing_bags')
.selectAll()
.where('trip_id', '=', trip_id as number)
.orderBy('sort_order', 'asc')
.orderBy('id', 'asc')
.execute();
}
// ---------------------------------------------------------------------------
@@ -194,14 +244,23 @@ export class PackingBagsRepository extends TrekRepository<PackingBags> {
.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'])
.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();
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);
}
@@ -252,6 +311,10 @@ export class PackingBagsRepository extends TrekRepository<PackingBags> {
* 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();
return await this.db()
.selectFrom('packing_bags')
.selectAll()
.where('trip_id', '=', trip_id as number)
.execute();
}
}
@@ -1,6 +1,6 @@
import type { PackingCategoryAssignees } from '../entities/PackingCategoryAssignees.entity';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
/** PK58/PK61's joined projection. */
export interface PackingCategoryAssigneeRow {
@@ -46,7 +46,12 @@ export class PackingCategoryAssigneesRepository extends TrekRepository<PackingCa
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'])
.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();
}
@@ -78,7 +83,10 @@ export class PackingCategoryAssigneesRepository extends TrekRepository<PackingCa
}
/** 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'>[]> {
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')
@@ -1,6 +1,6 @@
import type { PackingItemContributors } from '../entities/PackingItemContributors.entity';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
/** PK3's contributor projection (`enrichItems`). */
export interface PackingItemContributorRow {
@@ -42,7 +42,12 @@ export class PackingItemContributorsRepository extends TrekRepository<PackingIte
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')])
.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();
}
@@ -1,10 +1,10 @@
import type { PackingItems } from '../entities/PackingItems.entity';
import { currentTimestamp } from '../dialect/sql-functions';
import type { PackingItems } from '../entities/PackingItems.entity';
import type { DB } from '../kysely/db';
import { packingVisibleToActorExpr, type PackingVisibilityKyselyDB } from './_shared/packing-visibility';
import { presenceSet } from './_shared/presence-set';
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';
import type { DB } from '../kysely/db';
/** 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 {
@@ -49,7 +49,8 @@ export interface PackingItemExportRow {
* `CalendarStayKyselyDB`/`ReservationVisibilityKyselyDB` precedent,
* `Reservations.repository.ts`).
*/
type PackingItemsKyselyDB = PackingVisibilityKyselyDB & Pick<DB, 'packing_items' | 'packing_item_recipients' | 'users' | 'packing_bags'>;
type PackingItemsKyselyDB = PackingVisibilityKyselyDB &
Pick<DB, 'packing_items' | 'packing_item_recipients' | 'users' | 'packing_bags'>;
/**
* `packing_items` — the checklist rows themselves, plus (this class's own
@@ -114,7 +115,13 @@ export class PackingItemsRepository extends TrekRepository<PackingItems> {
/** 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();
return await this.db()
.selectFrom('packing_items')
.selectAll()
.where('trip_id', '=', trip_id as number)
.orderBy('sort_order', 'asc')
.orderBy('created_at', 'asc')
.execute();
}
/**
@@ -156,13 +163,25 @@ export class PackingItemsRepository extends TrekRepository<PackingItems> {
}
/** PK6 (`getItemPrivacy`) — `SELECT is_private, owner_id FROM packing_items WHERE id = ? AND trip_id = ?`. `id: number` (Plan 4 Task 8b, U6 — the program's gate-level id parsing carry: its one caller, `PackingService.getItemPrivacy`, is only reached with a `toRowId`-parsed id); `trip_id` stays `number | string`, a separate, still-accepted carry. */
async getPrivacy(id: number, 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).where('trip_id', '=', trip_id as number).executeTakeFirst();
async getPrivacy(
id: number,
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)
.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();
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;
}
@@ -190,8 +209,16 @@ export class PackingItemsRepository extends TrekRepository<PackingItems> {
* `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;
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({
@@ -219,8 +246,15 @@ export class PackingItemsRepository extends TrekRepository<PackingItems> {
* 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;
weight_grams: number | null; quantity: number; bag_id: number | null;
trip_id: number | string;
name: string;
category: string;
sort_order: number;
is_private: number;
owner_id: number | null;
weight_grams: number | null;
quantity: number;
bag_id: number | null;
}): Promise<number> {
const platform = this.getEntityManager().getPlatform();
const id = await this.insert({
@@ -279,7 +313,11 @@ export class PackingItemsRepository extends TrekRepository<PackingItems> {
* sites now thread a `toRowId`-parsed/Zod-typed id); `trip_id` stays
* `number | string`, a separate, still-accepted carry.
*/
async findVisibleInTrip(id: number, trip_id: number | string, actorId: number | undefined): Promise<PackingItemRow | undefined> {
async findVisibleInTrip(
id: number,
trip_id: number | string,
actorId: number | undefined,
): Promise<PackingItemRow | undefined> {
if (actorId == null) return undefined;
return await this.db()
.selectFrom('packing_items')
@@ -312,21 +350,31 @@ export class PackingItemsRepository extends TrekRepository<PackingItems> {
* no `updated_at` column at all).
*/
/** `id: number`, same Plan 4 Task 8b (U6) narrowing as {@link findById} (its one caller, `updateItem`, is only reached with a `toRowId`-parsed/Zod-typed id). */
async update(id: number, write: {
name?: readonly [present: boolean, value: string | null];
checked?: readonly [present: boolean, value: number];
packed_quantity?: readonly [present: boolean, value: number | null];
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> {
async update(
id: number,
write: {
name?: readonly [present: boolean, value: string | null];
checked?: readonly [present: boolean, value: number];
packed_quantity?: readonly [present: boolean, value: number | null];
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; packed_quantity: number | null; category: string | null; weight_grams: number | null;
bag: number | null; quantity: number; is_private: number; owner: number | null;
name: string | null;
checked: number;
packed_quantity: number | null;
category: string | null;
weight_grams: number | null;
bag: number | null;
quantity: number;
is_private: number;
owner: number | null;
}>({
name: write.name,
checked: write.checked,
@@ -353,7 +401,9 @@ export class PackingItemsRepository extends TrekRepository<PackingItems> {
*/
async updateSharing(id: number, is_private: number, claimOwnerId?: number): Promise<void> {
const platform = this.getEntityManager().getPlatform();
const data = presenceSet<{ owner: number }>({ owner: claimOwnerId !== undefined ? [true, claimOwnerId] : undefined });
const data = presenceSet<{ owner: number }>({
owner: claimOwnerId !== undefined ? [true, claimOwnerId] : undefined,
});
await this.nativeUpdate({ id }, { is_private, ...data, updated_at: currentTimestamp(platform) });
}
@@ -464,7 +514,16 @@ export class PackingItemsRepository extends TrekRepository<PackingItems> {
* 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> {
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,
@@ -1,7 +1,7 @@
import type { PackingTemplateCategories } from '../entities/PackingTemplateCategories.entity';
import type { DB } from '../kysely/db';
import { type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
/** A bare `packing_template_categories` row — every scalar column, incl. the `persist(false)` `template_id` relation mirror. */
export interface PackingTemplateCategoryRow {
@@ -26,7 +26,13 @@ export class PackingTemplateCategoriesRepository extends TrekRepository<PackingT
/** 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();
return await this.db()
.selectFrom('packing_template_categories')
.selectAll()
.where('template_id', '=', template_id as number)
.orderBy('sort_order', 'asc')
.orderBy('id', 'asc')
.execute();
}
/**
@@ -37,29 +43,53 @@ export class PackingTemplateCategoriesRepository extends TrekRepository<PackingT
* with `TrekRepository`/`EntityRepository`'s own same-named method.
*/
async insertCategory(template_id: number | string, name: string, sort_order: number): Promise<number> {
const inserted = await this.kysely<PackingTemplateCategoriesInsertKyselyDB>().insertInto('packing_template_categories').values({ template_id: template_id as number, name, sort_order }).returning('id').executeTakeFirstOrThrow();
const inserted = await this.kysely<PackingTemplateCategoriesInsertKyselyDB>()
.insertInto('packing_template_categories')
.values({ template_id: template_id as number, name, sort_order })
.returning('id')
.executeTakeFirstOrThrow();
return inserted.id;
}
/** 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();
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();
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();
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();
await this.db()
.updateTable('packing_template_categories')
.set({ name })
.where('id', '=', id as number)
.execute();
}
/** PK83 (`deleteTemplateCategory`) — `DELETE FROM packing_template_categories WHERE id = ?`. */
@@ -1,7 +1,7 @@
import type { PackingTemplateItems } from '../entities/PackingTemplateItems.entity';
import type { DB } from '../kysely/db';
import { type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
/** A bare `packing_template_items` row — every scalar column, incl. the `persist(false)` `category_id` relation mirror. */
export interface PackingTemplateItemRow {
@@ -109,13 +109,21 @@ export class PackingTemplateItemsRepository extends TrekRepository<PackingTempla
/** 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();
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();
return await this.db()
.selectFrom('packing_template_items')
.selectAll()
.where('id', '=', id as number)
.executeTakeFirst();
}
/**
@@ -136,7 +144,11 @@ export class PackingTemplateItemsRepository extends TrekRepository<PackingTempla
/** 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();
await this.db()
.updateTable('packing_template_items')
.set({ name })
.where('id', '=', id as number)
.execute();
}
/** PK90 (`deleteTemplateItem`) — `DELETE FROM packing_template_items WHERE id = ?`. */
@@ -1,7 +1,7 @@
import type { PackingTemplates } from '../entities/PackingTemplates.entity';
import type { DB } from '../kysely/db';
import { type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
/** A bare `packing_templates` row — every scalar column, incl. the `persist(false)` `created_by` relation mirror. */
export interface PackingTemplateRow {
@@ -27,7 +27,10 @@ export interface PackingTemplateAdminRow extends PackingTemplateRow {
category_count: number;
}
type PackingTemplatesKyselyDB = Pick<DB, 'packing_templates' | 'packing_template_categories' | 'packing_template_items' | 'users'>;
type PackingTemplatesKyselyDB = Pick<
DB,
'packing_templates' | 'packing_template_categories' | 'packing_template_items' | 'users'
>;
/** The table `insertTemplate` (PK55/PK68) inserts into; `id`/`created_at` are `InsertOptional` in the generated type. */
type PackingTemplatesInsertKyselyDB = Pick<DB, 'packing_templates'>;
@@ -106,7 +109,11 @@ export class PackingTemplatesRepository extends TrekRepository<PackingTemplates>
* `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();
return await this.db()
.selectFrom('packing_templates')
.selectAll()
.where('id', '=', id as number)
.executeTakeFirst();
}
/**
@@ -118,13 +125,21 @@ export class PackingTemplatesRepository extends TrekRepository<PackingTemplates>
* .insertItem`'s precedent).
*/
async insertTemplate(name: string, created_by: number): Promise<number> {
const inserted = await this.kysely<PackingTemplatesInsertKyselyDB>().insertInto('packing_templates').values({ name, created_by }).returning('id').executeTakeFirstOrThrow();
const inserted = await this.kysely<PackingTemplatesInsertKyselyDB>()
.insertInto('packing_templates')
.values({ name, created_by })
.returning('id')
.executeTakeFirstOrThrow();
return inserted.id;
}
/** 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();
await this.db()
.updateTable('packing_templates')
.set({ name })
.where('id', '=', id as number)
.execute();
}
/** PK74 (`deletePackingTemplate`) — `DELETE FROM packing_templates WHERE id = ?`. */
@@ -1,7 +1,7 @@
import type { PasswordResetTokens } from '../entities/PasswordResetTokens.entity';
import type { AssertRowKeys } from './_shared/rows';
import { currentTimestamp } from '../dialect/sql-functions';
import type { PasswordResetTokens } from '../entities/PasswordResetTokens.entity';
import type { DbTimestamp } from '../types';
import type { AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
/** A `password_reset_tokens` row as the API emits it. */
@@ -102,7 +102,9 @@ export class PasswordResetTokensRepository extends TrekRepository<PasswordResetT
*/
async findByTokenHash(hash: string): Promise<PasswordResetTokenLookup | null> {
const row = await this.findOne({ token_hash: hash }, { fields: ['id', 'user', 'expires_at', 'consumed_at'] });
return row ? { id: row.id, user_id: row.user.id, expires_at: row.expires_at, consumed_at: row.consumed_at ?? null } : null;
return row
? { id: row.id, user_id: row.user.id, expires_at: row.expires_at, consumed_at: row.consumed_at ?? null }
: null;
}
/**
@@ -58,7 +58,18 @@ export class PhotoProviderFieldsRepository extends TrekRepository<PhotoProviderF
const rows = await this.find(
{},
{
fields: ['provider', 'field_key', 'label', 'input_type', 'placeholder', 'required', 'secret', 'settings_key', 'payload_key', 'sort_order'],
fields: [
'provider',
'field_key',
'label',
'input_type',
'placeholder',
'required',
'secret',
'settings_key',
'payload_key',
'sort_order',
],
orderBy: { sort_order: 'asc', id: 'asc' },
},
);
@@ -1,6 +1,6 @@
import type { Photos } from '../entities/Photos.entity';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
/** The `photos` tables {@link PhotosRepository.findTripIdByFilename} reads. */
type PhotosKyselyDB = Pick<DB, 'photos'>;
@@ -9,7 +9,11 @@ export class PlaceDetailsCacheRepository extends TrekRepository<PlaceDetailsCach
* `NOT NULL DEFAULT ''`, never NULL) and `expanded` bound to the
* `CACHE_KIND` constant.
*/
async findEntry(placeId: string, lang: string, kind: number): Promise<{ payload_json: string; fetched_at: number } | null> {
async findEntry(
placeId: string,
lang: string,
kind: number,
): Promise<{ payload_json: string; fetched_at: number } | null> {
const row = await this.findOne(
{ place_id: placeId, lang, expanded: kind },
{ fields: ['payload_json', 'fetched_at'] },
@@ -29,7 +33,13 @@ export class PlaceDetailsCacheRepository extends TrekRepository<PlaceDetailsCach
* `lang`/`expanded` values on the same place. `fetched_at` is ms-epoch,
* never `currentTimestamp`.
*/
async upsertEntry(row: { place_id: string; lang: string; expanded: number; payload_json: string; fetched_at: number }): Promise<void> {
async upsertEntry(row: {
place_id: string;
lang: string;
expanded: number;
payload_json: string;
fetched_at: number;
}): Promise<void> {
await this.upsert(row, { onConflictFields: ['place_id', 'lang', 'expanded'], onConflictAction: 'merge' });
}
}
@@ -1,6 +1,6 @@
import type { PlaceRatings } from '../entities/PlaceRatings.entity';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
/** One rated place, from `QueryHelpersService.loadRatingsByPlaceIds` (QH2). */
export interface PlaceRatingForPlaceRow {
@@ -107,6 +107,9 @@ export class PlaceRatingsRepository extends TrekRepository<PlaceRatings> {
* unique {@link upsertRating} documents.
*/
async insertIgnore(place_id: number, user_id: number, rating: number): Promise<void> {
await this.upsert({ place: place_id, user: user_id, rating }, { onConflictFields: ['place', 'user'], onConflictAction: 'ignore' });
await this.upsert(
{ place: place_id, user: user_id, rating },
{ onConflictFields: ['place', 'user'], onConflictAction: 'ignore' },
);
}
}
@@ -1,6 +1,6 @@
import type { PlaceRegions } from '../entities/PlaceRegions.entity';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
/** `place_regions` — the columns `AT28`'s `SELECT *` needs. */
export interface PlaceRegionRow {
@@ -30,7 +30,11 @@ export class PlaceRegionsRepository extends TrekRepository<PlaceRegions> {
/** AT3 (`resolvePlaceCountries`'s batch cache probe) — `SELECT place_id, country_code FROM place_regions WHERE place_id IN (...)`. Empty-array short-circuit (matches the legacy's own dynamic-`IN` guard). */
async listCountryCodesForPlaceIds(placeIds: number[]): Promise<{ place_id: number; country_code: string }[]> {
if (placeIds.length === 0) return [];
return await this.db().selectFrom('place_regions').select(['place_id', 'country_code']).where('place_id', 'in', placeIds).execute();
return await this.db()
.selectFrom('place_regions')
.select(['place_id', 'country_code'])
.where('place_id', 'in', placeIds)
.execute();
}
/** AT28 (`visitedRegions`'s cache probe) — `SELECT * FROM place_regions WHERE place_id IN (...)`. */
@@ -70,7 +74,9 @@ export class PlaceRegionsRepository extends TrekRepository<PlaceRegions> {
.where('places.id', '=', place.id)
.where('places.lat', '=', place.lat)
.where('places.lng', '=', place.lng)
.where((wb) => (place.address == null ? wb('places.address', 'is', null) : wb('places.address', '=', place.address))),
.where((wb) =>
place.address == null ? wb('places.address', 'is', null) : wb('places.address', '=', place.address),
),
)
.onConflict((oc) =>
oc.column('place_id').doUpdateSet((ub) => ({
@@ -88,7 +94,16 @@ export class PlaceRegionsRepository extends TrekRepository<PlaceRegions> {
* pr.region_code, p.lat, p.lng, p.address FROM place_regions pr JOIN places p
* ON p.id = pr.place_id ORDER BY pr.place_id`.
*/
async listWithPlaceLocation(): Promise<{ id: number; country_code: string; region_code: string; lat: number | null; lng: number | null; address: string | null }[]> {
async listWithPlaceLocation(): Promise<
{
id: number;
country_code: string;
region_code: string;
lat: number | null;
lng: number | null;
address: string | null;
}[]
> {
return await this.db()
.selectFrom('place_regions as pr')
.innerJoin('places as p', 'p.id', 'pr.place_id')
@@ -103,7 +118,14 @@ export class PlaceRegionsRepository extends TrekRepository<PlaceRegions> {
* id = ? AND lat IS ? AND lng IS ? AND address IS ?)`. Only while the place
* still holds the location the row was read with. Returns whether a row went.
*/
async deleteRegionWhileUnmoved(row: { id: number; country_code: string; region_code: string; lat: number | null; lng: number | null; address: string | null }): Promise<boolean> {
async deleteRegionWhileUnmoved(row: {
id: number;
country_code: string;
region_code: string;
lat: number | null;
lng: number | null;
address: string | null;
}): Promise<boolean> {
const result = await this.db()
.deleteFrom('place_regions')
.where('place_id', '=', row.id)
@@ -117,7 +139,9 @@ export class PlaceRegionsRepository extends TrekRepository<PlaceRegions> {
.where('places.id', '=', row.id)
.where((wb) => (row.lat == null ? wb('places.lat', 'is', null) : wb('places.lat', '=', row.lat)))
.where((wb) => (row.lng == null ? wb('places.lng', 'is', null) : wb('places.lng', '=', row.lng)))
.where((wb) => (row.address == null ? wb('places.address', 'is', null) : wb('places.address', '=', row.address))),
.where((wb) =>
row.address == null ? wb('places.address', 'is', null) : wb('places.address', '=', row.address),
),
),
)
.executeTakeFirst();
@@ -1,5 +1,5 @@
import type { PlaceShadowPicks } from '../entities/PlaceShadowPicks.entity';
import { countAll, countAllRef, maxOf, minOf, nowMinusDays } from '../dialect/sql-functions';
import type { PlaceShadowPicks } from '../entities/PlaceShadowPicks.entity';
import { toRow, type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
@@ -80,7 +80,11 @@ export class PlaceShadowPicksRepository extends TrekRepository<PlaceShadowPicks>
// coverage), unreachable, not a real "no rows" guard. Non-null
// asserted, matching the docstring's own claim.
const row = await this.qb('p')
.select([countAll(platform, 'total'), minOf(platform, 'p.created_at', 'oldest'), maxOf(platform, 'p.created_at', 'newest')])
.select([
countAll(platform, 'total'),
minOf(platform, 'p.created_at', 'oldest'),
maxOf(platform, 'p.created_at', 'newest'),
])
.execute<{ total: number; oldest: string | null; newest: string | null } | undefined>('get', false);
return { total: row!.total, oldest: row!.oldest, newest: row!.newest };
}
@@ -1,6 +1,6 @@
import type { PluginActions } from '../entities/PluginActions.entity';
import type { PluginActionScope } from '@trek/shared';
import { TrekRepository } from './_shared/trek-repository';
import type { PluginActionScope } from '@trek/shared';
/** `actionsOf`'s own projection — mapped to `PluginActionDescriptor` in the service. */
export interface PluginActionRow {
@@ -23,7 +23,13 @@ export class PluginActionsRepository extends TrekRepository<PluginActions> {
{ plugin_id: pluginId, scope },
{ fields: ['action_key', 'label', 'hint', 'danger', 'scope'], orderBy: { sort_order: 'asc' } },
);
return rows.map((r) => ({ action_key: r.action_key, label: r.label, hint: r.hint ?? null, danger: r.danger, scope: r.scope as PluginActionScope }));
return rows.map((r) => ({
action_key: r.action_key,
label: r.label,
hint: r.hint ?? null,
danger: r.danger,
scope: r.scope as PluginActionScope,
}));
}
/** PR35 (uninstall cascade) — `DELETE FROM plugin_actions WHERE plugin_id = ?`. The caller wraps this in its own try/catch (table absent on a slimmed test schema is tolerated here). */
@@ -42,7 +48,15 @@ export class PluginActionsRepository extends TrekRepository<PluginActions> {
async insertActions(pluginId: string, actions: NewPluginActionRow[]): Promise<void> {
if (!actions.length) return;
await this.insertMany(
actions.map((a) => ({ plugin_id: pluginId, action_key: a.action_key, label: a.label, hint: a.hint, danger: a.danger, scope: a.scope, sort_order: a.sort_order })),
actions.map((a) => ({
plugin_id: pluginId,
action_key: a.action_key,
label: a.label,
hint: a.hint,
danger: a.danger,
scope: a.scope,
sort_order: a.sort_order,
})),
);
}
}
@@ -1,6 +1,6 @@
import type { PluginCapabilityAudit } from '../entities/PluginCapabilityAudit.entity';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
/**
* Plan 3j Task 2 note: this repository's ONLY method today is the uninstall
@@ -42,7 +42,12 @@ export class PluginCapabilityAuditRepository extends TrekRepository<PluginCapabi
.where(
'id',
'not in',
db.selectFrom('plugin_capability_audit').select('id').where('plugin_id', '=', pluginId).orderBy('id', 'desc').limit(keep),
db
.selectFrom('plugin_capability_audit')
.select('id')
.where('plugin_id', '=', pluginId)
.orderBy('id', 'desc')
.limit(keep),
)
.execute();
}
@@ -98,7 +103,14 @@ export class PluginCapabilityAuditRepository extends TrekRepository<PluginCapabi
.orderBy('a.id', 'desc')
.limit(limit)
.execute();
return rows.map((r) => ({ ts: r.ts, plugin_id: r.plugin_id, plugin_name: r.plugin_name ?? null, method: r.method, resource: r.resource, code: r.code }));
return rows.map((r) => ({
ts: r.ts,
plugin_id: r.plugin_id,
plugin_name: r.plugin_name ?? null,
method: r.method,
resource: r.resource,
code: r.code,
}));
}
/**
@@ -111,7 +123,13 @@ export class PluginCapabilityAuditRepository extends TrekRepository<PluginCapabi
{ plugin_id: pluginId },
{ fields: ['ts', 'acting_user_id', 'method', 'resource', 'code'], orderBy: { id: 'desc' }, limit },
);
return rows.map((r) => ({ ts: r.ts, acting_user_id: r.acting_user_id ?? null, method: r.method, resource: r.resource ?? null, code: r.code }));
return rows.map((r) => ({
ts: r.ts,
acting_user_id: r.acting_user_id ?? null,
method: r.method,
resource: r.resource ?? null,
code: r.code,
}));
}
/**
@@ -28,7 +28,10 @@ export class PluginEgressHostsRepository extends TrekRepository<PluginEgressHost
async replaceAllForPlugin(pluginId: string, hosts: string[]): Promise<void> {
await this.nativeDelete({ plugin_id: pluginId });
for (const host of hosts) {
await this.upsert({ plugin_id: pluginId, host }, { onConflictFields: ['plugin_id', 'host'], onConflictAction: 'ignore' });
await this.upsert(
{ plugin_id: pluginId, host },
{ onConflictFields: ['plugin_id', 'host'], onConflictAction: 'ignore' },
);
}
}
@@ -1,5 +1,5 @@
import type { PluginEntityMetadata } from '../entities/PluginEntityMetadata.entity';
import { currentTimestamp } from '../dialect/sql-functions';
import type { PluginEntityMetadata } from '../entities/PluginEntityMetadata.entity';
import { TrekRepository } from './_shared/trek-repository';
export class PluginEntityMetadataRepository extends TrekRepository<PluginEntityMetadata> {
@@ -22,7 +22,10 @@ export class PluginEntityMetadataRepository extends TrekRepository<PluginEntityM
* narrower method for the same 4-column read.
*/
async findValue(pluginId: string, entityType: string, entityId: number, key: string): Promise<string | null> {
const row = await this.findOne({ plugin_id: pluginId, entity_type: entityType, entity_id: entityId, key }, { fields: ['value'] });
const row = await this.findOne(
{ plugin_id: pluginId, entity_type: entityType, entity_id: entityId, key },
{ fields: ['value'] },
);
return row?.value ?? null;
}
@@ -45,7 +48,14 @@ export class PluginEntityMetadataRepository extends TrekRepository<PluginEntityM
async upsertValue(pluginId: string, entityType: string, entityId: number, key: string, value: string): Promise<void> {
const platform = this.getEntityManager().getPlatform();
await this.upsert(
{ plugin_id: pluginId, entity_type: entityType, entity_id: entityId, key, value, updated_at: currentTimestamp(platform) },
{
plugin_id: pluginId,
entity_type: entityType,
entity_id: entityId,
key,
value,
updated_at: currentTimestamp(platform),
},
{
onConflictFields: ['plugin_id', 'entity_type', 'entity_id', 'key'],
onConflictAction: 'merge',
@@ -55,7 +65,11 @@ export class PluginEntityMetadataRepository extends TrekRepository<PluginEntityM
}
/** MR5 — `SELECT key, value FROM plugin_entity_metadata WHERE plugin_id=? AND entity_type=? AND entity_id=? ORDER BY key`. */
async listForEntity(pluginId: string, entityType: string, entityId: number): Promise<{ key: string; value: string }[]> {
async listForEntity(
pluginId: string,
entityType: string,
entityId: number,
): Promise<{ key: string; value: string }[]> {
const rows = await this.find(
{ plugin_id: pluginId, entity_type: entityType, entity_id: entityId },
{ fields: ['key', 'value'], orderBy: { key: 'asc' } },
@@ -87,7 +101,14 @@ export class PluginEntityMetadataRepository extends TrekRepository<PluginEntityM
* Returns whether the write happened; `false` means a NEW key was blocked
* by the cap (the caller maps that to `BadParams`, same message as before).
*/
async upsertValueCapped(pluginId: string, entityType: string, entityId: number, key: string, value: string, maxKeys: number): Promise<boolean> {
async upsertValueCapped(
pluginId: string,
entityType: string,
entityId: number,
key: string,
value: string,
maxKeys: number,
): Promise<boolean> {
return this.getEntityManager().transactional(async () => {
const exists = (await this.findValue(pluginId, entityType, entityId, key)) !== null;
if (!exists) {
@@ -1,6 +1,6 @@
import type { PluginErrorLog } from '../entities/PluginErrorLog.entity';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
/** PR2 delivery row / plugins.service.ts `errors()`'s own projection. */
export interface PluginErrorLogRow {
@@ -35,7 +35,12 @@ export class PluginErrorLogRepository extends TrekRepository<PluginErrorLog> {
.where(
'id',
'not in',
db.selectFrom('plugin_error_log').select('id').where('plugin_id', '=', pluginId).orderBy('id', 'desc').limit(retention),
db
.selectFrom('plugin_error_log')
.select('id')
.where('plugin_id', '=', pluginId)
.orderBy('id', 'desc')
.limit(retention),
)
.execute();
}
@@ -1,6 +1,6 @@
import type { PluginOauthState } from '../entities/PluginOauthState.entity';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
/**
* Plan 3j Task 2 note: this repository's ONLY method today is the uninstall
@@ -37,7 +37,13 @@ export class PluginOauthStateRepository extends TrekRepository<PluginOauthState>
}
/** PO4 (`startConnect`) — `INSERT INTO plugin_oauth_state (state, plugin_id, user_id, verifier, created_at) VALUES (?, ?, ?, ?, ?)`. */
async insertState(state: string, pluginId: string, userId: number, verifier: string, createdAt: number): Promise<void> {
async insertState(
state: string,
pluginId: string,
userId: number,
verifier: string,
createdAt: number,
): Promise<void> {
await this.insert({ state, plugin_id: pluginId, user_id: userId, verifier, created_at: createdAt });
}
@@ -1,7 +1,7 @@
import type { PluginOauthTokens } from '../entities/PluginOauthTokens.entity';
import { currentTimestampKysely } from '../dialect/kysely-functions';
import { TrekRepository } from './_shared/trek-repository';
import type { PluginOauthTokens } from '../entities/PluginOauthTokens.entity';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
/**
* Plan 3j Task 2 note: this repository's ONLY method today is the uninstall
@@ -38,14 +38,26 @@ export class PluginOauthTokensRepository extends TrekRepository<PluginOauthToken
/** PO2 (`status`) — `SELECT 1 FROM plugin_oauth_tokens WHERE plugin_id = ? AND user_id = ? AND access_token IS NOT NULL`, as a boolean existence check. */
async hasAccessToken(pluginId: string, userId: number): Promise<boolean> {
const row = await this.findOne({ plugin_id: pluginId, user_id: userId, access_token: { $ne: null } }, { fields: ['plugin_id'] });
const row = await this.findOne(
{ plugin_id: pluginId, user_id: userId, access_token: { $ne: null } },
{ fields: ['plugin_id'] },
);
return row !== null;
}
/** PO8 (`getAccessToken`) — `SELECT access_token, refresh_token, expires_at FROM plugin_oauth_tokens WHERE plugin_id = ? AND user_id = ?`. */
async findTokenRow(pluginId: string, userId: number): Promise<PluginOauthTokenRow | null> {
const row = await this.findOne({ plugin_id: pluginId, user_id: userId }, { fields: ['access_token', 'refresh_token', 'expires_at'] });
return row ? { access_token: row.access_token ?? null, refresh_token: row.refresh_token ?? null, expires_at: row.expires_at ?? null } : null;
const row = await this.findOne(
{ plugin_id: pluginId, user_id: userId },
{ fields: ['access_token', 'refresh_token', 'expires_at'] },
);
return row
? {
access_token: row.access_token ?? null,
refresh_token: row.refresh_token ?? null,
expires_at: row.expires_at ?? null,
}
: null;
}
/** PO9 (`disconnect`) — `DELETE FROM plugin_oauth_tokens WHERE plugin_id = ? AND user_id = ?`. */
@@ -104,7 +116,8 @@ export class PluginOauthTokensRepository extends TrekRepository<PluginOauthToken
.onConflict((oc) =>
oc.columns(['plugin_id', 'user_id']).doUpdateSet({
access_token: (eb) => eb.ref('excluded.access_token'),
refresh_token: (eb) => eb.fn.coalesce(eb.ref('excluded.refresh_token'), eb.ref('plugin_oauth_tokens.refresh_token')),
refresh_token: (eb) =>
eb.fn.coalesce(eb.ref('excluded.refresh_token'), eb.ref('plugin_oauth_tokens.refresh_token')),
expires_at: (eb) => eb.ref('excluded.expires_at'),
scope: (eb) => eb.ref('excluded.scope'),
updated_at: () => currentTimestampKysely(platform),
@@ -32,7 +32,13 @@ export class PluginScheduledTasksRepository extends TrekRepository<PluginSchedul
{ due_at: { $lte: now }, plugin_id: { $in: pluginIds } },
{ fields: ['id', 'plugin_id', 'name', 'payload', 'every_ms'], orderBy: { due_at: 'asc' }, limit },
);
return rows.map((r) => ({ id: r.id, plugin_id: r.plugin_id, name: r.name, payload: r.payload, every_ms: r.every_ms ?? null }));
return rows.map((r) => ({
id: r.id,
plugin_id: r.plugin_id,
name: r.name,
payload: r.payload,
every_ms: r.every_ms ?? null,
}));
}
/**
@@ -103,8 +109,18 @@ export class PluginScheduledTasksRepository extends TrekRepository<PluginSchedul
*/
async upsertTask(input: PluginScheduledTaskUpsertInput): Promise<void> {
await this.upsert(
{ plugin_id: input.plugin_id, name: input.name, due_at: input.due_at, payload: input.payload, every_ms: input.every_ms },
{ onConflictFields: ['plugin_id', 'name'], onConflictAction: 'merge', onConflictMergeFields: ['due_at', 'payload', 'every_ms'] },
{
plugin_id: input.plugin_id,
name: input.name,
due_at: input.due_at,
payload: input.payload,
every_ms: input.every_ms,
},
{
onConflictFields: ['plugin_id', 'name'],
onConflictAction: 'merge',
onConflictMergeFields: ['due_at', 'payload', 'every_ms'],
},
);
}
@@ -62,7 +62,17 @@ export class PluginSettingsFieldsRepository extends TrekRepository<PluginSetting
const rows = await this.find(
{ plugin_id: pluginId, scope },
{
fields: ['field_key', 'label', 'input_type', 'placeholder', 'hint', 'required', 'secret', 'options', 'default_value'],
fields: [
'field_key',
'label',
'input_type',
'placeholder',
'hint',
'required',
'secret',
'options',
'default_value',
],
orderBy: [{ sort_order: 'asc' }, { id: 'asc' }],
},
);
@@ -111,7 +121,10 @@ export class PluginSettingsFieldsRepository extends TrekRepository<PluginSetting
* this repository's own established convention on every other `scope`-taking
* method here).
*/
async listFieldKeysWithSecretFlag(pluginId: string, scope: 'instance' | 'user'): Promise<Array<{ field_key: string; secret: number }>> {
async listFieldKeysWithSecretFlag(
pluginId: string,
scope: 'instance' | 'user',
): Promise<Array<{ field_key: string; secret: number }>> {
const rows = await this.find({ plugin_id: pluginId, scope }, { fields: ['field_key', 'secret'] });
return rows.map((r) => ({ field_key: r.field_key, secret: r.secret }));
}
@@ -153,7 +166,10 @@ export class PluginSettingsFieldsRepository extends TrekRepository<PluginSetting
* manifest parse drops it before it ever reaches a row) — the `secret = 0` filter is
* belt-and-braces, kept exactly as the legacy statement had it.
*/
async listDefaults(pluginId: string, scope: 'instance' | 'user'): Promise<Array<{ field_key: string; default_value: string }>> {
async listDefaults(
pluginId: string,
scope: 'instance' | 'user',
): Promise<Array<{ field_key: string; default_value: string }>> {
const rows = await this.find(
{ plugin_id: pluginId, scope, secret: 0, default_value: { $ne: null } },
{ fields: ['field_key', 'default_value'] },
@@ -1,5 +1,5 @@
import type { PluginUserConfig } from '../entities/PluginUserConfig.entity';
import { currentTimestamp } from '../dialect/sql-functions';
import type { PluginUserConfig } from '../entities/PluginUserConfig.entity';
import { TrekRepository } from './_shared/trek-repository';
/** `exportUserData`'s own per-user config scan. */
@@ -40,7 +40,11 @@ export class PluginUserConfigRepository extends TrekRepository<PluginUserConfig>
const platform = this.getEntityManager().getPlatform();
await this.upsert(
{ plugin_id: pluginId, user_id: userId, config, updated_at: currentTimestamp(platform) },
{ onConflictFields: ['plugin_id', 'user_id'], onConflictAction: 'merge', onConflictMergeFields: ['config', 'updated_at'] },
{
onConflictFields: ['plugin_id', 'user_id'],
onConflictAction: 'merge',
onConflictMergeFields: ['config', 'updated_at'],
},
);
}
@@ -1,6 +1,6 @@
import type { PluginUserErasureQueue } from '../entities/PluginUserErasureQueue.entity';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
/** The drain's own pending-row projection. */
export interface PendingErasureRow {
@@ -15,7 +15,10 @@ type PluginUserErasureQueueKyselyDB = Pick<DB, 'plugin_user_erasure_queue' | 'pl
export class PluginUserErasureQueueRepository extends TrekRepository<PluginUserErasureQueue> {
/** PR8 — `INSERT OR IGNORE INTO plugin_user_erasure_queue (plugin_id, user_id) VALUES (?, ?)` (idempotent — a duplicate enqueue for the same pair is a no-op). */
async insertIgnore(pluginId: string, userId: number): Promise<void> {
await this.upsert({ plugin_id: pluginId, user_id: userId }, { onConflictFields: ['plugin_id', 'user_id'], onConflictAction: 'ignore' });
await this.upsert(
{ plugin_id: pluginId, user_id: userId },
{ onConflictFields: ['plugin_id', 'user_id'], onConflictAction: 'ignore' },
);
}
/**
@@ -1,5 +1,5 @@
import type { Plugins } from '../entities/Plugins.entity';
import { currentTimestamp } from '../dialect/sql-functions';
import type { Plugins } from '../entities/Plugins.entity';
import { TrekRepository } from './_shared/trek-repository';
/**
@@ -128,7 +128,12 @@ export class PluginsRepository extends TrekRepository<Plugins> {
/** PR15/PR16/PR25 — `SELECT id, version, enabled, dependencies FROM plugins` (identical text, three call sites: `installedDepRows`, `deactivateForDisabledAddon`, `deactivateWithDependents`). */
async listDepRows(): Promise<PluginDepListRow[]> {
const rows = await this.find({}, { fields: ['id', 'version', 'enabled', 'dependencies'] });
return rows.map((r) => ({ id: r.id ?? '', version: r.version ?? null, enabled: r.enabled, dependencies: r.dependencies ?? null }));
return rows.map((r) => ({
id: r.id ?? '',
version: r.version ?? null,
enabled: r.enabled,
dependencies: r.dependencies ?? null,
}));
}
// -----------------------------------------------------------------------
@@ -137,7 +142,10 @@ export class PluginsRepository extends TrekRepository<Plugins> {
/** PR17 — `SELECT permissions, granted_permissions, dependencies, trek_range, api_version FROM plugins WHERE id = ?`. */
async findActivationGate(id: string): Promise<PluginActivationGateRow | null> {
const row = await this.findOne({ id }, { fields: ['permissions', 'granted_permissions', 'dependencies', 'trek_range', 'api_version'] });
const row = await this.findOne(
{ id },
{ fields: ['permissions', 'granted_permissions', 'dependencies', 'trek_range', 'api_version'] },
);
return row
? {
permissions: row.permissions ?? '[]',
@@ -195,7 +203,9 @@ export class PluginsRepository extends TrekRepository<Plugins> {
/** PR26 — `SELECT enabled, granted_permissions, version FROM plugins WHERE id = ?`. */
async findPreUpdateSnapshot(id: string): Promise<PluginPreUpdateRow | null> {
const row = await this.findOne({ id }, { fields: ['enabled', 'granted_permissions', 'version'] });
return row ? { enabled: row.enabled, granted_permissions: row.granted_permissions ?? '', version: row.version ?? null } : null;
return row
? { enabled: row.enabled, granted_permissions: row.granted_permissions ?? '', version: row.version ?? null }
: null;
}
// -----------------------------------------------------------------------
@@ -344,9 +354,27 @@ export class PluginsRepository extends TrekRepository<Plugins> {
{},
{
fields: [
'id', 'name', 'description', 'type', 'icon', 'version', 'status', 'enabled', 'last_error', 'reviewed_at', 'source_repo',
'permissions', 'capabilities', 'dependencies', 'operator_egress', 'trek_range', 'author_pubkey',
'update_block_code', 'update_block_detail', 'update_block_version', 'update_hold',
'id',
'name',
'description',
'type',
'icon',
'version',
'status',
'enabled',
'last_error',
'reviewed_at',
'source_repo',
'permissions',
'capabilities',
'dependencies',
'operator_egress',
'trek_range',
'author_pubkey',
'update_block_code',
'update_block_detail',
'update_block_version',
'update_hold',
],
orderBy: [{ sort_order: 'asc' }, { name: 'asc' }],
},
@@ -470,7 +498,10 @@ export class PluginsRepository extends TrekRepository<Plugins> {
/** SG1 — `UPDATE plugins SET update_block_code = ?, update_block_detail = ?, update_block_version = ? WHERE id = ?` (`setUpdateBlock`, a signature-verification failure). */
async setUpdateBlockColumns(id: string, code: string, detail: string, version: string | null): Promise<void> {
await this.nativeUpdate({ id }, { update_block_code: code, update_block_detail: detail, update_block_version: version });
await this.nativeUpdate(
{ id },
{ update_block_code: code, update_block_detail: detail, update_block_version: version },
);
}
/** SG2 — `UPDATE plugins SET update_block_code = NULL, update_block_detail = NULL, update_block_version = NULL WHERE id = ?` (`clearUpdateBlock`, the inverse — a successful install/update). */
@@ -485,8 +516,17 @@ export class PluginsRepository extends TrekRepository<Plugins> {
// -----------------------------------------------------------------------
/** RG2 (`install`'s post-discover provenance write) — `UPDATE plugins SET source_repo = ?, source_commit = ?, sha256 = ?, reviewed_at = ? WHERE id = ?`. */
async setInstallProvenance(id: string, sourceRepo: string, sourceCommit: string, sha256: string, reviewedAt: string | null): Promise<void> {
await this.nativeUpdate({ id }, { source_repo: sourceRepo, source_commit: sourceCommit, sha256, reviewed_at: reviewedAt });
async setInstallProvenance(
id: string,
sourceRepo: string,
sourceCommit: string,
sha256: string,
reviewedAt: string | null,
): Promise<void> {
await this.nativeUpdate(
{ id },
{ source_repo: sourceRepo, source_commit: sourceCommit, sha256, reviewed_at: reviewedAt },
);
}
/** RG3 (`install`'s TOFU pin) — `UPDATE plugins SET author_pubkey = ? WHERE id = ?`. Security-sensitive: only ever called with a key the artifact just verified under (see `registry.service.ts#install`'s own docstring) — never cleared to NULL by this method. */
@@ -534,7 +574,9 @@ export class PluginsRepository extends TrekRepository<Plugins> {
}
/** RG11 (`assertRetrustable`) — `SELECT source_repo, author_pubkey FROM plugins WHERE id = ?`. */
async findSourceRepoAndAuthorPubkey(id: string): Promise<{ source_repo: string | null; author_pubkey: string | null } | null> {
async findSourceRepoAndAuthorPubkey(
id: string,
): Promise<{ source_repo: string | null; author_pubkey: string | null } | null> {
const row = await this.findOne({ id }, { fields: ['source_repo', 'author_pubkey'] });
return row ? { source_repo: row.source_repo ?? null, author_pubkey: row.author_pubkey ?? null } : null;
}
@@ -556,7 +598,10 @@ export class PluginsRepository extends TrekRepository<Plugins> {
async findActiveFeedRows(): Promise<PluginFeedRow[]> {
const rows = await this.find(
{ status: 'active' },
{ fields: ['id', 'name', 'type', 'icon', 'capabilities', 'granted_permissions'], orderBy: [{ sort_order: 'asc' }, { name: 'asc' }] },
{
fields: ['id', 'name', 'type', 'icon', 'capabilities', 'granted_permissions'],
orderBy: [{ sort_order: 'asc' }, { name: 'asc' }],
},
);
return rows.map((r) => ({
id: r.id ?? '',
@@ -1,9 +1,9 @@
import type { PushSubscriptions } from '../entities/PushSubscriptions.entity';
import { columnIncrementedBy, currentTimestamp } from '../dialect/sql-functions';
import { currentTimestampKysely } from '../dialect/kysely-functions';
import { columnIncrementedBy, currentTimestamp } from '../dialect/sql-functions';
import type { PushSubscriptions } from '../entities/PushSubscriptions.entity';
import type { DB } from '../kysely/db';
import type { AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
/** A `push_subscriptions` row exactly as `SELECT *` reads it (Web Push, #894). */
export interface PushSubscriptionRow {
@@ -1,7 +1,7 @@
import type { ReservationDayPositions } from '../entities/ReservationDayPositions.entity';
import { columnRef } from '../dialect/sql-functions';
import { TrekRepository } from './_shared/trek-repository';
import type { ReservationDayPositions } from '../entities/ReservationDayPositions.entity';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
/** `reservation_day_positions`/`reservations`/`days`'s shape for RS31's Kysely upsert. */
type ReservationDayPositionsKyselyDB = Pick<DB, 'reservation_day_positions' | 'reservations' | 'days'>;
@@ -23,7 +23,11 @@ export class ReservationDayPositionsRepository extends TrekRepository<Reservatio
// entity instead); `columnRef` selects the literal physical column.
return this.qb('rdp')
.join('rdp.reservation', 'r')
.select([columnRef(platform, 'rdp.reservation_id').as('reservation_id'), columnRef(platform, 'rdp.day_id').as('day_id'), 'rdp.position'])
.select([
columnRef(platform, 'rdp.reservation_id').as('reservation_id'),
columnRef(platform, 'rdp.day_id').as('day_id'),
'rdp.position',
])
.where({ 'r.trip': trip_id })
.execute<{ reservation_id: number; day_id: number; position: number }[]>('all', false);
}
@@ -42,7 +46,12 @@ export class ReservationDayPositionsRepository extends TrekRepository<Reservatio
* insert, never a foreign-key error) — preserved exactly, not hoisted
* into a pre-check.
*/
async upsertScoped(trip_id: number | string, reservation_id: number, day_id: number, position: number): Promise<void> {
async upsertScoped(
trip_id: number | string,
reservation_id: number,
day_id: number,
position: number,
): Promise<void> {
await this.kysely<ReservationDayPositionsKyselyDB>()
.insertInto('reservation_day_positions')
.orReplace()
@@ -1,9 +1,9 @@
import type { ReservationEndpoints } from '../entities/ReservationEndpoints.entity';
import { type AssertRowKeys } from './_shared/rows';
import { columnRef } from '../dialect/sql-functions';
import { travelerOwnsExpr, type ReservationTravelersOwnsKyselyDB } from './_shared/reservation-travelers-owns';
import { TrekRepository } from './_shared/trek-repository';
import type { ReservationEndpoints } from '../entities/ReservationEndpoints.entity';
import type { DB } from '../kysely/db';
import { travelerOwnsExpr, type ReservationTravelersOwnsKyselyDB } from './_shared/reservation-travelers-owns';
import { type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
/** A `reservation_endpoints` row exactly as `r.*`/`SELECT *` read it (every scalar column). */
export interface ReservationEndpointRow {
@@ -117,14 +117,19 @@ export class ReservationEndpointsRepository extends TrekRepository<ReservationEn
* `e.reservation_id, e.sequence`) — a genuinely different statement, per
* D4.
*/
async listFlightEndpointsForTrip(trip_id: number): Promise<{ reservation_id: number; code: string | null; local_date: string | null; sequence: number }[]> {
async listFlightEndpointsForTrip(
trip_id: number,
): Promise<{ reservation_id: number; code: string | null; local_date: string | null; sequence: number }[]> {
const platform = this.getEntityManager().getPlatform();
return this.qb('e')
.join('e.reservation', 'r')
.select([columnRef(platform, 'e.reservation_id').as('reservation_id'), 'e.code', 'e.local_date', 'e.sequence'])
.where({ 'r.trip': trip_id, 'r.type': 'flight' })
.orderBy({ sequence: 'asc' })
.execute<{ reservation_id: number; code: string | null; local_date: string | null; sequence: number }[]>('all', false);
.execute<{ reservation_id: number; code: string | null; local_date: string | null; sequence: number }[]>(
'all',
false,
);
}
// ---------------------------------------------------------------------------
@@ -155,9 +160,24 @@ export class ReservationEndpointsRepository extends TrekRepository<ReservationEn
.selectFrom('reservation_endpoints as e')
.innerJoin('reservations as r', 'r.id', 'e.reservation_id')
.select((eb) => [
'e.id', 'e.reservation_id', 'r.trip_id', 'e.role', 'e.code', 'e.lat', 'e.lng', 'e.local_date', 'e.local_time',
'r.type as reservation_type', 'r.status as reservation_status',
eb.case().when('e.role', '=', 'to').then(eb.fn.coalesce('r.reservation_end_time', 'r.reservation_time')).else(eb.fn.coalesce('r.reservation_time', 'r.reservation_end_time')).end().as('fallback_time'),
'e.id',
'e.reservation_id',
'r.trip_id',
'e.role',
'e.code',
'e.lat',
'e.lng',
'e.local_date',
'e.local_time',
'r.type as reservation_type',
'r.status as reservation_status',
eb
.case()
.when('e.role', '=', 'to')
.then(eb.fn.coalesce('r.reservation_end_time', 'r.reservation_time'))
.else(eb.fn.coalesce('r.reservation_time', 'r.reservation_end_time'))
.end()
.as('fallback_time'),
])
.distinct()
.where('r.trip_id', 'in', tripIds)
@@ -189,9 +209,24 @@ export class ReservationEndpointsRepository extends TrekRepository<ReservationEn
.innerJoin('trips as t', 't.id', 'r.trip_id')
.leftJoin('trip_members as tm', 'tm.trip_id', 't.id')
.select((eb) => [
'e.id', 'e.reservation_id', 'r.trip_id', 'e.role', 'e.code', 'e.lat', 'e.lng', 'e.local_date', 'e.local_time',
'r.type as reservation_type', 'r.status as reservation_status',
eb.case().when('e.role', '=', 'to').then(eb.fn.coalesce('r.reservation_end_time', 'r.reservation_time')).else(eb.fn.coalesce('r.reservation_time', 'r.reservation_end_time')).end().as('fallback_time'),
'e.id',
'e.reservation_id',
'r.trip_id',
'e.role',
'e.code',
'e.lat',
'e.lng',
'e.local_date',
'e.local_time',
'r.type as reservation_type',
'r.status as reservation_status',
eb
.case()
.when('e.role', '=', 'to')
.then(eb.fn.coalesce('r.reservation_end_time', 'r.reservation_time'))
.else(eb.fn.coalesce('r.reservation_time', 'r.reservation_end_time'))
.end()
.as('fallback_time'),
])
.distinct()
.where((eb) => eb.or([eb('t.user_id', '=', userId), eb('tm.user_id', '=', userId)]))
@@ -240,7 +275,15 @@ export class ReservationEndpointsRepository extends TrekRepository<ReservationEn
const platform = this.getEntityManager().getPlatform();
return this.qb('e')
.join('e.reservation', 'r')
.select([columnRef(platform, 'e.reservation_id').as('reservation_id'), 'e.role', 'e.sequence', 'e.name', 'e.code', 'e.lat', 'e.lng'])
.select([
columnRef(platform, 'e.reservation_id').as('reservation_id'),
'e.role',
'e.sequence',
'e.name',
'e.code',
'e.lat',
'e.lng',
])
.where({ 'r.trip': trip_id })
.orderBy({ 'e.reservation': 'asc', 'e.sequence': 'asc' })
.execute<RoadtripTerminalRow[]>('all', false);
@@ -275,7 +318,8 @@ export interface TravelerOwnedEndpointRow {
}
/** {@link ReservationEndpointsRepository.listOwnedEndpointsForTrips}'s `reservation_endpoints`/`reservations`/`reservation_travelers` tables (`r` aliased for `travelerOwnsExpr`, R7). */
type TravelerOwnedEndpointsKyselyDB = ReservationTravelersOwnsKyselyDB & Pick<DB, 'reservation_endpoints' | 'reservations'>;
type TravelerOwnedEndpointsKyselyDB = ReservationTravelersOwnsKyselyDB &
Pick<DB, 'reservation_endpoints' | 'reservations'>;
/** {@link ReservationEndpointsRepository.listOwnedEndpointsForUser}/{@link ReservationEndpointsRepository.listOwnedFlightLegsForUser}'s tables, adding `trips`/`trip_members` to {@link TravelerOwnedEndpointsKyselyDB}. */
type TravelerOwnedEndpointsWithTripsKyselyDB = TravelerOwnedEndpointsKyselyDB & Pick<DB, 'trips' | 'trip_members'>;
@@ -1,5 +1,5 @@
import type { ReservationTravelers } from '../entities/ReservationTravelers.entity';
import { coalesce, columnRef } from '../dialect/sql-functions';
import type { ReservationTravelers } from '../entities/ReservationTravelers.entity';
import { TrekRepository } from './_shared/trek-repository';
/** A traveler row as RS6/RR3 project it (before `toTraveler()`'s `avatar_url` add). */
@@ -30,7 +30,13 @@ export class ReservationTravelersRepository extends TrekRepository<ReservationTr
return this.qb('rt')
.join('rt.reservation', 'r')
.join('rt.user', 'u')
.select([columnRef(platform, 'rt.reservation_id').as('reservation_id'), columnRef(platform, 'rt.user_id').as('user_id'), coalesce(platform, 'u.display_name', 'u.username').as('username'), 'u.avatar', 'u.is_guest'])
.select([
columnRef(platform, 'rt.reservation_id').as('reservation_id'),
columnRef(platform, 'rt.user_id').as('user_id'),
coalesce(platform, 'u.display_name', 'u.username').as('username'),
'u.avatar',
'u.is_guest',
])
.where({ 'r.trip': trip_id })
.orderBy({ 'rt.reservation': 'asc' })
.execute<TravelerJoinRow[]>('all', false);
@@ -47,7 +53,12 @@ export class ReservationTravelersRepository extends TrekRepository<ReservationTr
const platform = this.getEntityManager().getPlatform();
return this.qb('rt')
.join('rt.user', 'u')
.select([columnRef(platform, 'rt.user_id').as('user_id'), coalesce(platform, 'u.display_name', 'u.username').as('username'), 'u.avatar', 'u.is_guest'])
.select([
columnRef(platform, 'rt.user_id').as('user_id'),
coalesce(platform, 'u.display_name', 'u.username').as('username'),
'u.avatar',
'u.is_guest',
])
.where({ reservation: reservation_id })
.execute<Omit<TravelerJoinRow, 'reservation_id'>[]>('all', false);
}
@@ -1,7 +1,7 @@
import type { RoadtripDayBoundary } from '@trek/shared';
import type { RoadtripDayBoundaries } from '../entities/RoadtripDayBoundaries.entity';
import { columnRef } from '../dialect/sql-functions';
import type { RoadtripDayBoundaries } from '../entities/RoadtripDayBoundaries.entity';
import { TrekRepository } from './_shared/trek-repository';
import type { RoadtripDayBoundary } from '@trek/shared';
/**
* `roadtrip_day_boundaries` — where a manual day ending sits (a stop, or a
@@ -23,7 +23,12 @@ export class RoadtripDayBoundariesRepository extends TrekRepository<RoadtripDayB
async listForTrip(trip_id: number): Promise<RoadtripDayBoundary[]> {
const platform = this.getEntityManager().getPlatform();
return await this.qb('b')
.select(['b.day_number', columnRef(platform, 'b.from_assignment_id'), columnRef(platform, 'b.to_assignment_id'), 'b.fraction'])
.select([
'b.day_number',
columnRef(platform, 'b.from_assignment_id'),
columnRef(platform, 'b.to_assignment_id'),
'b.fraction',
])
.where({ trip: trip_id })
.orderBy({ day_number: 'asc' })
.execute<RoadtripDayBoundary[]>('all', false);
@@ -54,7 +59,11 @@ export class RoadtripDayBoundariesRepository extends TrekRepository<RoadtripDayB
toAssignment: boundary.to_assignment_id,
fraction: boundary.fraction,
},
{ onConflictFields: ['trip', 'day_number'], onConflictAction: 'merge', onConflictMergeFields: ['fromAssignment', 'toAssignment', 'fraction'] },
{
onConflictFields: ['trip', 'day_number'],
onConflictAction: 'merge',
onConflictMergeFields: ['fromAssignment', 'toAssignment', 'fraction'],
},
);
}
@@ -1,7 +1,7 @@
import type { RoadtripDayTrack } from '@trek/shared';
import type { RoadtripDayTracks } from '../entities/RoadtripDayTracks.entity';
import { columnRef } from '../dialect/sql-functions';
import type { RoadtripDayTracks } from '../entities/RoadtripDayTracks.entity';
import { TrekRepository } from './_shared/trek-repository';
import type { RoadtripDayTrack } from '@trek/shared';
/**
* `roadtrip_day_tracks` — which recorded track (a `places` row with route
@@ -30,6 +30,9 @@ export class RoadtripPreferencesRepository extends TrekRepository<RoadtripPrefer
* `key`, the key itself).
*/
async upsertValue(trip_id: number, key: string, value: string): Promise<void> {
await this.upsert({ trip: trip_id, key, value }, { onConflictFields: ['trip', 'key'], onConflictAction: 'merge', onConflictMergeFields: ['value'] });
await this.upsert(
{ trip: trip_id, key, value },
{ onConflictFields: ['trip', 'key'], onConflictAction: 'merge', onConflictMergeFields: ['value'] },
);
}
}
@@ -1,9 +1,9 @@
import type { RoadtripVia } from '@trek/shared';
import type { AnchoredVia } from '@trek/shared/roadtrip';
import type { RoadtripVias } from '../entities/RoadtripVias.entity';
import { columnRef, maxOf } from '../dialect/sql-functions';
import type { RoadtripVias } from '../entities/RoadtripVias.entity';
import { toRow, type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
import type { RoadtripVia } from '@trek/shared';
import type { AnchoredVia } from '@trek/shared/roadtrip';
const _roadtripViaRowKeys: AssertRowKeys<RoadtripVia, RoadtripVias> = true;
@@ -31,7 +31,10 @@ export interface RoadtripViaLegRow {
export class RoadtripViasRepository extends TrekRepository<RoadtripVias> {
/** RT2/AC16/AS23 — `SELECT id, day_id, after_order_index, sequence, lat, lng, created_at FROM roadtrip_vias WHERE day_id = ? ORDER BY after_order_index, sequence, id`. */
async listForDay(day_id: number): Promise<RoadtripVia[]> {
const vias = await this.find({ day: day_id }, { orderBy: { after_order_index: 'asc', sequence: 'asc', id: 'asc' } });
const vias = await this.find(
{ day: day_id },
{ orderBy: { after_order_index: 'asc', sequence: 'asc', id: 'asc' } },
);
return vias.map((v) => toRow(v) as RoadtripVia);
}
@@ -53,7 +56,15 @@ export class RoadtripViasRepository extends TrekRepository<RoadtripVias> {
const platform = this.getEntityManager().getPlatform();
return await this.qb('v')
.join('v.day', 'd')
.select(['v.id', columnRef(platform, 'v.day_id'), 'v.after_order_index', 'v.sequence', 'v.lat', 'v.lng', 'v.created_at'])
.select([
'v.id',
columnRef(platform, 'v.day_id'),
'v.after_order_index',
'v.sequence',
'v.lat',
'v.lng',
'v.created_at',
])
.where({ 'd.trip': trip_id })
.orderBy({ 'd.id': 'asc', 'v.after_order_index': 'asc', 'v.sequence': 'asc', 'v.id': 'asc' })
.execute<RoadtripVia[]>('all', false);
@@ -78,7 +89,13 @@ export class RoadtripViasRepository extends TrekRepository<RoadtripVias> {
}
/** RT5/RT11/TP43 — `INSERT INTO roadtrip_vias (day_id, after_order_index, sequence, lat, lng) VALUES (?×5)`, returning the new id. */
async insertVia(input: { day_id: number; after_order_index: number; sequence: number; lat: number; lng: number }): Promise<number> {
async insertVia(input: {
day_id: number;
after_order_index: number;
sequence: number;
lat: number;
lng: number;
}): Promise<number> {
return await this.insert({
day: input.day_id,
after_order_index: input.after_order_index,
@@ -1,7 +1,7 @@
import type { RouteUsageDaily } from '../entities/RouteUsageDaily.entity';
import { nowDateOffset } from '../dialect/sql-functions';
import { TrekRepository } from './_shared/trek-repository';
import type { RouteUsageDaily } from '../entities/RouteUsageDaily.entity';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
/**
* A `route_usage_daily` row exactly as `SELECT *` reads it (RU3's shape,
@@ -1,6 +1,6 @@
import type { SchedulerLeases } from '../entities/SchedulerLeases.entity';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
/**
* `scheduler_leases`: which process may run a cron job's tick, and until when
@@ -23,7 +23,9 @@ export class SchedulerLeasesRepository extends TrekRepository<SchedulerLeases> {
oc
.column('name')
.doUpdateSet({ owner, expires_at: until })
.where((eb) => eb.or([eb('scheduler_leases.expires_at', '<=', now), eb('scheduler_leases.owner', '=', owner)])),
.where((eb) =>
eb.or([eb('scheduler_leases.expires_at', '<=', now), eb('scheduler_leases.owner', '=', owner)]),
),
)
.executeTakeFirst();
return (result.numInsertedOrUpdatedRows ?? 0n) > 0n;
@@ -1,7 +1,7 @@
import type { SchoolHolidayCountries } from '../entities/SchoolHolidayCountries.entity';
import type { DB } from '../kysely/db';
import { toRow, type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
import type { DB } from '../kysely/db';
/** A `school_holiday_countries` row as the API emits it (SH1/SH3 — `SchoolHolidayCountryRequest`'s exact shape, `@trek/shared`). */
export interface SchoolHolidayCountryRow {
@@ -1,6 +1,6 @@
import type { SchoolHolidayPeriod } from '@trek/shared';
import type { SchoolHolidayPeriods } from '../entities/SchoolHolidayPeriods.entity';
import { TrekRepository } from './_shared/trek-repository';
import type { SchoolHolidayPeriod } from '@trek/shared';
/**
* `school_holiday_periods`'s single-table read/write shape (Plan 3f Task 2,
@@ -57,6 +57,13 @@ export class SchoolHolidayPeriodsRepository extends TrekRepository<SchoolHoliday
*/
async insertPeriods(region_id: number, holidays: SchoolHolidayPeriod[]): Promise<void> {
if (holidays.length === 0) return;
await this.insertMany(holidays.map((holiday) => ({ region: region_id, name: holiday.name, start_date: holiday.startDate, end_date: holiday.endDate })));
await this.insertMany(
holidays.map((holiday) => ({
region: region_id,
name: holiday.name,
start_date: holiday.startDate,
end_date: holiday.endDate,
})),
);
}
}
@@ -124,7 +124,10 @@ export class SchoolHolidayRegionsRepository extends TrekRepository<SchoolHoliday
*/
async updateWithRevision(id: number, expectedRevision: number, name: string): Promise<number> {
const platform = this.getEntityManager().getPlatform();
return this.nativeUpdate({ id, revision: expectedRevision }, { name, revision: columnIncrementedBy(platform, 'revision', 1) });
return this.nativeUpdate(
{ id, revision: expectedRevision },
{ name, revision: columnIncrementedBy(platform, 'revision', 1) },
);
}
/**

Some files were not shown because too many files have changed in this diff Show More