Add expense store lookup by document number
This commit is contained in:
1 parent
4b3a899e5a
commit
b21d92efae
19 files changed
+658
-51
No files matched your search
@@ -1,9 +1,6 @@
|
||||
import { usageError } from "../../core/errors.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import type { createSealClient } from "../../core/http/factory.js";
|
||||
import { runCapability } from "../helpers.js";
|
||||
import { numberOption, stringOption } from "../parser.js";
|
||||
import { outputOptions } from "../printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
|
||||
export async function handleDataCommand(
|
||||
@@ -12,16 +9,9 @@ export async function handleDataCommand(
|
||||
corp: CorpConfig,
|
||||
args: ParsedArgs
|
||||
) {
|
||||
const params = {
|
||||
offset: numberOption(args.options.offset),
|
||||
limit: numberOption(args.options.limit),
|
||||
startDate: stringOption(args.options.startDate) ?? stringOption(args.options["start-date"]),
|
||||
endDate: stringOption(args.options.endDate) ?? stringOption(args.options["end-date"]),
|
||||
search: stringOption(args.options.search) ?? stringOption(args.options.query)
|
||||
};
|
||||
|
||||
if (action === "expenses" || action === "expense") {
|
||||
await runCapability("sealExpensesList", client, corp, params, outputOptions(args.options));
|
||||
const { handleExpensesCommand } = await import("./expenses.js");
|
||||
await handleExpensesCommand(args.command[2], client, corp, args);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test"
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import { runCli } from "../runner.js"
|
||||
|
||||
const envKeys = ["SEAL_USE_CONFIG_FILE", "SEAL_USE_ENTERPRISES_DIR", "SEAL_USE_TOKEN_STORE", "SEAL_USE_USAGE_FILE"] as const
|
||||
const oldEnv = Object.fromEntries(envKeys.map(key => [key, process.env[key]]))
|
||||
const oldFetch = globalThis.fetch
|
||||
let dir: string
|
||||
let requests: Array<{ method: string; path: string; query: URLSearchParams }>
|
||||
let approvalSN: string
|
||||
let expenseCount: number
|
||||
let failureStatus: number | undefined
|
||||
let description: string
|
||||
const sn = "SN-CLI-FIXTURE"
|
||||
|
||||
beforeEach(() => {
|
||||
dir = mkdtempSync(join(tmpdir(), "seal-expense-cli-"))
|
||||
const enterprises = join(dir, "enterprises")
|
||||
mkdirSync(enterprises)
|
||||
process.env.SEAL_USE_CONFIG_FILE = join(dir, "config.json")
|
||||
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises
|
||||
process.env.SEAL_USE_TOKEN_STORE = join(dir, "tokens.json")
|
||||
process.env.SEAL_USE_USAGE_FILE = join(dir, "usage.json")
|
||||
writeFileSync(join(enterprises, "expense-cli-test.json"), JSON.stringify({
|
||||
id: "expense-cli-test", name: "Expense Test", environment: "test", seal: { url: "https://expense.example.test" },
|
||||
source: { type: "seal", token: "test-token", sealUrl: "https://expense.example.test", staffId: "fixture" }
|
||||
}))
|
||||
requests = []
|
||||
approvalSN = sn
|
||||
expenseCount = 2
|
||||
failureStatus = undefined
|
||||
description = "Fixture only"
|
||||
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const request = new Request(input, init)
|
||||
const url = new URL(request.url)
|
||||
requests.push({ method: request.method, path: url.pathname, query: url.searchParams })
|
||||
if (request.method !== "GET") throw new Error("Unexpected mutation")
|
||||
if (url.pathname === "/api/v1/approvals") return Response.json({ data: { records: [{ id: "record-1", sourceDocumentSN: approvalSN, sourceDocumentId: "source-1", documentId: "document-1" }], total: 1 } })
|
||||
if (failureStatus) return Response.json({ error: { message: "fixture failure" } }, { status: failureStatus })
|
||||
if (!url.searchParams.has("filter[search]") && !url.searchParams.has("filter[recordId]")) return Response.json({ error: "filter required" }, { status: 400 })
|
||||
const offset = Number(url.searchParams.get("offset"))
|
||||
const limit = Number(url.searchParams.get("limit"))
|
||||
const expenses = Array.from({ length: expenseCount }, (_, i) => ({ id: `expense-${i}`, recordId: "record-1", documentId: "document-1", type: "fixture", amount: i + 1, currency: "CNY", description, user: { mobile: "private-fixture" } }))
|
||||
return Response.json({ data: { expenses: expenses.slice(offset, offset + limit), total: expenses.length } })
|
||||
}) as typeof fetch
|
||||
})
|
||||
afterEach(() => {
|
||||
for (const key of envKeys) {
|
||||
if (oldEnv[key] === undefined) delete process.env[key]
|
||||
else process.env[key] = oldEnv[key]
|
||||
}
|
||||
globalThis.fetch = oldFetch
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
})
|
||||
function cli(...argv: string[]) { return runCli([...argv, "--corp", "expense-cli-test"]) }
|
||||
|
||||
describe("expense document lookup CLI", () => {
|
||||
test("canonical, singular, list and data entrances all execute the same read-only lookup", async () => {
|
||||
for (const prefix of [["expenses"], ["expense"], ["expenses", "list"], ["data", "expenses"], ["data", "expense", "list"]]) {
|
||||
const result = await cli(...prefix, "--sn", sn, "--limit", "1")
|
||||
expect(result.exitCode).toBe(0)
|
||||
expect(JSON.parse(result.stdout)).toMatchObject({ status: "found", found: true, complete: true, matchedCount: 2 })
|
||||
expect(result.stdout).not.toContain("private-fixture")
|
||||
}
|
||||
expect(requests.every(request => request.method === "GET")).toBe(true)
|
||||
expect(requests.filter(request => request.path.includes("expenses")).every(request => request.query.get("filter[recordId]") === "record-1")).toBe(true)
|
||||
})
|
||||
|
||||
test("raw list behavior stays compatible while bare list and record filters get a required filter object", async () => {
|
||||
const raw = await cli("expenses", "list")
|
||||
expect(raw.exitCode).toBe(0)
|
||||
expect(JSON.parse(raw.stdout)).toHaveProperty("expenses")
|
||||
expect(requests[0]?.query.get("filter[search]")).toBe("")
|
||||
expect(requests[0]?.query.has("filter[startDate]")).toBe(false)
|
||||
const byRecord = await cli("data", "expenses", "--record-id", "record-1")
|
||||
expect(byRecord.exitCode).toBe(0)
|
||||
expect(requests[1]?.query.get("filter[recordId]")).toBe("record-1")
|
||||
await cli("expenses", "--search", "交通", "--offset", "2")
|
||||
expect(requests[2]?.query.get("filter[search]")).toBe("交通")
|
||||
expect(requests[2]?.query.get("offset")).toBe("2")
|
||||
})
|
||||
|
||||
test("absence and unresolved linking have different JSON conclusions", async () => {
|
||||
expenseCount = 0
|
||||
expect(JSON.parse((await cli("expenses", "--sn", sn)).stdout)).toMatchObject({ status: "not_found", found: false, complete: true })
|
||||
approvalSN = `${sn}-UNRELATED`
|
||||
expect(JSON.parse((await cli("expenses", "--sn", sn)).stdout)).toMatchObject({ status: "unknown", found: null, complete: false, reason: "approval_link_not_found" })
|
||||
})
|
||||
|
||||
test("limits are explicit and partial scans cannot return not_found", async () => {
|
||||
const result = await cli("expenses", "--sn", sn, "--max-scan", "1")
|
||||
expect(result.exitCode).toBe(0)
|
||||
expect(JSON.parse(result.stdout)).toMatchObject({ status: "found", complete: false, reason: "scan_limit", matchedCount: 1 })
|
||||
})
|
||||
|
||||
test("bad selector combinations, unknown verbs and invalid scan budgets fail before requests", async () => {
|
||||
for (const argv of [
|
||||
["expenses", "delete"], ["expenses", "SN-as-unsupported-positional"], ["expenses", "list", sn], ["data", "expenses", "list", sn],
|
||||
["expenses", "--sn", sn, "--search", "text"], ["expenses", "--sn", sn, "--record-id", "record-1"],
|
||||
["expenses", "--sn", sn, "--offset", "0"], ["expenses", "--max-scan", "1"]
|
||||
]) expect((await cli(...argv)).exitCode).toBe(2)
|
||||
expect((await cli("expenses", "--sn", sn, "--max-scan", "0")).exitCode).toBe(13)
|
||||
expect(requests).toHaveLength(0)
|
||||
})
|
||||
|
||||
test("expense lookup failures retain JSON uncertainty and correct exit codes", async () => {
|
||||
for (const status of [400, 403]) {
|
||||
failureStatus = status
|
||||
const result = await cli("expenses", "--sn", sn)
|
||||
expect(result.exitCode).toBe(status === 403 ? 11 : 1)
|
||||
expect(JSON.parse(result.stdout)).toMatchObject({ status: "unknown", complete: false, found: null })
|
||||
expect(result.stderr).toContain("incomplete")
|
||||
}
|
||||
})
|
||||
|
||||
test("oversized reports retain existing output protection and can be exported as JSON", async () => {
|
||||
description = "x".repeat(210000)
|
||||
expect((await cli("expenses", "--sn", sn)).exitCode).toBe(12)
|
||||
const path = join(dir, "report.json")
|
||||
const result = await cli("expenses", "--sn", sn, "--output-file", path)
|
||||
expect(result.exitCode).toBe(0)
|
||||
expect(JSON.parse(result.stdout)).toMatchObject({ outputFile: path })
|
||||
expect(JSON.parse(readFileSync(path, "utf8"))).toMatchObject({ status: "found", complete: true, matchedCount: 2 })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,33 @@
|
||||
import type { CorpConfig } from "../../core/config/types.js"
|
||||
import type { createSealClient } from "../../core/http/factory.js"
|
||||
import { usageError } from "../../core/errors.js"
|
||||
import { ExpenseLookupError } from "../../domains/seal/expenses/lookup.js"
|
||||
import { runCapabilityResult } from "../helpers.js"
|
||||
import { numberOption, stringOption } from "../parser.js"
|
||||
import { outputOptions, printJson } from "../printer.js"
|
||||
import type { ParsedArgs } from "../types.js"
|
||||
|
||||
export async function handleExpensesCommand(action: string | undefined, client: Awaited<ReturnType<typeof createSealClient>>, corp: CorpConfig, args: ParsedArgs) {
|
||||
const prefixLength = args.command[0]?.toLowerCase() === "data" ? 2 : 1
|
||||
if ((action && action !== "list") || args.command.length > prefixLength + Number(Boolean(action))) {
|
||||
throw usageError("Usage: seal-use expenses [list] [--sn <documentSN>|--record-id <recordId>|--search <text>]")
|
||||
}
|
||||
const sn = stringOption(args.options.sn)
|
||||
const recordId = stringOption(args.options["record-id"]) ?? stringOption(args.options.recordId)
|
||||
const search = stringOption(args.options.search) ?? stringOption(args.options.query)
|
||||
const offset = numberOption(args.options.offset)
|
||||
const maxScan = numberOption(args.options["max-scan"]) ?? numberOption(args.options.maxScan)
|
||||
if (sn !== undefined && (recordId !== undefined || search !== undefined || offset !== undefined)) throw usageError("--sn cannot be combined with --search, --record-id, or --offset")
|
||||
if (maxScan !== undefined && sn === undefined) throw usageError("--max-scan requires --sn")
|
||||
try {
|
||||
const result = await runCapabilityResult("sealExpensesList", client, corp, {
|
||||
sn, recordId, search, offset, maxScan, limit: numberOption(args.options.limit),
|
||||
startDate: stringOption(args.options.startDate) ?? stringOption(args.options["start-date"]),
|
||||
endDate: stringOption(args.options.endDate) ?? stringOption(args.options["end-date"])
|
||||
})
|
||||
printJson(result, outputOptions(args.options))
|
||||
} catch (error) {
|
||||
if (error instanceof ExpenseLookupError) printJson(error.report, outputOptions(args.options))
|
||||
throw error
|
||||
}
|
||||
}
|
||||
+5
-5
@@ -1169,8 +1169,8 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
commands: [
|
||||
{
|
||||
name: "expenses",
|
||||
summary: "Search raw expense items (also available as 'seal-use expenses')",
|
||||
usage: ["seal-use data expenses [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--corp <corpId>]"]
|
||||
summary: "List expenses, or verify expense-store membership by exact document number with --sn",
|
||||
usage: ["seal-use data expenses [--sn <documentSN>|--record-id <recordId>|--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--max-scan <n>] [--corp <corpId>]"]
|
||||
},
|
||||
{
|
||||
name: "invoices",
|
||||
@@ -1204,13 +1204,13 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
{
|
||||
area: "expenses",
|
||||
title: "费用明细查询",
|
||||
description: "查询历史费用明细记录。",
|
||||
description: "查询历史费用明细;--sn 按单号关联审批记录并核验费用库存在性,区分找到、关联范围内未找到和无法确定。",
|
||||
commands: [
|
||||
{
|
||||
name: "list",
|
||||
summary: "分页查询费用明细",
|
||||
summary: "普通查询分页返回原始记录;--sn 自动翻页核验,--limit 为页大小,--max-scan 默认为 5000",
|
||||
usage: [
|
||||
"seal-use expenses [list] [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--corp <corpId>]"
|
||||
"seal-use expenses [list] [--sn <documentSN>|--record-id <recordId>|--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--max-scan <n>] [--corp <corpId>]"
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
+1
-1
@@ -59,7 +59,7 @@ export const VALUE_FLAGS = new Set([
|
||||
"json", "json-path", "key-id", "keyId", "keyword", "ledger", "level", "limit",
|
||||
"lines", "link", "linter", "manual-status", "manualApprovalStatus", "manualStatus",
|
||||
"max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "message-id", "messageId", "metadata", "metadata-key", "min-score", "minScore", "mode",
|
||||
"max-runs",
|
||||
"max-runs", "max-scan", "maxScan",
|
||||
"month",
|
||||
"n", "name", "name-contains", "node-id", "nodeId", "note", "observation-id", "observation-types", "o", "offset", "out",
|
||||
"out-dir", "outDir", "outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file",
|
||||
|
||||
@@ -27,7 +27,8 @@ describe("CLI read-only classification", () => {
|
||||
"auth test",
|
||||
"auth doctor",
|
||||
"auth seal-link list",
|
||||
"doctor auth"
|
||||
"doctor auth",
|
||||
"expenses "
|
||||
]);
|
||||
|
||||
test("every allow-listed command exists in the help registry", () => {
|
||||
@@ -55,6 +56,10 @@ describe("CLI read-only classification", () => {
|
||||
["corp", "list"],
|
||||
["corp", "get", "corp-a"],
|
||||
["documents", "list", "--corp", "corp-a"],
|
||||
["expenses", "--sn", "SN-FIXTURE", "--corp", "corp-a"],
|
||||
["expenses", "list", "--record-id", "run-1", "--corp", "corp-a"],
|
||||
["expense", "--sn", "SN-FIXTURE", "--corp", "corp-a"],
|
||||
["data", "expenses", "--sn", "SN-FIXTURE", "--corp", "corp-a"],
|
||||
["documents", "get", "doc-1", "--corp", "corp-a"],
|
||||
["documents", "search", "差旅", "--corp", "corp-a"],
|
||||
["approval-runs", "get", "01a09dac-c688-767b-8eb4-37b945095585"],
|
||||
|
||||
@@ -70,6 +70,7 @@ const READ_ONLY_COMMANDS: Record<string, string[]> = {
|
||||
users: ["search", "get"],
|
||||
contacts: ["departments", "children", "users", "sync-time"],
|
||||
data: ["expenses", "invoices"],
|
||||
expenses: ["", "list"],
|
||||
llm: ["config", "providers"],
|
||||
permissions: ["available", "configs"],
|
||||
billing: ["status", "plans", "features"],
|
||||
|
||||
+1
-1
@@ -66,7 +66,7 @@ const CLIENT_COMMANDS: Record<string, ClientCommand> = {
|
||||
"contacts": async (args, corp, client) => (await import("./commands/contacts.js")).handleContactsCommand(args.command[1], args.command[2], client, corp, args),
|
||||
"data": async (args, corp, client) => (await import("./commands/data.js")).handleDataCommand(args.command[1], client, corp, args),
|
||||
"invoices": async (args, corp, client) => (await import("./commands/invoices.js")).handleInvoicesCommand(args.command[1], args.command[2], client, corp, args),
|
||||
"expenses": async (args, corp, client) => (await import("./commands/data.js")).handleDataCommand("expenses", client, corp, args),
|
||||
"expenses": async (args, corp, client) => (await import("./commands/expenses.js")).handleExpensesCommand(args.command[1], client, corp, args),
|
||||
"llm": async (args, corp, client) => (await import("./commands/llm.js")).handleLlmCommand(args.command[1], client, corp, args),
|
||||
"permissions": async (args, corp, client) => (await import("./commands/permissions.js")).handlePermissionsCommand(args.command[1], client, corp, args),
|
||||
"billing": async (args, corp, client) => (await import("./commands/billing.js")).handleBillingCommand(args.command[1], client, corp, args),
|
||||
|
||||
Reference in new issue
Block a user