const std = @import("std"); const Amount = @import("journal/Amount.zig"); const Posting = @import("journal/Posting.zig"); const diag = @import("diag.zig"); const Comparison = @import("journal/Comparison.zig"); const Decimal = @import("Decimal.zig"); const row = @import("row.zig"); const Error = Comparison.Error; const Journal = @This(); pub const Transaction = @import("journal/Transaction.zig"); pub const parse = @import("journal/parse.zig"); /// Source data-row order (M1-JRN-001). transactions: []const Transaction, /// Reports the first difference and stops. Later differences in the same pair /// are rarely independent -- one missing transaction shifts everything after /// it -- so listing them would be noise rather than information. pub fn compare(self: Journal, other: Journal, at: Comparison) Error!void { if (self.transactions.len != other.transactions.len) { return at.differs( "the approved journal has {d} transactions, the candidate {d}", .{ self.transactions.len, other.transactions.len }, ); } // M1-HIST-007: order is part of the comparison, so index against index. for (self.transactions, other.transactions, 0..) |a, c, index| { try a.compare(c, at.inTransaction(index)); } } /// The whole journal. Empty in, empty out: a CSV with no data rows yields a /// zero-byte file (M1-JRN-011). pub fn format(self: Journal, writer: *std.Io.Writer) std.Io.Writer.Error!void { if (self.transactions.len == 0) { return; } try writer.print("{f}", .{self.transactions[0]}); for (self.transactions[1..]) |transaction| { // A blank line between transactions, never after the last, so a // non-empty journal ends in exactly one LF (M1-JRN-010). try writer.print("\n{f}", .{transaction}); } } // -- tests ------------------------------------------------------------------- test { _ = Amount; _ = Comparison; _ = parse; _ = Posting; } const expect = std.testing.expect; const expectEqual = std.testing.expectEqual; const expectEqualStrings = std.testing.expectEqualStrings; const expectError = std.testing.expectError; const expectStringStartsWith = std.testing.expectStringStartsWith; const pair: diag.HistoryAt = .{ .csv = "bank/2026.csv", .journal = "bank/2026.csv.journal", }; fn compareText( arena: *std.heap.ArenaAllocator, approved_text: []const u8, candidate_text: []const u8, ) !struct { diags: *diag.List, result: anyerror!void } { const alloc = arena.allocator(); const diags = try diag.List.create(alloc); const approved = try parse.parse(alloc, pair.journal, approved_text, diags); const candidate = try parse.parse(alloc, pair.journal, candidate_text, diags); return .{ .result = approved.compare(candidate, .{ .diags = diags, .location = pair }), .diags = diags, }; } fn expectEquivalent(approved_text: []const u8, candidate_text: []const u8) !void { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const outcome = try compareText(&arena, approved_text, candidate_text); try outcome.result; } fn expectDiffers(approved_text: []const u8, candidate_text: []const u8) !void { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const outcome = try compareText(&arena, approved_text, candidate_text); try expectError(error.Differs, outcome.result); } const base = @embedFile("./testdata/journal/base.journal"); test "M1-HIST-006: identical journals compare equal" { try expectEquivalent(base, base); } test "M1-AC-005: formatting-only differences compare equal" { // CRLF, different indentation, wider gaps, extra blank lines, and a // different fractional scale on the same value. const reformatted = "2026-09-11 market\r\n" ++ "\tassets:bank:checking -1.5000 EUR ; note\r\n" ++ " expenses:food\r\n" ++ "\r\n"; try expectEquivalent(base, reformatted); } test "M1-HIST-008: decimal scale and sign spelling are not differences" { try expectEquivalent( "2026-09-11 x\n a:b 100.0 EUR\n c:d\n", "2026-09-11 x\n a:b 100.00 EUR\n c:d\n", ); try expectEquivalent( "2026-09-11 x\n a:b 0.00 EUR\n c:d\n", "2026-09-11 x\n a:b -0.000 EUR\n c:d\n", ); } test "M1-AC-006: a differing date is caught" { try expectDiffers(base, \\2026-09-12 market \\ assets:bank:checking -1.50 EUR ; note \\ expenses:food \\ ); } test "M1-AC-006: a differing narration is caught" { try expectDiffers(base, \\2026-09-11 supermarket \\ assets:bank:checking -1.50 EUR ; note \\ expenses:food \\ ); } test "M1-AC-006: a differing account is caught" { try expectDiffers(base, \\2026-09-11 market \\ assets:bank:checking -1.50 EUR ; note \\ expenses:groceries \\ ); } test "M1-AC-006: a differing amount value is caught" { try expectDiffers(base, \\2026-09-11 market \\ assets:bank:checking -1.51 EUR ; note \\ expenses:food \\ ); } test "M1-AC-006: a differing currency is caught" { try expectDiffers(base, \\2026-09-11 market \\ assets:bank:checking -1.50 USD ; note \\ expenses:food \\ ); } test "M1-AC-006: a differing comment is caught" { try expectDiffers(base, \\2026-09-11 market \\ assets:bank:checking -1.50 EUR ; other \\ expenses:food \\ ); } test "M1-HIST-007: comment presence is compared, not just payload" { try expectDiffers(base, \\2026-09-11 market \\ assets:bank:checking -1.50 EUR \\ expenses:food \\ ); } test "M1-AC-006: differing transaction order is caught" { const first = \\2026-09-11 one \\ a:b 1 EUR \\ c:d \\ \\2026-09-12 two \\ a:b 2 EUR \\ c:d \\ ; const swapped = \\2026-09-12 two \\ a:b 2 EUR \\ c:d \\ \\2026-09-11 one \\ a:b 1 EUR \\ c:d \\ ; try expectDiffers(first, swapped); } test "M1-AC-006: a differing transaction count is caught" { try expectDiffers(base, ""); try expectDiffers("", base); } test "M1-HIST-009: comparison is exact, with no trimming" { // A trailing space inside the comment payload is data. try expectDiffers( "2026-09-11 x\n a:b 1 EUR ; note\n c:d\n", "2026-09-11 x\n a:b 1 EUR ; note \n c:d\n", ); } test "M1-HIST-014: the rule that classified a row is not compared" { // Two journals generated by differently named rules are equal as long as // the generated data matches. Nothing records which rule produced what. try expectEquivalent( "2026-09-11 x\n a:b 1 EUR\n c:d\n", "2026-09-11 x\n a:b 1 EUR\n c:d\n", ); // It matters only where the name reached the output, as {ruleName} does. try expectDiffers( "2026-09-11 x\n a:b 1 EUR\n c:d ; by groceries\n", "2026-09-11 x\n a:b 1 EUR\n c:d ; by food\n", ); } test "M1-HIST-010: a difference names the pair and the differing posting" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const outcome = try compareText(&arena, base, \\2026-09-11 market \\ assets:bank:checking -1.50 EUR ; note \\ expenses:groceries \\ ); try expectError(error.Differs, outcome.result); const last_diag = outcome.diags.items.items[outcome.diags.items.items.len - 1]; try expectEqualStrings("bank/2026.csv", last_diag.file.?); try expectEqualStrings("bank/2026.csv.journal", last_diag.journal.?); try expectEqual(@as(usize, 0), last_diag.transaction.?); try expectEqual(@as(usize, 1), last_diag.posting.?); } test "M1-HIST-007: amount presence differs even when no value is comparable" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const alloc = arena.allocator(); const diags = try diag.List.create(alloc); // The parser refuses an explicit destination amount, so this state is // built directly to exercise the presence comparison itself. const amount: Amount = .{ .quantity = try Decimal.parseLiteral("1"), .currency = .eur, }; const with: Transaction = .{ .date = .{ .year = 2026, .month = 9, .day = 11 }, .narration = "x", .postings = .{ .{ .account = "a:b", .amount = amount, .comment = null }, .{ .account = "c:d", .amount = amount, .comment = null }, }, }; var without = with; without.postings[1].amount = null; try expectError(error.Differs, compare( .{ .transactions = &.{with} }, .{ .transactions = &.{without} }, .{ .diags = diags, .location = pair }, )); } test "M1-HIST-006: emitted output parses back and compares equal" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const alloc = arena.allocator(); const diags = try diag.List.create(alloc); const original = try parse.parse(alloc, pair.journal, base, diags); const text = try arena.allocator().print("{f}", .{original}); const reparsed = try parse.parse(alloc, pair.journal, text, diags); try original.compare(reparsed, .{ .diags = diags, .location = pair }); } test "M1-HIST-010: a whitespace-only difference is shown, not left to the eye" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); // ยง11.3: our parser keeps whatever whitespace surrounds a narration, so // these two are not equal. Printed plainly they look identical, which // makes the diagnostic read like a bug in the comparison. const outcome = try compareText( &arena, "2026-03-01 market \n a:b -2.00 EUR\n c:d\n", "2026-03-01 market\n a:b -2.00 EUR\n c:d\n", ); try expectError(error.Differs, outcome.result); const message = outcome.diags.items.items[0].message; try expect(std.mem.find(u8, message, "whitespace") != null); try expect(std.mem.find(u8, message, "market\u{00B7}\u{00B7}") != null); } test "M1-HIST-010: a comment differing only in trailing whitespace says so" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); // The likeliest case of the three: M1-TPL-010 requires emitting an // untrimmed comment, and editors strip trailing whitespace on save. const outcome = try compareText( &arena, "2026-03-01 market\n a:b -2.00 EUR ; note \n c:d\n", "2026-03-01 market\n a:b -2.00 EUR ; note\n c:d\n", ); try expectError(error.Differs, outcome.result); const message = outcome.diags.items.items[0].message; try expect(std.mem.find(u8, message, "whitespace") != null); try expect(std.mem.find(u8, message, "note\u{00B7}") != null); } test "M1-HIST-010: a tab is shown as a tab, not as a space" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const outcome = try compareText( &arena, "2026-03-01 market\n a:b -2.00 EUR ; note\tx\n c:d\n", "2026-03-01 market\n a:b -2.00 EUR ; note x\n c:d\n", ); try expectError(error.Differs, outcome.result); const message = outcome.diags.items.items[0].message; try expect(std.mem.find(u8, message, "note\u{2192}x") != null); try expect(std.mem.find(u8, message, "note\u{00B7}x") != null); } test "M1-HIST-010: extra words are not a whitespace difference" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); // Strip the whitespace and one is a prefix of the other, which is not the // same thing as differing only in whitespace. const outcome = try compareText( &arena, "2026-03-01 market\n a:b -2.00 EUR\n c:d\n", "2026-03-01 market stall\n a:b -2.00 EUR\n c:d\n", ); try expectError(error.Differs, outcome.result); try expect(std.mem.find(u8, outcome.diags.items.items[0].message, "whitespace") == null); } test "M1-HIST-010: a difference that is not about whitespace reads as before" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const outcome = try compareText( &arena, "2026-03-01 market\n a:b -2.00 EUR\n c:d\n", "2026-03-01 grocer\n a:b -2.00 EUR\n c:d\n", ); try expectError(error.Differs, outcome.result); // Ordinary differences are legible already; nothing is dressed up. const message = outcome.diags.items.items[0].message; try expectEqualStrings( "narration differs: approved 'market', candidate 'grocer'", message[std.mem.find(u8, message, "narration").?..], ); } fn amountOf(text: []const u8, currency: row.Currency) Amount { return .{ // zlinter-disable-next-line no_swallow_error - test-only: every literal passed below parses .quantity = Decimal.parseLiteral(text) catch unreachable, .currency = currency, }; } fn transactionOf(spec: struct { amount: Amount, destination_comment: ?[]const u8 = null, narration: []const u8, source_account: []const u8, source_comment: ?[]const u8 = null, target_account: []const u8, }) Transaction { return .{ .date = .{ .year = 2026, .month = 9, .day = 11 }, .narration = spec.narration, .postings = .{ .{ .account = spec.source_account, .amount = spec.amount, .comment = spec.source_comment }, .{ .account = spec.target_account, .amount = null, .comment = spec.destination_comment }, }, }; } fn emitOf(arena: *std.heap.ArenaAllocator, transactions: []const Transaction) error{OutOfMemory}![]const u8 { const journal: Journal = .{ .transactions = transactions }; return arena.allocator().print("{f}", .{journal}); } const simple = transactionOf(.{ .narration = "groceries at market", .source_account = "assets:bank:checking", .amount = amountOf("-1.50", .eur), .target_account = "expenses:food", }); test "M1-JRN-002: a transaction opens with its date and narration" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const text = try emitOf(&arena, &.{simple}); try expectStringStartsWith(text, "2026-09-11 groceries at market\n"); } test "M1-JRN-003: exactly two postings, source then destination" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const text = try emitOf(&arena, &.{simple}); var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, text, "\n"), '\n'); _ = lines.next(); try expect(std.mem.find(u8, lines.next().?, "assets:bank:checking") != null); try expect(std.mem.find(u8, lines.next().?, "expenses:food") != null); try expect(lines.next() == null); } test "M1-JRN-004: the source posting carries the signed quantity and currency" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const text = try emitOf(&arena, &.{simple}); try expect(std.mem.find(u8, text, "-1.50 EUR") != null); } test "M1-JRN-005: the destination posting omits its amount" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const text = try emitOf(&arena, &.{simple}); const last = std.mem.trimEnd(u8, text, "\n"); const line = last[std.mem.findScalarLast(u8, last, '\n').? + 1 ..]; try expectEqualStrings(" expenses:food", line); } test "M1-JRN-007: the emitted shape is exactly this" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const text = try emitOf(&arena, &.{transactionOf(.{ .narration = "market", .source_account = "assets:bank:checking", .amount = amountOf("-1.50", .eur), .target_account = "expenses:food", .source_comment = "bank/2026.csv:12", .destination_comment = "classified by groceries", })}); try expectEqualStrings( \\2026-09-11 market \\ assets:bank:checking -1.50 EUR ; bank/2026.csv:12 \\ expenses:food ; classified by groceries \\ , text); } test "M1-JRN-001: transactions keep source order and are separated" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const first = transactionOf(.{ .narration = "one", .source_account = "a:b", .amount = amountOf("1", .eur), .target_account = "c:d" }); var second = transactionOf(.{ .narration = "two", .source_account = "a:b", .amount = amountOf("2", .eur), .target_account = "c:d" }); second.date = .{ .year = 2026, .month = 9, .day = 12 }; const text = try emitOf(&arena, &.{ first, second }); try expectEqualStrings( \\2026-09-11 one \\ a:b 1 EUR \\ c:d \\ \\2026-09-12 two \\ a:b 2 EUR \\ c:d \\ , text); } test "M1-JRN-011: zero transactions produce zero bytes" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); try expectEqualStrings("", try emitOf(&arena, &.{})); } test "M1-JRN-010: output is LF-terminated with no BOM" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const text = try emitOf(&arena, &.{simple}); try expect(std.mem.endsWith(u8, text, "\n")); try expect(std.mem.findScalar(u8, text, '\r') == null); try expect(!std.mem.startsWith(u8, text, "\xEF\xBB\xBF")); } test "M1-JRN-009: a comment payload is emitted exactly, indentation aside" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); // A leading space in the payload survives the one separator space. const text = try emitOf(&arena, &.{transactionOf(.{ .narration = "x", .source_account = "a:b", .amount = amountOf("1", .eur), .target_account = "c:d", .source_comment = " leading", })}); try expect(std.mem.find(u8, text, "; leading\n") != null); } test "M1-AC-014: a whitespace-only comment is emitted, not dropped" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const text = try emitOf(&arena, &.{transactionOf(.{ .narration = "x", .source_account = "a:b", .amount = amountOf("1", .eur), .target_account = "c:d", .destination_comment = " ", })}); try expect(std.mem.find(u8, text, "c:d ; \n") != null); } test "M1-TPL-010: an absent comment emits no comment syntax" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const text = try emitOf(&arena, &.{simple}); try expect(std.mem.findScalar(u8, text, ';') == null); } test "M1-JRN-012: no excluded construct appears in the output" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const text = try emitOf(&arena, &.{transactionOf(.{ .narration = "x", .source_account = "a:b", .amount = amountOf("1", .eur), .target_account = "c:d", .source_comment = "note", })}); // No price, cost, assertion, code, status, tag or directive syntax. for ([_][]const u8{ "@", "@@", "=", "!", "*", "(", ")", "{", "}" }) |excluded| { try expect(std.mem.find(u8, text, excluded) == null); } } test "M1-CSV-019: the quantity keeps its source scale" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const text = try emitOf(&arena, &.{transactionOf(.{ .narration = "x", .source_account = "a:b", .amount = amountOf("100.00", .usd), .target_account = "c:d", })}); try expect(std.mem.find(u8, text, "100.00 USD") != null); }