// FRAZIER Finance OS — Calendar page (#calendar), master sheet (8 Oct 2026).
// One calendar month (period) per view, read-only. Data: period.calendar from
// fin_sheet_dashboard (CONTRACT §2.2) through useFinSheet() / useFinPeriod();
// no other endpoint. Every row links back to its cell in Google Sheets.
// ONE finance sheet covers every date: it is shown once, above the month.
//
// Views:
// desktop / tablet (> 768px) Mon–Sun month grid.
// phone (≤ 768px) agenda list (one row per day with activity).
// ‹ › step through the months of the sheet (earliest month with a dated row
// to the latest, always including this month). A month with no dated rows,
// or a month outside that range asked for in the hash (?p=YYYY-MM), shows an
// intentional "No rows dated in …" state, never a grid of zeros.
// Live updates swap the payload in place: the open day stays open (it is
// kept by its date), and it closes only when that month is gone.
// Marker kinds, in display order. tone = the category key dot (legend).
const FIN_CAL_KINDS = [
{ id: 'issued', list: 'invoicesIssued', label: 'Invoices issued', key: 'Issued', short: 'Billed', one: 'invoice', many: 'invoices', tone: 'violet', amount: (t) => t.billed },
{ id: 'paid', list: 'invoicesPaid', label: 'Payments received', key: 'Paid', short: 'Paid', one: 'payment', many: 'payments', tone: 'ok', amount: (t) => t.collected },
{ id: 'in', list: 'bankIn', label: 'Bank in', key: 'Bank in', short: 'In', one: 'entry', many: 'entries', tone: 'info', amount: (t) => t.in },
{ id: 'out', list: 'bankOut', label: 'Bank out', key: 'Bank out', short: 'Out', one: 'entry', many: 'entries', tone: 'neutral', amount: (t) => t.out },
{ id: 'bill', list: 'vendorBills', label: 'Vendor bills', key: 'Bills', short: 'Bill', one: 'bill', many: 'bills', tone: 'warn', amount: (t) => t.vendorBilled },
{ id: 'jv', list: 'journal', label: 'Journal lines', key: 'Journal', short: 'JV', one: 'line', many: 'lines', tone: 'ring', amount: null },
];
const FIN_CAL_WD = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
const FIN_CAL_WD_LONG = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
// ── Date maths on 'YYYY-MM-DD' strings (UTC, so no timezone shift) ──────
function finCalMs(iso) {
const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(iso || ''));
return m ? Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]), 12) : NaN;
}
function finCalIso(ms) {
const d = new Date(ms);
return d.getUTCFullYear() + '-' + String(d.getUTCMonth() + 1).padStart(2, '0') + '-' + String(d.getUTCDate()).padStart(2, '0');
}
function finCalAddDays(iso, n) { return finCalIso(finCalMs(iso) + n * 86400000); }
// 1 = Monday … 7 = Sunday
function finCalDow(iso) { const d = new Date(finCalMs(iso)).getUTCDay(); return d === 0 ? 7 : d; }
function finCalDayNum(iso) { return Number(String(iso).slice(8, 10)); }
function finCalLongDate(iso) { return FIN_CAL_WD_LONG[finCalDow(iso) - 1] + ', ' + finCalDayNum(iso) + ' ' + FIN_MON_LONG[Number(String(iso).slice(5, 7)) - 1] + ' ' + String(iso).slice(0, 4); }
function finCalPlural(n, one, many) { return n + ' ' + (n === 1 ? one : many); }
// Weeks (arrays of 7 ISO dates, Mon–Sun) covering one calendar month.
function finCalWeeks(ym) {
const first = ym + '-01';
const last = finMonthEnd(ym);
let d = finCalAddDays(first, 1 - finCalDow(first));
const end = finCalAddDays(last, 7 - finCalDow(last));
const weeks = [];
let w = [];
for (let guard = 0; d <= end && guard < 50; guard++) {
w.push(d);
if (w.length === 7) { weeks.push(w); w = []; }
d = finCalAddDays(d, 1);
}
return weeks;
}
function finCalUnitLabel(p) {
return p ? (p.label || finMonthLabel(p.key)) : '';
}
// Markers of one day: [{ kind, count, amount }] for the kinds present.
function finCalMarkers(day) {
if (!day || !day.hasActivity) return [];
const c = day.counts || {}; const t = day.totals || {};
return FIN_CAL_KINDS.map((k) => {
const n = Number(c[k.list]) || 0;
if (!n) return null;
return { kind: k, count: n, amount: k.amount ? Number(k.amount(t)) || 0 : null };
}).filter(Boolean);
}
function finCalMarkerText(m, full) {
const k = m.kind;
if (!k.amount) return k.label + ': ' + finCalPlural(m.count, k.one, k.many);
return k.label + ': ' + finCalPlural(m.count, k.one, k.many) + ', ' + (full ? finIDR(m.amount) : finIDRCompact(m.amount));
}
function finCalDayAria(iso, day, bankUnknown) {
const parts = finCalMarkers(day).map((m) => finCalMarkerText(m, true));
return finCalLongDate(iso) + (parts.length ? ': ' + parts.join('; ') : ': nothing recorded')
+ (bankUnknown ? '; bank in and out not known, the Bank Book has no entries for this day yet' : '');
}
// A section whose tab is missing from the sheet: never a zero.
function finCalSectionGone(period, key) {
const s = period ? period[key] : null;
if (!s) return 'Not in the sheet';
if (s.available === false) return s.reason || 'Not in the sheet';
return null;
}
// Bank Book coverage of the period, read the same way as Home's Money in /
// out / net: when its last entry is before the period starts, the month's
// bank movement is UNKNOWN (never zero). partial = it covers only the first
// part of the period (through knownThrough).
// { ok, gone (no Bank Book tab), reason, knownThrough, partial }
function finCalBankState(period, cal) {
const bank = period && period.bank;
if (!bank || bank.available === false || (cal && !cal.bankAvailable)) {
return { ok: false, gone: true, reason: finCalSectionGone(period, 'bank') || 'No Bank Book tab in the sheet', knownThrough: null };
}
const kt = bank.knownThrough || (cal && cal.bankKnownThrough) || null;
if (!kt || kt < period.start) {
return { ok: false, gone: false, reason: kt ? 'No Bank Book entries since ' + finDate(kt) : 'No Bank Book entries yet', knownThrough: kt };
}
const asOf = (period.kpis && period.kpis.asOfDate) || period.end;
return { ok: true, gone: false, reason: null, knownThrough: kt, partial: kt < asOf };
}
// A past or current day after the Bank Book's last entry: its bank in / out
// are not known (the sheet has not been filled in that far), not zero.
// Future days are already dimmed and say nothing about money.
function finCalBankUnknownOn(iso, bs, cal) {
if (!bs || bs.gone) return false;
if (cal && cal.today && iso > cal.today) return false;
return !bs.knownThrough || iso > bs.knownThrough;
}
// ── Small parts ─────────────────────────────────────────────────────────
function FinCalDot({ tone }) {
return ;
}
// Wide cells: [count badge] Label ····· Rp 3,0 jt. Narrow cells (container
// query in fin-calendar.css): the badge and label give way to a key dot, the
// amount stays whole. Journal: "JV 4" (count only, no amount).
function FinCalMarker({ m }) {
const k = m.kind;
if (!k.amount) {
return (
{'JV ' + m.count}
);
}
return (
{m.count}{k.short}{finIDRCompact(m.amount)}
);
}
// Long labels where the row has room, short ones (Issued, Paid, Bills…)
// when it would otherwise wrap (container query in fin-calendar.css).
function FinCalLegend() {
return (
{FIN_CAL_KINDS.map((k) => (
{k.label}{k.key}
))}
);
}
// One line under the key when part of the visible month is past the Bank
// Book's last entry: those days are shaded, and their bank in / out are
// unknown, not zero. The shaded swatch doubles as the key for the grid.
function FinCalBankNote({ bs, period }) {
if (!bs || bs.gone) return null;
let text;
if (!bs.ok) text = bs.reason + ': bank in and out on the shaded days are unknown, not zero.';
else if (bs.partial) text = 'The Bank Book runs through ' + finDate(bs.knownThrough) + ': bank in and out on the shaded days are unknown, not zero.';
else return null;
return (
);
}
// The finance sheet, once: every month reads it. "Old copy" + "as of" when
// the numbers on screen are older than they should be.
function FinCalSheet({ meta, staleCopy }) {
const s = meta.sheet || {};
const title = s.title || 'Your finance sheet';
const range = finDataRangeText(meta.dataRange);
const synced = meta.syncedAt ? finSyncTime(meta.syncedAt, meta.today) : '';
const err = meta.servedStale ? meta.error : null;
const at = err && err.at ? finSyncTime(err.at, meta.today) : '';
return (
{title}
{staleCopy ? Old copy : null}
One sheet for every month
{range ? {'Rows dated ' + range} : null}
{staleCopy ? (
{(meta.servedStale ? 'Couldn’t reach Google Sheets' + (at ? ' at ' + at : '') : 'Couldn’t reach the server') + (synced ? ' · numbers as of ' + synced : '')}
) : null}
{s.url ? (
) : null}
);
}
function FinCalMetrics({ period, cal, bs }) {
const t = cal.totals || {};
const days = cal.days || {};
const n = { invoicesIssued: 0, invoicesPaid: 0, bankIn: 0, bankOut: 0, vendorBills: 0, journal: 0 };
Object.keys(days).forEach((d) => { const c = days[d].counts || {}; Object.keys(n).forEach((k) => { n[k] += Number(c[k]) || 0; }); });
const bankGone = bs.gone ? bs.reason : null;
// Bank in / out / net: unknown (never Rp 0) when the Bank Book's last
// entry is before the month starts, exactly like Home.
const flowGone = bs.ok ? null : bs.reason;
const through = bs.ok && bs.partial ? ' · through ' + finDate(bs.knownThrough, { year: false }) : '';
// A left-out tab of this year makes the month's totals unknown, never Rp 0.
const salesGone = finCalSectionGone(period, 'sales') || (finPartial(period.sales) ? finPartialHint(period.sales) : null);
const vendorGone = finCalSectionGone(period, 'vendor') || (finPartial(period.vendor) ? finPartialHint(period.vendor) : null);
const jvGone = finCalSectionGone(period, 'journal');
const cash = period.kpis && period.kpis.cash;
const gone = (why) => ({ value: '—', hint: why });
const balanced = Math.abs((Number(t.journalDebit) || 0) - (Number(t.journalCredit) || 0)) < 0.5;
let bal;
if (bankGone || !cash) bal = gone(bankGone || 'No Bank Book tab in the sheet');
else if (!cash.hasData) bal = gone('No Bank Book entries yet');
else bal = { money: cash.amount, hint: 'as of ' + finDate(cash.asOf) + (cash.stale ? ' (last entry)' : ''), tone: cash.stale ? 'warn' : undefined };
const tiles = [
Object.assign({ id: 'in', icon: 'arrowin', label: 'Bank in' }, flowGone ? gone(flowGone) : { money: t.in, hint: finCalPlural(n.bankIn, 'entry', 'entries') + through }),
Object.assign({ id: 'out', icon: 'arrowout', label: 'Bank out' }, flowGone ? gone(flowGone) : { money: t.out, hint: finCalPlural(n.bankOut, 'entry', 'entries') + through }),
Object.assign({ id: 'net', icon: 'bank', label: 'Net' }, flowGone ? gone(flowGone) : { money: t.net, hint: 'In minus out' + through }),
Object.assign({ id: 'bal', icon: 'wallet', label: 'Bank balance' }, bal),
Object.assign({ id: 'billed', icon: 'invoice', label: 'Billed' }, salesGone ? gone(salesGone) : { money: t.billed, hint: finCalPlural(n.invoicesIssued, 'invoice', 'invoices') + ' · DPP' + (n.invoicesIssued ? ' · nett ' + finIDRCompact(t.billedNett) : '') }),
Object.assign({ id: 'coll', icon: 'circlecheck', label: 'Collected' }, salesGone ? gone(salesGone) : { money: t.collected, hint: finCalPlural(n.invoicesPaid, 'payment', 'payments') + ' received' }),
Object.assign({ id: 'bills', icon: 'receipt', label: 'Vendor bills' }, vendorGone ? gone(vendorGone) : { money: t.vendorBilled, hint: finCalPlural(n.vendorBills, 'bill', 'bills') }),
Object.assign({ id: 'jv', icon: 'book', label: 'Journal lines', tone: !jvGone && !balanced ? 'warn' : undefined },
jvGone ? gone(jvGone) : { value: String(n.journal), hint: n.journal ? (balanced ? 'Debit = credit · ' + finIDRCompact(t.journalDebit) : 'Debit ' + finIDRCompact(t.journalDebit) + ' ≠ credit ' + finIDRCompact(t.journalCredit)) : 'None dated in this month' }),
];
// Phones: one compact well, label and value on one line per row.
// When bank in / out / net are unknown for the same reason, one row says
// it once instead of three rows repeating it (and wrapping unevenly).
const kvTiles = flowGone
? [{ id: 'flow', label: 'Bank in / out', value: '—', hint: flowGone }].concat(tiles.slice(3))
: tiles;
const kvRows = kvTiles.map((x) => ({
id: x.id, label: x.label, note: x.hint, sep: x.id === 'billed',
value: x.money !== undefined ? finIDRCompact(x.money) : x.value,
title: x.money !== undefined ? finIDR(x.money) : undefined,
tone: x.value === '—' ? 'muted' : x.tone === 'warn' ? 'warn' : undefined,
}));
return (
<>
{tiles.map((x) => )}
>
);
}
// ── Page ────────────────────────────────────────────────────────────────
const FIN_CAL_YM = /^\d{4}-(0[1-9]|1[0-2])$/;
function FinCalendar({ args }) {
const sheet = useFinSheet();
const per = useFinPeriod();
const data = sheet.data;
const meta = sheet.meta || {};
const periods = per.periods || [];
const todayIso = meta.today || finTodayIso();
// A month asked for in the hash that the sheet has no rows for at all
// (?p=YYYY-MM outside its months): shown as such, never swapped silently.
const rawP = finHashParse().params.p || null;
const gapMonth = rawP && FIN_CAL_YM.test(rawP) && periods.length && !periods.some((p) => p.key === rawP) ? rawP : null;
const period = gapMonth ? null : per.period;
const cal = period ? period.calendar : null;
// ‹ › step through the sheet's months; from a month outside them, to the
// nearest month on either side.
let prevP = null; let nextP = null;
const idx = period ? periods.findIndex((p) => p.key === period.key) : -1;
if (idx !== -1) { prevP = periods[idx - 1] || null; nextP = periods[idx + 1] || null; }
else if (gapMonth) {
for (let i = periods.length - 1; i >= 0; i--) if (periods[i].key < gapMonth) { prevP = periods[i]; break; }
for (let i = 0; i < periods.length; i++) if (periods[i].key > gapMonth) { nextP = periods[i]; break; }
}
const todayP = periods.find((p) => todayIso >= p.start && todayIso <= p.end) || null;
const todayOn = !!(todayP && period && todayP.key === period.key);
// Day detail, kept by its date: a live update re-reads the same day.
// Any day of the month can be open (Home's "At a glance" opens quiet days
// too); the grid and agenda open days with activity.
const [openDay, setOpenDay] = React.useState(null);
const openOk = !!(openDay && cal && cal.days && cal.days[openDay]);
// Another month (‹ ›, the top selector, back / forward): its days differ.
React.useEffect(() => {
setOpenDay((d) => (d && period && d.slice(0, 7) === period.key ? d : null));
}, [period && period.key]); // eslint-disable-line
const go = (p) => { if (!p) return; setOpenDay(null); finSetPeriodKey(p.key); };
// args.date (Home's "At a glance" click): select the month holding that
// day, then open its detail. Taken once per navigation (args.nonce), so
// changing month later never reopens it.
const [wantDay, setWantDay] = React.useState(null);
React.useEffect(() => {
const d = args && typeof args.date === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(args.date) ? args.date : null;
if (d) setWantDay(d);
}, [args && args.nonce]); // eslint-disable-line
React.useEffect(() => {
if (!wantDay || !data) return;
const target = periods.find((p) => wantDay >= p.start && wantDay <= p.end) || null;
if (!target) { setWantDay(null); return; }
if (gapMonth || !period || period.key !== target.key) {
// Another month: switch to it (same history step), finish next render.
finSetPeriodKey(target.key, { replace: true });
return;
}
setOpenDay(wantDay);
setWantDay(null);
}, [wantDay, data, period && period.key, gapMonth]); // eslint-disable-line
if (!data) {
// The shell's gate covers the first load; never show zeros meanwhile.
return (
{[0, 1, 2, 3].map((i) => )}
);
}
const nav = ;
const sheetCard = ;
const sheetTitle = (meta.sheet && meta.sheet.title) || 'the finance sheet';
// ── A month with nothing dated in it ──
if (gapMonth || !period || period.hasData === false) {
const m = gapMonth || (period ? period.key : todayIso.slice(0, 7));
const shown = period || { key: m, label: finMonthLabel(m) };
return (
{sheetCard}
);
}
const head = ;
if (!cal || !cal.days) {
return (