From 85b2d795ee0a4980ef28fd87759fad5ea883cfa9 Mon Sep 17 00:00:00 2001 From: riotcoder Date: Mon, 23 Nov 2026 00:11:02 +0000 Subject: [PATCH] 0.3.2: approval card totals invoices like CoinPay; never shows a discount value as the amount describeAction for a CoinPay draft invoice with lineItems [{quantity: 2, unit_price: 150}] and discount {type: percent, value: 10} printed "Amount 10": pick() fell through to the nested discount.value. - pick() no longer descends into discount/tax/fee-like objects. - Itemised invoices: subtotal, discount (percent or fixed), per-line tax on the discounted share, and the total, in integer cents with CoinPay's rounding (invoiceTotals, exported). - When the amount cannot be pinned down (unusable items or discount, a discount over the subtotal, an amount that disagrees with the items, or an amount next to a discount/tax with no items) the card says "see details" and shows the raw line items or arguments. Co-Authored-By: Claude Opus 5.5 --- index.d.ts | 7 +++ package.json | 2 +- src/index.js | 2 + src/money.js | 115 +++++++++++++++++++++++++++++++++++++++++---- test/money.test.js | 66 +++++++++++++++++++++++++- 5 files changed, 180 insertions(+), 12 deletions(-) diff --git a/index.d.ts b/index.d.ts index 73ed419..efb288d 100644 --- a/index.d.ts +++ b/index.d.ts @@ -369,4 +369,11 @@ export function needsConfirmation(policy: PluginPolicy, tool: string): boolean; export function visibleInMode(policy: PluginPolicy, tool: string, mode: TradingMode): boolean; export function applyPolicy(policy: PluginPolicy | null, tools: T[], mode?: TradingMode): T[]; export function describeAction(policy: PluginPolicy | null, tool: string, args: Record): ActionSummary | null; +/** Shown as the Amount when the arguments do not pin the amount down; the raw line items or arguments follow. */ +export const AMOUNT_SEE_DETAILS: string; +/** CoinPay-style invoice totals in integer cents: subtotal, discount (percent|fixed), per-line tax_rate on the discounted share, total. `{ error }` when the input is ambiguous. */ +export function invoiceTotals( + items: unknown, + discount?: unknown +): { error: string } | { error?: undefined; subtotal: bigint; discount: bigint; discountLabel: string; tax: bigint; taxedLines: number; total: bigint; lines: unknown[] }; export function redactLog(v: unknown): string; diff --git a/package.json b/package.json index e5e38fc..b592a68 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@profullstack/chat-plugins", - "version": "0.3.1", + "version": "0.3.2", "type": "module", "description": "Chat plugins = remote MCP servers, with less hoops than connectors: paste a URL or pick from a catalog, sign-in is automatic (OAuth 2.1 + DCR + PKCE), and an agent loop runs the tools even on models with no native tool calling. Zero dependencies.", "keywords": [ diff --git a/src/index.js b/src/index.js index 12deb77..b4f94a7 100644 --- a/src/index.js +++ b/src/index.js @@ -37,6 +37,8 @@ export { visibleInMode, applyPolicy, describeAction, + invoiceTotals, + AMOUNT_SEE_DETAILS, redactLog, } from "./money.js"; export { DOCS_CATALOG, mcpAddCommand } from "./docs.js"; diff --git a/src/money.js b/src/money.js index 738a4af..c72154f 100644 --- a/src/money.js +++ b/src/money.js @@ -263,6 +263,8 @@ export function applyPolicy(policy, tools, mode = "paper") { return tools.filter((t) => visibleInMode(policy, t.name, mode)).map((t) => needsConfirmation(policy, t.name) ? { ...t, annotations: { ...t.annotations ?? {}, readOnlyHint: false, destructiveHint: true } } : { ...t, annotations: { ...t.annotations ?? {}, readOnlyHint: true, destructiveHint: false } }); } const str = (v) => v === undefined || v === null ? "" : typeof v === "string" ? v : typeof v === "number" || typeof v === "boolean" ? String(v) : JSON.stringify(v); +// Keys that hold an adjustment to an amount rather than the amount itself. +const ADJUSTMENT_KEY = /discount|tax|fee|tip|coupon|rebate|credit|adjust|shipping/i; function pick(args, names) { const norm = (k) => k.toLowerCase().replace(/[_-]/g, ""); const want = names.map(norm); @@ -277,7 +279,11 @@ function pick(args, names) { const top = scan(args); if (top) return top; - for (const v of Object.values(args)) { + // One level down for wrapped arguments ({ payment: { amount } }), but never + // into a discount, tax or fee object: its `value`/`amount` is an adjustment, + // not what the action moves. + for (const [k, v] of Object.entries(args)) { + if (ADJUSTMENT_KEY.test(k)) continue; if (v && typeof v === "object" && !Array.isArray(v)) { const inner = scan(v); if (inner) @@ -330,24 +336,113 @@ function tradingSummary(tool, args) { lines.push({ label: "Account", value: paper ? "PAPER (simulated, no real money)" : "LIVE (real money)" }); return { title, lines, account: paper ? "paper" : "live", note: MODEL_CAN_BE_WRONG }; } +// Invoice arithmetic in integer cents, the same as CoinPay's server +// (computeInvoiceTotals): subtotal of quantity x unit_price, then the discount +// (percent of the subtotal, or a fixed amount), then each line's tax_rate on +// its share of the discounted subtotal. Returns { error } instead of a number +// whenever the arguments do not pin the total down. +const toNum = (v) => typeof v === "number" ? (Number.isFinite(v) ? v : null) : typeof v === "string" && v.trim() !== "" ? num(v) : null; +const cents = (n) => BigInt(Math.round(n * 100)); +const divRound = (a, b) => (a * 2n + b) / (b * 2n); +const money = (c) => (Number(c) / 100).toLocaleString("en-US", { maximumFractionDigits: 2 }); +export function invoiceTotals(items, discount) { + if (!Array.isArray(items) || items.length === 0) return { error: "no line items" }; + const lines = []; + for (const [i, it] of items.entries()) { + if (!it || typeof it !== "object" || Array.isArray(it)) return { error: `line ${i + 1} is not an item` }; + const q = toNum(it.quantity); + const p = toNum(it.unit_price ?? it.unitPrice); + const r = it.tax_rate ?? it.taxRate; + const rate = r === undefined || r === null || r === "" ? 0 : toNum(r); + if (q === null || q < 0) return { error: `line ${i + 1} has no usable quantity` }; + if (p === null || p < 0) return { error: `line ${i + 1} has no usable unit_price` }; + if (rate === null || rate < 0) return { error: `line ${i + 1} has an unusable tax_rate` }; + lines.push({ c: divRound(BigInt(Math.round(q * 1e4)) * cents(p), 10000n), rate, q, p, d: it.description }); + } + const subtotal = lines.reduce((s, l) => s + l.c, 0n); + let off = 0n; + let discountLabel = ""; + if (discount !== undefined && discount !== null) { + const type = discount && typeof discount === "object" ? discount.type : undefined; + const value = discount && typeof discount === "object" ? toNum(discount.value) : null; + if ((type !== "percent" && type !== "fixed") || value === null || value < 0) return { error: "the discount is not {type: percent|fixed, value}" }; + if (type === "percent" && value > 100) return { error: "the discount is over 100%" }; + off = type === "percent" ? divRound(subtotal * BigInt(Math.round(value * 1000)), 100000n) : cents(value); + if (off > subtotal) return { error: "the discount is larger than the subtotal" }; + discountLabel = type === "percent" ? `${value}% = -${money(off)}` : `fixed -${money(off)}`; + } + const share = lines.map(() => 0n); + if (off > 0n) { + let given = 0n; + let last = -1; + lines.forEach((l, i) => { + if (l.c === 0n) return; + last = i; + share[i] = (l.c * off) / subtotal; + given += share[i]; + }); + share[last] += off - given; + } + const tax = lines.reduce((s, l, i) => s + (l.rate ? divRound((l.c - share[i]) * BigInt(Math.round(l.rate * 1000)), 100000n) : 0n), 0n); + const taxed = lines.filter((l) => l.rate).length; + return { subtotal, discount: off, discountLabel, tax, taxedLines: taxed, total: subtotal - off + tax, lines }; +} +function describeLines(items) { + const parts = items.map((it) => { + if (!it || typeof it !== "object") return str(it); + const d = str(it.description ?? it.name ?? ""); + return `${str(it.quantity)} x ${str(it.unit_price ?? it.unitPrice)}${d ? ` ${d}` : ""}${it.tax_rate ? ` (+${str(it.tax_rate)}% tax)` : ""}`; + }); + const s = parts.join("; "); + return s.length > 300 ? `${s.slice(0, 299)}…` : s; +} +const raw = (v) => { + const s = str(v); + return s.length > 500 ? `${s.slice(0, 499)}…` : s; +}; +export const AMOUNT_SEE_DETAILS = "see details"; function moneySummary(kind, tool, args) { const lines = []; const add = (label, value) => { if (value) lines.push({ label, value }); }; - let amount = pick(args, ["amount", "amountUsd", "value", "total", "paymentAmount"]); + const given = pick(args, ["amount", "amountUsd", "value", "total", "paymentAmount"]); let currency = pick(args, ["currency", "currencyCode", "asset", "coin"]); - const items = Array.isArray(args.lineItems) ? args.lineItems : null; - if (!amount && items) { - const t = items.reduce((s, i) => s + (Number(i?.quantity) || 0) * (Number(i?.unit_price) || 0), 0); - amount = `${t.toLocaleString("en-US", { maximumFractionDigits: 8 })} before tax and discount (${items.length} line item${items.length === 1 ? "" : "s"})`; - if (!currency) - currency = "USD"; - } + const items = args.lineItems ?? args.line_items; if (typeof args.minutes === "number") add("Time", `${args.minutes} minutes`); - add("Amount", amount); + if (items !== undefined) { + // An itemised invoice: the amount is what the items add up to, never a + // number found elsewhere in the arguments. + const t = invoiceTotals(items, args.discount); + if (t.error || (given && (num(given) === null || cents(num(given)) !== t.total))) { + add("Amount", `${AMOUNT_SEE_DETAILS} (${t.error ?? `the amount given (${given}) does not match the line items`})`); + add("Line items", raw(items)); + if (args.discount !== undefined) add("Discount", raw(args.discount)); + } else { + const n = t.lines.length; + add("Subtotal", `${money(t.subtotal)} (${n} line item${n === 1 ? "" : "s"})`); + add("Discount", t.discountLabel); + if (t.taxedLines) add("Tax", `+${money(t.tax)} (on ${t.taxedLines} of ${n} line${n === 1 ? "" : "s"})`); + const how = [`${money(t.subtotal)} subtotal`]; + if (t.discount > 0n) how.push(`- ${money(t.discount)} discount`); + if (t.taxedLines) how.push(`+ ${money(t.tax)} tax`); + add("Amount", `${money(t.total)} total${how.length > 1 ? ` (${how.join(" ")})` : ""}`); + add("Line items", describeLines(items)); + } + if (!currency) currency = "USD"; + } else { + // A discount, tax or fee next to an amount leaves it unclear whether the + // amount is before or after it: show the arguments instead of a guess. + const adjustments = Object.keys(args).filter((k) => ADJUSTMENT_KEY.test(k) && args[k] !== null && args[k] !== undefined && args[k] !== ""); + if (adjustments.length) { + add("Amount", AMOUNT_SEE_DETAILS); + add("Details", raw(args)); + } else { + add("Amount", given); + } + } add("Currency", currency); add("From", pick(args, ["fromAccountId", "sourceAccountId", "from", "accountId", "fromAccount", "businessId", "fromWallet"])); add("To", pick(args, ["recipientId", "toAccountId", "destinationAccountId", "to", "recipient", "toAddress", "address", "clientId", "contractorId", "projectId"])); diff --git a/test/money.test.js b/test/money.test.js index 2bc0f5d..9078e0b 100644 --- a/test/money.test.js +++ b/test/money.test.js @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test"; -import { applyPolicy, DEFAULT_PLUGINS, describeAction, FINANCE_CATALOG, needsApproval, needsConfirmation, POLICIES, policyFor, redactLog } from "../src/index.js"; +import { applyPolicy, DEFAULT_PLUGINS, describeAction, invoiceTotals, FINANCE_CATALOG, needsApproval, needsConfirmation, POLICIES, policyFor, redactLog } from "../src/index.js"; describe("money plugin catalog", () => { test("Mercury and CoinPay are on by default; moomoo is listed but off", () => { @@ -85,6 +85,70 @@ describe("approval card", () => { expect(s.lines.find((x) => x.label === "To")?.value).toBe("c1"); }); + const card = (tool, args) => { + const s = describeAction(POLICIES.coinpay, tool, args); + return (l) => s.lines.find((x) => x.label === l)?.value; + }; + + test("a percent discount: subtotal, discount and the total after it, never the discount value as the amount", () => { + const get = card("invoice_create_draft", { clientId: "c1", lineItems: [{ description: "Consulting", quantity: 2, unit_price: 150 }], discount: { type: "percent", value: 10 } }); + expect(get("Subtotal")).toBe("300 (1 line item)"); + expect(get("Discount")).toBe("10% = -30"); + expect(get("Amount")).toBe("270 total (300 subtotal - 30 discount)"); + expect(get("Amount")).not.toMatch(/^10\b/); + expect(get("Line items")).toBe("2 x 150 Consulting"); + expect(get("Currency")).toBe("USD"); + expect(get("Tax")).toBeUndefined(); + }); + + test("a fixed discount", () => { + const get = card("invoice_create_draft", { lineItems: [{ description: "a", quantity: 1, unit_price: 100 }, { description: "b", quantity: 3, unit_price: "50.5" }], discount: { type: "fixed", value: 25 } }); + expect(get("Subtotal")).toBe("251.5 (2 line items)"); + expect(get("Discount")).toBe("fixed -25"); + expect(get("Amount")).toBe("226.5 total (251.5 subtotal - 25 discount)"); + }); + + test("tax on its share of the discounted subtotal, like CoinPay's server", () => { + const get = card("invoice_create_draft", { + lineItems: [{ description: "taxed", quantity: 2, unit_price: 150, tax_rate: 8 }, { description: "exempt", quantity: 1, unit_price: 100 }], + discount: { type: "percent", value: 10 }, + }); + // subtotal 400, discount 40 (30 on the taxed line), tax 8% of 270 = 21.6 + expect(get("Subtotal")).toBe("400 (2 line items)"); + expect(get("Discount")).toBe("10% = -40"); + expect(get("Tax")).toBe("+21.6 (on 1 of 2 lines)"); + expect(get("Amount")).toBe("381.6 total (400 subtotal - 40 discount + 21.6 tax)"); + expect(invoiceTotals([{ quantity: 1, unit_price: 10, tax_rate: 5 }]).total).toBe(1050n); + }); + + test("no line items: a plain amount is shown; next to a discount or tax it is not guessed", () => { + expect(card("payment_create", { amount: 42, currency: "USDC" })("Amount")).toBe("42"); + const adj = card("payment_create", { amount: 42, discount: { type: "fixed", value: 2 } }); + expect(adj("Amount")).toBe("see details"); + expect(adj("Details")).toContain('"discount"'); + // A nested value inside a discount/tax object is never the amount. + expect(card("thing_create", { discount: { value: 10 } })("Amount")).toBe("see details"); + expect(card("thing_create", { order: { amount: 7 } })("Amount")).toBe("7"); + expect(card("invoice_send", { invoiceId: "inv_1" })("Amount")).toBeUndefined(); + }); + + test("line items that do not add up unambiguously show the raw items, not a number", () => { + for (const args of [ + { lineItems: [{ quantity: "two", unit_price: 150 }] }, + { lineItems: [{ quantity: 1 }] }, + { lineItems: [{ quantity: 1, unit_price: 10 }], discount: { value: 10 } }, + { lineItems: [{ quantity: 1, unit_price: 10 }], discount: { type: "fixed", value: 50 } }, + { lineItems: [{ quantity: 1, unit_price: 10 }], amount: 99 }, + { lineItems: [] }, + ]) { + const get = card("invoice_create_draft", args); + expect(get("Amount")).toStartWith("see details"); + expect(get("Line items")).toBe(JSON.stringify(args.lineItems)); + } + // A matching amount is fine. + expect(card("invoice_create_draft", { lineItems: [{ quantity: 1, unit_price: 10 }], amount: 10 })("Amount")).toBe("10 total"); + }); + test("an order shows symbol, side, quantity, type, prices, estimated cost and paper vs live", () => { const live = describeAction(POLICIES.moomoo, "trading_order_place", { acc_id: "123", code: "US.AAPL", side: "BUY", qty: "10", order_type: "LIMIT", price: "190.5", time_in_force: "DAY" }); const get = (l) => live.lines.find((x) => x.label === l)?.value;