Fixed assets, fully featured: tags, serials, acquisition links, label sheets, the fixed asset register, and an Assets section in the viewer; fix a flaky verify
- core: asset tags (generated PREFIX-0001 or the human's own; unique ignoring case; never reused by another asset) and serial numbers (rules.md B-24); a journaled link from an asset to the entry that acquired it (posted, unreversed, debiting the cost account); fixed_asset_register(as_of), reconciled to the GL (unposted depreciation, unregistered cost) - store: asset.tagged, asset.serial_set, asset.acquisition_linked journaled, replayed, projected (schema v9); differs_from now also compares control roles and tag history - config: [books] asset_tag_prefix, default the company's initials without legal-form words - import: Avery 5160/8160 label sheets with QR codes (geometry vendored from Avery, docs/spec/sources/avery-5160.md); the register as XLSX and PDF - mcp: register_asset tags (and links) automatically; books.label_asset, books.asset_labels; asset tools take a tag; books.show asset / assets page / register report; export fixed_asset_register (json, csv, xlsx, pdf) and in the CPA package - viewer: Assets page (register, reconciliation), asset page (identity, schedule posted vs not, entries, documents), Fixed asset register report, global search by tag/serial/description, journal text, needs-attention items - fix: verify compared snapshot amounts as strings; a zero total summed in hash-map order could print "0" or "0.00", so agreeing books failed verify at random. Now by value (regression test) - tests: spec-blind suites for tags, register, prefix, store, MCP; label and register PDF/XLSX tests; viewer tests Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01GWVo7x3UHw5kwCUaWxiejX
This commit is contained in:
1 parent
4e96b5f54d
commit
cd085108c1
53 files changed
+7872
-104
No files matched your search
@@ -0,0 +1,370 @@
|
||||
//! The fixed asset register as XLSX and PDF, for the CPA.
|
||||
//!
|
||||
//! [`ledger_core::fixed_asset_register`] computes the register; [`layout`]
|
||||
//! lays it out once — columns, one line per asset, the totals, and the
|
||||
//! reconciliation to the general ledger — and both renderers draw from
|
||||
//! that layout, so they can't drift apart. Amounts stay exact `Decimal`s
|
||||
//! until a renderer writes them, through the same paths as the statements
|
||||
//! ([`crate::report::amount_parts`] for PDF, the accounting number formats
|
||||
//! of [`crate::xlsx`] for XLSX).
|
||||
//!
|
||||
//! ```text
|
||||
//! GOAL: one list of what the company owns, its cost, depreciation, and
|
||||
//! book value, that a CPA can file, and that shows at a glance
|
||||
//! whether the register and the books agree.
|
||||
//! SOURCE: ledger_core::fixed_asset_register (INVARIANTS 1-4); CONVENTION
|
||||
//! (layout, the statements' header and footer).
|
||||
//! INVARIANTS:
|
||||
//! 1. One line per register row, in the register's order, disposed ones
|
||||
//! included and marked "Disposed DATE, proceeds AMOUNT"; held ones
|
||||
//! "Active".
|
||||
//! 2. The totals are the register's own totals (held assets only),
|
||||
//! never re-summed here.
|
||||
//! 3. Reconciliation: cost per register, per books, and their difference
|
||||
//! (unregistered_cost); accumulated depreciation per schedule, per
|
||||
//! books, and their difference (unposted_depreciation), exactly.
|
||||
//! 4. An empty register says "No fixed assets" and still shows totals
|
||||
//! and the reconciliation (the books may carry unregistered cost).
|
||||
//! 5. Header and footer as on every statement: company, "Fixed Asset
|
||||
//! Register", "As of DATE"; basis, prepared on, journal seq.
|
||||
//! 6. PDF: deterministic bytes; every text is data, never markup.
|
||||
//! ```
|
||||
|
||||
use crate::pdf::{INTER, PdfError};
|
||||
use crate::report::{ReportMeta, amount_parts, format_amount, long_date};
|
||||
use crate::xlsx::{Formats, XlsxError, footer, header, number};
|
||||
use ledger_core::reports::{AssetRegister, AssetRegisterRow};
|
||||
use rust_decimal::Decimal;
|
||||
use rust_xlsxwriter::{Format, FormatAlign, Workbook};
|
||||
use std::sync::OnceLock;
|
||||
use typst::foundations::{Dict, IntoValue};
|
||||
use typst_as_lib::{TypstEngine, TypstTemplateMainFile};
|
||||
use typst_layout::PagedDocument;
|
||||
|
||||
/// The report's title.
|
||||
pub const TITLE: &str = "Fixed Asset Register";
|
||||
|
||||
/// Column headings, left to right.
|
||||
pub const COLUMNS: [&str; 10] = [
|
||||
"Tag",
|
||||
"Description",
|
||||
"Serial",
|
||||
"In service",
|
||||
"Cost",
|
||||
"Salvage",
|
||||
"Life (months)",
|
||||
"Accumulated depreciation",
|
||||
"Book value",
|
||||
"Status",
|
||||
];
|
||||
|
||||
/// The line shown when there are no assets.
|
||||
pub const EMPTY: &str = "No fixed assets";
|
||||
|
||||
/// One asset's line.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct AssetLine {
|
||||
/// Tag, or empty.
|
||||
pub tag: String,
|
||||
/// What it is.
|
||||
pub description: String,
|
||||
/// Serial number, or empty.
|
||||
pub serial: String,
|
||||
/// In-service date, ISO 8601.
|
||||
pub in_service: String,
|
||||
/// Capitalized cost.
|
||||
pub cost: Decimal,
|
||||
/// Salvage value.
|
||||
pub salvage: Decimal,
|
||||
/// Useful life in months.
|
||||
pub life_months: u32,
|
||||
/// Accumulated depreciation by schedule (zero once disposed).
|
||||
pub accumulated: Decimal,
|
||||
/// Book value (zero once disposed).
|
||||
pub book_value: Decimal,
|
||||
/// "Active", or "Disposed 2026-09-30, proceeds 450.00".
|
||||
pub status: String,
|
||||
/// Disposed by the date (shown, not in the totals).
|
||||
pub disposed: bool,
|
||||
}
|
||||
|
||||
/// Which register column a reconciliation amount sits under.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ReconColumn {
|
||||
/// Under "Cost".
|
||||
Cost,
|
||||
/// Under "Accumulated depreciation".
|
||||
Accumulated,
|
||||
}
|
||||
|
||||
/// One reconciliation line.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ReconLine {
|
||||
/// "Cost per register", ...
|
||||
pub label: String,
|
||||
/// The amount.
|
||||
pub amount: Decimal,
|
||||
/// The column it reconciles.
|
||||
pub column: ReconColumn,
|
||||
/// A difference line (ruled above, bold).
|
||||
pub difference: bool,
|
||||
}
|
||||
|
||||
/// The register laid out for rendering.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct RegisterLayout {
|
||||
/// [`TITLE`].
|
||||
pub title: String,
|
||||
/// "As of October 15, 2026".
|
||||
pub period: String,
|
||||
/// One per asset, in register order.
|
||||
pub lines: Vec<AssetLine>,
|
||||
/// Total cost, accumulated depreciation, and book value of the assets
|
||||
/// held.
|
||||
pub totals: [Decimal; 3],
|
||||
/// Cost then accumulated depreciation: per register, per books,
|
||||
/// difference.
|
||||
pub reconciliation: Vec<ReconLine>,
|
||||
}
|
||||
|
||||
fn status(a: &AssetRegisterRow) -> String {
|
||||
match a.disposed {
|
||||
Some((date, proceeds)) => {
|
||||
format!("Disposed {date}, proceeds {}", format_amount(proceeds))
|
||||
}
|
||||
None => "Active".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Lay the register out (see the module spec).
|
||||
pub fn layout(r: &AssetRegister) -> RegisterLayout {
|
||||
let recon = |label: &str, amount, column, difference| ReconLine {
|
||||
label: label.to_string(),
|
||||
amount,
|
||||
column,
|
||||
difference,
|
||||
};
|
||||
RegisterLayout {
|
||||
title: TITLE.to_string(),
|
||||
period: format!("As of {}", long_date(r.as_of)),
|
||||
lines: r
|
||||
.rows
|
||||
.iter()
|
||||
.map(|a| AssetLine {
|
||||
tag: a.tag.clone().unwrap_or_default(),
|
||||
description: a.description.clone(),
|
||||
serial: a.serial.clone().unwrap_or_default(),
|
||||
in_service: a.in_service.to_string(),
|
||||
cost: a.cost,
|
||||
salvage: a.salvage,
|
||||
life_months: a.useful_life_months,
|
||||
accumulated: a.accumulated,
|
||||
book_value: a.book_value,
|
||||
status: status(a),
|
||||
disposed: a.disposed.is_some(),
|
||||
})
|
||||
.collect(),
|
||||
totals: [r.total_cost, r.total_accumulated, r.total_book_value],
|
||||
reconciliation: vec![
|
||||
recon("Cost per register", r.total_cost, ReconColumn::Cost, false),
|
||||
recon("Cost per books", r.ledger_cost, ReconColumn::Cost, false),
|
||||
recon(
|
||||
"Difference (unregistered cost)",
|
||||
r.unregistered_cost(),
|
||||
ReconColumn::Cost,
|
||||
true,
|
||||
),
|
||||
recon(
|
||||
"Accumulated depreciation per schedule",
|
||||
r.total_accumulated,
|
||||
ReconColumn::Accumulated,
|
||||
false,
|
||||
),
|
||||
recon(
|
||||
"Accumulated depreciation per books",
|
||||
r.ledger_accumulated,
|
||||
ReconColumn::Accumulated,
|
||||
false,
|
||||
),
|
||||
recon(
|
||||
"Difference (not yet posted)",
|
||||
r.unposted_depreciation(),
|
||||
ReconColumn::Accumulated,
|
||||
true,
|
||||
),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
/// The fixed asset register as XLSX bytes.
|
||||
///
|
||||
/// Layout as every statement (crate::xlsx INVARIANT 4): company, title,
|
||||
/// and date on rows 1-3, headings on row 5, one row per asset from row 6,
|
||||
/// amounts as numbers in the accounting format; then the totals row
|
||||
/// (double rule), an empty row, "Reconciliation to the books", and its
|
||||
/// lines with amounts under Cost and Accumulated depreciation.
|
||||
pub fn asset_register_xlsx(r: &AssetRegister, meta: &ReportMeta) -> Result<Vec<u8>, XlsxError> {
|
||||
let l = layout(r);
|
||||
let mut workbook = Workbook::new();
|
||||
let sheet = workbook.add_worksheet();
|
||||
let f = Formats::new();
|
||||
sheet.set_name(TITLE)?;
|
||||
let width = COLUMNS.len() as u16;
|
||||
let mut row = header(sheet, &f, meta, &l.title, &l.period, width)?;
|
||||
for (i, h) in COLUMNS.iter().enumerate() {
|
||||
let fmt = if (4..=8).contains(&i) {
|
||||
&f.header_right
|
||||
} else {
|
||||
&f.header
|
||||
};
|
||||
sheet.write_string_with_format(row, i as u16, h.to_uppercase(), fmt)?;
|
||||
}
|
||||
row += 1;
|
||||
if l.lines.is_empty() {
|
||||
sheet.write_string_with_format(row, 0, EMPTY, &f.sub_label)?;
|
||||
row += 1;
|
||||
}
|
||||
let quiet = Format::new().set_italic().set_font_color("#666666");
|
||||
let quiet_plain = f.plain.clone().set_italic().set_font_color("#666666");
|
||||
for a in &l.lines {
|
||||
let (text, amount) = if a.disposed {
|
||||
(&quiet, &quiet_plain)
|
||||
} else {
|
||||
(&Format::new(), &f.plain)
|
||||
};
|
||||
sheet.write_string_with_format(row, 0, &a.tag, text)?;
|
||||
sheet.write_string_with_format(row, 1, &a.description, text)?;
|
||||
sheet.write_string_with_format(row, 2, &a.serial, text)?;
|
||||
sheet.write_string_with_format(row, 3, &a.in_service, text)?;
|
||||
number(sheet, row, 4, a.cost, amount)?;
|
||||
number(sheet, row, 5, a.salvage, amount)?;
|
||||
sheet.write_number_with_format(
|
||||
row,
|
||||
6,
|
||||
f64::from(a.life_months),
|
||||
&text.clone().set_align(FormatAlign::Right),
|
||||
)?;
|
||||
number(sheet, row, 7, a.accumulated, amount)?;
|
||||
number(sheet, row, 8, a.book_value, amount)?;
|
||||
sheet.write_string_with_format(row, 9, &a.status, text)?;
|
||||
row += 1;
|
||||
}
|
||||
sheet.write_string_with_format(row, 0, "Total, assets held", &f.bold)?;
|
||||
for c in (1..width).filter(|c| ![4, 7, 8].contains(c)) {
|
||||
sheet.write_blank(row, c, &f.dollars_total)?;
|
||||
}
|
||||
for (c, d) in [4u16, 7, 8].into_iter().zip(l.totals) {
|
||||
number(sheet, row, c, d, &f.dollars_total)?;
|
||||
}
|
||||
row += 2;
|
||||
sheet.write_string_with_format(row, 0, "Reconciliation to the books", &f.bold)?;
|
||||
row += 1;
|
||||
for line in &l.reconciliation {
|
||||
let col = match line.column {
|
||||
ReconColumn::Cost => 4,
|
||||
ReconColumn::Accumulated => 7,
|
||||
};
|
||||
let (label_fmt, amount_fmt) = if line.difference {
|
||||
(&f.bold, &f.dollars_sum)
|
||||
} else {
|
||||
(&f.line_label, &f.plain)
|
||||
};
|
||||
sheet.write_string_with_format(row, 0, &line.label, label_fmt)?;
|
||||
number(sheet, row, col, line.amount, amount_fmt)?;
|
||||
row += 1;
|
||||
if line.difference {
|
||||
row += 1;
|
||||
}
|
||||
}
|
||||
for (c, w) in [
|
||||
(0, 12.0),
|
||||
(1, 40.0),
|
||||
(2, 20.0),
|
||||
(3, 12.0),
|
||||
(4, 14.0),
|
||||
(5, 12.0),
|
||||
(6, 9.0),
|
||||
(7, 16.0),
|
||||
(8, 14.0),
|
||||
(9, 34.0),
|
||||
] {
|
||||
sheet.set_column_width(c, w)?;
|
||||
}
|
||||
footer(sheet, &f, meta, row.saturating_sub(1), width)?;
|
||||
Ok(workbook.save_to_buffer()?)
|
||||
}
|
||||
|
||||
static TEMPLATE: &str = include_str!("../templates/asset_register.typ");
|
||||
|
||||
fn engine() -> &'static TypstEngine<TypstTemplateMainFile> {
|
||||
static ENGINE: OnceLock<TypstEngine<TypstTemplateMainFile>> = OnceLock::new();
|
||||
ENGINE.get_or_init(|| {
|
||||
TypstEngine::builder()
|
||||
.main_file(TEMPLATE)
|
||||
.fonts(INTER)
|
||||
.build()
|
||||
})
|
||||
}
|
||||
|
||||
fn amount(d: Decimal) -> serde_json::Value {
|
||||
let p = amount_parts(d);
|
||||
serde_json::json!({ "digits": p.digits, "negative": p.negative })
|
||||
}
|
||||
|
||||
/// The PDF template's input: the layout, every amount split for
|
||||
/// alignment.
|
||||
pub fn template_data(r: &AssetRegister, meta: &ReportMeta) -> serde_json::Value {
|
||||
let l = layout(r);
|
||||
serde_json::json!({
|
||||
"company": meta.company,
|
||||
"title": l.title,
|
||||
"period": l.period,
|
||||
"footer": meta.footer(),
|
||||
"columns": COLUMNS,
|
||||
"empty": EMPTY,
|
||||
"lines": l.lines.iter().map(|a| serde_json::json!({
|
||||
"tag": a.tag,
|
||||
"description": a.description,
|
||||
"serial": a.serial,
|
||||
"in_service": a.in_service,
|
||||
"cost": amount(a.cost),
|
||||
"salvage": amount(a.salvage),
|
||||
"life": a.life_months.to_string(),
|
||||
"accumulated": amount(a.accumulated),
|
||||
"book_value": amount(a.book_value),
|
||||
"status": a.status,
|
||||
"disposed": a.disposed,
|
||||
})).collect::<Vec<_>>(),
|
||||
"totals": l.totals.iter().map(|d| amount(*d)).collect::<Vec<_>>(),
|
||||
"reconciliation": l.reconciliation.iter().map(|x| serde_json::json!({
|
||||
"label": x.label,
|
||||
"amount": amount(x.amount),
|
||||
"difference": x.difference,
|
||||
})).collect::<Vec<_>>(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Typeset the register into a document (pages, before PDF encoding), so
|
||||
/// the layout can be inspected.
|
||||
pub fn typeset_asset_register(
|
||||
r: &AssetRegister,
|
||||
meta: &ReportMeta,
|
||||
) -> Result<PagedDocument, PdfError> {
|
||||
let mut inputs = Dict::new();
|
||||
inputs.insert(
|
||||
"data".into(),
|
||||
template_data(r, meta).to_string().into_value(),
|
||||
);
|
||||
engine()
|
||||
.compile_with_input(inputs)
|
||||
.output
|
||||
.map_err(|e| PdfError::Compile(format!("{e:?}")))
|
||||
}
|
||||
|
||||
/// The fixed asset register as PDF bytes (US Letter, landscape). See the
|
||||
/// module spec.
|
||||
pub fn asset_register_pdf(r: &AssetRegister, meta: &ReportMeta) -> Result<Vec<u8>, PdfError> {
|
||||
let doc = typeset_asset_register(r, meta)?;
|
||||
typst_pdf::pdf(&doc, &typst_pdf::PdfOptions::default())
|
||||
.map_err(|e| PdfError::Save(format!("{e:?}")))
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
//! Printable asset label sheets: one tag per label, with a QR code.
|
||||
//!
|
||||
//! Each label carries the company name, the asset tag (its headline), what
|
||||
//! the asset is, its serial number when recorded, and a QR code holding
|
||||
//! exactly the tag. Labels are typeset by `templates/labels.typ` with the
|
||||
//! same bundled Inter fonts as [`crate::pdf`]; the labels reach Typst as
|
||||
//! JSON data (`sys.inputs.data`), never as markup. The sheet geometry comes
|
||||
//! from the label maker's own specification, vendored in
|
||||
//! `docs/spec/sources/avery-5160.md`.
|
||||
//!
|
||||
//! ```text
|
||||
//! GOAL: tag every fixed asset with a label a phone can scan back to its
|
||||
//! record, printed on stock label sheets.
|
||||
//! SOURCE: docs/spec/sources/avery-5160.md (Avery 5160: 1" x 2-5/8", 30 per
|
||||
//! sheet, 3 x 10, top margin 0.5", side margin 0.1875", column pitch
|
||||
//! 2.75", row pitch 1"); ISO/IEC 18004 QR codes via the `qrcode`
|
||||
//! crate, error correction level M; CONVENTION (what a label shows).
|
||||
//! INVARIANTS:
|
||||
//! 1. Every label prints inside its cell: each label is a clipped box the
|
||||
//! size of its cell, and its text shrinks, then ellipsizes, to fit (the
|
||||
//! description in two lines, the rest in one; the tag shrinks to 6 pt
|
||||
//! before it would ever be cut, and the QR code always holds it whole).
|
||||
//! 2. Order: labels fill positions left to right, then top to bottom,
|
||||
//! starting at position `skip` of the first sheet, then on to the
|
||||
//! next sheet at position 0.
|
||||
//! 3. One page per sheet: pages = ceil((skip + labels) / per_sheet).
|
||||
//! 4. The QR code decodes to exactly the tag.
|
||||
//! 5. Deterministic: the same labels, company, sheet, and skip render to
|
||||
//! the same bytes.
|
||||
//! 6. Text is data: a description holding Typst syntax ("#panic()",
|
||||
//! "*bold*") prints literally and never runs.
|
||||
//! 7. Refused: no labels; skip >= per_sheet.
|
||||
//! SCENARIOS:
|
||||
//! - 1 label, skip 0: one page, the label at the top-left cell.
|
||||
//! - 30 labels, skip 0: one full sheet. 30 labels, skip 1: two pages, the
|
||||
//! last label at the top-left of sheet 2.
|
||||
//! - 61 labels: three pages, one label on the third.
|
||||
//! - A partly used sheet with 7 labels left: skip 23.
|
||||
//! ```
|
||||
|
||||
use crate::pdf::{INTER, PdfError};
|
||||
use qrcode::render::svg;
|
||||
use qrcode::{EcLevel, QrCode};
|
||||
use std::sync::OnceLock;
|
||||
use typst::foundations::{Dict, IntoValue};
|
||||
use typst_as_lib::{TypstEngine, TypstTemplateMainFile};
|
||||
use typst_layout::PagedDocument;
|
||||
|
||||
/// One asset label.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct AssetLabel {
|
||||
/// The asset tag, e.g. "FL-0001" (the label's headline and the QR code's content).
|
||||
pub tag: String,
|
||||
/// What it is, e.g. "Framework Laptop 13".
|
||||
pub description: String,
|
||||
/// Manufacturer serial number, if recorded.
|
||||
pub serial: Option<String>,
|
||||
}
|
||||
|
||||
/// A sheet layout.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum LabelSheet {
|
||||
/// Avery 5160 (and compatibles): 1" x 2-5/8", 30 per US Letter sheet.
|
||||
Avery5160,
|
||||
}
|
||||
|
||||
/// Where a sheet's labels sit, in PDF points (1/72 inch), measured from the
|
||||
/// page's top-left corner.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct SheetGeometry {
|
||||
/// Page width.
|
||||
pub page_width: f64,
|
||||
/// Page height.
|
||||
pub page_height: f64,
|
||||
/// One label's width.
|
||||
pub label_width: f64,
|
||||
/// One label's height.
|
||||
pub label_height: f64,
|
||||
/// Left edge of the first column (the side margin).
|
||||
pub left: f64,
|
||||
/// Top edge of the first row (the top margin).
|
||||
pub top: f64,
|
||||
/// Distance from one column's left edge to the next.
|
||||
pub pitch_x: f64,
|
||||
/// Distance from one row's top edge to the next.
|
||||
pub pitch_y: f64,
|
||||
/// Labels across.
|
||||
pub columns: usize,
|
||||
/// Labels down.
|
||||
pub rows: usize,
|
||||
/// Space kept clear inside each label's edge (printer drift).
|
||||
pub inset: f64,
|
||||
}
|
||||
|
||||
/// A label's cell on its page: `(x, y, width, height)` in points from the
|
||||
/// page's top-left corner.
|
||||
pub type Cell = (f64, f64, f64, f64);
|
||||
|
||||
impl SheetGeometry {
|
||||
/// Labels per sheet.
|
||||
pub fn per_sheet(&self) -> usize {
|
||||
self.columns * self.rows
|
||||
}
|
||||
|
||||
/// The cell at `position` (0-based, reading order) on a sheet.
|
||||
pub fn cell(&self, position: usize) -> Cell {
|
||||
let (row, col) = (position / self.columns, position % self.columns);
|
||||
(
|
||||
self.left + col as f64 * self.pitch_x,
|
||||
self.top + row as f64 * self.pitch_y,
|
||||
self.label_width,
|
||||
self.label_height,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const INCH: f64 = 72.0;
|
||||
|
||||
impl LabelSheet {
|
||||
/// The sheet's geometry, from the maker's specification
|
||||
/// (docs/spec/sources/avery-5160.md).
|
||||
pub fn geometry(self) -> SheetGeometry {
|
||||
match self {
|
||||
LabelSheet::Avery5160 => SheetGeometry {
|
||||
page_width: 8.5 * INCH,
|
||||
page_height: 11.0 * INCH,
|
||||
label_width: 2.625 * INCH,
|
||||
label_height: 1.0 * INCH,
|
||||
left: 0.1875 * INCH,
|
||||
top: 0.5 * INCH,
|
||||
pitch_x: 2.75 * INCH,
|
||||
pitch_y: 1.0 * INCH,
|
||||
columns: 3,
|
||||
rows: 10,
|
||||
inset: 4.0,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static TEMPLATE: &str = include_str!("../templates/labels.typ");
|
||||
|
||||
fn engine() -> &'static TypstEngine<TypstTemplateMainFile> {
|
||||
static ENGINE: OnceLock<TypstEngine<TypstTemplateMainFile>> = OnceLock::new();
|
||||
ENGINE.get_or_init(|| {
|
||||
TypstEngine::builder()
|
||||
.main_file(TEMPLATE)
|
||||
.fonts(INTER)
|
||||
.build()
|
||||
})
|
||||
}
|
||||
|
||||
/// The QR code for `tag` (error correction level M) as an SVG document,
|
||||
/// its 4-module quiet zone included.
|
||||
pub fn qr_svg(tag: &str) -> Result<String, PdfError> {
|
||||
let code = QrCode::with_error_correction_level(tag.as_bytes(), EcLevel::M)
|
||||
.map_err(|e| PdfError::Qr(format!("{tag:?}: {e}")))?;
|
||||
Ok(code
|
||||
.render::<svg::Color<'_>>()
|
||||
.quiet_zone(true)
|
||||
.module_dimensions(1, 1)
|
||||
.dark_color(svg::Color("#000000"))
|
||||
.light_color(svg::Color("#ffffff"))
|
||||
.build())
|
||||
}
|
||||
|
||||
/// The template's input: the geometry and every sheet's positions, with
|
||||
/// each label's QR code rendered.
|
||||
pub fn template_data(
|
||||
labels: &[AssetLabel],
|
||||
company: &str,
|
||||
sheet: LabelSheet,
|
||||
skip: usize,
|
||||
) -> Result<serde_json::Value, PdfError> {
|
||||
let g = sheet.geometry();
|
||||
let per = g.per_sheet();
|
||||
if labels.is_empty() {
|
||||
return Err(PdfError::NoLabels);
|
||||
}
|
||||
if skip >= per {
|
||||
return Err(PdfError::SkipOutOfRange {
|
||||
skip,
|
||||
per_sheet: per,
|
||||
});
|
||||
}
|
||||
let mut positions: Vec<serde_json::Value> = vec![serde_json::Value::Null; skip];
|
||||
for l in labels {
|
||||
positions.push(serde_json::json!({
|
||||
"tag": l.tag,
|
||||
"description": l.description,
|
||||
"serial": l.serial,
|
||||
"qr": qr_svg(&l.tag)?,
|
||||
}));
|
||||
}
|
||||
let pages: Vec<_> = positions.chunks(per).map(<[_]>::to_vec).collect();
|
||||
Ok(serde_json::json!({
|
||||
"company": company,
|
||||
"geometry": {
|
||||
"page_width": g.page_width,
|
||||
"page_height": g.page_height,
|
||||
"label_width": g.label_width,
|
||||
"label_height": g.label_height,
|
||||
"left": g.left,
|
||||
"top": g.top,
|
||||
"pitch_x": g.pitch_x,
|
||||
"pitch_y": g.pitch_y,
|
||||
"columns": g.columns,
|
||||
"rows": g.rows,
|
||||
"inset": g.inset,
|
||||
},
|
||||
"pages": pages,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Typeset label sheets into a document (pages, before PDF encoding), so
|
||||
/// the layout can be inspected. Same arguments and refusals as
|
||||
/// [`asset_labels_pdf`].
|
||||
pub fn typeset_labels(
|
||||
labels: &[AssetLabel],
|
||||
company: &str,
|
||||
sheet: LabelSheet,
|
||||
skip: usize,
|
||||
) -> Result<PagedDocument, PdfError> {
|
||||
let data = template_data(labels, company, sheet, skip)?;
|
||||
let mut inputs = Dict::new();
|
||||
inputs.insert("data".into(), data.to_string().into_value());
|
||||
engine()
|
||||
.compile_with_input(inputs)
|
||||
.output
|
||||
.map_err(|e| PdfError::Compile(format!("{e:?}")))
|
||||
}
|
||||
|
||||
/// Render labels onto sheets, starting `skip` positions into the first sheet (to reuse a partly used sheet), as PDF bytes.
|
||||
///
|
||||
/// See the module documentation for the spec. Refuses an empty `labels`
|
||||
/// ([`PdfError::NoLabels`]) and `skip` of a whole sheet or more
|
||||
/// ([`PdfError::SkipOutOfRange`]).
|
||||
pub fn asset_labels_pdf(
|
||||
labels: &[AssetLabel],
|
||||
company: &str,
|
||||
sheet: LabelSheet,
|
||||
skip: usize,
|
||||
) -> Result<Vec<u8>, PdfError> {
|
||||
let doc = typeset_labels(labels, company, sheet, skip)?;
|
||||
typst_pdf::pdf(&doc, &typst_pdf::PdfOptions::default())
|
||||
.map_err(|e| PdfError::Save(format!("{e:?}")))
|
||||
}
|
||||
@@ -6,20 +6,26 @@
|
||||
//! - [`report`]: the statement layout every renderer draws from.
|
||||
//! - [`xlsx`]: generate XLSX reports.
|
||||
//! - [`pdf`]: generate PDF financial statements (CPA handoff).
|
||||
//! - [`asset_register`]: the fixed asset register as XLSX and PDF.
|
||||
//! - [`labels`]: print asset label sheets with QR codes.
|
||||
//!
|
||||
//! All money stays `Decimal`; no floats in money paths.
|
||||
|
||||
pub mod asset_register;
|
||||
pub mod bank_csv;
|
||||
pub mod chart_csv;
|
||||
pub mod iif;
|
||||
pub mod labels;
|
||||
pub mod pdf;
|
||||
pub mod report;
|
||||
pub mod templates;
|
||||
pub mod xlsx;
|
||||
|
||||
pub use asset_register::{asset_register_pdf, asset_register_xlsx};
|
||||
pub use bank_csv::{BankCsvError, BankTransaction, DateOrder, parse_bank_csv, parse_bank_csv_with};
|
||||
pub use chart_csv::{ChartRow, parse_chart_csv};
|
||||
pub use iif::{IifAccount, IifError, QbAccountType, iif_accounts, journal_to_iif};
|
||||
pub use labels::{AssetLabel, LabelSheet, asset_labels_pdf};
|
||||
pub use pdf::{PdfError, statement_pdf};
|
||||
pub use report::{Member, ReportMeta, Row, RowKind, Statement, YearEarnings, format_amount};
|
||||
pub use templates::{ChartTemplate, EntityType, chart_template};
|
||||
|
||||
@@ -25,10 +25,24 @@ pub enum PdfError {
|
||||
/// The PDF writer failed.
|
||||
#[error("pdf save failed: {0}")]
|
||||
Save(String),
|
||||
/// No labels to print.
|
||||
#[error("no labels to print")]
|
||||
NoLabels,
|
||||
/// The skip would start past the first sheet.
|
||||
#[error("skip {skip} is out of range: a sheet has {per_sheet} labels, so skip must be 0 to {}", per_sheet - 1)]
|
||||
SkipOutOfRange {
|
||||
/// The requested skip.
|
||||
skip: usize,
|
||||
/// Labels per sheet.
|
||||
per_sheet: usize,
|
||||
},
|
||||
/// A tag could not be encoded as a QR code (too long).
|
||||
#[error("qr code failed: {0}")]
|
||||
Qr(String),
|
||||
}
|
||||
|
||||
static TEMPLATE: &str = include_str!("../templates/statement.typ");
|
||||
static INTER: [&[u8]; 3] = [
|
||||
pub(crate) static INTER: [&[u8]; 3] = [
|
||||
include_bytes!("../fonts/Inter-Regular.ttf"),
|
||||
include_bytes!("../fonts/Inter-SemiBold.ttf"),
|
||||
include_bytes!("../fonts/Inter-Bold.ttf"),
|
||||
|
||||
@@ -44,25 +44,25 @@ impl From<rust_xlsxwriter::XlsxError> for XlsxError {
|
||||
|
||||
/// Accounting number formats: the `_)` reserves a closing parenthesis's
|
||||
/// width on positives so decimal points line up with negatives.
|
||||
const PLAIN: &str = "#,##0.00_);(#,##0.00)";
|
||||
const DOLLARS: &str = "$#,##0.00_);($#,##0.00)";
|
||||
pub(crate) const PLAIN: &str = "#,##0.00_);(#,##0.00)";
|
||||
pub(crate) const DOLLARS: &str = "$#,##0.00_);($#,##0.00)";
|
||||
|
||||
struct Formats {
|
||||
bold: Format,
|
||||
company: Format,
|
||||
centered: Format,
|
||||
header: Format,
|
||||
header_right: Format,
|
||||
plain: Format,
|
||||
dollars_sum: Format,
|
||||
dollars_total: Format,
|
||||
line_label: Format,
|
||||
sub_label: Format,
|
||||
note: Format,
|
||||
pub(crate) struct Formats {
|
||||
pub(crate) bold: Format,
|
||||
pub(crate) company: Format,
|
||||
pub(crate) centered: Format,
|
||||
pub(crate) header: Format,
|
||||
pub(crate) header_right: Format,
|
||||
pub(crate) plain: Format,
|
||||
pub(crate) dollars_sum: Format,
|
||||
pub(crate) dollars_total: Format,
|
||||
pub(crate) line_label: Format,
|
||||
pub(crate) sub_label: Format,
|
||||
pub(crate) note: Format,
|
||||
}
|
||||
|
||||
impl Formats {
|
||||
fn new() -> Self {
|
||||
pub(crate) fn new() -> Self {
|
||||
let bold = Format::new().set_bold();
|
||||
let ruled = |f: Format| f.set_border_top(FormatBorder::Thin);
|
||||
Self {
|
||||
@@ -97,7 +97,7 @@ impl Formats {
|
||||
|
||||
/// Company, title, and period centered over `width` columns; returns the
|
||||
/// next free row.
|
||||
fn header(
|
||||
pub(crate) fn header(
|
||||
sheet: &mut Worksheet,
|
||||
f: &Formats,
|
||||
meta: &ReportMeta,
|
||||
@@ -120,7 +120,7 @@ fn header(
|
||||
}
|
||||
|
||||
/// Basis, preparation date, and journal seq under the last row.
|
||||
fn footer(
|
||||
pub(crate) fn footer(
|
||||
sheet: &mut Worksheet,
|
||||
f: &Formats,
|
||||
meta: &ReportMeta,
|
||||
@@ -143,7 +143,7 @@ fn footer(
|
||||
/// with more than 13 digits before the cents can't show exactly: such an
|
||||
/// amount is written as its exact text instead, right-aligned, so the
|
||||
/// spreadsheet never shows a wrong number.
|
||||
fn number(
|
||||
pub(crate) fn number(
|
||||
sheet: &mut Worksheet,
|
||||
row: u32,
|
||||
col: u16,
|
||||
|
||||
Reference in new issue
Block a user