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
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user