mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-22 21:11:14 +00:00
merge dev into feat/postgres-support
This commit is contained in:
@@ -89,6 +89,42 @@ describe('Create assignment', () => {
|
||||
await request(app).put(url).send({ end_day: true }).expect(401);
|
||||
});
|
||||
|
||||
it('ASSIGN-STAY: two visits of one place keep their own stay, the other falls back to the place (#3092)', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const { trip, day, place } = setupAssignmentFixtures(user.id);
|
||||
await updateRows(orm, Places, { id: place.id }, { duration_minutes: 60 });
|
||||
const cookie = authCookie(user.id);
|
||||
const plan = `/api/trips/${trip.id}/days/${day.id}/assignments`;
|
||||
const first = (await request(app).post(plan).set('Cookie', cookie).send({ place_id: place.id }).expect(201)).body
|
||||
.assignment;
|
||||
const second = (await request(app).post(plan).set('Cookie', cookie).send({ place_id: place.id }).expect(201)).body
|
||||
.assignment;
|
||||
expect(first.stay_minutes).toBeNull();
|
||||
|
||||
const url = `/api/trips/${trip.id}/assignments/${second.id}/stay`;
|
||||
const changed = await request(app).put(url).set('Cookie', cookie).send({ stay_minutes: 0 }).expect(200);
|
||||
expect(changed.body.assignment).toMatchObject({ id: second.id, stay_minutes: 0 });
|
||||
|
||||
// The other visit and the place itself are untouched.
|
||||
const listed = await request(app).get(`/api/trips/${trip.id}/days`).set('Cookie', cookie).expect(200);
|
||||
const visits = listed.body.days[0].assignments as Array<{ id: number; stay_minutes: number | null }>;
|
||||
expect(visits.find((a) => a.id === first.id)?.stay_minutes).toBeNull();
|
||||
expect(visits.find((a) => a.id === second.id)?.stay_minutes).toBe(0);
|
||||
expect((await findRows(orm, Places, { id: place.id }))[0]?.duration_minutes).toBe(60);
|
||||
|
||||
await request(app).put(url).set('Cookie', cookie).send({ stay_minutes: -5 }).expect(400);
|
||||
await request(app).put(url).set('Cookie', cookie).send({ stay_minutes: 1.5 }).expect(400);
|
||||
const foreign = createTrip(testDb, user.id);
|
||||
await request(app)
|
||||
.put(`/api/trips/${foreign.id}/assignments/${second.id}/stay`)
|
||||
.set('Cookie', cookie)
|
||||
.send({ stay_minutes: 10 })
|
||||
.expect(404);
|
||||
const reset = await request(app).put(url).set('Cookie', cookie).send({ stay_minutes: null }).expect(200);
|
||||
expect(reset.body.assignment.stay_minutes).toBeNull();
|
||||
await request(app).put(url).send({ stay_minutes: 10 }).expect(401);
|
||||
});
|
||||
|
||||
it('ASSIGN-001 — POST creates assignment linking place to day', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const { trip, day, place } = setupAssignmentFixtures(user.id);
|
||||
|
||||
@@ -1,15 +1,28 @@
|
||||
import { MailIngestAddresses } from '../../../src/db/entities/MailIngestAddresses.entity';
|
||||
import { MailIngestCandidates } from '../../../src/db/entities/MailIngestCandidates.entity';
|
||||
import { MailIngestMessages } from '../../../src/db/entities/MailIngestMessages.entity';
|
||||
import { Reservations } from '../../../src/db/entities/Reservations.entity';
|
||||
import { dbNow } from '../../../src/db/types';
|
||||
import { UnitOfWork } from '../../../src/nest/database/unit-of-work';
|
||||
import {
|
||||
AirtrailClient,
|
||||
type AirtrailAirport,
|
||||
type AirtrailFlightRaw,
|
||||
} from '../../../src/nest/integrations/airtrail.client';
|
||||
import { AirtrailService } from '../../../src/nest/integrations/airtrail.service';
|
||||
import { MailIngestApplyService } from '../../../src/nest/mail-ingest/mail-ingest-apply.service';
|
||||
import { MailIngestTripsService } from '../../../src/nest/mail-ingest/mail-ingest-trips.service';
|
||||
import { UNDO_WINDOW_DAYS } from '../../../src/nest/mail-ingest/mail-ingest.constants';
|
||||
import { sealMail } from '../../../src/nest/mail-ingest/mail-seal';
|
||||
import { makeBudgetItem } from '../../helpers/factories/budget';
|
||||
import { inContext } from '../../helpers/factories/context';
|
||||
import { updateRows } from '../../helpers/factories/rows';
|
||||
import type { CaseGroup } from './types';
|
||||
import { setAppSetting } from '../../helpers/factories/settings';
|
||||
import { makeTrip } from '../../helpers/factories/trips';
|
||||
import type { CaseGroup, Scene } from './types';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
import type { BookingImportPreviewItem } from '@trek/shared';
|
||||
|
||||
import { vi } from 'vitest';
|
||||
|
||||
@@ -130,6 +143,131 @@ function retype(app: INestApplication, id: number, type: string): Promise<number
|
||||
}
|
||||
|
||||
/** Bookings: reservations, transports, transit, stays and the AirTrail import. */
|
||||
// -- The booking mail import --------------------------------------------------
|
||||
|
||||
const DAY_MS = 86_400_000;
|
||||
const orm = (app: INestApplication) => app.get(MikroORM);
|
||||
/** A date `days` from today: the import's checks take a booking only within a few years of now. */
|
||||
const dayFromToday = (days: number) => new Date(Date.now() + days * DAY_MS).toISOString().slice(0, 10);
|
||||
const MAIL_DAY = dayFromToday(30);
|
||||
|
||||
/** A table booking, as a mail to the scene's owner would have been read. */
|
||||
const mailBooking = (s: Scene): BookingImportPreviewItem => ({
|
||||
type: 'restaurant',
|
||||
title: `Dinner ${s.n}`,
|
||||
reservation_time: `${MAIL_DAY}T19:00`,
|
||||
confirmation_number: `MAIL-${s.n}`,
|
||||
source: { fileName: 'mail', index: 0 },
|
||||
});
|
||||
|
||||
/** The scene's inbox entry and, for a move, the trip it goes to, by the scene's number. */
|
||||
const mailEntryOf = new Map<number, number>();
|
||||
const moveTargetOf = new Map<number, number>();
|
||||
const sceneRow = (ids: Map<number, number>, s: Scene) => {
|
||||
const id = ids.get(s.n);
|
||||
if (id === undefined) throw new Error(`scene ${s.n} has no row from its setup`);
|
||||
return id;
|
||||
};
|
||||
const mailEntry = (s: Scene) => sceneRow(mailEntryOf, s);
|
||||
const moveTarget = (s: Scene) => sceneRow(moveTargetOf, s);
|
||||
const mailPath = (s: Scene, action: string) => `/api/mail-ingest/candidates/${mailEntry(s)}/${action}`;
|
||||
|
||||
/** A mail the scene's owner forwarded, as the intake stores it: sealed, and named by its own address. */
|
||||
function forwardedMail(s: Scene): Buffer {
|
||||
return Buffer.from(
|
||||
[
|
||||
'From: Owner <owner@example.com>',
|
||||
'To: trips@example.com',
|
||||
'Subject: Your table',
|
||||
`Message-ID: <parity-${s.n}@example.com>`,
|
||||
'Content-Type: text/plain; charset=utf-8',
|
||||
'',
|
||||
`Table for two, reference MAIL-${s.n}.`,
|
||||
].join('\r\n'),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The import switched on, the owner's forwarded mail stored, and one entry
|
||||
* for its booking: waiting in the inbox, or already added to the scene's
|
||||
* trip. The add goes through the import's own write, which sends nothing;
|
||||
* announcing it is the business of the action that adds.
|
||||
*/
|
||||
async function mailEntryFor(s: Scene, app: INestApplication, added: boolean): Promise<void> {
|
||||
const db = orm(app);
|
||||
await setAppSetting(db, 'mail_ingest_enabled', 'true');
|
||||
const now = new Date();
|
||||
const raw = forwardedMail(s);
|
||||
const item = mailBooking(s);
|
||||
const id = await inContext(db, async (em) => {
|
||||
const addressId = await em.getRepository(MailIngestAddresses).insertAddress({
|
||||
userId: s.owner.id,
|
||||
tripId: null,
|
||||
tokenHash: `parity-${s.n}`,
|
||||
tokenEnc: 'sealed',
|
||||
createdAt: dbNow(now),
|
||||
});
|
||||
const messageId = await em.getRepository(MailIngestMessages).insertIfNew({
|
||||
transport: 'upload',
|
||||
messageIdHdr: `<parity-${s.n}@example.com>`,
|
||||
dedupeHash: `parity-${s.n}`,
|
||||
addressId,
|
||||
userId: s.owner.id,
|
||||
tripId: null,
|
||||
size: raw.length,
|
||||
rawEnc: sealMail(raw),
|
||||
receivedAt: dbNow(now),
|
||||
});
|
||||
if (messageId === null) throw new Error(`the mail of scene ${s.n} was stored already`);
|
||||
const entry = {
|
||||
messageId,
|
||||
userId: s.owner.id,
|
||||
position: 0,
|
||||
itemJson: JSON.stringify(item),
|
||||
source: 'kitinerary',
|
||||
checksJson: null,
|
||||
uncertainFields: null,
|
||||
matchJson: null,
|
||||
suggestedTripId: s.trip.id,
|
||||
dedupeKey: null,
|
||||
contentHash: null,
|
||||
createdAt: dbNow(now),
|
||||
};
|
||||
if (!added) {
|
||||
return em
|
||||
.getRepository(MailIngestCandidates)
|
||||
.insertCandidate({ ...entry, resolution: 'pending', reason: 'ask_first' });
|
||||
}
|
||||
const trips = app.get(MailIngestTripsService);
|
||||
const person = await trips.person(s.owner.id);
|
||||
const trip = person ? await trips.editableTrip(person, s.trip.id) : null;
|
||||
if (!trip) throw new Error(`the owner of scene ${s.n} cannot add bookings to its trip`);
|
||||
const apply = app.get(MailIngestApplyService);
|
||||
// test-sql-allow: MailIngestApplyService.prepare builds the booking to write, it is no SQL statement.
|
||||
const prepared = await apply.prepare(item, trip, s.owner.id, []);
|
||||
const written = await app.get(UnitOfWork).transactional(() => apply.writeInTx(prepared));
|
||||
return em.getRepository(MailIngestCandidates).insertCandidate({
|
||||
...entry,
|
||||
resolution: 'applied',
|
||||
reason: null,
|
||||
resolvedTripId: s.trip.id,
|
||||
createdIdsJson: JSON.stringify(written.created),
|
||||
resolvedAt: dbNow(now),
|
||||
undoUntil: dbNow(new Date(now.getTime() + UNDO_WINDOW_DAYS * DAY_MS)),
|
||||
});
|
||||
});
|
||||
mailEntryOf.set(s.n, id);
|
||||
}
|
||||
|
||||
const waitingMail = (s: Scene, app: INestApplication) => mailEntryFor(s, app, false);
|
||||
const addedMail = (s: Scene, app: INestApplication) => mailEntryFor(s, app, true);
|
||||
|
||||
/**
|
||||
* The person's inbox count, sent to every one of their sockets (the asking
|
||||
* tab included, on REST too): each action on an entry changes what waits.
|
||||
*/
|
||||
const INBOX_CHANGED = { event: 'mailInbox:changed', user: 'actor', all: true } as const;
|
||||
|
||||
export const bookings: CaseGroup = {
|
||||
name: 'bookings',
|
||||
prefix: 'BCP-BOOK',
|
||||
@@ -358,6 +496,71 @@ export const bookings: CaseGroup = {
|
||||
settle: true,
|
||||
expect: ['reservation:created', BOOKING_NOTICE],
|
||||
},
|
||||
|
||||
// -- The booking mail import ----------------------------------------------
|
||||
// A booking from a mail is announced once its write committed, to every
|
||||
// socket of the trip, the asking tab included: the same announcement the
|
||||
// import makes when it adds a booking with no tab asking at all.
|
||||
{
|
||||
// The booking, the mail as its document, and the inbox that shrank.
|
||||
tool: 'add_mail_booking',
|
||||
setup: waitingMail,
|
||||
args: (s) => ({ candidateId: mailEntry(s) }),
|
||||
rest: { method: 'post', path: (s) => mailPath(s, 'apply'), body: () => ({}) },
|
||||
expect: [{ event: 'reservation:created', all: true }, { event: 'file:created', all: true }, INBOX_CHANGED],
|
||||
},
|
||||
{
|
||||
// Out of the scene's trip into the owner's other trip in the booking's dates, its mail with it.
|
||||
tool: 'move_mail_booking',
|
||||
setup: async (s, app) => {
|
||||
await addedMail(s, app);
|
||||
const target = await makeTrip(orm(app), s.owner.id, {
|
||||
title: `Elsewhere ${s.n}`,
|
||||
start_date: dayFromToday(28),
|
||||
end_date: dayFromToday(32),
|
||||
});
|
||||
moveTargetOf.set(s.n, target.id);
|
||||
},
|
||||
args: (s) => ({ candidateId: mailEntry(s), trip_id: moveTarget(s) }),
|
||||
rest: { method: 'post', path: (s) => mailPath(s, 'move'), body: (s) => ({ trip_id: moveTarget(s) }) },
|
||||
expect: [
|
||||
{ event: 'reservation:deleted', all: true },
|
||||
{ event: 'reservation:created', all: true, room: moveTarget },
|
||||
{ event: 'file:created', all: true, room: moveTarget },
|
||||
INBOX_CHANGED,
|
||||
],
|
||||
},
|
||||
{
|
||||
tool: 'file_mail_booking',
|
||||
setup: waitingMail,
|
||||
args: (s) => ({ candidateId: mailEntry(s), trip_id: s.trip.id }),
|
||||
rest: { method: 'post', path: (s) => mailPath(s, 'file'), body: (s) => ({ trip_id: s.trip.id }) },
|
||||
expect: [{ event: 'file:created', all: true }, INBOX_CHANGED],
|
||||
},
|
||||
{
|
||||
tool: 'discard_mail_booking',
|
||||
setup: waitingMail,
|
||||
args: (s) => ({ candidateId: mailEntry(s) }),
|
||||
rest: { method: 'post', path: (s) => mailPath(s, 'discard') },
|
||||
expect: [INBOX_CHANGED],
|
||||
},
|
||||
{
|
||||
tool: 'undo_mail_booking',
|
||||
setup: addedMail,
|
||||
args: (s) => ({ candidateId: mailEntry(s) }),
|
||||
rest: { method: 'post', path: (s) => mailPath(s, 'undo'), body: () => ({}) },
|
||||
expect: [{ event: 'reservation:deleted', all: true }, INBOX_CHANGED],
|
||||
},
|
||||
{
|
||||
// The person's other tabs read their settings card again.
|
||||
tool: 'update_mail_import_settings',
|
||||
setup: async (_s, app) => {
|
||||
await setAppSetting(orm(app), 'mail_ingest_enabled', 'true');
|
||||
},
|
||||
args: () => ({ auto_add: false }),
|
||||
rest: { method: 'patch', path: () => '/api/mail-ingest/settings', body: () => ({ auto_add: false }) },
|
||||
expect: [{ event: 'mailInbox:settings', user: 'actor', all: true }],
|
||||
},
|
||||
],
|
||||
exempt: [],
|
||||
};
|
||||
|
||||
@@ -223,6 +223,34 @@ export const collabTrip: CaseGroup = {
|
||||
},
|
||||
expect: ['collab:message:reacted'],
|
||||
},
|
||||
{
|
||||
tool: 'create_collab_link',
|
||||
args: (s) => ({ tripId: s.trip.id, title: 'Ferry', url: 'https://example.com/ferry' }),
|
||||
rest: {
|
||||
method: 'post',
|
||||
path: (s) => tripPath(s, '/collab/links'),
|
||||
body: () => ({ title: 'Ferry', url: 'https://example.com/ferry' }),
|
||||
},
|
||||
expect: ['collab:link:created'],
|
||||
},
|
||||
{
|
||||
tool: 'update_collab_link',
|
||||
needs: ['collabLink'],
|
||||
args: (s) => ({ tripId: s.trip.id, linkId: s.collabLink.id, pinned: true }),
|
||||
rest: {
|
||||
method: 'put',
|
||||
path: (s) => tripPath(s, `/collab/links/${s.collabLink.id}`),
|
||||
body: () => ({ pinned: true }),
|
||||
},
|
||||
expect: ['collab:link:updated'],
|
||||
},
|
||||
{
|
||||
tool: 'delete_collab_link',
|
||||
needs: ['collabLink'],
|
||||
args: (s) => ({ tripId: s.trip.id, linkId: s.collabLink.id }),
|
||||
rest: { method: 'delete', path: (s) => tripPath(s, `/collab/links/${s.collabLink.id}`) },
|
||||
expect: ['collab:link:deleted'],
|
||||
},
|
||||
|
||||
// ── Files and the document store ──────────────────────────────────────
|
||||
{
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { ADDON_IDS } from '../../../src/addons';
|
||||
import { buildApp } from '../../../src/bootstrap';
|
||||
import { BudgetSettlements } from '../../../src/db/entities/BudgetSettlements.entity';
|
||||
import { CollabLinks } from '../../../src/db/entities/CollabLinks.entity';
|
||||
import { CollabPolls } from '../../../src/db/entities/CollabPolls.entity';
|
||||
import { DayAccommodations } from '../../../src/db/entities/DayAccommodations.entity';
|
||||
import { PackingTemplateCategories } from '../../../src/db/entities/PackingTemplateCategories.entity';
|
||||
@@ -220,7 +221,9 @@ export async function openHarness(): Promise<ParityHarness> {
|
||||
await app.init();
|
||||
const orm = app.get(MikroORM);
|
||||
await oneByOne(Object.values(ADDON_IDS), (addon) => setAddonEnabled(orm, addon, true));
|
||||
await oneByOne(['chat', 'notes', 'polls', 'whatsnext'] as const, (feature) => setCollabFeature(orm, feature, true));
|
||||
await oneByOne(['chat', 'notes', 'polls', 'links', 'whatsnext'] as const, (feature) =>
|
||||
setCollabFeature(orm, feature, true),
|
||||
);
|
||||
// The wanderer tools show only while wanderer is allowed under Tours.
|
||||
await setAppSetting(orm, 'tours_wanderer_enabled', 'true');
|
||||
// The photo search tools show only while a provider is on.
|
||||
@@ -319,6 +322,7 @@ export const NEED_KEYS: Record<Need, readonly (keyof Scene)[]> = {
|
||||
collabNote: ['collabNote'],
|
||||
collabMessage: ['collabMessage'],
|
||||
poll: ['poll'],
|
||||
collabLink: ['collabLink'],
|
||||
file: ['file'],
|
||||
collection: ['collection', 'collectionPlace'],
|
||||
journey: ['journey', 'journeyEntry'],
|
||||
@@ -443,6 +447,15 @@ const BUILDERS: Record<Need, Builder> = {
|
||||
});
|
||||
s.poll = { id: row.id };
|
||||
},
|
||||
async collabLink(s, _app, orm) {
|
||||
const id = await insertRow(orm, CollabLinks, {
|
||||
trip: s.trip.id,
|
||||
user: s.owner.id,
|
||||
title: `Ferry ${s.n}`,
|
||||
url: 'https://example.com/ferry',
|
||||
});
|
||||
s.collabLink = { id };
|
||||
},
|
||||
async file(s, _app, orm) {
|
||||
s.file = await makeTripFile(orm, s.trip.id);
|
||||
},
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { ListImportResult } from '../../../src/nest/places/places.helpers';
|
||||
import { PlacesService } from '../../../src/nest/places/places.service';
|
||||
import { StorageService } from '../../../src/nest/storage/storage.service';
|
||||
import { makeDayAssignment } from '../../helpers/factories/itinerary';
|
||||
import { makeTag } from '../../helpers/factories/places';
|
||||
import { insertRow, updateRows } from '../../helpers/factories/rows';
|
||||
import type { CaseGroup, Scene } from './types';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
@@ -22,6 +23,8 @@ const dayPlanPath = (s: Scene, day: 0 | 1 | 2) => `/api/trips/${s.trip.id}/days/
|
||||
/** The per-assignment routes of the scene's assignment. */
|
||||
const assignmentPath = (s: Scene) => `/api/trips/${s.trip.id}/assignments/${s.assignment.id}`;
|
||||
const dayNotesPath = (s: Scene) => `/api/trips/${s.trip.id}/days/${s.days[0].id}/notes`;
|
||||
/** The tags the scene's trip owns. */
|
||||
const tripTagsPath = (s: Scene) => `/api/trips/${s.trip.id}/tags`;
|
||||
const onAssignment = (s: Scene) => ({ tripId: s.trip.id, assignmentId: s.assignment.id });
|
||||
|
||||
/** One waypoint, the smallest file the importer turns into a place. */
|
||||
@@ -88,9 +91,24 @@ async function boundaryOnSecondDay(s: Scene, app: INestApplication): Promise<voi
|
||||
});
|
||||
}
|
||||
|
||||
/** The tag a setup gave a scene's trip, by the scene's number. */
|
||||
const tripTagOf = new Map<number, number>();
|
||||
|
||||
/** A tag of the scene's trip, for the cases that rename or delete one. */
|
||||
async function tripTag(s: Scene, app: INestApplication): Promise<void> {
|
||||
const tag = await makeTag(app.get(MikroORM), s.owner.id, { trip: s.trip.id, name: 'Monument' });
|
||||
tripTagOf.set(s.n, tag.id);
|
||||
}
|
||||
|
||||
const tripTagId = (s: Scene): number => {
|
||||
const id = tripTagOf.get(s.n);
|
||||
if (id === undefined) throw new Error(`scene ${s.n} has no trip tag from its setup`);
|
||||
return id;
|
||||
};
|
||||
|
||||
/**
|
||||
* The planner: places, the day plan, days, day notes, categories, and the
|
||||
* collection places copied into a trip.
|
||||
* The planner: places and the tags their trip owns, the day plan, days, day
|
||||
* notes, categories, and the collection places copied into a trip.
|
||||
*/
|
||||
export const plan: CaseGroup = {
|
||||
name: 'plan',
|
||||
@@ -213,6 +231,30 @@ export const plan: CaseGroup = {
|
||||
},
|
||||
expect: ['place:updated', 'place:updated'],
|
||||
},
|
||||
{
|
||||
tool: 'create_trip_tag',
|
||||
args: (s) => ({ tripId: s.trip.id, name: 'Monument' }),
|
||||
rest: { method: 'post', path: tripTagsPath, body: () => ({ name: 'Monument' }) },
|
||||
expect: ['tripTags:changed'],
|
||||
},
|
||||
{
|
||||
tool: 'update_trip_tag',
|
||||
setup: tripTag,
|
||||
args: (s) => ({ tripId: s.trip.id, tagId: tripTagId(s), name: 'Landmark' }),
|
||||
rest: {
|
||||
method: 'put',
|
||||
path: (s) => `${tripTagsPath(s)}/${tripTagId(s)}`,
|
||||
body: () => ({ name: 'Landmark' }),
|
||||
},
|
||||
expect: ['tripTags:changed'],
|
||||
},
|
||||
{
|
||||
tool: 'delete_trip_tag',
|
||||
setup: tripTag,
|
||||
args: (s) => ({ tripId: s.trip.id, tagId: tripTagId(s) }),
|
||||
rest: { method: 'delete', path: (s) => `${tripTagsPath(s)}/${tripTagId(s)}` },
|
||||
expect: ['tripTags:changed'],
|
||||
},
|
||||
{
|
||||
tool: 'assign_place_to_day',
|
||||
needs: ['place'],
|
||||
@@ -227,6 +269,13 @@ export const plan: CaseGroup = {
|
||||
rest: { method: 'put', path: (s) => `${assignmentPath(s)}/end-day`, body: () => ({ end_day: true }) },
|
||||
expect: ['assignment:updated'],
|
||||
},
|
||||
{
|
||||
tool: 'set_assignment_stay',
|
||||
needs: ['assignment'],
|
||||
args: (s) => ({ ...onAssignment(s), stay_minutes: 15 }),
|
||||
rest: { method: 'put', path: (s) => `${assignmentPath(s)}/stay`, body: () => ({ stay_minutes: 15 }) },
|
||||
expect: ['assignment:updated'],
|
||||
},
|
||||
{
|
||||
tool: 'unassign_place',
|
||||
needs: ['assignment'],
|
||||
|
||||
@@ -40,6 +40,8 @@ interface Wanted {
|
||||
only: Partial<Record<Surface, Receivers>>;
|
||||
/** The surfaces limit it differently on purpose, so their receivers are not compared. */
|
||||
onlyDiffers: boolean;
|
||||
/** The trip room of this send, when it is not the case's. */
|
||||
room?: (s: Scene) => number;
|
||||
}
|
||||
|
||||
function wanted(e: Expect): Wanted {
|
||||
@@ -53,7 +55,14 @@ function wanted(e: Expect): Wanted {
|
||||
: typeof e.only === 'string'
|
||||
? { MCP: e.only, REST: e.only }
|
||||
: { MCP: e.only.mcp, REST: e.only.rest };
|
||||
return { channel: 'trip', event: e.event, all: e.all === true, only, onlyDiffers: only.MCP !== only.REST };
|
||||
return {
|
||||
channel: 'trip',
|
||||
event: e.event,
|
||||
all: e.all === true,
|
||||
only,
|
||||
onlyDiffers: only.MCP !== only.REST,
|
||||
room: e.room,
|
||||
};
|
||||
}
|
||||
|
||||
const signature = (r: { channel: string; event: string }) => `${r.channel} ${r.event}`;
|
||||
@@ -129,7 +138,7 @@ function checkSurface(surface: Surface, c: ParityCase, records: Recorded[], s: S
|
||||
);
|
||||
if (want.user === 'others') return;
|
||||
} else {
|
||||
expect(Number(r.to[0]), `sent to another room than the trip's: ${where}`).toBe(room);
|
||||
expect(Number(r.to[0]), `sent to another room than the trip's: ${where}`).toBe(want.room?.(s) ?? room);
|
||||
checkLimit(want.only[surface], r, actorId, where);
|
||||
}
|
||||
const skips = surface === 'MCP' || want.all ? undefined : REST_SOCKET;
|
||||
|
||||
@@ -36,6 +36,7 @@ export type Need =
|
||||
| 'collabNote'
|
||||
| 'collabMessage'
|
||||
| 'poll'
|
||||
| 'collabLink'
|
||||
| 'file'
|
||||
| 'guest'
|
||||
| 'member'
|
||||
@@ -100,6 +101,8 @@ export interface Scene {
|
||||
collabMessage: CollabMessageRow;
|
||||
/** Two options, open. */
|
||||
poll: IdRow;
|
||||
/** A shared link on the trip's Links panel, saved by the owner. */
|
||||
collabLink: IdRow;
|
||||
file: TripFileRow;
|
||||
/** A guest (no account) on the trip. */
|
||||
guest: UserRow;
|
||||
@@ -149,10 +152,17 @@ export type Receivers = 'actor' | 'viewers';
|
||||
* - `{ event, user }`: to users' own sockets (`broadcastToUser`). `actor` means
|
||||
* the writer is among the receivers (REST leaves out the requesting socket
|
||||
* unless `all` is set too), `others` that only other users receive it.
|
||||
* - `{ event, room }`: to another trip room than the case's, for a write that
|
||||
* touches two trips (a booking moved from one trip into another).
|
||||
*/
|
||||
export type Expect =
|
||||
| TrekWsTripEventName
|
||||
| { event: TrekWsTripEventName; all?: true; only?: Receivers | { rest: Receivers; mcp: Receivers } }
|
||||
| {
|
||||
event: TrekWsTripEventName;
|
||||
all?: true;
|
||||
only?: Receivers | { rest: Receivers; mcp: Receivers };
|
||||
room?: (s: Scene) => number;
|
||||
}
|
||||
| { event: TrekWsUserEventName; user: 'actor' | 'others'; all?: true };
|
||||
|
||||
/** The REST twin of a tool, called as the same user with X-Socket-Id 'sock-rest'. */
|
||||
|
||||
@@ -245,6 +245,49 @@ describe('Three-tier packing sharing (#858)', () => {
|
||||
expect(res.body.item.contributors.map((c: any) => c.user_id)).toContain(helper.id);
|
||||
});
|
||||
|
||||
it('PACK-3T-004b — a member puts someone else down as the bringer, and takes the owner off again (#3098)', async () => {
|
||||
const { user: owner } = createUser(testDb);
|
||||
const { user: helper } = createUser(testDb);
|
||||
const { user: stranger } = createUser(testDb);
|
||||
const trip = createTrip(testDb, owner.id);
|
||||
addTripMember(testDb, trip.id, helper.id);
|
||||
const created = await request(app)
|
||||
.post(`/api/trips/${trip.id}/packing`)
|
||||
.set('Cookie', authCookie(owner.id))
|
||||
.send({ name: 'Stove', visibility: 'personal' });
|
||||
const id = created.body.item.id;
|
||||
await request(app)
|
||||
.put(`/api/trips/${trip.id}/packing/${id}/sharing`)
|
||||
.set('Cookie', authCookie(owner.id))
|
||||
.send({ visibility: 'common' });
|
||||
|
||||
const assigned = await request(app)
|
||||
.post(`/api/trips/${trip.id}/packing/${id}/contributors`)
|
||||
.set('Cookie', authCookie(owner.id))
|
||||
.send({ user_id: helper.id });
|
||||
expect(assigned.status).toBe(201);
|
||||
expect(assigned.body.item.contributors.map((c: { user_id: number }) => c.user_id)).toEqual([helper.id]);
|
||||
|
||||
const outsider = await request(app)
|
||||
.post(`/api/trips/${trip.id}/packing/${id}/contributors`)
|
||||
.set('Cookie', authCookie(owner.id))
|
||||
.send({ user_id: stranger.id });
|
||||
expect(outsider.status).toBe(404);
|
||||
|
||||
const bad = await request(app)
|
||||
.post(`/api/trips/${trip.id}/packing/${id}/contributors`)
|
||||
.set('Cookie', authCookie(owner.id))
|
||||
.send({ user_id: 'x' });
|
||||
expect(bad.status).toBe(400);
|
||||
|
||||
const ownerOff = await request(app)
|
||||
.delete(`/api/trips/${trip.id}/packing/${id}/contributors/${owner.id}`)
|
||||
.set('Cookie', authCookie(helper.id));
|
||||
expect(ownerOff.status).toBe(200);
|
||||
expect(ownerOff.body.item.owner_id).toBeNull();
|
||||
expect(ownerOff.body.item.contributors.map((c: { user_id: number }) => c.user_id)).toEqual([helper.id]);
|
||||
});
|
||||
|
||||
it('PACK-3T-005 — sharing can only be changed by the owner', async () => {
|
||||
const { user: owner } = createUser(testDb);
|
||||
const { user: member } = createUser(testDb);
|
||||
|
||||
@@ -1059,6 +1059,8 @@ describe('Copy trip with data', () => {
|
||||
place: place.id,
|
||||
order_index: 0,
|
||||
notes: 'Visit in morning',
|
||||
// #3092: the visit's own stay, apart from the place's duration
|
||||
stay_minutes: 90,
|
||||
});
|
||||
|
||||
// Accommodation spanning days 0→1
|
||||
@@ -1103,6 +1105,7 @@ describe('Copy trip with data', () => {
|
||||
// Assignment copied
|
||||
const newAssignments = await findRows(orm, DayAssignments, { day: { trip: newId } });
|
||||
expect(newAssignments).toHaveLength(1);
|
||||
expect(newAssignments[0].stay_minutes).toBe(90);
|
||||
|
||||
// Accommodation copied
|
||||
const newAccom = await findRows(orm, DayAccommodations, { trip: newId });
|
||||
|
||||
@@ -28,7 +28,16 @@ vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve([{ date: '2025-01-01', name: "New Year's Day", countryCode: 'DE' }]),
|
||||
json: () =>
|
||||
Promise.resolve([
|
||||
{
|
||||
date: '2025-01-01',
|
||||
name: "New Year's Day",
|
||||
countryCode: 'DE',
|
||||
nationalHoliday: true,
|
||||
subdivisionCodes: null,
|
||||
},
|
||||
]),
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -448,17 +457,6 @@ describe('Vacay stats restrictions', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('Vacay holidays error path', () => {
|
||||
it('VACAY-035 — GET /holidays/:year/:country returns 502 when external API fetch fails', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
// Use an unusual country/year to avoid cache hits from other tests
|
||||
vi.mocked(global.fetch as any).mockRejectedValueOnce(new Error('Network error'));
|
||||
|
||||
const res = await request(app).get('/api/addons/vacay/holidays/2099/ZZ').set('Cookie', authCookie(user.id));
|
||||
expect(res.status).toBe(502);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Vacay color restriction', () => {
|
||||
it('VACAY-036 — PUT /color with target_user_id not in plan returns 403', async () => {
|
||||
const { user: owner } = createUser(testDb);
|
||||
@@ -473,20 +471,6 @@ describe('Vacay color restriction', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('Vacay holidays success path', () => {
|
||||
it('VACAY-037 — GET /holidays/:year/:country returns data when fetch succeeds', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
// Use unique year/country to avoid cache from other tests
|
||||
vi.mocked(global.fetch as any).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve([{ date: '2025-05-01', name: 'Labour Day', countryCode: 'AT' }]),
|
||||
});
|
||||
|
||||
const res = await request(app).get('/api/addons/vacay/holidays/2025/AT').set('Cookie', authCookie(user.id));
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Vacay toggle entry for plan member', () => {
|
||||
it('VACAY-038 — POST /entries/toggle with target_user_id in plan toggles their entry', async () => {
|
||||
const { user: owner } = createUser(testDb);
|
||||
@@ -647,3 +631,41 @@ describe('Vacay read-only calendar shares', () => {
|
||||
expect(res.body.error).toBe('Already shared');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Vacay public holidays', () => {
|
||||
it('VACAY-035 — returns 502 when the external API fetch fails', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
vi.mocked(global.fetch as any).mockRejectedValueOnce(new Error('Network error'));
|
||||
|
||||
const res = await request(app).get('/api/addons/vacay/holidays/2099/ZZ').set('Cookie', authCookie(user.id));
|
||||
expect(res.status).toBe(502);
|
||||
});
|
||||
|
||||
it('VACAY-037 — adapts a Nager v4 record when the external API succeeds', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
vi.mocked(global.fetch as any).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () =>
|
||||
Promise.resolve([
|
||||
{
|
||||
date: '2025-05-01',
|
||||
name: 'Labour Day',
|
||||
nationalHoliday: true,
|
||||
subdivisionCodes: null,
|
||||
},
|
||||
]),
|
||||
});
|
||||
|
||||
const res = await request(app).get('/api/addons/vacay/holidays/2087/AT').set('Cookie', authCookie(user.id));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual([
|
||||
{
|
||||
date: '2025-05-01',
|
||||
name: 'Labour Day',
|
||||
localName: 'Labour Day',
|
||||
global: true,
|
||||
counties: null,
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user