refactor(journey, oidc, place-enrichment, tokens, trip-members): async DB-touching methods; transactions through UnitOfWork

This commit is contained in:
jubnl
2026-09-22 04:16:07 +02:00
parent ad6e1ce8f0
commit 845320e0a4
45 changed files with 1043 additions and 1026 deletions
@@ -69,7 +69,7 @@ beforeAll(async () => {
new QueryHelpersService(dbs),
// Real collaborator rather than a stub: reconcile() runs after every mutation
// and needs the same connection to see the rows these cases write.
new JourneyDomainService(dbs, realtime, new TrekPhotosRepository(dbs)),
new JourneyDomainService(dbs, realtime, new TrekPhotosRepository(dbs), await createTestUnitOfWork(dbs.connection)),
);
});
@@ -141,7 +141,7 @@ describe('deleting a member re-splits their expenses (#1553)', () => {
it('BUDGET-SVC-DB-010: re-derives the persons divisor when a guest in the split is deleted', async () => {
const { user: owner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const guests = ['G1', 'G2', 'G3'].map(n => createGuest(trip.id, n, owner.id).member);
const guests = await Promise.all(['G1', 'G2', 'G3'].map(async n => (await createGuest(trip.id, n, owner.id)).member));
const item = await budget.createBudgetItem(trip.id, {
name: 'Dinner', total_price: 400,
member_ids: [owner.id, ...guests.map(g => g.id)],
@@ -160,7 +160,7 @@ describe('deleting a member re-splits their expenses (#1553)', () => {
it('BUDGET-SVC-DB-011: leaves a manually entered persons count alone', async () => {
const { user: owner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const guest = createGuest(trip.id, 'G1', owner.id).member;
const guest = (await createGuest(trip.id, 'G1', owner.id)).member;
// No member rows — `persons` is just a number someone typed.
const item = await budget.createBudgetItem(trip.id, { name: 'Rental', total_price: 300, persons: 6 });
@@ -172,7 +172,7 @@ describe('deleting a member re-splits their expenses (#1553)', () => {
it('BUDGET-SVC-DB-012: drops the last member to a null divisor rather than zero', async () => {
const { user: owner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const guest = createGuest(trip.id, 'G1', owner.id).member;
const guest = (await createGuest(trip.id, 'G1', owner.id)).member;
const item = await budget.createBudgetItem(trip.id, { name: 'Taxi', total_price: 50, member_ids: [guest.id] });
await deleteGuest(trip.id, guest.id);
@@ -184,7 +184,7 @@ describe('deleting a member re-splits their expenses (#1553)', () => {
it('BUDGET-SVC-DB-013: saves a split from a stale client instead of failing on the users FK', async () => {
const { user: owner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const guest = createGuest(trip.id, 'G1', owner.id).member;
const guest = (await createGuest(trip.id, 'G1', owner.id)).member;
const item = await budget.createBudgetItem(trip.id, { name: 'Dinner', total_price: 200, member_ids: [owner.id, guest.id] });
await deleteGuest(trip.id, guest.id);
@@ -199,7 +199,7 @@ describe('deleting a member re-splits their expenses (#1553)', () => {
it('BUDGET-SVC-DB-014: ignores a deleted member arriving through updateMembers', async () => {
const { user: owner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const guest = createGuest(trip.id, 'G1', owner.id).member;
const guest = (await createGuest(trip.id, 'G1', owner.id)).member;
const item = await budget.createBudgetItem(trip.id, { name: 'Drinks', total_price: 60, member_ids: [owner.id, guest.id] });
await deleteGuest(trip.id, guest.id);
@@ -45,10 +45,11 @@ import { TrekPhotosRepository } from '../../../src/nest/photos/trek-photos.repos
import { JourneyDomainService } from '../../../src/nest/journey/journey-domain.service';
import { JourneyBookService } from '../../../src/nest/journey/journey-book.service';
import { db as dbConn } from '../../../src/db/database';
import { createTestUnitOfWork } from '../../helpers/test-uow';
const dbs = new DatabaseService(dbConn);
const domain = new JourneyDomainService(dbs, new RealtimeService(), new TrekPhotosRepository(dbs));
const books = new JourneyBookService(dbs, domain);
let domain: JourneyDomainService;
let books: JourneyBookService;
/** A minimal document that survives normalizeBookDocument unchanged. */
function doc(title = 'one') {
@@ -60,9 +61,12 @@ function doc(title = 'one') {
};
}
beforeAll(() => {
beforeAll(async () => {
createTables(testDb);
runMigrations(testDb);
const uow = await createTestUnitOfWork(testDb);
domain = new JourneyDomainService(dbs, new RealtimeService(), new TrekPhotosRepository(dbs), uow);
books = new JourneyBookService(dbs, domain);
});
beforeEach(() => {
@@ -76,15 +80,15 @@ afterAll(() => {
// -- Access -------------------------------------------------------------------
describe('access', () => {
it('refuses a journey the user cannot see', () => {
it('refuses a journey the user cannot see', async () => {
const { user: owner } = createUser(testDb);
const { user: stranger } = createUser(testDb);
const journey = createJourney(testDb, owner.id);
expect(books.getBook(journey.id, stranger.id)).toBeNull();
expect(books.saveBook(journey.id, stranger.id, { title: '', document: doc() })).toBeNull();
expect(books.deleteBook(journey.id, stranger.id)).toBeNull();
expect(books.canOpen(journey.id, stranger.id)).toBe(false);
expect(await books.getBook(journey.id, stranger.id)).toBeNull();
expect(await books.saveBook(journey.id, stranger.id, { title: '', document: doc() })).toBeNull();
expect(await books.deleteBook(journey.id, stranger.id)).toBeNull();
expect(await books.canOpen(journey.id, stranger.id)).toBe(false);
});
/*
@@ -92,80 +96,80 @@ describe('access', () => {
* over the same object is how two rules end up disagreeing about who may do
* what.
*/
it('lets a contributor edit, not only the owner', () => {
it('lets a contributor edit, not only the owner', async () => {
const { user: owner } = createUser(testDb);
const { user: helper } = createUser(testDb);
const journey = createJourney(testDb, owner.id);
addJourneyContributor(testDb, journey.id, helper.id, 'editor');
const saved = books.saveBook(journey.id, helper.id, { title: 'B', document: doc() });
const saved = await books.saveBook(journey.id, helper.id, { title: 'B', document: doc() });
expect(saved && 'record' in saved).toBe(true);
expect(books.getBook(journey.id, helper.id)).not.toBeNull();
expect(await books.getBook(journey.id, helper.id)).not.toBeNull();
});
it('lets a viewer read the book but not overwrite or delete it', () => {
it('lets a viewer read the book but not overwrite or delete it', async () => {
const { user: owner } = createUser(testDb);
const { user: guest } = createUser(testDb);
const journey = createJourney(testDb, owner.id);
addJourneyContributor(testDb, journey.id, guest.id, 'viewer');
books.saveBook(journey.id, owner.id, { title: 'Iceland', document: doc() });
await books.saveBook(journey.id, owner.id, { title: 'Iceland', document: doc() });
expect(books.canOpen(journey.id, guest.id)).toBe(true);
expect(books.getBook(journey.id, guest.id)).not.toBeNull();
expect(books.saveBook(journey.id, guest.id, { title: 'mine now', document: doc('two') })).toBeNull();
expect(books.deleteBook(journey.id, guest.id)).toBeNull();
expect(books.getBook(journey.id, owner.id)!.title).toBe('Iceland');
expect(await books.canOpen(journey.id, guest.id)).toBe(true);
expect(await books.getBook(journey.id, guest.id)).not.toBeNull();
expect(await books.saveBook(journey.id, guest.id, { title: 'mine now', document: doc('two') })).toBeNull();
expect(await books.deleteBook(journey.id, guest.id)).toBeNull();
expect((await books.getBook(journey.id, owner.id))!.title).toBe('Iceland');
});
it('says nothing about a journey that does not exist', () => {
it('says nothing about a journey that does not exist', async () => {
const { user } = createUser(testDb);
expect(books.canOpen(999_999, user.id)).toBe(false);
expect(books.getBook(999_999, user.id)).toBeNull();
expect(await books.canOpen(999_999, user.id)).toBe(false);
expect(await books.getBook(999_999, user.id)).toBeNull();
});
});
// -- Creating and reading -----------------------------------------------------
describe('creating and reading', () => {
it('is null for a journey with no book yet', () => {
it('is null for a journey with no book yet', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
expect(books.getBook(journey.id, user.id)).toBeNull();
expect(books.canOpen(journey.id, user.id)).toBe(true);
expect(await books.getBook(journey.id, user.id)).toBeNull();
expect(await books.canOpen(journey.id, user.id)).toBe(true);
});
it('creates on first save, at version 1', () => {
it('creates on first save, at version 1', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const saved = books.saveBook(journey.id, user.id, { title: 'Iceland', document: doc() });
const saved = await books.saveBook(journey.id, user.id, { title: 'Iceland', document: doc() });
expect(saved && 'record' in saved && saved.record.version).toBe(1);
expect(saved && 'record' in saved && saved.record.title).toBe('Iceland');
});
it('reads the document back as it went in', () => {
it('reads the document back as it went in', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
books.saveBook(journey.id, user.id, { title: 'T', document: doc() });
await books.saveBook(journey.id, user.id, { title: 'T', document: doc() });
const read = books.getBook(journey.id, user.id)!;
const read = (await books.getBook(journey.id, user.id))!;
expect(read.document.spreads).toHaveLength(1);
expect(read.document.page.pageWidth).toBe(210);
});
it('records who saved it', () => {
it('records who saved it', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
books.saveBook(journey.id, user.id, { title: 'T', document: doc() });
expect(books.getBook(journey.id, user.id)!.updatedBy).toBe(user.id);
await books.saveBook(journey.id, user.id, { title: 'T', document: doc() });
expect((await books.getBook(journey.id, user.id))!.updatedBy).toBe(user.id);
});
it('lists books without their documents', () => {
it('lists books without their documents', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
books.saveBook(journey.id, user.id, { title: 'Iceland', document: doc() });
await books.saveBook(journey.id, user.id, { title: 'Iceland', document: doc() });
const list = books.listBooks(journey.id, user.id)!;
const list = (await books.listBooks(journey.id, user.id))!;
expect(list).toHaveLength(1);
expect(list[0].title).toBe('Iceland');
expect('document' in list[0]).toBe(false);
@@ -176,7 +180,7 @@ describe('creating and reading', () => {
* not lock somebody out of their own book — normalizeBookDocument drops what
* it cannot read rather than throwing.
*/
it('opens a book whose stored JSON is broken, rather than throwing', () => {
it('opens a book whose stored JSON is broken, rather than throwing', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
testDb
@@ -185,7 +189,7 @@ describe('creating and reading', () => {
)
.run(journey.id);
const read = books.getBook(journey.id, user.id);
const read = await books.getBook(journey.id, user.id);
expect(read).not.toBeNull();
expect(read!.document.spreads).toEqual([]);
});
@@ -194,16 +198,16 @@ describe('creating and reading', () => {
// -- Concurrency --------------------------------------------------------------
describe('concurrency', () => {
function seed() {
async function seed() {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
books.saveBook(journey.id, user.id, { title: 'T', document: doc('one') });
await books.saveBook(journey.id, user.id, { title: 'T', document: doc('one') });
return { user, journey };
}
it('bumps the version on every save', () => {
const { user, journey } = seed();
const second = books.saveBook(journey.id, user.id, {
it('bumps the version on every save', async () => {
const { user, journey } = await seed();
const second = await books.saveBook(journey.id, user.id, {
title: 'T',
document: doc('two'),
baseVersion: 1,
@@ -212,11 +216,11 @@ describe('concurrency', () => {
});
/* The one this column exists for. */
it('refuses a save made against a version that has moved', () => {
const { user, journey } = seed();
books.saveBook(journey.id, user.id, { title: 'T', document: doc('two'), baseVersion: 1 });
it('refuses a save made against a version that has moved', async () => {
const { user, journey } = await seed();
await books.saveBook(journey.id, user.id, { title: 'T', document: doc('two'), baseVersion: 1 });
const stale = books.saveBook(journey.id, user.id, {
const stale = await books.saveBook(journey.id, user.id, {
title: 'T',
document: doc('three'),
baseVersion: 1,
@@ -224,11 +228,11 @@ describe('concurrency', () => {
expect(stale && 'conflict' in stale).toBe(true);
});
it('answers a conflict with the current record, not only a refusal', () => {
const { user, journey } = seed();
books.saveBook(journey.id, user.id, { title: 'Theirs', document: doc('two'), baseVersion: 1 });
it('answers a conflict with the current record, not only a refusal', async () => {
const { user, journey } = await seed();
await books.saveBook(journey.id, user.id, { title: 'Theirs', document: doc('two'), baseVersion: 1 });
const stale = books.saveBook(journey.id, user.id, {
const stale = await books.saveBook(journey.id, user.id, {
title: 'Mine',
document: doc('three'),
baseVersion: 1,
@@ -238,72 +242,72 @@ describe('concurrency', () => {
expect(stale && 'conflict' in stale && stale.conflict.document.title).toBe('two');
});
it('leaves the stored document untouched when it refuses', () => {
const { user, journey } = seed();
books.saveBook(journey.id, user.id, { title: 'Theirs', document: doc('two'), baseVersion: 1 });
books.saveBook(journey.id, user.id, { title: 'Mine', document: doc('three'), baseVersion: 1 });
it('leaves the stored document untouched when it refuses', async () => {
const { user, journey } = await seed();
await books.saveBook(journey.id, user.id, { title: 'Theirs', document: doc('two'), baseVersion: 1 });
await books.saveBook(journey.id, user.id, { title: 'Mine', document: doc('three'), baseVersion: 1 });
expect(books.getBook(journey.id, user.id)!.document.title).toBe('two');
expect(books.getBook(journey.id, user.id)!.version).toBe(2);
expect((await books.getBook(journey.id, user.id))!.document.title).toBe('two');
expect((await books.getBook(journey.id, user.id))!.version).toBe(2);
});
/*
* "Open Studio and start editing" has to work for the second person to
* arrive, who has a document but no version yet.
*/
it('takes a save with no base version as an ordinary write', () => {
const { user, journey } = seed();
const saved = books.saveBook(journey.id, user.id, { title: 'T', document: doc('two') });
it('takes a save with no base version as an ordinary write', async () => {
const { user, journey } = await seed();
const saved = await books.saveBook(journey.id, user.id, { title: 'T', document: doc('two') });
expect(saved && 'record' in saved && saved.record.version).toBe(2);
});
it('lets the loser save again once it has the new version', () => {
const { user, journey } = seed();
books.saveBook(journey.id, user.id, { title: 'T', document: doc('two'), baseVersion: 1 });
const conflict = books.saveBook(journey.id, user.id, {
it('lets the loser save again once it has the new version', async () => {
const { user, journey } = await seed();
await books.saveBook(journey.id, user.id, { title: 'T', document: doc('two'), baseVersion: 1 });
const conflict = await books.saveBook(journey.id, user.id, {
title: 'T',
document: doc('mine'),
baseVersion: 1,
});
expect(conflict && 'conflict' in conflict).toBe(true);
const retry = books.saveBook(journey.id, user.id, {
const retry = await books.saveBook(journey.id, user.id, {
title: 'T',
document: doc('mine'),
baseVersion: 2,
});
expect(retry && 'record' in retry && retry.record.version).toBe(3);
expect(books.getBook(journey.id, user.id)!.document.title).toBe('mine');
expect((await books.getBook(journey.id, user.id))!.document.title).toBe('mine');
});
it('does not let a version from another journey unlock this one', () => {
const { user, journey } = seed();
it('does not let a version from another journey unlock this one', async () => {
const { user, journey } = await seed();
const other = createJourney(testDb, user.id);
books.saveBook(other.id, user.id, { title: 'O', document: doc('other') });
await books.saveBook(other.id, user.id, { title: 'O', document: doc('other') });
// Version 1 is current over there and stale here.
books.saveBook(journey.id, user.id, { title: 'T', document: doc('two'), baseVersion: 1 });
const stale = books.saveBook(journey.id, user.id, {
await books.saveBook(journey.id, user.id, { title: 'T', document: doc('two'), baseVersion: 1 });
const stale = await books.saveBook(journey.id, user.id, {
title: 'T',
document: doc('three'),
baseVersion: 1,
});
expect(stale && 'conflict' in stale).toBe(true);
expect(books.getBook(other.id, user.id)!.version).toBe(1);
expect((await books.getBook(other.id, user.id))!.version).toBe(1);
});
});
// -- Broadcasting -------------------------------------------------------------
describe('broadcastSaved', () => {
it('sends the version, not the document, and excludes the saver', () => {
it('sends the version, not the document, and excludes the saver', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const saved = books.saveBook(journey.id, user.id, { title: 'T', document: doc() })!;
const saved = (await books.saveBook(journey.id, user.id, { title: 'T', document: doc() }))!;
const record = 'record' in saved ? saved.record : null;
const spy = vi.spyOn(domain, 'broadcastJourneyEvent').mockImplementation(() => {});
books.broadcastSaved(journey.id, user.id, record!, 'socket-7');
const spy = vi.spyOn(domain, 'broadcastJourneyEvent').mockImplementation(async () => {});
await books.broadcastSaved(journey.id, user.id, record!, 'socket-7');
expect(spy).toHaveBeenCalledWith(
journey.id,
@@ -318,25 +322,25 @@ describe('broadcastSaved', () => {
// -- Deleting -----------------------------------------------------------------
describe('deleting', () => {
it('removes the book and reports it', () => {
it('removes the book and reports it', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
books.saveBook(journey.id, user.id, { title: 'T', document: doc() });
await books.saveBook(journey.id, user.id, { title: 'T', document: doc() });
expect(books.deleteBook(journey.id, user.id)).toBe(true);
expect(books.getBook(journey.id, user.id)).toBeNull();
expect(await books.deleteBook(journey.id, user.id)).toBe(true);
expect(await books.getBook(journey.id, user.id)).toBeNull();
});
it('reports false when there was nothing to delete', () => {
it('reports false when there was nothing to delete', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
expect(books.deleteBook(journey.id, user.id)).toBe(false);
expect(await books.deleteBook(journey.id, user.id)).toBe(false);
});
it('goes with the journey it belongs to', () => {
it('goes with the journey it belongs to', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
books.saveBook(journey.id, user.id, { title: 'T', document: doc() });
await books.saveBook(journey.id, user.id, { title: 'T', document: doc() });
testDb.prepare('DELETE FROM journeys WHERE id = ?').run(journey.id);
File diff suppressed because it is too large Load Diff
@@ -49,10 +49,11 @@ let svc: JourneyShareService;
beforeAll(async () => {
createTables(testDb);
runMigrations(testDb);
const uow = await createTestUnitOfWork(testDb);
svc = new JourneyShareService(
dbs,
new JourneyDomainService(dbs, new RealtimeService(), new TrekPhotosRepository(dbs)),
new SettingsService(dbs, await createTestUnitOfWork(testDb)),
new JourneyDomainService(dbs, new RealtimeService(), new TrekPhotosRepository(dbs), uow),
new SettingsService(dbs, uow),
);
});
@@ -104,44 +105,44 @@ function insertJourneyPhoto(
// -- Tests --------------------------------------------------------------------
describe('createOrUpdateJourneyShareLink', () => {
it('JOURNEY-SHARE-001: creates a new share link with default permissions', () => {
it('JOURNEY-SHARE-001: creates a new share link with default permissions', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const result = svc.createOrUpdateJourneyShareLink(journey.id, user.id, {});
const result = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {});
expect(result.created).toBe(true);
expect(result.token).toBeTruthy();
expect(result.token.length).toBeGreaterThan(10);
});
it('JOURNEY-SHARE-002: creates a share link with custom permissions', () => {
it('JOURNEY-SHARE-002: creates a share link with custom permissions', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
svc.createOrUpdateJourneyShareLink(journey.id, user.id, {
await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {
share_timeline: true,
share_gallery: false,
share_map: false,
});
const link = svc.getJourneyShareLink(journey.id);
const link = await svc.getJourneyShareLink(journey.id);
expect(link).not.toBeNull();
expect(link!.share_timeline).toBe(true);
expect(link!.share_gallery).toBe(false);
expect(link!.share_map).toBe(false);
});
it('JOURNEY-SHARE-003: updates permissions on existing link without regenerating token', () => {
it('JOURNEY-SHARE-003: updates permissions on existing link without regenerating token', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const first = svc.createOrUpdateJourneyShareLink(journey.id, user.id, {
const first = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {
share_timeline: true,
share_gallery: true,
share_map: true,
});
const second = svc.createOrUpdateJourneyShareLink(journey.id, user.id, {
const second = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {
share_timeline: true,
share_gallery: false,
share_map: false,
@@ -150,35 +151,35 @@ describe('createOrUpdateJourneyShareLink', () => {
expect(second.created).toBe(false);
expect(second.token).toBe(first.token);
const link = svc.getJourneyShareLink(journey.id);
const link = await svc.getJourneyShareLink(journey.id);
expect(link!.share_gallery).toBe(false);
expect(link!.share_map).toBe(false);
});
it('JOURNEY-SHARE-029: reading the link separates "no link" from "not yours"', () => {
it('JOURNEY-SHARE-029: reading the link separates "no link" from "not yours"', async () => {
const { user: owner } = createUser(testDb);
const { user: helper } = createUser(testDb);
const journey = createJourney(testDb, owner.id);
addJourneyContributor(testDb, journey.id, helper.id, 'editor');
// Nothing published yet: an owner is allowed to look and finds nothing.
expect(svc.readJourneyShareLink(journey.id, owner.id)).toEqual({ allowed: true, link: null });
expect(await svc.readJourneyShareLink(journey.id, owner.id)).toEqual({ allowed: true, link: null });
svc.createOrUpdateJourneyShareLink(journey.id, owner.id, {});
const asOwner = svc.readJourneyShareLink(journey.id, owner.id);
await svc.createOrUpdateJourneyShareLink(journey.id, owner.id, {});
const asOwner = await svc.readJourneyShareLink(journey.id, owner.id);
expect(asOwner.allowed).toBe(true);
expect(asOwner.allowed && asOwner.link?.token).toBeTruthy();
// An editor is refused outright. Answering { link: null } here would tell a
// published journey's editor it is unpublished and offer to publish it.
expect(svc.readJourneyShareLink(journey.id, helper.id)).toEqual({ allowed: false });
expect(await svc.readJourneyShareLink(journey.id, helper.id)).toEqual({ allowed: false });
});
it('JOURNEY-SHARE-027: an update leaves out flags it was not given', () => {
it('JOURNEY-SHARE-027: an update leaves out flags it was not given', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
svc.createOrUpdateJourneyShareLink(journey.id, user.id, {
await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {
share_timeline: true,
share_gallery: false,
share_map: false,
@@ -186,61 +187,61 @@ describe('createOrUpdateJourneyShareLink', () => {
});
// A caller that only flips the timeline must not silently re-publish the
// gallery and map at the unchanged token.
svc.createOrUpdateJourneyShareLink(journey.id, user.id, { share_timeline: false });
await svc.createOrUpdateJourneyShareLink(journey.id, user.id, { share_timeline: false });
const link = svc.getJourneyShareLink(journey.id);
const link = await svc.getJourneyShareLink(journey.id);
expect(link!.share_timeline).toBe(false);
expect(link!.share_gallery).toBe(false);
expect(link!.share_map).toBe(false);
expect(link!.newest_first).toBe(true);
});
it('JOURNEY-SHARE-028: newest_first survives a flag-only update and is settable', () => {
it('JOURNEY-SHARE-028: newest_first survives a flag-only update and is settable', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
svc.createOrUpdateJourneyShareLink(journey.id, user.id, {});
expect(svc.getJourneyShareLink(journey.id)!.newest_first).toBe(false);
await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {});
expect((await svc.getJourneyShareLink(journey.id))!.newest_first).toBe(false);
svc.createOrUpdateJourneyShareLink(journey.id, user.id, { newest_first: true });
expect(svc.getJourneyShareLink(journey.id)!.newest_first).toBe(true);
await svc.createOrUpdateJourneyShareLink(journey.id, user.id, { newest_first: true });
expect((await svc.getJourneyShareLink(journey.id))!.newest_first).toBe(true);
svc.createOrUpdateJourneyShareLink(journey.id, user.id, { share_gallery: false });
expect(svc.getJourneyShareLink(journey.id)!.newest_first).toBe(true);
await svc.createOrUpdateJourneyShareLink(journey.id, user.id, { share_gallery: false });
expect((await svc.getJourneyShareLink(journey.id))!.newest_first).toBe(true);
});
it('JOURNEY-SHARE-004: different journeys get different tokens', () => {
it('JOURNEY-SHARE-004: different journeys get different tokens', async () => {
const { user } = createUser(testDb);
const j1 = createJourney(testDb, user.id);
const j2 = createJourney(testDb, user.id);
const r1 = svc.createOrUpdateJourneyShareLink(j1.id, user.id, {});
const r2 = svc.createOrUpdateJourneyShareLink(j2.id, user.id, {});
const r1 = await svc.createOrUpdateJourneyShareLink(j1.id, user.id, {});
const r2 = await svc.createOrUpdateJourneyShareLink(j2.id, user.id, {});
expect(r1.token).not.toBe(r2.token);
});
});
describe('getJourneyShareLink', () => {
it('JOURNEY-SHARE-005: returns null when no share link exists', () => {
it('JOURNEY-SHARE-005: returns null when no share link exists', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const result = svc.getJourneyShareLink(journey.id);
const result = await svc.getJourneyShareLink(journey.id);
expect(result).toBeNull();
});
it('JOURNEY-SHARE-006: returns share link info when it exists', () => {
it('JOURNEY-SHARE-006: returns share link info when it exists', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
svc.createOrUpdateJourneyShareLink(journey.id, user.id, {
await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {
share_timeline: true,
share_gallery: false,
share_map: true,
});
const result = svc.getJourneyShareLink(journey.id);
const result = await svc.getJourneyShareLink(journey.id);
expect(result).not.toBeNull();
expect(result!.token).toBeTruthy();
@@ -252,83 +253,83 @@ describe('getJourneyShareLink', () => {
});
describe('deleteJourneyShareLink', () => {
it('JOURNEY-SHARE-007: owner can remove an existing share link', () => {
it('JOURNEY-SHARE-007: owner can remove an existing share link', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
svc.createOrUpdateJourneyShareLink(journey.id, user.id, {});
await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {});
const ok = svc.deleteJourneyShareLink(journey.id, user.id);
const ok = await svc.deleteJourneyShareLink(journey.id, user.id);
expect(ok).toBe(true);
expect(svc.getJourneyShareLink(journey.id)).toBeNull();
expect(await svc.getJourneyShareLink(journey.id)).toBeNull();
});
it('JOURNEY-SHARE-008: does not throw when deleting non-existent link', () => {
it('JOURNEY-SHARE-008: does not throw when deleting non-existent link', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
expect(() => svc.deleteJourneyShareLink(journey.id, user.id)).not.toThrow();
await expect(svc.deleteJourneyShareLink(journey.id, user.id)).resolves.toBe(true);
});
});
describe('validateShareTokenForPhoto', () => {
it('JOURNEY-SHARE-009: returns journeyId and ownerId for valid token + photo', () => {
it('JOURNEY-SHARE-009: returns journeyId and ownerId for valid token + photo', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const entry = createJourneyEntry(testDb, journey.id, user.id);
const photoId = insertJourneyPhoto(entry.id, { ownerId: user.id });
const { token } = svc.createOrUpdateJourneyShareLink(journey.id, user.id, {});
const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {});
const result = svc.validateShareTokenForPhoto(token, photoId);
const result = await svc.validateShareTokenForPhoto(token, photoId);
expect(result).not.toBeNull();
expect(result!.journeyId).toBe(journey.id);
expect(result!.ownerId).toBe(user.id);
});
it('JOURNEY-SHARE-010: returns null for invalid token', () => {
const result = svc.validateShareTokenForPhoto('nonexistent-token', 1);
it('JOURNEY-SHARE-010: returns null for invalid token', async () => {
const result = await svc.validateShareTokenForPhoto('nonexistent-token', 1);
expect(result).toBeNull();
});
it('JOURNEY-SHARE-011: returns null when photo does not belong to shared journey', () => {
it('JOURNEY-SHARE-011: returns null when photo does not belong to shared journey', async () => {
const { user } = createUser(testDb);
const journey1 = createJourney(testDb, user.id);
const journey2 = createJourney(testDb, user.id);
const entry2 = createJourneyEntry(testDb, journey2.id, user.id);
const photoId = insertJourneyPhoto(entry2.id);
const { token } = svc.createOrUpdateJourneyShareLink(journey1.id, user.id, {});
const { token } = await svc.createOrUpdateJourneyShareLink(journey1.id, user.id, {});
const result = svc.validateShareTokenForPhoto(token, photoId);
const result = await svc.validateShareTokenForPhoto(token, photoId);
expect(result).toBeNull();
});
it('JOURNEY-SHARE-012: falls back to journey owner_id when photo has no owner_id', () => {
it('JOURNEY-SHARE-012: falls back to journey owner_id when photo has no owner_id', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const entry = createJourneyEntry(testDb, journey.id, user.id);
const photoId = insertJourneyPhoto(entry.id, { ownerId: undefined });
const { token } = svc.createOrUpdateJourneyShareLink(journey.id, user.id, {});
const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {});
const result = svc.validateShareTokenForPhoto(token, photoId);
const result = await svc.validateShareTokenForPhoto(token, photoId);
expect(result).not.toBeNull();
expect(result!.ownerId).toBe(user.id);
});
// Regression — GHSA-9hc8 sibling: the byte proxy must honour share_gallery.
it('JOURNEY-SHARE-017: returns null when the owner disabled the gallery (share_gallery=false)', () => {
it('JOURNEY-SHARE-017: returns null when the owner disabled the gallery (share_gallery=false)', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const entry = createJourneyEntry(testDb, journey.id, user.id);
const photoId = insertJourneyPhoto(entry.id, { ownerId: user.id });
const { token } = svc.createOrUpdateJourneyShareLink(journey.id, user.id, { share_timeline: true, share_gallery: false, share_map: true });
const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, { share_timeline: true, share_gallery: false, share_map: true });
expect(svc.validateShareTokenForPhoto(token, photoId)).toBeNull();
expect(await svc.validateShareTokenForPhoto(token, photoId)).toBeNull();
});
it('JOURNEY-SHARE-016: resolves correctly when trek_photos.id differs from journey_photos.id (Immich bulk-sync scenario)', () => {
it('JOURNEY-SHARE-016: resolves correctly when trek_photos.id differs from journey_photos.id (Immich bulk-sync scenario)', async () => {
// Simulate a user who has many trek_photos from Immich syncs before adding a journey photo.
// trek_photos.id will be higher than journey_photos.id — the previous bug matched on jp.id
// instead of jp.photo_id, causing a 404 for Immich photos in public shares.
@@ -343,10 +344,10 @@ describe('validateShareTokenForPhoto', () => {
// This trek_photos row gets a high id (e.g. 6) while journey_photos id will be 1
const trekPhotoId = insertJourneyPhoto(entry.id, { assetId: 'journey-asset-xyz', ownerId: user.id });
const { token } = svc.createOrUpdateJourneyShareLink(journey.id, user.id, {});
const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {});
// photoId = trek_photos.id (6), not journey_photos.id (1)
const result = svc.validateShareTokenForPhoto(token, trekPhotoId);
const result = await svc.validateShareTokenForPhoto(token, trekPhotoId);
expect(result).not.toBeNull();
expect(result!.ownerId).toBe(user.id);
@@ -355,59 +356,59 @@ describe('validateShareTokenForPhoto', () => {
});
describe('validateShareTokenForAsset', () => {
it('JOURNEY-SHARE-013: returns ownerId when asset belongs to shared journey', () => {
it('JOURNEY-SHARE-013: returns ownerId when asset belongs to shared journey', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const entry = createJourneyEntry(testDb, journey.id, user.id);
insertJourneyPhoto(entry.id, { assetId: 'immich-asset-123', ownerId: user.id });
const { token } = svc.createOrUpdateJourneyShareLink(journey.id, user.id, {});
const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {});
const result = svc.validateShareTokenForAsset(token, 'immich-asset-123');
const result = await svc.validateShareTokenForAsset(token, 'immich-asset-123');
expect(result).not.toBeNull();
expect(result!.ownerId).toBe(user.id);
});
it('JOURNEY-SHARE-014: returns null for invalid token', () => {
const result = svc.validateShareTokenForAsset('bad-token', 'some-asset');
it('JOURNEY-SHARE-014: returns null for invalid token', async () => {
const result = await svc.validateShareTokenForAsset('bad-token', 'some-asset');
expect(result).toBeNull();
});
// Regression — GHSA-9hc8 sibling: the asset proxy must honour share_gallery.
it('JOURNEY-SHARE-018: returns null when the owner disabled the gallery (share_gallery=false)', () => {
it('JOURNEY-SHARE-018: returns null when the owner disabled the gallery (share_gallery=false)', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const entry = createJourneyEntry(testDb, journey.id, user.id);
insertJourneyPhoto(entry.id, { assetId: 'immich-asset-999', ownerId: user.id });
const { token } = svc.createOrUpdateJourneyShareLink(journey.id, user.id, { share_timeline: true, share_gallery: false, share_map: true });
const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, { share_timeline: true, share_gallery: false, share_map: true });
expect(svc.validateShareTokenForAsset(token, 'immich-asset-999')).toBeNull();
expect(await svc.validateShareTokenForAsset(token, 'immich-asset-999')).toBeNull();
});
it('JOURNEY-SHARE-029: falls back to the journey owner when the photo has no owner_id', () => {
it('JOURNEY-SHARE-029: falls back to the journey owner when the photo has no owner_id', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const entry = createJourneyEntry(testDb, journey.id, user.id);
insertJourneyPhoto(entry.id, { assetId: 'immich-asset-orphan' });
const { token } = svc.createOrUpdateJourneyShareLink(journey.id, user.id, {});
const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {});
// Without the fallback the controller filled the gap from the :ownerId path
// segment, i.e. an anonymous caller picked whose provider credentials to try.
const result = svc.validateShareTokenForAsset(token, 'immich-asset-orphan');
const result = await svc.validateShareTokenForAsset(token, 'immich-asset-orphan');
expect(result).not.toBeNull();
expect(result!.ownerId).toBe(user.id);
});
it('JOURNEY-SHARE-015: denies (returns null) when the asset is not part of the shared journey', () => {
it('JOURNEY-SHARE-015: denies (returns null) when the asset is not part of the shared journey', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const { token } = svc.createOrUpdateJourneyShareLink(journey.id, user.id, {});
const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {});
// A valid share token must NOT resolve arbitrary asset IDs to the owner —
// otherwise it could proxy any asset out of the owner's Immich/Synology
// library (IDOR). Only assets actually in the journey may resolve.
const result = svc.validateShareTokenForAsset(token, 'nonexistent-asset');
const result = await svc.validateShareTokenForAsset(token, 'nonexistent-asset');
expect(result).toBeNull();
});
@@ -438,7 +439,7 @@ describe('getPublicJourney', () => {
location_name: 'Kyoto',
});
insertJourneyPhoto(entry1.id);
const { token } = svc.createOrUpdateJourneyShareLink(journey.id, user.id, {
const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {
share_timeline: true,
share_gallery: true,
share_map: false,
@@ -467,7 +468,7 @@ describe('getPublicJourney', () => {
const journey = createJourney(testDb, user.id);
testDb.prepare('UPDATE journeys SET show_mood = 0, show_weather = 0 WHERE id = ?').run(journey.id);
createJourneyEntry(testDb, journey.id, user.id, { type: 'entry', title: 'Tag 1', entry_date: '2026-03-20' });
const { token } = svc.createOrUpdateJourneyShareLink(journey.id, user.id, {
const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {
share_timeline: true, share_gallery: false, share_map: true,
});
@@ -489,7 +490,7 @@ describe('getPublicJourney', () => {
title: 'Skeleton Entry',
entry_date: '2026-01-11',
});
const { token } = svc.createOrUpdateJourneyShareLink(journey.id, user.id, {});
const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {});
const result = await svc.getPublicJourney(token);
@@ -510,7 +511,7 @@ describe('getPublicJourney', () => {
.run(JSON.stringify(['food', 'culture']), entry.id);
insertJourneyPhoto(entry.id, { filePath: '/photos/a.jpg' });
insertJourneyPhoto(entry.id, { filePath: '/photos/b.jpg' });
const { token } = svc.createOrUpdateJourneyShareLink(journey.id, user.id, {});
const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {});
const result = await svc.getPublicJourney(token);
@@ -523,7 +524,7 @@ describe('getPublicJourney', () => {
it('JOURNEY-SHARE-020: returns empty entries array for journey with no entries', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id, { title: 'Empty Journey' });
const { token } = svc.createOrUpdateJourneyShareLink(journey.id, user.id, {});
const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {});
const result = await svc.getPublicJourney(token);
@@ -542,7 +543,7 @@ describe('getPublicJourney', () => {
});
testDb.prepare('UPDATE journey_entries SET location_lat = ?, location_lng = ? WHERE id = ?').run(48.8566, 2.3522, entry.id);
insertJourneyPhoto(entry.id);
const { token } = svc.createOrUpdateJourneyShareLink(journey.id, user.id, {
const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {
share_timeline: false, share_gallery: false, share_map: false,
});
@@ -559,7 +560,7 @@ describe('getPublicJourney', () => {
type: 'entry', title: 'Day 1', story: 'notes', entry_date: '2026-05-01', location_name: 'Paris',
});
testDb.prepare('UPDATE journey_entries SET location_lat = ?, location_lng = ? WHERE id = ?').run(48.8566, 2.3522, entry.id);
const { token } = svc.createOrUpdateJourneyShareLink(journey.id, user.id, {
const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {
share_timeline: true, share_gallery: true, share_map: false,
});
@@ -578,7 +579,7 @@ describe('getPublicJourney', () => {
type: 'entry', title: 'Day 1', story: 'private notes', entry_date: '2026-05-01', location_name: 'Paris',
});
testDb.prepare('UPDATE journey_entries SET location_lat = ?, location_lng = ? WHERE id = ?').run(48.8566, 2.3522, entry.id);
const { token } = svc.createOrUpdateJourneyShareLink(journey.id, user.id, {
const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {
share_timeline: false, share_gallery: false, share_map: true,
});
@@ -602,7 +603,7 @@ describe('getPublicJourney', () => {
testDb.prepare('UPDATE trek_photos SET lat = ?, lng = ?, taken_at = ? WHERE id = ?')
.run(48.8584, 2.2945, '2026-05-01T10:00:00Z', trekId);
const { token } = svc.createOrUpdateJourneyShareLink(journey.id, user.id, {
const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {
share_timeline: true, share_gallery: true, share_map: false,
});
@@ -629,7 +630,7 @@ describe('getPublicJourney', () => {
testDb.prepare('UPDATE trek_photos SET lat = ?, lng = ? WHERE id = ?')
.run(48.8584, 2.2945, trekId);
const { token } = svc.createOrUpdateJourneyShareLink(journey.id, user.id, {
const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {
share_timeline: true, share_gallery: true, share_map: true,
});
@@ -645,7 +646,7 @@ describe('getPublicJourney', () => {
type: 'entry', title: 'Day 1', story: 'notes', entry_date: '2026-05-01',
});
insertJourneyPhoto(entry.id, { ownerId: user.id });
const { token } = svc.createOrUpdateJourneyShareLink(journey.id, user.id, {
const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {
share_timeline: true, share_gallery: false, share_map: true,
});
@@ -671,7 +672,7 @@ describe('getPublicJourney', () => {
insertJourneyPhoto(day1.id, { filePath: '/photos/day1.jpg' });
testDb.prepare('UPDATE trek_photos SET taken_at = ? WHERE id = ?').run('2026-05-02T16:00:00.000Z', late);
const { token } = svc.createOrUpdateJourneyShareLink(journey.id, user.id, {
const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {
share_timeline: true, share_gallery: true, share_map: true,
});
@@ -682,7 +683,7 @@ describe('getPublicJourney', () => {
it('JOURNEY-SHARE-030: cartoApiKey resolves owner setting → admin instance default → empty (#2054)', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const { token } = svc.createOrUpdateJourneyShareLink(journey.id, user.id, { share_map: true });
const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, { share_map: true });
expect((await svc.getPublicJourney(token))!.cartoApiKey).toBe('');
testDb.prepare("INSERT INTO app_settings (key, value) VALUES ('default_user_setting_carto_api_key', 'instance-key')").run();
@@ -66,9 +66,10 @@ import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import { TrekPhotosRepository } from '../../../src/nest/photos/trek-photos.repository';
import { JourneyDomainService } from '../../../src/nest/journey/journey-domain.service';
import { db as dbConn } from '../../../src/db/database';
import { createTestUnitOfWork } from '../../helpers/test-uow';
const dbs = new DatabaseService(dbConn);
const svc = new JourneyDomainService(dbs, new RealtimeService(), new TrekPhotosRepository(dbs));
let svc: JourneyDomainService;
/** The factory has no coordinate fields, and a route is made of coordinates. */
function placeEntry(
@@ -85,9 +86,10 @@ function placeEntry(
return entry;
}
beforeAll(() => {
beforeAll(async () => {
createTables(testDb);
runMigrations(testDb);
svc = new JourneyDomainService(dbs, new RealtimeService(), new TrekPhotosRepository(dbs), await createTestUnitOfWork(testDb));
});
beforeEach(() => {
@@ -100,24 +102,24 @@ afterAll(() => {
});
describe('journeyStats access', () => {
it('is null for a journey the user cannot see', () => {
it('is null for a journey the user cannot see', async () => {
const { user: owner } = createUser(testDb);
const { user: stranger } = createUser(testDb);
const journey = createJourney(testDb, owner.id);
expect(svc.journeyStats(journey.id, stranger.id)).toBeNull();
expect(await svc.journeyStats(journey.id, stranger.id)).toBeNull();
});
it('is null for a journey that does not exist', () => {
it('is null for a journey that does not exist', async () => {
const { user } = createUser(testDb);
expect(svc.journeyStats(999_999, user.id)).toBeNull();
expect(await svc.journeyStats(999_999, user.id)).toBeNull();
});
it('answers for the owner', () => {
it('answers for the owner', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const stats = svc.journeyStats(journey.id, user.id);
const stats = await svc.journeyStats(journey.id, user.id);
expect(stats).not.toBeNull();
expect(stats!.journeyId).toBe(journey.id);
@@ -125,13 +127,13 @@ describe('journeyStats access', () => {
});
describe('journeyStats route', () => {
it('builds the route from the entries when they carry coordinates', () => {
it('builds the route from the entries when they carry coordinates', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
placeEntry(journey.id, user.id, 64.14, -21.94, { title: 'Reykjavík', entry_date: '2026-06-02' });
placeEntry(journey.id, user.id, 65.68, -18.12, { title: 'Akureyri', entry_date: '2026-06-06' });
const stats = svc.journeyStats(journey.id, user.id)!;
const stats = (await svc.journeyStats(journey.id, user.id))!;
expect(stats.points.map(p => p.label)).toEqual(['Reykjavík', 'Akureyri']);
expect(stats.distance).toBeGreaterThan(240_000);
@@ -139,24 +141,24 @@ describe('journeyStats route', () => {
expect(stats.steps).toBe(2);
});
it('orders the route by entry date, not by insertion', () => {
it('orders the route by entry date, not by insertion', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
placeEntry(journey.id, user.id, 65.68, -18.12, { title: 'second', entry_date: '2026-06-06' });
placeEntry(journey.id, user.id, 64.14, -21.94, { title: 'first', entry_date: '2026-06-02' });
const stats = svc.journeyStats(journey.id, user.id)!;
const stats = (await svc.journeyStats(journey.id, user.id))!;
expect(stats.points.map(p => p.label)).toEqual(['first', 'second']);
});
it('skips entries without coordinates but still counts them as steps', () => {
it('skips entries without coordinates but still counts them as steps', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
placeEntry(journey.id, user.id, 64.14, -21.94, { entry_date: '2026-06-02' });
createJourneyEntry(testDb, journey.id, user.id, { title: 'no place', entry_date: '2026-06-03' });
const stats = svc.journeyStats(journey.id, user.id)!;
const stats = (await svc.journeyStats(journey.id, user.id))!;
expect(stats.points).toHaveLength(1);
expect(stats.steps).toBe(2);
@@ -166,7 +168,7 @@ describe('journeyStats route', () => {
* The fallback that makes the feature work at all for the common case: a
* journey built by adding trips, before anyone has written a word.
*/
it('falls back to the trip places when no entry has coordinates', () => {
it('falls back to the trip places when no entry has coordinates', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const trip = createTrip(testDb, user.id);
@@ -179,13 +181,13 @@ describe('journeyStats route', () => {
createDayAssignment(testDb, day2.id, b.id);
createDayAssignment(testDb, day1.id, a.id);
const stats = svc.journeyStats(journey.id, user.id)!;
const stats = (await svc.journeyStats(journey.id, user.id))!;
expect(stats.points.map(p => p.label)).toEqual(['Hallgrímskirkja', 'Goðafoss']);
expect(stats.days).toBe(3);
});
it('prefers the entries over the trip places rather than mixing them', () => {
it('prefers the entries over the trip places rather than mixing them', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const trip = createTrip(testDb, user.id);
@@ -193,7 +195,7 @@ describe('journeyStats route', () => {
createPlace(testDb, trip.id, { name: 'a place', lat: 48.85, lng: 2.35 });
placeEntry(journey.id, user.id, 64.14, -21.94, { title: 'an entry', entry_date: '2026-06-02' });
const stats = svc.journeyStats(journey.id, user.id)!;
const stats = (await svc.journeyStats(journey.id, user.id))!;
expect(stats.points.map(p => p.label)).toEqual(['an entry']);
});
@@ -204,7 +206,7 @@ describe('journeyStats route', () => {
* journey two extra legs of zero length — harmless — plus two extra stops in
* the middle of the route, which is not.
*/
it('visits a place assigned to several days only once', () => {
it('visits a place assigned to several days only once', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const trip = createTrip(testDb, user.id);
@@ -215,13 +217,13 @@ describe('journeyStats route', () => {
createDayAssignment(testDb, createDay(testDb, trip.id, { date }).id, hotel.id);
}
const stats = svc.journeyStats(journey.id, user.id)!;
const stats = (await svc.journeyStats(journey.id, user.id))!;
expect(stats.points.filter(p => p.label === 'Hotel')).toHaveLength(1);
expect(stats.places).toBe(1);
});
it('puts unscheduled places after the scheduled ones', () => {
it('puts unscheduled places after the scheduled ones', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const trip = createTrip(testDb, user.id);
@@ -232,12 +234,12 @@ describe('journeyStats route', () => {
createDayAssignment(testDb, createDay(testDb, trip.id, { date: '2026-06-02' }).id, planned.id);
expect(loose.id).toBeGreaterThan(0);
const stats = svc.journeyStats(journey.id, user.id)!;
const stats = (await svc.journeyStats(journey.id, user.id))!;
expect(stats.points.map(p => p.label)).toEqual(['scheduled', 'unscheduled']);
});
it('counts places across every trip on the journey', () => {
it('counts places across every trip on the journey', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const one = createTrip(testDb, user.id);
@@ -248,18 +250,18 @@ describe('journeyStats route', () => {
createPlace(testDb, two.id, { lat: 52.52, lng: 13.4 });
createPlace(testDb, two.id, { lat: 50.11, lng: 8.68 });
expect(svc.journeyStats(journey.id, user.id)!.places).toBe(3);
expect((await svc.journeyStats(journey.id, user.id))!.places).toBe(3);
});
});
describe('journeyStats countries', () => {
it('resolves each stop to a country and names it', () => {
it('resolves each stop to a country and names it', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
placeEntry(journey.id, user.id, 64.14, -21.94, { entry_date: '2026-06-02' });
placeEntry(journey.id, user.id, 52.52, 13.4, { entry_date: '2026-06-20' });
const stats = svc.journeyStats(journey.id, user.id)!;
const stats = (await svc.journeyStats(journey.id, user.id))!;
expect(stats.countries.map(c => c.code)).toEqual(['IS', 'DE']);
expect(stats.countries[0].name).toBe('Iceland');
@@ -271,7 +273,7 @@ describe('journeyStats countries', () => {
* of repeating a point-in-polygon test is the difference between a query and
* a boundary index.
*/
it('prefers the place_regions cache over recomputing a place country', () => {
it('prefers the place_regions cache over recomputing a place country', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const trip = createTrip(testDb, user.id);
@@ -281,7 +283,7 @@ describe('journeyStats countries', () => {
.prepare('INSERT INTO place_regions (place_id, country_code, region_code, region_name) VALUES (?, ?, ?, ?)')
.run(place.id, 'fr', 'FR-75', 'Paris');
const stats = svc.journeyStats(journey.id, user.id)!;
const stats = (await svc.journeyStats(journey.id, user.id))!;
// The cached answer wins even though the coordinates say Iceland, and the
// expensive lookup is never reached for that place.
@@ -289,12 +291,12 @@ describe('journeyStats countries', () => {
expect(countryCalls).toHaveLength(0);
});
it('leaves a stop with no country out of the list rather than inventing one', () => {
it('leaves a stop with no country out of the list rather than inventing one', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
placeEntry(journey.id, user.id, -33.86, 151.2, { entry_date: '2026-06-02' });
const stats = svc.journeyStats(journey.id, user.id)!;
const stats = (await svc.journeyStats(journey.id, user.id))!;
expect(stats.countries).toEqual([]);
expect(stats.points).toHaveLength(1);
@@ -303,7 +305,7 @@ describe('journeyStats countries', () => {
});
describe('journeyStats totals', () => {
it('counts the gallery photographs', () => {
it('counts the gallery photographs', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const photo = testDb
@@ -313,28 +315,28 @@ describe('journeyStats totals', () => {
.prepare('INSERT INTO journey_photos (journey_id, photo_id, sort_order, created_at) VALUES (?, ?, 0, ?)')
.run(journey.id, photo.lastInsertRowid, Date.now());
expect(svc.journeyStats(journey.id, user.id)!.photos).toBe(1);
expect((await svc.journeyStats(journey.id, user.id))!.photos).toBe(1);
});
it('falls back to the trip dates when the entries carry none', () => {
it('falls back to the trip dates when the entries carry none', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const trip = createTrip(testDb, user.id, { start_date: '2026-06-01', end_date: '2026-06-10' });
linkTripToJourney(testDb, journey.id, trip.id);
createPlace(testDb, trip.id, { lat: 64.14, lng: -21.94 });
const stats = svc.journeyStats(journey.id, user.id)!;
const stats = (await svc.journeyStats(journey.id, user.id))!;
expect(stats.start).toBe('2026-06-01');
expect(stats.end).toBe('2026-06-10');
expect(stats.days).toBe(10);
});
it('is all zeroes for an empty journey rather than failing', () => {
it('is all zeroes for an empty journey rather than failing', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const stats = svc.journeyStats(journey.id, user.id)!;
const stats = (await svc.journeyStats(journey.id, user.id))!;
expect(stats.distance).toBe(0);
expect(stats.days).toBe(0);
@@ -345,7 +347,7 @@ describe('journeyStats totals', () => {
expect(stats.points).toEqual([]);
});
it('answers for a contributor, not only the owner', () => {
it('answers for a contributor, not only the owner', async () => {
const { user: owner } = createUser(testDb);
const { user: helper } = createUser(testDb);
const journey = createJourney(testDb, owner.id);
@@ -353,7 +355,7 @@ describe('journeyStats totals', () => {
.prepare('INSERT INTO journey_contributors (journey_id, user_id, role, added_at) VALUES (?, ?, ?, ?)')
.run(journey.id, helper.id, 'editor', Date.now());
expect(svc.journeyStats(journey.id, helper.id)).not.toBeNull();
expect(await svc.journeyStats(journey.id, helper.id)).not.toBeNull();
});
});
@@ -364,14 +366,14 @@ describe('journeyStats totals', () => {
* switched back on.
*/
describe('journeyStats excluded stops', () => {
it('leaves a switched-off entry out of the route, the distance and the countries', () => {
it('leaves a switched-off entry out of the route, the distance and the countries', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
placeEntry(journey.id, user.id, 52.52, 13.4, { title: 'Berlin, the airport', entry_date: '2026-06-01', stats_excluded: 1 });
placeEntry(journey.id, user.id, 64.14, -21.94, { title: 'Reykjavík', entry_date: '2026-06-02' });
placeEntry(journey.id, user.id, 65.68, -18.12, { title: 'Akureyri', entry_date: '2026-06-06' });
const stats = svc.journeyStats(journey.id, user.id)!;
const stats = (await svc.journeyStats(journey.id, user.id))!;
expect(stats.points.map(p => p.label)).toEqual(['Reykjavík', 'Akureyri']);
// Reykjavík to Akureyri and nothing else; the leg in from Berlin is gone.
@@ -381,49 +383,49 @@ describe('journeyStats excluded stops', () => {
expect(stats.days).toBe(5);
});
it('names the switched-off stop under excluded so it can be switched back on', () => {
it('names the switched-off stop under excluded so it can be switched back on', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const airport = placeEntry(journey.id, user.id, 63.98, -22.62, { title: 'Keflavík', entry_date: '2026-06-01', stats_excluded: 1 });
placeEntry(journey.id, user.id, 64.14, -21.94, { title: 'Reykjavík', entry_date: '2026-06-02' });
const stats = svc.journeyStats(journey.id, user.id)!;
const stats = (await svc.journeyStats(journey.id, user.id))!;
expect(stats.excluded).toEqual([{ entryId: airport.id, label: 'Keflavík', date: '2026-06-01' }]);
});
it('does not count a switched-off entry as a step', () => {
it('does not count a switched-off entry as a step', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
placeEntry(journey.id, user.id, 63.98, -22.62, { entry_date: '2026-06-01', stats_excluded: 1 });
placeEntry(journey.id, user.id, 64.14, -21.94, { entry_date: '2026-06-02' });
expect(svc.journeyStats(journey.id, user.id)!.steps).toBe(1);
expect((await svc.journeyStats(journey.id, user.id))!.steps).toBe(1);
});
/* An entry without a place was never a stop, so there is nothing to offer back. */
it('lists nothing under excluded for a switched-off entry without coordinates', () => {
it('lists nothing under excluded for a switched-off entry without coordinates', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
createJourneyEntry(testDb, journey.id, user.id, { title: 'a thought', entry_date: '2026-06-03', stats_excluded: 1 });
placeEntry(journey.id, user.id, 64.14, -21.94, { entry_date: '2026-06-02' });
const stats = svc.journeyStats(journey.id, user.id)!;
const stats = (await svc.journeyStats(journey.id, user.id))!;
expect(stats.excluded).toEqual([]);
expect(stats.steps).toBe(1);
});
it('carries the entry on every stop read from the entries', () => {
it('carries the entry on every stop read from the entries', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const a = placeEntry(journey.id, user.id, 64.14, -21.94, { entry_date: '2026-06-02' });
const b = placeEntry(journey.id, user.id, 65.68, -18.12, { entry_date: '2026-06-06' });
expect(svc.journeyStats(journey.id, user.id)!.points.map(p => p.entryId)).toEqual([a.id, b.id]);
expect((await svc.journeyStats(journey.id, user.id))!.points.map(p => p.entryId)).toEqual([a.id, b.id]);
});
it('drops the place behind a switched-off skeleton from the place count', () => {
it('drops the place behind a switched-off skeleton from the place count', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const trip = createTrip(testDb, user.id);
@@ -432,12 +434,12 @@ describe('journeyStats excluded stops', () => {
const town = createPlace(testDb, trip.id, { name: 'Vík', lat: 63.42, lng: -19.01 });
createDayAssignment(testDb, createDay(testDb, trip.id, { date: '2026-06-01' }).id, airport.id);
createDayAssignment(testDb, createDay(testDb, trip.id, { date: '2026-06-02' }).id, town.id);
svc.syncTripPlaces(journey.id, trip.id, user.id);
await svc.syncTripPlaces(journey.id, trip.id, user.id);
testDb
.prepare('UPDATE journey_entries SET stats_excluded = 1 WHERE journey_id = ? AND source_place_id = ?')
.run(journey.id, airport.id);
const stats = svc.journeyStats(journey.id, user.id)!;
const stats = (await svc.journeyStats(journey.id, user.id))!;
// The town's skeleton still draws the route, so this is the entries path.
expect(stats.points.map(p => p.label)).toEqual(['Vík']);
@@ -450,7 +452,7 @@ describe('journeyStats excluded stops', () => {
* from a trip place; switching it off and then drawing the place it came
* from would put the same stop straight back on the map by its other name.
*/
it('leaves the place behind a switched-off skeleton out of the fallback route', () => {
it('leaves the place behind a switched-off skeleton out of the fallback route', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const trip = createTrip(testDb, user.id);
@@ -460,7 +462,7 @@ describe('journeyStats excluded stops', () => {
// Only the airport is on a day, so only the airport gets a skeleton; the
// town stays a bare trip place that the fallback is there to draw.
createDayAssignment(testDb, createDay(testDb, trip.id, { date: '2026-06-01' }).id, airport.id);
svc.syncTripPlaces(journey.id, trip.id, user.id);
await svc.syncTripPlaces(journey.id, trip.id, user.id);
// Switched off, and its point cleared by hand afterwards, which is what
// sends the journey down the fallback while the skeleton still names the
// place it came from.
@@ -472,7 +474,7 @@ describe('journeyStats excluded stops', () => {
`)
.run(journey.id, airport.id);
const stats = svc.journeyStats(journey.id, user.id)!;
const stats = (await svc.journeyStats(journey.id, user.id))!;
expect(stats.points.map(p => p.label)).toEqual(['Vík']);
expect(stats.points[0].entryId).toBeNull();
@@ -484,7 +486,7 @@ describe('journeyStats excluded stops', () => {
* The pair of cases that decide which source a journey reads from, now that
* a stop can be taken out of one of them.
*/
it('draws no route at all when every stop of the journal is switched off', () => {
it('draws no route at all when every stop of the journal is switched off', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const trip = createTrip(testDb, user.id);
@@ -492,14 +494,14 @@ describe('journeyStats excluded stops', () => {
createPlace(testDb, trip.id, { name: 'a trip place', lat: 48.85, lng: 2.35 });
placeEntry(journey.id, user.id, 52.52, 13.4, { title: 'Berlin, the airport', entry_date: '2026-06-01', stats_excluded: 1 });
const stats = svc.journeyStats(journey.id, user.id)!;
const stats = (await svc.journeyStats(journey.id, user.id))!;
expect(stats.points).toEqual([]);
expect(stats.distance).toBe(0);
expect(stats.excluded.map(s => s.label)).toEqual(['Berlin, the airport']);
});
it('still falls back to the trip places for a journal that never had a point', () => {
it('still falls back to the trip places for a journal that never had a point', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const trip = createTrip(testDb, user.id);
@@ -507,7 +509,7 @@ describe('journeyStats excluded stops', () => {
createPlace(testDb, trip.id, { name: 'a trip place', lat: 48.85, lng: 2.35 });
createJourneyEntry(testDb, journey.id, user.id, { title: 'written, not placed', stats_excluded: 1 });
const stats = svc.journeyStats(journey.id, user.id)!;
const stats = (await svc.journeyStats(journey.id, user.id))!;
expect(stats.points.map(p => p.label)).toEqual(['a trip place']);
});
@@ -46,14 +46,6 @@ function ctl(service: JourneyService, books: Partial<JourneyBookService> = {}):
return new JourneyController(service, storageStub, books as JourneyBookService, captureBackfillStub);
}
function thrown(fn: () => unknown): { status: number; body: unknown } {
try { fn(); } catch (err) {
expect(err).toBeInstanceOf(HttpException);
const e = err as HttpException;
return { status: e.getStatus(), body: e.getResponse() };
}
throw new Error('expected throw');
}
async function thrownAsync(fn: () => Promise<unknown>): Promise<{ status: number; body: unknown }> {
try { await fn(); } catch (err) {
expect(err).toBeInstanceOf(HttpException);
@@ -66,24 +58,24 @@ async function thrownAsync(fn: () => Promise<unknown>): Promise<{ status: number
beforeEach(() => vi.clearAllMocks());
describe('JourneyController', () => {
it('GET / lists; POST / 400 without title, else creates', () => {
expect(ctl(svc({ listJourneys: vi.fn().mockReturnValue([{ id: 1 }]) } as Partial<JourneyService>)).list(user)).toEqual({ journeys: [{ id: 1 }] });
expect(thrown(() => ctl(svc()).create(user, { title: ' ' }))).toEqual({ status: 400, body: { error: 'Title is required' } });
it('GET / lists; POST / 400 without title, else creates', async () => {
expect(await ctl(svc({ listJourneys: vi.fn().mockReturnValue([{ id: 1 }]) } as Partial<JourneyService>)).list(user)).toEqual({ journeys: [{ id: 1 }] });
expect(await thrownAsync(() => ctl(svc()).create(user, { title: ' ' }))).toEqual({ status: 400, body: { error: 'Title is required' } });
const createJourney = vi.fn().mockReturnValue({ id: 9 });
expect(ctl(svc({ createJourney } as Partial<JourneyService>)).create(user, { title: ' Trip ', trip_ids: [1, '2'] })).toEqual({ id: 9 });
expect(await ctl(svc({ createJourney } as Partial<JourneyService>)).create(user, { title: ' Trip ', trip_ids: [1, '2'] })).toEqual({ id: 9 });
expect(createJourney).toHaveBeenCalledWith(1, { title: 'Trip', subtitle: undefined, trip_ids: [1, 2] });
});
it('GET /suggestions + /available-trips', () => {
expect(ctl(svc({ getSuggestions: vi.fn().mockReturnValue([{ id: 1 }]) } as Partial<JourneyService>)).suggestions(user)).toEqual({ trips: [{ id: 1 }] });
expect(ctl(svc({ listUserTrips: vi.fn().mockReturnValue([{ id: 2 }]) } as Partial<JourneyService>)).availableTrips(user)).toEqual({ trips: [{ id: 2 }] });
it('GET /suggestions + /available-trips', async () => {
expect(await ctl(svc({ getSuggestions: vi.fn().mockReturnValue([{ id: 1 }]) } as Partial<JourneyService>)).suggestions(user)).toEqual({ trips: [{ id: 1 }] });
expect(await ctl(svc({ listUserTrips: vi.fn().mockReturnValue([{ id: 2 }]) } as Partial<JourneyService>)).availableTrips(user)).toEqual({ trips: [{ id: 2 }] });
});
it('PATCH/DELETE entries map 404', () => {
expect(thrown(() => ctl(svc({ updateEntry: vi.fn().mockReturnValue(null) } as Partial<JourneyService>)).updateEntry(user, '3', {}))).toEqual({ status: 404, body: { error: 'Entry not found' } });
expect(ctl(svc({ updateEntry: vi.fn().mockReturnValue({ id: 3 }) } as Partial<JourneyService>)).updateEntry(user, '3', { title: 'x' })).toEqual({ id: 3 });
expect(thrown(() => ctl(svc({ deleteEntry: vi.fn().mockReturnValue(false) } as Partial<JourneyService>)).deleteEntry(user, '3'))).toEqual({ status: 404, body: { error: 'Entry not found' } });
expect(ctl(svc({ deleteEntry: vi.fn().mockReturnValue(true) } as Partial<JourneyService>)).deleteEntry(user, '3')).toEqual({ success: true });
it('PATCH/DELETE entries map 404', async () => {
expect(await thrownAsync(() => ctl(svc({ updateEntry: vi.fn().mockReturnValue(null) } as Partial<JourneyService>)).updateEntry(user, '3', {}))).toEqual({ status: 404, body: { error: 'Entry not found' } });
expect(await ctl(svc({ updateEntry: vi.fn().mockReturnValue({ id: 3 }) } as Partial<JourneyService>)).updateEntry(user, '3', { title: 'x' })).toEqual({ id: 3 });
expect(await thrownAsync(() => ctl(svc({ deleteEntry: vi.fn().mockReturnValue(false) } as Partial<JourneyService>)).deleteEntry(user, '3'))).toEqual({ status: 404, body: { error: 'Entry not found' } });
expect(await ctl(svc({ deleteEntry: vi.fn().mockReturnValue(true) } as Partial<JourneyService>)).deleteEntry(user, '3')).toEqual({ success: true });
});
it('provider-photos: batch, single 400/403, success', async () => {
@@ -93,19 +85,19 @@ describe('JourneyController', () => {
expect(await thrownAsync(() => ctl(svc({ addProviderPhoto: vi.fn().mockReturnValue(null) } as Partial<JourneyService>)).providerPhotos(user, '3', { provider: 'immich', asset_id: 'a' }))).toEqual({ status: 403, body: { error: 'Not allowed or duplicate' } });
});
it('link-photo: 400 without id (accepts legacy photo_id), 403, success', () => {
expect(thrown(() => ctl(svc()).linkPhoto(user, '3', {}))).toEqual({ status: 400, body: { error: 'journey_photo_id required' } });
it('link-photo: 400 without id (accepts legacy photo_id), 403, success', async () => {
expect(await thrownAsync(() => ctl(svc()).linkPhoto(user, '3', {}))).toEqual({ status: 400, body: { error: 'journey_photo_id required' } });
const linkPhotoToEntry = vi.fn().mockReturnValue({ id: 5 });
const c = ctl(svc({ linkPhotoToEntry } as Partial<JourneyService>));
expect(c.linkPhoto(user, '3', { photo_id: 5 })).toEqual({ id: 5 });
expect(await c.linkPhoto(user, '3', { photo_id: 5 })).toEqual({ id: 5 });
expect(linkPhotoToEntry).toHaveBeenCalledWith(3, 5, 1);
// accepts the canonical journey_photo_id, 403 when the service refuses
expect(thrown(() => ctl(svc({ linkPhotoToEntry: vi.fn().mockReturnValue(null) } as Partial<JourneyService>)).linkPhoto(user, '3', { journey_photo_id: 9 }))).toEqual({ status: 403, body: { error: 'Not allowed' } });
expect(await thrownAsync(() => ctl(svc({ linkPhotoToEntry: vi.fn().mockReturnValue(null) } as Partial<JourneyService>)).linkPhoto(user, '3', { journey_photo_id: 9 }))).toEqual({ status: 403, body: { error: 'Not allowed' } });
});
it('unlink photo (204) maps 404; delete photo 404 then removes the object', async () => {
expect(thrown(() => ctl(svc({ unlinkPhotoFromEntry: vi.fn().mockReturnValue(false) } as Partial<JourneyService>)).unlinkPhoto(user, '3', '7'))).toEqual({ status: 404, body: { error: 'Not found or not allowed' } });
expect(ctl(svc({ unlinkPhotoFromEntry: vi.fn().mockReturnValue(true) } as Partial<JourneyService>)).unlinkPhoto(user, '3', '7')).toBeUndefined();
expect(await thrownAsync(() => ctl(svc({ unlinkPhotoFromEntry: vi.fn().mockReturnValue(false) } as Partial<JourneyService>)).unlinkPhoto(user, '3', '7'))).toEqual({ status: 404, body: { error: 'Not found or not allowed' } });
expect(await ctl(svc({ unlinkPhotoFromEntry: vi.fn().mockReturnValue(true) } as Partial<JourneyService>)).unlinkPhoto(user, '3', '7')).toBeUndefined();
expect(await thrownAsync(() => ctl(svc({ deletePhoto: vi.fn().mockReturnValue(null) } as Partial<JourneyService>)).deletePhoto(user, '7'))).toEqual({ status: 404, body: { error: 'Photo not found' } });
expect(await ctl(svc({ deletePhoto: vi.fn().mockReturnValue({ id: 7, file_path: null }) } as Partial<JourneyService>)).deletePhoto(user, '7')).toEqual({ success: true });
});
@@ -154,54 +146,54 @@ describe('JourneyController', () => {
expect(eOne).toHaveBeenCalledWith(4, 1, 'immich', 'y', undefined, undefined, 'video');
});
it('GET/PATCH/DELETE /:id map 404', () => {
expect(thrown(() => ctl(svc({ getJourneyFull: vi.fn().mockReturnValue(null) } as Partial<JourneyService>)).get(user, '9'))).toEqual({ status: 404, body: { error: 'Journey not found' } });
expect(ctl(svc({ getJourneyFull: vi.fn().mockReturnValue({ id: 9 }) } as Partial<JourneyService>)).get(user, '9')).toEqual({ id: 9 });
expect(thrown(() => ctl(svc({ updateJourney: vi.fn().mockReturnValue(null) } as Partial<JourneyService>)).update(user, '9', {}))).toEqual({ status: 404, body: { error: 'Journey not found' } });
expect(thrown(() => ctl(svc({ deleteJourney: vi.fn().mockReturnValue(false) } as Partial<JourneyService>)).remove(user, '9'))).toEqual({ status: 404, body: { error: 'Journey not found' } });
it('GET/PATCH/DELETE /:id map 404', async () => {
expect(await thrownAsync(() => ctl(svc({ getJourneyFull: vi.fn().mockReturnValue(null) } as Partial<JourneyService>)).get(user, '9'))).toEqual({ status: 404, body: { error: 'Journey not found' } });
expect(await ctl(svc({ getJourneyFull: vi.fn().mockReturnValue({ id: 9 }) } as Partial<JourneyService>)).get(user, '9')).toEqual({ id: 9 });
expect(await thrownAsync(() => ctl(svc({ updateJourney: vi.fn().mockReturnValue(null) } as Partial<JourneyService>)).update(user, '9', {}))).toEqual({ status: 404, body: { error: 'Journey not found' } });
expect(await thrownAsync(() => ctl(svc({ deleteJourney: vi.fn().mockReturnValue(false) } as Partial<JourneyService>)).remove(user, '9'))).toEqual({ status: 404, body: { error: 'Journey not found' } });
});
it('trips: POST 400 without trip_id / 403, DELETE 403', () => {
expect(thrown(() => ctl(svc()).addTrip(user, '9', {}))).toEqual({ status: 400, body: { error: 'trip_id required' } });
expect(thrown(() => ctl(svc({ addTripToJourney: vi.fn().mockReturnValue(false) } as Partial<JourneyService>)).addTrip(user, '9', { trip_id: 2 }))).toEqual({ status: 403, body: { error: 'Not allowed' } });
expect(ctl(svc({ addTripToJourney: vi.fn().mockReturnValue(true) } as Partial<JourneyService>)).addTrip(user, '9', { trip_id: 2 })).toEqual({ success: true });
expect(thrown(() => ctl(svc({ removeTripFromJourney: vi.fn().mockReturnValue(false) } as Partial<JourneyService>)).removeTrip(user, '9', '2'))).toEqual({ status: 403, body: { error: 'Not allowed' } });
it('trips: POST 400 without trip_id / 403, DELETE 403', async () => {
expect(await thrownAsync(() => ctl(svc()).addTrip(user, '9', {}))).toEqual({ status: 400, body: { error: 'trip_id required' } });
expect(await thrownAsync(() => ctl(svc({ addTripToJourney: vi.fn().mockReturnValue(false) } as Partial<JourneyService>)).addTrip(user, '9', { trip_id: 2 }))).toEqual({ status: 403, body: { error: 'Not allowed' } });
expect(await ctl(svc({ addTripToJourney: vi.fn().mockReturnValue(true) } as Partial<JourneyService>)).addTrip(user, '9', { trip_id: 2 })).toEqual({ success: true });
expect(await thrownAsync(() => ctl(svc({ removeTripFromJourney: vi.fn().mockReturnValue(false) } as Partial<JourneyService>)).removeTrip(user, '9', '2'))).toEqual({ status: 403, body: { error: 'Not allowed' } });
});
it('entries under journey: list 404, create 400/404, reorder 400/403', () => {
expect(thrown(() => ctl(svc({ listEntries: vi.fn().mockReturnValue(null) } as Partial<JourneyService>)).listEntries(user, '9'))).toEqual({ status: 404, body: { error: 'Journey not found' } });
expect(ctl(svc({ listEntries: vi.fn().mockReturnValue([{ id: 1 }]) } as Partial<JourneyService>)).listEntries(user, '9')).toEqual({ entries: [{ id: 1 }] });
expect(thrown(() => ctl(svc()).createEntry(user, '9', {}))).toEqual({ status: 400, body: { error: 'entry_date is required' } });
expect(thrown(() => ctl(svc({ createEntry: vi.fn().mockReturnValue(null) } as Partial<JourneyService>)).createEntry(user, '9', { entry_date: '2026-01-01' }))).toEqual({ status: 404, body: { error: 'Journey not found' } });
expect(thrown(() => ctl(svc()).reorderEntries(user, '9', { orderedIds: 'no' }))).toEqual({ status: 400, body: { error: 'orderedIds must be an array of numbers' } });
expect(thrown(() => ctl(svc({ reorderEntries: vi.fn().mockReturnValue(false) } as Partial<JourneyService>)).reorderEntries(user, '9', { orderedIds: [1, 2] }))).toEqual({ status: 403, body: { error: 'Not allowed' } });
it('entries under journey: list 404, create 400/404, reorder 400/403', async () => {
expect(await thrownAsync(() => ctl(svc({ listEntries: vi.fn().mockReturnValue(null) } as Partial<JourneyService>)).listEntries(user, '9'))).toEqual({ status: 404, body: { error: 'Journey not found' } });
expect(await ctl(svc({ listEntries: vi.fn().mockReturnValue([{ id: 1 }]) } as Partial<JourneyService>)).listEntries(user, '9')).toEqual({ entries: [{ id: 1 }] });
expect(await thrownAsync(() => ctl(svc()).createEntry(user, '9', {}))).toEqual({ status: 400, body: { error: 'entry_date is required' } });
expect(await thrownAsync(() => ctl(svc({ createEntry: vi.fn().mockReturnValue(null) } as Partial<JourneyService>)).createEntry(user, '9', { entry_date: '2026-01-01' }))).toEqual({ status: 404, body: { error: 'Journey not found' } });
expect(await thrownAsync(() => ctl(svc()).reorderEntries(user, '9', { orderedIds: 'no' }))).toEqual({ status: 400, body: { error: 'orderedIds must be an array of numbers' } });
expect(await thrownAsync(() => ctl(svc({ reorderEntries: vi.fn().mockReturnValue(false) } as Partial<JourneyService>)).reorderEntries(user, '9', { orderedIds: [1, 2] }))).toEqual({ status: 403, body: { error: 'Not allowed' } });
});
it('contributors: add 400/403, update 403, remove 403', () => {
expect(thrown(() => ctl(svc()).addContributor(user, '9', {}))).toEqual({ status: 400, body: { error: 'user_id required' } });
expect(thrown(() => ctl(svc({ addContributor: vi.fn().mockReturnValue(false) } as Partial<JourneyService>)).addContributor(user, '9', { user_id: 2 }))).toEqual({ status: 403, body: { error: 'Not allowed' } });
expect(ctl(svc({ addContributor: vi.fn().mockReturnValue(true) } as Partial<JourneyService>)).addContributor(user, '9', { user_id: 2 })).toEqual({ success: true });
expect(thrown(() => ctl(svc({ updateContributorRole: vi.fn().mockReturnValue(false) } as Partial<JourneyService>)).updateContributor(user, '9', '2', { role: 'editor' }))).toEqual({ status: 403, body: { error: 'Not allowed' } });
expect(thrown(() => ctl(svc({ removeContributor: vi.fn().mockReturnValue(false) } as Partial<JourneyService>)).removeContributor(user, '9', '2'))).toEqual({ status: 403, body: { error: 'Not allowed' } });
it('contributors: add 400/403, update 403, remove 403', async () => {
expect(await thrownAsync(() => ctl(svc()).addContributor(user, '9', {}))).toEqual({ status: 400, body: { error: 'user_id required' } });
expect(await thrownAsync(() => ctl(svc({ addContributor: vi.fn().mockReturnValue(false) } as Partial<JourneyService>)).addContributor(user, '9', { user_id: 2 }))).toEqual({ status: 403, body: { error: 'Not allowed' } });
expect(await ctl(svc({ addContributor: vi.fn().mockReturnValue(true) } as Partial<JourneyService>)).addContributor(user, '9', { user_id: 2 })).toEqual({ success: true });
expect(await thrownAsync(() => ctl(svc({ updateContributorRole: vi.fn().mockReturnValue(false) } as Partial<JourneyService>)).updateContributor(user, '9', '2', { role: 'editor' }))).toEqual({ status: 403, body: { error: 'Not allowed' } });
expect(await thrownAsync(() => ctl(svc({ removeContributor: vi.fn().mockReturnValue(false) } as Partial<JourneyService>)).removeContributor(user, '9', '2'))).toEqual({ status: 403, body: { error: 'Not allowed' } });
});
it('preferences 403, share-link get/set/delete', () => {
expect(thrown(() => ctl(svc({ updateJourneyPreferences: vi.fn().mockReturnValue(null) } as Partial<JourneyService>)).preferences(user, '9', {}))).toEqual({ status: 403, body: { error: 'Not allowed' } });
expect(ctl(svc({ getJourneyShareLink: vi.fn().mockReturnValue({ allowed: true, link: { token: 'abc' } }) } as Partial<JourneyService>)).getShareLink(user, '9')).toEqual({ link: { token: 'abc' } });
it('preferences 403, share-link get/set/delete', async () => {
expect(await thrownAsync(() => ctl(svc({ updateJourneyPreferences: vi.fn().mockReturnValue(null) } as Partial<JourneyService>)).preferences(user, '9', {}))).toEqual({ status: 403, body: { error: 'Not allowed' } });
expect(await ctl(svc({ getJourneyShareLink: vi.fn().mockReturnValue({ allowed: true, link: { token: 'abc' } }) } as Partial<JourneyService>)).getShareLink(user, '9')).toEqual({ link: { token: 'abc' } });
// An owner whose journey has no link gets the null; a non-owner gets the
// same refusal set/delete give, so the client can tell the two apart.
expect(ctl(svc({ getJourneyShareLink: vi.fn().mockReturnValue({ allowed: true, link: null }) } as Partial<JourneyService>)).getShareLink(user, '9')).toEqual({ link: null });
expect(thrown(() => ctl(svc({ getJourneyShareLink: vi.fn().mockReturnValue({ allowed: false }) } as Partial<JourneyService>)).getShareLink(user, '9'))).toEqual({ status: 403, body: { error: 'Not allowed' } });
expect(thrown(() => ctl(svc({ createOrUpdateJourneyShareLink: vi.fn().mockReturnValue(null) } as Partial<JourneyService>)).setShareLink(user, '9', {}))).toEqual({ status: 403, body: { error: 'Not allowed' } });
expect(await ctl(svc({ getJourneyShareLink: vi.fn().mockReturnValue({ allowed: true, link: null }) } as Partial<JourneyService>)).getShareLink(user, '9')).toEqual({ link: null });
expect(await thrownAsync(() => ctl(svc({ getJourneyShareLink: vi.fn().mockReturnValue({ allowed: false }) } as Partial<JourneyService>)).getShareLink(user, '9'))).toEqual({ status: 403, body: { error: 'Not allowed' } });
expect(await thrownAsync(() => ctl(svc({ createOrUpdateJourneyShareLink: vi.fn().mockReturnValue(null) } as Partial<JourneyService>)).setShareLink(user, '9', {}))).toEqual({ status: 403, body: { error: 'Not allowed' } });
const setLink = vi.fn().mockReturnValue({ token: 'abc' });
expect(ctl(svc({ createOrUpdateJourneyShareLink: setLink } as Partial<JourneyService>)).setShareLink(user, '9', { share_timeline: true })).toEqual({ token: 'abc' });
expect(await ctl(svc({ createOrUpdateJourneyShareLink: setLink } as Partial<JourneyService>)).setShareLink(user, '9', { share_timeline: true })).toEqual({ token: 'abc' });
// newest_first is part of the shared contract and the public viewer reads
// it, so it has to reach the service instead of being dropped here (#1614).
expect(setLink).toHaveBeenCalledWith(9, 1, { share_timeline: true, share_gallery: undefined, share_map: undefined, newest_first: undefined });
const withOrder = vi.fn().mockReturnValue({ token: 'abc' });
ctl(svc({ createOrUpdateJourneyShareLink: withOrder } as Partial<JourneyService>)).setShareLink(user, '9', { newest_first: true });
await ctl(svc({ createOrUpdateJourneyShareLink: withOrder } as Partial<JourneyService>)).setShareLink(user, '9', { newest_first: true });
expect(withOrder).toHaveBeenCalledWith(9, 1, { share_timeline: undefined, share_gallery: undefined, share_map: undefined, newest_first: true });
expect(thrown(() => ctl(svc({ deleteJourneyShareLink: vi.fn().mockReturnValue(false) } as Partial<JourneyService>)).deleteShareLink(user, '9'))).toEqual({ status: 403, body: { error: 'Not allowed' } });
expect(await thrownAsync(() => ctl(svc({ deleteJourneyShareLink: vi.fn().mockReturnValue(false) } as Partial<JourneyService>)).deleteShareLink(user, '9'))).toEqual({ status: 403, body: { error: 'Not allowed' } });
});
it('takes the committed bytes back out when the upload is refused', async () => {
@@ -272,9 +264,9 @@ describe('JourneyController', () => {
expect(await ctl(svc({ addProviderPhoto: vi.fn().mockReturnValue({ id: 2 }) } as Partial<JourneyService>)).providerPhotos(user, '3', { provider: 'immich', asset_id: 'a' })).toEqual({ id: 2 });
});
it('PATCH photos: 404 then returns the updated photo', () => {
expect(thrown(() => ctl(svc({ updatePhoto: vi.fn().mockReturnValue(null) } as Partial<JourneyService>)).updatePhoto(user, '7', { caption: 'x' }))).toEqual({ status: 404, body: { error: 'Photo not found' } });
expect(ctl(svc({ updatePhoto: vi.fn().mockReturnValue({ id: 7 }) } as Partial<JourneyService>)).updatePhoto(user, '7', { caption: 'x' })).toEqual({ id: 7 });
it('PATCH photos: 404 then returns the updated photo', async () => {
expect(await thrownAsync(() => ctl(svc({ updatePhoto: vi.fn().mockReturnValue(null) } as Partial<JourneyService>)).updatePhoto(user, '7', { caption: 'x' }))).toEqual({ status: 404, body: { error: 'Photo not found' } });
expect(await ctl(svc({ updatePhoto: vi.fn().mockReturnValue({ id: 7 }) } as Partial<JourneyService>)).updatePhoto(user, '7', { caption: 'x' })).toEqual({ id: 7 });
});
it('DELETE photo removes the storage object when a path exists', async () => {
@@ -322,8 +314,8 @@ describe('JourneyController', () => {
expect(storageStub.delete).toHaveBeenCalledWith('journey', 'poster.jpg');
});
it('PATCH /:id returns the updated journey on success', () => {
expect(ctl(svc({ updateJourney: vi.fn().mockReturnValue({ id: 9 }) } as Partial<JourneyService>)).update(user, '9', { title: 'x' })).toEqual({ id: 9 });
it('PATCH /:id returns the updated journey on success', async () => {
expect(await ctl(svc({ updateJourney: vi.fn().mockReturnValue({ id: 9 }) } as Partial<JourneyService>)).update(user, '9', { title: 'x' })).toEqual({ id: 9 });
});
it('cover upload: 400 without file, 404 when the journey is gone, else commits + returns the journey', async () => {
@@ -335,42 +327,42 @@ describe('JourneyController', () => {
expect(updateJourney).toHaveBeenCalledWith(9, 1, { cover_image: 'journey/c.jpg' });
});
it('DELETE /:id and trips/contributors success paths', () => {
expect(ctl(svc({ deleteJourney: vi.fn().mockReturnValue(true) } as Partial<JourneyService>)).remove(user, '9')).toEqual({ success: true });
expect(ctl(svc({ removeTripFromJourney: vi.fn().mockReturnValue(true) } as Partial<JourneyService>)).removeTrip(user, '9', '2')).toEqual({ success: true });
expect(ctl(svc({ updateContributorRole: vi.fn().mockReturnValue(true) } as Partial<JourneyService>)).updateContributor(user, '9', '2', { role: 'editor' })).toEqual({ success: true });
expect(ctl(svc({ removeContributor: vi.fn().mockReturnValue(true) } as Partial<JourneyService>)).removeContributor(user, '9', '2')).toEqual({ success: true });
it('DELETE /:id and trips/contributors success paths', async () => {
expect(await ctl(svc({ deleteJourney: vi.fn().mockReturnValue(true) } as Partial<JourneyService>)).remove(user, '9')).toEqual({ success: true });
expect(await ctl(svc({ removeTripFromJourney: vi.fn().mockReturnValue(true) } as Partial<JourneyService>)).removeTrip(user, '9', '2')).toEqual({ success: true });
expect(await ctl(svc({ updateContributorRole: vi.fn().mockReturnValue(true) } as Partial<JourneyService>)).updateContributor(user, '9', '2', { role: 'editor' })).toEqual({ success: true });
expect(await ctl(svc({ removeContributor: vi.fn().mockReturnValue(true) } as Partial<JourneyService>)).removeContributor(user, '9', '2')).toEqual({ success: true });
});
it('addContributor defaults the role to viewer when omitted', () => {
it('addContributor defaults the role to viewer when omitted', async () => {
const addContributor = vi.fn().mockReturnValue(true);
ctl(svc({ addContributor } as Partial<JourneyService>)).addContributor(user, '9', { user_id: 2 });
await ctl(svc({ addContributor } as Partial<JourneyService>)).addContributor(user, '9', { user_id: 2 });
expect(addContributor).toHaveBeenCalledWith(9, 1, 2, 'viewer');
});
it('createEntry returns the entry when the journey exists', () => {
expect(ctl(svc({ createEntry: vi.fn().mockReturnValue({ id: 4 }) } as Partial<JourneyService>)).createEntry(user, '9', { entry_date: '2026-01-01' })).toEqual({ id: 4 });
it('createEntry returns the entry when the journey exists', async () => {
expect(await ctl(svc({ createEntry: vi.fn().mockReturnValue({ id: 4 }) } as Partial<JourneyService>)).createEntry(user, '9', { entry_date: '2026-01-01' })).toEqual({ id: 4 });
});
it('reorderEntries succeeds for a numeric array', () => {
expect(ctl(svc({ reorderEntries: vi.fn().mockReturnValue(true) } as Partial<JourneyService>)).reorderEntries(user, '9', { orderedIds: [3, 1, 2] })).toEqual({ success: true });
it('reorderEntries succeeds for a numeric array', async () => {
expect(await ctl(svc({ reorderEntries: vi.fn().mockReturnValue(true) } as Partial<JourneyService>)).reorderEntries(user, '9', { orderedIds: [3, 1, 2] })).toEqual({ success: true });
});
it('restoreSuggestions answers with the count, and refuses a viewer the same way its siblings do', () => {
it('restoreSuggestions answers with the count, and refuses a viewer the same way its siblings do', async () => {
const restore = vi.fn().mockReturnValue({ restored: 3 });
expect(ctl(svc({ restoreDismissedSuggestions: restore } as Partial<JourneyService>)).restoreSuggestions(user, '9')).toEqual({ restored: 3 });
expect(await ctl(svc({ restoreDismissedSuggestions: restore } as Partial<JourneyService>)).restoreSuggestions(user, '9')).toEqual({ restored: 3 });
expect(restore).toHaveBeenCalledWith(9, 1);
expect(
thrown(() => ctl(svc({ restoreDismissedSuggestions: vi.fn().mockReturnValue(null) } as Partial<JourneyService>)).restoreSuggestions(user, '9')),
await thrownAsync(() => ctl(svc({ restoreDismissedSuggestions: vi.fn().mockReturnValue(null) } as Partial<JourneyService>)).restoreSuggestions(user, '9')),
).toEqual({ status: 403, body: { error: 'Not allowed' } });
});
it('preferences returns the result on success', () => {
expect(ctl(svc({ updateJourneyPreferences: vi.fn().mockReturnValue({ ok: true }) } as Partial<JourneyService>)).preferences(user, '9', { theme: 'dark' })).toEqual({ ok: true });
it('preferences returns the result on success', async () => {
expect(await ctl(svc({ updateJourneyPreferences: vi.fn().mockReturnValue({ ok: true }) } as Partial<JourneyService>)).preferences(user, '9', { theme: 'dark' })).toEqual({ ok: true });
});
it('deleteShareLink returns success when removed', () => {
expect(ctl(svc({ deleteJourneyShareLink: vi.fn().mockReturnValue(true) } as Partial<JourneyService>)).deleteShareLink(user, '9')).toEqual({ success: true });
it('deleteShareLink returns success when removed', async () => {
expect(await ctl(svc({ deleteJourneyShareLink: vi.fn().mockReturnValue(true) } as Partial<JourneyService>)).deleteShareLink(user, '9')).toEqual({ success: true });
});
/*
* The Studio book (#1973). Its access shape is the same as everything around
@@ -378,25 +370,25 @@ describe('JourneyController', () => {
* is a 404 rather than a 403, so the route cannot be used to find out which
* journeys exist.
*/
it('book: 404 vs a journey with no book yet, and the save status codes', () => {
it('book: 404 vs a journey with no book yet, and the save status codes', async () => {
// A journey with no book yet is not an error: Studio opens on it, lays a
// book out and saves. 404 here would make "no book" and "no journey"
// indistinguishable to the client.
expect(ctl(svc(), { getBook: vi.fn().mockReturnValue(null), canOpen: vi.fn().mockReturnValue(true) }).getBook(user, '9')).toEqual({ book: null });
expect(thrown(() => ctl(svc(), { getBook: vi.fn().mockReturnValue(null), canOpen: vi.fn().mockReturnValue(false) }).getBook(user, '9'))).toEqual({ status: 404, body: { error: 'Journey not found' } });
expect(ctl(svc(), { getBook: vi.fn().mockReturnValue({ id: 3, version: 4 }), canOpen: vi.fn() }).getBook(user, '9')).toEqual({ book: { id: 3, version: 4 } });
expect(await ctl(svc(), { getBook: vi.fn().mockReturnValue(null), canOpen: vi.fn().mockReturnValue(true) }).getBook(user, '9')).toEqual({ book: null });
expect(await thrownAsync(() => ctl(svc(), { getBook: vi.fn().mockReturnValue(null), canOpen: vi.fn().mockReturnValue(false) }).getBook(user, '9'))).toEqual({ status: 404, body: { error: 'Journey not found' } });
expect(await ctl(svc(), { getBook: vi.fn().mockReturnValue({ id: 3, version: 4 }), canOpen: vi.fn() }).getBook(user, '9')).toEqual({ book: { id: 3, version: 4 } });
// A refused save says which refusal it was. Out of reach entirely is still
// 404; a viewer who can open the journey but may not write it gets 403, so
// the editor can say why instead of claiming the journey vanished.
expect(thrown(() => ctl(svc(), { saveBook: vi.fn().mockReturnValue(null), canOpen: vi.fn().mockReturnValue(false) }).saveBook(user, '9', { document: {} } as never))).toEqual({ status: 404, body: { error: 'Journey not found' } });
expect(thrown(() => ctl(svc(), { saveBook: vi.fn().mockReturnValue(null), canOpen: vi.fn().mockReturnValue(true) }).saveBook(user, '9', { document: {} } as never))).toEqual({ status: 403, body: { error: 'Not allowed' } });
expect(await thrownAsync(() => ctl(svc(), { saveBook: vi.fn().mockReturnValue(null), canOpen: vi.fn().mockReturnValue(false) }).saveBook(user, '9', { document: {} } as never))).toEqual({ status: 404, body: { error: 'Journey not found' } });
expect(await thrownAsync(() => ctl(svc(), { saveBook: vi.fn().mockReturnValue(null), canOpen: vi.fn().mockReturnValue(true) }).saveBook(user, '9', { document: {} } as never))).toEqual({ status: 403, body: { error: 'Not allowed' } });
// The record comes back bare, not in an envelope — the contract in
// shared/src/book/book-store.schema.ts is the record itself.
const broadcastSaved = vi.fn();
const saveBook = vi.fn().mockReturnValue({ record: { id: 3, version: 5 } });
expect(ctl(svc(), { saveBook, broadcastSaved }).saveBook(user, '9', { title: 'T', document: { v: 1 }, baseVersion: 4 } as never, 'sock-7')).toEqual({ id: 3, version: 5 });
expect(await ctl(svc(), { saveBook, broadcastSaved }).saveBook(user, '9', { title: 'T', document: { v: 1 }, baseVersion: 4 } as never, 'sock-7')).toEqual({ id: 3, version: 5 });
expect(saveBook).toHaveBeenCalledWith(9, 1, { title: 'T', document: { v: 1 }, baseVersion: 4 });
// Forwarded so the client that just saved does not process its own change.
expect(broadcastSaved).toHaveBeenCalledWith(9, 1, { id: 3, version: 5 }, 'sock-7');
@@ -404,11 +396,11 @@ describe('JourneyController', () => {
// A missing title is '' rather than undefined: the column is NOT NULL and
// an untitled book is an ordinary thing to have.
const untitled = vi.fn().mockReturnValue({ record: { id: 3, version: 1 } });
ctl(svc(), { saveBook: untitled, broadcastSaved: vi.fn() }).saveBook(user, '9', { document: {} } as never);
await ctl(svc(), { saveBook: untitled, broadcastSaved: vi.fn() }).saveBook(user, '9', { document: {} } as never);
expect(untitled.mock.calls[0][2].title).toBe('');
});
it('book: a conflict is a 409 that carries the other version', () => {
it('book: a conflict is a 409 that carries the other version', async () => {
/*
* Two people editing is the normal case, not an exception. A bare 409 would
* make showing what the other version is a second round trip, at exactly
@@ -416,7 +408,7 @@ describe('JourneyController', () => {
*/
const broadcastSaved = vi.fn();
const saveBook = vi.fn().mockReturnValue({ conflict: { id: 3, version: 6, title: 'Theirs' } });
expect(thrown(() => ctl(svc(), { saveBook, broadcastSaved }).saveBook(user, '9', { document: {}, baseVersion: 4 } as never))).toEqual({
expect(await thrownAsync(() => ctl(svc(), { saveBook, broadcastSaved }).saveBook(user, '9', { document: {}, baseVersion: 4 } as never))).toEqual({
status: 409,
body: { error: 'Book was changed by someone else', current: { id: 3, version: 6, title: 'Theirs' } },
});
@@ -424,13 +416,13 @@ describe('JourneyController', () => {
expect(broadcastSaved).not.toHaveBeenCalled();
});
it('book: delete answers 204, 403 for a viewer, or 404 out of reach', () => {
expect(ctl(svc(), { deleteBook: vi.fn().mockReturnValue(true) }).deleteBook(user, '9')).toBeUndefined();
it('book: delete answers 204, 403 for a viewer, or 404 out of reach', async () => {
expect(await ctl(svc(), { deleteBook: vi.fn().mockReturnValue(true) }).deleteBook(user, '9')).toBeUndefined();
// False means there was nothing to delete, which is still a 204 — deleting
// a book that is already gone is not a failure.
expect(ctl(svc(), { deleteBook: vi.fn().mockReturnValue(false) }).deleteBook(user, '9')).toBeUndefined();
expect(thrown(() => ctl(svc(), { deleteBook: vi.fn().mockReturnValue(null), canOpen: vi.fn().mockReturnValue(false) }).deleteBook(user, '9'))).toEqual({ status: 404, body: { error: 'Journey not found' } });
expect(thrown(() => ctl(svc(), { deleteBook: vi.fn().mockReturnValue(null), canOpen: vi.fn().mockReturnValue(true) }).deleteBook(user, '9'))).toEqual({ status: 403, body: { error: 'Not allowed' } });
expect(await ctl(svc(), { deleteBook: vi.fn().mockReturnValue(false) }).deleteBook(user, '9')).toBeUndefined();
expect(await thrownAsync(() => ctl(svc(), { deleteBook: vi.fn().mockReturnValue(null), canOpen: vi.fn().mockReturnValue(false) }).deleteBook(user, '9'))).toEqual({ status: 404, body: { error: 'Journey not found' } });
expect(await thrownAsync(() => ctl(svc(), { deleteBook: vi.fn().mockReturnValue(null), canOpen: vi.fn().mockReturnValue(true) }).deleteBook(user, '9'))).toEqual({ status: 403, body: { error: 'Not allowed' } });
});
});
+12 -12
View File
@@ -278,16 +278,16 @@ describe('createAuthCode / consumeAuthCode', () => {
// ── generateToken ─────────────────────────────────────────────────────────────
describe('generateToken', () => {
it('OIDC-SVC-057: remember=true signs with the SESSION_DURATION_REMEMBER lifetime', () => {
it('OIDC-SVC-057: remember=true signs with the SESSION_DURATION_REMEMBER lifetime', async () => {
const { user } = createUser(testDb, { email: 'remember@example.com' });
const token = svc.generateToken({ id: user.id }, true);
const token = await svc.generateToken({ id: user.id }, true);
const decoded = jwtLib.decode(token) as { iat: number; exp: number };
expect(decoded.exp - decoded.iat).toBe(2592000);
});
it('OIDC-SVC-058: remember=false or absent signs with the default SESSION_DURATION lifetime', () => {
it('OIDC-SVC-058: remember=false or absent signs with the default SESSION_DURATION lifetime', async () => {
const { user } = createUser(testDb, { email: 'default@example.com' });
for (const token of [svc.generateToken({ id: user.id }, false), svc.generateToken({ id: user.id })]) {
for (const token of [await svc.generateToken({ id: user.id }, false), await svc.generateToken({ id: user.id })]) {
const decoded = jwtLib.decode(token) as { iat: number; exp: number };
expect(decoded.exp - decoded.iat).toBe(86400);
}
@@ -1212,8 +1212,8 @@ describe('wrapper methods', () => {
// The SSO configuration read/write moved here from AdminService, which held the SQL
// for a domain that already had a module. Same cases, same service, new owner.
describe('OIDC settings', () => {
it('ADMIN-SVC-047 — getOidcSettings returns default empty values when no OIDC configured', () => {
const result = svc.getOidcSettings() as any;
it('ADMIN-SVC-047 — getOidcSettings returns default empty values when no OIDC configured', async () => {
const result = await svc.getOidcSettings() as any;
expect(result.issuer).toBe('');
expect(result.client_id).toBe('');
expect(result.oidc_only).toBe(false);
@@ -1224,14 +1224,14 @@ describe('OIDC settings', () => {
it('ADMIN-SVC-048 — updateOidcSettings persists issuer and client_id, then getOidcSettings returns them', async () => {
await svc.updateOidcSettings({ issuer: 'https://auth.example.com', client_id: 'my-client' });
const result = svc.getOidcSettings() as any;
const result = await svc.getOidcSettings() as any;
expect(result.issuer).toBe('https://auth.example.com');
expect(result.client_id).toBe('my-client');
});
it('ADMIN-SVC-049 — updateOidcSettings does not write oidc_only (replaced by granular toggles)', async () => {
await svc.updateOidcSettings({ issuer: 'https://auth.example.com', client_id: 'my-client' });
const result = svc.getOidcSettings() as any;
const result = await svc.getOidcSettings() as any;
// oidc_only is no longer managed by updateOidcSettings; use password_login/oidc_login toggles
expect(result.oidc_only).toBe(false);
});
@@ -1239,7 +1239,7 @@ describe('OIDC settings', () => {
it('ADMIN-SVC-075 — updateOidcSettings applies all five writes atomically', async () => {
const result = await svc.updateOidcSettings({ issuer: 'https://idp', client_id: 'cid', display_name: 'IdP' }) as any;
expect(result.success).toBe(true);
const settings = svc.getOidcSettings();
const settings = await svc.getOidcSettings();
expect(settings).toMatchObject({ issuer: 'https://idp', client_id: 'cid', display_name: 'IdP' });
});
});
@@ -1264,13 +1264,13 @@ describe('OIDC settings — the lockout guard', () => {
it('OIDC-SETTINGS-052 an omitted client_secret keeps the stored one, an empty string clears it', async () => {
const toggles = vi.spyOn(auth, 'resolveAuthToggles').mockResolvedValue({ password_login: true } as never);
await svc.updateOidcSettings({ issuer: 'https://idp', client_id: 'c', client_secret: 'shh' });
expect(svc.getOidcSettings().client_secret_set).toBe(true);
expect((await svc.getOidcSettings()).client_secret_set).toBe(true);
// Omitted: the write skips the column entirely rather than blanking it, which is
// what lets the admin panel save the form without re-typing the secret.
await svc.updateOidcSettings({ issuer: 'https://idp', client_id: 'c' });
expect(svc.getOidcSettings().client_secret_set).toBe(true);
expect((await svc.getOidcSettings()).client_secret_set).toBe(true);
await svc.updateOidcSettings({ issuer: 'https://idp', client_id: 'c', client_secret: '' });
expect(svc.getOidcSettings().client_secret_set).toBe(false);
expect((await svc.getOidcSettings()).client_secret_set).toBe(false);
toggles.mockRestore();
});
});
@@ -145,17 +145,17 @@ beforeEach(() => {
// ── Kill switch ──────────────────────────────────────────────────────────────
describe('enrichDisabled', () => {
it('ENRICH-001: is off only when the setting is literally "false"', () => {
it('ENRICH-001: is off only when the setting is literally "false"', async () => {
const svc = make(mapsStub(), cacheStub());
mockDbGet.mockReturnValue(undefined);
expect(svc.enrichDisabled()).toBe(false); // never configured — fail open
expect(await svc.enrichDisabled()).toBe(false); // never configured — fail open
mockDbGet.mockReturnValue({ value: 'true' });
expect(svc.enrichDisabled()).toBe(false);
expect(await svc.enrichDisabled()).toBe(false);
mockDbGet.mockReturnValue({ value: 'false' });
expect(svc.enrichDisabled()).toBe(true);
expect(await svc.enrichDisabled()).toBe(true);
});
it('ENRICH-002: answers the disabled envelope without touching a provider', async () => {
@@ -90,7 +90,7 @@ async function svc(searchNominatim: MapsService['searchNominatim']): Promise<Pla
new QueryHelpersService(dbs),
new UnsplashService(dbs, new RuntimeEnvService(), storageFx.storage),
photoCacheStub,
new JourneyDomainService(dbs, new RealtimeService(), new TrekPhotosRepository(dbs)),
new JourneyDomainService(dbs, new RealtimeService(), new TrekPhotosRepository(dbs), await createTestUnitOfWork(dbs.connection)),
storageFx.storage,
await accommodationsOver(dbs), await createTestUnitOfWork(dbs.connection),
);
@@ -106,7 +106,7 @@ async function makePlacesService(maps: MapsService = new MapsService(dbs, photoC
new QueryHelpersService(dbs),
new UnsplashService(dbs, new RuntimeEnvService(), placesStorageFx.storage),
photoCacheStub,
new JourneyDomainService(dbs, new RealtimeService(), new TrekPhotosRepository(dbs)),
new JourneyDomainService(dbs, new RealtimeService(), new TrekPhotosRepository(dbs), await createTestUnitOfWork(dbs.connection)),
placesStorageFx.storage,
await accommodationsOver(dbs), await createTestUnitOfWork(dbs.connection),
);
@@ -53,7 +53,7 @@ describe('members', () => {
it('GET 404 without access, else owner+members+current_user_id', async () => {
expect(await thrown(() => tc(svc({ canAccessTrip: vi.fn().mockReturnValue(undefined) })).members(user, '9'))).toEqual({ status: 404, body: { error: 'Trip not found' } });
const s = svc({ listMembers: vi.fn().mockReturnValue({ owner: { id: 1 }, members: [] }) } as Partial<TripMembersService>);
expect(tc(s).members(user, '9')).toEqual({ owner: { id: 1 }, members: [], current_user_id: 1 });
expect(await tc(s).members(user, '9')).toEqual({ owner: { id: 1 }, members: [], current_user_id: 1 });
});
it('POST 403 without member_manage, else adds + notifies', async () => {
@@ -134,7 +134,7 @@ describe('guests (#1362)', () => {
expect(await thrown(() => tc(wsGuest).createGuest(user, '9', { name: ' ' }))).toEqual({ status: 400, body: { error: 'Guest name is required' } });
const createGuest = vi.fn().mockReturnValue({ member: { id: 7, username: 'Anna', is_guest: true } });
const s = svc({ createGuest } as Partial<TripMembersService>);
expect(tc(s).createGuest(user, '9', { name: 'Anna' })).toEqual({ member: { id: 7, username: 'Anna', is_guest: true } });
expect(await tc(s).createGuest(user, '9', { name: 'Anna' })).toEqual({ member: { id: 7, username: 'Anna', is_guest: true } });
expect(createGuest).toHaveBeenCalledWith('9', 'Anna', user.id);
});
@@ -142,7 +142,7 @@ describe('guests (#1362)', () => {
const miss = svc({ renameGuest: vi.fn().mockReturnValue(false) } as Partial<TripMembersService>);
expect(await thrown(() => tc(miss).renameGuest(user, '9', '7', { name: 'Bob' }))).toEqual({ status: 404, body: { error: 'Guest not found' } });
const ok = svc({ renameGuest: vi.fn().mockReturnValue(true) } as Partial<TripMembersService>);
expect(tc(ok).renameGuest(user, '9', '7', { name: 'Bob' })).toEqual({ success: true });
expect(await tc(ok).renameGuest(user, '9', '7', { name: 'Bob' })).toEqual({ success: true });
});
it('delete: 404 when the guest is missing, else success', async () => {
@@ -126,7 +126,7 @@ afterAll(() => {
// ── Delegating helpers (what the controller calls around the mutations) ───────
describe('TripMembersService delegation', () => {
it('MEMBERS-SVC-001: canAccessTrip forwards the db helper — owner and member get the access row, a stranger gets nothing', () => {
it('MEMBERS-SVC-001: canAccessTrip forwards the db helper — owner and member get the access row, a stranger gets nothing', async () => {
const { user: owner } = createUser(testDb);
const { user: member } = createUser(testDb);
const { user: stranger } = createUser(testDb);
@@ -136,9 +136,9 @@ describe('TripMembersService delegation', () => {
// Every member route answers 404 on a falsy result and reads access.user_id as
// the trip owner, so a delegation that stopped forwarding would lock the whole
// roster out rather than fail loudly.
expect(roster.canAccessTrip(String(trip.id), owner.id)).toMatchObject({ user_id: owner.id });
expect(roster.canAccessTrip(trip.id, member.id)).toMatchObject({ user_id: owner.id });
expect(roster.canAccessTrip(trip.id, stranger.id)).toBeUndefined();
expect(await roster.canAccessTrip(String(trip.id), owner.id)).toMatchObject({ user_id: owner.id });
expect(await roster.canAccessTrip(trip.id, member.id)).toMatchObject({ user_id: owner.id });
expect(await roster.canAccessTrip(trip.id, stranger.id)).toBeUndefined();
});
it('MEMBERS-SVC-002: can() resolves member_manage at its trip_owner default and lets admins through', async () => {
@@ -152,7 +152,7 @@ describe('TripMembersService delegation', () => {
expect(await roster.can('member_manage', 'admin', owner.id, member.id, true)).toBe(true);
});
it('MEMBERS-SVC-003: broadcast forwards the socket id so the originating client is not echoed', () => {
it('MEMBERS-SVC-003: broadcast forwards the socket id so the originating client is not echoed', async () => {
roster.broadcast('9', 'trip:updated', { trip: { id: 9 } } as never, 'sock-1');
expect(broadcast).toHaveBeenCalledWith('9', 'trip:updated', { trip: { id: 9 } }, 'sock-1');
@@ -162,7 +162,7 @@ describe('TripMembersService delegation', () => {
expect(broadcast).toHaveBeenLastCalledWith('9', 'trip:updated', { trip: { id: 9 } }, undefined);
});
it('MEMBERS-SVC-004: getTripForViewer re-reads the trip in list shape, with is_owner per viewer', () => {
it('MEMBERS-SVC-004: getTripForViewer re-reads the trip in list shape, with is_owner per viewer', async () => {
const { user: owner } = createUser(testDb);
const { user: member } = createUser(testDb);
const trip = createTrip(testDb, owner.id, { title: 'Handover' });
@@ -171,11 +171,11 @@ describe('TripMembersService delegation', () => {
// The handover broadcast hands the raw :id route param straight in, so the
// named-parameter query has to keep matching a string id against the INTEGER
// column — and the payload the clients re-read must carry their own is_owner.
const asOwner = roster.getTripForViewer(String(trip.id), owner.id) as Record<string, unknown>;
const asOwner = await roster.getTripForViewer(String(trip.id), owner.id) as Record<string, unknown>;
expect(asOwner).toMatchObject({ id: trip.id, title: 'Handover', is_owner: 1, owner_username: owner.username, shared_count: 1 });
const asMember = roster.getTripForViewer(trip.id, member.id) as Record<string, unknown>;
const asMember = await roster.getTripForViewer(trip.id, member.id) as Record<string, unknown>;
expect(asMember.is_owner).toBe(0);
expect(roster.getTripForViewer(999999, owner.id)).toBeUndefined();
expect(await roster.getTripForViewer(999999, owner.id)).toBeUndefined();
});
it('MEMBERS-SVC-005: notifyInvite sends a user-scoped trip_invite carrying the actor, invitee and trip', async () => {
@@ -217,44 +217,44 @@ describe('addMember fallbacks', () => {
// membership is inserted — losing that row must not cost the invitee their
// access or throw on an undefined title.
const broken = await rosterWithMissingRow('SELECT title FROM trips WHERE id = ?');
const result = broken.addMember(trip.id, invitee.email, owner.id, owner.id);
const result = await broken.addMember(trip.id, invitee.email, owner.id, owner.id);
expect(result.tripTitle).toBe('Untitled');
expect(testDb.prepare('SELECT id FROM trip_members WHERE trip_id = ? AND user_id = ?').get(trip.id, invitee.id)).toBeDefined();
});
it('MEMBERS-SVC-008: addMember resolves a padded identifier and matches on username as well as email', () => {
it('MEMBERS-SVC-008: addMember resolves a padded identifier and matches on username as well as email', async () => {
const { user: owner } = createUser(testDb);
const { user: invitee } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
// Pasted invites arrive with surrounding whitespace; without the trim the
// lookup misses and the box answers 'User not found' for a real account.
expect(roster.addMember(trip.id, ` ${invitee.username} `, owner.id, owner.id).member.id).toBe(invitee.id);
expect((await roster.addMember(trip.id, ` ${invitee.username} `, owner.id, owner.id)).member.id).toBe(invitee.id);
});
});
// ── transferOwnership guard rails (#973) ─────────────────────────────────────
describe('transferOwnership guard rails', () => {
it('MEMBERS-SVC-009: rejects a trip that no longer exists, before any other check', () => {
it('MEMBERS-SVC-009: rejects a trip that no longer exists, before any other check', async () => {
const { user: owner } = createUser(testDb);
// NotFoundError, not ValidationError: the controller maps the two to 404 and
// 400. Passing the owner as the new owner too proves the trip lookup runs
// first — otherwise this would surface as 'You already own this trip'.
expect(() => roster.transferOwnership(999999, owner.id, owner.id)).toThrow(NotFoundError);
expect(() => roster.transferOwnership(999999, owner.id, owner.id)).toThrow('Trip not found');
await expect(roster.transferOwnership(999999, owner.id, owner.id)).rejects.toThrow(NotFoundError);
await expect(roster.transferOwnership(999999, owner.id, owner.id)).rejects.toThrow('Trip not found');
});
it('MEMBERS-SVC-010: rejects an id with no user row before it checks membership', () => {
it('MEMBERS-SVC-010: rejects an id with no user row before it checks membership', async () => {
const { user: owner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
// A stale id from the client must read as a 404 'User not found' rather than
// the 400 the non-member branch below it would produce, and the trip must keep
// its owner either way.
expect(() => roster.transferOwnership(trip.id, 999999, owner.id)).toThrow(NotFoundError);
expect(() => roster.transferOwnership(trip.id, 999999, owner.id)).toThrow('User not found');
await expect(roster.transferOwnership(trip.id, 999999, owner.id)).rejects.toThrow(NotFoundError);
await expect(roster.transferOwnership(trip.id, 999999, owner.id)).rejects.toThrow('User not found');
expect((testDb.prepare('SELECT user_id FROM trips WHERE id = ?').get(trip.id) as { user_id: number }).user_id).toBe(owner.id);
});
@@ -268,7 +268,7 @@ describe('transferOwnership guard rails', () => {
// handover halfway, which would leave the owner pointer and the member rows
// disagreeing about who owns the trip.
const broken = await rosterWithMissingRow('SELECT email FROM users WHERE id = ?');
const result = broken.transferOwnership(trip.id, member.id, owner.id);
const result = await broken.transferOwnership(trip.id, member.id, owner.id);
expect(result.fromEmail).toBe('');
expect(result.toEmail).toBe(member.email);
expect((testDb.prepare('SELECT user_id FROM trips WHERE id = ?').get(trip.id) as { user_id: number }).user_id).toBe(member.id);
@@ -278,13 +278,13 @@ describe('transferOwnership guard rails', () => {
// ── Guest name validation (#1362) ────────────────────────────────────────────
describe('guest name validation', () => {
it('MEMBERS-SVC-012: createGuest rejects an absent, blank or over-long name and writes nothing', () => {
it('MEMBERS-SVC-012: createGuest rejects an absent, blank or over-long name and writes nothing', async () => {
const { user: owner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
expect(() => roster.createGuest(trip.id, undefined as never, owner.id)).toThrow(ValidationError);
expect(() => roster.createGuest(trip.id, ' ', owner.id)).toThrow('Guest name is required');
expect(() => roster.createGuest(trip.id, 'x'.repeat(51), owner.id)).toThrow('Guest name must be 50 characters or fewer');
await expect(roster.createGuest(trip.id, undefined as never, owner.id)).rejects.toThrow(ValidationError);
await expect(roster.createGuest(trip.id, ' ', owner.id)).rejects.toThrow('Guest name is required');
await expect(roster.createGuest(trip.id, 'x'.repeat(51), owner.id)).rejects.toThrow('Guest name must be 50 characters or fewer');
// The guards run ahead of the transaction, so a rejected name can never leave
// a credential-less users row behind with no trip to belong to.
@@ -292,25 +292,25 @@ describe('guest name validation', () => {
// 50 is the accepted boundary the DTO shares — off by one here and the API
// starts refusing names the client believes are valid.
expect(roster.createGuest(trip.id, 'x'.repeat(50), owner.id).member.username).toHaveLength(50);
expect((await roster.createGuest(trip.id, 'x'.repeat(50), owner.id)).member.username).toHaveLength(50);
});
it('MEMBERS-SVC-013: renameGuest rejects an absent, blank or over-long name — before the trip-scope check', () => {
it('MEMBERS-SVC-013: renameGuest rejects an absent, blank or over-long name — before the trip-scope check', async () => {
const { user: owner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const { member: guest } = roster.createGuest(trip.id, 'Ida', owner.id);
const { member: guest } = await roster.createGuest(trip.id, 'Ida', owner.id);
expect(() => roster.renameGuest(trip.id, guest.id, undefined as never)).toThrow(ValidationError);
expect(() => roster.renameGuest(trip.id, guest.id, ' ')).toThrow('Guest name is required');
expect(() => roster.renameGuest(trip.id, guest.id, 'x'.repeat(51))).toThrow('Guest name must be 50 characters or fewer');
await expect(roster.renameGuest(trip.id, guest.id, undefined as never)).rejects.toThrow(ValidationError);
await expect(roster.renameGuest(trip.id, guest.id, ' ')).rejects.toThrow('Guest name is required');
await expect(roster.renameGuest(trip.id, guest.id, 'x'.repeat(51))).rejects.toThrow('Guest name must be 50 characters or fewer');
// Order matters for the status code: an unusable name throws (400) even for an
// id that is not a guest of this trip, where the scope check returns false (404).
expect(() => roster.renameGuest(trip.id, owner.id, '')).toThrow('Guest name is required');
await expect(roster.renameGuest(trip.id, owner.id, '')).rejects.toThrow('Guest name is required');
expect((testDb.prepare('SELECT display_name FROM users WHERE id = ?').get(guest.id) as { display_name: string }).display_name).toBe('Ida');
// A padded name is stored trimmed, so the roster does not render the spaces.
expect(roster.renameGuest(trip.id, guest.id, ' Ida M. ')).toBe(true);
expect(await roster.renameGuest(trip.id, guest.id, ' Ida M. ')).toBe(true);
expect((testDb.prepare('SELECT display_name FROM users WHERE id = ?').get(guest.id) as { display_name: string }).display_name).toBe('Ida M.');
});
@@ -319,7 +319,7 @@ describe('guest name validation', () => {
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const otherTrip = createTrip(testDb, other.id);
const { member: guest } = roster.createGuest(trip.id, 'Jo', owner.id);
const { member: guest } = await roster.createGuest(trip.id, 'Jo', owner.id);
// The route only proves ownership of the trip in the URL, so this check is the
// only thing between it and a foreign guest's users row — and the delete
@@ -332,7 +332,7 @@ describe('guest name validation', () => {
// ── listMembers shaping ──────────────────────────────────────────────────────
describe('listMembers shaping', () => {
it('MEMBERS-SVC-015: avatar_url follows the storage form and the inviter is named, not just its id', () => {
it('MEMBERS-SVC-015: avatar_url follows the storage form and the inviter is named, not just its id', async () => {
const { user: owner } = createUser(testDb);
const { user: uploaded } = createUser(testDb);
const { user: sso } = createUser(testDb);
@@ -345,7 +345,7 @@ describe('listMembers shaping', () => {
testDb.prepare('INSERT INTO trip_members (trip_id, user_id, invited_by) VALUES (?, ?, ?)').run(trip.id, sso.id, owner.id);
addTripMember(testDb, trip.id, bare.id);
const { owner: ownerRow, members } = roster.listMembers(trip.id, owner.id);
const { owner: ownerRow, members } = await roster.listMembers(trip.id, owner.id);
// added_at has second resolution, so rows created in one test are tied — index
// by id rather than asserting the ORDER BY.
const byId = new Map(members.map(m => [m.id, m]));
@@ -106,7 +106,7 @@ beforeAll(async () => {
dbs(), new PermissionsService(dbs(), await createTestUnitOfWork(dbs().connection)), new RealtimeService(),
new MapsService(dbs(), photoCache), new QueryHelpersService(dbs()),
new UnsplashService(dbs(), new RuntimeEnvService(), makeStorageFixture('').storage), photoCache,
new JourneyDomainService(dbs(), new RealtimeService(), new TrekPhotosRepository(dbs())),
new JourneyDomainService(dbs(), new RealtimeService(), new TrekPhotosRepository(dbs()), await createTestUnitOfWork(dbs().connection)),
makeStorageFixture('').storage,
await accommodationsOver(dbs()), await createTestUnitOfWork(dbs().connection),
);
+34 -34
View File
@@ -133,7 +133,7 @@ beforeAll(async () => {
new QueryHelpersService(dbs()),
new UnsplashService(dbs(), new RuntimeEnvService(), coversFx.storage),
photoCache,
new JourneyDomainService(dbs(), new RealtimeService(), new TrekPhotosRepository(dbs())),
new JourneyDomainService(dbs(), new RealtimeService(), new TrekPhotosRepository(dbs()), await createTestUnitOfWork(dbs().connection)),
makeStorageFixture('').storage,
await accommodationsOver(dbs()), await createTestUnitOfWork(dbs().connection),
);
@@ -589,13 +589,13 @@ describe('resyncAccommodationDays (#1288)', () => {
});
describe('transferOwnership (#973)', () => {
it('TRIP-SVC-020: hands the trip to a member and demotes the former owner to a member', () => {
it('TRIP-SVC-020: hands the trip to a member and demotes the former owner to a member', async () => {
const { user: owner } = createUser(testDb);
const { user: member } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
addTripMember(testDb, trip.id, member.id);
const result = membersSvc.transferOwnership(trip.id, member.id, owner.id);
const result = await membersSvc.transferOwnership(trip.id, member.id, owner.id);
expect(result.toEmail).toBe(member.email);
const updated = testDb.prepare('SELECT user_id FROM trips WHERE id = ?').get(trip.id) as { user_id: number };
@@ -607,35 +607,35 @@ describe('transferOwnership (#973)', () => {
expect(memberIds).not.toContain(member.id);
});
it('TRIP-SVC-021: rejects a transfer from a non-owner', () => {
it('TRIP-SVC-021: rejects a transfer from a non-owner', async () => {
const { user: owner } = createUser(testDb);
const { user: member } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
addTripMember(testDb, trip.id, member.id);
// member (not the owner) attempts the transfer
expect(() => membersSvc.transferOwnership(trip.id, member.id, member.id)).toThrow();
await expect(membersSvc.transferOwnership(trip.id, member.id, member.id)).rejects.toThrow();
});
it('TRIP-SVC-022: rejects a transfer to someone who is not a member', () => {
it('TRIP-SVC-022: rejects a transfer to someone who is not a member', async () => {
const { user: owner } = createUser(testDb);
const { user: stranger } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
expect(() => membersSvc.transferOwnership(trip.id, stranger.id, owner.id)).toThrow('New owner must be a trip member');
await expect(membersSvc.transferOwnership(trip.id, stranger.id, owner.id)).rejects.toThrow('New owner must be a trip member');
});
it('TRIP-SVC-023: rejects transferring to yourself', () => {
it('TRIP-SVC-023: rejects transferring to yourself', async () => {
const { user: owner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
expect(() => membersSvc.transferOwnership(trip.id, owner.id, owner.id)).toThrow('You already own this trip');
await expect(membersSvc.transferOwnership(trip.id, owner.id, owner.id)).rejects.toThrow('You already own this trip');
});
});
describe('guest members (#1362)', () => {
it('TRIP-SVC-030: createGuest adds a credential-less user joined into the trip', () => {
it('TRIP-SVC-030: createGuest adds a credential-less user joined into the trip', async () => {
const { user: owner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const { member } = membersSvc.createGuest(trip.id, ' Anna ', owner.id);
const { member } = await membersSvc.createGuest(trip.id, ' Anna ', owner.id);
expect(member.username).toBe('Anna');
expect(member.is_guest).toBe(true);
@@ -650,17 +650,17 @@ describe('guest members (#1362)', () => {
expect(m).toBeTruthy();
// Surfaces in listMembers with is_guest=true and the typed display name.
const { members } = membersSvc.listMembers(trip.id, owner.id) as any;
const { members } = await membersSvc.listMembers(trip.id, owner.id) as any;
const guest = members.find((x: any) => x.id === member.id);
expect(guest.username).toBe('Anna');
expect(guest.is_guest).toBe(true);
});
it('TRIP-SVC-031: the same guest name is allowed, not suffixed (#1446)', () => {
it('TRIP-SVC-031: the same guest name is allowed, not suffixed (#1446)', async () => {
const { user: owner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const a = membersSvc.createGuest(trip.id, 'Sam', owner.id);
const b = membersSvc.createGuest(trip.id, 'Sam', owner.id);
const a = await membersSvc.createGuest(trip.id, 'Sam', owner.id);
const b = await membersSvc.createGuest(trip.id, 'Sam', owner.id);
// both keep the plain display name; only the internal (uuid) username differs
expect(a.member.username).toBe('Sam');
expect(b.member.username).toBe('Sam');
@@ -669,26 +669,26 @@ describe('guest members (#1362)', () => {
expect(usernames[0].username).not.toBe(usernames[1].username);
});
it('TRIP-SVC-032: renameGuest updates the display name (trip-scoped, guest-only)', () => {
it('TRIP-SVC-032: renameGuest updates the display name (trip-scoped, guest-only)', async () => {
const { user: owner } = createUser(testDb);
const { user: other } = createUser(testDb);
const otherTrip = createTrip(testDb, other.id);
const trip = createTrip(testDb, owner.id);
const { member } = membersSvc.createGuest(trip.id, 'Bob', owner.id);
const { member } = await membersSvc.createGuest(trip.id, 'Bob', owner.id);
expect(membersSvc.renameGuest(trip.id, member.id, 'Robert')).toBe(true);
expect(await membersSvc.renameGuest(trip.id, member.id, 'Robert')).toBe(true);
expect((testDb.prepare('SELECT display_name FROM users WHERE id = ?').get(member.id) as any).display_name).toBe('Robert');
// A real user cannot be renamed through the guest path…
expect(membersSvc.renameGuest(trip.id, owner.id, 'Hacked')).toBe(false);
expect(await membersSvc.renameGuest(trip.id, owner.id, 'Hacked')).toBe(false);
// …and a guest cannot be renamed from a different trip.
expect(membersSvc.renameGuest(otherTrip.id, member.id, 'Nope')).toBe(false);
expect(await membersSvc.renameGuest(otherTrip.id, member.id, 'Nope')).toBe(false);
});
it('TRIP-SVC-033: deleteGuest removes the user (cascading membership), guest-only + trip-scoped', async () => {
const { user: owner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const { member } = membersSvc.createGuest(trip.id, 'Carol', owner.id);
const { member } = await membersSvc.createGuest(trip.id, 'Carol', owner.id);
// Real members are not deletable via the guest path.
expect(await membersSvc.deleteGuest(trip.id, owner.id)).toBe(false);
@@ -698,15 +698,15 @@ describe('guest members (#1362)', () => {
expect(testDb.prepare('SELECT id FROM trip_members WHERE user_id = ?').get(member.id)).toBeUndefined();
});
it('TRIP-SVC-034: a guest is never invitable (addMember) nor a transfer target', () => {
it('TRIP-SVC-034: a guest is never invitable (addMember) nor a transfer target', async () => {
const { user: owner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const { member } = membersSvc.createGuest(trip.id, 'Dora', owner.id);
const { member } = await membersSvc.createGuest(trip.id, 'Dora', owner.id);
// The synthetic username/email must not resolve through the invite box.
expect(() => membersSvc.addMember(trip.id, 'Dora', owner.id, owner.id)).toThrow('User not found');
await expect(membersSvc.addMember(trip.id, 'Dora', owner.id, owner.id)).rejects.toThrow('User not found');
// Ownership can never be handed to a guest.
expect(() => membersSvc.transferOwnership(trip.id, member.id, owner.id)).toThrow('Cannot transfer ownership to a guest');
await expect(membersSvc.transferOwnership(trip.id, member.id, owner.id)).rejects.toThrow('Cannot transfer ownership to a guest');
});
});
@@ -1113,22 +1113,22 @@ describe('folded quirk branches', () => {
expect(getDays(trip.id)).toHaveLength(7);
});
it('TRIP-SVC-049: addMember inserts the membership and reports the trip title; removeMember deletes it', () => {
it('TRIP-SVC-049: addMember inserts the membership and reports the trip title; removeMember deletes it', async () => {
const { user: owner } = createUser(testDb);
const { user: invitee } = createUser(testDb);
const trip = createTrip(testDb, owner.id, { title: 'Joinable' });
const result = membersSvc.addMember(trip.id, invitee.email, owner.id, owner.id);
const result = await membersSvc.addMember(trip.id, invitee.email, owner.id, owner.id);
expect(result.member.id).toBe(invitee.id);
expect(result.tripTitle).toBe('Joinable');
expect(result.targetUserId).toBe(invitee.id);
// Duplicate + owner + missing identifier reject with the byte-identical errors.
expect(() => membersSvc.addMember(trip.id, invitee.email, owner.id, owner.id)).toThrow('User already has access');
expect(() => membersSvc.addMember(trip.id, owner.email, owner.id, owner.id)).toThrow('Trip owner is already a member');
expect(() => membersSvc.addMember(trip.id, '', owner.id, owner.id)).toThrow('Email or username required');
await expect(membersSvc.addMember(trip.id, invitee.email, owner.id, owner.id)).rejects.toThrow('User already has access');
await expect(membersSvc.addMember(trip.id, owner.email, owner.id, owner.id)).rejects.toThrow('Trip owner is already a member');
await expect(membersSvc.addMember(trip.id, '', owner.id, owner.id)).rejects.toThrow('Email or username required');
membersSvc.removeMember(trip.id, invitee.id);
await membersSvc.removeMember(trip.id, invitee.id);
expect(testDb.prepare('SELECT id FROM trip_members WHERE trip_id = ? AND user_id = ?').get(trip.id, invitee.id)).toBeUndefined();
});
@@ -1248,7 +1248,7 @@ describe('quirk fixes', () => {
it('TRIP-SVC-052: deleteGuest is atomic — a failed user DELETE rolls the budget re-split back', async () => {
const { user: owner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const { member: guest } = membersSvc.createGuest(trip.id, 'Gia', owner.id);
const { member: guest } = await membersSvc.createGuest(trip.id, 'Gia', owner.id);
const item = await budgetSvc.createBudgetItem(trip.id, { name: 'Dinner', total_price: 80, member_ids: [owner.id, guest.id] });
const broken = await failingMembers('DELETE FROM users WHERE id = ? AND is_guest = 1');
@@ -1260,11 +1260,11 @@ describe('quirk fixes', () => {
expect(row.persons).toBe(2);
});
it('TRIP-SVC-053: listMembers prefers the owner display_name over the raw username (quirk fix)', () => {
it('TRIP-SVC-053: listMembers prefers the owner display_name over the raw username (quirk fix)', async () => {
const { user: owner } = createUser(testDb, { username: 'owner-handle' });
testDb.prepare('UPDATE users SET display_name = ? WHERE id = ?').run('Olive Displayed', owner.id);
const trip = createTrip(testDb, owner.id);
const { owner: row } = membersSvc.listMembers(trip.id, owner.id);
const { owner: row } = await membersSvc.listMembers(trip.id, owner.id);
expect(row.username).toBe('Olive Displayed');
});
});
@@ -77,7 +77,7 @@ beforeAll(async () => {
new QueryHelpersService(dbs),
new UnsplashService(dbs, runtimeEnv, makeStorageFixture('').storage),
photoCache,
new JourneyDomainService(dbs, realtime, new TrekPhotosRepository(dbs)),
new JourneyDomainService(dbs, realtime, new TrekPhotosRepository(dbs), await createTestUnitOfWork(dbs.connection)),
makeStorageFixture('').storage,
await accommodationsOver(dbs), await createTestUnitOfWork(dbs.connection),
);