diff --git a/README.md b/README.md index d735560..51b89f1 100644 --- a/README.md +++ b/README.md @@ -204,7 +204,7 @@ Every command supports `--json` for piping into `jq` or Claude. | Command | Description | |---|---| | `mna trips list [--status=planning\|ready\|finished\|cancelled] [--include-example]` | List trips. | -| `mna trips show [--all-options]` | Show one trip in detail, with an accommodation table per variant (cost, guest rating in its source scale, facilities). `--all-options` adds the unselected options. | +| `mna trips show [--all-options]` | Show one trip in detail: each variant's party, plus an accommodation table per variant (cost, guest rating in its source scale, facilities). By default only the selected variant and its selected options; `--all-options` adds the unselected variants and options. | | `mna trips create --name [--cover-photo ]` | Create a new trip. | | `mna trips edit [--name=...] [--cover-photo=...] [--status=...]` | Update trip-level fields. | | `mna trips delete [--yes]` | Delete a trip permanently. | @@ -215,9 +215,9 @@ Every command supports `--json` for piping into `jq` or Claude. | Command | Description | |---|---| -| `mna variants add --name [--notes=...]` | Add a new variant. Dates are required — see below. | -| `mna variants duplicate ` | Duplicate a variant. | -| `mna variants edit [--name=...] [--notes=...] []` | Update variant fields. Omitting the date flags leaves the dates alone. | +| `mna variants add --name [] [--notes=...]` | Add a new variant. Dates are required, and the party defaults to one adult — see below. | +| `mna variants duplicate ` | Duplicate a variant, party included. | +| `mna variants edit [--name=...] [--notes=...] [] []` | Update variant fields. Omitting the date or party flags leaves those alone. | | `mna variants select ` | Set the selected variant. | | `mna variants delete [--yes]` | Delete a variant. | @@ -235,6 +235,26 @@ mna variants add --name "Flexible option" \ --min-nights 7 --max-nights 10 ``` +A variant also records who is travelling, and the budget breakdown is worked out from it. **Set it +whenever the trip is not solo:** a variant created without it is stored as one adult. + +- `--adults=` — at least 1. +- `--child-ages=` — one age per child, 0–17, comma-separated or repeated. Requires `--adults` on `add`. +- `--no-children` — an adults-only party; on `edit`, removes any children already set. + +```bash +mna variants add --name "Family option" --start-date 2026-09-01 --end-date 2026-09-08 \ + --adults 2 --child-ages 8,5 +mna variants edit --adults 3 # keeps the children +mna variants edit --child-ages 8,5,2 # keeps the adults +mna variants edit --no-children +``` + +The API replaces the whole party on every write, so `variants edit` reads the current one first and +changes only what you named. Leave the flags off and the party stays untouched. `variants duplicate` +copies the party along with everything else. To see it, `mna trips show` has a Party column for the +selected variant; add `--all-options` to include the other variants. + ### Destinations | Command | Description | @@ -311,7 +331,7 @@ mna variants add --name "Flexible option" \ All command groups (auth/keys/config, trips, variants, destinations, options, events, access, vote/votes, goals, collections) are wired, CI-tested, and backed by live `/v1/` endpoints in production. Pre-1.0 means the public API contract is still allowed to break under `/v1/`. Once `1.0.0` ships, `/v1/` becomes stable; breaking changes require `/v2/`. -The contract of record is `https://api.mynextadventure.cloud/v1/openapi.json`. If a write seems to "succeed" but a field doesn't stick, re-fetch with `mna trips show --json` to confirm — and check the request body shape against the OpenAPI schema for that endpoint. +The contract of record is `https://api.mynextadventure.cloud/v1/openapi.json`. If a write seems to "succeed" but a field doesn't stick, re-fetch with `mna trips show --all-options --json` to confirm — and check the request body shape against the OpenAPI schema for that endpoint. ## Configuration diff --git a/skills/mna/SKILL.md b/skills/mna/SKILL.md index fd4d96f..5f5de13 100644 --- a/skills/mna/SKILL.md +++ b/skills/mna/SKILL.md @@ -49,7 +49,7 @@ Before any research, establish: - **Anchors** — the fixed points nothing else can move: a booked flight, an event date, a pickup, a hard return-by date. - **Party** — who travels, which legs (trips can split), and children's ages, which change room - eligibility and price. + eligibility and price. Every variant stores this party (see step 3). - **Dates** — exact if known, otherwise a window plus a night count. - **Budget and home currency** — the ceiling, and the currency every total gets presented in. Never infer it from the destination or carry it over from a previous trip. @@ -89,7 +89,7 @@ Build what the user agreed to, one level at a time: | Level | Command | Notes | |---|---|---| | trip | `mna trips create --name "…"` | the container | -| variant | `mna variants add --name "…" --start-date --end-date `, or `variants duplicate ` | a whole-trip **strategy** ("single base" vs "stopover + base"), not a tweak. Dates are required — exact, or the six flexible-date flags (see reference). Fork a baseline, then diverge. | +| variant | `mna variants add --name "…" --start-date --end-date --adults [--child-ages ]`, or `variants duplicate ` | a whole-trip **strategy** ("single base" vs "stopover + base"), not a tweak. Dates are required — exact, or the six flexible-date flags (see reference). **Always pass the party:** without it the variant is stored as one adult and its budget breakdown comes out wrong, with no error. Fork a baseline, then diverge; a duplicate keeps the party. | | destination | `mna destinations add --place "" --start-date --end-date ` | in travel order; `--return-to-home` marks the home leg; `destinations reorder … --order=k1,k2,k3` fixes order | | option | `mna options add --from-json `, then `mna options select …` | `` = `accommodation` \| `transport` \| `getting-around` | | event | `mna events add --from-json ` | only if the user wants them — the app is not a day-by-day itinerary planner, and many users don't want one | @@ -101,7 +101,7 @@ and break a long drive with a stopover. Attach each transport leg to the destina Set real data, not placeholders: exact coordinates on each option's `location`, per-destination dates, check-in/out, `--free-cancellation-until` on accommodation. Replace stale options rather than piling new ones on top. Write responses are thin — **re-fetch -`mna trips show --json`** and confirm the field you set actually persisted. +`mna trips show --all-options --json`** and confirm the field you set actually persisted. Without `--all-options` only the selected variant comes back, so a newly added one looks missing. ### 4. Compare end-to-end diff --git a/skills/mna/references/cli-and-schemas.md b/skills/mna/references/cli-and-schemas.md index a7a14f3..0c967aa 100644 --- a/skills/mna/references/cli-and-schemas.md +++ b/skills/mna/references/cli-and-schemas.md @@ -8,8 +8,8 @@ the field shapes you can't guess. Examples below use neutral placeholders. ``` trips list | show [--all-options] | create --name | edit | delete | share | unshare -variants add --name [--notes] | duplicate - edit [--name --notes ] | select | delete +variants add --name [--adults --child-ages --no-children --notes] | duplicate + edit [--name --notes --adults --child-ages --no-children] | select | delete destinations add --place [--start-date --end-date --notes --return-to-home] edit [--place --notes --start-date --end-date --return-to-home/--no-…] reorder --order=k1,k2,k3 | delete @@ -143,11 +143,42 @@ mna variants add --name "Flexible option" \ `variants edit` takes the same flags; leave them off and the existing dates stay untouched. Switching a variant between the two shapes is just an edit with the other flag set. +## Variant party — set it on create + +Each variant stores who is travelling, and its budget breakdown is worked out from that. Omit it +on `variants add` and the variant is silently stored as **one adult**, so always pass the party the +user gave you: + +```bash +mna variants add --name "Family option" --start-date 2026-09-01 --end-date 2026-09-08 \ + --adults 2 --child-ages 8,5 +mna variants add --name "Couple option" --start-date 2026-09-01 --end-date 2026-09-08 --adults 2 +``` + +- `--adults` — whole number, at least 1. +- `--child-ages` — one age per child, a whole number from 0 to 17 at the time of the trip; anyone + older counts as an adult. Comma-separated (`8,5`) or repeated. Needs `--adults` on `add`. +- `--no-children` — adults only. On `edit`, this is how to remove children. + +To correct a variant, use `variants edit` with only the flags that changed: + +```bash +mna variants edit --adults 3 +mna variants edit --child-ages 8,5,2 +mna variants edit --no-children +``` + +The API's `participants` field replaces the whole party, so the CLI reads the current one and merges +your change; children, adults and any stored room count you didn't name survive. With no party flag +it isn't sent at all. `variants duplicate` copies the party. If a raw API body is ever needed, send +the complete `{ adults, children: [{ age }], numberOfRooms? }`, without the `_id`s a read returns. + ## Verify-after-write Mutation responses are intentionally thin (often just the new key). Confirm the state with -`mna trips show --json` and parse the field you changed. This is the reliable way to -catch a silently-dropped field or an accidental duplicate create. +`mna trips show --all-options --json` and parse the field you changed. This is the reliable way to +catch a silently-dropped field or an accidental duplicate create. Without `--all-options` the read +returns only the selected variant, so a newly added or unselected one looks missing. ## Auth / config diff --git a/src/commands/trips/show.test.ts b/src/commands/trips/show.test.ts new file mode 100644 index 0000000..8524781 --- /dev/null +++ b/src/commands/trips/show.test.ts @@ -0,0 +1,48 @@ +import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test' +import { tripsShowCommand } from './show' + +type RunFn = (ctx: { args: Record }) => Promise +const run = (args: Record) => (tripsShowCommand.run as unknown as RunFn)({ args }) + +let originalFetch: typeof fetch +let originalKey: string | undefined + +beforeEach(() => { + originalFetch = global.fetch + originalKey = process.env.MNA_API_KEY + process.env.MNA_API_KEY = 'mna_test' + global.fetch = (async () => + Response.json({ + id: 't', + name: 'Trip', + status: 'planning', + variants: [ + { + id: 'v', + name: 'Family', + participants: { adults: 2, children: [{ age: 10 }, { age: 7 }] }, + destinations: [], + eventsToAttend: [], + }, + ], + })) as unknown as typeof fetch +}) + +afterEach(() => { + global.fetch = originalFetch + process.env.MNA_API_KEY = originalKey + if (originalKey === undefined) Reflect.deleteProperty(process.env, 'MNA_API_KEY') +}) + +describe('trips show', () => { + test("prints each variant's party", async () => { + const stdout = spyOn(process.stdout, 'write').mockImplementation(() => true) + + await run({ tripId: 't', 'all-options': false, json: false }) + + const printed = stdout.mock.calls.map(([chunk]) => String(chunk)).join('') + stdout.mockRestore() + expect(printed).toContain('Party') + expect(printed).toContain('2 adults, 2 children (10, 7)') + }) +}) diff --git a/src/commands/trips/show.ts b/src/commands/trips/show.ts index 459f51d..a919257 100644 --- a/src/commands/trips/show.ts +++ b/src/commands/trips/show.ts @@ -5,6 +5,7 @@ import { renderJson } from '../../render/json' import { renderTable } from '../../render/table' import { accommodationRows } from '../../render/accommodation' import { colors } from '../../render/colors' +import { formatParty } from '../../render/party' import { reportAndExit, requireApiKey } from '../../util/errors' export const tripsShowCommand = defineCommand({ @@ -61,12 +62,14 @@ export const tripsShowCommand = defineCommand({ renderTable({ columns: [ { header: 'Variant', key: 'name', maxWidth: 30 }, + { header: 'Party', key: 'party' }, { header: 'Destinations', key: 'destinationsCount' }, { header: 'Events', key: 'eventsCount' }, ], rows: data.variants?.map((v) => ({ name: v.name, + party: formatParty(v.participants), destinationsCount: v.destinations?.length ?? 0, eventsCount: v.eventsToAttend?.length ?? 0, })) ?? [], diff --git a/src/commands/variants/add.ts b/src/commands/variants/add.ts index 8b144a9..d049dd8 100644 --- a/src/commands/variants/add.ts +++ b/src/commands/variants/add.ts @@ -3,8 +3,12 @@ import { createApiClient } from '../../api/client' import { loadCredentials, resolveApiKey, resolveBaseUrl } from '../../auth/credentials-store' import { renderJson } from '../../render/json' import { colors } from '../../render/colors' +import { formatParty } from '../../render/party' import { reportAndExit, requireApiKey } from '../../util/errors' import { requireVariantDates, variantDateArgs } from './dates' +import { parsePartyChange, participantsForNewVariant, variantPartyArgs } from './party' + +const POSITIONAL_COUNT = 1 export const variantsAddCommand = defineCommand({ meta: { name: 'add', description: 'Add a new variant to a trip.' }, @@ -13,11 +17,13 @@ export const variantsAddCommand = defineCommand({ name: { type: 'string', required: true, description: 'Variant name.' }, notes: { type: 'string', description: 'Free-form variant notes.' }, ...variantDateArgs, + ...variantPartyArgs, json: { type: 'boolean', default: false, description: 'Output as JSON.' }, }, async run({ args }) { try { const dates = requireVariantDates(args) + const participants = participantsForNewVariant(parsePartyChange(args, POSITIONAL_COUNT)) const creds = await loadCredentials() const apiKey = resolveApiKey(creds) @@ -26,6 +32,7 @@ export const variantsAddCommand = defineCommand({ const body: Record = { name: args.name, dates } if (args.notes !== undefined) body.notes = args.notes + if (participants !== undefined) body.participants = participants const { data, error } = await client.POST('/v1/trips/{id}/variants', { params: { path: { id: args.tripId } }, @@ -35,12 +42,18 @@ export const variantsAddCommand = defineCommand({ const created = data as unknown as { id?: string; name?: string } | undefined + if (participants === undefined) { + process.stderr.write( + colors.dim('No party given, so this variant is for 1 adult. Use --adults and --child-ages to change it.\n'), + ) + } if (args.json) { renderJson(created) } else { process.stdout.write( `${colors.green('✓')} Added variant ${colors.bold(created?.name ?? args.name)} (${created?.id ?? ''})\n`, ) + if (participants !== undefined) process.stdout.write(` Party: ${formatParty(participants)}\n`) } } catch (err) { reportAndExit(err) diff --git a/src/commands/variants/edit.test.ts b/src/commands/variants/edit.test.ts index 7bb0578..6b97850 100644 --- a/src/commands/variants/edit.test.ts +++ b/src/commands/variants/edit.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, test, beforeEach, afterEach } from 'bun:test' +import { describe, expect, test, beforeEach, afterEach, spyOn } from 'bun:test' import { variantsAddCommand } from './add' import { variantsEditCommand } from './edit' @@ -103,3 +103,115 @@ describe('variants edit — date flags', () => { }) }) }) + +describe('variants add — party flags', () => { + const exactDates = { 'start-date': '2026-09-01', 'end-date': '2026-09-08' } + + test('sends adults and children ages', async () => { + await runAdd({ tripId: 't', name: 'Family', ...exactDates, adults: '2', 'child-ages': '10,7', json: false }) + + expect(captured?.body).toMatchObject({ + participants: { adults: 2, children: [{ age: 10 }, { age: 7 }] }, + }) + }) + + test('sends adults alone with an explicit empty children list', async () => { + await runAdd({ tripId: 't', name: 'Couple', ...exactDates, adults: '2', json: false }) + + expect(captured?.body).toMatchObject({ participants: { adults: 2, children: [] } }) + }) + + test('omits participants when no party flag is given', async () => { + await runAdd({ tripId: 't', name: 'Solo', ...exactDates, json: false }) + + expect(captured?.body).not.toHaveProperty('participants') + }) +}) + +describe('variants edit — party flags', () => { + const SELECTED = 'selected-variant' + const UNSELECTED = 'other-variant' + const storedParty = { + adults: 2, + children: [{ age: 10, _id: 'child-id' }], + numberOfRooms: 2, + _id: 'party-id', + } + + let requests: { method: string; url: string; body: unknown }[] + + const patchBodies = () => requests.filter((request) => request.method === 'PATCH').map((request) => request.body) + + // Mirrors the real read: without includeAllOptions only the selected variant comes back. + beforeEach(() => { + requests = [] + global.fetch = (async (input: Request | URL | string, init?: RequestInit) => { + const req = input instanceof Request ? input : new Request(String(input), init) + const text = await req.text() + requests.push({ method: req.method, url: req.url, body: text ? JSON.parse(text) : undefined }) + if (req.method !== 'GET') return new Response(null, { status: 200 }) + + const variants = [{ id: SELECTED, name: 'Selected', participants: { adults: 1, children: [] } }] + if (req.url.includes('includeAllOptions=true')) { + variants.push({ id: UNSELECTED, name: 'Other', participants: storedParty as never }) + } + return Response.json({ id: 't', name: 'Trip', variants }) + }) as unknown as typeof fetch + }) + + test('--adults keeps the stored children and rooms, without their ids', async () => { + await runEdit({ tripId: 't', variantId: UNSELECTED, adults: '3', json: false }) + + expect(patchBodies()).toEqual([{ participants: { adults: 3, children: [{ age: 10 }], numberOfRooms: 2 } }]) + }) + + test('--child-ages keeps the stored adults and rooms', async () => { + await runEdit({ tripId: 't', variantId: UNSELECTED, 'child-ages': '4,5', json: false }) + + expect(patchBodies()).toEqual([ + { participants: { adults: 2, children: [{ age: 4 }, { age: 5 }], numberOfRooms: 2 } }, + ]) + }) + + test('giving both flags still keeps the stored rooms', async () => { + await runEdit({ tripId: 't', variantId: UNSELECTED, adults: '1', 'child-ages': '4', json: false }) + + expect(patchBodies()).toEqual([{ participants: { adults: 1, children: [{ age: 4 }], numberOfRooms: 2 } }]) + }) + + test('--no-children clears the children only', async () => { + await runEdit({ tripId: 't', variantId: UNSELECTED, children: false, json: false }) + + expect(patchBodies()).toEqual([{ participants: { adults: 2, children: [], numberOfRooms: 2 } }]) + }) + + test('combines with other fields in one write', async () => { + await runEdit({ tripId: 't', variantId: UNSELECTED, name: 'Renamed', adults: '3', json: false }) + + expect(patchBodies()).toEqual([ + { name: 'Renamed', participants: { adults: 3, children: [{ age: 10 }], numberOfRooms: 2 } }, + ]) + }) + + test('neither flag reads nothing and leaves participants out of the write', async () => { + await runEdit({ tripId: 't', variantId: UNSELECTED, name: 'Renamed', json: false }) + + expect(requests.map((request) => request.method)).toEqual(['PATCH']) + expect(patchBodies()).toEqual([{ name: 'Renamed' }]) + }) + + test('an unknown variant fails without writing', async () => { + const stderr = spyOn(process.stderr, 'write').mockImplementation(() => true) + const exit = spyOn(process, 'exit').mockImplementation(((code: number) => { + throw new Error(`exit ${code}`) + }) as never) + + await expect(runEdit({ tripId: 't', variantId: 'missing', adults: '3', json: false })).rejects.toThrow('exit 1') + + const printed = stderr.mock.calls.map(([chunk]) => String(chunk)).join('') + stderr.mockRestore() + exit.mockRestore() + expect(printed).toContain('Variant missing not found on trip t') + expect(patchBodies()).toEqual([]) + }) +}) diff --git a/src/commands/variants/edit.ts b/src/commands/variants/edit.ts index e6441be..7c4eb6e 100644 --- a/src/commands/variants/edit.ts +++ b/src/commands/variants/edit.ts @@ -3,8 +3,12 @@ import { createApiClient } from '../../api/client' import { loadCredentials, resolveApiKey, resolveBaseUrl } from '../../auth/credentials-store' import { renderJson } from '../../render/json' import { colors } from '../../render/colors' +import { formatParty } from '../../render/party' import { reportAndExit, requireApiKey } from '../../util/errors' import { buildVariantDates, variantDateArgs } from './dates' +import { fetchVariantParticipants, mergeParticipants, parsePartyChange, variantPartyArgs } from './party' + +const POSITIONAL_COUNT = 2 export const variantsEditCommand = defineCommand({ meta: { name: 'edit', description: 'Update fields on an existing variant.' }, @@ -14,6 +18,7 @@ export const variantsEditCommand = defineCommand({ name: { type: 'string', description: 'New variant name.' }, notes: { type: 'string', description: 'New variant notes.' }, ...variantDateArgs, + ...variantPartyArgs, json: { type: 'boolean', default: false, description: 'Output as JSON.' }, }, async run({ args }) { @@ -23,8 +28,9 @@ export const variantsEditCommand = defineCommand({ if (args.notes !== undefined) updates.notes = args.notes const dates = buildVariantDates(args) if (dates !== undefined) updates.dates = dates - if (Object.keys(updates).length === 0) { - throw new Error('Specify at least one of --name, --notes, or the date flags.') + const partyChange = parsePartyChange(args, POSITIONAL_COUNT) + if (Object.keys(updates).length === 0 && partyChange === undefined) { + throw new Error('Specify at least one of --name, --notes, the date flags, or the party flags.') } const creds = await loadCredentials() @@ -32,6 +38,11 @@ export const variantsEditCommand = defineCommand({ requireApiKey(apiKey) const client = createApiClient({ baseUrl: resolveBaseUrl(creds), apiKey }) + const participants = + partyChange && + mergeParticipants(await fetchVariantParticipants(client, args.tripId, args.variantId), partyChange) + if (participants !== undefined) updates.participants = participants + const { data, error } = await client.PATCH('/v1/trips/{id}/variants/{variantId}', { params: { path: { id: args.tripId, variantId: args.variantId } }, body: updates as never, @@ -42,6 +53,7 @@ export const variantsEditCommand = defineCommand({ renderJson(data) } else { process.stdout.write(`${colors.green('✓')} Updated variant ${args.variantId}.\n`) + if (participants !== undefined) process.stdout.write(` Party: ${formatParty(participants)}\n`) } } catch (err) { reportAndExit(err) diff --git a/src/commands/variants/party.test.ts b/src/commands/variants/party.test.ts new file mode 100644 index 0000000..fa0cbc1 --- /dev/null +++ b/src/commands/variants/party.test.ts @@ -0,0 +1,115 @@ +import { describe, expect, test } from 'bun:test' +import { mergeParticipants, parsePartyChange, participantsForNewVariant } from './party' + +const ADD_POSITIONALS = 1 + +const parse = (args: Record) => parsePartyChange(args, ADD_POSITIONALS) + +describe('parsePartyChange', () => { + test('returns undefined when no party flag is given', () => { + expect(parse({ name: 'Beach option' })).toBeUndefined() + }) + + test('parses adults alone without inventing children', () => { + expect(parse({ adults: '2' })).toEqual({ adults: 2, children: undefined }) + }) + + test('parses comma-separated ages in order, tolerating spaces', () => { + expect(parse({ 'child-ages': '10, 7' })?.children).toEqual([{ age: 10 }, { age: 7 }]) + }) + + test('parses a repeated flag, which citty hands over as an array', () => { + expect(parse({ 'child-ages': ['10', '7,3'] })?.children).toEqual([{ age: 10 }, { age: 7 }, { age: 3 }]) + }) + + test('accepts the bounds of the age range', () => { + expect(parse({ 'child-ages': '0,17' })?.children).toEqual([{ age: 0 }, { age: 17 }]) + }) + + test('--no-children is an explicit empty list, distinct from not saying', () => { + expect(parse({ children: false })).toEqual({ adults: undefined, children: [] }) + }) + + test.each(['0', '-1', '1.5', 'two', '', ' ', '1e1', '0x2', '99999999999999999999'])( + 'rejects adult count %p', + (adults) => { + expect(() => parse({ adults })).toThrow(/Invalid adult count for --adults/) + }, + ) + + test('rejects --adults given twice rather than picking one', () => { + expect(() => parse({ adults: ['2', '3'] })).toThrow(/more than once/) + }) + + test.each(['18', '-1', '7.5', 'seven', '10,,7', '10,'])('rejects child ages %p', (ages) => { + expect(() => parse({ 'child-ages': ages })).toThrow(/Invalid child age for --child-ages/) + }) + + test('an empty --child-ages is an error, so an unset shell variable cannot wipe children', () => { + expect(() => parse({ 'child-ages': '' })).toThrow(/--no-children/) + }) + + test('rejects --child-ages together with --no-children', () => { + expect(() => parse({ 'child-ages': '10', children: false })).toThrow(/contradict/) + }) + + test('rejects a bare --children, which carries no ages', () => { + expect(() => parse({ children: true })).toThrow(/--child-ages/) + }) + + test('rejects space-separated ages instead of dropping all but the first', () => { + expect(() => parse({ _: ['trip', '7'], 'child-ages': '10' })).toThrow(/Unexpected argument: 7/) + }) + + test('counts only the positionals beyond the ones the command declares', () => { + expect(parsePartyChange({ _: ['trip', 'variant'], 'child-ages': '10' }, 2)?.children).toEqual([{ age: 10 }]) + }) +}) + +describe('participantsForNewVariant', () => { + test('leaves the API default alone when no party flag was given', () => { + expect(participantsForNewVariant(undefined)).toBeUndefined() + }) + + test('sends an explicit empty children list for adults only', () => { + expect(participantsForNewVariant({ adults: 2 })).toEqual({ adults: 2, children: [] }) + }) + + test('refuses children without adults rather than letting them default to one', () => { + expect(() => participantsForNewVariant({ children: [{ age: 10 }] })).toThrow(/--adults is required/) + expect(() => participantsForNewVariant({ children: [] })).toThrow(/--adults is required/) + }) +}) + +describe('mergeParticipants', () => { + const current = { adults: 2, children: [{ age: 10 }, { age: 7 }], numberOfRooms: 2 } + + test('changing adults keeps the children and rooms', () => { + expect(mergeParticipants(current, { adults: 3 })).toEqual({ ...current, adults: 3 }) + }) + + test('changing children keeps the adults and rooms', () => { + expect(mergeParticipants(current, { children: [{ age: 4 }] })).toEqual({ + adults: 2, + children: [{ age: 4 }], + numberOfRooms: 2, + }) + }) + + test('an empty children list clears them', () => { + expect(mergeParticipants(current, { children: [] }).children).toEqual([]) + }) + + test('changing everything the flags cover still keeps rooms', () => { + expect(mergeParticipants(current, { adults: 1, children: [] }).numberOfRooms).toBe(2) + }) + + test('strips the Mongo ids a read carries, which writes reject', () => { + const stored = { adults: 2, children: [{ age: 10, _id: 'c' }], _id: 'p' } + + expect(JSON.parse(JSON.stringify(mergeParticipants(stored, { adults: 3 })))).toEqual({ + adults: 3, + children: [{ age: 10 }], + }) + }) +}) diff --git a/src/commands/variants/party.ts b/src/commands/variants/party.ts new file mode 100644 index 0000000..1835777 --- /dev/null +++ b/src/commands/variants/party.ts @@ -0,0 +1,122 @@ +import type { Api } from '../../api/client' +import type { components } from '../../api/generated/schema' + +type Participants = components['schemas']['TripVariantParticipantsV1Dto'] +type Child = Participants['children'][number] + +export interface PartyChange { + adults?: number + children?: Child[] +} + +const MIN_ADULTS = 1 +const MAX_CHILD_AGE = 17 +const WHOLE_NUMBER = /^\d+$/ +const READ_EVERY_VARIANT = { includeAllOptions: true } + +/** Party flags shared by `variants add` and `variants edit`. */ +export const variantPartyArgs = { + adults: { type: 'string', description: `Number of adults travelling (at least ${MIN_ADULTS}).` }, + 'child-ages': { + type: 'string', + description: `Children's ages, one per child, comma-separated or repeated: --child-ages 8,5. Each 0-${MAX_CHILD_AGE}.`, + }, + children: { + type: 'boolean', + description: 'Use --no-children for an adults-only party (removes any children already set).', + }, +} as const + +function parseWholeNumber(value: string): number | undefined { + const trimmed = value.trim() + const parsed = Number(trimmed) + return WHOLE_NUMBER.test(trimmed) && Number.isSafeInteger(parsed) ? parsed : undefined +} + +function parseAdults(value: unknown): number | undefined { + if (value === undefined) return undefined + if (Array.isArray(value)) throw new Error('--adults was given more than once.') + + const adults = parseWholeNumber(String(value)) + if (adults === undefined || adults < MIN_ADULTS) { + throw new Error(`Invalid adult count for --adults: "${value}". Use a whole number of at least ${MIN_ADULTS}.`) + } + return adults +} + +function parseChildAge(value: string): Child { + const age = parseWholeNumber(value) + if (age === undefined || age > MAX_CHILD_AGE) { + throw new Error( + `Invalid child age for --child-ages: "${value.trim()}". Use a whole number from 0 to ${MAX_CHILD_AGE}; anyone older counts as an adult.`, + ) + } + return { age } +} + +function parseChildAges(value: unknown): Child[] | undefined { + if (value === undefined) return undefined + + const entries = [value].flat().flatMap((entry) => String(entry).split(',')) + if (entries.every((entry) => entry.trim() === '')) { + throw new Error('--child-ages needs at least one age, e.g. --child-ages 8,5. For no children use --no-children.') + } + return entries.map(parseChildAge) +} + +function rejectSpaceSeparatedAges(args: Record, positionalCount: number): void { + const positionals = (args._ as unknown[] | undefined) ?? [] + const extras = positionals.slice(positionalCount) + if (args['child-ages'] !== undefined && extras.length > 0) { + throw new Error(`Unexpected argument: ${extras.join(' ')}. Separate child ages with commas: --child-ages 8,5.`) + } +} + +/** Reads the party flags, or returns undefined when none were given. */ +export function parsePartyChange(args: Record, positionalCount: number): PartyChange | undefined { + if (args.children === true) { + throw new Error('--children does not take ages. Use --child-ages to list them, or --no-children for none.') + } + if (args.children === false && args['child-ages'] !== undefined) { + throw new Error('--child-ages and --no-children contradict each other. Use one of them.') + } + rejectSpaceSeparatedAges(args, positionalCount) + + const adults = parseAdults(args.adults) + const children = args.children === false ? [] : parseChildAges(args['child-ages']) + if (adults === undefined && children === undefined) return undefined + return { adults, children } +} + +/** The party to create a variant with, or undefined to leave the API's solo-adult default. */ +export function participantsForNewVariant(change: PartyChange | undefined): Participants | undefined { + if (change === undefined) return undefined + if (change.adults === undefined) { + throw new Error('--adults is required with --child-ages or --no-children when adding a variant.') + } + return { adults: change.adults, children: change.children ?? [] } +} + +/** + * The API replaces `participants` wholesale, so whatever this change leaves alone + * has to be sent back as it was. Only declared fields are copied: reads carry + * Mongo `_id`s on the party and on each child, and writes reject unknown fields. + */ +export function mergeParticipants(current: Participants, change: PartyChange): Participants { + return { + adults: change.adults ?? current.adults, + children: (change.children ?? current.children).map(({ age }) => ({ age })), + numberOfRooms: current.numberOfRooms ?? undefined, + } +} + +export async function fetchVariantParticipants(client: Api, tripId: string, variantId: string): Promise { + const { data, error } = await client.GET('/v1/trips/{id}', { + params: { path: { id: tripId }, query: READ_EVERY_VARIANT as never }, + }) + if (error) throw new Error(`Unexpected error fetching trip: ${JSON.stringify(error)}`) + + const variant = data?.variants?.find((candidate) => candidate.id === variantId) + if (!variant) throw new Error(`Variant ${variantId} not found on trip ${tripId}.`) + return variant.participants +} diff --git a/src/render/party.test.ts b/src/render/party.test.ts new file mode 100644 index 0000000..b9f27ec --- /dev/null +++ b/src/render/party.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, test } from 'bun:test' +import { formatParty } from './party' + +describe('formatParty', () => { + test('shows adults alone when there are no children', () => { + expect(formatParty({ adults: 1, children: [] })).toBe('1 adult') + expect(formatParty({ adults: 2 })).toBe('2 adults') + }) + + test('lists every child age in the stored order', () => { + expect(formatParty({ adults: 2, children: [{ age: 10 }, { age: 7 }] })).toBe('2 adults, 2 children (10, 7)') + }) + + test('keeps an infant age of 0 and uses the singular for one child', () => { + expect(formatParty({ adults: 1, children: [{ age: 0 }] })).toBe('1 adult, 1 child (0)') + }) + + test('renders nothing when the party is absent', () => { + expect(formatParty(undefined)).toBe('') + }) +}) diff --git a/src/render/party.ts b/src/render/party.ts new file mode 100644 index 0000000..08d7e38 --- /dev/null +++ b/src/render/party.ts @@ -0,0 +1,19 @@ +interface Party { + adults: number + children?: { age: number }[] +} + +function pluralize(count: number, singular: string, plural: string): string { + return `${count} ${count === 1 ? singular : plural}` +} + +export function formatParty(party: Party | undefined): string { + if (!party) return '' + + const adults = pluralize(party.adults, 'adult', 'adults') + const children = party.children ?? [] + if (children.length === 0) return adults + + const ages = children.map((child) => child.age).join(', ') + return `${adults}, ${pluralize(children.length, 'child', 'children')} (${ages})` +}