merge: the adapter runs drafts and evidence (X-H1c's wanderbooks half; reviewed, re-checked)
Wanderbooks passes every bookspec example for its picks on drafts and their evidence: a draft waiting on its receipt, a discard that leaves the books as they were, a draft holding its period open, the one evidence decision answering for every entry. A refused hand entry is posted on a rehearsal of the real store, so the refusal is the engine's own; payroll postings are their own exemption source. No engine change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
b8e9b3ea8e
12 files changed
+473
-42
No files matched your search
@@ -216,6 +216,50 @@ pub(crate) fn new_schedule(
|
||||
}
|
||||
}
|
||||
|
||||
/// A store of the books as they stood (see [`Books::rehearsal`]), and the
|
||||
/// directory it lives in, which goes with it.
|
||||
pub(crate) struct Rehearsal {
|
||||
store: Store,
|
||||
_dir: tempfile::TempDir,
|
||||
}
|
||||
|
||||
impl std::ops::Deref for Rehearsal {
|
||||
type Target = Store;
|
||||
fn deref(&self) -> &Store {
|
||||
&self.store
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::DerefMut for Rehearsal {
|
||||
fn deref_mut(&mut self) -> &mut Store {
|
||||
&mut self.store
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy the directory `from` to `to`, the entries `keep` names (by file
|
||||
/// name) only, subdirectories whole.
|
||||
fn copy_tree(
|
||||
from: &std::path::Path,
|
||||
to: &std::path::Path,
|
||||
keep: &dyn Fn(&str) -> bool,
|
||||
) -> std::io::Result<()> {
|
||||
std::fs::create_dir_all(to)?;
|
||||
for entry in std::fs::read_dir(from)? {
|
||||
let entry = entry?;
|
||||
let name = entry.file_name();
|
||||
if !keep(&name.to_string_lossy()) {
|
||||
continue;
|
||||
}
|
||||
let target = to.join(&name);
|
||||
if entry.file_type()?.is_dir() {
|
||||
copy_tree(&entry.path(), &target, &|_| true)?;
|
||||
} else {
|
||||
std::fs::copy(entry.path(), target)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl<'a> Books<'a> {
|
||||
/// The books an example sets up, before any event: its shape checked,
|
||||
/// its accounts, fixed assets, schedules, parties, members, payees,
|
||||
@@ -502,6 +546,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;
|
||||
@@ -544,6 +603,27 @@ impl<'a> Books<'a> {
|
||||
|
||||
/// The entry event `event` (counting from 1) posted: an event applied
|
||||
/// already, that posted exactly one.
|
||||
/// The books as they stand, replayed from their journal into a store of
|
||||
/// their own (a copy of the journal and the blobs, opened as any store
|
||||
/// is), for a step the books must refuse without keeping a trace: a store
|
||||
/// journals a draft the moment it is made, so a refused entry is made on
|
||||
/// this and dropped with it. The directory lives as long as the store.
|
||||
pub(crate) fn rehearsal(&self, what: &str) -> Rehearsal {
|
||||
let from = self._dir.path().join("books");
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let to = dir.path().join("books");
|
||||
// The journal is the books; the database is derived, and the lock is
|
||||
// this process's own.
|
||||
copy_tree(&from, &to, &|name| {
|
||||
name != ledger_store::store::LOCK_FILE
|
||||
&& !ledger_store::store::is_database_file(name)
|
||||
&& !name.contains(".db-")
|
||||
})
|
||||
.unwrap_or_else(|e| panic!("{what}: copying the books for a rehearsal: {e}"));
|
||||
let store = took(Store::open(&to), &format!("{what}: the rehearsal"));
|
||||
Rehearsal { store, _dir: dir }
|
||||
}
|
||||
|
||||
pub(crate) fn entry_of(&self, event: usize, what: &str) -> EntryId {
|
||||
assert!(
|
||||
event >= 1 && event <= self.posted.len(),
|
||||
|
||||
@@ -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}")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,12 +357,117 @@ 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(())
|
||||
}
|
||||
// Not a panic: the example fails as an engine refusal (`another
|
||||
// refusal: ...`), and the harness goes on to report it.
|
||||
"reverses" if e.draft => Err(StoreError::Io(std::io::Error::new(
|
||||
std::io::ErrorKind::Unsupported,
|
||||
format!(
|
||||
"{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
|
||||
// clone, which is how the engine refuses it.
|
||||
let mut probe = self.store.ledger().clone();
|
||||
let entry = probe.create_entry(day(), description);
|
||||
// refused one leaves no draft behind. The store journals a
|
||||
// draft the moment it is made, so the entry is made, lined
|
||||
// and posted on a rehearsal: the same books, replayed from
|
||||
// their journal into a store of their own, which the engine
|
||||
// refuses through its own gate (`post_entry_checked` under a
|
||||
// policy, the server's path for a hand entry) and which is
|
||||
// then thrown away. The refusal is the engine's, never
|
||||
// rebuilt here.
|
||||
let mut rehearsal = self.rehearsal(what);
|
||||
let entry = rehearsal.create_entry(day(), description)?;
|
||||
for (i, line) in e.lines.iter().enumerate() {
|
||||
let side = match line.side.as_str() {
|
||||
"debit" => Side::Debit,
|
||||
@@ -347,15 +476,19 @@ impl Books<'_> {
|
||||
};
|
||||
let amount = Money::new(money(&line.amount), self.currency);
|
||||
let account = self.id(&line.account);
|
||||
probe.add_line(entry, account, side, amount)?;
|
||||
rehearsal.add_line(entry, account, side, amount)?;
|
||||
if let Some(p) = &line.project {
|
||||
let class = *self.projects.get(p).unwrap_or_else(|| {
|
||||
panic!("{what}: project {p:?} not in setup.projects")
|
||||
});
|
||||
probe.set_line_class(entry, i, Some(class))?;
|
||||
rehearsal.set_line_class(entry, i, Some(class))?;
|
||||
}
|
||||
}
|
||||
Ok(probe.post_entry(entry)?)
|
||||
if self.has_policy() {
|
||||
rehearsal.post_entry_checked(entry)
|
||||
} else {
|
||||
rehearsal.post_entry(entry)
|
||||
}
|
||||
}
|
||||
"lines" => {
|
||||
let post = |this: &mut Self| -> Result<(), StoreError> {
|
||||
@@ -377,7 +510,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 +536,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 +821,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,81 @@
|
||||
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",
|
||||
// A payroll command's posting (a run, or the tax
|
||||
// remittance) is its own source, not a document's.
|
||||
s if s.starts_with("a payroll") => "payroll_posting",
|
||||
s if s.starts_with("a document's entry") => "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),
|
||||
|
||||
@@ -21,7 +21,13 @@ more lines, debits = credits exactly); `Ledger::add_line` for the account
|
||||
check at line-adding time
|
||||
(`a_line_on_an_unknown_or_placeholder_account_is_refused_when_added`).
|
||||
**Checked:** Kani `check_lines_is_exact`, `accepted_entry_nets_to_zero`; Lean
|
||||
`Accepted.net_zero`; property `prop_posted_entries_balance`.
|
||||
`Accepted.net_zero`; property `prop_posted_entries_balance`; bookspec example
|
||||
`entry-a-line-on-a-header-is-refused-when-it-is-added` (BS-entry-6, the option
|
||||
picked: a draft with a line on a header account is refused as the draft is
|
||||
made, through `Ledger::try_create_entry` and `Ledger::add_line`, and the
|
||||
refusal read off the engine's `LedgerError::PlaceholderAccount`); the example
|
||||
`entry-a-line-on-a-header-is-refused-when-the-entry-posts` names the option
|
||||
not picked and is skipped.
|
||||
|
||||
### Product rules
|
||||
|
||||
@@ -209,7 +215,21 @@ pinned; every tool over every old book).
|
||||
(`draft_states_replay_and_project`, `drafts_v2_waits_for_the_upgrade`,
|
||||
`posted_seq_is_the_posting_lines_seq`); `ledger-cli` `tests/drafts.rs` (`a_draft_waits_for_its_receipt_and_posts`,
|
||||
`a_reversal_needs_no_receipt_of_its_own`, `gui_and_server_gate_agree`,
|
||||
`stale_preview_refused`).
|
||||
`stale_preview_refused`); bookspec examples, through `Store::post_entry_checked`,
|
||||
`Store::set_draft_state`, `Store::attach_receipt`, `Store::discard_draft` and
|
||||
`ledger_core::evidence::requirement`, each answer read off the engine:
|
||||
`entry-a-draft-waits-on-its-evidence-and-posts-once-it-has-it`,
|
||||
`entry-a-discarded-draft-leaves-the-books-unchanged`,
|
||||
`entry-a-drafts-state-is-a-note-and-a-posted-entry-has-none`,
|
||||
`period-a-draft-holds-its-period-open-until-it-is-discarded` (BS-period-2's
|
||||
`LedgerError::DraftsInPeriod`), `entry-evidence-is-decided-in-one-place` and
|
||||
`entry-only-a-draft-can-be-posted-or-discarded` (`LedgerError::EntryAlreadyPosted`
|
||||
and `LedgerError::UnknownEntry`, through `Store::post_entry` and `Store::discard_draft`). An entry the example
|
||||
says is refused when posted at once is made, lined and posted on a rehearsal:
|
||||
the books replayed from their journal into a `Store` of their own (the
|
||||
journal and the blobs copied, `Store::open`), so the refusal, an evidence
|
||||
refusal included, is `Store::post_entry_checked`'s own and the example's books
|
||||
keep no draft the engine would have journaled.
|
||||
|
||||
### Product rules
|
||||
|
||||
|
||||
@@ -164,7 +164,12 @@ None.
|
||||
(`a_draft_waits_for_its_receipt_and_posts`,
|
||||
`a_reversal_needs_no_receipt_of_its_own`); `ledger-store`
|
||||
`tests/store.rs` (`draft_states_replay_and_project`,
|
||||
`drafts_v2_waits_for_the_upgrade`).
|
||||
`drafts_v2_waits_for_the_upgrade`); bookspec example
|
||||
`ledger-a-reversal-needs-no-evidence-of-its-own` (BS-ledger-17, the option
|
||||
picked: a reversal of a 40.00 entry under a policy of over 25.00 posts at once
|
||||
and `ledger_core::evidence::requirement` exempts it as a reversal); the example
|
||||
`ledger-a-reversal-carries-its-own-evidence` names the option not picked and is
|
||||
skipped.
|
||||
|
||||
### Product rules
|
||||
|
||||
|
||||
Reference in new issue
Block a user