test(core): the adapter runs drafts and evidence

bookspec's examples for BS-entry-5, BS-entry-6 and BS-ledger-17 are run through
the real Store, none reimplemented: a draft is made by `Store::create_entry` and
`add_line` (tried on a clone first, so a line the engine refuses on a header
account leaves no half-made draft in the journal), posted by `post_entry_checked`
when the example states an evidence policy (the server's gate; the primitive
otherwise), given its state by `set_draft_state`, its document by
`attach_receipt` and thrown away by `discard_draft`. A close a draft holds back
is tried on a clone too. The two queries are read off the engine: a draft's
state from the entry itself, and the evidence decision from
`evidence::requirement`, its sentence of exemption read into the examples'
closed words. The refusals are read off the engine's errors: a placeholder
account is `header_account`, the receipt gate `evidence_required`, a draft's
command on an entry that is no draft `not_drafted`, a close with a draft in its
period `drafts_in_period`.

Wanderbooks passes every example for its picks (check-when-line-added,
reversal-evidence-is-originals); the two examples for the other options are
skipped, so the pinned skip count goes from 11 to 13.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Sonnet 5.5 committed 2026-11-09 03:44:13 -07:00
1 parent 609e4e6b26
commit 8c57046c53
10 files changed
+378 -32

No files matched your search

@@ -502,6 +502,21 @@ impl<'a> Books<'a> {
"{what}: twice"
);
}
// The evidence policy the example assumes (BS-entry-5): the books'
// own setting, as an engine holds it (BS-ledger-9). An example that
// states none has no policy, and its drafts post by the primitive.
if let Some(over) = &s.evidence_over {
use ledger_core::settings::Change;
let change = Change {
key: "policy.evidence.threshold".into(),
value: Some(serde_json::json!(over)),
};
took(
self.store
.change_settings(&[change], &bookspec_source(&ex.id)),
&format!("{}: the evidence policy", ex.id),
);
}
self.members = members;
self.party_members = party_members;
self.parties = parties;
+7 -1
View File
@@ -18,7 +18,11 @@ pub(crate) fn check(b: &Books<'_>, x: &Expect) -> Option<&'static str> {
queries.join(" and ")
);
};
only(x.entry.is_some(), "entry", &["entry", "party_part"]);
only(
x.entry.is_some(),
"entry",
&["entry", "party_part", "draft_state", "evidence"],
);
only(x.event.is_some(), "event", &["run"]);
only(
x.asset.is_some(),
@@ -111,6 +115,8 @@ pub(crate) fn check(b: &Books<'_>, x: &Expect) -> Option<&'static str> {
"document_dates" => check_document_dates(b, x),
"document" => check_document(b, x),
"invoice_numbers" => check_invoice_numbers(b, x),
"draft_state" => check_draft_state(b, x),
"evidence" => check_evidence(b, x),
q => {
let &(_, by) = FORMAT_QUERIES
.iter()
@@ -163,6 +163,17 @@ pub(crate) fn refusal(e: &LedgerError) -> String {
LedgerError::ParentTypeMismatch { .. } => "parent_type_mismatch",
LedgerError::EntryAlreadyReversed(..) => "already_reversed",
LedgerError::ClosedPeriod(..) => "period_closed",
// A line on a header account (a placeholder takes no postings),
// BS-entry-1 and BS-entry-6.
LedgerError::PlaceholderAccount(_) => "header_account",
// A close with a draft dated in its period (BS-period-2).
LedgerError::DraftsInPeriod(_) => "drafts_in_period",
// A draft's command on an entry that is no draft: it is posted
// already (a post, a state, a discard), or was discarded and is
// gone (BS-entry-5).
LedgerError::EntryAlreadyPosted(_)
| LedgerError::PostedEntryImmutable
| LedgerError::UnknownEntry(_) => "not_drafted",
other => return format!("another refusal: {other}"),
}
.to_string()
@@ -173,6 +184,8 @@ pub(crate) fn refusal(e: &LedgerError) -> String {
pub(crate) fn store_refusal(e: &StoreError) -> String {
match e {
StoreError::Ledger(e) => refusal(e),
// The evidence gate (BS-entry-5): the entry needs a document.
StoreError::ReceiptRequired(_) => "evidence_required".to_string(),
other => format!("another refusal: {other}"),
}
}
@@ -210,6 +223,7 @@ pub(crate) fn exact(s: &str, what: &str) -> Decimal {
pub(crate) fn store_refusal_obj(e: &StoreError) -> Refusal {
match e {
StoreError::Ledger(e) => Refusal::of_reason(refusal(e)),
StoreError::ReceiptRequired(_) => Refusal::of_reason("evidence_required"),
other => Refusal::of_reason(format!("another refusal: {other}")),
}
}
+194 -27
View File
@@ -20,11 +20,15 @@ impl Books<'_> {
("dispose_asset", e.dispose_asset.is_some()),
("run_schedules", e.run_schedules.is_some()),
("register_schedule", e.register_schedule.is_some()),
("post_draft", e.post_draft.is_some()),
("set_draft_state", e.set_draft_state.is_some()),
("attach_receipt", e.attach_receipt.is_some()),
("discard_draft", e.discard_draft.is_some()),
];
match kinds.iter().filter(|(_, given)| *given).collect::<Vec<_>>()[..] {
[(kind, _)] => kind,
_ => panic!(
"{} event {n}: an event is one of lines, reverses, close, bill, invoice, write_off, payment, settlement, recovery, run_depreciation, dispose_asset, run_schedules or register_schedule",
"{} event {n}: an event is one of lines, reverses, close, bill, invoice, write_off, payment, settlement, recovery, run_depreciation, dispose_asset, run_schedules, register_schedule, post_draft, set_draft_state, attach_receipt or discard_draft",
self.ex.id
),
}
@@ -80,8 +84,20 @@ impl Books<'_> {
"{ex} event {n}: {kind} is tagged with no parties or payment method"
);
assert!(
e.refused.is_none() || !matches!(kind, "close" | "invoice"),
"{ex} event {n}: refused is for a reversal, an entry, a bill or a command, which the books take whole or not at all"
e.refused.is_none() || kind != "invoice",
"{ex} event {n}: refused is for a reversal, an entry, a bill, a command or a close, which the books take whole or not at all"
);
assert!(
!e.draft || matches!(kind, "lines" | "reverses"),
"{ex} event {n}: draft is an entry's lines or a reversal, prepared and not yet posted"
);
assert!(
!e.draft
|| (e.parties.is_empty()
&& e.instrument.is_none()
&& e.payee.is_none()
&& !e.older),
"{ex} event {n}: a draft carries no payee, parties or payment method"
);
assert!(
!(e.older && e.refused.is_some()),
@@ -204,11 +220,19 @@ impl Books<'_> {
&self.posted[n - 1],
"{what}: what the event posted is kept"
);
// What a draft event made stands as a draft (until a `post_draft`
// posts it); what any other event made is posted.
let made = if e.draft {
EntryStatus::Draft
} else {
EntryStatus::Posted
};
for &id in &posted {
assert_eq!(
self.l().get_entry(id).map(|x| x.status()),
Some(EntryStatus::Posted),
"{what}: entry {id}, which it made, is posted"
Some(made),
"{what}: entry {id}, which it made, is {}",
if e.draft { "a draft" } else { "posted" }
);
}
if (own || matches!(kind, "write_off" | "payment" | "settlement")) && e.refused.is_none() {
@@ -333,6 +357,100 @@ impl Books<'_> {
};
let day = || when.expect("checked: dated");
match kind {
// A draft (BS-entry-5, BS-entry-6): the entry prepared, and posted
// by nothing here. The engine refuses a line on a header account
// as it is added (it picks check-when-line-added), and the books
// take an entry whole or not at all, so the draft is tried on a
// clone first: a refusal leaves no half-made draft in the journal.
"lines" if e.draft => {
let lines: Vec<_> = e
.lines
.iter()
.map(|line| {
let side = match line.side.as_str() {
"debit" => Side::Debit,
"credit" => Side::Credit,
other => panic!("{what}: side {other:?}"),
};
let class = line.project.as_ref().map(|p| {
*self.projects.get(p).unwrap_or_else(|| {
panic!("{what}: project {p:?} not in setup.projects")
})
});
(
self.id(&line.account),
side,
Money::new(money(&line.amount), self.currency),
class,
)
})
.collect();
let mut probe = self.store.ledger().clone();
let entry = probe.try_create_entry(day(), description)?;
for (i, &(account, side, amount, class)) in lines.iter().enumerate() {
probe.add_line(entry, account, side, amount)?;
if class.is_some() {
probe.set_line_class(entry, i, class)?;
}
}
let entry = self.store.create_entry(day(), description)?;
for (i, &(account, side, amount, class)) in lines.iter().enumerate() {
self.store.add_line(entry, account, side, amount)?;
if class.is_some() {
self.store.set_line_class(entry, i, class)?;
}
}
Ok(())
}
"reverses" if e.draft => panic!(
"{what}: wanderbooks has no draft reversal: it picks reversal-evidence-is-originals (BS-ledger-17), under which a reversal posts at once"
),
"post_draft" => {
let p = e.post_draft.as_ref().expect("checked: a post");
let entry = self.entry_of(p.entry, what);
// With an evidence policy the post is the gate's: the
// server's path for a hand-made draft; without one, the
// primitive.
if self.has_policy() {
self.store.post_entry_checked(entry)
} else {
self.store.post_entry(entry)
}
}
"set_draft_state" => {
let s = e.set_draft_state.as_ref().expect("checked: a state");
let entry = self.entry_of(s.entry, what);
let state = match (s.state.as_str(), &s.note) {
("building", None) => ledger_core::DraftState::Building,
("awaiting_evidence", Some(note)) => {
ledger_core::DraftState::AwaitingEvidence { note: note.clone() }
}
other => panic!("{what}: draft state {other:?}"),
};
self.store.set_draft_state(entry, state)
}
"attach_receipt" => {
let r = e.attach_receipt.as_ref().expect("checked: a receipt");
let entry = self.entry_of(r.entry, what);
// The document, by its reference: its own bytes, so that two
// references are two documents (identical bytes are one file,
// plan P6 step 4).
let bytes = format!("%PDF-1.4\n{}\n%%EOF\n", r.receipt);
self.store
.attach_receipt(
Some(entry),
&format!("{}.pdf", r.receipt.replace([' ', ',', '/'], "-")),
"application/pdf",
bytes.as_bytes(),
Some(&r.receipt),
)
.map(drop)
}
"discard_draft" => {
let d = e.discard_draft.as_ref().expect("checked: a discard");
let entry = self.entry_of(d.entry, what);
self.store.discard_draft(entry, &d.reason)
}
"lines" if e.refused.is_some() => {
// The books take an entry whole or not at all, so a
// refused one leaves no draft behind: it is tried on a
@@ -355,6 +473,27 @@ impl Books<'_> {
probe.set_line_class(entry, i, Some(class))?;
}
}
// The evidence gate, as the server's post runs it: a hand entry
// the policy covers has no document, and an event cannot
// attach one before the entry exists.
if self.has_policy() {
let draft = probe.get_entry(entry).expect("just drafted").clone();
let settings = probe.settings();
if let ledger_core::evidence::Requirement::Required { reason } =
ledger_core::evidence::requirement(&probe, &draft, settings)
{
let policy = ledger_core::evidence::Policy::from_settings(settings);
return Err(StoreError::ReceiptRequired(Box::new(
ledger_store::error::ReceiptRequiredInfo {
entry_id: entry,
debits: ledger_core::evidence::Policy::entry_debits(&draft).ok(),
policy: policy.describe(),
split_group: policy.split_group(&probe, entry, &draft),
reason,
},
)));
}
}
Ok(probe.post_entry(entry)?)
}
"lines" => {
@@ -377,7 +516,11 @@ impl Books<'_> {
this.store.set_line_class(entry, i, Some(class))?;
}
}
this.store.post_entry(entry)
if this.has_policy() {
this.store.post_entry_checked(entry)
} else {
this.store.post_entry(entry)
}
};
if e.older {
ledger_core::parties::replaying(|| post(self))
@@ -399,30 +542,20 @@ impl Books<'_> {
"close" => {
let c = e.close.as_ref().expect("checked: a close");
let start = date(&c.start, what);
if e.refused.is_some() {
// A close the books refuse (a draft stands in the period,
// BS-period-2) opens no period and posts nothing: it is
// tried on a clone, with the same close below.
let mut probe = self.store.ledger().clone();
let p = probe.create_period(&format!("event {n}"), start, day())?;
return Ok(probe
.close_period_to(p, &self.close_to(c, what))
.map(drop)?);
}
let p = self
.store
.create_period(&format!("event {n}"), start, day())?;
let members: Vec<MemberClose> = self
.members
.iter()
.map(|m| MemberClose {
capital: m.capital_account,
share: m.share,
distributions: None,
})
.collect();
if c.to == "members" {
assert!(
!members.is_empty() && members.iter().all(|m| m.share > Decimal::ZERO),
"{what}: a close to the members needs their shares"
);
}
let to = match (c.to.as_str(), c.rounding.as_deref()) {
("members", None) => CloseTo::Members(members),
("members", Some("per-close")) => CloseTo::MembersPerClose(members),
("retained_earnings", None) => CloseTo::RetainedEarnings { sweep: vec![] },
other => panic!("{what}: close {other:?}"),
};
let to = self.close_to(c, what);
let closed = self.store.close_period_to(p, &to)?;
assert!(closed.is_some(), "{what}: the close has nothing to close");
Ok(())
@@ -694,6 +827,40 @@ impl Books<'_> {
}
}
}
impl Books<'_> {
/// Whether the example states an evidence policy (`setup.evidence_over`):
/// the books' own setting, which the server's post gate reads.
pub(crate) fn has_policy(&self) -> bool {
self.ex.setup.evidence_over.is_some()
}
/// Where a close sends the period's income: to retained earnings, or to
/// the members by their shares.
pub(crate) fn close_to(&self, c: &bookspec_checker::CloseSpec, what: &str) -> CloseTo {
let members: Vec<MemberClose> = self
.members
.iter()
.map(|m| MemberClose {
capital: m.capital_account,
share: m.share,
distributions: None,
})
.collect();
if c.to == "members" {
assert!(
!members.is_empty() && members.iter().all(|m| m.share > Decimal::ZERO),
"{what}: a close to the members needs their shares"
);
}
match (c.to.as_str(), c.rounding.as_deref()) {
("members", None) => CloseTo::Members(members),
("members", Some("per-close")) => CloseTo::MembersPerClose(members),
("retained_earnings", None) => CloseTo::RetainedEarnings { sweep: vec![] },
other => panic!("{what}: close {other:?}"),
}
}
}
impl Books<'_> {
/// Make a change that posts no entry (after event `after`).
/// Make a change that posts no entry (after event `after`), or say why
@@ -163,10 +163,12 @@ pub(crate) fn every_bookspec_example_holds() {
// -11 (recovery-movement), -12 (net-of-expected-discount), -13
// (net-against-the-deposit) and -14 (apportion-across-the-lines),
// BS-prepaid-2's equal-months and BS-ledger-20's refuse (each option's
// example, so no allow-list grows).
// example, so no allow-list grows), BS-entry-6's check-only-when-posting
// and BS-ledger-17's reversal-needs-its-own (wanderbooks refuses a line on
// a header as it is added, and a reversal needs no evidence of its own).
assert_eq!(
skipped.len(),
11,
"the eleven unpicked-option examples: {skipped:?}"
13,
"the thirteen unpicked-option examples: {skipped:?}"
);
}
@@ -629,3 +629,61 @@ pub(crate) fn an_invoice_lines_project_is_what_the_project_counts() {
},
);
}
/// A draft's state the engine does not hold is a failure, not a pass: the
/// example says the entry is still `building` after it posted.
#[test]
#[should_panic(expected = "state")]
pub(crate) fn a_wrong_draft_state_fails() {
run_edited(
"entry-a-draft-waits-on-its-evidence-and-posts-once-it-has-it.toml",
|t| t.replacen("state = \"posted\"", "state = \"building\"", 1),
);
}
/// An evidence decision the engine does not give is a failure.
#[test]
#[should_panic(expected = "decision")]
pub(crate) fn a_wrong_evidence_decision_fails() {
run_edited("entry-evidence-is-decided-in-one-place.toml", |t| {
t.replacen("decision = \"required\"", "decision = \"exempt\"", 1)
});
}
/// A post the gate refuses is a refusal the example must say: leaving it out
/// is a failure (the engine refused an event the example takes).
#[test]
#[should_panic(expected = "post_draft")]
pub(crate) fn a_post_without_its_evidence_must_be_marked_refused() {
run_edited(
"entry-a-draft-waits-on-its-evidence-and-posts-once-it-has-it.toml",
|t| t.replacen("refused = \"evidence_required\"\n", "", 1),
);
}
/// A discard of a posted entry is refused: saying it is accepted fails.
#[test]
#[should_panic(expected = "discard_draft")]
pub(crate) fn a_discard_of_a_posted_entry_must_be_marked_refused() {
run_edited(
"entry-a-drafts-state-is-a-note-and-a-posted-entry-has-none.toml",
|t| {
t.replacen(
"discard_draft = { entry = 1, reason = \"Posted by mistake\" }\nrefused = \"not_drafted\"",
"discard_draft = { entry = 1, reason = \"Posted by mistake\" }",
1,
)
},
);
}
/// A close the books hold back for a draft in its period is refused and
/// changes nothing: saying it is accepted fails.
#[test]
#[should_panic(expected = "draft entries exist")]
pub(crate) fn a_close_with_a_draft_in_its_period_must_be_marked_refused() {
run_edited(
"period-a-draft-holds-its-period-open-until-it-is-discarded.toml",
|t| t.replacen("refused = \"drafts_in_period\"\n", "", 1),
);
}
@@ -76,6 +76,7 @@ pub(crate) use queries::assets::*;
pub(crate) use queries::commands::*;
pub(crate) use queries::dates::*;
pub(crate) use queries::documents::*;
pub(crate) use queries::drafts::*;
pub(crate) use queries::formats::*;
pub(crate) use queries::parties::*;
pub(crate) use queries::statements::*;
@@ -160,7 +160,7 @@ pub(crate) fn check_document_dates(b: &Books<'_>, x: &Expect) {
check_figures(b, x, b.answer_document_dates(&x.query()));
}
fn check_figures(b: &Books<'_>, x: &Expect, answer: Result<Value, Refusal>) {
pub(crate) fn check_figures(b: &Books<'_>, x: &Expect, answer: Result<Value, Refusal>) {
let ex = b.ex;
let Value::Object(got) =
answer.unwrap_or_else(|r| panic!("{}: {}: {}", ex.id, x.query, r.reason))
@@ -0,0 +1,80 @@
use crate::*;
impl Books<'_> {
/// Where the entry event `q.entry` made stands (BS-entry-5), read from
/// the engine's own books: a draft's state (with its note when it awaits
/// evidence), posted (a posted entry has no state of its own), or gone
/// (a discarded draft leaves the ledger).
pub(crate) fn answer_draft_state(&self, q: &Query) -> Result<Value, Refusal> {
let n = q.entry.ok_or_else(|| self.missing("entry"))?;
let id = self.entry_or_refuse(n)?;
let mut m = JsonMap::new();
let state = match self.l().get_entry(id) {
None => "discarded",
Some(e) if e.status() == EntryStatus::Posted => "posted",
Some(e) => match e.draft_state() {
ledger_core::DraftState::Building => "building",
ledger_core::DraftState::AwaitingEvidence { note } => {
m.insert("note".to_string(), Value::String(note.clone()));
"awaiting_evidence"
}
},
};
m.insert("state".to_string(), Value::String(state.to_string()));
Ok(Value::Object(m))
}
/// The engine's one decision whether the entry event `q.entry` made
/// needs evidence (`ledger_core::evidence::requirement`, BS-entry-5): the
/// decision as the engine gives it, its reason or exemption read into
/// the examples' closed words.
pub(crate) fn answer_evidence(&self, q: &Query) -> Result<Value, Refusal> {
use ledger_core::evidence::{Requirement, requirement};
let n = q.entry.ok_or_else(|| self.missing("entry"))?;
let id = self.entry_or_refuse(n)?;
let entry = self
.l()
.get_entry(id)
.ok_or_else(|| self.missing("entry"))?;
let (decision, because) = match requirement(self.l(), entry, self.l().settings()) {
Requirement::Required { .. } => ("required", "policy"),
Requirement::Exempt { source } => (
"exempt",
// The engine words the source of an exemption in sentences;
// the examples' words are the closed list of BS-entry-5.
match source {
s if s.starts_with("the receipt policy") => "policy",
s if s.starts_with("a reversal") => "reversal",
s if s.starts_with("a period's closing entry") => "closing_entry",
s if s.starts_with("a schedule month's posting") => "schedule_posting",
s if s.starts_with("a depreciation run") => "depreciation_run",
s if s.starts_with("an asset's disposal") => "asset_disposal",
s if s.starts_with("a document's entry") || s.starts_with("a payroll") => {
"document_entry"
}
other => {
return Err(engine_refusal(
RuleId::new(Area::Entry, 5),
format!("an exemption with no word in the examples: {other}"),
));
}
},
),
};
Ok(json_figures([
("decision".to_string(), decision.to_string()),
("because".to_string(), because.to_string()),
]))
}
}
/// Check a `draft_state` expectation: the state, and the note when the draft
/// awaits evidence, and nothing else.
pub(crate) fn check_draft_state(b: &Books<'_>, x: &Expect) {
check_figures(b, x, b.answer_draft_state(&x.query()));
}
/// Check an `evidence` expectation: the decision and why, both given.
pub(crate) fn check_evidence(b: &Books<'_>, x: &Expect) {
check_figures(b, x, b.answer_evidence(&x.query()));
}
@@ -4,6 +4,7 @@ pub(crate) mod assets;
pub(crate) mod commands;
pub(crate) mod dates;
pub(crate) mod documents;
pub(crate) mod drafts;
pub(crate) mod formats;
pub(crate) mod parties;
pub(crate) mod statements;
@@ -89,6 +90,8 @@ impl Books<'_> {
"document_dates" => self.answer_document_dates(q),
"document" => self.answer_document(q),
"invoice_numbers" => self.answer_invoice_numbers(q),
"draft_state" => self.answer_draft_state(q),
"evidence" => self.answer_evidence(q),
"run" => self.answer_run(q),
"disposal" => self.answer_disposal(q),
"depreciation_schedule" => self.answer_depreciation_schedule(q),