feat(assistant): vacation calendar cards with the days left

This commit is contained in:
Maurice
2026-10-22 15:50:55 +02:00
parent da7af8337d
commit c0f75b9a5e
59 changed files with 4783 additions and 70 deletions
+57 -3
View File
@@ -1,4 +1,58 @@
import type { DomainCards } from '../card-types';
import type { DomainCards, ToolCards } from '../card-types';
import { VACAY_ANSWER_CARDS } from './vacay-answer';
import { appliedCompany, appliedToggle } from './vacay-applied';
import { VACAY_CHANGE_CARDS, VACAY_DESCRIBERS } from './vacay-change';
import { loadDay, loadStats, type VacayLoaded, type VacayStatsLoaded } from './vacay-load';
/** The cards of the vacation planner. None yet: this package fills them in. */
export const VACAY_CARDS: DomainCards = { id: 'vacay', tools: {} };
/**
* The vacation planner in the assistant chat. Its reads show the days off,
* the days left and the public holidays on a month calendar; a held toggle,
* company holiday or new allowance shows the day (or the year) it changes,
* with the leave before and after. Vacation days are the plan's, not the
* trip's, so each held change looks the plan up first (`load`). A decision
* can come hours after the hold, so the applied card follows what the tool
* says it did, not what the held card foresaw (`applied`).
*
* A toggle cannot be undone from the chat yet: whether the day is still as
* the change left it needs the change's own date, which an undo check is not
* handed (`undo.unchanged` gets the result only, and the result names no
* date). The other vacation writes stay cards built from their arguments.
*/
const toggle: ToolCards<VacayLoaded> = {
write: { verbKey: 'addVacationDay', entity: 'vacay' },
load: loadDay,
describe: VACAY_DESCRIBERS.toggle_vacay_entry,
change: VACAY_CHANGE_CARDS.toggle_vacay_entry,
applied: appliedToggle,
};
const companyHoliday: ToolCards<VacayLoaded> = {
write: { verbKey: 'setCompanyHoliday', entity: 'vacay' },
load: loadDay,
describe: VACAY_DESCRIBERS.toggle_company_holiday,
change: VACAY_CHANGE_CARDS.toggle_company_holiday,
applied: appliedCompany,
};
const allowance: ToolCards<VacayStatsLoaded> = {
write: { verbKey: 'setVacationAllowance', entity: 'vacay' },
load: loadStats,
describe: VACAY_DESCRIBERS.update_vacay_stats,
change: VACAY_CHANGE_CARDS.update_vacay_stats,
};
export const VACAY_CARDS: DomainCards = {
id: 'vacay',
tools: {
toggle_vacay_entry: toggle,
toggle_company_holiday: companyHoliday,
update_vacay_stats: allowance,
get_vacay_entries: { answer: VACAY_ANSWER_CARDS.get_vacay_entries },
get_vacay_stats: { answer: VACAY_ANSWER_CARDS.get_vacay_stats },
list_holidays: { answer: VACAY_ANSWER_CARDS.list_holidays },
},
prompt: [
'toggle_vacay_entry clears a day logged with the same size and kind, so read get_vacay_entries before you toggle.',
],
};
@@ -0,0 +1,128 @@
import type { AnswerInput } from '../card-types';
import {
balanceOf,
companyIn,
daysIn,
inMonths,
keepKnown,
knownPeople,
monthKey,
monthOf,
peopleOf,
tripDatesIn,
tripMonthsOf,
type CardMonth,
} from './vacay-frame';
import { yearArg } from './vacay-load';
import { entriesOf, holidaysOf, statsOf, type VacayEntryRow } from './vacay-reads';
import { VACAY_CARD_MAX_HOLIDAYS, type VacayCard } from '@trek/shared';
/**
* The answer cards of the vacation planner's reads: the days off of a year on
* a few months of calendar (`get_vacay_entries`), the days left per person
* (`get_vacay_stats`) and a country's public holidays (`list_holidays`). An
* answer card has the read's own answer and the trip card, nothing else, so
* it draws the planner's usual week (Monday first, Saturday and Sunday off).
*/
const MAX_MONTHS = 3;
/** An answer card with nothing on it yet. */
function emptyCard(): VacayCard {
return {
kind: 'vacay',
months: [],
weekStart: 1,
weekendDays: [0, 6],
people: [],
days: [],
company: [],
holidays: [],
tripDates: [],
proposal: null,
balances: [],
otherDays: 0,
};
}
/** The distinct months of `dates` in order, at most `max`. */
function monthsOfDates(dates: readonly string[], max: number): CardMonth[] {
const keys = [...new Set([...dates].sort().map(monthKey))].slice(0, max);
return keys.map((key) => monthOf(`${key}-01`));
}
/**
* The months a year's days off are shown on: the trip's months inside the
* year, else the coming months the signed-in user is off in, else this month
* when it lies in the year, else the year's first month. The year is taken
* from January to December, widened to the months the answer holds days of.
*/
function focusMonths(input: AnswerInput, entries: readonly VacayEntryRow[], year: number): CardMonth[] {
const span = [`${year}-01`, `${year}-12`, ...entries.map((entry) => monthKey(entry.date))].sort();
const first = span[0] ?? `${year}-01`;
const last = span[span.length - 1] ?? `${year}-12`;
const inside = (key: string) => key >= first && key <= last;
const trip = tripMonthsOf(input.card, 12).filter((month) => inside(monthKey(month)));
if (trip.length > 0) return trip.slice(0, MAX_MONTHS);
const coming = entries
.filter((entry) => entry.personId === input.card.viewerId && entry.date >= input.today)
.map((entry) => entry.date);
if (coming.length > 0) return monthsOfDates(coming, MAX_MONTHS);
if (inside(monthKey(input.today))) return [monthOf(input.today)];
return [monthOf(`${first}-01`)];
}
export const VACAY_ANSWER_CARDS = {
get_vacay_entries: (input: AnswerInput): VacayCard | null => {
const logged = entriesOf(input.value);
if (!logged) return null;
const viewerId = input.card.viewerId;
const year = yearArg(input.args);
const months = focusMonths(input, logged.entries, year ?? Number(input.today.slice(0, 4)));
const days = daysIn(logged.entries, months, viewerId);
const people = peopleOf(
[viewerId, ...days.map((day) => day.personId)],
knownPeople(null, logged.entries, []),
viewerId,
);
const otherDays = logged.entries
.filter((entry) => entry.personId === viewerId && entry.kind === 'vacation' && !inMonths(entry.date, months))
.reduce((sum, entry) => sum + entry.fraction, 0);
return {
...emptyCard(),
months,
people,
days: keepKnown(days, people),
company: companyIn(logged.company, months),
tripDates: tripDatesIn(input.card, months),
otherDays: Math.min(1000, otherDays),
// The leave year asked for, which Vacay opens on: a leave year from April holds a February trip of the next.
...(year === null ? {} : { year }),
};
},
get_vacay_stats: (input: AnswerInput): VacayCard | null => {
const stats = statsOf(input.value);
if (!stats || stats.length === 0) return null;
const viewerId = input.card.viewerId;
const people = peopleOf(stats.map((row) => row.personId), knownPeople(null, [], stats), viewerId);
const order = new Map(people.map((person, index) => [person.id, index]));
const balances = keepKnown(stats, people)
.sort((a, b) => (order.get(a.personId) ?? 0) - (order.get(b.personId) ?? 0))
.map((row) => balanceOf(row));
return { ...emptyCard(), people, balances };
},
list_holidays: (input: AnswerInput): VacayCard | null => {
const holidays = holidaysOf(input.value, null, null);
if (holidays.length === 0) return null;
const dates = holidays.map((holiday) => holiday.date);
const trip = tripMonthsOf(input.card).filter((month) => dates.some((date) => inMonths(date, [month])));
const coming = dates.filter((date) => date >= input.today);
const months = trip.length > 0 ? trip : monthsOfDates(coming.length > 0 ? coming : dates, 2);
return {
...emptyCard(),
months,
holidays: holidays.filter((holiday) => inMonths(holiday.date, months)).slice(0, VACAY_CARD_MAX_HOLIDAYS),
tripDates: tripDatesIn(input.card, months),
};
},
};
@@ -0,0 +1,103 @@
import type { ToolArgs } from '../card-types';
import { recordOf } from '../card-values';
import { counted } from './vacay-change';
import type { Fraction } from './vacay-reads';
import type { AssistantChangePreview, VacayCard, VacayCardProposal } from '@trek/shared';
/**
* The card of an applied vacation change. The change card was drawn when the
* call was held, which can be hours before the user decided, and the day may
* have changed since; the tool's answer says what was really done (`added`,
* `removed`, `updated`). Where that is what the card foresaw, the card stands.
* Where it is not, the day shows what was done, and the days left follow the
* answer where it tells enough to count them and change nothing where it does
* not, rather than show a count the day never got.
*/
type Outcome = VacayCardProposal['outcome'];
type DayKind = VacayCardProposal['kind'];
interface AppliedInput {
args: ToolArgs;
result: unknown;
preview: AssistantChangePreview | null;
}
const DONE = new Map<string, Outcome>([
['added', 'add'],
['removed', 'remove'],
['updated', 'convert'],
]);
/** The held card with its day, when the stored preview has one. */
function heldOf(preview: AssistantChangePreview | null): { card: VacayCard; proposal: VacayCardProposal } | null {
const card = preview?.card;
if (card?.kind !== 'vacay' || !card.proposal) return null;
return { card, proposal: card.proposal };
}
/** What the tool says it did; null for an answer that names nothing (a refusal). */
function doneOf(result: unknown): Outcome | null {
const action = recordOf(result).action;
return typeof action === 'string' ? (DONE.get(action) ?? null) : null;
}
function fractionOf(value: unknown, fallback: Fraction): Fraction {
if (value === 0.5 || value === 1) return value;
return fallback;
}
function kindOf(value: unknown, fallback: DayKind): DayKind {
if (value === 'vacation' || value === 'comp') return value;
return fallback;
}
/**
* What a toggle that did `outcome` adds to the used days: an added day by its
* own size, a cleared one by the size it was asked with (the planner clears
* only that), a converted one only when the card knew the day before.
*/
function toggleDays(
outcome: Outcome,
proposal: VacayCardProposal,
done: { fraction: Fraction; kind: DayKind },
): number | null {
if (outcome === 'add') return counted(done.kind, done.fraction);
if (outcome === 'remove') return -counted(proposal.kind, proposal.fraction);
if (outcome === 'convert' && proposal.before) {
return counted(done.kind, done.fraction) - counted(proposal.before.kind, proposal.before.fraction);
}
return null;
}
/** A day off as it was applied. */
export function appliedToggle({ result, preview }: AppliedInput): VacayCard | null {
const held = heldOf(preview);
const outcome = doneOf(result);
if (!held || !outcome) return null;
const { card, proposal } = held;
const answer = recordOf(result);
const fraction = fractionOf(answer.fraction, proposal.fraction);
const kind = kindOf(answer.kind, proposal.kind);
if (outcome === proposal.outcome && fraction === proposal.fraction && kind === proposal.kind) return card;
const days = toggleDays(outcome, proposal, { fraction, kind });
const { personId, periodYear } = proposal;
const deltas =
days === null || personId === null || periodYear === null ? [] : [{ personId, year: periodYear, days }];
return { ...card, proposal: { ...proposal, outcome, fraction, kind, deltas } };
}
/**
* A company holiday as it was applied. What it gave back depends on the days
* logged when it was applied, which the answer does not name, so a holiday
* that did something else than foreseen changes nobody's days left.
*/
export function appliedCompany({ result, preview }: AppliedInput): VacayCard | null {
const held = heldOf(preview);
const outcome = doneOf(result);
if (!held || !outcome) return null;
const { card, proposal } = held;
const fraction = fractionOf(recordOf(result).fraction, proposal.fraction);
if (outcome === proposal.outcome && fraction === proposal.fraction) return card;
return { ...card, proposal: { ...proposal, outcome, fraction, deltas: [] } };
}
@@ -0,0 +1,250 @@
import type { Described, PreviewContext, ToolArgs } from '../card-types';
import { argId } from '../card-values';
import { formatDate, Rows, text } from '../preview-format';
import {
balanceOf,
companyIn,
daysIn,
inMonths,
keepKnown,
knownPeople,
monthOf,
peopleOf,
periodOf,
tripDatesIn,
} from './vacay-frame';
import { dateArg, yearArg, type VacayLoaded, type VacayStatsLoaded } from './vacay-load';
import type { Fraction, VacayEntryRow } from './vacay-reads';
import {
VACAY_CARD_MAX_HOLIDAYS,
type AssistantChangeVerbKey,
type VacayCard,
type VacayCardProposal,
type VacayDayKind,
type VacayProposalNote,
} from '@trek/shared';
/**
* The change cards of the vacation planner: a day off taken, given back or
* changed (`toggle_vacay_entry`), a company holiday (`toggle_company_holiday`)
* and a new allowance (`update_vacay_stats`). A toggle's arguments do not say
* whether it adds or clears a day, so the card works it out from what is
* logged, the way the planner's service will: the same size and kind again
* clears the day, another converts it, a blocked weekend refuses it, and half
* a company holiday leaves room for half a day only. The card shows the day on
* its month with the leave before it; the client works out the leave after.
*/
/** A day off as it counts against the allowance: leave by its size, a comp day not at all. */
export function counted(kind: VacayDayKind, fraction: Fraction): number {
return kind === 'vacation' ? fraction : 0;
}
function weekdayOf(date: string): number {
return new Date(`${date}T00:00:00Z`).getUTCDay();
}
function fractionArg(value: unknown): Fraction {
return value === 0.5 ? 0.5 : 1;
}
/** What a toggle does to a day: the same size and kind clears it, another converts it, a blocked weekend refuses. */
function toggleOutcome(
inPlan: boolean,
existing: VacayEntryRow | undefined,
asked: { fraction: Fraction; kind: 'vacation' | 'comp' },
blockedDay: boolean,
): VacayCardProposal['outcome'] {
if (!inPlan) return 'blocked';
if (existing && existing.fraction === asked.fraction && existing.kind === asked.kind) return 'remove';
if (blockedDay) return 'blocked';
return existing ? 'convert' : 'add';
}
/** What the user should know about the day before the toggle is applied. */
function toggleNotes(
loaded: VacayLoaded,
date: string,
facts: { inPlan: boolean; weekend: boolean; counts: boolean; outcome: VacayCardProposal['outcome'] },
): VacayProposalNote[] {
const { plan } = loaded;
const company = plan.companyOn ? loaded.company.find((row) => row.date === date) : undefined;
const notes: VacayProposalNote[] = [];
if (!facts.inPlan) notes.push('notInPlan');
else if (facts.weekend && plan.blockWeekends && facts.outcome === 'blocked') notes.push('weekendBlocked');
if (facts.weekend && !plan.blockWeekends && facts.counts) notes.push('weekend');
if (loaded.holidays.some((holiday) => holiday.date === date)) notes.push('publicHoliday');
if (company?.fraction === 1) notes.push('companyHoliday');
if (company?.fraction === 0.5) notes.push('companyHalf');
return notes;
}
/** What a toggle of `date` would do, for whom and to which leave year. */
function toggleProposal(viewerId: number, args: ToolArgs, loaded: VacayLoaded, date: string): VacayCardProposal {
const { plan } = loaded;
const named = argId(args, 'targetUserId');
// A target that is no id is refused by the tool's schema: the card says so instead of showing the user's own day.
const unreadable = named === null && args.targetUserId !== undefined && args.targetUserId !== null;
const personId = named ?? viewerId;
const inPlan = !unreadable && plan.people.has(personId);
const company = plan.companyOn ? loaded.company.find((row) => row.date === date) : undefined;
const fraction: Fraction = company?.fraction === 0.5 ? 0.5 : fractionArg(args.fraction);
const kind = args.kind === 'comp' ? 'comp' : 'vacation';
const existing = loaded.entries.find((entry) => entry.date === date && entry.personId === personId);
const weekend = plan.weekendDays.includes(weekdayOf(date));
const outcome = toggleOutcome(inPlan, existing, { fraction, kind }, weekend && plan.blockWeekends);
const was = existing ? counted(existing.kind, existing.fraction) : 0;
const will = outcome === 'remove' ? 0 : outcome === 'blocked' ? was : counted(kind, fraction);
const year = Number(date.slice(0, 4));
const periodYear = periodOf(date, loaded.stats.find((row) => row.personId === personId && row.year === year));
const counts = kind === 'vacation' && (outcome === 'add' || outcome === 'convert');
return {
date,
personId,
kind,
fraction,
outcome,
before: existing ? { fraction: existing.fraction, kind: existing.kind } : null,
periodYear,
notes: toggleNotes(loaded, date, { inPlan, weekend, counts, outcome }),
deltas: inPlan ? [{ personId, year: periodYear, days: will - was }] : [],
};
}
/** What a whole company holiday takes off a logged day, and a half one: a whole day becomes half a day. */
function companyDelta(entry: VacayEntryRow, fraction: Fraction): number {
if (fraction === 1) return -counted(entry.kind, entry.fraction);
return entry.fraction === 1 ? -counted(entry.kind, 0.5) : 0;
}
/** What a company holiday on `date` would do to the plan and to everyone's leave that day. */
function companyProposal(args: ToolArgs, loaded: VacayLoaded, date: string): VacayCardProposal {
const fraction: Fraction = args.half === true ? 0.5 : 1;
const existing = loaded.company.find((row) => row.date === date);
let outcome: VacayCardProposal['outcome'] = existing ? 'convert' : 'add';
if (existing?.fraction === fraction) outcome = 'remove';
const year = Number(date.slice(0, 4));
const deltas =
outcome === 'remove'
? []
: loaded.entries.flatMap((entry) => {
const days = entry.date === date ? companyDelta(entry, fraction) : 0;
if (days === 0) return [];
const row = loaded.stats.find((stat) => stat.personId === entry.personId && stat.year === year);
return [{ personId: entry.personId, year: periodOf(date, row), days }];
});
const notes: VacayProposalNote[] = [];
// The planner refuses a company holiday while they are off, the tool still writes one: the card warns.
if (!loaded.plan.companyOn) notes.push('companyOff');
if (loaded.holidays.some((holiday) => holiday.date === date)) notes.push('publicHoliday');
return {
date,
personId: null,
kind: 'company',
fraction,
outcome,
before: existing ? { fraction: existing.fraction, kind: 'company' } : null,
periodYear: null,
notes,
deltas: deltas.slice(0, 8),
};
}
/** The month of a held day with what is logged there, the change and the leave before it. */
function dayCard(ctx: PreviewContext, loaded: VacayLoaded, proposal: VacayCardProposal): VacayCard {
const viewerId = ctx.card.viewerId;
const months = [monthOf(proposal.date)];
const days = daysIn(loaded.entries, months, viewerId);
const touched = proposal.personId === null ? proposal.deltas.map((delta) => delta.personId) : [proposal.personId];
const known = knownPeople(loaded.plan.people, loaded.entries, loaded.stats);
const people = peopleOf([viewerId, ...touched, ...days.map((day) => day.personId)], known, viewerId);
const periods = new Set(proposal.deltas.map((delta) => `${delta.personId}:${delta.year}`));
const rows = loaded.stats.filter((row) => periods.has(`${row.personId}:${row.year}`));
const balances = rows.map((row) => balanceOf(row));
return {
kind: 'vacay',
months,
weekStart: loaded.plan.weekStart,
weekendDays: loaded.plan.weekendDays,
people,
days: keepKnown(days, people),
company: companyIn(loaded.company, months),
holidays: loaded.holidays.filter((row) => inMonths(row.date, months)).slice(0, VACAY_CARD_MAX_HOLIDAYS),
tripDates: tripDatesIn(ctx.card, months),
proposal,
balances: keepKnown(balances, people),
otherDays: 0,
};
}
/** The verb a toggle's card is labelled with: what it would do to the day. */
const TOGGLE_VERBS = {
add: 'addVacationDay',
remove: 'removeVacationDay',
convert: 'changeVacationDay',
blocked: 'addVacationDay',
} as const satisfies Record<VacayCardProposal['outcome'], AssistantChangeVerbKey>;
/** A held day's words: its date, in the vacation planner; no rows, the card states the facts. */
function dayDescribed(ctx: PreviewContext, args: ToolArgs): Described {
const date = dateArg(args);
return {
subject: date ? formatDate(ctx, date) : text(args.date),
rows: new Rows(),
dayId: null,
placeIds: [],
domain: 'vacay',
};
}
export const VACAY_DESCRIBERS = {
toggle_vacay_entry: (ctx: PreviewContext, args: ToolArgs, loaded: VacayLoaded | null): Described => {
const described = dayDescribed(ctx, args);
const date = dateArg(args);
if (!loaded || !date) return described;
return { ...described, verbKey: TOGGLE_VERBS[toggleProposal(ctx.card.viewerId, args, loaded, date).outcome] };
},
toggle_company_holiday: (ctx: PreviewContext, args: ToolArgs): Described => {
const described = dayDescribed(ctx, args);
described.rows.add('notes', text(args.note));
return described;
},
update_vacay_stats: (_ctx: PreviewContext, args: ToolArgs): Described => {
const year = yearArg(args);
const rows = new Rows().add('quantity', text(args.vacationDays));
return { subject: year === null ? '' : String(year), rows, dayId: null, placeIds: [], domain: 'vacay' };
},
};
export const VACAY_CHANGE_CARDS = {
toggle_vacay_entry: (ctx: PreviewContext, args: ToolArgs, loaded: VacayLoaded | null): VacayCard | null => {
const date = dateArg(args);
return loaded && date ? dayCard(ctx, loaded, toggleProposal(ctx.card.viewerId, args, loaded, date)) : null;
},
toggle_company_holiday: (ctx: PreviewContext, args: ToolArgs, loaded: VacayLoaded | null): VacayCard | null => {
const date = dateArg(args);
return loaded && date ? dayCard(ctx, loaded, companyProposal(args, loaded, date)) : null;
},
/** The signed-in user's leave in that year, with the total the new allowance gives. */
update_vacay_stats: (ctx: PreviewContext, args: ToolArgs, loaded: VacayStatsLoaded | null): VacayCard | null => {
const year = yearArg(args);
const allowance = args.vacationDays;
const row = loaded?.stats.find((stat) => stat.personId === ctx.card.viewerId && stat.year === year);
if (!row || typeof allowance !== 'number' || !Number.isInteger(allowance) || allowance < 0) return null;
const known = knownPeople(null, [], [row]);
return {
kind: 'vacay',
months: [],
weekStart: 1,
weekendDays: [0, 6],
people: peopleOf([row.personId], known, ctx.card.viewerId),
days: [],
company: [],
holidays: [],
tripDates: [],
proposal: null,
balances: [balanceOf(row, Math.min(1000, allowance + row.carried))],
otherDays: 0,
};
},
};
@@ -0,0 +1,150 @@
import type { TripCard } from '../../assistant-context';
import type { VacayEntryRow, VacayPerson, VacayStatRow } from './vacay-reads';
import {
VACAY_CARD_MAX_DATES,
VACAY_CARD_MAX_DAYS,
type VacayCard,
type VacayCardBalance,
type VacayCardDay,
type VacayCardPerson,
} from '@trek/shared';
/**
* The calendar part every vacation card shares: which months it shows, the
* days of the trip and the logged days inside them, and the people those
* days belong to, the signed-in user first.
*/
export type CardMonth = VacayCard['months'][number];
const MAX_PEOPLE = 8;
/** "2026-10" for a date or a month. */
export function monthKey(value: string | CardMonth): string {
return typeof value === 'string' ? value.slice(0, 7) : `${value.year}-${String(value.month).padStart(2, '0')}`;
}
export function monthOf(date: string): CardMonth {
return { year: Number(date.slice(0, 4)), month: Number(date.slice(5, 7)) };
}
export function inMonths(date: string, months: readonly CardMonth[]): boolean {
const key = monthKey(date);
return months.some((month) => monthKey(month) === key);
}
/** The dated days of the trip, from its days or else its first and last date (a year of them at most). */
function tripDatesOf(card: TripCard): string[] {
const dated = card.days.flatMap((day) => (day.date ? [day.date] : []));
if (dated.length > 0) return [...new Set(dated)].sort();
if (!card.startDate || !card.endDate || card.startDate > card.endDate) return [];
const dates: string[] = [];
const day = new Date(`${card.startDate}T00:00:00Z`);
while (dates.length < 366) {
const iso = day.toISOString().slice(0, 10);
if (iso > card.endDate) break;
dates.push(iso);
day.setUTCDate(day.getUTCDate() + 1);
}
return dates;
}
/** The dated days of the trip inside `months`, as many as a card holds. */
export function tripDatesIn(card: TripCard, months: readonly CardMonth[]): string[] {
return tripDatesOf(card).filter((date) => inMonths(date, months)).slice(0, VACAY_CARD_MAX_DATES);
}
/** The company holidays inside `months`, each date once. */
export function companyIn<T extends { date: string }>(rows: readonly T[], months: readonly CardMonth[]): T[] {
const inside = rows.filter((row) => inMonths(row.date, months));
return [...new Map(inside.map((row) => [row.date, row])).values()].slice(0, VACAY_CARD_MAX_DATES);
}
/** The trip's months in order, at most `max`. */
export function tripMonthsOf(card: TripCard, max = 3): CardMonth[] {
const keys = [...new Set(tripDatesOf(card).map(monthKey))].slice(0, max);
return keys.map((key) => monthOf(`${key}-01`));
}
/** A logged day as a card holds it. */
function cardDay(entry: VacayEntryRow): VacayCardDay {
return { date: entry.date, personId: entry.personId, fraction: entry.fraction, kind: entry.kind };
}
/** The logged days inside `months`, the signed-in user's first when there are more than a card holds. */
export function daysIn(
entries: readonly VacayEntryRow[],
months: readonly CardMonth[],
viewerId: number,
): VacayCardDay[] {
const inside = entries.filter((entry) => inMonths(entry.date, months));
const ranked = [...inside].sort(
(a, b) => Number(b.personId === viewerId) - Number(a.personId === viewerId) || a.date.localeCompare(b.date),
);
return ranked
.slice(0, VACAY_CARD_MAX_DAYS)
.map(cardDay)
.sort((a, b) => a.date.localeCompare(b.date) || a.personId - b.personId);
}
/**
* The people a card names, by id: the signed-in user first, then in the
* order they come up. A person no source names is left out, and `keepKnown`
* leaves out their days and balances too.
*/
export function peopleOf(
ids: readonly number[],
known: ReadonlyMap<number, VacayPerson>,
viewerId: number,
): VacayCardPerson[] {
const order = [...new Set(ids)].sort((a, b) => Number(b === viewerId) - Number(a === viewerId));
return order
.flatMap((id) => {
const person = known.get(id);
return person ? [{ id, name: person.name, avatarKey: null, color: person.color }] : [];
})
.slice(0, MAX_PEOPLE);
}
/** Only the rows of the people a card names. */
export function keepKnown<T extends { personId: number }>(rows: readonly T[], people: readonly VacayCardPerson[]): T[] {
const ids = new Set(people.map((person) => person.id));
return rows.filter((row) => ids.has(row.personId));
}
/** The people every source names, the plan's own names first. */
export function knownPeople(
plan: ReadonlyMap<number, VacayPerson> | null,
entries: readonly VacayEntryRow[],
stats: readonly VacayStatRow[],
): Map<number, VacayPerson> {
const known = new Map<number, VacayPerson>();
for (const row of [...entries, ...stats]) {
if (row.person && !known.has(row.personId)) known.set(row.personId, row.person);
}
for (const [id, person] of plan ?? []) known.set(id, person);
return known;
}
/** A person's leave in a year as a card shows it. */
export function balanceOf(row: VacayStatRow, totalAfter: number | null = null): VacayCardBalance {
return {
personId: row.personId,
year: row.year,
total: row.total,
carried: Math.min(row.carried, row.total),
used: row.used,
comp: row.comp,
totalAfter,
windowStart: row.windowStart,
windowEnd: row.windowEnd,
};
}
/** The leave year a date counts in for a person, from their row of the date's calendar year. */
export function periodOf(date: string, row: VacayStatRow | undefined): number {
const year = Number(date.slice(0, 4));
if (!row) return year;
if (date < row.windowStart) return row.year - 1;
return date >= row.windowEnd ? row.year + 1 : row.year;
}
@@ -0,0 +1,116 @@
import type { CardReader, ToolArgs } from '../card-types';
import { argId } from '../card-values';
import {
countryOf,
entriesOf,
holidaysOf,
isoDate,
planOf,
statsOf,
type VacayCompanyRow,
type VacayEntryRow,
type VacayHolidayRow,
type VacayPlanView,
type VacayStatRow,
} from './vacay-reads';
/**
* What a held vacation write is described with, read before its card is
* drawn: the plan (people, colours, weekends, calendars), the days left of
* the leave year the day falls in, that year's logged days and company
* holidays, and the public holidays of the plan's first calendar. Vacation
* days belong to the plan, not to the trip, so nothing of this is on the trip
* card.
*
* A lookup may read four times. The plan and the days left of the day's
* calendar year come first; a leave year that starts later in the year (a
* fiscal or a hire-date year) can put the day in the year before, which takes
* the days left of that year too and leaves no read for the holidays, unless
* the toggle names a person whose own year holds the day. Who the signed-in
* user is, the card decides later from the trip card.
*
* The logged days come from the signed-in user's own calendar grid, which
* runs from the first of the month their leave year starts in. The lookup
* cannot tell which person that is, so it reads the grid year every person
* agrees on; where their years start in different months and split on the
* day, the existing entry could be missed, and the lookup gives nothing (the
* generic card) rather than a card that says "add" where the toggle removes.
*/
export interface VacayLoaded {
plan: VacayPlanView;
/** The days left per person, of the day's calendar year and, where it counts there, the year before. */
stats: VacayStatRow[];
entries: VacayEntryRow[];
company: VacayCompanyRow[];
holidays: VacayHolidayRow[];
}
export interface VacayStatsLoaded {
stats: VacayStatRow[];
}
/** The day a held vacation write names, when it names a real one. */
export function dateArg(args: ToolArgs): string | null {
const date = isoDate(args.date);
return date && !Number.isNaN(Date.parse(`${date}T00:00:00Z`)) ? date : null;
}
/** A year argument the planner takes. */
export function yearArg(args: ToolArgs): number | null {
const year = args.year;
return typeof year === 'number' && Number.isInteger(year) && year >= 2000 && year <= 2100 ? year : null;
}
/** The public holidays of the plan's first calendar in `year`; none while the plan shows none. */
async function holidaysFor(plan: VacayPlanView, year: number, read: CardReader): Promise<VacayHolidayRow[]> {
const calendar = plan.calendars[0];
if (!calendar) return [];
const value = await read('list_holidays', { country: countryOf(calendar.region), year });
return holidaysOf(value, calendar.region, calendar.color);
}
/**
* The year whose calendar grid shows `date`: a grid starts on the first of
* the month a leave year starts in. Null when the people of the plan split on
* it, since the grid is the signed-in user's and the lookup does not know who
* that is.
*/
function gridYearOf(date: string, year: number, rows: readonly VacayStatRow[]): number | null {
const later = rows.filter((row) => date < `${row.windowStart.slice(0, 7)}-01`).length;
if (later === 0) return year;
return later === rows.length ? year - 1 : null;
}
/** Everything a card of one day needs; null without a day or a plan (the addon off, no access). */
export async function loadDay(args: ToolArgs, read: CardReader): Promise<VacayLoaded | null> {
const date = dateArg(args);
if (!date) return null;
const plan = planOf(await read('get_vacay_plan'));
if (!plan) return null;
const year = Number(date.slice(0, 4));
const thisYear = statsOf(await read('get_vacay_stats', { year })) ?? [];
const gridYear = gridYearOf(date, year, thisYear);
if (gridYear === null) return null;
// The year before counts where a person's leave year holds the day there; a named person decides it alone.
const target = thisYear.find((row) => row.personId === argId(args, 'targetUserId'));
const earlier = target ? date < target.windowStart : thisYear.some((row) => date < row.windowStart);
const before = earlier ? (statsOf(await read('get_vacay_stats', { year: year - 1 })) ?? []) : [];
const logged = entriesOf(await read('get_vacay_entries', { year: gridYear }));
const holidays = earlier ? [] : await holidaysFor(plan, year, read);
return {
plan,
stats: [...thisYear, ...before],
entries: logged?.entries ?? [],
company: logged?.company ?? [],
holidays,
};
}
/** The days left of the year a new allowance is for. */
export async function loadStats(args: ToolArgs, read: CardReader): Promise<VacayStatsLoaded | null> {
const year = yearArg(args);
if (year === null) return null;
const stats = statsOf(await read('get_vacay_stats', { year }));
return stats ? { stats } : null;
}
@@ -0,0 +1,206 @@
import { clipped, finite, hexOrNull, recordOf, type Row } from '../card-values';
import { rowsOf } from '../undo-snapshot';
/**
* The vacation planner's tools as its cards read them: the plan
* (`get_vacay_plan`), the logged days of a year (`get_vacay_entries`), the
* days left (`get_vacay_stats`) and a country's public holidays
* (`list_holidays`). Every reader takes the tool's raw answer, trusts no
* shape and leaves out what does not parse; names are masked like a provider
* answer, so an e-mail address used as a user name never reaches a card.
*/
export type Fraction = 0.5 | 1;
const DATE = /^\d{4}-\d{2}-\d{2}$/;
export function isoDate(value: unknown): string | null {
return typeof value === 'string' && DATE.test(value) ? value : null;
}
/** A stored fraction as the planner counts it: below a whole day is half a day. */
function fractionOf(value: unknown): Fraction {
const fraction = finite(value);
return fraction !== null && fraction < 1 ? 0.5 : 1;
}
function idOf(value: unknown): number | null {
return typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : null;
}
export interface VacayPerson {
name: string;
color: string | null;
}
export interface VacayPlanView {
weekStart: 0 | 1;
weekendDays: number[];
blockWeekends: boolean;
companyOn: boolean;
people: ReadonlyMap<number, VacayPerson>;
/** The public-holiday calendars, while the plan shows public holidays. */
calendars: ReadonlyArray<{ region: string; color: string | null }>;
}
export interface VacayEntryRow {
date: string;
personId: number;
fraction: Fraction;
kind: 'vacation' | 'comp';
person: VacayPerson | null;
}
export interface VacayCompanyRow {
date: string;
fraction: Fraction;
}
export interface VacayStatRow {
personId: number;
year: number;
total: number;
used: number;
comp: number;
carried: number;
windowStart: string;
windowEnd: string;
person: VacayPerson | null;
}
export interface VacayHolidayRow {
date: string;
name: string;
color: string | null;
}
function personOf(name: unknown, color: unknown): VacayPerson | null {
const shown = clipped(name, 80);
return shown ? { name: shown, color: hexOrNull(color) } : null;
}
/**
* "0,6" as the weekdays it names. Only a missing or empty value is the
* planner's Saturday and Sunday (`isBlockedWeekend` reads it so); a value
* naming no real weekday is no weekend at all, there as here.
*/
function weekendOf(value: unknown): number[] {
if (typeof value !== 'string' || value === '') return [0, 6];
const days = value
.split(',')
.map(Number)
.filter((day) => Number.isInteger(day) && day >= 0 && day <= 6);
return [...new Set(days)].slice(0, 7);
}
/** The plan as `get_vacay_plan` answers it (`{ plan: { plan, users } }`); null for anything else. */
export function planOf(value: unknown): VacayPlanView | null {
const data = recordOf(recordOf(value).plan);
const plan = recordOf(data.plan);
if (!Array.isArray(data.users) || Object.keys(plan).length === 0) return null;
const people = new Map<number, VacayPerson>();
for (const user of rowsOf(data.users)) {
const id = idOf(user.id);
const person = personOf(user.username, user.color);
if (id !== null && person) people.set(id, person);
}
const holidaysOn = plan.holidays_enabled === true || plan.holidays_enabled === 1;
const calendars = holidaysOn
? rowsOf(plan.holiday_calendars)
.filter((calendar) => (calendar.type ?? 'public_holiday') === 'public_holiday')
.flatMap((calendar) =>
typeof calendar.region === 'string' && calendar.region.trim() !== ''
? [{ region: calendar.region.trim(), color: hexOrNull(calendar.color) }]
: [],
)
: [];
return {
weekStart: plan.week_start === 0 ? 0 : 1,
weekendDays: weekendOf(plan.weekend_days),
blockWeekends: plan.block_weekends === true || plan.block_weekends === 1,
companyOn: plan.company_holidays_enabled === true || plan.company_holidays_enabled === 1,
people,
calendars,
};
}
/** The logged days and company holidays as `get_vacay_entries` answers them (`{ entries: { entries, ... } }`). */
export function entriesOf(value: unknown): { entries: VacayEntryRow[]; company: VacayCompanyRow[] } | null {
const data = recordOf(recordOf(value).entries);
if (!Array.isArray(data.entries)) return null;
const entries = rowsOf(data.entries).flatMap((row): VacayEntryRow[] => {
const date = isoDate(row.date);
const personId = idOf(row.user_id);
if (!date || personId === null) return [];
return [
{
date,
personId,
fraction: fractionOf(row.fraction),
kind: row.kind === 'comp' ? 'comp' : 'vacation',
person: personOf(row.person_name, row.person_color),
},
];
});
const company = rowsOf(data.companyHolidays).flatMap((row): VacayCompanyRow[] => {
const date = isoDate(row.date);
return date ? [{ date, fraction: fractionOf(row.fraction) }] : [];
});
return { entries, company };
}
function days(value: unknown): number {
const count = finite(value);
return count === null ? 0 : Math.min(1000, Math.max(0, count));
}
/** The days left per person as `get_vacay_stats` answers them (`{ stats: [...] }`). */
export function statsOf(value: unknown): VacayStatRow[] | null {
const rows = recordOf(value).stats;
if (!Array.isArray(rows)) return null;
return rowsOf(rows).flatMap((row: Row): VacayStatRow[] => {
const personId = idOf(row.user_id);
const year = finite(row.year);
const windowStart = isoDate(row.window_start);
const windowEnd = isoDate(row.window_end);
if (personId === null || year === null || !windowStart || !windowEnd) return [];
return [
{
personId,
year,
total: days(row.total_available),
used: days(row.used),
comp: days(row.comp_used),
carried: days(row.carried_over),
windowStart,
windowEnd,
person: personOf(row.person_name, row.person_color),
},
];
});
}
/**
* A country's public holidays as `list_holidays` answers them (nager.at
* rows), narrowed to `region` the way the planner clears them: a holiday of
* the whole country, or one of the region's own. A country that splits its
* holidays by region gives nothing for a calendar without one.
*/
export function holidaysOf(value: unknown, region: string | null, color: string | null): VacayHolidayRow[] {
const rows = rowsOf(recordOf(value).holidays);
const regional = rows.some((row) => Array.isArray(row.counties) && row.counties.length > 0);
const subdivision = region && region.includes('-') ? region : null;
if (regional && region !== null && !subdivision) return [];
return rows.flatMap((row): VacayHolidayRow[] => {
const date = isoDate(row.date);
const name = clipped(row.localName, 80) ?? clipped(row.name, 80);
const counties = Array.isArray(row.counties) ? row.counties : null;
const applies = row.global === true || !counties || (subdivision !== null && counties.includes(subdivision));
return date && name && applies ? [{ date, name, color }] : [];
});
}
/** The country a calendar region names: "DE-BY" is Germany. */
export function countryOf(region: string): string {
return (region.split('-')[0] ?? region).toUpperCase();
}