Why Agency Retainer Spreadsheets Break: Integer-Cent Rollover Ledgers, Effective-Dated Rate Cards & CSV Formula Injection
Every agency starts tracking client retainers in a spreadsheet or a couple of Numbers columns on a monday.com board. It holds up fine when you have three clients, one flat hourly rate, and nobody asks what happened four months ago.
Then reality shows up. A senior engineer gets a raise on May 15. A client negotiates a 25% unused-hours rollover cap that expires every cycle. Someone logs 10 minutes on a $175/hr retainer. And at month-end, your operations manager exports the board to CSV and opens it in Excel.
Suddenly Q1 profit margins shift retroactively, an 80% burn warning fails to trigger because of IEEE 754 drift, and an unescaped task name turns into a live spreadsheet formula. Here are the five concrete failure modes we had to engineer around when building a retainer P&L engine in TypeScript (financialEngine.ts and csvExport.ts).
1. Integer-Cent Arithmetic and Cross-Multiplication Thresholds
Storing hours as floats (0.16666667) and dollars as floats (175.00) guarantees rounding mismatches between line items and invoice totals. We represent every duration as integer minutes and every monetary value as integer cents (rateCentsPerHr, amountCents, monthlyFeeCents), with expense markups stored in integer basis points (1000 bps = 10%).
Half-up rounding stays completely inside integer math:
export function calcAmountCents(durationMinutes: number, rateCentsPerHr: number): number { if (!Number.isFinite(durationMinutes) || !Number.isFinite(rateCentsPerHr)) { return 0; } if (durationMinutes <= 0 || rateCentsPerHr <= 0) { return 0; } return Math.floor((durationMinutes * rateCentsPerHr + 30) / 60); } export function calcExpenseBillableCents( amountCents: number, billable: boolean, markupBps: number ): number { if (!billable || !Number.isFinite(amountCents) || amountCents <= 0) { return 0; } const safeMarkup = Number.isFinite(markupBps) && markupBps >= 0 ? markupBps : 0; return Math.floor((amountCents * (10000 + safeMarkup) + 5000) / 10000); } The subtler floating-point bug shows up in burn alerts. If you write (burned / allowance) * 100 >= warningThresholdPct, floating-point division can yield 79.99999999999999 >= 80, silently missing the threshold on the exact minute a retainer hits 80%.
In computeBurnMetrics, we never compare floating percentages at all. We cross-multiply integers and compute the display percentage separately:
export function computeBurnMetrics(params: { num: number; den: number; configured: boolean; warningThresholdPct: number; billingModel: BillingModel; }): { burnPct: number | null; burnStatus: BurnStatus } { const { num, den, configured, warningThresholdPct, billingModel } = params; if (!configured) return { burnPct: null, burnStatus: "unconfigured" }; if (den <= 0) { if (billingModel === "time_and_materials") { return { burnPct: null, burnStatus: "healthy" }; } return { burnPct: null, burnStatus: num > 0 ? "over_budget" : "healthy" }; } const burnPct = Math.floor((num * 1000) / den) / 10; let burnStatus: BurnStatus; if (num >= den) { burnStatus = "over_budget"; } else if (num * 100 >= den * warningThresholdPct) { burnStatus = "warning"; } else { burnStatus = "healthy"; } return { burnPct, burnStatus }; } Notice the den <= 0 branch too: an uncapped time_and_materials board stays "healthy", whereas a retainer or fixed-fee board with zero allowance and logged work trips "over_budget" immediately instead of dividing by zero into Infinity or NaN.
2. Four-Tier Effective-Dated Rate Cards
The fastest way to corrupt agency reporting is a single mutable rate cell per employee. Bump a designer's cost rate from $65/hr to $75/hr in June and your spreadsheet quietly rewrites January through May, shrinking historical gross profit you already closed in accounting.
Instead, every rate card carries a strict ISO effectiveFrom date ("YYYY-MM-DD", validated with a UTC calendar round-trip in isValidIsoDate so "2026-02-30" is rejected outright). When pricing a time entry, resolveRateCard filters to c.effectiveFrom <= lookup.workDate first, then resolves across four tiers in strict precedence order: user -> role (case-insensitive) -> board_default -> config_default. Within each tier, pickLatest selects the card with the newest effectiveFrom.
Mid-month promotions, contractor swaps, and annual client rate increases all work cleanly without touching a single historical line item.
3. Sequential 36-Month Rollover Chains
Retainer rollover cannot be calculated by looking at one month in isolation. Month N's effective allowance is openingRolloverMinutes + includedMinutes, where openingRolloverMinutes depends on Month N-1's unused minutes after applying the contract's cap policy.
We replay the chain sequentially in computeBoardPnl from cycleStartMonth up to the requested month, bounded by MAX_ROLLOVER_LOOKBACK_MONTHS = 36 so a typo in cycleStartMonth (say 1999-01) cannot force a 300-iteration loop per request:
function computeRolloverOutMinutes( unusedMinutes: number, includedMinutes: number, policy: BoardConfigDoc["rolloverPolicy"], capValue: number ): number { if (unusedMinutes <= 0 || policy === "none") return 0; if (policy === "unlimited") return unusedMinutes; if (policy === "capped_percent") { const cap = Math.floor((includedMinutes * capValue) / 100); return Math.min(unusedMinutes, Math.max(0, cap)); } if (policy === "capped_hours") { const cap = capValue * 60; return Math.min(unusedMinutes, Math.max(0, cap)); } return 0; } One contract detail that trips up naive implementations: under capped_percent, the cap is computed against includedMinutes, not effectiveAllowanceMinutes. If you cap against the combined allowance, unused hours compound month over month and your "25% rollover cap" quietly drifts above 33% of the monthly retainer. Each iteration computes mUnused = Math.max(0, mAllowance - mBurned), mOverage = Math.max(0, mBurned - mAllowance), and mExpired = Math.max(0, mUnused - mRolloverOut), then slices the trailing 6 months (MAX_ROLLOVER_LEDGER_ROWS = 6) for the ledger table while preserving the exact multi-month carry-in.
4. Merging Time Sources on Standard-Plan Workspaces
On monday.com, the native Time Tracking column is gated to Pro and Enterprise plans. Smaller agencies on Standard plans log hours in a plain Numbers column or inside an app's built-in time log table, and teams mid-migration often run both at once.
mergeTimeEntries normalizes built_in_logs, native_time_tracking, and numbers_column into a single NormalizedTimeEntry[] array. Built-in logs register their idempotencyKey in seenExternalIds, and external entries carrying a matching externalId are skipped. That lets "combined" mode pull from all three sources without double-counting mirrored entries, while silently dropping invalid dates or non-positive durations.
5. Neutralizing CSV Formula Injection for Excel and QuickBooks
Once your P&L numbers are clean, finance exports them to CSV and opens them in Excel or imports them into QuickBooks. Every item name, time-log note, and expense memo is user-controlled text. If a client-submitted board item starts with =, +, -, @, \t, or \r, Excel happily treats it as a formula or DDE payload (=cmd|' /C calc'!A0).
In csvExport.ts, every cell runs through neutralizeCsvCell before RFC 4180 quoting and \r\n joining:
const FORMULA_PREFIX_RE = /^[=+\-@\t\r]/; export function neutralizeCsvCell(val: unknown): string { if (val === null || val === undefined) { return ""; } let str = String(val); if (FORMULA_PREFIX_RE.test(str)) { str = `'${str}`; } const needsQuotes = /[",\r\n]/.test(str) || str.startsWith(" ") || str.endsWith(" "); if (needsQuotes) { return `"${str.replace(/"/g, '""')}"`; } return str; } We also strip unsafe filename characters via sanitizeCsvFilename before setting Content-Disposition. One honest tradeoff to note in the implementation above: because formatCsvRow passes every cell through neutralizeCsvCell, a negative gross profit formatted as "-450.00" by centsToDecimal also matches the leading - and gets prefixed as '-450.00. That guarantees zero injection surface across every column, though if your accountants rely on Excel SUM() over negative profit columns without re-typing, you should whitelist strict /^-?\d+(\.\d+)?$/ numeric strings from the prefix rule while keeping all free-text fields locked down.
This financial engine runs behind RetainerFlow, our retainer burn, rollover, and margin tracking app for monday.com agencies. If you want to sanity-check rollover caps, overage rates, and effective hourly margins on your own retainer numbers before touching a board, try the free Retainer Burn & Rollover Calculator.
