mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 18:07:00 +01:00
feat: add accounting CLI workflows and dashboard previews
Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
799e4d556f
commit
c1102f05d4
21 files changed
+1365
-13
No files matched your search
@@ -0,0 +1,62 @@
|
||||
import { Command } from "commander";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { registerCostCommands } from "../commands/client/cost.js";
|
||||
|
||||
function program() {
|
||||
const result = new Command().exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} });
|
||||
registerCostCommands(result);
|
||||
return result;
|
||||
}
|
||||
const context = ["--company-id", "test-company", "--api-base", "http://paperclip.test", "--api-key", "test-key", "--json"];
|
||||
afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); });
|
||||
describe("cost report date options", () => {
|
||||
it.each([["cost", "summary", "costs/summary"], ["finance", "events", "costs/finance-events"]])("forwards bounds and all-time for %s %s", async (group, name, path) => {
|
||||
const fetch = vi.fn().mockImplementation(() => Promise.resolve(Response.json({})));
|
||||
vi.stubGlobal("fetch", fetch);
|
||||
vi.spyOn(console, "log").mockImplementation(() => {});
|
||||
await program().parseAsync([group, name, ...context, "--all-time"], { from: "user" });
|
||||
expect(fetch.mock.calls[0][0]).toBe(`http://paperclip.test/api/companies/test-company/${path}?period=all`);
|
||||
await program().parseAsync([group, name, ...context, "--from", "2026-09-01", "--to", "2026-09-02"], { from: "user" });
|
||||
expect(fetch.mock.calls[1][0]).toBe(`http://paperclip.test/api/companies/test-company/${path}?from=2026-09-01&to=2026-09-02`);
|
||||
});
|
||||
it.each([["accounting", "health"], ["accounting", "inspect"], ["accounting", "invoices"], ["budget", "overview"], ["cost", "window-spend"], ["cost", "quota-windows"]])("rejects unsupported date flags for %s %s", async (group, name) => {
|
||||
const fetch = vi.fn(); vi.stubGlobal("fetch", fetch);
|
||||
for (const args of [["--all-time"], ["--from", "2026-09-01"], ["--to", "2026-09-02"]]) {
|
||||
await expect(program().parseAsync([group, name, ...context, ...args], { from: "user" })).rejects.toThrow("unknown option");
|
||||
}
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("accounting operator requests", () => {
|
||||
const id = "5bc31923-fd9c-4bc5-a717-c975eebc4331";
|
||||
const requests = [
|
||||
{ name: "repair", path: "accounting/repair", payload: { fingerprint: "a".repeat(64), reason: "Reviewed projection drift" } },
|
||||
{ name: "retry", path: "accounting/retry", payload: { runId: id } },
|
||||
{ name: "provider:import", path: "accounting/provider-costs/import", payload: { provider: "openai", secretId: id, accountId: "account-1", scopeIds: ["project-1"], from: "2026-09-01", to: "2026-09-03" } },
|
||||
{ name: "invoice:import", path: "accounting/invoices", payload: { biller: "openai", externalId: "invoice-1", currency: "USD", lines: [{ externalId: "line-1", amountCents: "0.0000001", occurredAt: "2026-09-01T00:00:00Z", runId: id }] } },
|
||||
{ name: "event:correct", path: `accounting/events/${id}/adjustments`, id, payload: { idempotencyKey: "correction-1", expectedCents: "0.0000001", correctedCents: "1.2500001", reason: "Provider invoice", pricing: { source: "provider_invoice" } } },
|
||||
];
|
||||
it.each(requests)("posts the company-scoped $name request without changing exact amounts", async ({ name, path, payload, ...extra }) => {
|
||||
const fetch = vi.fn().mockResolvedValue(Response.json({ ok: true }));
|
||||
vi.stubGlobal("fetch", fetch);
|
||||
vi.spyOn(console, "log").mockImplementation(() => {});
|
||||
await program().parseAsync(["accounting", name, ...(extra.id ? [extra.id] : []), ...context, "--payload-json", JSON.stringify(payload)], { from: "user" });
|
||||
expect(fetch).toHaveBeenCalledOnce();
|
||||
const [url, options] = fetch.mock.calls[0];
|
||||
expect(url).toBe(`http://paperclip.test/api/companies/test-company/${path}`);
|
||||
expect(options.method).toBe("POST");
|
||||
expect(JSON.parse(options.body)).toEqual(payload);
|
||||
});
|
||||
it("reviews one invoice using GET with an encoded ID and no request body", async () => {
|
||||
const fetch = vi.fn().mockResolvedValue(Response.json({ id }));
|
||||
vi.stubGlobal("fetch", fetch);
|
||||
vi.spyOn(console, "log").mockImplementation(() => {});
|
||||
await program().parseAsync(["accounting", "invoice:review", "invoice/one?details", ...context], { from: "user" });
|
||||
expect(fetch).toHaveBeenCalledOnce();
|
||||
const [url, options] = fetch.mock.calls[0];
|
||||
expect(url).toBe("http://paperclip.test/api/companies/test-company/accounting/invoices/invoice%2Fone%3Fdetails");
|
||||
expect(options.method).toBe("GET");
|
||||
expect(options.body).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -10,6 +10,9 @@ import {
|
||||
|
||||
interface CompanyOptions extends BaseClientOptions {
|
||||
companyId?: string;
|
||||
from?: string;
|
||||
to?: string;
|
||||
allTime?: boolean;
|
||||
}
|
||||
|
||||
interface JsonPayloadOptions extends CompanyOptions {
|
||||
@@ -33,7 +36,7 @@ export function registerCostCommands(program: Command): void {
|
||||
["window-spend", "costs/window-spend"],
|
||||
["quota-windows", "costs/quota-windows"],
|
||||
] as const) {
|
||||
addCompanyGet(cost, name, `Get ${name} cost data`, path);
|
||||
addCompanyGet(cost, name, `Get ${name} cost data`, path, name !== "window-spend" && name !== "quota-windows");
|
||||
}
|
||||
|
||||
addCommonClientOptions(
|
||||
@@ -54,12 +57,33 @@ export function registerCostCommands(program: Command): void {
|
||||
|
||||
addCompanyPostJson(cost, "event:create", "Record a cost event", "cost-events");
|
||||
|
||||
const accounting = program.command("accounting").description("Inspect and reconcile company accounting");
|
||||
addCompanyGet(accounting, "health", "Show pending receipts, pricing and reservations", "accounting/health");
|
||||
addCompanyGet(accounting, "inspect", "Read-only comparison of ledger and projections", "accounting/inspect");
|
||||
addCompanyGet(accounting, "invoices", "List imported provider invoices", "accounting/invoices");
|
||||
addCompanyPostJson(accounting, "repair", "Repair reviewed projections with inspection fingerprint and reason", "accounting/repair");
|
||||
addCompanyPostJson(accounting, "retry", "Retry accounting for a company run", "accounting/retry");
|
||||
addCompanyPostJson(accounting, "provider:import", "Import a provider cost report using a company admin credential", "accounting/provider-costs/import");
|
||||
addCompanyPostJson(accounting, "invoice:import", "Import a normalized billing invoice JSON", "accounting/invoices");
|
||||
for (const [name, , method] of [["invoice:review", "invoices", "get"], ["event:correct", "events", "post"]] as const) {
|
||||
addCommonClientOptions(accounting.command(name).argument("<id>").option("-C, --company-id <id>", "Company ID")
|
||||
.option("--payload-json <json>", "Correction JSON payload", "{}")
|
||||
.action(async (id: string, opts: JsonPayloadOptions) => {
|
||||
try {
|
||||
const ctx = resolveCommandContext(opts, { requireCompany: true });
|
||||
const url = method === "get" ? apiPath`/api/companies/${ctx.companyId}/accounting/invoices/${id}` : apiPath`/api/companies/${ctx.companyId}/accounting/events/${id}/adjustments`;
|
||||
const result = method === "get" ? await ctx.api.get(url) : await ctx.api.post(url, parseJson(opts.payloadJson));
|
||||
printOutput(result, { json: ctx.json });
|
||||
} catch (error) { handleCommandError(error); }
|
||||
}), { includeCompany: false });
|
||||
}
|
||||
|
||||
const finance = program.command("finance").description("Finance event and summary operations");
|
||||
addCompanyPostJson(finance, "event:create", "Record a finance event", "finance-events");
|
||||
addCompanyGet(finance, "events", "List finance events", "costs/finance-events");
|
||||
addCompanyGet(finance, "summary", "Get finance summary", "costs/finance-summary");
|
||||
addCompanyGet(finance, "by-biller", "Get finance summary by biller", "costs/finance-by-biller");
|
||||
addCompanyGet(finance, "by-kind", "Get finance summary by kind", "costs/finance-by-kind");
|
||||
addCompanyGet(finance, "events", "List finance events", "costs/finance-events", true);
|
||||
addCompanyGet(finance, "summary", "Get finance summary", "costs/finance-summary", true);
|
||||
addCompanyGet(finance, "by-biller", "Get finance summary by biller", "costs/finance-by-biller", true);
|
||||
addCompanyGet(finance, "by-kind", "Get finance summary by kind", "costs/finance-by-kind", true);
|
||||
|
||||
const budget = program.command("budget").description("Budget policy and incident operations");
|
||||
addCompanyGet(budget, "overview", "Get budget overview", "budgets/overview");
|
||||
@@ -123,16 +147,25 @@ export function registerCostCommands(program: Command): void {
|
||||
);
|
||||
}
|
||||
|
||||
function addCompanyGet(parent: Command, name: string, description: string, path: string): void {
|
||||
function addCompanyGet(parent: Command, name: string, description: string, path: string, dateRange = false): void {
|
||||
const command = parent.command(name).description(description).option("-C, --company-id <id>", "Company ID");
|
||||
if (dateRange) {
|
||||
command
|
||||
.option("--from <iso-date>", "Inclusive start date (default: UTC month start; unbounded with --to alone)")
|
||||
.option("--to <iso-date>", "Inclusive end timestamp (date-only values stop at 00:00 UTC that day)")
|
||||
.option("--all-time", "Report all recorded history");
|
||||
}
|
||||
addCommonClientOptions(
|
||||
parent
|
||||
.command(name)
|
||||
.description(description)
|
||||
.option("-C, --company-id <id>", "Company ID")
|
||||
.action(async (opts: CompanyOptions) => {
|
||||
command.action(async (opts: CompanyOptions) => {
|
||||
try {
|
||||
const ctx = resolveCommandContext(opts, { requireCompany: true });
|
||||
const result = await ctx.api.get(`${apiPath`/api/companies/${ctx.companyId}`}/${path}`);
|
||||
const params = new URLSearchParams();
|
||||
if (opts.allTime && (opts.from || opts.to)) throw new Error("--all-time cannot be combined with --from or --to");
|
||||
if (opts.allTime) params.set("period", "all");
|
||||
if (opts.from) params.set("from", opts.from);
|
||||
if (opts.to) params.set("to", opts.to);
|
||||
const suffix = params.size ? `?${params}` : "";
|
||||
const result = await ctx.api.get(`${apiPath`/api/companies/${ctx.companyId}`}/${path}${suffix}`);
|
||||
printOutput(result, { json: ctx.json });
|
||||
} catch (err) {
|
||||
handleCommandError(err);
|
||||
|
||||
Reference in new issue
Block a user