mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-04 09:54:14 +00:00
feat(assistant): packing list and to-do cards
This commit is contained in:
@@ -1,4 +1,18 @@
|
||||
import type { DomainCards } from '../card-types';
|
||||
import { PACKING_TOOLS } from './packing-tools';
|
||||
import { TODO_TOOLS } from './todo-cards';
|
||||
|
||||
/** The cards of packing lists and to-dos. None yet: this package fills them in. */
|
||||
export const PACKING_CARDS: DomainCards = { id: 'packing', tools: {} };
|
||||
/**
|
||||
* The packing lists and to-dos in the assistant chat: the lists a read shows
|
||||
* as cards, the card every change to an item, a bag, a category's people or a
|
||||
* to-do shows inside its change card, and the receipts that say which part of
|
||||
* the list a change touched.
|
||||
*/
|
||||
export const PACKING_CARDS: DomainCards = {
|
||||
id: 'packing',
|
||||
tools: { ...PACKING_TOOLS, ...TODO_TOOLS },
|
||||
prompt: [
|
||||
'Packing lists, bags and to-dos you read show as cards under your answer: do not list their items again.',
|
||||
'To add several packing items, make one bulk_import_packing call instead of many create_packing_item calls.',
|
||||
],
|
||||
};
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import type { AnswerInput } from '../card-types';
|
||||
import { clipped, recordOf } from '../card-values';
|
||||
import {
|
||||
assigneesOf,
|
||||
bagsNamed,
|
||||
bagsOf,
|
||||
categoryOf,
|
||||
itemRow,
|
||||
listItemsOf,
|
||||
MAX_CARD_GROUPS,
|
||||
packingCard,
|
||||
packingGroups,
|
||||
positiveId,
|
||||
quantityOf,
|
||||
rowsOf,
|
||||
tripPacking,
|
||||
type ListItem,
|
||||
} from './packing-rows';
|
||||
import { PACKING_PLACEHOLDER_NAME, type PackingCardGroup, type PackingListCard } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* The cards a packing read shows beside its answer, built from the read's
|
||||
* raw value: the list grouped the way the app groups it, the bags with what
|
||||
* they weigh, and the part of the list a tour points at. An empty list, no
|
||||
* bags and a tour that points at nothing (or at a category nobody can see an
|
||||
* item of any more) show no card; the answer says so in words.
|
||||
*/
|
||||
|
||||
/** `list_packing_items`: the items the user may see, grouped by category or by bag. */
|
||||
export function listItemsAnswer({ args, value, card }: AnswerInput): PackingListCard | null {
|
||||
const root = recordOf(value);
|
||||
const items = listItemsOf(root.items).filter((item) => !item.placeholder);
|
||||
if (items.length === 0) return null;
|
||||
const groupBy = args.group_by === 'bag' ? 'bag' : 'category';
|
||||
const bags = bagsOf(card, root);
|
||||
const assignees = recordOf(root.category_assignees);
|
||||
const { groups, moreGroups } = packingGroups(card, items, {
|
||||
groupBy,
|
||||
bagIds: bags.flatMap((bag) => bag.id ?? []),
|
||||
assigneesOf: (category) => (category === null ? [] : assigneesOf(card, assignees[category])),
|
||||
rowOf: (item) => itemRow(card, item),
|
||||
});
|
||||
const progress = { packed: items.filter((item) => item.checked).length, total: items.length };
|
||||
return packingCard({ type: 'trip' }, groupBy, bagsNamed(bags, groups), groups, { moreGroups, progress });
|
||||
}
|
||||
|
||||
/**
|
||||
* `list_packing_bags`: one head per bag with what it weighs and who packs it,
|
||||
* its items counted from the trip's list, and the pile in no bag when there is
|
||||
* one. No rows: a bag overview is its heads.
|
||||
*/
|
||||
export function listBagsAnswer({ value, card }: AnswerInput): PackingListCard | null {
|
||||
const bags = bagsOf(card, value);
|
||||
if (bags.length === 0) return null;
|
||||
const items = tripPacking(card).filter((item) => !item.placeholder);
|
||||
const group = (bagId: number | null): PackingCardGroup => {
|
||||
const inside = items.filter((item) => item.bagId === bagId);
|
||||
return {
|
||||
key: { by: 'bag', bagKey: bagId === null ? null : `id:${bagId}` },
|
||||
assignees: [],
|
||||
assigneesRemoved: [],
|
||||
items: [],
|
||||
count: inside.length,
|
||||
packed: inside.filter((item) => item.checked).length,
|
||||
};
|
||||
};
|
||||
const shown = bags.slice(0, MAX_CARD_GROUPS);
|
||||
const groups = shown.flatMap((bag) => (bag.id === null ? [] : [group(bag.id)]));
|
||||
const loose = group(null);
|
||||
if (loose.count > 0 && groups.length < MAX_CARD_GROUPS) groups.push(loose);
|
||||
return packingCard({ type: 'trip' }, 'bag', shown, groups, { moreGroups: bags.length - shown.length });
|
||||
}
|
||||
|
||||
/**
|
||||
* `get_tour_packing`: the part of the list a tour points at, as the tour
|
||||
* shows it. What the trip's list knows of an item (its weight, tier)
|
||||
* fills in what the tour's answer leaves out; its bag is not named, since the
|
||||
* card reads no bags.
|
||||
*/
|
||||
export function tourPackingAnswer({ args, value, card }: AnswerInput): PackingListCard | null {
|
||||
const root = recordOf(value);
|
||||
const placeId = positiveId(args.placeId);
|
||||
if (placeId === null || !root.packing_link || root.state === 'missing') return null;
|
||||
const name = clipped(recordOf(root.tour).name, 200) ?? clipped(card.places.get(placeId)?.name, 200);
|
||||
if (name === null) return null;
|
||||
const known = new Map(tripPacking(card).map((item): [number, ListItem] => [item.id, item]));
|
||||
const items = rowsOf(root.items).flatMap((raw): ListItem[] => {
|
||||
const id = positiveId(raw.id);
|
||||
// The `...` stand-in of an empty category is never a row.
|
||||
const rawName = typeof raw.name === 'string' ? raw.name : null;
|
||||
if (rawName === null || rawName === PACKING_PLACEHOLDER_NAME) return [];
|
||||
const shown = clipped(rawName, 200);
|
||||
if (id === null || shown === null) return [];
|
||||
const base = known.get(id);
|
||||
return [
|
||||
{
|
||||
id,
|
||||
name: shown,
|
||||
rawName,
|
||||
category: categoryOf(raw.category),
|
||||
quantity: quantityOf(raw.quantity),
|
||||
packedQuantity: base?.packedQuantity ?? null,
|
||||
checked: raw.packed === true,
|
||||
unitGrams: base?.unitGrams ?? null,
|
||||
bagId: base?.bagId ?? null,
|
||||
isPrivate: base?.isPrivate ?? false,
|
||||
ownerId: base?.ownerId ?? null,
|
||||
recipientIds: base?.recipientIds ?? [],
|
||||
placeholder: false,
|
||||
},
|
||||
];
|
||||
});
|
||||
const { groups, moreGroups } = packingGroups(card, items, {
|
||||
groupBy: 'category',
|
||||
bagIds: [],
|
||||
rowOf: (item) => itemRow(card, item),
|
||||
});
|
||||
const category = clipped(recordOf(root.packing_link).category, 200);
|
||||
const progress = { packed: items.filter((item) => item.checked).length, total: items.length };
|
||||
return packingCard({ type: 'tour', placeId, name, category }, 'category', [], groups, { moreGroups, progress });
|
||||
}
|
||||
@@ -0,0 +1,430 @@
|
||||
import type { TripCard } from '../../assistant-context';
|
||||
import type { CardReader, PreviewContext, ToolArgs } from '../card-types';
|
||||
import { argId, clipped, hexOrNull, recordOf, type Row } from '../card-values';
|
||||
import {
|
||||
argText,
|
||||
bagOf,
|
||||
bagsOf,
|
||||
categoryCard,
|
||||
categoryOf,
|
||||
gramsOf,
|
||||
idsOf,
|
||||
itemRow,
|
||||
MAX_PACKING_ROWS,
|
||||
packingCard,
|
||||
packingGroups,
|
||||
peopleOf,
|
||||
positiveId,
|
||||
quantityOf,
|
||||
rowsOf,
|
||||
slotOf,
|
||||
tierOf,
|
||||
tripItem,
|
||||
tripPacking,
|
||||
type ListItem,
|
||||
type PackingTier,
|
||||
} from './packing-rows';
|
||||
import {
|
||||
resolvePackedState,
|
||||
type PackingCardBag,
|
||||
type PackingCardItem,
|
||||
type PackingListCard,
|
||||
} from '@trek/shared';
|
||||
|
||||
/**
|
||||
* The card each packing change shows inside its change card, from the call's
|
||||
* arguments, the trip's list as the turn read it, and what the change's
|
||||
* lookup found (the bags, the templates, who looks after a category). The
|
||||
* defaults are the server's own: a new item goes under "General", an imported
|
||||
* one under "Other", a quantity is 1 to 999, a new bag is indigo. A change to
|
||||
* an item, bag or template the turn cannot find shows no card; the server
|
||||
* refuses it anyway.
|
||||
*/
|
||||
|
||||
/** The colour `create_packing_bag` gives a bag without one. */
|
||||
const DEFAULT_BAG_COLOR = '#6366f1';
|
||||
/** New bags one import card names. */
|
||||
const MAX_NEW_BAGS = 20;
|
||||
|
||||
type Changed = PackingCardItem['changed'];
|
||||
|
||||
/** The bags as the lookup read them, raw. */
|
||||
function rawBags(loaded: unknown): Row[] {
|
||||
return rowsOf(recordOf(loaded).bags);
|
||||
}
|
||||
|
||||
/** Reads the trip's bags, for a change that names one. */
|
||||
export function loadBags(_args: ToolArgs, read: CardReader): Promise<unknown> {
|
||||
return read('list_packing_bags');
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the bags only when the call names one (`bag_id`), also to take an
|
||||
* item out of its bag (`null`), so the card can name the bag it leaves.
|
||||
*/
|
||||
export function loadBagsWhenNamed(args: ToolArgs, read: CardReader): Promise<unknown> {
|
||||
return args.bag_id === undefined ? Promise.resolve(null) : read('list_packing_bags');
|
||||
}
|
||||
|
||||
/** Reads the bags only when an imported item names one by its name. */
|
||||
export function loadBagsForImport(args: ToolArgs, read: CardReader): Promise<unknown> {
|
||||
const named = rowsOf(args.items).some((item) => typeof item.bag === 'string' && item.bag.trim() !== '');
|
||||
return named ? read('list_packing_bags') : Promise.resolve(null);
|
||||
}
|
||||
|
||||
export function loadTemplates(_args: ToolArgs, read: CardReader): Promise<unknown> {
|
||||
return read('list_packing_templates');
|
||||
}
|
||||
|
||||
export function loadPackingAssignees(_args: ToolArgs, read: CardReader): Promise<unknown> {
|
||||
return read('get_packing_category_assignees');
|
||||
}
|
||||
|
||||
/** The tier a write's arguments put an item in, the server's way (`visibility` before `is_private`). */
|
||||
function visibilityOf(args: ToolArgs): PackingTier {
|
||||
const visibility = args.visibility;
|
||||
if (visibility === 'common' || visibility === 'personal' || visibility === 'shared') return visibility;
|
||||
return args.is_private === true ? 'personal' : 'common';
|
||||
}
|
||||
|
||||
/** The people a shared item covers: trip members, never its owner (the server drops both). */
|
||||
function recipientsOf(card: TripCard, value: unknown): number[] {
|
||||
return idsOf(value).filter((id) => id !== card.viewerId && card.members.has(id));
|
||||
}
|
||||
|
||||
/**
|
||||
* One item in its category, with the bag it goes into. The category's name is
|
||||
* masked when it comes from the trip, kept as written from arguments.
|
||||
*/
|
||||
function oneItemCard(
|
||||
card: TripCard,
|
||||
item: ListItem,
|
||||
row: PackingCardItem,
|
||||
bags: PackingCardBag[],
|
||||
mask = true,
|
||||
): PackingListCard {
|
||||
const bag = bags.find((b) => b.id !== null && b.id === item.bagId);
|
||||
const name = mask ? clipped(item.category, 100) : argText(item.category, 100);
|
||||
return categoryCard(card, { name, raw: item.category, personal: item.isPrivate }, [row], bag ? [bag] : []);
|
||||
}
|
||||
|
||||
/** `create_packing_item`: the new row under its category. */
|
||||
export function createItemCard(ctx: PreviewContext, args: ToolArgs, loaded: unknown): PackingListCard | null {
|
||||
const name = argText(args.name, 200);
|
||||
if (name === null) return null;
|
||||
const tier = visibilityOf(args);
|
||||
const bags = bagsOf(ctx.card, loaded);
|
||||
const bagId = positiveId(args.bag_id);
|
||||
const item: ListItem = {
|
||||
id: 0,
|
||||
name,
|
||||
rawName: name,
|
||||
category: argText(args.category, 100) ?? 'General',
|
||||
quantity: quantityOf(args.quantity),
|
||||
packedQuantity: null,
|
||||
checked: !!args.checked,
|
||||
unitGrams: gramsOf(args.weight_grams),
|
||||
bagId: bags.some((bag) => bag.id === bagId) ? bagId : null,
|
||||
isPrivate: tier !== 'common',
|
||||
ownerId: ctx.card.viewerId,
|
||||
recipientIds: tier === 'shared' ? recipientsOf(ctx.card, args.recipient_ids) : [],
|
||||
placeholder: false,
|
||||
};
|
||||
return oneItemCard(ctx.card, item, itemRow(ctx.card, item, 'add'), bags, false);
|
||||
}
|
||||
|
||||
/** An imported weight as the server keeps it: whole grams cut (`parseInt`), none for 0. */
|
||||
function importGrams(value: unknown): number | null {
|
||||
return gramsOf(typeof value === 'number' ? Math.trunc(value) : value) || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* `bulk_import_packing`: every imported item under its category ("Other"
|
||||
* without one), a bag named by an existing bag's exact name going into that
|
||||
* bag and any other name making a new one, as the server does.
|
||||
*/
|
||||
export function bulkImportCard(ctx: PreviewContext, args: ToolArgs, loaded: unknown): PackingListCard | null {
|
||||
const existing = rawBags(loaded);
|
||||
const known = bagsOf(ctx.card, loaded);
|
||||
const created: PackingCardBag[] = [];
|
||||
const keys = new Map<number, string>();
|
||||
const keyOf = (bagName: string): string | null => {
|
||||
const found = positiveId(existing.find((bag) => bag.name === bagName)?.id);
|
||||
if (found !== null) return `id:${found}`;
|
||||
const shown = argText(bagName, 100);
|
||||
const already = created.find((bag) => bag.name === shown);
|
||||
if (already) return already.key;
|
||||
if (shown === null || created.length >= MAX_NEW_BAGS) return null;
|
||||
const bag = newBag(`new:${created.length}`, shown, null, null);
|
||||
created.push(bag);
|
||||
return bag.key;
|
||||
};
|
||||
const items = rowsOf(args.items).flatMap((raw, index): ListItem[] => {
|
||||
const name = argText(raw.name, 200);
|
||||
if (name === null) return [];
|
||||
const bagName = typeof raw.bag === 'string' ? raw.bag.trim() : '';
|
||||
const key = bagName === '' ? null : keyOf(bagName);
|
||||
if (key) keys.set(-1 - index, key);
|
||||
return [
|
||||
{
|
||||
id: -1 - index,
|
||||
name,
|
||||
rawName: name,
|
||||
category: argText(raw.category, 100) ?? 'Other',
|
||||
quantity: quantityOf(raw.quantity),
|
||||
packedQuantity: null,
|
||||
checked: raw.checked === true,
|
||||
unitGrams: importGrams(raw.weight_grams),
|
||||
bagId: null,
|
||||
isPrivate: false,
|
||||
ownerId: ctx.card.viewerId,
|
||||
recipientIds: [],
|
||||
placeholder: false,
|
||||
},
|
||||
];
|
||||
});
|
||||
if (items.length === 0) return null;
|
||||
const { groups, moreGroups } = packingGroups(ctx.card, items, {
|
||||
groupBy: 'category',
|
||||
bagIds: [],
|
||||
categoryName: (category) => argText(category, 100),
|
||||
rowOf: (item) => ({ ...itemRow(ctx.card, item, 'add'), bagKey: keys.get(item.id) ?? null }),
|
||||
maxRows: MAX_PACKING_ROWS,
|
||||
fillSingleGroup: true,
|
||||
});
|
||||
const named = new Set(groups.flatMap((group) => group.items.flatMap((row) => row.bagKey ?? [])));
|
||||
const bags = [...known, ...created].filter((bag) => named.has(bag.key));
|
||||
return packingCard({ type: 'trip' }, 'category', bags, groups, { moreGroups });
|
||||
}
|
||||
|
||||
/** A bag a change creates, before the server has given it an id. */
|
||||
function newBag(key: string, name: string, color: string | null, limitGrams: number | null): PackingCardBag {
|
||||
return {
|
||||
key,
|
||||
id: null,
|
||||
name,
|
||||
color,
|
||||
weightGrams: null,
|
||||
limitGrams,
|
||||
owner: null,
|
||||
members: [],
|
||||
membersRemoved: [],
|
||||
change: 'add',
|
||||
changed: [],
|
||||
movesOut: 0,
|
||||
};
|
||||
}
|
||||
|
||||
/** `apply_packing_template`: the template and how many items it adds; its items cannot be read. */
|
||||
export function applyTemplateCard(_ctx: PreviewContext, args: ToolArgs, loaded: unknown): PackingListCard | null {
|
||||
const templateId = argId(args, 'templateId');
|
||||
const template = rowsOf(recordOf(loaded).templates).find((row) => row.id === templateId);
|
||||
const name = clipped(template?.name, 100);
|
||||
if (templateId === null || !template || name === null) return null;
|
||||
const itemCount = Math.max(0, Math.min(5_000, Math.floor(Number(template.item_count) || 0)));
|
||||
return packingCard({ type: 'template', templateId, name, itemCount }, 'category', [], []);
|
||||
}
|
||||
|
||||
/**
|
||||
* `toggle_packing_item`: the row ticked off or not, its packed count with it.
|
||||
* The row keeps how many were packed before, so the tick is only taken back
|
||||
* when that brings the item back to where it was.
|
||||
*/
|
||||
export function toggleItemCard(ctx: PreviewContext, args: ToolArgs): PackingListCard | null {
|
||||
const before = tripItem(ctx.card, argId(args, 'itemId'));
|
||||
if (!before) return null;
|
||||
const checked = args.checked === true;
|
||||
const after = { ...before, checked, packedQuantity: null };
|
||||
const changed: Changed = [{ field: 'packed', before: String(itemRow(ctx.card, before).packed) }];
|
||||
return oneItemCard(ctx.card, after, itemRow(ctx.card, after, checked ? 'check' : 'uncheck', changed), []);
|
||||
}
|
||||
|
||||
/** `delete_packing_item`: the row as it is, about to go. */
|
||||
export function deleteItemCard(ctx: PreviewContext, args: ToolArgs): PackingListCard | null {
|
||||
const before = tripItem(ctx.card, argId(args, 'itemId'));
|
||||
return before ? oneItemCard(ctx.card, before, itemRow(ctx.card, before, 'remove'), []) : null;
|
||||
}
|
||||
|
||||
function bagName(bags: readonly PackingCardBag[], bagId: number | null): string | null {
|
||||
return bagId === null ? null : (bags.find((bag) => bag.id === bagId)?.name ?? null);
|
||||
}
|
||||
|
||||
/** What a field read before a change, as stored. */
|
||||
function grams(value: number | null): string | null {
|
||||
return value === null ? null : String(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* `update_packing_item`: the row with the arguments merged in, under its new
|
||||
* category. Taking it out of its bag is `bag_id: null`; a packed count that
|
||||
* reaches the quantity ticks it off, 0 or null clears the count, as the
|
||||
* server settles them (`resolvePackedState`). Every field that changes keeps
|
||||
* what it held before.
|
||||
*/
|
||||
export function updateItemCard(ctx: PreviewContext, args: ToolArgs, loaded: unknown): PackingListCard | null {
|
||||
const before = tripItem(ctx.card, argId(args, 'itemId'));
|
||||
if (!before) return null;
|
||||
const bags = bagsOf(ctx.card, loaded);
|
||||
const quantity = args.quantity === undefined ? before.quantity : quantityOf(args.quantity);
|
||||
const bodyKeys = args.packed_quantity === undefined ? [] : ['packed_quantity'];
|
||||
const packed = resolvePackedState(
|
||||
{ checked: before.checked ? 1 : 0, packed_quantity: before.packedQuantity },
|
||||
{ bodyKeys, packed_quantity: typeof args.packed_quantity === 'number' ? args.packed_quantity : null, quantity },
|
||||
);
|
||||
// A name sent again as it is stays the one shown, masked as the trip read it.
|
||||
const named = argText(args.name, 200);
|
||||
const after: ListItem = {
|
||||
...before,
|
||||
name: named === null || named === argText(before.rawName, 200) ? before.name : named,
|
||||
rawName: named ?? before.rawName,
|
||||
category: args.category === undefined ? before.category : (argText(args.category, 100) ?? before.category),
|
||||
quantity,
|
||||
checked: packed.checked === 1,
|
||||
packedQuantity: packed.packed_quantity,
|
||||
unitGrams: args.weight_grams === undefined ? before.unitGrams : gramsOf(args.weight_grams),
|
||||
bagId: args.bag_id === undefined ? before.bagId : positiveId(args.bag_id),
|
||||
isPrivate: typeof args.is_private === 'boolean' ? args.is_private : before.isPrivate,
|
||||
};
|
||||
const changed: Changed = [];
|
||||
const note = (field: Changed[number]['field'], old: string | null, now: string | null) => {
|
||||
if (old !== now) changed.push({ field, before: old === null ? null : old.slice(0, 120) });
|
||||
};
|
||||
note('name', before.name, after.name);
|
||||
if (before.category !== after.category) changed.push({ field: 'category', before: clipped(before.category, 100) });
|
||||
note('quantity', String(before.quantity), String(after.quantity));
|
||||
note('packed', String(itemRow(ctx.card, before).packed), String(itemRow(ctx.card, after).packed));
|
||||
// Weights compare as the row shows them, every piece together.
|
||||
if (before.unitGrams !== after.unitGrams) {
|
||||
const total = (item: ListItem) => itemRow(ctx.card, item).weightGrams;
|
||||
changed.push({ field: 'weight', before: grams(total(before)) });
|
||||
}
|
||||
note('bag', bagName(bags, before.bagId), bagName(bags, after.bagId));
|
||||
note('tier', tierOf(before), tierOf(after));
|
||||
// A bag the lookup does not know stays unnamed: the row shows no swatch rather than a wrong one.
|
||||
return oneItemCard(ctx.card, after, itemRow(ctx.card, after, 'update', changed), bags, args.category === undefined);
|
||||
}
|
||||
|
||||
/** `set_packing_item_sharing`: the row in the tier it moves to, with the people it covers. */
|
||||
export function sharingCard(ctx: PreviewContext, args: ToolArgs): PackingListCard | null {
|
||||
const before = tripItem(ctx.card, argId(args, 'itemId'));
|
||||
if (!before) return null;
|
||||
const tier = visibilityOf(args);
|
||||
const after: ListItem = {
|
||||
...before,
|
||||
isPrivate: tier !== 'common',
|
||||
recipientIds: tier === 'shared' ? recipientsOf(ctx.card, args.recipient_ids) : [],
|
||||
};
|
||||
const row = itemRow(ctx.card, after, 'share', [{ field: 'tier', before: tierOf(before) }]);
|
||||
return oneItemCard(ctx.card, after, row, []);
|
||||
}
|
||||
|
||||
/**
|
||||
* `set_packing_category_assignees`: the category's head with the people it
|
||||
* will have, new ones marked, and the ones it drops; its items are counted.
|
||||
*/
|
||||
export function packingAssigneesCard(ctx: PreviewContext, args: ToolArgs, loaded: unknown): PackingListCard | null {
|
||||
const raw = typeof args.categoryName === 'string' ? args.categoryName : null;
|
||||
const name = argText(raw, 100);
|
||||
if (raw === null || name === null) return null;
|
||||
const chosen = idsOf(args.userIds);
|
||||
const before = rowsOf(recordOf(recordOf(loaded).assignees)[raw]).flatMap((row) => positiveId(row.user_id) ?? []);
|
||||
const inside = tripPacking(ctx.card).filter((item) => !item.placeholder && item.category === raw);
|
||||
const personal = inside.length > 0 && inside.every((item) => item.isPrivate);
|
||||
return packingCard({ type: 'trip' }, 'category', [], [
|
||||
{
|
||||
key: { by: 'category', name, slot: slotOf(ctx.card, raw, personal) },
|
||||
assignees: peopleOf(ctx.card, chosen, 6),
|
||||
assigneesRemoved: peopleOf(ctx.card, before.filter((id) => !chosen.includes(id)), 6),
|
||||
items: [],
|
||||
count: inside.length,
|
||||
packed: inside.filter((item) => item.checked).length,
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
/** A bag head on a card of its own: what a change to one bag shows. */
|
||||
function bagCard(card: TripCard, bag: PackingCardBag): PackingListCard {
|
||||
const inside = tripPacking(card).filter((item) => !item.placeholder && bag.id !== null && item.bagId === bag.id);
|
||||
return packingCard({ type: 'trip' }, 'bag', [bag], [
|
||||
{
|
||||
key: { by: 'bag', bagKey: bag.key },
|
||||
assignees: [],
|
||||
assigneesRemoved: [],
|
||||
items: [],
|
||||
count: inside.length,
|
||||
packed: inside.filter((item) => item.checked).length,
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
/** The bag a call names (`bagId`), as the lookup read it. */
|
||||
function namedBag(card: TripCard, args: ToolArgs, loaded: unknown): PackingCardBag | null {
|
||||
const bagId = argId(args, 'bagId');
|
||||
return bagId === null ? null : bagOf(card, rawBags(loaded).find((bag) => bag.id === bagId));
|
||||
}
|
||||
|
||||
/** `create_packing_bag`: the new bag's head, in its colour (indigo without one) and with its limit. */
|
||||
export function createBagCard(ctx: PreviewContext, args: ToolArgs): PackingListCard | null {
|
||||
const name = argText(args.name, 100);
|
||||
if (name === null) return null;
|
||||
const bag = newBag('new:0', name, hexOrNull(args.color) ?? DEFAULT_BAG_COLOR, gramsOf(args.weight_limit_grams));
|
||||
return bagCard(ctx.card, bag);
|
||||
}
|
||||
|
||||
/** `update_packing_bag`: the bag with the arguments merged in, each changed field with its old value. */
|
||||
export function updateBagCard(ctx: PreviewContext, args: ToolArgs, loaded: unknown): PackingListCard | null {
|
||||
const before = namedBag(ctx.card, args, loaded);
|
||||
if (!before) return null;
|
||||
const ownerId = args.user_id === undefined ? (before.owner?.id ?? null) : positiveId(args.user_id);
|
||||
const after: PackingCardBag = {
|
||||
...before,
|
||||
name: argText(args.name, 100) ?? before.name,
|
||||
color: args.color === undefined ? before.color : (hexOrNull(args.color) ?? before.color),
|
||||
limitGrams: args.weight_limit_grams === undefined ? before.limitGrams : gramsOf(args.weight_limit_grams),
|
||||
owner: ownerId === null ? null : (peopleOf(ctx.card, [ownerId], 1)[0] ?? null),
|
||||
change: 'update',
|
||||
};
|
||||
const changed: PackingCardBag['changed'] = [];
|
||||
if (after.name !== before.name) changed.push({ field: 'name', before: before.name.slice(0, 120) });
|
||||
if (after.color !== before.color) changed.push({ field: 'color', before: before.color });
|
||||
if (after.limitGrams !== before.limitGrams) changed.push({ field: 'limit', before: grams(before.limitGrams) });
|
||||
if (after.owner?.id !== before.owner?.id) changed.push({ field: 'owner', before: before.owner?.name ?? null });
|
||||
return bagCard(ctx.card, { ...after, changed });
|
||||
}
|
||||
|
||||
/** `set_bag_members`: the bag with the people who will pack it, and the ones it drops. */
|
||||
export function bagMembersCard(ctx: PreviewContext, args: ToolArgs, loaded: unknown): PackingListCard | null {
|
||||
const before = namedBag(ctx.card, args, loaded);
|
||||
if (!before) return null;
|
||||
const chosen = idsOf(args.userIds);
|
||||
const members = peopleOf(ctx.card, chosen, 6);
|
||||
const membersRemoved = before.members.filter((person) => !chosen.includes(person.id));
|
||||
return bagCard(ctx.card, { ...before, members, membersRemoved, change: 'members' });
|
||||
}
|
||||
|
||||
/** `delete_packing_bag`: the bag about to go, and how many items land in "Unassigned". */
|
||||
export function deleteBagCard(ctx: PreviewContext, args: ToolArgs, loaded: unknown): PackingListCard | null {
|
||||
const before = namedBag(ctx.card, args, loaded);
|
||||
if (!before) return null;
|
||||
const movesOut = tripPacking(ctx.card).filter((item) => !item.placeholder && item.bagId === before.id).length;
|
||||
return bagCard(ctx.card, { ...before, change: 'remove', movesOut: Math.min(movesOut, 5_000) });
|
||||
}
|
||||
|
||||
/**
|
||||
* `link_tour_packing`: the part of the list the tour will point at, as the
|
||||
* tour will show it (the whole list, or one category of it).
|
||||
*/
|
||||
export function linkTourCard(ctx: PreviewContext, args: ToolArgs): PackingListCard | null {
|
||||
const placeId = argId(args, 'placeId');
|
||||
const name = clipped(placeId === null ? null : ctx.card.places.get(placeId)?.name, 200);
|
||||
if (placeId === null || name === null) return null;
|
||||
const category = categoryOf(args.category);
|
||||
const items = tripPacking(ctx.card).filter((item) => category === null || item.category === category);
|
||||
const { groups, moreGroups } = packingGroups(ctx.card, items, {
|
||||
groupBy: 'category',
|
||||
bagIds: [],
|
||||
rowOf: (item) => itemRow(ctx.card, item),
|
||||
});
|
||||
const shown = category === null ? null : argText(category, 200);
|
||||
return packingCard({ type: 'tour', placeId, name, category: shown }, 'category', [], groups, { moreGroups });
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
import type { TripCard } from '../../assistant-context';
|
||||
import { clipped, finite, hexOrNull, personOf, recordOf, type Row } from '../card-values';
|
||||
import {
|
||||
PACKING_PLACEHOLDER_NAME,
|
||||
type CardPerson,
|
||||
type PackingCardBag,
|
||||
type PackingCardGroup,
|
||||
type PackingCardItem,
|
||||
type PackingListCard,
|
||||
} from '@trek/shared';
|
||||
|
||||
/**
|
||||
* The pieces every packing card is built from: an item as the packing tools
|
||||
* answer it, its row on a card, its group (a category or a bag) and the bags.
|
||||
* Text from a tool's answer is masked like a provider answer (`clipped`), text
|
||||
* from a call's arguments only cut (`argText`), since it is what will be
|
||||
* stored. The `...` stand-in of an empty category is never a row and never
|
||||
* counted, but it still holds its category's place in the list's order.
|
||||
*/
|
||||
|
||||
/** Rows one packing card shows, and at most per group. */
|
||||
export const MAX_PACKING_ROWS = 24;
|
||||
const ROWS_PER_GROUP = 8;
|
||||
export const MAX_CARD_GROUPS = 12;
|
||||
const MAX_CARD_BAGS = 20;
|
||||
const MAX_GRAMS = 1_000_000;
|
||||
|
||||
export type PackingTier = PackingCardItem['tier'];
|
||||
type Source = PackingListCard['source'];
|
||||
type GroupBy = PackingListCard['groupBy'];
|
||||
|
||||
/** A packing item as `get_trip_summary`, `list_packing_items` and the writes answer it. */
|
||||
export interface ListItem {
|
||||
id: number;
|
||||
/** As shown: masked when it comes from a tool's answer. */
|
||||
name: string;
|
||||
/** As stored, to tell whether a write really renames it; never shown. */
|
||||
rawName: string;
|
||||
category: string | null;
|
||||
quantity: number;
|
||||
packedQuantity: number | null;
|
||||
checked: boolean;
|
||||
/** The weight of one piece. */
|
||||
unitGrams: number | null;
|
||||
bagId: number | null;
|
||||
isPrivate: boolean;
|
||||
ownerId: number | null;
|
||||
recipientIds: number[];
|
||||
/** The `...` stand-in of an empty category. */
|
||||
placeholder: boolean;
|
||||
}
|
||||
|
||||
export function rowsOf(value: unknown): Row[] {
|
||||
return Array.isArray(value) ? value.map(recordOf) : [];
|
||||
}
|
||||
|
||||
export function positiveId(value: unknown): number | null {
|
||||
return typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : null;
|
||||
}
|
||||
|
||||
function cut(text: string, max: number): string {
|
||||
return text.length > max ? `${text.slice(0, max - 1)}…` : text;
|
||||
}
|
||||
|
||||
/** A text from a call's arguments as it will be stored: on one line and cut to `max`, never masked. */
|
||||
export function argText(value: unknown, max: number): string | null {
|
||||
if (typeof value !== 'string') return null;
|
||||
const line = value.replace(/\s+/g, ' ').trim();
|
||||
return line === '' ? null : cut(line, max);
|
||||
}
|
||||
|
||||
/** How many of an item: what the server keeps, 1 to 999. */
|
||||
export function quantityOf(value: unknown): number {
|
||||
const n = finite(value);
|
||||
return n === null ? 1 : Math.min(999, Math.max(1, Math.floor(n)));
|
||||
}
|
||||
|
||||
export function gramsOf(value: unknown): number | null {
|
||||
const n = finite(value);
|
||||
return n === null || n < 0 ? null : Math.min(MAX_GRAMS, Math.round(n));
|
||||
}
|
||||
|
||||
/** A category as stored: an empty one is none. */
|
||||
export function categoryOf(value: unknown): string | null {
|
||||
return typeof value === 'string' && value.trim() !== '' ? value : null;
|
||||
}
|
||||
|
||||
/** One packing item from a tool's answer; null for a row without an id or a name. */
|
||||
function listItemOf(raw: unknown): ListItem | null {
|
||||
const row = recordOf(raw);
|
||||
const id = positiveId(row.id);
|
||||
const name = typeof row.name === 'string' ? row.name : null;
|
||||
if (id === null || name === null) return null;
|
||||
const placeholder = name === PACKING_PLACEHOLDER_NAME;
|
||||
const shown = placeholder ? name : clipped(name, 200);
|
||||
if (shown === null) return null;
|
||||
return {
|
||||
id,
|
||||
name: shown,
|
||||
rawName: name,
|
||||
category: categoryOf(row.category),
|
||||
quantity: quantityOf(row.quantity),
|
||||
packedQuantity: finite(row.packed_quantity),
|
||||
checked: !!row.checked,
|
||||
unitGrams: gramsOf(row.weight_grams),
|
||||
bagId: positiveId(row.bag_id),
|
||||
isPrivate: !!row.is_private,
|
||||
ownerId: positiveId(row.owner_id),
|
||||
recipientIds: rowsOf(row.recipients).flatMap((r) => positiveId(r.user_id) ?? []),
|
||||
placeholder,
|
||||
};
|
||||
}
|
||||
|
||||
export function listItemsOf(value: unknown): ListItem[] {
|
||||
return rowsOf(value).flatMap((row) => listItemOf(row) ?? []);
|
||||
}
|
||||
|
||||
const TRIP_PACKING = new WeakMap<TripCard, ListItem[]>();
|
||||
|
||||
/** The trip's packing list as the turn read it, the stand-ins included; read once per card. */
|
||||
export function tripPacking(card: TripCard): ListItem[] {
|
||||
let items = TRIP_PACKING.get(card);
|
||||
if (!items) {
|
||||
items = listItemsOf(recordOf(recordOf(card.sources.summary).packing).items);
|
||||
TRIP_PACKING.set(card, items);
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
/** The trip's item `id` as the turn read it. */
|
||||
export function tripItem(card: TripCard, id: number | null): ListItem | null {
|
||||
return id === null ? null : (tripPacking(card).find((item) => item.id === id && !item.placeholder) ?? null);
|
||||
}
|
||||
|
||||
/** The tier an item sits in (#858): the common list, the owner's own, or shared with named people. */
|
||||
export function tierOf(item: Pick<ListItem, 'isPrivate' | 'recipientIds'>): PackingTier {
|
||||
if (!item.isPrivate) return 'common';
|
||||
return item.recipientIds.length > 0 ? 'shared' : 'personal';
|
||||
}
|
||||
|
||||
/** The trip members among `ids`, in order, at most `max`; anyone outside the trip is left out. */
|
||||
export function peopleOf(card: TripCard, ids: readonly number[], max: number): CardPerson[] {
|
||||
return [...new Set(ids)].flatMap((id) => personOf(card, id) ?? []).slice(0, max);
|
||||
}
|
||||
|
||||
/** The ids of an id list argument. */
|
||||
export function idsOf(value: unknown): number[] {
|
||||
return Array.isArray(value) ? value.flatMap((v: unknown) => positiveId(v) ?? []) : [];
|
||||
}
|
||||
|
||||
/** How many of an item are packed: all of it once ticked, the partial count before (#2296). */
|
||||
function packedOf(item: Pick<ListItem, 'checked' | 'quantity' | 'packedQuantity'>): number {
|
||||
return item.checked ? item.quantity : Math.max(0, Math.min(item.packedQuantity ?? 0, item.quantity));
|
||||
}
|
||||
|
||||
const bagKeyOf = (bagId: number | null): string | null => (bagId === null ? null : `id:${bagId}`);
|
||||
|
||||
/** An item's row on a card; without the trip card (an applied change) nobody it is shared with is named. */
|
||||
export function itemRow(
|
||||
card: TripCard | null,
|
||||
item: ListItem,
|
||||
change: PackingCardItem['change'] = 'none',
|
||||
changed: PackingCardItem['changed'] = [],
|
||||
): PackingCardItem {
|
||||
const tier = tierOf(item);
|
||||
return {
|
||||
id: item.id > 0 ? item.id : null,
|
||||
name: item.name,
|
||||
quantity: item.quantity,
|
||||
packed: packedOf(item),
|
||||
checked: item.checked,
|
||||
weightGrams: item.unitGrams === null ? null : Math.min(MAX_GRAMS, item.unitGrams * item.quantity),
|
||||
bagKey: bagKeyOf(item.bagId),
|
||||
tier,
|
||||
sharedWith: card && tier === 'shared' ? peopleOf(card, item.recipientIds, 4) : [],
|
||||
change,
|
||||
changed,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The categories of a view of the list in the order it first shows them,
|
||||
* the way the packing panel colours them (`packingCategoryOrder`): the common
|
||||
* list, or the personal one.
|
||||
*/
|
||||
function categoryOrder(items: readonly ListItem[], personal: boolean): Array<string | null> {
|
||||
const order: Array<string | null> = [];
|
||||
for (const item of items) {
|
||||
if (item.isPrivate === personal && !order.includes(item.category)) order.push(item.category);
|
||||
}
|
||||
return order;
|
||||
}
|
||||
|
||||
/**
|
||||
* The colour slot of a category: its place in the order of the view its items
|
||||
* sit in (the personal one when every one of them is restricted), null for a
|
||||
* category the trip's list does not hold yet, and for every one without the trip card.
|
||||
*/
|
||||
export function slotOf(card: TripCard | null, category: string | null, personal: boolean): number | null {
|
||||
if (!card) return null;
|
||||
const index = categoryOrder(tripPacking(card), personal).indexOf(category);
|
||||
return index < 0 ? null : index;
|
||||
}
|
||||
|
||||
/** The people of an assignee list (`[{ user_id }]`), as trip members. */
|
||||
export function assigneesOf(card: TripCard, raw: unknown): CardPerson[] {
|
||||
return peopleOf(card, rowsOf(raw).flatMap((row) => positiveId(row.user_id) ?? []), 6);
|
||||
}
|
||||
|
||||
/** One bag as `list_packing_bags` answers it. */
|
||||
export function bagOf(card: TripCard, raw: unknown): PackingCardBag | null {
|
||||
const row = recordOf(raw);
|
||||
const id = positiveId(row.id);
|
||||
const name = clipped(row.name, 100);
|
||||
if (id === null || name === null) return null;
|
||||
const ownerId = positiveId(row.user_id);
|
||||
return {
|
||||
key: `id:${id}`,
|
||||
id,
|
||||
name,
|
||||
color: hexOrNull(row.color),
|
||||
weightGrams: gramsOf(row.total_weight_grams),
|
||||
limitGrams: gramsOf(row.weight_limit_grams),
|
||||
owner: ownerId === null ? null : personOf(card, ownerId),
|
||||
members: assigneesOf(card, row.members),
|
||||
membersRemoved: [],
|
||||
change: 'none',
|
||||
changed: [],
|
||||
movesOut: 0,
|
||||
};
|
||||
}
|
||||
|
||||
/** The bags of a `list_packing_bags` answer, in its order. */
|
||||
export function bagsOf(card: TripCard, value: unknown): PackingCardBag[] {
|
||||
return rowsOf(recordOf(value).bags).flatMap((row) => bagOf(card, row) ?? []);
|
||||
}
|
||||
|
||||
/** A group of items on its way to the card. */
|
||||
interface Bucket {
|
||||
key: PackingCardGroup['key'];
|
||||
items: ListItem[];
|
||||
assignees: CardPerson[];
|
||||
}
|
||||
|
||||
interface GroupOptions {
|
||||
groupBy: GroupBy;
|
||||
/** The bags in the list's order; a bag group follows it, the pile in no bag comes last. */
|
||||
bagIds: readonly number[];
|
||||
/** Who looks after a category. */
|
||||
assigneesOf?: (category: string | null) => CardPerson[];
|
||||
/** How a category from the answer is shown. */
|
||||
categoryName?: (category: string) => string | null;
|
||||
rowOf: (item: ListItem) => PackingCardItem;
|
||||
maxRows?: number;
|
||||
/** A card of one group shows up to `maxRows` of it, not eight (a change that adds many rows to one category). */
|
||||
fillSingleGroup?: boolean;
|
||||
}
|
||||
|
||||
function bucketsOf(card: TripCard | null, items: readonly ListItem[], options: GroupOptions): Bucket[] {
|
||||
const buckets = new Map<string, Bucket>();
|
||||
const name = options.categoryName ?? ((category: string) => clipped(category, 100));
|
||||
for (const item of items) {
|
||||
const key = options.groupBy === 'bag' ? `b${item.bagId ?? ''}` : `c${item.category ?? ''}`;
|
||||
let bucket = buckets.get(key);
|
||||
if (!bucket) {
|
||||
bucket = {
|
||||
key:
|
||||
options.groupBy === 'bag'
|
||||
? { by: 'bag', bagKey: bagKeyOf(item.bagId) }
|
||||
: { by: 'category', name: item.category === null ? null : name(item.category), slot: null },
|
||||
items: [],
|
||||
assignees: options.groupBy === 'category' ? (options.assigneesOf?.(item.category) ?? []) : [],
|
||||
};
|
||||
buckets.set(key, bucket);
|
||||
}
|
||||
bucket.items.push(item);
|
||||
}
|
||||
const list = [...buckets.values()];
|
||||
for (const bucket of list) {
|
||||
if (bucket.key.by !== 'category') continue;
|
||||
const personal = bucket.items.every((item) => item.isPrivate);
|
||||
bucket.key = { ...bucket.key, slot: slotOf(card, bucket.items[0]?.category ?? null, personal) };
|
||||
}
|
||||
if (options.groupBy !== 'bag') return list;
|
||||
const rank = (bucket: Bucket) => {
|
||||
const bagKey = bucket.key.by === 'bag' ? bucket.key.bagKey : null;
|
||||
if (bagKey === null) return Number.MAX_SAFE_INTEGER;
|
||||
const index = options.bagIds.indexOf(Number(bagKey.slice(3)));
|
||||
return index < 0 ? options.bagIds.length : index;
|
||||
};
|
||||
return list.sort((a, b) => rank(a) - rank(b));
|
||||
}
|
||||
|
||||
/**
|
||||
* The groups of a card: by category in the order the items first show them,
|
||||
* or by bag in the bags' order with the pile in no bag last. At most twelve
|
||||
* groups and 24 rows (eight per group); every group still counts all of its
|
||||
* items, and the groups left out are counted on the card.
|
||||
*/
|
||||
export function packingGroups(
|
||||
card: TripCard | null,
|
||||
items: readonly ListItem[],
|
||||
options: GroupOptions,
|
||||
): { groups: PackingCardGroup[]; moreGroups: number } {
|
||||
const buckets = bucketsOf(card, items.filter((item) => !item.placeholder), options);
|
||||
let left = options.maxRows ?? MAX_PACKING_ROWS;
|
||||
const perGroup = options.fillSingleGroup && buckets.length === 1 ? left : ROWS_PER_GROUP;
|
||||
const groups = buckets.slice(0, MAX_CARD_GROUPS).map((bucket): PackingCardGroup => {
|
||||
const shown = bucket.items.slice(0, Math.min(perGroup, left));
|
||||
left -= shown.length;
|
||||
return {
|
||||
key: bucket.key,
|
||||
assignees: bucket.assignees,
|
||||
assigneesRemoved: [],
|
||||
items: shown.map(options.rowOf),
|
||||
count: bucket.items.length,
|
||||
packed: bucket.items.filter((item) => item.checked).length,
|
||||
};
|
||||
});
|
||||
return { groups, moreGroups: Math.max(0, buckets.length - MAX_CARD_GROUPS) };
|
||||
}
|
||||
|
||||
/** The bags a card names: those its groups or rows point at, in the list's order. */
|
||||
export function bagsNamed(bags: readonly PackingCardBag[], groups: readonly PackingCardGroup[]): PackingCardBag[] {
|
||||
const keys = new Set<string>();
|
||||
for (const group of groups) {
|
||||
if (group.key.by === 'bag' && group.key.bagKey) keys.add(group.key.bagKey);
|
||||
for (const item of group.items) if (item.bagKey) keys.add(item.bagKey);
|
||||
}
|
||||
return bags.filter((bag) => keys.has(bag.key)).slice(0, MAX_CARD_BAGS);
|
||||
}
|
||||
|
||||
/**
|
||||
* The rows with a bag the card does not carry, taken out of it: a card that
|
||||
* read no bags (a tick, a tour) cannot name or colour the bag, and a row
|
||||
* pointing at a bag the reader cannot see would read as "Unassigned".
|
||||
*/
|
||||
function withKnownBags(groups: PackingCardGroup[], bags: readonly PackingCardBag[]): PackingCardGroup[] {
|
||||
const keys = new Set(bags.map((bag) => bag.key));
|
||||
const unknown = (row: PackingCardItem) => row.bagKey !== null && !keys.has(row.bagKey);
|
||||
return groups.map((group) =>
|
||||
group.items.some(unknown)
|
||||
? { ...group, items: group.items.map((row) => (unknown(row) ? { ...row, bagKey: null } : row)) }
|
||||
: group,
|
||||
);
|
||||
}
|
||||
|
||||
/** A packing card; a row's bag is always one of the card's bags. */
|
||||
export function packingCard(
|
||||
source: Source,
|
||||
groupBy: GroupBy,
|
||||
bags: PackingCardBag[],
|
||||
groups: PackingCardGroup[],
|
||||
extra: { moreGroups?: number; progress?: PackingListCard['progress'] } = {},
|
||||
): PackingListCard {
|
||||
const shown = bags.slice(0, MAX_CARD_BAGS);
|
||||
return {
|
||||
kind: 'packingList',
|
||||
source,
|
||||
groupBy,
|
||||
progress: extra.progress ?? null,
|
||||
bags: shown,
|
||||
groups: withKnownBags(groups, shown),
|
||||
moreGroups: extra.moreGroups ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
/** A card of one category group holding `rows`: what a change to one item shows. */
|
||||
export function categoryCard(
|
||||
card: TripCard,
|
||||
category: { name: string | null; raw: string | null; personal: boolean },
|
||||
rows: PackingCardItem[],
|
||||
bags: PackingCardBag[] = [],
|
||||
): PackingListCard {
|
||||
const group: PackingCardGroup = {
|
||||
key: { by: 'category', name: category.name, slot: slotOf(card, category.raw, category.personal) },
|
||||
assignees: [],
|
||||
assigneesRemoved: [],
|
||||
items: rows,
|
||||
count: rows.length,
|
||||
packed: rows.filter((row) => row.checked).length,
|
||||
};
|
||||
return packingCard({ type: 'trip' }, 'category', bags, [group]);
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
import type { Described, PreviewContext, ToolArgs, ToolCards } from '../card-types';
|
||||
import { argId, idIn, readKey, recordOf } from '../card-values';
|
||||
import { memberNames, Rows, text } from '../preview-format';
|
||||
import { byId, same, STABLE_FIELDS } from '../undo-snapshot';
|
||||
import { listBagsAnswer, listItemsAnswer, tourPackingAnswer } from './packing-answers';
|
||||
import {
|
||||
applyTemplateCard,
|
||||
bagMembersCard,
|
||||
bulkImportCard,
|
||||
createBagCard,
|
||||
createItemCard,
|
||||
deleteBagCard,
|
||||
deleteItemCard,
|
||||
linkTourCard,
|
||||
loadBags,
|
||||
loadBagsForImport,
|
||||
loadBagsWhenNamed,
|
||||
loadPackingAssignees,
|
||||
loadTemplates,
|
||||
packingAssigneesCard,
|
||||
sharingCard,
|
||||
toggleItemCard,
|
||||
updateBagCard,
|
||||
updateItemCard,
|
||||
} from './packing-changes';
|
||||
import { idsOf, itemRow, listItemsOf, packingCard, packingGroups, positiveId, rowsOf, tripItem } from './packing-rows';
|
||||
import type { AssistantChangePreview, PackingListCard, TrekCard } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* Every packing tool's entry: the cards of the reads, the change card of
|
||||
* every write, the words of the writes the core has no card for (named by
|
||||
* their own label, so the receipt says the bag or the list it touched), the
|
||||
* ways back from a tick and a new bag, and the ids a receipt names.
|
||||
*/
|
||||
|
||||
/** Ids one receipt names at most. */
|
||||
const MAX_APPLIED_IDS = 50;
|
||||
|
||||
/** The words of a change with its tool's own label. */
|
||||
function words(tool: string, subject: string, rows: Rows = new Rows()): Described {
|
||||
return { subject, rows, dayId: null, placeIds: [], tool };
|
||||
}
|
||||
|
||||
/** The item a call works on, named from the trip's list. */
|
||||
function itemName(ctx: PreviewContext, args: ToolArgs): string {
|
||||
const itemId = argId(args, 'itemId');
|
||||
return tripItem(ctx.card, itemId)?.name ?? (itemId === null ? '' : `#${itemId}`);
|
||||
}
|
||||
|
||||
/** A row the lookup read, by its id argument (`bagId` in `bags`, `templateId` in `templates`). */
|
||||
function lookedUp(loaded: unknown, list: string, args: ToolArgs, key: string): Record<string, unknown> | null {
|
||||
const wanted = argId(args, key);
|
||||
return wanted === null ? null : (rowsOf(recordOf(loaded)[list]).find((row) => row.id === wanted) ?? null);
|
||||
}
|
||||
|
||||
function lookedUpName(loaded: unknown, list: string, args: ToolArgs, key: string): string {
|
||||
const row = lookedUp(loaded, list, args, key);
|
||||
const wanted = argId(args, key);
|
||||
return row ? text(row.name) : wanted === null ? '' : `#${wanted}`;
|
||||
}
|
||||
|
||||
const grams = (value: unknown) => (typeof value === 'number' ? `${value} g` : '');
|
||||
|
||||
/** The ids a receipt names from an answer's `items` (an import, a template). */
|
||||
function itemIds(_args: ToolArgs, result: unknown): number[] {
|
||||
return rowsOf(recordOf(result).items)
|
||||
.flatMap((row) => positiveId(row.id) ?? [])
|
||||
.slice(0, MAX_APPLIED_IDS);
|
||||
}
|
||||
|
||||
const bagIdArg = (args: ToolArgs): number[] => {
|
||||
const bagId = argId(args, 'bagId');
|
||||
return bagId === null ? [] : [bagId];
|
||||
};
|
||||
|
||||
/** The applied card of a single new row: the preview's, with the id the server gave it. */
|
||||
function withCreatedId(result: unknown, preview: AssistantChangePreview | null): TrekCard | null {
|
||||
const id = positiveId(recordOf(recordOf(result).item).id);
|
||||
const card = preview?.card;
|
||||
if (id === null || card?.kind !== 'packingList') return null;
|
||||
const groups = card.groups.map((group) => ({
|
||||
...group,
|
||||
items: group.items.map((row) => (row.id === null ? { ...row, id } : row)),
|
||||
}));
|
||||
return { ...card, groups };
|
||||
}
|
||||
|
||||
/** The applied card of a template: the items it added, by category, under the template's name. */
|
||||
function templateApplied(result: unknown, preview: AssistantChangePreview | null): PackingListCard | null {
|
||||
const items = listItemsOf(recordOf(result).items).filter((item) => !item.placeholder);
|
||||
const card = preview?.card;
|
||||
if (items.length === 0 || card?.kind !== 'packingList') return null;
|
||||
const { groups, moreGroups } = packingGroups(null, items, {
|
||||
groupBy: 'category',
|
||||
bagIds: [],
|
||||
rowOf: (item) => ({ ...itemRow(null, item, 'add'), bagKey: null }),
|
||||
});
|
||||
return packingCard(card.source, 'category', [], groups, { moreGroups });
|
||||
}
|
||||
|
||||
/** How many of a ticked row were packed before the tick, as its change card kept it, and of how many. */
|
||||
function packedBefore(preview: AssistantChangePreview | null): { packed: number; quantity: number } | null {
|
||||
const card = preview?.card;
|
||||
const row = card?.kind === 'packingList' ? card.groups[0]?.items[0] : undefined;
|
||||
const kept = row?.changed.find((entry) => entry.field === 'packed')?.before;
|
||||
return row && typeof kept === 'string' ? { packed: Number(kept), quantity: row.quantity } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A ticked item taken back with the opposite tick, while it is still as the
|
||||
* tick left it, and only where that is where it was: a tick of an item with
|
||||
* nothing packed, an untick of one packed in full. A tick that changed
|
||||
* nothing, or one that wiped a partial count, has no way back.
|
||||
*/
|
||||
const UNTOGGLE_ITEM: NonNullable<ToolCards['undo']> = {
|
||||
tool: 'toggle_packing_item',
|
||||
args: (args, result, preview) => {
|
||||
const itemId = idIn(result, 'item') ?? argId(args, 'itemId');
|
||||
if (itemId === null || typeof args.checked !== 'boolean') return null;
|
||||
const was = packedBefore(preview);
|
||||
if (!was || was.packed !== (args.checked ? 0 : was.quantity)) return null;
|
||||
return { itemId, checked: !args.checked };
|
||||
},
|
||||
unchanged: (result, snapshot) => {
|
||||
const item = recordOf(recordOf(result).item);
|
||||
const items = rowsOf(recordOf(recordOf(snapshot.summary).packing).items);
|
||||
return same(item, byId(items, item.id), STABLE_FIELDS.packing);
|
||||
},
|
||||
};
|
||||
|
||||
const BAG_READ = { tool: 'list_packing_bags', args: {} };
|
||||
|
||||
/**
|
||||
* A new bag taken back while nobody has used it: it still has the name,
|
||||
* colour, limit and owner it was made with, nobody packs it, no item the user
|
||||
* can see sits in it and it weighs nothing (its weight counts every member's
|
||||
* items, so a hidden item with a weight shows there). Deleting a bag only
|
||||
* unpacks its items, so an item another member keeps to themselves would only
|
||||
* land in "Unassigned".
|
||||
*/
|
||||
const DELETE_CREATED_BAG: NonNullable<ToolCards['undo']> = {
|
||||
tool: 'delete_packing_bag',
|
||||
args: (_args, result) => {
|
||||
const bagId = idIn(result, 'bag');
|
||||
return bagId ? { bagId } : null;
|
||||
},
|
||||
reads: () => [BAG_READ],
|
||||
unchanged: (result, snapshot) => {
|
||||
const bag = recordOf(recordOf(result).bag);
|
||||
const bags = rowsOf(recordOf(snapshot.reads.get(readKey(BAG_READ.tool, BAG_READ.args))).bags);
|
||||
const current = byId(bags, bag.id);
|
||||
if (!current || !same(bag, current, ['name', 'color', 'weight_limit_grams', 'user_id'])) return false;
|
||||
const items = rowsOf(recordOf(recordOf(snapshot.summary).packing).items);
|
||||
const empty = !Number(current.total_weight_grams ?? 0);
|
||||
return empty && rowsOf(current.members).length === 0 && !items.some((item) => item.bag_id === bag.id);
|
||||
},
|
||||
};
|
||||
|
||||
const ITEM_UPDATE = { verbKey: 'genericUpdate', entity: 'packing' } as const;
|
||||
const BAG_UPDATE = { verbKey: 'genericUpdate', entity: 'packing_bag' } as const;
|
||||
|
||||
export const PACKING_TOOLS: Readonly<Record<string, ToolCards>> = {
|
||||
list_packing_items: { answer: listItemsAnswer },
|
||||
list_packing_bags: { answer: listBagsAnswer },
|
||||
get_tour_packing: { answer: tourPackingAnswer },
|
||||
link_tour_packing: { change: linkTourCard },
|
||||
create_packing_item: {
|
||||
load: loadBagsWhenNamed,
|
||||
change: createItemCard,
|
||||
applied: ({ result, preview }) => withCreatedId(result, preview),
|
||||
},
|
||||
update_packing_item: { load: loadBagsWhenNamed, change: updateItemCard },
|
||||
toggle_packing_item: {
|
||||
write: ITEM_UPDATE,
|
||||
describe: (ctx, args) => {
|
||||
const before = tripItem(ctx.card, argId(args, 'itemId'));
|
||||
const rows = new Rows();
|
||||
if (typeof args.checked === 'boolean') {
|
||||
rows.change('packed', before ? text(before.checked) : null, text(args.checked));
|
||||
}
|
||||
return words('toggle_packing_item', itemName(ctx, args), rows);
|
||||
},
|
||||
change: toggleItemCard,
|
||||
undo: UNTOGGLE_ITEM,
|
||||
},
|
||||
delete_packing_item: {
|
||||
write: { verbKey: 'genericRemove', entity: 'packing' },
|
||||
describe: (ctx, args) => words('delete_packing_item', itemName(ctx, args)),
|
||||
change: deleteItemCard,
|
||||
},
|
||||
set_packing_item_sharing: {
|
||||
write: ITEM_UPDATE,
|
||||
describe: (ctx, args) =>
|
||||
words(
|
||||
'set_packing_item_sharing',
|
||||
itemName(ctx, args),
|
||||
new Rows().add('type', text(args.visibility)).add('members', memberNames(ctx, args.recipient_ids)),
|
||||
),
|
||||
change: sharingCard,
|
||||
},
|
||||
bulk_import_packing: {
|
||||
write: { verbKey: 'genericCreate', entity: 'packing' },
|
||||
load: loadBagsForImport,
|
||||
describe: (_ctx, args) => {
|
||||
const names = rowsOf(args.items).flatMap((row) => (typeof row.name === 'string' ? row.name : []));
|
||||
return words('bulk_import_packing', text(names.join(', ')), new Rows().add('quantity', text(names.length || '')));
|
||||
},
|
||||
change: bulkImportCard,
|
||||
appliedIds: itemIds,
|
||||
},
|
||||
apply_packing_template: {
|
||||
write: { verbKey: 'genericCreate', entity: 'packing' },
|
||||
load: loadTemplates,
|
||||
describe: (_ctx, args, loaded) =>
|
||||
words(
|
||||
'apply_packing_template',
|
||||
lookedUpName(loaded, 'templates', args, 'templateId'),
|
||||
new Rows().add('type', text(args.visibility)),
|
||||
),
|
||||
change: applyTemplateCard,
|
||||
applied: ({ result, preview }) => templateApplied(result, preview),
|
||||
appliedIds: itemIds,
|
||||
},
|
||||
reorder_packing_items: {
|
||||
write: ITEM_UPDATE,
|
||||
describe: (ctx, args) => {
|
||||
const names = idsOf(args.orderedIds).map((id) => tripItem(ctx.card, id)?.name ?? `#${id}`);
|
||||
return words('reorder_packing_items', text(names.join(', ')));
|
||||
},
|
||||
},
|
||||
set_packing_category_assignees: {
|
||||
write: ITEM_UPDATE,
|
||||
load: loadPackingAssignees,
|
||||
describe: (ctx, args) =>
|
||||
words(
|
||||
'set_packing_category_assignees',
|
||||
text(args.categoryName),
|
||||
new Rows().add('members', memberNames(ctx, args.userIds)),
|
||||
),
|
||||
change: packingAssigneesCard,
|
||||
},
|
||||
create_packing_bag: {
|
||||
write: { verbKey: 'genericCreate', entity: 'packing_bag' },
|
||||
describe: (_ctx, args) =>
|
||||
words(
|
||||
'create_packing_bag',
|
||||
text(args.name),
|
||||
new Rows().add('color', text(args.color)).add('weight', grams(args.weight_limit_grams)),
|
||||
),
|
||||
change: createBagCard,
|
||||
appliedIds: (_args, result) => {
|
||||
const bagId = idIn(result, 'bag');
|
||||
return bagId === null ? [] : [bagId];
|
||||
},
|
||||
undo: DELETE_CREATED_BAG,
|
||||
},
|
||||
update_packing_bag: {
|
||||
write: BAG_UPDATE,
|
||||
load: loadBags,
|
||||
describe: (ctx, args, loaded) => {
|
||||
const bag = lookedUp(loaded, 'bags', args, 'bagId');
|
||||
const rows = new Rows();
|
||||
if (args.name !== undefined) rows.change('name', bag ? text(bag.name) : null, text(args.name));
|
||||
if (args.color !== undefined) rows.change('color', bag ? text(bag.color) : null, text(args.color));
|
||||
if (args.weight_limit_grams !== undefined) {
|
||||
rows.change('weight', bag ? grams(bag.weight_limit_grams) : null, grams(args.weight_limit_grams));
|
||||
}
|
||||
if (args.user_id !== undefined) {
|
||||
const owner = (id: unknown) => memberNames(ctx, typeof id === 'number' ? [id] : null);
|
||||
rows.change('assignee', bag ? owner(bag.user_id) : null, owner(args.user_id));
|
||||
}
|
||||
return words('update_packing_bag', lookedUpName(loaded, 'bags', args, 'bagId'), rows);
|
||||
},
|
||||
change: updateBagCard,
|
||||
appliedIds: bagIdArg,
|
||||
},
|
||||
delete_packing_bag: {
|
||||
write: { verbKey: 'genericRemove', entity: 'packing_bag' },
|
||||
load: loadBags,
|
||||
describe: (_ctx, args, loaded) => words('delete_packing_bag', lookedUpName(loaded, 'bags', args, 'bagId')),
|
||||
change: deleteBagCard,
|
||||
appliedIds: bagIdArg,
|
||||
},
|
||||
set_bag_members: {
|
||||
write: BAG_UPDATE,
|
||||
load: loadBags,
|
||||
describe: (ctx, args, loaded) =>
|
||||
words(
|
||||
'set_bag_members',
|
||||
lookedUpName(loaded, 'bags', args, 'bagId'),
|
||||
new Rows().add('members', memberNames(ctx, args.userIds)),
|
||||
),
|
||||
change: bagMembersCard,
|
||||
appliedIds: bagIdArg,
|
||||
},
|
||||
save_packing_template: {
|
||||
// Templates are global, not part of the trip, like the one `delete_packing_template` drops.
|
||||
write: { verbKey: 'genericCreate', entity: 'other' },
|
||||
describe: (_ctx, args) => words('save_packing_template', text(args.templateName)),
|
||||
},
|
||||
delete_packing_template: {
|
||||
write: { verbKey: 'genericRemove', entity: 'other' },
|
||||
load: loadTemplates,
|
||||
describe: (_ctx, args, loaded) =>
|
||||
words('delete_packing_template', lookedUpName(loaded, 'templates', args, 'templateId')),
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,303 @@
|
||||
import type { AnswerInput, PreviewContext, ToolArgs, ToolCards } from '../card-types';
|
||||
import { argId, clipped, recordOf } from '../card-values';
|
||||
import { formatDate, memberNames, Rows, text } from '../preview-format';
|
||||
import { byId, same, STABLE_FIELDS } from '../undo-snapshot';
|
||||
import { argText, idsOf, peopleOf, positiveId, rowsOf } from './packing-rows';
|
||||
import {
|
||||
dateOf,
|
||||
listTodosOf,
|
||||
priorityOf,
|
||||
todoCard,
|
||||
todoGroups,
|
||||
todoRow,
|
||||
todoSlot,
|
||||
tripTodo,
|
||||
tripTodos,
|
||||
type ListTodo,
|
||||
} from './todo-rows';
|
||||
import type { AssistantChangePreview, TodoCardItem, TodoListCard } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* The to-dos in the assistant chat: the list a read shows, grouped as the
|
||||
* to-do panel groups it, and the card each change to a to-do or to a list's
|
||||
* people shows inside its change card. A change names the to-do from the
|
||||
* trip as the turn read it; one it cannot find shows no card.
|
||||
*/
|
||||
|
||||
/** `list_todos`: the trip's to-dos by list, with what is open, done and overdue. */
|
||||
function listTodosAnswer({ value, card, today }: AnswerInput): TodoListCard | null {
|
||||
const todos = listTodosOf(recordOf(value).items);
|
||||
if (todos.length === 0) return null;
|
||||
const { groups, moreGroups } = todoGroups(card, todos);
|
||||
const open = todos.filter((todo) => !todo.checked);
|
||||
const progress = {
|
||||
open: open.length,
|
||||
done: todos.length - open.length,
|
||||
overdue: open.filter((todo) => todo.dueDate !== null && todo.dueDate < today).length,
|
||||
};
|
||||
return todoCard(groups, { moreGroups, progress });
|
||||
}
|
||||
|
||||
/**
|
||||
* One to-do in its list: what a change to a single to-do shows. The list's
|
||||
* name is masked when it comes from the trip, kept as written from arguments.
|
||||
*/
|
||||
function oneTodoCard(ctx: PreviewContext, row: TodoCardItem, category: string | null, mask = true): TodoListCard {
|
||||
const name = mask ? clipped(category, 100) : argText(category, 100);
|
||||
return todoCard([
|
||||
{
|
||||
category: name,
|
||||
slot: todoSlot(ctx.card, category),
|
||||
assignees: [],
|
||||
assigneesRemoved: [],
|
||||
items: [row],
|
||||
count: 1,
|
||||
open: row.checked ? 0 : 1,
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
function has(args: ToolArgs, key: string): boolean {
|
||||
return args[key] !== undefined;
|
||||
}
|
||||
|
||||
function descriptionOf(value: unknown): string | null {
|
||||
return typeof value === 'string' ? value : null;
|
||||
}
|
||||
|
||||
/** A to-do with the fields a write names merged in; `null` clears a field that may be empty. */
|
||||
function mergedTodo(before: ListTodo, args: ToolArgs): ListTodo {
|
||||
// A name sent again as it is stays the one shown, masked as the trip read it.
|
||||
const named = has(args, 'name') ? argText(args.name, 300) : null;
|
||||
return {
|
||||
...before,
|
||||
name: named === null || named === argText(before.rawName, 300) ? before.name : named,
|
||||
rawName: named ?? before.rawName,
|
||||
category: has(args, 'category') ? argText(args.category, 100) : before.category,
|
||||
dueDate: has(args, 'due_date') ? dateOf(args.due_date) : before.dueDate,
|
||||
description: has(args, 'description') ? descriptionOf(args.description) : before.description,
|
||||
assigneeId: has(args, 'assigned_user_id') ? positiveId(args.assigned_user_id) : before.assigneeId,
|
||||
priority: has(args, 'priority') ? priorityOf(args.priority) : before.priority,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The fields a write changes, each with what it held before. The notes are
|
||||
* the rows' own (the old one masked), the list names the old one masked.
|
||||
*/
|
||||
function todoChanges(
|
||||
ctx: PreviewContext,
|
||||
before: ListTodo,
|
||||
after: ListTodo,
|
||||
notes: [string | null, string | null],
|
||||
): TodoCardItem['changed'] {
|
||||
const name = (id: number | null) => (id === null ? null : (ctx.card.members.get(id)?.name ?? null));
|
||||
// Each field with its old value as shown, and whether the write changes it.
|
||||
const fields: Array<[TodoCardItem['changed'][number]['field'], string | null, boolean]> = [
|
||||
['name', before.name, before.name !== after.name],
|
||||
['note', notes[0], notes[0] !== notes[1]],
|
||||
['category', clipped(before.category, 100), before.category !== after.category],
|
||||
['dueDate', before.dueDate, before.dueDate !== after.dueDate],
|
||||
['priority', String(before.priority), before.priority !== after.priority],
|
||||
['assignee', name(before.assigneeId), before.assigneeId !== after.assigneeId],
|
||||
];
|
||||
return fields
|
||||
.filter(([, , changes]) => changes)
|
||||
.map(([field, old]) => ({ field, before: old === null ? null : old.slice(0, 120) }));
|
||||
}
|
||||
|
||||
function createTodoCard(ctx: PreviewContext, args: ToolArgs): TodoListCard | null {
|
||||
const name = argText(args.name, 300);
|
||||
if (name === null) return null;
|
||||
const category = argText(args.category, 100);
|
||||
const todo: ListTodo = {
|
||||
id: 0,
|
||||
name,
|
||||
rawName: name,
|
||||
category,
|
||||
checked: false,
|
||||
dueDate: dateOf(args.due_date),
|
||||
priority: priorityOf(args.priority),
|
||||
assigneeId: positiveId(args.assigned_user_id),
|
||||
description: descriptionOf(args.description),
|
||||
};
|
||||
return oneTodoCard(ctx, todoRow(ctx.card, todo, { mask: false, change: 'add' }), category, false);
|
||||
}
|
||||
|
||||
function updateTodoCard(ctx: PreviewContext, args: ToolArgs): TodoListCard | null {
|
||||
const before = tripTodo(ctx.card, argId(args, 'itemId'));
|
||||
if (!before) return null;
|
||||
const after = mergedTodo(before, args);
|
||||
// The note comes from the arguments only when the write sets it.
|
||||
const row = todoRow(ctx.card, after, { mask: !has(args, 'description'), change: 'update' });
|
||||
const oldNote = todoRow(ctx.card, before, { mask: true }).note;
|
||||
const changed = todoChanges(ctx, before, after, [oldNote, row.note]);
|
||||
return oneTodoCard(ctx, { ...row, changed }, after.category, !has(args, 'category'));
|
||||
}
|
||||
|
||||
/** A tick, keeping whether the to-do was done before, so the tick is only taken back when it changed that. */
|
||||
function toggleTodoCard(ctx: PreviewContext, args: ToolArgs): TodoListCard | null {
|
||||
const before = tripTodo(ctx.card, argId(args, 'itemId'));
|
||||
if (!before) return null;
|
||||
const checked = args.checked === true;
|
||||
const changed: TodoCardItem['changed'] = [{ field: 'done', before: before.checked ? '1' : '0' }];
|
||||
const change = checked ? 'check' : 'uncheck';
|
||||
const row = todoRow(ctx.card, { ...before, checked }, { mask: true, change, changed });
|
||||
return oneTodoCard(ctx, row, before.category);
|
||||
}
|
||||
|
||||
function deleteTodoCard(ctx: PreviewContext, args: ToolArgs): TodoListCard | null {
|
||||
const before = tripTodo(ctx.card, argId(args, 'itemId'));
|
||||
return before ? oneTodoCard(ctx, todoRow(ctx.card, before, { mask: true, change: 'remove' }), before.category) : null;
|
||||
}
|
||||
|
||||
/** The default assignees a list has now, by list name (`get_todo_category_assignees`). */
|
||||
type TodoAssignees = Record<string, unknown>;
|
||||
|
||||
async function loadTodoAssignees(_args: ToolArgs, read: (tool: string) => Promise<unknown>): Promise<TodoAssignees> {
|
||||
return recordOf(recordOf(await read('get_todo_category_assignees')).assignees);
|
||||
}
|
||||
|
||||
/** `set_todo_category_assignees`: the list's head with the people it will have and the ones it drops. */
|
||||
function todoAssigneesCard(ctx: PreviewContext, args: ToolArgs, loaded: TodoAssignees): TodoListCard | null {
|
||||
const category = argText(args.categoryName, 100);
|
||||
if (category === null || typeof args.categoryName !== 'string') return null;
|
||||
const chosen = idsOf(args.userIds);
|
||||
const before = rowsOf(loaded[args.categoryName]).flatMap((row) => positiveId(row.user_id) ?? []);
|
||||
const inList = tripTodos(ctx.card).filter((todo) => todo.category === args.categoryName);
|
||||
return todoCard([
|
||||
{
|
||||
category,
|
||||
slot: todoSlot(ctx.card, args.categoryName),
|
||||
assignees: peopleOf(ctx.card, chosen, 6),
|
||||
assigneesRemoved: peopleOf(ctx.card, before.filter((id) => !chosen.includes(id)), 6),
|
||||
items: [],
|
||||
count: inList.length,
|
||||
open: inList.filter((todo) => !todo.checked).length,
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
/** The name of the to-do a call works on, from the trip as the turn read it. */
|
||||
function todoName(ctx: PreviewContext, args: ToolArgs): string {
|
||||
const itemId = argId(args, 'itemId');
|
||||
return tripTodo(ctx.card, itemId)?.name ?? (itemId === null ? '' : `#${itemId}`);
|
||||
}
|
||||
|
||||
function updateTodoRows(ctx: PreviewContext, args: ToolArgs): Rows {
|
||||
const before = tripTodo(ctx.card, argId(args, 'itemId'));
|
||||
const rows = new Rows();
|
||||
const date = (value: unknown) => (typeof value === 'string' ? formatDate(ctx, value) : '');
|
||||
const priority = (value: unknown) => (typeof value === 'number' && value > 0 ? `P${value}` : '');
|
||||
const member = (id: unknown) => memberNames(ctx, id === null || id === undefined ? null : [id]);
|
||||
if (has(args, 'name')) rows.change('name', before?.name ?? null, text(args.name));
|
||||
// The old values are the trip's, so they are masked like an answer; the new ones are the call's own.
|
||||
if (has(args, 'description')) {
|
||||
rows.change('description', before ? clipped(before.description, 160) : null, text(args.description));
|
||||
}
|
||||
if (has(args, 'category')) {
|
||||
rows.change('category', before ? clipped(before.category, 100) : null, text(args.category));
|
||||
}
|
||||
if (has(args, 'due_date')) rows.change('dueDate', before ? date(before.dueDate) : null, date(args.due_date));
|
||||
if (has(args, 'priority')) {
|
||||
rows.change('priority', before ? priority(before.priority) : null, priority(args.priority));
|
||||
}
|
||||
if (has(args, 'assigned_user_id')) {
|
||||
rows.change('assignee', before ? member(before.assigneeId) : null, member(args.assigned_user_id));
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** Whether the to-do was done before its tick, as the tick's change card kept it. */
|
||||
function doneBefore(preview: AssistantChangePreview | null): string | null {
|
||||
const card = preview?.card;
|
||||
const row = card?.kind === 'todoList' ? card.groups[0]?.items[0] : undefined;
|
||||
return row?.changed.find((entry) => entry.field === 'done')?.before ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A toggled to-do taken back with the opposite toggle, while it is still as
|
||||
* the toggle left it, and only when the toggle changed it: ticking one that
|
||||
* was already done has no way back.
|
||||
*/
|
||||
const UNTOGGLE_TODO: NonNullable<ToolCards['undo']> = {
|
||||
tool: 'toggle_todo',
|
||||
args: (args, result, preview) => {
|
||||
const itemId = positiveId(recordOf(recordOf(result).item).id) ?? argId(args, 'itemId');
|
||||
if (itemId === null || typeof args.checked !== 'boolean') return null;
|
||||
if (doneBefore(preview) !== (args.checked ? '0' : '1')) return null;
|
||||
return { itemId, checked: !args.checked };
|
||||
},
|
||||
unchanged: (result, snapshot) => {
|
||||
const item = recordOf(recordOf(result).item);
|
||||
return same(item, byId(rowsOf(recordOf(snapshot.summary).todos), item.id), STABLE_FIELDS.todo);
|
||||
},
|
||||
};
|
||||
|
||||
const UPDATE = { verbKey: 'genericUpdate', entity: 'todo' } as const;
|
||||
|
||||
export const TODO_TOOLS: Readonly<Record<string, ToolCards>> = {
|
||||
list_todos: { answer: listTodosAnswer },
|
||||
create_todo: {
|
||||
change: createTodoCard,
|
||||
applied: ({ result, preview }) => {
|
||||
const id = positiveId(recordOf(recordOf(result).item).id);
|
||||
const card = preview?.card;
|
||||
if (id === null || card?.kind !== 'todoList') return null;
|
||||
return { ...card, groups: card.groups.map((g) => ({ ...g, items: g.items.map((row) => ({ ...row, id })) })) };
|
||||
},
|
||||
},
|
||||
update_todo: {
|
||||
write: UPDATE,
|
||||
describe: (ctx, args) => ({
|
||||
subject: todoName(ctx, args),
|
||||
rows: updateTodoRows(ctx, args),
|
||||
dayId: null,
|
||||
placeIds: [],
|
||||
tool: 'update_todo',
|
||||
}),
|
||||
change: updateTodoCard,
|
||||
},
|
||||
toggle_todo: {
|
||||
write: UPDATE,
|
||||
describe: (ctx, args) => ({
|
||||
subject: todoName(ctx, args),
|
||||
rows: new Rows(),
|
||||
dayId: null,
|
||||
placeIds: [],
|
||||
tool: 'toggle_todo',
|
||||
}),
|
||||
change: toggleTodoCard,
|
||||
undo: UNTOGGLE_TODO,
|
||||
},
|
||||
delete_todo: {
|
||||
write: { verbKey: 'genericRemove', entity: 'todo' },
|
||||
describe: (ctx, args) => ({
|
||||
subject: todoName(ctx, args),
|
||||
rows: new Rows(),
|
||||
dayId: null,
|
||||
placeIds: [],
|
||||
tool: 'delete_todo',
|
||||
}),
|
||||
change: deleteTodoCard,
|
||||
},
|
||||
reorder_todos: {
|
||||
write: UPDATE,
|
||||
describe: (ctx, args) => {
|
||||
const names = idsOf(args.orderedIds).map((id) => tripTodo(ctx.card, id)?.name ?? `#${id}`);
|
||||
return { subject: text(names.join(', ')), rows: new Rows(), dayId: null, placeIds: [], tool: 'reorder_todos' };
|
||||
},
|
||||
},
|
||||
set_todo_category_assignees: {
|
||||
write: UPDATE,
|
||||
load: loadTodoAssignees,
|
||||
describe: (ctx, args) => ({
|
||||
subject: text(args.categoryName),
|
||||
rows: new Rows().add('members', memberNames(ctx, args.userIds)),
|
||||
dayId: null,
|
||||
placeIds: [],
|
||||
tool: 'set_todo_category_assignees',
|
||||
}),
|
||||
change: (ctx, args, loaded) => todoAssigneesCard(ctx, args, recordOf(loaded)),
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,179 @@
|
||||
import type { TripCard } from '../../assistant-context';
|
||||
import { clipped, finite, personOf, recordOf } from '../card-values';
|
||||
import { argText, categoryOf, positiveId, rowsOf } from './packing-rows';
|
||||
import type { TodoCardGroup, TodoCardItem, TodoListCard } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* The pieces every to-do card is built from: a to-do as the to-do tools
|
||||
* answer it, its row, its group (its list) and the list's colour slot. Text
|
||||
* from a tool's answer is masked like a provider answer, text from a call's
|
||||
* arguments only cut.
|
||||
*/
|
||||
|
||||
const MAX_TODO_ROWS = 20;
|
||||
/** Rows a group shows at least, done ones filling up after the open ones. */
|
||||
const TODO_FILL = 5;
|
||||
const MAX_TODO_GROUPS = 12;
|
||||
const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
|
||||
|
||||
/** A to-do as `get_trip_summary`, `list_todos` and the writes answer it. */
|
||||
export interface ListTodo {
|
||||
id: number;
|
||||
/** As shown: masked when it comes from a tool's answer. */
|
||||
name: string;
|
||||
/** As stored, to tell whether a write really renames it; never shown. */
|
||||
rawName: string;
|
||||
category: string | null;
|
||||
checked: boolean;
|
||||
dueDate: string | null;
|
||||
priority: number;
|
||||
assigneeId: number | null;
|
||||
description: string | null;
|
||||
}
|
||||
|
||||
export function dateOf(value: unknown): string | null {
|
||||
return typeof value === 'string' && ISO_DATE.test(value) ? value : null;
|
||||
}
|
||||
|
||||
export function priorityOf(value: unknown): number {
|
||||
const n = finite(value);
|
||||
return n !== null && Number.isInteger(n) && n >= 1 && n <= 3 ? n : 0;
|
||||
}
|
||||
|
||||
/** One to-do from a tool's answer; null for a row without an id or a name. */
|
||||
function listTodoOf(raw: unknown): ListTodo | null {
|
||||
const row = recordOf(raw);
|
||||
const id = positiveId(row.id);
|
||||
const rawName = typeof row.name === 'string' ? row.name : null;
|
||||
const name = clipped(rawName, 300);
|
||||
if (id === null || rawName === null || name === null) return null;
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
rawName,
|
||||
category: categoryOf(row.category),
|
||||
checked: !!row.checked,
|
||||
dueDate: dateOf(row.due_date),
|
||||
priority: priorityOf(row.priority),
|
||||
assigneeId: positiveId(row.assigned_user_id),
|
||||
description: typeof row.description === 'string' ? row.description : null,
|
||||
};
|
||||
}
|
||||
|
||||
export function listTodosOf(value: unknown): ListTodo[] {
|
||||
return rowsOf(value).flatMap((row) => listTodoOf(row) ?? []);
|
||||
}
|
||||
|
||||
const TRIP_TODOS = new WeakMap<TripCard, ListTodo[]>();
|
||||
|
||||
/** The trip's to-dos as the turn read them; read once per card. */
|
||||
export function tripTodos(card: TripCard): ListTodo[] {
|
||||
let todos = TRIP_TODOS.get(card);
|
||||
if (!todos) {
|
||||
todos = listTodosOf(recordOf(card.sources.summary).todos);
|
||||
TRIP_TODOS.set(card, todos);
|
||||
}
|
||||
return todos;
|
||||
}
|
||||
|
||||
export function tripTodo(card: TripCard, id: number | null): ListTodo | null {
|
||||
return id === null ? null : (tripTodos(card).find((todo) => todo.id === id) ?? null);
|
||||
}
|
||||
|
||||
/** The trip day on a date, for the date to show it in the plan. */
|
||||
function dayOn(card: TripCard, date: string | null): number | null {
|
||||
return date === null ? null : (card.days.find((day) => day.date === date)?.id ?? null);
|
||||
}
|
||||
|
||||
/** The first line of a description with text on it: masked from an answer, only cut from arguments. */
|
||||
function noteOf(description: string | null, mask: boolean): string | null {
|
||||
const line = description?.split(/\r?\n/).find((part) => part.trim() !== '') ?? null;
|
||||
return mask ? clipped(line, 160) : argText(line, 160);
|
||||
}
|
||||
|
||||
/**
|
||||
* The lists in the order the to-do panel sorts them (`todoCategories`): by
|
||||
* name in the reader's language, the same `localeCompare` the panel calls.
|
||||
*/
|
||||
function todoCategories(todos: readonly ListTodo[]): string[] {
|
||||
const names = new Set<string>();
|
||||
for (const todo of todos) if (todo.category) names.add(todo.category);
|
||||
return [...names].sort((a, b) => a.localeCompare(b));
|
||||
}
|
||||
|
||||
/** A list's colour slot among the trip's lists; null for a list the trip does not hold yet. */
|
||||
export function todoSlot(card: TripCard, category: string | null): number | null {
|
||||
if (category === null) return null;
|
||||
const index = todoCategories(tripTodos(card)).indexOf(category);
|
||||
return index < 0 ? null : index;
|
||||
}
|
||||
|
||||
/** A to-do's row on a card; the note is masked unless it comes from the call's own arguments. */
|
||||
export function todoRow(
|
||||
card: TripCard,
|
||||
todo: ListTodo,
|
||||
options: { mask: boolean; change?: TodoCardItem['change']; changed?: TodoCardItem['changed'] },
|
||||
): TodoCardItem {
|
||||
return {
|
||||
id: todo.id > 0 ? todo.id : null,
|
||||
name: todo.name,
|
||||
note: noteOf(todo.description, options.mask),
|
||||
checked: todo.checked,
|
||||
dueDate: todo.dueDate,
|
||||
dueDayId: dayOn(card, todo.dueDate),
|
||||
priority: todo.priority,
|
||||
assignee: todo.assigneeId === null ? null : personOf(card, todo.assigneeId),
|
||||
change: options.change ?? 'none',
|
||||
changed: options.changed ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
/** Nearest due date first, undated ones after every dated one; ties keep their order (`compareTodoDue`). */
|
||||
function compareDue(a: ListTodo, b: ListTodo): number {
|
||||
if (!a.dueDate) return b.dueDate ? 1 : 0;
|
||||
if (!b.dueDate) return -1;
|
||||
return a.dueDate < b.dueDate ? -1 : a.dueDate > b.dueDate ? 1 : 0;
|
||||
}
|
||||
|
||||
/** A to-do list card. */
|
||||
export function todoCard(
|
||||
groups: TodoCardGroup[],
|
||||
extra: { moreGroups?: number; progress?: TodoListCard['progress'] } = {},
|
||||
): TodoListCard {
|
||||
return { kind: 'todoList', progress: extra.progress ?? null, groups, moreGroups: extra.moreGroups ?? 0 };
|
||||
}
|
||||
|
||||
/**
|
||||
* The to-dos of an answer by list, in the panel's order with the ones on no
|
||||
* list last. A list shows its open to-dos first, overdue and soonest due on
|
||||
* top, and done ones only to fill up to five rows; 20 rows in all. Every
|
||||
* group counts all of its to-dos.
|
||||
*/
|
||||
export function todoGroups(
|
||||
card: TripCard,
|
||||
todos: readonly ListTodo[],
|
||||
): { groups: TodoCardGroup[]; moreGroups: number } {
|
||||
const lists: Array<string | null> = todoCategories(todos);
|
||||
if (todos.some((todo) => todo.category === null)) lists.push(null);
|
||||
let left = MAX_TODO_ROWS;
|
||||
const groups = lists.slice(0, MAX_TODO_GROUPS).map((category, slot): TodoCardGroup => {
|
||||
const all = todos.filter((todo) => todo.category === category);
|
||||
const open = all.filter((todo) => !todo.checked).sort(compareDue);
|
||||
const shown = open.slice(0, left);
|
||||
for (const done of all.filter((todo) => todo.checked)) {
|
||||
if (shown.length >= Math.min(TODO_FILL, left)) break;
|
||||
shown.push(done);
|
||||
}
|
||||
left -= shown.length;
|
||||
return {
|
||||
category: category === null ? null : clipped(category, 100),
|
||||
slot: category === null ? null : slot,
|
||||
assignees: [],
|
||||
assigneesRemoved: [],
|
||||
items: shown.map((todo) => todoRow(card, todo, { mask: true })),
|
||||
count: all.length,
|
||||
open: open.length,
|
||||
};
|
||||
});
|
||||
return { groups, moreGroups: Math.max(0, lists.length - MAX_TODO_GROUPS) };
|
||||
}
|
||||
@@ -21,15 +21,20 @@ import {
|
||||
packingApplyTemplateRequestSchema,
|
||||
packingCreateBagRequestSchema,
|
||||
packingCreateItemRequestSchema,
|
||||
packingListItemsRequestSchema,
|
||||
packingSetSharingRequestSchema,
|
||||
packingUpdateBagRequestSchema,
|
||||
packingUpdateItemRequestSchema,
|
||||
type PackingListItemsRequest,
|
||||
type PackingVisibility,
|
||||
idSchema,
|
||||
} from '@trek/shared';
|
||||
|
||||
import { z } from 'zod';
|
||||
|
||||
/** What `list_packing_items` filters a packing item by. */
|
||||
type PackingListRow = { category?: string | null; bag_id?: number | null; checked?: number | boolean | null };
|
||||
|
||||
/** Legacy registrar gate: the whole packing surface rides the packing addon. */
|
||||
const packingAddonOn = addonGate(ADDON_IDS.PACKING);
|
||||
|
||||
@@ -50,9 +55,10 @@ function parseId(value: string | string[]): number | null {
|
||||
* by trekMcpAccessPolicy). The two template-management tools keep their inline
|
||||
* admin gate (isAdminUser), matching the REST routes.
|
||||
*
|
||||
* set_packing_item_sharing is the one tool with no legacy ancestor: PUT
|
||||
* /:id/sharing had no counterpart here, so the whole three-tier sharing model
|
||||
* (#858) was invisible to an assistant.
|
||||
* set_packing_item_sharing and list_packing_items have no legacy ancestor.
|
||||
* PUT /:id/sharing had no counterpart here, so the whole three-tier sharing
|
||||
* model (#858) was invisible to an assistant; and the items themselves could
|
||||
* only be read inside get_trip_summary, unfiltered and without their bags.
|
||||
*/
|
||||
@McpController()
|
||||
export class PackingMcp {
|
||||
@@ -308,6 +314,47 @@ export class PackingMcp {
|
||||
return ok({ success: true });
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'list_packing_items',
|
||||
description:
|
||||
"List the packing items of a trip the user may see (another member's personal items stay hidden), with the trip's bags and who looks after each category. Narrow it to one category, one bag or what is still open; group_by says how the list is meant to be shown, by category or by bag, as the packing list groups it.",
|
||||
inputSchema: {
|
||||
tripId: idSchema,
|
||||
category: packingListItemsRequestSchema.shape.category.describe(
|
||||
'Only the items of this category, named exactly as the items carry it',
|
||||
),
|
||||
bag_id: packingListItemsRequestSchema.shape.bag_id.describe(
|
||||
'Only the items in this bag (ids come from list_packing_bags); null for the items in no bag',
|
||||
),
|
||||
status: packingListItemsRequestSchema.shape.status.describe(
|
||||
"'open' for what is still to pack, 'packed' for what is ticked off, 'all' (the default) for both",
|
||||
),
|
||||
group_by: packingListItemsRequestSchema.shape.group_by.describe(
|
||||
"How the list is shown: by 'category' (the default) or by 'bag'. It filters nothing",
|
||||
),
|
||||
},
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
when: packingAddonOn,
|
||||
access: { group: 'packing', mode: 'read' },
|
||||
})
|
||||
async listPackingItems(
|
||||
{ tripId, category, bag_id, status }: { tripId: number } & PackingListItemsRequest,
|
||||
ctx: McpContext,
|
||||
) {
|
||||
if (!(await this.packing.verifyTripAccess(tripId, ctx.userId))) return noAccess();
|
||||
// The viewer's own list (#858): another member's personal items never come back.
|
||||
const visible = (await this.packing.listItems(tripId, ctx.userId)) as PackingListRow[];
|
||||
const items = visible.filter(
|
||||
(item) =>
|
||||
(category === undefined || item.category === category) &&
|
||||
(bag_id === undefined || (item.bag_id ?? null) === bag_id) &&
|
||||
(status === 'open' ? !item.checked : status === 'packed' ? !!item.checked : true),
|
||||
);
|
||||
const bags = await this.packing.listBags(tripId);
|
||||
const category_assignees = await this.packing.getCategoryAssignees(tripId);
|
||||
return ok({ items, bags, category_assignees });
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'list_packing_bags',
|
||||
description: 'List all packing bags for a trip.',
|
||||
|
||||
Reference in New Issue
Block a user