Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(sheets): add accounting number format (#8082)
Will Hutchinsonb019450909ef
diff --git a/apps/web/src/features/block-spreadsheet/README.md b/apps/web/src/features/block-spreadsheet/README.mdindex 2bb2e2db89..51139e5791 100644--- a/apps/web/src/features/block-spreadsheet/README.md+++ b/apps/web/src/features/block-spreadsheet/README.md@@ -264,7 +264,7 @@ trailing update for the final selection.IronCalc handles formula parsing, ranges, relative and absolute references,dependency evaluation, functions, circular references, Excel errors, and arrayspills. The model uses fixed English settings and UTC on every client. Number-formatting uses fixed `en-US` display rules; currency formatting means USD. The+formatting uses fixed `en-US` display rules; currency and accounting mean USD. Thebinding exposes numbers through formatted strings, so the adapter requests ascientific format with sufficient significant digits before applying UI formats.Calculations use the engine's numeric values, not rounded UI values.@@ -302,8 +302,12 @@ compare formula, error, and formatting behavior before replacing it.- The ribbon exposes font family/size, bold/italic/underline/strikethrough,text/fill colors, per-edge borders, horizontal/vertical alignment, and wrapping.All cell styles persist, sync independently, copy/fill, and undo. Number formats- include general, number, USD currency, percent, scientific, date, time, and plain- text, with adjustable decimal places. Date/time displays are deterministic UTC.+ include general, number, USD currency, USD accounting, percent, scientific, date,+ time, and plain text, with adjustable decimal places. Accounting follows Excel:+ the grid pins `$` to the cell's left edge and the amount to its right, negatives+ show in parentheses and zero as a dash. It exports as Excel's built-in accounting+ format, and imported dollar formats with a repeated fill (`*`) open as accounting.+ Date/time displays are deterministic UTC.Cells without an explicit format honor the date/time formats IronCalc infers fortyped dates, `DATE()`-style results and arithmetic on date cells (formula resultsonly from the year 2000 on, so day counts stay numbers). A cell holding onediff --git a/apps/web/src/features/block-spreadsheet/browser-test/formatting.browser.e2e.ts b/apps/web/src/features/block-spreadsheet/browser-test/formatting.browser.e2e.tsindex aa57889d6c..ee30443548 100644--- a/apps/web/src/features/block-spreadsheet/browser-test/formatting.browser.e2e.ts+++ b/apps/web/src/features/block-spreadsheet/browser-test/formatting.browser.e2e.ts@@ -98,6 +98,84 @@ test('treats direct typing and formula-bar edits as percentage points while presawait expect(page.locator('[data-address="E2"]')).toHaveText('75');});+test('lays accounting figures across the cell with parentheses, dashes and digits aligned', async ({+ page,+}) => {+ for (const [address, value] of [+ ['C2', '=-B2'],+ ['C3', '=B3-B3'],+ ['C4', '1234.5'],+ ]) {+ await page.locator(`[data-address="${address}"]`).dblclick();+ const editor = page.getByRole('textbox', {+ name: `Edit ${address}`,+ exact: true,+ });+ await editor.fill(value);+ await editor.press('Enter');+ }+ await page.locator('[data-address="C2"]').click();+ await page.locator('[data-address="C4"]').click({ modifiers: ['Shift'] });+ await choose(page, 'Number format', 'Accounting $ (1,234.00)');+ await expect(page.getByRole('grid', { name: 'Spreadsheet' })).toBeFocused();+ for (const [address, label] of [+ ['C2', 'C2: $(10.00)'],+ ['C3', 'C3: $-'],+ ['C4', 'C4: $1,234.50'],+ ])+ await expect(page.locator(`[data-address="${address}"]`)).toHaveAttribute(+ 'aria-label',+ label+ );+ const saved = await page.evaluate(+ () => window.spreadsheetFixture.snapshot()[0].cells+ );+ expect(saved.C2).toEqual({ value: '=-B2', format: 'accounting' });++ const layout = await page.evaluate(() =>+ Object.fromEntries(+ ['C2', 'C3', 'C4'].map((address) => {+ const cell = document.querySelector(`[data-address="${address}"]`)!;+ const [symbol, amount] = cell.querySelectorAll(+ '[data-accounting] > span'+ );+ const text = amount.firstChild!;+ const right = (index: number) => {+ const range = document.createRange();+ range.setStart(text, index);+ range.setEnd(text, index + 1);+ return range.getBoundingClientRect().right;+ };+ const value = text.textContent!;+ const digit = value.search(/\d(?=\D*$)/);+ const point = value.search(/[.-]/);+ return [+ address,+ {+ cell: cell.getBoundingClientRect().toJSON(),+ symbolLeft: symbol.getBoundingClientRect().left,+ amountRight: amount.getBoundingClientRect().right,+ lastDigit: digit < 0 ? undefined : right(digit),+ pointOrDash: right(point),+ },+ ];+ })+ )+ );+ for (const { cell, symbolLeft, amountRight } of Object.values(layout)) {+ expect(symbolLeft - cell.left).toBeLessThan(8);+ expect(cell.right - amountRight).toBeLessThan(8);+ }+ // Positives leave room for a closing parenthesis, and zero's dash sits+ // where the decimal point does, as in Excel.+ expect(+ Math.abs(layout.C2.lastDigit! - layout.C4.lastDigit!)+ ).toBeLessThanOrEqual(1);+ expect(+ Math.abs(layout.C3.pointOrDash - layout.C4.pointOrDash)+ ).toBeLessThanOrEqual(1);+});+test('edits formula-bar text and formulas directly with the production mention editor enabled', async ({page,}) => {diff --git a/apps/web/src/features/block-spreadsheet/components/SpreadsheetGrid.test.tsx b/apps/web/src/features/block-spreadsheet/components/SpreadsheetGrid.test.tsxindex 50bd1082f6..8a703d7f6c 100644--- a/apps/web/src/features/block-spreadsheet/components/SpreadsheetGrid.test.tsx+++ b/apps/web/src/features/block-spreadsheet/components/SpreadsheetGrid.test.tsx@@ -988,6 +988,58 @@ describe('spreadsheet presentation', () => {expect(cell.style.textAlign).toBe('left');expect(view.cells().A1.value).toBe('=SUM(B1:B3)');});++ it('pins the accounting symbol to the left edge and pads amounts to line up with negatives', () => {+ const [showFormulas, setShowFormulas] = createSignal(false);+ const view = renderGrid(+ {+ A1: { value: '1234.5', format: 'accounting' },+ A2: { value: '=-A1', format: 'accounting' },+ A3: { value: '=A1-A1', format: 'accounting' },+ A4: { value: 'Total', format: 'accounting' },+ },+ {+ get showFormulas() {+ return showFormulas();+ },+ values: {+ A2: { display: '$(1,234.50)', number: -1234.5 },+ A3: { display: '$-', number: 0 },+ A4: { display: 'Total' },+ },+ }+ );+ const cell = (address: string) =>+ view.container.querySelector<HTMLElement>(`[data-address="${address}"]`)!;+ const layout = (address: string) => {+ const parts = cell(address).querySelector('[data-accounting]');+ return (+ parts && {+ symbol: parts.children[0].textContent,+ amount: parts.children[1].firstChild?.textContent,+ padding: parts.querySelector('.invisible')?.textContent,+ }+ );+ };+ // A literal shows as calculation will before its first result arrives.+ expect(layout('A1')).toEqual({+ symbol: '$',+ amount: '1,234.50',+ padding: ')',+ });+ expect(layout('A2')).toEqual({+ symbol: '$',+ amount: '(1,234.50)',+ padding: '',+ });+ expect(layout('A3')).toEqual({ symbol: '$', amount: '-', padding: '00)' });+ expect(cell('A2').getAttribute('aria-label')).toBe('A2: $(1,234.50)');+ expect(layout('A4')).toBeNull();+ expect(cell('A4').textContent).toBe('Total');+ setShowFormulas(true);+ expect(layout('A2')).toBeNull();+ expect(cell('A2').textContent).toBe('=-A1');+ });});it('renders imported URL and email cells without raw native tooltips, but leaves formulas intact', () => {diff --git a/apps/web/src/features/block-spreadsheet/components/SpreadsheetGrid.tsx b/apps/web/src/features/block-spreadsheet/components/SpreadsheetGrid.tsxindex 0acf3ca184..b0a8192efe 100644--- a/apps/web/src/features/block-spreadsheet/components/SpreadsheetGrid.tsx+++ b/apps/web/src/features/block-spreadsheet/components/SpreadsheetGrid.tsx@@ -2,6 +2,7 @@ import { isTouchDevice } from '@core/mobile/isTouchDevice';import { cellPlainText } from '@macro-inc/spreadsheet/cell-mentions';import type { ConditionalAppearance } from '@macro-inc/spreadsheet/conditional-formatting';import {+ accountingParts,literalNumber,literalNumberDisplay,} from '@macro-inc/spreadsheet/number-display';@@ -336,6 +337,18 @@ export function SpreadsheetGrid(props: {: (literalNumberDisplay(cell) ?? cellPlainText(cell?.value ?? ''))));};+ const accounting = (address: string) => {+ const cell = props.cells[address];+ if (cell?.format !== 'accounting') return;+ if (props.showFormulas && cell.value.startsWith('=')) return;+ const value = props.values[address];+ const numeric = value+ ? value.number !== undefined+ : literalNumber(cell) !== undefined;+ return numeric+ ? accountingParts(display(address), cell.decimals)+ : undefined;+ };const rootStyle = getComputedStyle(document.documentElement);const fontFamilies = {sans: rootStyle.getPropertyValue('--font-sans') || 'sans-serif',@@ -759,7 +772,10 @@ export function SpreadsheetGrid(props: {for (const address of addresses) {const cell = props.cells[address];context.font = `${cell?.italic ? 'italic ' : ''}${cell?.bold ? 600 : 400} ${fontPixels(cell, defaultFontSize())}px ${fontFamily(cell)}`;- const text = display(address);+ const parts = accounting(address);+ const text = parts+ ? `${parts.symbol} ${parts.amount}${parts.padding}`+ : display(address);for (const line of text.split('\n'))measured = Math.max(measured,@@ -1835,13 +1851,35 @@ export function SpreadsheetGrid(props: {/>}>- {look()?.showValue === false- ? ''- : decorated()- ? props.mentions!.renderText(- cell()!.value.replace(/^'/, '')- )- : display(address)}+ {look()?.showValue === false ? (+ ''+ ) : decorated() ? (+ props.mentions!.renderText(+ cell()!.value.replace(/^'/, '')+ )+ ) : (+ <Show+ when={accounting(address)}+ fallback={display(address)}+ >+ {(parts) => (+ <span+ data-accounting+ class="flex justify-between gap-[0.25em]"+ >+ <span class="shrink-0">+ {parts().symbol}+ </span>+ <span class="min-w-0 overflow-hidden text-ellipsis">+ {parts().amount}+ <span class="invisible">+ {parts().padding}+ </span>+ </span>+ </span>+ )}+ </Show>+ )}</Show></div>}diff --git a/apps/web/src/features/block-spreadsheet/components/SpreadsheetToolbar.test.tsx b/apps/web/src/features/block-spreadsheet/components/SpreadsheetToolbar.test.tsxindex e4d8e7ee0d..59172ebfb2 100644--- a/apps/web/src/features/block-spreadsheet/components/SpreadsheetToolbar.test.tsx+++ b/apps/web/src/features/block-spreadsheet/components/SpreadsheetToolbar.test.tsx@@ -210,6 +210,16 @@ describe('spreadsheet toolbar', () => {{ key: 'Enter' });expect(view.onStyle).toHaveBeenCalledWith({ format: 'currency' });+ fireEvent.keyDown(view.getByRole('button', { name: 'Number format' }), {+ key: 'ArrowDown',+ });+ fireEvent.keyDown(+ await screen.findByRole('menuitem', {+ name: 'Accounting $ (1,234.00)',+ }),+ { key: 'Enter' }+ );+ expect(view.onStyle).toHaveBeenCalledWith({ format: 'accounting' });});it.each([diff --git a/apps/web/src/features/block-spreadsheet/core/calculation.test.ts b/apps/web/src/features/block-spreadsheet/core/calculation.test.tsindex b54e446bf8..0dd97dcb72 100644--- a/apps/web/src/features/block-spreadsheet/core/calculation.test.ts+++ b/apps/web/src/features/block-spreadsheet/core/calculation.test.ts@@ -196,6 +196,19 @@ describe('spreadsheet calculation with IronCalc', () => {expect(result.A8.display).toBe('0.00');});+ it('formats accounting results with parentheses and a dash for zero', () => {+ const result = calculator.calculate({+ A1: { value: '1234.5', format: 'accounting' },+ A2: { value: '=-A1*2', format: 'accounting' },+ A3: { value: '=A1-1234.5', format: 'accounting' },+ A4: { value: '=A1', format: 'accounting', decimals: 0 },+ });+ expect(result.A1).toEqual({ display: '$1,234.50', number: 1234.5 });+ expect(result.A2).toEqual({ display: '$(2,469.00)', number: -2469 });+ expect(result.A3).toEqual({ display: '$-', number: 0 });+ expect(result.A4.display).toBe('$1,235');+ });+it('reads results at Excel’s fifteen significant digits', () => {const result = calculator.calculate(cells({diff --git a/apps/web/src/features/block-spreadsheet/core/toolbar-types.ts b/apps/web/src/features/block-spreadsheet/core/toolbar-types.tsindex 4df7633936..87f648e083 100644--- a/apps/web/src/features/block-spreadsheet/core/toolbar-types.ts+++ b/apps/web/src/features/block-spreadsheet/core/toolbar-types.ts@@ -71,6 +71,7 @@ export const SPREADSHEET_NUMBER_FORMATS = [{ value: 'general', label: 'Automatic', example: '1,234.5' },{ value: 'number', label: 'Number', example: '1,234.00' },{ value: 'currency', label: 'Currency', example: '$1,234.00' },+ { value: 'accounting', label: 'Accounting', example: '$ (1,234.00)' },{ value: 'percent', label: 'Percent', example: '12.50%' },{ value: 'date', label: 'Date', example: '9/17/2026' },{ value: 'time', label: 'Time', example: '12:30 PM' },diff --git a/apps/web/src/features/block-spreadsheet/core/xlsx-codec.test.ts b/apps/web/src/features/block-spreadsheet/core/xlsx-codec.test.tsindex 71d0371049..7b547af9d3 100644--- a/apps/web/src/features/block-spreadsheet/core/xlsx-codec.test.ts+++ b/apps/web/src/features/block-spreadsheet/core/xlsx-codec.test.ts@@ -177,6 +177,54 @@ describe('Excel workbook files', () => {expect(result.sheets[0].cells).toEqual(sheet.cells);});+ it("exports accounting as Excel's accounting format and imports it back", async () => {+ const sheet = simpleSheet();+ sheet.cells = {+ A1: { value: '1234.5', format: 'accounting' },+ A2: { value: '-3', format: 'accounting', decimals: 0 },+ };+ const encoded = await encodeXlsx({ sheets: [sheet] });+ // ExcelJS drops backslashes from the codes it reads, so read the part.+ const styles = strFromU8(unzipSync(encoded.bytes)['xl/styles.xml']);+ expect(styles).toContain(+ 'formatCode="_("$"* #,##0.00_);_("$"* \\(#,##0.00\\);_("$"* "-"??_);_(@_)"'+ );+ expect(styles).toContain(+ 'formatCode="_("$"* #,##0_);_("$"* \\(#,##0\\);_("$"* "-"_);_(@_)"'+ );+ const decoded = await decodeXlsx(encoded.bytes);+ expect(decoded.sheets[0].cells).toEqual({+ A1: { value: '1234.5', format: 'accounting', decimals: 2 },+ A2: { value: '-3', format: 'accounting', decimals: 0 },+ });+ });++ it('imports dollar formats with a repeated fill as accounting, keeping variants for export', async () => {+ const variant = '_($* #,##0.00_);_($* (#,##0.00);_($* "-"??_);_(@_)';+ const workbook = new ExcelJS.Workbook();+ const sheet = workbook.addWorksheet('Ledger');+ sheet.getCell('A1').value = 10;+ sheet.getCell('A1').numFmt = variant;+ sheet.getCell('A2').value = 10;+ sheet.getCell('A2').numFmt = '$#,##0.00';+ sheet.getCell('A3').value = 10;+ sheet.getCell('A3').numFmt =+ '_(* #,##0.00_);_(* \\(#,##0.00\\);_(* "-"??_);_(@_)';+ const imported = await decodeXlsx(await file(workbook));+ const cells = imported.sheets[0].cells;+ expect(cells.A1).toEqual({+ value: '10',+ format: 'accounting',+ decimals: 2,+ numberFormat: variant,+ });+ expect(cells.A2).toEqual({ value: '10', format: 'currency', decimals: 2 });+ expect(cells.A3.format).toBe('number');+ const reopened = new ExcelJS.Workbook();+ await reopened.xlsx.load((await encodeXlsx(imported)).bytes.slice().buffer);+ expect(reopened.worksheets[0].getCell('A1').numFmt).toBe(variant);+ });+it('imports and round trips an independently generated openpyxl workbook', async () => {// This fixture was written by Python openpyxl, not the ExcelJS codec under test.const bytes = readFileSync(diff --git a/apps/web/src/features/block-spreadsheet/core/xlsx-styles.ts b/apps/web/src/features/block-spreadsheet/core/xlsx-styles.tsindex 978eb56c2e..956b5597dc 100644--- a/apps/web/src/features/block-spreadsheet/core/xlsx-styles.ts+++ b/apps/web/src/features/block-spreadsheet/core/xlsx-styles.ts@@ -37,6 +37,8 @@ function numberFormatCode(style: Required<SpreadsheetCellStyle>) {general: style.decimals < 0 ? 'General' : `0${fraction}`,number: `#,##0${fraction}`,currency: `$#,##0${fraction}`,+ // Excel's built-in accounting formats 42 and 44 at 0 and 2 decimals.+ accounting: `_("$"* #,##0${fraction}_);_("$"* \\(#,##0${fraction}\\);_("$"* "-"${'?'.repeat(digits)}_);_(@_)`,percent: `0${style.decimals < 0 ? '.##' : fraction}%`,date: 'm/d/yyyy',time: 'h:mm:ss AM/PM',@@ -69,7 +71,14 @@ export function readNumberFormat(format: string): SpreadsheetCellStyle {else if (tokens.includes('%'))style = { format: 'percent', decimals: tokens === '0.##%' ? -1 : decimals };else if (/E[+-]?0/i.test(tokens)) style = { format: 'scientific', decimals };- else if (/\$/.test(format)) style = { format: 'currency', decimals };+ else if (/\$/.test(format))+ style = {+ // A repeated fill character spreads the symbol and amount apart.+ format: tokens.replace(/_./g, '').includes('*')+ ? 'accounting'+ : 'currency',+ decimals,+ };else if (/[0#]/.test(tokens))style = { format: tokens.includes(',') ? 'number' : 'general', decimals };else style = {};diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.tsindex 469df2e259..518f82c2ed 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts@@ -498,6 +498,7 @@ export const SpreadsheetResponse = z.any().superRefine((x, ctx) => {z.literal('general'),z.literal('number'),z.literal('currency'),+ z.literal('accounting'),z.literal('percent'),z.literal('date'),z.literal('time'),@@ -8019,6 +8020,7 @@ export const EditSpreadsheet = z.object({z.literal('general'),z.literal('number'),z.literal('currency'),+ z.literal('accounting'),z.literal('percent'),z.literal('date'),z.literal('time'),diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.tsindex d25c74c25c..9e29576dee 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts@@ -136,12 +136,13 @@ export type SpreadsheetHorizontalAlign = 'auto' | 'left' | 'center' | 'right';*/export type SpreadsheetVerticalAlign = 'top' | 'middle' | 'bottom';/**- * Number interpretation and display; currency is USD and dates use UTC.+ * Number interpretation and display; currency and accounting are USD and dates use UTC.*/export type SpreadsheetNumberFormat =| 'general'| 'number'| 'currency'+ | 'accounting'| 'percent'| 'date'| 'time'diff --git a/crates/documents/src/domain/spreadsheet/models.rs b/crates/documents/src/domain/spreadsheet/models.rsindex 65ff8b3785..4fb9506a0a 100644--- a/crates/documents/src/domain/spreadsheet/models.rs+++ b/crates/documents/src/domain/spreadsheet/models.rs@@ -40,7 +40,7 @@ pub enum SpreadsheetVerticalAlign {Bottom,}-/// Number interpretation and display; currency is USD and dates use UTC.+/// Number interpretation and display; currency and accounting are USD and dates use UTC.#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]#[serde(rename_all = "snake_case")]pub enum SpreadsheetNumberFormat {@@ -50,6 +50,8 @@ pub enum SpreadsheetNumberFormat {Number,/// Currency.Currency,+ /// Accounting: $ at the cell's left edge, negatives in parentheses, zero as a dash.+ Accounting,/// Percent.Percent,/// Date.diff --git a/crates/documents/src/domain/spreadsheet/test.rs b/crates/documents/src/domain/spreadsheet/test.rsindex 32fcddc7df..0382b62a52 100644--- a/crates/documents/src/domain/spreadsheet/test.rs+++ b/crates/documents/src/domain/spreadsheet/test.rs@@ -263,6 +263,14 @@ fn imported_styles_round_trip_through_the_ai_contract() {});let style: super::models::SpreadsheetStyle = serde_json::from_value(json.clone()).unwrap();assert_eq!(serde_json::to_value(style).unwrap(), json);+ let accounting = serde_json::json!({"format": "accounting", "decimals": 0});+ let style: super::models::SpreadsheetStyle =+ serde_json::from_value(accounting.clone()).unwrap();+ assert!(matches!(+ style.format,+ Some(super::models::SpreadsheetNumberFormat::Accounting)+ ));+ assert_eq!(serde_json::to_value(style).unwrap(), accounting);assert!(serde_json::from_value::<super::models::SpreadsheetStyle>(serde_json::json!({"borderBottomStyle":"bogus"})diff --git a/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.mdindex c7839a05c4..7e8cae6b45 100644--- a/docs/AGENT_GUIDE/documents.md+++ b/docs/AGENT_GUIDE/documents.md@@ -302,7 +302,10 @@ The document title and Share button sit above a compact formatting ribbon:undo/redo, paste, zoom and view options, currency/percent/decimals/number format,font and size, text styles, text/fill color, borders, alignment, wrapping,functions, format/data actions, and find. Icon controls expose accessible button-names and tooltips. **Paste special** offers **Paste** and **Paste values only**.+names and tooltips. **Number format → Accounting** shows Excel's accounting layout:+`$` at the cell's left edge, the amount at the right, negatives in parentheses and+zero as a dash; the cell's accessible name reads like `B2: $(1,234.50)`.+**Paste special** offers **Paste** and **Paste values only**.Select a range first; formatting applies to all selected cells. Toggling bold,italic, underline, or strikethrough on a mixed selection first enables it for theentire selection. Whole-column formatting preserves the viewport. In a cell thatdiff --git a/packages/spreadsheet/src/ai-formatting.test.ts b/packages/spreadsheet/src/ai-formatting.test.tsindex 7d50692788..fc53d4eb76 100644--- a/packages/spreadsheet/src/ai-formatting.test.ts+++ b/packages/spreadsheet/src/ai-formatting.test.ts@@ -120,4 +120,52 @@ describe('AI formatting preserves spreadsheet values', () => {doc.free();}});++ it('applies the accounting format and reads Excel’s accounting display back', () => {+ const doc = new LoroDoc();+ try {+ doc.getMap('spreadsheetMeta').set('formatVersion', 1);+ writeSpreadsheetCells(doc, {+ A1: { value: '1200' },+ A2: { value: '=-A1' },+ A3: { value: '=A1+A2' },+ });+ const prepared = prepareSpreadsheetEdit(+ doc,+ {+ action: 'edit',+ expectedRevision: 'v',+ operations: [+ {+ type: 'format_cells',+ sheetId: 'sheet1',+ range: 'A1:A3',+ style: { format: 'accounting' },+ },+ ],+ },+ calculator+ );+ doc.import(prepared.update);+ expect(readSpreadsheetCells(doc).A2).toEqual({+ value: '=-A1',+ format: 'accounting',+ });+ const result = readSpreadsheetForAi(+ doc,+ 'v',+ { action: 'read', ranges: ['A1:A3'], includeStyles: true },+ calculator+ );+ expect(+ result.ranges[0].cells.map(({ display, style }) => ({ display, style }))+ ).toEqual([+ { display: '$1,200.00', style: { format: 'accounting' } },+ { display: '$(1,200.00)', style: { format: 'accounting' } },+ { display: '$-', style: { format: 'accounting' } },+ ]);+ } finally {+ doc.free();+ }+ });});diff --git a/packages/spreadsheet/src/number-display.test.ts b/packages/spreadsheet/src/number-display.test.tsindex 113b89e5d6..1be75f7921 100644--- a/packages/spreadsheet/src/number-display.test.ts+++ b/packages/spreadsheet/src/number-display.test.ts@@ -1,5 +1,11 @@+import { format as formatExcelNumber } from 'ssf';import { describe, expect, it } from 'vitest';-import { literalNumber, literalNumberDisplay } from './number-display';+import {+ accountingParts,+ displayNumber,+ literalNumber,+ literalNumberDisplay,+} from './number-display';describe('literal number display', () => {it('formats imported literals as calculation will', () => {@@ -12,6 +18,9 @@ describe('literal number display', () => {expect(literalNumberDisplay({ value: '0.25', format: 'percent' })).toBe('25%');+ expect(literalNumberDisplay({ value: '-42', format: 'accounting' })).toBe(+ '$(42.00)'+ );expect(literalNumberDisplay({ value: '1234.5' })).toBe('1234.5');});@@ -27,3 +36,56 @@ describe('literal number display', () => {}});});++describe('accounting display', () => {+ const accounting = (number: number, decimals?: number) =>+ displayNumber(number, { value: '', format: 'accounting', decimals });++ it('puts negatives in parentheses and shows a dash for zero', () => {+ expect(accounting(1234.5)).toBe('$1,234.50');+ expect(accounting(-1234.5)).toBe('$(1,234.50)');+ expect(accounting(0)).toBe('$-');+ expect(accounting(0.001)).toBe('$0.00');+ expect(accounting(-0.001)).toBe('$(0.00)');+ expect(accounting(1234.5, 0)).toBe('$1,235');+ expect(accounting(-1234.5678, 3)).toBe('$(1,234.568)');+ });++ it('shows what Excel shows for the format code it exports', () => {+ const codes = [+ [2, '_("$"* #,##0.00_);_("$"* \\(#,##0.00\\);_("$"* "-"??_);_(@_)'],+ [0, '_("$"* #,##0_);_("$"* \\(#,##0\\);_("$"* "-"_);_(@_)'],+ ] as const;+ for (const [decimals, code] of codes)+ for (const number of [1234.5, -1234.5, 0, 0.001, -0.001, 1e9])+ expect(accounting(number, decimals)).toBe(+ formatExcelNumber(code, number).trim()+ );+ });++ it('lays the symbol and the amount out at the cell edges', () => {+ expect(accountingParts('$1,234.50')).toEqual({+ symbol: '$',+ amount: '1,234.50',+ padding: ')',+ });+ expect(accountingParts(' $(1,234.50)')).toEqual({+ symbol: '$',+ amount: '(1,234.50)',+ padding: '',+ });+ expect(accountingParts('$-')).toEqual({+ symbol: '$',+ amount: '-',+ padding: '00)',+ });+ expect(accountingParts(' $- ', 0)).toEqual({+ symbol: '$',+ amount: '-',+ padding: ')',+ });+ expect(accountingParts('1,234.50 €')).toBeUndefined();+ expect(accountingParts('-$1.00')).toBeUndefined();+ expect(accountingParts('$')).toBeUndefined();+ });+});diff --git a/packages/spreadsheet/src/number-display.ts b/packages/spreadsheet/src/number-display.tsindex 5d445bfa8d..81c904c740 100644--- a/packages/spreadsheet/src/number-display.ts+++ b/packages/spreadsheet/src/number-display.ts@@ -1,5 +1,8 @@import { format as formatExcelNumber } from 'ssf';-import type { SpreadsheetCell } from './spreadsheet-document';+import type {+ SpreadsheetCell,+ SpreadsheetFormat,+} from './spreadsheet-document';const numberFormatters = new Map<string, Intl.NumberFormat>();const dateFormatter = new Intl.DateTimeFormat('en-US', {@@ -40,6 +43,20 @@ export function displayNumber(number: number, cell?: SpreadsheetCell): string {);}const decimals = cell?.decimals ?? -1;+ if (format === 'accounting') {+ // Excel's accounting sections: the symbol stays outside the parentheses+ // and only an exact zero shows a dash.+ if (number === 0) return '$-';+ const amount = numberFormatter('number', decimals).format(Math.abs(number));+ return number < 0 ? `$(${amount})` : `$${amount}`;+ }+ return numberFormatter(format, decimals).format(number);+}++function numberFormatter(+ format: SpreadsheetFormat,+ decimals: number+): Intl.NumberFormat {const key = `${format}:${decimals}`;let formatter = numberFormatters.get(key);if (!formatter) {@@ -62,7 +79,30 @@ export function displayNumber(number: number, cell?: SpreadsheetCell): string {formatter = new Intl.NumberFormat('en-US', options);numberFormatters.set(key, formatter);}- return formatter.format(number);+ return formatter;+}++/**+ * An accounting display as Excel lays it out across the cell: the symbol at+ * the left edge and the amount at the right. `padding` is hidden text after+ * the amount that lines positives and zero's dash up with negatives' closing+ * parenthesis. Undefined when the display does not start with a symbol, as+ * some imported accounting formats place it after the amount.+ */+export function accountingParts(+ display: string,+ decimals = -1+): { symbol: string; amount: string; padding: string } | undefined {+ const match = /^\s*([^\d\s().,-]+)\s*(\S.*?)\s*$/.exec(display);+ if (!match) return;+ const [, symbol, amount] = match;+ const padding =+ amount === '-'+ ? `${'0'.repeat(decimals < 0 ? 2 : decimals)})`+ : amount.endsWith(')')+ ? ''+ : ')';+ return { symbol, amount, padding };}/** A cell's number when it holds a literal one rather than a formula or text. */diff --git a/packages/spreadsheet/src/spreadsheet-document.ts b/packages/spreadsheet/src/spreadsheet-document.tsindex 61b01b129d..cb7fe28aa6 100644--- a/packages/spreadsheet/src/spreadsheet-document.ts+++ b/packages/spreadsheet/src/spreadsheet-document.ts@@ -25,6 +25,7 @@ export type SpreadsheetFormat =| 'general'| 'number'| 'currency'+ | 'accounting'| 'percent'| 'date'| 'time'@@ -542,6 +543,7 @@ export function isSpreadsheetFormat(value === 'general' ||value === 'number' ||value === 'currency' ||+ value === 'accounting' ||value === 'percent' ||value === 'date' ||value === 'time' ||diff --git a/services/ai-editing-worker/src/spreadsheet/runtime.test.ts b/services/ai-editing-worker/src/spreadsheet/runtime.test.tsindex c6afe477f6..1a02ee53e6 100644--- a/services/ai-editing-worker/src/spreadsheet/runtime.test.ts+++ b/services/ai-editing-worker/src/spreadsheet/runtime.test.ts@@ -371,6 +371,28 @@ it('accepts imported financial styles in AI edits while rejecting unknown borderexpect(spreadsheetBodySchema.safeParse(body).success).toBe(false);});+it('accepts the accounting number format in AI edits', () => {+ const edit = (format: string) =>+ spreadsheetBodySchema.safeParse({+ documentId: crypto.randomUUID(),+ documentToken: 'token',+ request: {+ action: 'edit',+ expectedRevision: 'rev',+ operations: [+ {+ type: 'format_cells',+ sheetId: 'sheet1',+ range: 'B2:B9',+ style: { format, decimals: 0 },+ },+ ],+ },+ }).success;+ expect(edit('accounting')).toBe(true);+ expect(edit('ledger')).toBe(false);+});+it('accepts dropdown operations and rejects unknown dropdown fields', () => {const edit = (operation: Record<string, unknown>) =>spreadsheetBodySchema.safeParse({diff --git a/services/ai-editing-worker/src/spreadsheet/schema.ts b/services/ai-editing-worker/src/spreadsheet/schema.tsindex 9eea11b982..cdbecca05f 100644--- a/services/ai-editing-worker/src/spreadsheet/schema.ts+++ b/services/ai-editing-worker/src/spreadsheet/schema.ts@@ -67,6 +67,7 @@ const style = z'general','number','currency',+ 'accounting','percent','date','time',