mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-01 17:03:15 +00:00
fix(server): plan 3f close-out — ntfy operator-scope test on the live send path; vacay date-offset and shift-order parity; todo reminder window; coverage and parity ratchets for the atlas and vacay repositories
This commit is contained in:
@@ -42,6 +42,13 @@ interface TodoItemsCopyInsertKyselyDB {
|
||||
};
|
||||
}
|
||||
|
||||
/** `isoDate` + 1 calendar day, in UTC — turns {@link TodoItemsRepository.listDueForReminder}'s inclusive cutoff into an exclusive `$lt` bound (L2, task-7-review.md). */
|
||||
function dayAfter(isoDate: string): string {
|
||||
const d = new Date(`${isoDate}T00:00:00Z`);
|
||||
d.setUTCDate(d.getUTCDate() + 1);
|
||||
return d.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
/**
|
||||
* `todo_items` — Kysely throughout: `trip_id`/`assigned_user_id` are
|
||||
* `persist(false)` relation mirrors (the program-wide bare-`select`/`fields`
|
||||
@@ -192,12 +199,17 @@ export class TodoItemsRepository extends TrekRepository<TodoItems> {
|
||||
* JS-computed by the caller (`todayDate`/`cutoffDate`, both `Date.UTC`-
|
||||
* based `YYYY-MM-DD` text — matching SQLite's own UTC `date('now')`, per
|
||||
* the same reasoning RJ3's restructuring documents) and bound directly
|
||||
* against `ti.due_date` (documented elsewhere as always canonical
|
||||
* `YYYY-MM-DD` text, so `date(ti.due_date)`'s normalization is a no-op for
|
||||
* well-formed rows and the wrapping is dropped). The `datetime('now',
|
||||
* '-20 hours')` dedup bound stays genuinely in SQL, via `nowMinusHours`
|
||||
* (Task 0's R9 helper) — RJ5's brief explicitly calls for it, not a JS
|
||||
* equivalent.
|
||||
* against `ti.due_date`. `due_date` is an unconstrained `z.string()` on
|
||||
* the wire, not always canonical `YYYY-MM-DD` text, so `date(ti.due_date)`'s
|
||||
* normalization is NOT a no-op: a time-bearing due date on the cutoff day
|
||||
* itself (`2026-07-14T09:00`) sorts lexically AFTER the bare cutoff date
|
||||
* string, so a plain `$lte: cutoffDate` drops it a day early (L2,
|
||||
* task-7-review.md). `date(ti.due_date) <= cutoffDate` is reproduced as an
|
||||
* exclusive `$lt` against the day AFTER cutoff instead of re-adding the
|
||||
* `date()` wrap (Kysely `sql` is banned under repositories). The
|
||||
* `datetime('now', '-20 hours')` dedup bound stays genuinely in SQL, via
|
||||
* `nowMinusHours` (Task 0's R9 helper) — RJ5's brief explicitly calls for
|
||||
* it, not a JS equivalent.
|
||||
*/
|
||||
async listDueForReminder(todayDate: string, cutoffDate: string): Promise<TodoReminderRow[]> {
|
||||
const platform = this.getEntityManager().getPlatform();
|
||||
@@ -208,7 +220,7 @@ export class TodoItemsRepository extends TrekRepository<TodoItems> {
|
||||
.andWhere({ due_date: { $ne: null } })
|
||||
.andWhere({ due_date: { $ne: '' } })
|
||||
.andWhere({ due_date: { $gte: todayDate } })
|
||||
.andWhere({ due_date: { $lte: cutoffDate } })
|
||||
.andWhere({ due_date: { $lt: dayAfter(cutoffDate) } })
|
||||
.andWhere({ $or: [{ reminded_at: null }, { reminded_at: { $lte: nowMinusHours(platform, 20) } }] })
|
||||
.execute<TodoReminderQueryRow[]>('all', false);
|
||||
return rows.map((row) => ({
|
||||
|
||||
@@ -83,7 +83,12 @@ export class VacayEntriesRepository extends TrekRepository<VacayEntries> {
|
||||
*/
|
||||
async shiftForOwnerWindow(planId: number, userId: number, start: string, end: string, offset: number): Promise<void> {
|
||||
const platform = this.getEntityManager().getPlatform();
|
||||
const rows = await this.find({ plan: planId, user: userId, date: { $gte: start, $lte: end } }, { fields: ['id', 'date'] });
|
||||
// M1 (task-7-review.md): legacy's single `UPDATE OR IGNORE` walks rows in
|
||||
// rowid order; without an explicit orderBy here, SQLite returns rows in
|
||||
// (user, plan, date) index order instead, so the per-row collision check
|
||||
// above skips different rows than legacy did on consecutive days inserted
|
||||
// out of id order.
|
||||
const rows = await this.find({ plan: planId, user: userId, date: { $gte: start, $lte: end } }, { fields: ['id', 'date'], orderBy: { id: 'asc' } });
|
||||
for (const row of rows) {
|
||||
const shiftedDate = shiftIsoDate(row.date, offset);
|
||||
const collision = await this.findOne({ plan: planId, user: userId, date: shiftedDate }, { fields: ['id'] });
|
||||
|
||||
@@ -33,7 +33,7 @@ export class VacayUserColorsRepository extends TrekRepository<VacayUserColors> {
|
||||
* `acceptInvite`'s own-color migration and its no-collision else-branch —
|
||||
* three identical-text call sites, one method).
|
||||
*/
|
||||
async insertIgnore(userId: number, planId: number, color: string): Promise<void> {
|
||||
async insertIgnore(userId: number, planId: number, color: string | null): Promise<void> {
|
||||
await this.upsert({ user: userId, plan: planId, color }, { onConflictFields: ['user', 'plan'], onConflictAction: 'ignore' });
|
||||
}
|
||||
|
||||
|
||||
@@ -45,7 +45,7 @@ export class VacayUserYearsRepository extends TrekRepository<VacayUserYears> {
|
||||
* legacy SQL text inserts the exact same row a bound `30` does), so a
|
||||
* single flexible method, not four near-duplicates.
|
||||
*/
|
||||
async insertIgnore(userId: number, planId: number, year: number, vacationDays: number, carriedOver: number): Promise<void> {
|
||||
async insertIgnore(userId: number, planId: number, year: number, vacationDays: number | null, carriedOver: number | null): Promise<void> {
|
||||
await this.upsert(
|
||||
{ user: userId, plan: planId, year, vacation_days: vacationDays, carried_over: carriedOver },
|
||||
{ onConflictFields: ['user', 'plan', 'year'], onConflictAction: 'ignore' },
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Injectable, Logger, OnApplicationBootstrap, Optional } from '@nestjs/common';
|
||||
import { Injectable, Logger, OnApplicationBootstrap } from '@nestjs/common';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import { withRequestContext } from '../database/request-context';
|
||||
import { StorageEventsService } from '../storage/storage-events.service';
|
||||
@@ -23,11 +23,13 @@ const DEBOUNCE_WINDOW_MS = 60 * 60 * 1000;
|
||||
* its OWN fresh request context on every invocation — the same
|
||||
* `withRequestContext` shape `CronRegistrarService.register`'s wrapped tick
|
||||
* uses — independent of whatever context (if any) was active at the call
|
||||
* site that triggered the failure. `orm` is `@Optional()` (matching
|
||||
* `CronRegistrarService`'s own reasoning): a hand-built test double that
|
||||
* constructs this service directly, with no MikroORM, still gets the exact
|
||||
* pre-Task-4 behavior (send called without a context wrapper) rather than
|
||||
* failing to compile or throwing.
|
||||
* site that triggered the failure. `orm` is a required constructor param
|
||||
* (L4, task-7-review.md): in production it is always injected, so
|
||||
* `@Optional()` was a fail-open seam that existed only to serve hand-built
|
||||
* test doubles — a DI miswire would have sent without a request context
|
||||
* instead of refusing. A test double now passes the shared test ORM, the
|
||||
* same real MikroORM instance STORAGE-HEALTH-CTX-001's full `buildApp()`
|
||||
* boot exercises this against.
|
||||
*/
|
||||
@Injectable()
|
||||
export class StorageHealthNotifierService implements OnApplicationBootstrap {
|
||||
@@ -37,7 +39,7 @@ export class StorageHealthNotifierService implements OnApplicationBootstrap {
|
||||
constructor(
|
||||
private readonly events: StorageEventsService,
|
||||
private readonly notifications: NotificationsService,
|
||||
@Optional() private readonly orm?: MikroORM,
|
||||
private readonly orm: MikroORM,
|
||||
) {}
|
||||
|
||||
onApplicationBootstrap(): void {
|
||||
@@ -64,11 +66,7 @@ export class StorageHealthNotifierService implements OnApplicationBootstrap {
|
||||
`replica_failure notification failed: ${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
});
|
||||
if (this.orm) {
|
||||
void withRequestContext(this.orm, sendNotification);
|
||||
} else {
|
||||
void sendNotification();
|
||||
}
|
||||
void withRequestContext(this.orm, sendNotification);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -186,6 +186,21 @@ function windowEndYear(end: string): number {
|
||||
return end.endsWith('-01-01') ? y - 1 : y;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a date or datetime string the way SQLite's `julianday()` does — the
|
||||
* numeric components taken at face value as UTC, never the host's local
|
||||
* timezone. `Date.parse` only does this for a bare `YYYY-MM-DD`; a datetime
|
||||
* string with no zone suffix (`2025-06-12T23:30`) is local time per the ES
|
||||
* spec, which drifted from `julianday`'s always-UTC reading by whatever the
|
||||
* server's offset is (M2, task-7-review.md). Unparseable input returns `NaN`.
|
||||
*/
|
||||
function parseAsUtcMillis(value: string): number {
|
||||
const m = /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2}))?)?/.exec(value);
|
||||
if (!m) return NaN;
|
||||
const [, y, mo, d, h, mi, s] = m;
|
||||
return Date.UTC(Number(y), Number(mo) - 1, Number(d), Number(h ?? 0), Number(mi ?? 0), Number(s ?? 0));
|
||||
}
|
||||
|
||||
/**
|
||||
* Vacay domain service — owns the vacay SQL, now through the ten vacay
|
||||
* repositories (+ `SchoolHolidayRegionsRepository`'s cross-domain read,
|
||||
@@ -403,9 +418,15 @@ export class VacayService {
|
||||
// VC4 (R9's verified restructured shape): `CAST(julianday(?) - julianday(?)
|
||||
// AS INTEGER)` on two BOUND VALUES is plain JS date-diff arithmetic —
|
||||
// verified against the SQL on 5 date pairs incl. a leap-year boundary and a
|
||||
// negative offset, all matched exactly (task-0-report.md).
|
||||
const offset = Math.round((Date.parse(newStart) - Date.parse(oldStart)) / 86400000);
|
||||
if (offset === 0) return;
|
||||
// negative offset, all matched exactly (task-0-report.md). M2
|
||||
// (task-7-review.md): `trip.start_date` is an unconstrained `z.string()`,
|
||||
// so both bounds are parsed as UTC (never the host's local time) and
|
||||
// truncated — not rounded — to match `CAST(... AS INTEGER)`; a non-finite
|
||||
// offset (an unparseable start, legacy's NULL-julianday case) is a no-op,
|
||||
// same as legacy, instead of writing a NaN date and 500ing after the trip
|
||||
// row is already committed.
|
||||
const offset = Math.trunc((parseAsUtcMillis(newStart) - parseAsUtcMillis(oldStart)) / 86400000);
|
||||
if (!Number.isFinite(offset) || offset === 0) return;
|
||||
|
||||
const plan = await this.getOwnPlan(ownerId);
|
||||
|
||||
@@ -557,7 +578,14 @@ export class VacayService {
|
||||
for (const u of users) {
|
||||
const used = await this.usedDays(u.id, planId, yr);
|
||||
const config = await this.userYears.findForYear(u.id, planId, yr);
|
||||
const total = (config ? config.vacation_days ?? 30 : 30) + (config ? config.carried_over ?? 0 : 0);
|
||||
// L1 (task-7-review.md): legacy bound `config.vacation_days`/
|
||||
// `config.carried_over` into this total AS-IS, letting a NULL
|
||||
// column pass through and coerce to 0 in the `+` (JS: `null + n
|
||||
// = n`) — never defaulting a NULL vacation_days to 30. `?? 0`
|
||||
// (not `?? 30`) reproduces that exact coercion under strict
|
||||
// nullable typing; only the OUTER `config ? … : 30` (no row at
|
||||
// all) is a genuine default.
|
||||
const total = (config ? config.vacation_days ?? 0 : 30) + (config ? config.carried_over ?? 0 : 0);
|
||||
const carry = Math.max(0, total - used);
|
||||
await this.userYears.upsertCarriedOver(u.id, planId, nextYr, carry);
|
||||
}
|
||||
@@ -719,11 +747,15 @@ export class VacayService {
|
||||
await this.entries.updatePlanIdForUser(planId, ownPlan.id, userId);
|
||||
const ownYears = await this.userYears.listForUserAndPlan(userId, ownPlan.id);
|
||||
for (const y of ownYears) {
|
||||
await this.userYears.insertIgnore(userId, planId, y.year, y.vacation_days ?? 30, y.carried_over ?? 0);
|
||||
// L1 (task-7-review.md): legacy bound these AS-IS — a NULL
|
||||
// vacation_days/carried_over on the source row migrates as NULL,
|
||||
// never defaulted to 30/0.
|
||||
await this.userYears.insertIgnore(userId, planId, y.year, y.vacation_days, y.carried_over);
|
||||
}
|
||||
const colorRow = await this.userColors.findColor(userId, ownPlan.id);
|
||||
if (colorRow) {
|
||||
await this.userColors.insertIgnore(userId, planId, colorRow.color ?? '#6366f1');
|
||||
// L1: same — a NULL color migrates as NULL, not '#6366f1'.
|
||||
await this.userColors.insertIgnore(userId, planId, colorRow.color);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1020,7 +1052,10 @@ export class VacayService {
|
||||
const prevConfig = await this.userYears.findForYear(u.id, planId, year - 1);
|
||||
if (prevConfig) {
|
||||
const used = await this.usedDays(u.id, planId, year - 1);
|
||||
const total = (prevConfig.vacation_days ?? 30) + (prevConfig.carried_over ?? 0);
|
||||
// L1 (task-7-review.md): `?? 0`, not `?? 30` — reproduces
|
||||
// legacy's raw `prevConfig.vacation_days + prevConfig.carried_over`,
|
||||
// where a NULL vacation_days coerced to 0 in the `+`, never to 30.
|
||||
const total = (prevConfig.vacation_days ?? 0) + (prevConfig.carried_over ?? 0);
|
||||
carriedOver = Math.max(0, total - used);
|
||||
}
|
||||
}
|
||||
@@ -1078,7 +1113,10 @@ export class VacayService {
|
||||
const prevConfig = await this.userYears.findForYear(u.id, planId, prevYear);
|
||||
if (prevConfig) {
|
||||
const used = await this.usedDays(u.id, planId, prevYear);
|
||||
const total = (prevConfig.vacation_days ?? 30) + (prevConfig.carried_over ?? 0);
|
||||
// L1 (task-7-review.md): `?? 0`, not `?? 30` — reproduces
|
||||
// legacy's raw `prevConfig.vacation_days + prevConfig.carried_over`,
|
||||
// where a NULL vacation_days coerced to 0 in the `+`, never to 30.
|
||||
const total = (prevConfig.vacation_days ?? 0) + (prevConfig.carried_over ?? 0);
|
||||
carry = Math.max(0, total - used);
|
||||
}
|
||||
}
|
||||
@@ -1165,7 +1203,7 @@ export class VacayService {
|
||||
// rather than left silently un-transacted.
|
||||
const rows: {
|
||||
user_id: number; person_name: string; person_color: string;
|
||||
year: number; vacation_days: number; carried_over: number;
|
||||
year: number; vacation_days: number | null; carried_over: number | null;
|
||||
total_available: number; used: number; remaining: number; comp_used: number;
|
||||
window_start: string; window_end: string;
|
||||
}[] = [];
|
||||
@@ -1174,9 +1212,15 @@ export class VacayService {
|
||||
const used = await this.usedDays(u.id, planId, year);
|
||||
const compUsed = await this.compUsedDays(u.id, planId, year);
|
||||
const config = await this.userYears.findForYear(u.id, planId, year);
|
||||
const vacationDays = config ? config.vacation_days ?? 30 : 30;
|
||||
const carriedOver = carryOverEnabled ? (config ? config.carried_over ?? 0 : 0) : 0;
|
||||
const total = vacationDays + carriedOver;
|
||||
// L1 (task-7-review.md): a NULL vacation_days/carried_over passes
|
||||
// through on the wire, never defaulted to 30/0 — only the "no row at
|
||||
// all" case (`config` itself null) is a genuine default. `total`
|
||||
// still needs a number, so it null-coalesces separately, the same
|
||||
// way legacy's `vacationDays + carriedOver` silently coerced a NULL
|
||||
// operand to 0 in the `+`.
|
||||
const vacationDays = config ? config.vacation_days : 30;
|
||||
const carriedOver = carryOverEnabled ? (config ? config.carried_over : 0) : 0;
|
||||
const total = (vacationDays ?? 0) + (carriedOver ?? 0);
|
||||
const remaining = total - used;
|
||||
const colorRow = await this.userColors.findColor(u.id, planId);
|
||||
// The period this row was computed over (#737) — the UI labels the window and
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* Atlas background-geocode request-context ratchet (L5, task-7-review.md).
|
||||
*
|
||||
* `AtlasService`'s `/stats` (AT4) and `/regions` (AT29) handlers fire an
|
||||
* un-awaited IIFE after the response that reverse-geocodes a place and
|
||||
* writes through `PlaceRegionsRepository.upsertRegion` — a repository
|
||||
* method, so it validates it is running inside a request context
|
||||
* (`AsyncLocalStorage`-carried EntityManager fork) rather than the global
|
||||
* one. The reviewer traced this with a real `buildApp()` boot, a 1.2s-delayed
|
||||
* `reverseGeocodeRegion` and a spy on `upsertRegion` catching whatever it
|
||||
* would otherwise swallow: `GET /stats` writes `FR`/`FR-IDF` after the
|
||||
* response, `GET /regions` writes two places about 2.4s apart, and in both
|
||||
* cases `AsyncLocalStorage` carries the request fork with zero
|
||||
* `cannotUseGlobalContext` errors — no `withRequestContext` wrap is needed
|
||||
* in production code. Landed as a ratchet so a future refactor that breaks
|
||||
* that carry (e.g. detaching the IIFE onto a timer or a queue) fails loudly
|
||||
* here instead of only in a live-traffic gap between a response and its
|
||||
* background write.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest';
|
||||
import request from 'supertest';
|
||||
import type { Application } from 'express';
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
|
||||
vi.mock('../../src/db/database', async () => {
|
||||
const { createSnapshotTestDb, buildDbMock } = await import('../helpers/db-mock');
|
||||
return buildDbMock(createSnapshotTestDb());
|
||||
});
|
||||
vi.mock('../../src/config', () => ({
|
||||
JWT_SECRET: 'test-jwt-secret-for-trek-testing-only',
|
||||
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
|
||||
updateJwtSecret: () => {},
|
||||
SESSION_DURATION: '24h', SESSION_DURATION_MS: 86400000, SESSION_DURATION_SECONDS: 86400, DEFAULT_LANGUAGE: 'en',
|
||||
}));
|
||||
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn(), broadcastToUser: vi.fn() }));
|
||||
vi.mock('../../src/nest/atlas/atlas-geo', async (orig) => {
|
||||
const actual = await orig<typeof import('../../src/nest/atlas/atlas-geo')>();
|
||||
return {
|
||||
...actual,
|
||||
resolveCountryCodeSync: () => null,
|
||||
reverseGeocodeRegion: async (lat: number) => {
|
||||
await new Promise((r) => setTimeout(r, 1200)); // Nominatim-rate delay
|
||||
return { country_code: 'FR', region_code: lat > 45 ? 'FR-IDF' : 'FR-PAC', region_name: 'R' };
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
import { db as testDb } from '../../src/db/database';
|
||||
import { buildApp } from '../../src/bootstrap';
|
||||
import { resetTestDb } from '../helpers/test-db';
|
||||
import { createUser, createTrip, createPlace } from '../helpers/factories';
|
||||
import { authCookie } from '../helpers/auth';
|
||||
import { PlaceRegionsRepository } from '../../src/db/repositories/PlaceRegions.repository';
|
||||
|
||||
let nestApp: INestApplication;
|
||||
let app: Application;
|
||||
const errors: unknown[] = [];
|
||||
beforeAll(async () => {
|
||||
const orig = PlaceRegionsRepository.prototype.upsertRegion;
|
||||
PlaceRegionsRepository.prototype.upsertRegion = async function (...a: Parameters<typeof orig>) {
|
||||
try {
|
||||
return await orig.apply(this, a);
|
||||
} catch (e) {
|
||||
errors.push(e);
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
nestApp = await buildApp();
|
||||
app = nestApp.getHttpAdapter().getInstance();
|
||||
}, 60_000);
|
||||
afterAll(async () => {
|
||||
await nestApp.close();
|
||||
testDb.close();
|
||||
});
|
||||
|
||||
describe('AT4/AT29 background geocode request context', () => {
|
||||
it('IIFE-CTX-AT4 — /stats IIFE writes place_regions after the response, no cannotUseGlobalContext', async () => {
|
||||
resetTestDb(testDb);
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const p = createPlace(testDb, trip.id, { lat: 48.85, lng: 2.35 });
|
||||
const res = await request(app).get('/api/addons/atlas/stats').set('Cookie', authCookie(user.id));
|
||||
expect(res.status).toBe(200);
|
||||
expect(testDb.prepare('SELECT * FROM place_regions WHERE place_id=?').get(p.id)).toBeUndefined();
|
||||
await new Promise((r) => setTimeout(r, 2500));
|
||||
expect(errors).toEqual([]);
|
||||
expect(testDb.prepare('SELECT * FROM place_regions WHERE place_id=?').get(p.id)).toMatchObject({ country_code: 'FR', region_code: 'FR-IDF' });
|
||||
}, 15_000);
|
||||
|
||||
it('IIFE-CTX-AT29 — /regions IIFE writes two places sequentially (2nd after ~2.4s)', async () => {
|
||||
resetTestDb(testDb);
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const p1 = createPlace(testDb, trip.id, { lat: 48.85, lng: 2.35 });
|
||||
const p2 = createPlace(testDb, trip.id, { lat: 43.3, lng: 5.4 });
|
||||
const res = await request(app).get('/api/addons/atlas/regions').set('Cookie', authCookie(user.id));
|
||||
expect(res.status).toBe(200);
|
||||
await new Promise((r) => setTimeout(r, 3500));
|
||||
expect(errors).toEqual([]);
|
||||
const rows = testDb.prepare('SELECT place_id, region_code FROM place_regions ORDER BY place_id').all();
|
||||
expect(rows).toEqual([
|
||||
{ place_id: p1.id, region_code: 'FR-IDF' },
|
||||
{ place_id: p2.id, region_code: 'FR-PAC' },
|
||||
]);
|
||||
}, 15_000);
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
/**
|
||||
* TodoItemsRepository.listDueForReminder — RJ4 parity (L2, task-7-review.md).
|
||||
*
|
||||
* `due_date` is an unconstrained `z.string()` on the wire, not always
|
||||
* canonical `YYYY-MM-DD` text. Legacy wrapped the column in `date(...)`
|
||||
* before comparing it to the cutoff, which normalizes a time-bearing value
|
||||
* down to its date part; the converted repository compared the raw string
|
||||
* against a bare `YYYY-MM-DD` cutoff instead, which sorts a due date on the
|
||||
* cutoff day itself (`2026-07-14T09:00`) AFTER the cutoff and drops it a day
|
||||
* early. One seeded world, mixed `due_date` shapes, id set compared against
|
||||
* the legacy SQL statement (`sn-cycle`/`rj4` reviewer probe, ported per the
|
||||
* fix-wave brief rather than imported from the reviewer's scratchpad).
|
||||
*/
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { createSnapshotTestDb } from '../../../helpers/db-mock';
|
||||
import { resetTestDb } from '../../../helpers/test-db';
|
||||
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
|
||||
import { createUser, createTrip } from '../../../helpers/factories';
|
||||
import { TodoItems } from '../../../../src/db/entities/TodoItems.entity';
|
||||
import type { TodoItemsRepository } from '../../../../src/db/repositories/TodoItems.repository';
|
||||
|
||||
const testDb = createSnapshotTestDb();
|
||||
let t: TestOrm;
|
||||
let repo: TodoItemsRepository;
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb);
|
||||
repo = t.repo(TodoItems);
|
||||
});
|
||||
beforeEach(() => {
|
||||
resetTestDb(testDb);
|
||||
t.clear();
|
||||
});
|
||||
afterAll(async () => {
|
||||
await t.close();
|
||||
testDb.close();
|
||||
});
|
||||
|
||||
const iso = (d: Date) => d.toISOString().slice(0, 10);
|
||||
|
||||
describe('listDueForReminder', () => {
|
||||
it('RJ4 parity: mixed due_date shapes on the last day of the window match the legacy date()-wrapped SQL, id for id', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const now = new Date();
|
||||
const t0 = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
|
||||
const plus = (n: number) => {
|
||||
const d = new Date(t0);
|
||||
d.setUTCDate(d.getUTCDate() + n);
|
||||
return d;
|
||||
};
|
||||
const LEAD = 3;
|
||||
const shapes = [
|
||||
iso(t0),
|
||||
iso(plus(LEAD)),
|
||||
iso(plus(LEAD)) + 'T09:00',
|
||||
iso(plus(LEAD)) + ' 09:00:00',
|
||||
iso(t0) + 'T00:00:00Z',
|
||||
iso(plus(-1)),
|
||||
iso(plus(LEAD + 1)),
|
||||
'soon',
|
||||
'',
|
||||
];
|
||||
for (const s of shapes) {
|
||||
testDb.prepare('INSERT INTO todo_items (trip_id, name, due_date, checked) VALUES (?, ?, ?, 0)').run(trip.id, 'n:' + s, s);
|
||||
}
|
||||
|
||||
const legacy = (
|
||||
testDb
|
||||
.prepare(
|
||||
`SELECT ti.id FROM todo_items ti JOIN trips t ON t.id = ti.trip_id
|
||||
WHERE ti.checked = 0 AND ti.due_date IS NOT NULL AND ti.due_date <> ''
|
||||
AND date(ti.due_date) <= date('now', '+' || ? || ' days')
|
||||
AND date(ti.due_date) >= date('now')
|
||||
AND (ti.reminded_at IS NULL OR ti.reminded_at <= datetime('now', '-20 hours'))
|
||||
ORDER BY ti.id`,
|
||||
)
|
||||
.all(LEAD) as { id: number }[]
|
||||
).map((r) => r.id);
|
||||
|
||||
const head = (await repo.listDueForReminder(iso(t0), iso(plus(LEAD)))).map((r) => r.id).sort((a, b) => a - b);
|
||||
const names = (ids: number[]) => ids.map((i) => (testDb.prepare('SELECT name FROM todo_items WHERE id=?').get(i) as { name: string }).name);
|
||||
|
||||
expect(names(head)).toEqual(names(legacy));
|
||||
expect(head.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
@@ -848,3 +848,41 @@ describe('TripsRepository.listTravellerUsernames (PublicApiService.buildTravelle
|
||||
expect(await trips.listTravellerUsernames(trip.id)).toEqual([{ username: 'solo-owner', is_owner: 1 }]);
|
||||
});
|
||||
});
|
||||
|
||||
// L6 (task-7-review.md item 11): AT1 had no full-key legacy-raw `toEqual` —
|
||||
// TRIPREPO-011/012 above only proved `listAccessibleIds` (ids only). One
|
||||
// seeded world: an owned trip, a trip the caller only belongs to as a
|
||||
// member, and a stranger's trip that must not appear.
|
||||
describe('TripsRepository.listOwnedOrMember — AT1 parity with the legacy statement', () => {
|
||||
const LEGACY_OWNED_OR_MEMBER = `
|
||||
SELECT DISTINCT t.* FROM trips t
|
||||
LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ?
|
||||
WHERE t.user_id = ? OR m.user_id = ?
|
||||
ORDER BY t.start_date DESC
|
||||
`;
|
||||
|
||||
it('TRIPREPO-058: byte-identical to the legacy DISTINCT/LEFT JOIN statement — owned and member trips, in the same start_date-desc order, a stranger\'s trip excluded', async () => {
|
||||
const { user: caller } = createUser(testDb);
|
||||
const { user: stranger } = createUser(testDb);
|
||||
const owned = createTrip(testDb, caller.id, { start_date: '2026-03-01', end_date: '2026-03-05' });
|
||||
const memberOf = createTrip(testDb, stranger.id, { start_date: '2026-06-01', end_date: '2026-06-05' });
|
||||
addTripMember(testDb, memberOf.id, caller.id);
|
||||
createTrip(testDb, stranger.id, { start_date: '2026-01-01', end_date: '2026-01-02' }); // not the caller's
|
||||
|
||||
const legacy = testDb.prepare(LEGACY_OWNED_OR_MEMBER).all(caller.id, caller.id, caller.id);
|
||||
const rows = await trips.listOwnedOrMember(caller.id);
|
||||
|
||||
expect(rows).toEqual(legacy);
|
||||
expect(rows.map((r) => r.id)).toEqual([memberOf.id, owned.id]);
|
||||
});
|
||||
|
||||
it('TRIPREPO-059: no owned or member trips returns an empty array, matching the legacy statement', async () => {
|
||||
const { user: caller } = createUser(testDb);
|
||||
const { user: stranger } = createUser(testDb);
|
||||
createTrip(testDb, stranger.id);
|
||||
|
||||
const legacy = testDb.prepare(LEGACY_OWNED_OR_MEMBER).all(caller.id, caller.id, caller.id);
|
||||
expect(await trips.listOwnedOrMember(caller.id)).toEqual(legacy);
|
||||
expect(legacy).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* VacaySharesRepository.listOutgoing/listIncoming — VC81/VC82 parity (L6,
|
||||
* task-7-review.md item 11). One seeded world: two owners sharing with a
|
||||
* common recipient (one hidden, one not), plus an unrelated share that must
|
||||
* not leak across owners/recipients.
|
||||
*/
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { createSnapshotTestDb } from '../../../helpers/db-mock';
|
||||
import { resetTestDb } from '../../../helpers/test-db';
|
||||
import { createUser } from '../../../helpers/factories';
|
||||
import { createTestVacaySharesRepo } from '../../../helpers/vacay-repos';
|
||||
import type { VacaySharesRepository } from '../../../../src/db/repositories/VacayShares.repository';
|
||||
|
||||
const testDb = createSnapshotTestDb();
|
||||
let repo: VacaySharesRepository;
|
||||
|
||||
beforeAll(async () => {
|
||||
repo = await createTestVacaySharesRepo(testDb);
|
||||
});
|
||||
beforeEach(() => {
|
||||
resetTestDb(testDb);
|
||||
});
|
||||
afterAll(() => testDb.close());
|
||||
|
||||
const LEGACY_LIST_OUTGOING = `SELECT s.id, s.user_id, u.username FROM vacay_shares s JOIN users u ON s.user_id = u.id WHERE s.owner_id = ? ORDER BY s.id`;
|
||||
const LEGACY_LIST_INCOMING = `SELECT s.id, s.owner_id, s.hidden, u.username FROM vacay_shares s JOIN users u ON s.owner_id = u.id WHERE s.user_id = ? ORDER BY s.id`;
|
||||
|
||||
function insertShare(ownerId: number, userId: number, hidden = 0): number {
|
||||
return Number(
|
||||
testDb.prepare('INSERT INTO vacay_shares (owner_id, user_id, hidden) VALUES (?, ?, ?)').run(ownerId, userId, hidden).lastInsertRowid,
|
||||
);
|
||||
}
|
||||
|
||||
describe('VacaySharesRepository — VC81/VC82 parity with the legacy statements', () => {
|
||||
it('VC81 listOutgoing: byte-identical to the legacy statement, ordered by id, usernames only (emails withheld)', async () => {
|
||||
const { user: ownerA } = createUser(testDb, { username: 'owner-a' });
|
||||
const { user: recipient1 } = createUser(testDb, { username: 'recipient-1' });
|
||||
const { user: recipient2 } = createUser(testDb, { username: 'recipient-2' });
|
||||
const { user: ownerB } = createUser(testDb, { username: 'owner-b' });
|
||||
insertShare(ownerA.id, recipient2.id);
|
||||
insertShare(ownerA.id, recipient1.id);
|
||||
insertShare(ownerB.id, recipient1.id); // a different owner — must not appear for ownerA
|
||||
|
||||
const legacy = testDb.prepare(LEGACY_LIST_OUTGOING).all(ownerA.id);
|
||||
const rows = await repo.listOutgoing(ownerA.id);
|
||||
|
||||
expect(rows).toEqual(legacy);
|
||||
expect(rows.map((r) => r.username)).toEqual(['recipient-2', 'recipient-1']);
|
||||
});
|
||||
|
||||
it('VC81 listOutgoing: an owner with no outgoing shares returns [], matching the legacy statement', async () => {
|
||||
const { user: owner } = createUser(testDb);
|
||||
expect(await repo.listOutgoing(owner.id)).toEqual(testDb.prepare(LEGACY_LIST_OUTGOING).all(owner.id));
|
||||
});
|
||||
|
||||
it('VC82/VC91 listIncoming: byte-identical to the legacy statement, ordered by id, carrying owner username and the hidden flag', async () => {
|
||||
const { user: recipient } = createUser(testDb, { username: 'recipient' });
|
||||
const { user: ownerA } = createUser(testDb, { username: 'owner-a' });
|
||||
const { user: ownerB } = createUser(testDb, { username: 'owner-b' });
|
||||
const { user: elsewhere } = createUser(testDb, { username: 'elsewhere' });
|
||||
insertShare(ownerB.id, recipient.id, 1); // hidden
|
||||
insertShare(ownerA.id, recipient.id, 0);
|
||||
insertShare(ownerA.id, elsewhere.id, 0); // a different recipient — must not appear for `recipient`
|
||||
|
||||
const legacy = testDb.prepare(LEGACY_LIST_INCOMING).all(recipient.id);
|
||||
const rows = await repo.listIncoming(recipient.id);
|
||||
|
||||
expect(rows).toEqual(legacy);
|
||||
expect(rows.map((r) => ({ username: r.username, hidden: r.hidden }))).toEqual([
|
||||
{ username: 'owner-b', hidden: 1 },
|
||||
{ username: 'owner-a', hidden: 0 },
|
||||
]);
|
||||
});
|
||||
|
||||
it('VC82/VC91 listIncoming: a recipient with no incoming shares returns [], matching the legacy statement', async () => {
|
||||
const { user: recipient } = createUser(testDb);
|
||||
expect(await repo.listIncoming(recipient.id)).toEqual(testDb.prepare(LEGACY_LIST_INCOMING).all(recipient.id));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,155 @@
|
||||
/**
|
||||
* TRAVELER_OWNS consumers — full-row parity (L6, task-7-review.md item 11).
|
||||
*
|
||||
* `reservation-travelers-owns.parity.test.ts` (this directory) proves the
|
||||
* predicate fragment itself against ids only. AT6 (`listOwnedEndpointsForTrips`),
|
||||
* AT45 (`listOwnedEndpointsForUser`) and AT46 (`listOwnedFlightLegsForUser`,
|
||||
* ordered) are its three ACTUAL production consumers and had no full-row
|
||||
* `toEqual` against the legacy statement before this. One seeded world
|
||||
* covering zero-traveler, caller-assigned, foreign-only, cancelled and
|
||||
* multi-traveler bookings across a past trip, a future trip and a dateless
|
||||
* trip; every row of every method compared byte-for-byte against the legacy
|
||||
* SQL text (kept fixed here, independent of the repository under test, per
|
||||
* `reservation-visibility.test.ts`'s own oracle reasoning).
|
||||
*/
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import { createSnapshotTestDb } from '../../../../helpers/db-mock';
|
||||
import { resetTestDb } from '../../../../helpers/test-db';
|
||||
import { createReservation, createTrip, createUser, addTripMember } from '../../../../helpers/factories';
|
||||
import { createTestReservationEndpointsRepo } from '../../../../helpers/test-uow';
|
||||
import type { ReservationEndpointsRepository } from '../../../../../src/db/repositories/ReservationEndpoints.repository';
|
||||
import { todayUtc } from '@trek/shared';
|
||||
|
||||
const TRAVELER_OWNS = `
|
||||
(NOT EXISTS (SELECT 1 FROM reservation_travelers rt WHERE rt.reservation_id = r.id)
|
||||
OR EXISTS (SELECT 1 FROM reservation_travelers rt WHERE rt.reservation_id = r.id AND rt.user_id = ?))`;
|
||||
|
||||
const AT6 = (n: number) => `
|
||||
SELECT DISTINCT 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,
|
||||
CASE e.role
|
||||
WHEN 'to' THEN COALESCE(r.reservation_end_time, r.reservation_time)
|
||||
ELSE COALESCE(r.reservation_time, r.reservation_end_time)
|
||||
END AS fallback_time
|
||||
FROM reservation_endpoints e
|
||||
JOIN reservations r ON e.reservation_id = r.id
|
||||
WHERE r.trip_id IN (${Array(n).fill('?').join(',')}) AND e.role IN ('from', 'to')
|
||||
AND ${TRAVELER_OWNS}`;
|
||||
|
||||
const AT45 = `
|
||||
SELECT DISTINCT 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,
|
||||
CASE e.role
|
||||
WHEN 'to' THEN COALESCE(r.reservation_end_time, r.reservation_time)
|
||||
ELSE COALESCE(r.reservation_time, r.reservation_end_time)
|
||||
END AS fallback_time
|
||||
FROM reservation_endpoints e
|
||||
JOIN reservations r ON e.reservation_id = r.id
|
||||
JOIN trips t ON r.trip_id = t.id
|
||||
LEFT JOIN trip_members tm ON t.id = tm.trip_id
|
||||
WHERE (t.user_id = ? OR tm.user_id = ?) AND e.role IN ('from', 'to')
|
||||
AND COALESCE(t.start_date, t.end_date) IS NOT NULL
|
||||
AND COALESCE(t.start_date, t.end_date) <= date('now')
|
||||
AND ${TRAVELER_OWNS}`;
|
||||
|
||||
const AT46 = `
|
||||
SELECT re.reservation_id, re.lat, re.lng
|
||||
FROM reservation_endpoints re
|
||||
JOIN reservations r ON r.id = re.reservation_id
|
||||
JOIN trips t ON t.id = r.trip_id
|
||||
LEFT JOIN trip_members tm ON tm.trip_id = t.id AND tm.user_id = ?
|
||||
WHERE (t.user_id = ? OR tm.user_id IS NOT NULL)
|
||||
AND r.type = 'flight'
|
||||
AND r.status != 'cancelled'
|
||||
AND ${TRAVELER_OWNS}
|
||||
ORDER BY re.reservation_id, re.sequence`;
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
let repo: ReservationEndpointsRepository;
|
||||
const users: number[] = [];
|
||||
const trips: number[] = [];
|
||||
const sortRows = (rows: unknown[]) => [...rows].sort((a, b) => (a as { id: number }).id - (b as { id: number }).id);
|
||||
|
||||
beforeAll(async () => {
|
||||
resetTestDb(db);
|
||||
repo = await createTestReservationEndpointsRepo(db);
|
||||
const A = createUser(db).user.id, B = createUser(db).user.id, C = createUser(db).user.id, D = createUser(db).user.id;
|
||||
users.push(A, B, C, D);
|
||||
const past = createTrip(db, A, { start_date: '2020-01-01', end_date: '2020-01-05' }).id;
|
||||
const future = createTrip(db, A, { start_date: '2099-01-01', end_date: '2099-01-02' }).id;
|
||||
const dateless = createTrip(db, B).id;
|
||||
trips.push(past, future, dateless);
|
||||
addTripMember(db, past, B);
|
||||
addTripMember(db, past, C);
|
||||
addTripMember(db, future, B);
|
||||
const ep = db.prepare(
|
||||
'INSERT INTO reservation_endpoints (reservation_id, role, sequence, name, code, lat, lng, local_date, local_time) VALUES (?,?,?,?,?,?,?,?,?)',
|
||||
);
|
||||
const trv = db.prepare('INSERT INTO reservation_travelers (reservation_id, user_id) VALUES (?, ?)');
|
||||
let k = 0;
|
||||
for (const tid of [past, future, dateless]) {
|
||||
const shapes: [string, string | null, number[]][] = [
|
||||
['flight', null, []], // zero travelers
|
||||
['flight', null, [A]], // assigned to A
|
||||
['flight', null, [C]], // foreign-only (C)
|
||||
['flight', 'cancelled', []],
|
||||
['train', 'confirmed', [A, B]],
|
||||
['flight', 'confirmed', [B, C]],
|
||||
];
|
||||
for (const [type, status, tr] of shapes) {
|
||||
const r = createReservation(db, tid, { type }).id;
|
||||
db.prepare('UPDATE reservations SET status = ?, reservation_time = ?, reservation_end_time = ? WHERE id = ?').run(
|
||||
status ?? 'pending',
|
||||
k % 2 ? '2020-01-01T10:00' : null,
|
||||
k % 3 ? '2020-01-01T14:00' : null,
|
||||
r,
|
||||
);
|
||||
k++;
|
||||
ep.run(r, 'from', 0, 'X', 'FRA', 50.03 + k, 8.57, k % 2 ? '2020-01-01' : null, k % 2 ? '10:00' : null);
|
||||
ep.run(r, 'stop', 1, 'X', 'DXB', 25.25, 55.36, null, null);
|
||||
ep.run(r, 'to', 2, 'X', 'SIN', 1.36, 103.99 + k, '2020-01-02', null);
|
||||
for (const u of tr) trv.run(r, u);
|
||||
}
|
||||
}
|
||||
});
|
||||
afterAll(() => db.close());
|
||||
|
||||
describe('TRAVELER_OWNS consumers: repository vs legacy raw SQL, full rows', () => {
|
||||
it('AT6 — listOwnedEndpointsForTrips', async () => {
|
||||
for (const u of users) {
|
||||
const legacy = db.prepare(AT6(trips.length)).all(...trips, u);
|
||||
expect(sortRows(await repo.listOwnedEndpointsForTrips(trips, u))).toEqual(sortRows(legacy));
|
||||
}
|
||||
});
|
||||
|
||||
it('AT45 — listOwnedEndpointsForUser', async () => {
|
||||
for (const u of users) {
|
||||
const legacy = db.prepare(AT45).all(u, u, u);
|
||||
expect(sortRows(await repo.listOwnedEndpointsForUser(u, todayUtc()))).toEqual(sortRows(legacy));
|
||||
}
|
||||
});
|
||||
|
||||
it('AT46 — listOwnedFlightLegsForUser (ordered)', async () => {
|
||||
for (const u of users) {
|
||||
const legacy = db.prepare(AT46).all(u, u, u);
|
||||
expect(await repo.listOwnedFlightLegsForUser(u)).toEqual(legacy);
|
||||
}
|
||||
});
|
||||
|
||||
it('seeded cases are non-trivial (C sees foreign-only; A does not; D has no access at all)', () => {
|
||||
const [A, , C, D] = users;
|
||||
const ids = (u: number) =>
|
||||
JSON.stringify(
|
||||
[
|
||||
...new Set((db.prepare(AT6(trips.length)).all(...trips, u) as { reservation_id: number }[]).map((r) => r.reservation_id)),
|
||||
].sort(),
|
||||
);
|
||||
const a = ids(A).length;
|
||||
const c = ids(C).length;
|
||||
const d = db.prepare(AT45).all(D, D, D).length;
|
||||
expect(a).toBeGreaterThan(0);
|
||||
expect(c).toBeGreaterThan(0);
|
||||
expect(d).toBe(0);
|
||||
expect(ids(A)).not.toBe(ids(C));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* Atlas repositories — M3 branch ratchet (task-7-review.md). Plan 3f Task 1
|
||||
* added empty-array short-circuits and not-found/no-op ternaries across
|
||||
* these repositories with no test exercising the empty/no-op arm. One
|
||||
* seeded world per repository (shared `testDb`, reset between tests).
|
||||
*/
|
||||
import { afterAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { createSnapshotTestDb } from '../../../helpers/db-mock';
|
||||
import { resetTestDb } from '../../../helpers/test-db';
|
||||
import { createUser } from '../../../helpers/factories';
|
||||
import { createTestPlaceRegionsRepo, createTestVisitedCountriesRepo, createTestBucketListRepo } from '../../../helpers/atlas-repos';
|
||||
import { createTestReservationEndpointsRepo } from '../../../helpers/test-uow';
|
||||
import { createTestSchoolHolidayCountriesRepo } from '../../../helpers/school-holidays-repos';
|
||||
|
||||
const testDb = createSnapshotTestDb();
|
||||
beforeEach(() => resetTestDb(testDb));
|
||||
afterAll(() => testDb.close());
|
||||
|
||||
describe('PlaceRegionsRepository — empty-array short-circuits (AT3/AT28/AT23)', () => {
|
||||
it('listCountryCodesForPlaceIds/listForPlaceIds/listDistinctRegionCodesForCountryAndPlaces all return [] for an empty id list, without querying', async () => {
|
||||
const repo = await createTestPlaceRegionsRepo(testDb);
|
||||
expect(await repo.listCountryCodesForPlaceIds([])).toEqual([]);
|
||||
expect(await repo.listForPlaceIds([])).toEqual([]);
|
||||
expect(await repo.listDistinctRegionCodesForCountryAndPlaces('FR', [])).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('VisitedCountriesRepository.markVisited — the ON CONFLICT DO NOTHING return (AT12)', () => {
|
||||
it('returns false on a repeat mark (no row actually inserted the second time), true on the first', async () => {
|
||||
const repo = await createTestVisitedCountriesRepo(testDb);
|
||||
const { user } = createUser(testDb);
|
||||
expect(await repo.markVisited(user.id, 'FR', 'manual')).toBe(true);
|
||||
expect(await repo.markVisited(user.id, 'FR', 'manual')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ReservationEndpointsRepository.listOwnedEndpointsForTrips — empty-array short-circuit (AT6)', () => {
|
||||
it('returns [] for an empty tripIds list, without querying', async () => {
|
||||
const repo = await createTestReservationEndpointsRepo(testDb);
|
||||
const { user } = createUser(testDb);
|
||||
expect(await repo.listOwnedEndpointsForTrips([], user.id)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('BucketListRepository.update — the no-op empty-patch branch (AT35)', () => {
|
||||
it('an empty write leaves the row untouched', async () => {
|
||||
const repo = await createTestBucketListRepo(testDb);
|
||||
const { user } = createUser(testDb);
|
||||
const id = await repo.insertItem({ user_id: user.id, name: 'Kyoto', lat: null, lng: null, country_code: null, notes: null, target_date: null });
|
||||
|
||||
await repo.update(id, user.id, {});
|
||||
|
||||
const row = await repo.findById(id);
|
||||
expect(row?.name).toBe('Kyoto');
|
||||
});
|
||||
});
|
||||
|
||||
// Folded in for the aggregate `src/db/repositories/**` gate (task-7-review.md
|
||||
// M3: "the 3e-carried lines belong to 3e's own ratchet but block CI all the
|
||||
// same. Fold them in, or name the owner.") — the same ON CONFLICT DO NOTHING
|
||||
// affected-row-count pattern as VisitedCountriesRepository.markVisited above.
|
||||
describe('SchoolHolidayCountriesRepository.insertIgnore — the ON CONFLICT DO NOTHING return', () => {
|
||||
it('returns false on a repeat insert of the same code, true on the first', async () => {
|
||||
const repo = await createTestSchoolHolidayCountriesRepo(testDb);
|
||||
expect(await repo.insertIgnore({ code: 'US', name: 'United States' })).toBe(true);
|
||||
expect(await repo.insertIgnore({ code: 'US', name: 'United States' })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* Vacay repositories — M3 branch ratchet (task-7-review.md). Plan 3f Task 5
|
||||
* added `?? null`/`?? default` folds and not-found ternaries across these
|
||||
* repositories with no test exercising the fallback arm. One seeded world
|
||||
* per repository (shared `testDb`, reset between tests), raw SQL where a
|
||||
* NULL needs to land on a column the ORM itself would never write (the
|
||||
* entity's own default keeps every normal write non-null).
|
||||
*/
|
||||
import { afterAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { createSnapshotTestDb } from '../../../helpers/db-mock';
|
||||
import { resetTestDb } from '../../../helpers/test-db';
|
||||
import { createUser } from '../../../helpers/factories';
|
||||
import { createTestVacayHolidayCalendarsRepo } from '../../../helpers/school-holidays-repos';
|
||||
import {
|
||||
createTestVacayPlansRepo,
|
||||
createTestVacayPlanMembersRepo,
|
||||
createTestVacayUserColorsRepo,
|
||||
createTestVacayCompanyHolidaysRepo,
|
||||
createTestVacaySharesRepo,
|
||||
} from '../../../helpers/vacay-repos';
|
||||
|
||||
const testDb = createSnapshotTestDb();
|
||||
|
||||
function makePlan(ownerId: number): number {
|
||||
return Number(testDb.prepare('INSERT INTO vacay_plans (owner_id) VALUES (?)').run(ownerId).lastInsertRowid);
|
||||
}
|
||||
|
||||
beforeEach(() => resetTestDb(testDb));
|
||||
afterAll(() => testDb.close());
|
||||
|
||||
describe('VacayCompanyHolidaysRepository — note ?? null (VC29/VC67/VC112)', () => {
|
||||
it('listForPlan/listForRange return note: null for a row whose note column is genuinely NULL', async () => {
|
||||
const repo = await createTestVacayCompanyHolidaysRepo(testDb);
|
||||
const { user } = createUser(testDb);
|
||||
const planId = makePlan(user.id);
|
||||
testDb.prepare('INSERT INTO vacay_company_holidays (plan_id, date, note) VALUES (?, ?, NULL)').run(planId, '2026-12-25');
|
||||
|
||||
expect(await repo.listForPlan(planId)).toEqual([{ date: '2026-12-25', note: null }]);
|
||||
expect(await repo.listForRange(planId, '2026-12-01', '2027-01-01')).toMatchObject([{ date: '2026-12-25', note: null }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('VacayUserColorsRepository — color ?? null (VC79/VC57.../VC59)', () => {
|
||||
it('listForPlan/findColor/listOtherColors return color: null for a row whose color column is genuinely NULL', async () => {
|
||||
const repo = await createTestVacayUserColorsRepo(testDb);
|
||||
const { user: u1 } = createUser(testDb);
|
||||
const { user: u2 } = createUser(testDb);
|
||||
const planId = makePlan(u1.id);
|
||||
testDb.prepare('INSERT INTO vacay_user_colors (user_id, plan_id, color) VALUES (?, ?, NULL)').run(u1.id, planId);
|
||||
testDb.prepare('INSERT INTO vacay_user_colors (user_id, plan_id, color) VALUES (?, ?, ?)').run(u2.id, planId, '#111111');
|
||||
|
||||
expect(await repo.listForPlan(planId)).toEqual(expect.arrayContaining([{ color: null }, { color: '#111111' }]));
|
||||
expect(await repo.findColor(u1.id, planId)).toEqual({ color: null });
|
||||
expect(await repo.listOtherColors(planId, u2.id)).toEqual([{ color: null }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('VacayHolidayCalendarsRepository — findById/findScopedForPlan not-found (VC39/VC42/VC40/VC43)', () => {
|
||||
it('both return null for an id that does not exist', async () => {
|
||||
const repo = await createTestVacayHolidayCalendarsRepo(testDb);
|
||||
expect(await repo.findById(999999)).toBeNull();
|
||||
expect(await repo.findScopedForPlan(999999, 1)).toBeNull();
|
||||
});
|
||||
|
||||
it('findScopedForPlan returns the row for the correct plan, null under a DIFFERENT plan', async () => {
|
||||
const repo = await createTestVacayHolidayCalendarsRepo(testDb);
|
||||
const { user } = createUser(testDb);
|
||||
const planId = makePlan(user.id);
|
||||
const otherPlanId = makePlan(createUser(testDb).user.id);
|
||||
const id = Number(
|
||||
testDb
|
||||
.prepare("INSERT INTO vacay_holiday_calendars (plan_id, type, region, color, sort_order) VALUES (?, 'public_holiday', 'US', '#fecaca', 0)")
|
||||
.run(planId).lastInsertRowid,
|
||||
);
|
||||
expect((await repo.findScopedForPlan(id, planId))?.id).toBe(id);
|
||||
expect(await repo.findScopedForPlan(id, otherPlanId)).toBeNull();
|
||||
expect((await repo.findById(id))?.id).toBe(id);
|
||||
});
|
||||
});
|
||||
|
||||
describe('VacayPlanMembersRepository — findMembership/findAcceptedForUser (VC48/VC49)', () => {
|
||||
it('findMembership returns null for no row, the row for a pending/accepted one, and status: null for a genuinely NULL status column', async () => {
|
||||
const repo = await createTestVacayPlanMembersRepo(testDb);
|
||||
const { user: owner } = createUser(testDb);
|
||||
const { user: target } = createUser(testDb);
|
||||
const planId = makePlan(owner.id);
|
||||
|
||||
expect(await repo.findMembership(planId, target.id)).toBeNull();
|
||||
|
||||
testDb.prepare("INSERT INTO vacay_plan_members (plan_id, user_id, status) VALUES (?, ?, 'pending')").run(planId, target.id);
|
||||
const pending = await repo.findMembership(planId, target.id);
|
||||
expect(pending).toMatchObject({ status: 'pending' });
|
||||
|
||||
testDb.prepare('UPDATE vacay_plan_members SET status = NULL WHERE plan_id = ? AND user_id = ?').run(planId, target.id);
|
||||
expect(await repo.findMembership(planId, target.id)).toEqual({ id: pending!.id, status: null });
|
||||
});
|
||||
|
||||
it('findAcceptedForUser returns null for nobody fused, and the row once accepted', async () => {
|
||||
const repo = await createTestVacayPlanMembersRepo(testDb);
|
||||
const { user: owner } = createUser(testDb);
|
||||
const { user: target } = createUser(testDb);
|
||||
const planId = makePlan(owner.id);
|
||||
|
||||
expect(await repo.findAcceptedForUser(target.id)).toBeNull();
|
||||
|
||||
const id = Number(
|
||||
testDb.prepare("INSERT INTO vacay_plan_members (plan_id, user_id, status) VALUES (?, ?, 'accepted')").run(planId, target.id).lastInsertRowid,
|
||||
);
|
||||
expect(await repo.findAcceptedForUser(target.id)).toEqual({ id });
|
||||
});
|
||||
});
|
||||
|
||||
describe('VacayPlansRepository — findOwnerId/getHolidaysEnabled/findVacayUser (VC18/VC103/VC21/VC16)', () => {
|
||||
it('findOwnerId returns null for a plan id that does not exist, the owner id for one that does', async () => {
|
||||
const repo = await createTestVacayPlansRepo(testDb);
|
||||
const { user } = createUser(testDb);
|
||||
const planId = makePlan(user.id);
|
||||
expect(await repo.findOwnerId(999999)).toBeNull();
|
||||
expect(await repo.findOwnerId(planId)).toEqual({ owner_id: user.id });
|
||||
});
|
||||
|
||||
it('getHolidaysEnabled returns null for a missing plan, null for a genuinely NULL column, and the value when set', async () => {
|
||||
const repo = await createTestVacayPlansRepo(testDb);
|
||||
const { user } = createUser(testDb);
|
||||
const planId = makePlan(user.id);
|
||||
expect(await repo.getHolidaysEnabled(999999)).toBeNull();
|
||||
|
||||
testDb.prepare('UPDATE vacay_plans SET holidays_enabled = NULL WHERE id = ?').run(planId);
|
||||
expect(await repo.getHolidaysEnabled(planId)).toBeNull();
|
||||
|
||||
testDb.prepare('UPDATE vacay_plans SET holidays_enabled = 1 WHERE id = ?').run(planId);
|
||||
expect(await repo.getHolidaysEnabled(planId)).toBe(1);
|
||||
});
|
||||
|
||||
it('findVacayUser returns null for a user id that does not exist', async () => {
|
||||
const repo = await createTestVacayPlansRepo(testDb);
|
||||
expect(await repo.findVacayUser(999999)).toBeNull();
|
||||
const { user } = createUser(testDb);
|
||||
expect(await repo.findVacayUser(user.id)).toMatchObject({ id: user.id, username: user.username });
|
||||
});
|
||||
});
|
||||
|
||||
describe('VacaySharesRepository.listDistinctViewerIdsForOwners — empty-array short-circuit (VC20)', () => {
|
||||
it('returns [] for an empty ownerIds list, without querying', async () => {
|
||||
const repo = await createTestVacaySharesRepo(testDb);
|
||||
expect(await repo.listDistinctViewerIdsForOwners([])).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -49,6 +49,7 @@ vi.mock('../../../src/utils/ssrfGuard', () => {
|
||||
import { getEventText, buildEmailHtml } from '../../../src/nest/notifications/mailer/email-html';
|
||||
import { WebhookService, buildWebhookBody } from '../../../src/nest/notifications/transports/webhook.service';
|
||||
import { NtfyService, resolveNtfyUrl, resolveAdminNtfyUrl, resolveNtfyToken, type NtfyConfig } from '../../../src/nest/notifications/transports/ntfy.service';
|
||||
import { buildBuiltinChannels } from '../../../src/nest/notifications/channels/builtins';
|
||||
import { checkSsrf } from '../../../src/utils/ssrfGuard';
|
||||
import { logError } from '../../../src/nest/audit/audit-log.logger';
|
||||
import { createTables } from '../../../src/db/schema';
|
||||
@@ -58,10 +59,13 @@ import { createTestSettingsRepo, createTestAppSettingsRepo } from '../../helpers
|
||||
// The transports are providers now, taking SettingsRepository/
|
||||
// AppSettingsRepository instead of DatabaseService — a real, throwaway
|
||||
// in-memory DB (never read by any case in this file: every case here drives
|
||||
// sendWebhook/sendNtfy directly, never the config getters, except the
|
||||
// GHSA-7pqc-fj3c-9346 case below, which resolves real configs through the
|
||||
// same repositories) replaces the STUB-DB fixture the fake `DatabaseService`
|
||||
// connection used to supply.
|
||||
// sendWebhook/sendNtfy directly, never the config getters — including the
|
||||
// GHSA-7pqc-fj3c-9346 case below, which hand-builds both NtfyConfigs and never
|
||||
// reaches ntfy.getUserNtfyConfig/getAdminNtfyConfig or the production send
|
||||
// path; the "GHSA-7pqc live path" case further down is the one that seeds this
|
||||
// same DB and resolves real configs through the repositories, driving
|
||||
// buildBuiltinChannels(...).sendToUser) replaces the STUB-DB fixture the fake
|
||||
// `DatabaseService` connection used to supply.
|
||||
let webhookSvc: WebhookService;
|
||||
let ntfySvc: NtfyService;
|
||||
let sendWebhook: WebhookService['sendWebhook'];
|
||||
@@ -450,6 +454,54 @@ describe('GHSA-7pqc-fj3c-9346: ntfy token is only attached when the target is th
|
||||
});
|
||||
});
|
||||
|
||||
// M4 fix-wave (task-7-review.md): the case above drives resolveNtfyToken/sendNtfy
|
||||
// directly and never reaches ntfy.getUserNtfyConfig/getAdminNtfyConfig or the
|
||||
// production dispatch path (channels/builtins.ts sendToUser) — reverting the fix
|
||||
// on that live-send leg (`resolveNtfyToken(adminCfg, userCfg)` back to
|
||||
// `userCfg?.token ?? adminCfg.token` at builtins.ts:98) leaves every committed
|
||||
// test in this file green. This case seeds the DB for real, builds NtfyService
|
||||
// on the real repositories, and drives buildBuiltinChannels(...).sendToUser —
|
||||
// the same call NotificationsService.send() makes.
|
||||
describe('GHSA-7pqc-fj3c-9346 (live path): buildBuiltinChannels sendToUser resolves configs through the repositories', () => {
|
||||
it('operator-server user gets the admin token; foreign-server user does not', async () => {
|
||||
const liveDb = new Database(':memory:');
|
||||
createTables(liveDb);
|
||||
runMigrations(liveDb);
|
||||
liveDb
|
||||
.prepare("INSERT INTO users (id, username, email, password_hash, role) VALUES (1,'op','op@x','x','admin'),(2,'u2','u2@x','x','user')")
|
||||
.run();
|
||||
liveDb
|
||||
.prepare(
|
||||
"INSERT INTO app_settings (key, value) VALUES ('admin_ntfy_server','https://ntfy.operator.example'),('admin_ntfy_topic','ops'),('admin_ntfy_token','operator-secret')",
|
||||
)
|
||||
.run();
|
||||
liveDb
|
||||
.prepare(
|
||||
"INSERT INTO settings (user_id, key, value) VALUES (1,'ntfy_topic','t1'),(2,'ntfy_topic','t2'),(2,'ntfy_server','https://ntfy.attacker.example')",
|
||||
)
|
||||
.run();
|
||||
const liveNtfy = new NtfyService(await createTestSettingsRepo(liveDb), await createTestAppSettingsRepo(liveDb));
|
||||
const ntfyChannel = buildBuiltinChannels({ mailer: {} as never, webhook: {} as never, ntfy: liveNtfy }).find((c) => c.id === 'ntfy')!;
|
||||
|
||||
const mockFetch = globalThis.fetch as unknown as ReturnType<typeof vi.fn>;
|
||||
mockFetch.mockClear();
|
||||
mockFetch.mockResolvedValue({ ok: true, text: async () => '' } as never);
|
||||
vi.mocked(checkSsrf).mockResolvedValue({ allowed: true, isPrivate: false, resolvedIp: '1.2.3.4' });
|
||||
|
||||
await ntfyChannel.sendToUser(1, { event: 'trip_reminder', title: 'T', body: 'B' });
|
||||
await ntfyChannel.sendToUser(2, { event: 'trip_reminder', title: 'T', body: 'B' });
|
||||
|
||||
expect(mockFetch.mock.calls[0][0]).toBe('https://ntfy.operator.example/t1');
|
||||
expect((mockFetch.mock.calls[0][1] as RequestInit & { headers: Record<string, string> }).headers['Authorization']).toBe(
|
||||
'Bearer operator-secret',
|
||||
);
|
||||
expect(mockFetch.mock.calls[1][0]).toBe('https://ntfy.attacker.example/t2');
|
||||
expect(
|
||||
(mockFetch.mock.calls[1][1] as RequestInit & { headers: Record<string, string> }).headers['Authorization'],
|
||||
).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveNtfyUrl', () => {
|
||||
const adminCfg: NtfyConfig = { server: 'https://ntfy.sh', topic: 'admin-topic', token: null };
|
||||
|
||||
|
||||
@@ -1,13 +1,30 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest';
|
||||
import { StorageEventsService } from '../../../../src/nest/storage/storage-events.service';
|
||||
import { StorageHealthNotifierService } from '../../../../src/nest/notifications/storage-health-notifier.service';
|
||||
import type { NotificationsService } from '../../../../src/nest/notifications/notifications.service';
|
||||
import { createSnapshotTestDb } from '../../../helpers/db-mock';
|
||||
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
|
||||
|
||||
// L4 (task-7-review.md): `orm` is now a required constructor param — in
|
||||
// production it is always injected, so `@Optional()` was a fail-open seam
|
||||
// (a DI miswire would silently send without a request context instead of
|
||||
// refusing to boot). These hand-built doubles pass the shared test ORM
|
||||
// instead (STORAGE-HEALTH-CTX-001's own precedent for a real one).
|
||||
const testDb = createSnapshotTestDb();
|
||||
let t: TestOrm;
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb);
|
||||
});
|
||||
afterAll(async () => {
|
||||
await t.close();
|
||||
testDb.close();
|
||||
});
|
||||
|
||||
describe('StorageHealthNotifierService', () => {
|
||||
it('NOTIF-001 subscribes on bootstrap and sends an admin-scoped replica_failure with params', () => {
|
||||
const events = new StorageEventsService();
|
||||
const send = vi.fn().mockResolvedValue(undefined);
|
||||
const notifier = new StorageHealthNotifierService(events, { send } as unknown as NotificationsService);
|
||||
const notifier = new StorageHealthNotifierService(events, { send } as unknown as NotificationsService, t.orm);
|
||||
notifier.onApplicationBootstrap();
|
||||
events.emitReplicaFailure({ backend: 's3-bkp', key: 'backups/db.zip', op: 'put', error: 'timeout', at: 1 });
|
||||
expect(send).toHaveBeenCalledWith({
|
||||
@@ -25,7 +42,7 @@ describe('StorageHealthNotifierService', () => {
|
||||
it('NOTIF-002 a rejected send never throws into the emitter (write path stays safe)', () => {
|
||||
const events = new StorageEventsService();
|
||||
const send = vi.fn().mockRejectedValue(new Error('smtp down'));
|
||||
const notifier = new StorageHealthNotifierService(events, { send } as unknown as NotificationsService);
|
||||
const notifier = new StorageHealthNotifierService(events, { send } as unknown as NotificationsService, t.orm);
|
||||
notifier.onApplicationBootstrap();
|
||||
expect(() =>
|
||||
events.emitReplicaFailure({ backend: 'b', key: 'k', op: 'delete', error: 'e', at: 3 }),
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
/**
|
||||
* SystemNoticesService.getActiveFor — M3 branch ratchet (task-7-review.md).
|
||||
*
|
||||
* A separate, isolated file from `system-notices.service.test.ts` so these
|
||||
* fixtures (deliberately shaped to hit specific fallback/tie-break branches)
|
||||
* never leak into that file's shared `SYSTEM_NOTICES` mock and its exact
|
||||
* `.toEqual([...])` assertions. Covers:
|
||||
* - `addonEnabled`/`settingFlag`'s `?? false` fallback for a key that
|
||||
* never appears in ANY notice's own conditions (so the up-front flag
|
||||
* map, built by scanning every notice's conditions, never populates it)
|
||||
* — only reachable via a registered `case 'custom'` predicate that asks
|
||||
* about a DIFFERENT key than any `addonEnabled`/`settingFlag` condition
|
||||
* names.
|
||||
* - a per-version-recurring notice's dismissal row with a NULL
|
||||
* `dismissed_app_version` (an old dismissal from before the per-version
|
||||
* feature existed).
|
||||
* - the sort comparator's three tie-break levels (priority, severity,
|
||||
* publishedAt), each of which needs at least two notices active in the
|
||||
* SAME call for `.sort()` to ever invoke the comparator at all.
|
||||
*/
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import type { SystemNotice } from '../../../src/systemNotices/types';
|
||||
|
||||
const { PRIORITY_HI, PRIORITY_LO, SEVERITY_HI, SEVERITY_LO, PUBLISHED_NEW, PUBLISHED_OLD, ADDON_FLAG_MISS, SETTING_FLAG_MISS, RELEASE } =
|
||||
vi.hoisted(() => {
|
||||
const base = { display: 'toast' as const, dismissible: true, conditions: [{ kind: 'always' as const }], publishedAt: '2020-01-01T00:00:00Z' };
|
||||
const priorityHi: SystemNotice = { ...base, id: 'sn-priority-hi', severity: 'info', titleKey: 't', bodyKey: 'b', priority: 5 };
|
||||
// No `priority` field at all (not just 0) — exercises the `b.priority ??
|
||||
// 0` / `a.priority ?? 0` fallback itself, not just a priority of 0.
|
||||
const priorityLo: SystemNotice = { ...base, id: 'sn-priority-lo', severity: 'info', titleKey: 't', bodyKey: 'b' };
|
||||
const severityHi: SystemNotice = { ...base, id: 'sn-severity-hi', severity: 'critical', titleKey: 't', bodyKey: 'b', priority: 0 };
|
||||
const severityLo: SystemNotice = { ...base, id: 'sn-severity-lo', severity: 'info', titleKey: 't', bodyKey: 'b', priority: 0 };
|
||||
const publishedNew: SystemNotice = { ...base, id: 'sn-published-new', severity: 'info', titleKey: 't', bodyKey: 'b', priority: 0, publishedAt: '2024-06-01T00:00:00Z' };
|
||||
const publishedOld: SystemNotice = { ...base, id: 'sn-published-old', severity: 'info', titleKey: 't', bodyKey: 'b', priority: 0, publishedAt: '2020-01-01T00:00:00Z' };
|
||||
const addonFlagMiss: SystemNotice = {
|
||||
id: 'sn-addon-flag-miss', display: 'toast', severity: 'info', titleKey: 't', bodyKey: 'b', dismissible: true,
|
||||
conditions: [{ kind: 'custom', id: 'branch-cov-addon-probe' }], publishedAt: '2020-01-01T00:00:00Z', priority: 0,
|
||||
};
|
||||
const settingFlagMiss: SystemNotice = {
|
||||
id: 'sn-setting-flag-miss', display: 'toast', severity: 'info', titleKey: 't', bodyKey: 'b', dismissible: true,
|
||||
conditions: [{ kind: 'custom', id: 'branch-cov-setting-probe' }], publishedAt: '2020-01-01T00:00:00Z', priority: 0,
|
||||
};
|
||||
const release: SystemNotice = {
|
||||
id: 'sn-release-nullver', display: 'modal', severity: 'info', titleKey: 'system_notice.release_notes.headline', bodyKey: 'system_notice.release_notes.intro',
|
||||
dismissible: true, conditions: [], recurring: 'per-version', publishedAt: '2020-01-01T00:00:00Z', priority: 0,
|
||||
release: { version: '4.3.0', headlineKey: 'system_notice.release_notes.headline' } as SystemNotice['release'],
|
||||
};
|
||||
return {
|
||||
PRIORITY_HI: priorityHi, PRIORITY_LO: priorityLo, SEVERITY_HI: severityHi, SEVERITY_LO: severityLo,
|
||||
PUBLISHED_NEW: publishedNew, PUBLISHED_OLD: publishedOld, ADDON_FLAG_MISS: addonFlagMiss, SETTING_FLAG_MISS: settingFlagMiss, RELEASE: release,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('../../../src/systemNotices/registry', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../../src/systemNotices/registry')>();
|
||||
return {
|
||||
...actual,
|
||||
SYSTEM_NOTICES: [PRIORITY_HI, PRIORITY_LO, SEVERITY_HI, SEVERITY_LO, PUBLISHED_NEW, PUBLISHED_OLD, ADDON_FLAG_MISS, SETTING_FLAG_MISS, RELEASE],
|
||||
};
|
||||
});
|
||||
|
||||
import { SystemNoticesService } from '../../../src/nest/system-notices/system-notices.service';
|
||||
import { getCurrentAppVersion } from '../../../src/systemNotices/service';
|
||||
import { registerPredicate } from '../../../src/systemNotices/conditions';
|
||||
import type { UserRow } from '../../../src/db/repositories/Users.repository';
|
||||
import type { UserNoticeDismissalRow } from '../../../src/db/repositories/UserNoticeDismissals.repository';
|
||||
|
||||
// Neither key is asked about by any `addonEnabled`/`settingFlag` condition
|
||||
// anywhere in the fixtures above, so the up-front flag map never populates
|
||||
// them — the only way to reach them is a `case 'custom'` predicate calling
|
||||
// `ctx.addonEnabled`/`ctx.settingFlag` with a key of its own choosing.
|
||||
const addonProbe = vi.fn((ctx: { addonEnabled: (id: string) => boolean }) => ctx.addonEnabled('addon-nobody-asks-about') === false);
|
||||
const settingProbe = vi.fn((ctx: { settingFlag: (key: string) => boolean }) => ctx.settingFlag('setting-nobody-asks-about') === false);
|
||||
registerPredicate('branch-cov-addon-probe', addonProbe);
|
||||
registerPredicate('branch-cov-setting-probe', settingProbe);
|
||||
|
||||
const BASE_USER = { id: 7, login_count: 5, first_seen_version: '3.0.0', role: 'user' } as UserRow;
|
||||
|
||||
function makeService(overrides: { listForUser?: UserNoticeDismissalRow[] } = {}) {
|
||||
const findById = vi.fn(async () => BASE_USER);
|
||||
const countForUser = vi.fn(async () => 0);
|
||||
const listForUser = vi.fn(async () => overrides.listForUser ?? []);
|
||||
const upsertDismissal = vi.fn(async () => undefined);
|
||||
const isAddonEnabled = vi.fn(async () => false);
|
||||
const getValue = vi.fn(async () => null);
|
||||
const isManaged = vi.fn(() => false);
|
||||
const svc = new SystemNoticesService(
|
||||
{ isAddonEnabled } as never,
|
||||
{ isManaged } as never,
|
||||
{ findById } as never,
|
||||
{ countForUser } as never,
|
||||
{ listForUser, upsertDismissal } as never,
|
||||
{ getValue } as never,
|
||||
);
|
||||
return { svc, isAddonEnabled };
|
||||
}
|
||||
|
||||
describe('SystemNoticesService.getActiveFor — M3 branch coverage', () => {
|
||||
it('addonEnabled resolves false (not undefined/throw) for a key no condition ever names, never calling the injected AddonsService for it', async () => {
|
||||
const { svc, isAddonEnabled } = makeService();
|
||||
const ids = (await svc.getActiveFor(BASE_USER.id)).map((n) => n.id);
|
||||
expect(ids).toContain('sn-addon-flag-miss');
|
||||
expect(addonProbe).toHaveReturnedWith(true);
|
||||
expect(isAddonEnabled).not.toHaveBeenCalledWith('addon-nobody-asks-about');
|
||||
});
|
||||
|
||||
it('settingFlag resolves false (not undefined/throw) for a key no condition ever names', async () => {
|
||||
const { svc } = makeService();
|
||||
const ids = (await svc.getActiveFor(BASE_USER.id)).map((n) => n.id);
|
||||
expect(ids).toContain('sn-setting-flag-miss');
|
||||
expect(settingProbe).toHaveReturnedWith(true);
|
||||
});
|
||||
|
||||
it('a per-version notice dismissed by a row with a NULL dismissed_app_version (a pre-per-version dismissal) re-shows, same as an empty-string version', async () => {
|
||||
const { svc } = makeService({ listForUser: [{ notice_id: 'sn-release-nullver', dismissed_app_version: null }] });
|
||||
const ids = (await svc.getActiveFor(BASE_USER.id, new Set(['release']), getCurrentAppVersion())).map((n) => n.id);
|
||||
expect(ids).toContain('sn-release-nullver');
|
||||
});
|
||||
|
||||
it('a per-version notice dismissed by a row whose dismissed_app_version semver cannot coerce falls back to 0.0.0, same as re-showing', async () => {
|
||||
const { svc } = makeService({ listForUser: [{ notice_id: 'sn-release-nullver', dismissed_app_version: 'not-a-semver-string' }] });
|
||||
const ids = (await svc.getActiveFor(BASE_USER.id, new Set(['release']), getCurrentAppVersion())).map((n) => n.id);
|
||||
expect(ids).toContain('sn-release-nullver');
|
||||
});
|
||||
|
||||
it('sorts by priority first: a higher-priority notice comes before a same-severity, same-date, lower-priority one', async () => {
|
||||
const { svc } = makeService();
|
||||
const order = (await svc.getActiveFor(BASE_USER.id)).map((n) => n.id).filter((id) => id === 'sn-priority-hi' || id === 'sn-priority-lo');
|
||||
expect(order).toEqual(['sn-priority-hi', 'sn-priority-lo']);
|
||||
});
|
||||
|
||||
it('falls through to severity when priority ties: a critical notice comes before a same-priority, same-date info one', async () => {
|
||||
const { svc } = makeService();
|
||||
const order = (await svc.getActiveFor(BASE_USER.id)).map((n) => n.id).filter((id) => id === 'sn-severity-hi' || id === 'sn-severity-lo');
|
||||
expect(order).toEqual(['sn-severity-hi', 'sn-severity-lo']);
|
||||
});
|
||||
|
||||
it('falls through to publishedAt when priority AND severity tie: the newer notice comes first', async () => {
|
||||
const { svc } = makeService();
|
||||
const order = (await svc.getActiveFor(BASE_USER.id)).map((n) => n.id).filter((id) => id === 'sn-published-new' || id === 'sn-published-old');
|
||||
expect(order).toEqual(['sn-published-new', 'sn-published-old']);
|
||||
});
|
||||
|
||||
// The running app version is only ever the real getCurrentAppVersion() in
|
||||
// every other test in this file, which semver.coerce always parses — this
|
||||
// is the one case that forces the '0.0.0' fallback used for the
|
||||
// dismissal-recency comparison.
|
||||
it('a running app version semver cannot coerce falls back to 0.0.0 instead of throwing', async () => {
|
||||
vi.resetModules();
|
||||
vi.doMock('../../../src/systemNotices/service', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../../src/systemNotices/service')>();
|
||||
return { ...actual, getCurrentAppVersion: () => 'not-a-semver-string' };
|
||||
});
|
||||
try {
|
||||
const { SystemNoticesService: Reloaded } = await import('../../../src/nest/system-notices/system-notices.service');
|
||||
const inst = new Reloaded(
|
||||
{ isAddonEnabled: async () => false } as never,
|
||||
{ isManaged: () => false } as never,
|
||||
{ findById: async () => BASE_USER } as never,
|
||||
{ countForUser: async () => 0 } as never,
|
||||
{ listForUser: async () => [{ notice_id: 'sn-release-nullver', dismissed_app_version: '1.0.0' }] } as never,
|
||||
{ getValue: async () => null } as never,
|
||||
);
|
||||
await expect(inst.getActiveFor(BASE_USER.id)).resolves.toEqual(expect.any(Array));
|
||||
} finally {
|
||||
vi.doUnmock('../../../src/systemNotices/service');
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -183,6 +183,16 @@ describe('SystemNoticesService (Plan 3f Task 6)', () => {
|
||||
expect((await svc.getActiveFor(BASE_USER.id, new Set(['release']), 'dev')).map((n) => n.id)).toEqual(['sn-test-generic']);
|
||||
});
|
||||
|
||||
// L3 (task-7-review.md): dropped by Task 6, restored — the running app
|
||||
// version is read loosely (`semver.coerce`-shaped, tolerating a leading
|
||||
// `v`), same as the server reads its own.
|
||||
it('reads the version loosely, as the server reads its own', async () => {
|
||||
const { svc } = makeService();
|
||||
const ids = (await svc.getActiveFor(BASE_USER.id, new Set(['release']), 'v' + getCurrentAppVersion())).map((n) => n.id);
|
||||
expect(ids).toContain('sn-test-release');
|
||||
expect(ids).toContain('sn-test-generic');
|
||||
});
|
||||
|
||||
it('always delivers a notice without a release block', async () => {
|
||||
const { svc } = makeService();
|
||||
expect((await svc.getActiveFor(BASE_USER.id)).map((n) => n.id)).toEqual(['sn-test-generic']);
|
||||
@@ -190,6 +200,29 @@ describe('SystemNoticesService (Plan 3f Task 6)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// L3 (task-7-review.md): dropped by Task 6, restored. The emitted
|
||||
// design:paramtypes metadata guards an unresolved class binding with
|
||||
// `typeof AddonsService === 'undefined' ? Object : AddonsService`.
|
||||
// Simulate that mid-cycle state: the module must still evaluate and the
|
||||
// instance must still serve notices.
|
||||
it('still loads and works when the AddonsService binding is unresolved (import-cycle fallback)', async () => {
|
||||
vi.resetModules();
|
||||
vi.doMock('../../../src/nest/addons/addons.service', () => ({ AddonsService: undefined }));
|
||||
const { SystemNoticesService: Reloaded } = await import('../../../src/nest/system-notices/system-notices.service');
|
||||
const isAddonEnabled = vi.fn(async () => false);
|
||||
const inst = new Reloaded(
|
||||
{ isAddonEnabled } as never,
|
||||
{ isManaged: () => false } as never,
|
||||
{ findById: async () => BASE_USER } as never,
|
||||
{ countForUser: async () => 1 } as never,
|
||||
{ listForUser: async () => [] } as never,
|
||||
{ getValue: async () => null } as never,
|
||||
);
|
||||
const out = await inst.getActiveFor(BASE_USER.id);
|
||||
expect(out.map((n) => n.id)).toEqual(['sn-test-generic']);
|
||||
vi.doUnmock('../../../src/nest/addons/addons.service');
|
||||
});
|
||||
|
||||
describe('dismiss', () => {
|
||||
it('SN5 — upserts through the composite-PK repository with Date.now()/getCurrentAppVersion(), and returns true', async () => {
|
||||
const { svc, upsertDismissal } = makeService();
|
||||
|
||||
@@ -583,6 +583,60 @@ describe('shiftOwnerEntriesForTripWindow', () => {
|
||||
const row = testDb.prepare('SELECT date FROM vacay_entries WHERE plan_id = ? AND user_id = ?').get(plan.id, user.id) as { date: string };
|
||||
expect(row.date).toBe('2026-05-05');
|
||||
});
|
||||
|
||||
it('VACAY-SVC-030d (M2 parity): an unparseable start (garbage) resolves as a no-op, same as legacy\'s NULL-julianday offset of 0, instead of writing a NaN date', async () => {
|
||||
const { user, plan } = await setupUserWithPlan();
|
||||
testDb.prepare('INSERT INTO vacay_entries (plan_id, user_id, date, note) VALUES (?, ?, ?, ?)').run(plan.id, user.id, '2026-05-05', '');
|
||||
|
||||
await expect(svc.shiftOwnerEntriesForTripWindow(user.id, '2026-05-01', '2026-05-10', 'soon')).resolves.toBeUndefined();
|
||||
|
||||
const row = testDb.prepare('SELECT date FROM vacay_entries WHERE plan_id = ? AND user_id = ?').get(plan.id, user.id) as { date: string };
|
||||
expect(row.date).toBe('2026-05-05');
|
||||
});
|
||||
|
||||
it('VACAY-SVC-030e (M2 parity): a datetime start with no zone suffix is parsed as UTC and truncated, matching base\'s CAST(julianday(...) AS INTEGER) rather than a local-time round', async () => {
|
||||
// base: CAST(julianday('2025-06-12T23:30') - julianday('2025-06-10') AS INTEGER) = 2
|
||||
// (2 days 23.5 hours, truncated toward zero) — a local-time Date.parse +
|
||||
// Math.round of the same pair computed 3 instead (task-7-review.md M2).
|
||||
const { user, plan } = await setupUserWithPlan();
|
||||
testDb.prepare('INSERT INTO vacay_entries (plan_id, user_id, date, note) VALUES (?, ?, ?, ?)').run(plan.id, user.id, '2025-06-15', '');
|
||||
|
||||
await svc.shiftOwnerEntriesForTripWindow(user.id, '2025-06-10', '2025-06-20', '2025-06-12T23:30');
|
||||
|
||||
const row = testDb.prepare('SELECT date FROM vacay_entries WHERE plan_id = ? AND user_id = ?').get(plan.id, user.id) as { date: string };
|
||||
expect(row.date).toBe('2025-06-17');
|
||||
});
|
||||
|
||||
it('VACAY-SVC-030f (M1 parity): consecutive-day entries inserted in descending-id order shift to the rowid-ordered (legacy) outcome, not the date-index-ordered one', async () => {
|
||||
// Legacy's single `UPDATE OR IGNORE` walks rows in rowid order.
|
||||
// VacayEntriesRepository.shiftForOwnerWindow's `find` had no `orderBy`, so
|
||||
// SQLite returned candidates in (user, plan, date) index order instead —
|
||||
// a different per-row collision check skips different rows
|
||||
// (task-7-review.md M1). Inserting the latest date first makes the id
|
||||
// order run opposite the date order, so the two orderings disagree.
|
||||
const { user, plan } = await setupUserWithPlan();
|
||||
const insertEntry = (date: string) =>
|
||||
testDb.prepare('INSERT INTO vacay_entries (plan_id, user_id, date, note) VALUES (?, ?, ?, ?)').run(plan.id, user.id, date, '');
|
||||
const readDates = () =>
|
||||
(testDb.prepare('SELECT date FROM vacay_entries WHERE plan_id = ? AND user_id = ? ORDER BY date').all(plan.id, user.id) as { date: string }[]).map(
|
||||
(r) => r.date,
|
||||
);
|
||||
|
||||
insertEntry('2026-07-12');
|
||||
insertEntry('2026-07-11');
|
||||
insertEntry('2026-07-10');
|
||||
|
||||
await svc.shiftOwnerEntriesForTripWindow(user.id, '2026-07-01', '2026-07-20', '2026-07-02'); // offset +1
|
||||
expect(readDates()).toEqual(['2026-07-11', '2026-07-12', '2026-07-13']);
|
||||
|
||||
testDb.prepare('DELETE FROM vacay_entries WHERE plan_id = ?').run(plan.id);
|
||||
insertEntry('2026-07-12');
|
||||
insertEntry('2026-07-11');
|
||||
insertEntry('2026-07-10');
|
||||
|
||||
await svc.shiftOwnerEntriesForTripWindow(user.id, '2026-07-02', '2026-07-21', '2026-07-01'); // offset -1
|
||||
expect(readDates()).toEqual(['2026-07-09', '2026-07-11', '2026-07-12']);
|
||||
});
|
||||
});
|
||||
|
||||
// ── getEntries / toggleEntry ──────────────────────────────────────────────────
|
||||
@@ -975,6 +1029,24 @@ describe('getStats', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('VACAY-SVC-044a (L1 parity): a legacy NULL vacation_days/carried_over row passes through on the wire, not defaulted to 30/0', async () => {
|
||||
// task-7-review.md L1: `?? 30`/`?? 0` on these nullable columns would show
|
||||
// a fabricated default instead of the row's actual NULL — legacy bound
|
||||
// them AS-IS. `total_available`/`remaining` still need a number, so the
|
||||
// arithmetic null-coalesces separately, reproducing legacy's `null + n =
|
||||
// n` coercion without lying about the row on the wire.
|
||||
const { user, plan } = await setupUserWithPlan();
|
||||
const yr = new Date().getFullYear();
|
||||
testDb.prepare('UPDATE vacay_user_years SET vacation_days = NULL, carried_over = NULL WHERE user_id = ? AND plan_id = ? AND year = ?').run(user.id, plan.id, yr);
|
||||
|
||||
const stats = await svc.getStats(plan.id, yr);
|
||||
|
||||
expect(stats[0].vacation_days).toBeNull();
|
||||
expect(stats[0].carried_over).toBeNull();
|
||||
expect(stats[0].total_available).toBe(0);
|
||||
expect(stats[0].remaining).toBe(0);
|
||||
});
|
||||
|
||||
it('VACAY-SVC-045: used reflects the actual number of entries for that user and year', async () => {
|
||||
const { user, plan } = await setupUserWithPlan();
|
||||
const yr = new Date().getFullYear();
|
||||
|
||||
Reference in New Issue
Block a user