feat(mcp): books.mark_sent, and the send in the read tools (P4b S5)

`books.mark_sent` records the send the human or a delegate made: the
invoice (`invoice:7` or its id), the day, who sent it (the token's name
unless given), how (email by default, or mail, portal, hand, another
channel), to whom (the bill-to email, else the customer's), whether it
was the original or a reminder (original on the first send, reminder
after), and the channel's own id. It answers with every send on the
invoice, newest last. `books.documents` rows gain `last_sent` and
`books.document` shows the sends, so "did we send it, and when" is one
read away, while a bill (which we receive) has none.

The schema lint refuses a parameter named `to` (a path-name rule), so
the recipients parameter is `recipients`; the journal event and the
result keep the plan's `to`. The tool needs `books:write`: it changes
the record, never a figure.

The handbook gains the invoices-and-bills section (S4.5 had not landed
yet) with the send procedure: the books never send, the PDF goes to the
human, and each send is recorded afterwards.

Over the wire, mark_sent_records_who_and_how: two sends (the second a
reminder with a message id), the list's `last_sent`, the document's
`sends`, and the invoice still owing its total. The P2 cutover refuses
a send before consent and takes it after.
This commit is contained in:
swaits committed 2026-10-27 13:24:10 -06:00
1 parent d1fb512e4b
commit 75d8c23d9b
10 files changed
+416 -14

No files matched your search

+4
View File
@@ -103,6 +103,10 @@ pub const SECTIONS: &[(&str, &str)] = &[
"tracing-figures",
include_str!("../handbook/tracing-figures.md"),
),
(
"invoices-and-bills",
include_str!("../handbook/invoices-and-bills.md"),
),
];
/// The resource URI of the handbook's index, and the prefix of a section's.
+3 -1
View File
@@ -56,7 +56,7 @@ const C: Needs = PostWhenConfirmed;
const K: Needs = PostForApprovalRules;
/// Every tool and what it needs (INVARIANT 1).
pub const TABLE: [(&str, Needs); 122] = [
pub const TABLE: [(&str, Needs); 123] = [
("books.handbook", R),
("books.start", R),
// Settings are committed at once: the settings commit of the plan.
@@ -166,6 +166,8 @@ pub const TABLE: [(&str, Needs); 122] = [
("books.receive_payment", P),
("books.pay_bill", P),
("books.void_document", P),
// Records a send: changes the books' record, never a figure.
("books.mark_sent", W),
("books.control_check", R),
("books.documents", R),
("books.document", R),
+2 -1
View File
@@ -42,7 +42,7 @@ fn annotations_complete() {
const D: Hints = (Some(false), Some(true), None);
const WI: Hints = (Some(false), Some(false), Some(true));
const DI: Hints = (Some(false), Some(true), Some(true));
let table: [(&str, Hints); 122] = [
let table: [(&str, Hints); 123] = [
("books.handbook", R),
("books.start", R),
("books.set_setting", DI),
@@ -145,6 +145,7 @@ fn annotations_complete() {
("books.receive_payment", D),
("books.pay_bill", D),
("books.void_document", D),
("books.mark_sent", W),
("books.control_check", R),
("books.documents", R),
("books.document", R),
+168 -7
View File
@@ -77,6 +77,56 @@ fn doc_label(doc: ledger_core::DocRef) -> String {
}
}
/// A recorded send on the wire (plan P4b S5).
fn sent_out(s: &ledger_core::arap::Sent) -> SentOut {
SentOut {
on: s.on.to_string(),
by: s.by.clone(),
via: s.via.key(),
to: s.to.clone(),
kind: s.kind.key().to_string(),
reference: s.reference.clone(),
note: s.note.clone(),
}
}
/// The day an invoice last went out, when a send is recorded.
fn last_sent(sends: &[ledger_core::arap::Sent]) -> Option<String> {
sends.iter().map(|s| s.on).max().map(|d| d.to_string())
}
/// `books.mark_sent`'s `invoice`: `invoice:7` (as books.documents names
/// it), or a bare id.
fn invoice_id(r: &str) -> Result<u64, String> {
let t = r.trim();
let t = t.strip_prefix("invoice:").map(str::trim).unwrap_or(t);
t.parse::<u64>()
.map_err(|_| format!("bad invoice {r:?}: expected invoice:7 or 7"))
}
/// The channel a send went by: email, mail, portal, hand, or another
/// channel's own name (`Other`).
fn sent_via(s: &str) -> Result<ledger_core::arap::SentVia, String> {
use ledger_core::arap::SentVia;
let t = s.trim();
match t.to_ascii_lowercase().as_str() {
"email" => Ok(SentVia::Email),
"mail" | "post" | "paper mail" => Ok(SentVia::Mail),
"portal" => Ok(SentVia::Portal),
"hand" | "in person" => Ok(SentVia::Hand),
_ if t.is_empty() => {
Err("via is empty: give email, mail, portal, hand or another channel".into())
}
_ => Ok(SentVia::Other(t.to_string())),
}
}
/// original or reminder.
fn send_kind(s: &str) -> Result<ledger_core::arap::SendKind, String> {
ledger_core::arap::SendKind::parse(s.trim())
.ok_or_else(|| format!("bad kind {s:?}: expected original or reminder"))
}
/// An invoice's or bill's lines as the tool takes them: each amount
/// parsed and each project resolved ([`resolve_class`]) before anything is
/// written.
@@ -308,6 +358,83 @@ impl BooksServer {
}))
}
#[tool(
name = "books.mark_sent",
title = "Record an invoice sent",
description = "Record that an invoice went out: who sent it (by), how (via: email, mail, portal, hand, or another channel's name), to whom, the day, original or reminder, and the channel's own reference (a message id). The books never send mail: the owner or a delegate sends, then this records it. Several sends are allowed (reminders). A send changes no figure and never moves the due date. Refused on a void invoice, dated before it, with no recipients, or while the books wait for their format upgrade (documents_v2).",
annotations(
read_only_hint = false,
destructive_hint = false,
open_world_hint = false
)
)]
async fn mark_sent(
&self,
params: Parameters<MarkSentParams>,
) -> Result<Json<MarkSentOut>, String> {
use ledger_core::arap::{SendKind, Sent};
let p = params.0;
let on = self.as_of(p.on.as_deref())?;
let id = invoice_id(&p.invoice)?;
let mut store = self.lock()?;
let (to, kind) = {
let invoice = store
.ledger()
.get_invoice(id)
.ok_or_else(|| format!("no invoice {id}: see books.documents"))?;
let to = match p.recipients {
Some(to) if !to.is_empty() => to,
_ => {
let bill_to = invoice.bill_to.as_ref().and_then(|b| b.email.clone());
let party = store
.ledger()
.party_of_customer(invoice.customer_id)
.and_then(|pid| store.ledger().get_party(pid))
.and_then(|p| p.email.clone());
vec![bill_to.or(party).ok_or_else(|| {
format!(
"invoice {id} has no bill-to email and its customer no email: give to"
)
})?]
}
};
let kind = match p.kind.as_deref() {
Some(k) => send_kind(k)?,
None if invoice.sends.is_empty() => SendKind::Original,
None => SendKind::Reminder,
};
(to, kind)
};
let by = p.by.unwrap_or_else(|| {
CALLER
.with(|c| c.borrow().as_ref().map(|(_, name)| name.clone()))
.unwrap_or_else(|| ledger_store::auth::DEFAULT_NAME.to_string())
});
let via = sent_via(p.via.as_deref().unwrap_or("email"))?;
store
.mark_sent(
id,
Sent {
on,
by,
via,
to,
kind,
reference: p.reference,
note: p.note,
},
)
.map_err(|e| e.to_string())?;
let invoice = store
.ledger()
.get_invoice(id)
.ok_or_else(|| format!("invoice {id} not found after its send"))?;
Ok(Json(MarkSentOut {
invoice: format!("invoice:{id}"),
sends: invoice.sends.iter().map(sent_out).collect(),
}))
}
#[tool(
name = "books.documents",
title = "List invoices or bills",
@@ -345,7 +472,13 @@ impl BooksServer {
}
let store = self.lock()?;
let ledger = store.ledger();
let docs: Vec<(ledger_core::DocRef, String, NaiveDate, NaiveDate)> = if invoices {
let docs: Vec<(
ledger_core::DocRef,
String,
NaiveDate,
NaiveDate,
Option<String>,
)> = if invoices {
ledger
.invoices()
.into_iter()
@@ -354,7 +487,13 @@ impl BooksServer {
.get_customer(i.customer_id)
.map(|c| c.name.clone())
.unwrap_or_default();
(ledger_core::DocRef::Invoice(i.id), who, i.date, i.due_date)
(
ledger_core::DocRef::Invoice(i.id),
who,
i.date,
i.due_date,
last_sent(&i.sends),
)
})
.collect()
} else {
@@ -366,14 +505,20 @@ impl BooksServer {
.get_vendor(b.vendor_id)
.map(|v| v.name.clone())
.unwrap_or_default();
(ledger_core::DocRef::Bill(b.id), who, b.date, b.due_date)
(
ledger_core::DocRef::Bill(b.id),
who,
b.date,
b.due_date,
None,
)
})
.collect()
};
let party = p.party.as_deref().map(|s| s.trim().to_lowercase());
let mut rows = Vec::new();
let mut owed = Decimal::ZERO;
for (doc, who, date, due) in docs {
for (doc, who, date, due, last_sent) in docs {
if let Some(want_party) = &party
&& who.to_lowercase() != *want_party
&& doc_id(doc).to_string() != *want_party
@@ -411,6 +556,7 @@ impl BooksServer {
outstanding: money(st.outstanding),
status: key.to_string(),
overdue_days: st.overdue_days,
last_sent,
},
));
}
@@ -441,7 +587,7 @@ impl BooksServer {
let doc = parse_doc_ref(&p.r#ref)?;
let store = self.lock()?;
let ledger = store.ledger();
let (who, date, due, entry_id, lines) = match doc {
let (who, date, due, entry_id, lines, sends) = match doc {
ledger_core::DocRef::Invoice(id) => {
let i = ledger
.get_invoice(id)
@@ -450,7 +596,14 @@ impl BooksServer {
.get_customer(i.customer_id)
.map(|c| c.name.clone())
.unwrap_or_default();
(who, i.date, i.due_date, i.entry_id, i.lines.clone())
(
who,
i.date,
i.due_date,
i.entry_id,
i.lines.clone(),
i.sends.iter().map(sent_out).collect(),
)
}
ledger_core::DocRef::Bill(id) => {
let b = ledger
@@ -460,7 +613,14 @@ impl BooksServer {
.get_vendor(b.vendor_id)
.map(|v| v.name.clone())
.unwrap_or_default();
(who, b.date, b.due_date, b.entry_id, b.lines.clone())
(
who,
b.date,
b.due_date,
b.entry_id,
b.lines.clone(),
Vec::new(),
)
}
};
let st = ledger
@@ -532,6 +692,7 @@ impl BooksServer {
status: st.status.key().to_string(),
overdue_days: st.overdue_days,
timeline,
sends,
pdf,
}))
}
+78 -1
View File
@@ -3170,6 +3170,10 @@ pub struct DocumentRowOut {
pub status: String,
/// Days past due while something is owed; 0 otherwise.
pub overdue_days: i64,
/// The day it last went out, when a send is recorded (P4b S5);
/// absent for a document never sent and for every bill.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_sent: Option<String>,
}
/// Output of `books.documents`.
@@ -3263,6 +3267,11 @@ pub struct DocumentOut {
pub overdue_days: i64,
/// Every ledger line tagged with it, in posting order.
pub timeline: Vec<DocumentEventOut>,
/// Every recorded send, in order (P4b S5): who, how, to whom, when,
/// original or reminder, and the channel's own reference. Empty for a
/// bill and for an invoice never sent.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub sends: Vec<SentOut>,
/// The invoice's PDF, handed over (with `pdf`): run its download.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pdf: Option<HandedFile>,
@@ -4719,7 +4728,7 @@ pub struct ReconciliationsOut {
/// Parameters for `books.handbook`.
#[derive(Debug, Default, Deserialize, JsonSchema)]
pub struct HandbookParams {
/// The section to read: contract, entries, drafts-and-reversals, evidence-and-receipts, attachments, files-in-out, reconciliation, fixed-assets, prepaid-and-recurring, revenue-and-payouts, projects, parties-and-tins, 1099, cpa-handoff, settings-and-conventions, viewer, backups, self-host, format-upgrade, rules-that-change, control-roles, tracing-figures, or "all" for the whole handbook in order. Omit for the index.
/// The section to read: contract, entries, drafts-and-reversals, evidence-and-receipts, attachments, files-in-out, reconciliation, fixed-assets, prepaid-and-recurring, revenue-and-payouts, projects, parties-and-tins, 1099, cpa-handoff, settings-and-conventions, viewer, backups, self-host, format-upgrade, rules-that-change, control-roles, tracing-figures, invoices-and-bills, or "all" for the whole handbook in order. Omit for the index.
#[serde(default)]
pub section: Option<String>,
}
@@ -4758,3 +4767,71 @@ pub struct HandbookOut {
/// The section asked for (null: none was).
pub section: Option<HandbookTextOut>,
}
// P4b S5: sent tracking.
/// Parameters for `books.mark_sent`.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct MarkSentParams {
/// The invoice: `invoice:7` (as books.documents names it) or its id,
/// `7`.
pub invoice: String,
/// The day it went out, YYYY-MM-DD (omitted: today in the company's
/// time zone).
#[serde(default)]
pub on: Option<String>,
/// Who sent it: the owner, or a named delegate such as an agent
/// (omitted: this session's token name).
#[serde(default)]
pub by: Option<String>,
/// The channel: email (the default), mail, portal, hand, or another
/// channel's own name.
#[serde(default)]
pub via: Option<String>,
/// The recipients (omitted: the invoice's bill-to email, else the
/// customer's email; refused when neither is set). The journal keeps
/// them as the send's `to`.
#[serde(default)]
pub recipients: Option<Vec<String>>,
/// original (the default for a first send) or reminder (the default
/// after one).
#[serde(default)]
pub kind: Option<String>,
/// The channel's own id (a message id, a tracking number).
#[serde(default)]
pub reference: Option<String>,
/// A note about the send.
#[serde(default)]
pub note: Option<String>,
}
/// One recorded send of an invoice (P4b S5).
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SentOut {
/// The day it went out.
pub on: String,
/// Who sent it.
pub by: String,
/// How: email, mail, portal, hand, or another channel's name.
pub via: String,
/// The recipients.
pub to: Vec<String>,
/// original or reminder.
pub kind: String,
/// The channel's own id, when given.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reference: Option<String>,
/// A note about the send, when given.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub note: Option<String>,
}
/// Output of `books.mark_sent`.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct MarkSentOut {
/// The invoice, as `invoice:7`.
pub invoice: String,
/// Every send on it, in order, the newest last.
pub sends: Vec<SentOut>,
}