feat: expose user-readable expense types
This commit is contained in:
+119
-6
@@ -80,6 +80,9 @@ const XFT_MANAGED_SUBMISSION_FIELDS = new Set([
|
||||
const XFT_STANDARD_FORM_FIELD_NUMBERS = new Set(["billCompanyCode", "billDepartmentCode"]);
|
||||
const CITY_OPTIONS_TIMEOUT_MS = 45_000;
|
||||
const CITY_OPTIONS_CACHE_MS = 24 * 60 * 60 * 1000;
|
||||
const EXPENSE_TYPE_SOURCE_PAGE_SIZE = 100;
|
||||
const EXPENSE_TYPE_SOURCE_MAX_PAGES = 5;
|
||||
const EXPENSE_TYPE_HINT = /费用\s*(?:类型|类别|项目)|(?:类型|类别|项目)\s*费用|费目|expense[\s_-]*type/i;
|
||||
|
||||
/** Official XFT OpenAPI adapter. It never accepts an empId from an Agent. */
|
||||
export class XftOpenApiClient implements XftApprovalProvider {
|
||||
@@ -369,13 +372,13 @@ export class XftOpenApiClient implements XftApprovalProvider {
|
||||
limit = 50,
|
||||
) {
|
||||
const identity = await this.resolveIdentity(user);
|
||||
await this.requireSubmissionTemplate(identity, template);
|
||||
const current = await this.requireSubmissionTemplate(identity, template);
|
||||
let options: XftSubmissionOption[];
|
||||
let cacheHit = false;
|
||||
if (kind === "department") {
|
||||
const member = await this.requireCurrentMember(identity);
|
||||
options = extractDepartmentOptions(member);
|
||||
} else {
|
||||
} else if (kind === "city") {
|
||||
if (this.cityOptionsCache && Date.now() - this.cityOptionsCache.fetchedAt < CITY_OPTIONS_CACHE_MS) {
|
||||
options = this.cityOptionsCache.items;
|
||||
cacheHit = true;
|
||||
@@ -390,13 +393,21 @@ export class XftOpenApiClient implements XftApprovalProvider {
|
||||
options = extractCityOptions(cities);
|
||||
this.cityOptionsCache = { fetchedAt: Date.now(), items: options };
|
||||
}
|
||||
} else {
|
||||
options = await this.loadExpenseTypeOptions(identity, current);
|
||||
if (!options.length) {
|
||||
throw new ApprovalSafetyError("暂时无法实时获取可选费用类型,请稍后重试或在薪福通客户端完成");
|
||||
}
|
||||
}
|
||||
const filtered = query.trim()
|
||||
? options.filter((item) => `${item.label}\n${item.code}`.toLowerCase().includes(query.trim().toLowerCase()))
|
||||
: options;
|
||||
const boundedLimit = Math.min(100, Math.max(1, limit));
|
||||
return {
|
||||
kind,
|
||||
items: filtered.slice(0, Math.min(100, Math.max(1, limit))),
|
||||
items: filtered.slice(0, boundedLimit),
|
||||
total: filtered.length,
|
||||
hasMore: filtered.length > boundedLimit,
|
||||
diagnostics: {
|
||||
source: "xft_official_openapi",
|
||||
realtime: !cacheHit,
|
||||
@@ -407,6 +418,64 @@ export class XftOpenApiClient implements XftApprovalProvider {
|
||||
};
|
||||
}
|
||||
|
||||
private async loadExpenseTypeOptions(
|
||||
identity: XftIdentity,
|
||||
template: XftSubmissionTemplate,
|
||||
): Promise<XftSubmissionOption[]> {
|
||||
try {
|
||||
const rawFields = await this.request(
|
||||
`/itrip/xft-api/v1/form/customFields/eventSeqId/${encodeURIComponent(template.eventSeqId)}`,
|
||||
undefined,
|
||||
"GET",
|
||||
identity,
|
||||
);
|
||||
const embedded = extractExpenseTypeOptions(rawFields);
|
||||
if (embedded.length) return embedded;
|
||||
} catch {
|
||||
// Some templates do not expose standard expense dictionaries in custom fields.
|
||||
// Fall through to the enterprise multilevel data-source APIs.
|
||||
}
|
||||
|
||||
const candidates: Array<{ id: string; raw: JsonObject }> = [];
|
||||
for (let page = 0; page < EXPENSE_TYPE_SOURCE_MAX_PAGES; page += 1) {
|
||||
let response: unknown;
|
||||
try {
|
||||
response = await this.request(
|
||||
"/itrip/xft-api/v1/dataSource/findMultilevelSourcePage",
|
||||
{ start: page * EXPENSE_TYPE_SOURCE_PAGE_SIZE, limit: EXPENSE_TYPE_SOURCE_PAGE_SIZE },
|
||||
"POST",
|
||||
identity,
|
||||
);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const records = pagedRecords(response);
|
||||
for (const record of records) {
|
||||
const name = stringAt(record, ["sourceName", "dataSourceName", "multilevelSourceName", "displayName", "name", "title"]);
|
||||
const id = stringAt(record, ["sourceSeqId", "dataSourceSeqId", "multilevelSourceSeqId", "seqId", "id"]);
|
||||
if (id && name && EXPENSE_TYPE_HINT.test(name)) candidates.push({ id, raw: record });
|
||||
}
|
||||
if (records.length < EXPENSE_TYPE_SOURCE_PAGE_SIZE) break;
|
||||
}
|
||||
|
||||
const output: XftSubmissionOption[] = [];
|
||||
for (const candidate of candidates.slice(0, 10)) {
|
||||
output.push(...extractExpenseTypeOptions(candidate.raw, true));
|
||||
try {
|
||||
const detail = await this.request(
|
||||
`/itrip/xft-api/v1/dataSource/getMultiLevelDetail/${encodeURIComponent(candidate.id)}`,
|
||||
undefined,
|
||||
"GET",
|
||||
identity,
|
||||
);
|
||||
output.push(...extractExpenseTypeOptions(detail, true));
|
||||
} catch {
|
||||
// Continue with other matching sources. Empty output fails closed below.
|
||||
}
|
||||
}
|
||||
return uniqueOptions(output);
|
||||
}
|
||||
|
||||
async submitApproval(
|
||||
user: AuthenticatedDingTalkUser,
|
||||
template: XftSubmissionTemplate,
|
||||
@@ -1258,6 +1327,41 @@ function extractCityOptions(value: unknown): XftSubmissionOption[] {
|
||||
return uniqueOptions(candidates);
|
||||
}
|
||||
|
||||
function extractExpenseTypeOptions(value: unknown, trustedExpenseSource = false): XftSubmissionOption[] {
|
||||
const candidates: XftSubmissionOption[] = [];
|
||||
const visit = (current: unknown, path: string[], inheritedHint: boolean, depth: number): void => {
|
||||
if (depth > 12) return;
|
||||
if (Array.isArray(current)) {
|
||||
for (const item of current) visit(item, path, inheritedHint, depth + 1);
|
||||
return;
|
||||
}
|
||||
if (!isObject(current)) return;
|
||||
const record = current;
|
||||
const recordHint = EXPENSE_TYPE_HINT.test(stringAt(record, [
|
||||
"fieldName", "name", "label", "title", "sourceName", "dataSourceName", "multilevelSourceName",
|
||||
]) ?? "");
|
||||
const pathHint = path.some((part) => EXPENSE_TYPE_HINT.test(part));
|
||||
const inExpenseContext = trustedExpenseSource || inheritedHint || recordHint || pathHint;
|
||||
if (inExpenseContext && record.selectable !== false && record.canSelect !== false && record.disabled !== true) {
|
||||
const explicitCode = stringAt(record, [
|
||||
"expenseNumber", "expenseTypeNumber", "expTypeCode", "expenseTypeCode", "expenseTypeNo", "expTypeNo",
|
||||
]);
|
||||
const code = explicitCode ?? (path.length > 0 ? stringAt(record, [
|
||||
"optionCode", "optionNumber", "itemCode", "itemNumber", "nodeCode", "nodeNumber", "dataCode", "dataNumber",
|
||||
"sourceOptionCode", "sourceOptionNumber", "code", "number", "value", "key",
|
||||
]) : undefined);
|
||||
const label = stringAt(record, [
|
||||
"expenseName", "expenseTypeName", "expTypeName", "optionName", "itemName", "nodeName", "dataName",
|
||||
"sourceOptionName", "label", "text", "displayName", "name", "title",
|
||||
]);
|
||||
if (code && label) candidates.push({ code, label });
|
||||
}
|
||||
for (const [key, child] of Object.entries(record)) visit(child, [...path, key], inExpenseContext, depth + 1);
|
||||
};
|
||||
visit(value, [], trustedExpenseSource, 0);
|
||||
return uniqueOptions(candidates);
|
||||
}
|
||||
|
||||
function visitObjects(
|
||||
value: unknown,
|
||||
visitor: (record: JsonObject, path: string[]) => void,
|
||||
@@ -1420,10 +1524,19 @@ function normalizeSubmissionField(value: JsonObject): XftSubmissionField[] {
|
||||
...(typeof value.multiple === "boolean" ? { multiple: value.multiple } : {}),
|
||||
...(Array.isArray(value.options) ? { options: value.options.map((option) => sanitizeOption(option)).filter((option) => option !== undefined) } : {}),
|
||||
...(typeof value.moduleType === "string" && value.moduleType ? { moduleType: value.moduleType } : {}),
|
||||
...(isExpenseTypeField(fieldNumber, name) ? { optionSource: expenseTypeOptionSource() } : {}),
|
||||
...submissionFieldShape(value, type),
|
||||
}];
|
||||
}
|
||||
|
||||
function isExpenseTypeField(fieldNumber: string, name: string): boolean {
|
||||
return EXPENSE_TYPE_HINT.test(name) || /^(?:expenseNumber|expenseTypeNumber|expTypeCode)$/i.test(fieldNumber);
|
||||
}
|
||||
|
||||
function expenseTypeOptionSource() {
|
||||
return { tool: "approval_get_submission_options" as const, kind: "expense_type" as const };
|
||||
}
|
||||
|
||||
function submissionFieldShape(value: JsonObject, type: string): Pick<XftSubmissionField, "valueFormat" | "itemFields"> {
|
||||
const normalized = type.toUpperCase();
|
||||
if (normalized.includes("TABLE")) {
|
||||
@@ -1522,7 +1635,7 @@ function submissionInputContractSummary(kind: XftSubmissionKind): Record<string,
|
||||
function expenseApplicationFields(): Array<Record<string, unknown>> {
|
||||
return [{
|
||||
key: "applyExpenses", label: "事前申请费用列表", required: true, type: "array", minItems: 1, itemFields: [
|
||||
{ key: "expenseNumber", label: "费用类型编码", required: true, type: "string", description: "企业费用管理中定义的费用类型编码" },
|
||||
{ key: "expenseNumber", label: "费用类型", required: true, type: "string", description: "向用户展示可读名称,内部填写所选项的 code", optionSource: expenseTypeOptionSource() },
|
||||
{ key: "amount", label: "申请金额", required: true, type: "decimal", precision: 2 },
|
||||
{ key: "occurrenceDate", label: "费用发生时间", required: false, type: "datetime", description: "ISO 8601 时间" },
|
||||
{ key: "payCityCode", label: "消费城市编码", required: false, type: "string" },
|
||||
@@ -1560,7 +1673,7 @@ function travelApplicationFields(): Array<Record<string, unknown>> {
|
||||
{ key: "endTimePrecision", label: "结束时间半天精度", required: false, type: "string", enum: ["AM", "PM"] },
|
||||
{ key: "customArchiveOptionNumbers", label: "行程自定义档案选项", required: false, type: "array" },
|
||||
{ key: "estimateExpenses", label: "预计费用", required: false, type: "array", itemFields: [
|
||||
{ key: "expenseTypeNumber", label: "费用类型编码", required: true, type: "string" },
|
||||
{ key: "expenseTypeNumber", label: "费用类型", required: true, type: "string", description: "向用户展示可读名称,内部填写所选项的 code", optionSource: expenseTypeOptionSource() },
|
||||
{ key: "applyAmount", label: "申请金额", required: true, type: "decimal" },
|
||||
{ key: "remark", label: "备注", required: false, type: "string" },
|
||||
{ key: "spreadInfo", label: "分摊信息", required: false, type: "object" },
|
||||
@@ -1622,7 +1735,7 @@ function travelReimbursementFields(): Array<Record<string, unknown>> {
|
||||
|
||||
function expenseListField(travel: boolean): Record<string, unknown> {
|
||||
const itemFields: Array<Record<string, unknown>> = [
|
||||
{ key: "expTypeCode", label: "费用类型编码", required: true, type: "string", maxLength: 100, description: "企业费用管理中定义的费用类型编码" },
|
||||
{ key: "expTypeCode", label: "费用类型", required: true, type: "string", maxLength: 100, description: "向用户展示可读名称,内部填写所选项的 code", optionSource: expenseTypeOptionSource() },
|
||||
{ key: "currencyCode", label: "费用币种", required: true, type: "string", enum: ["CNY"] },
|
||||
{ key: "originalCurrencyReimAmt", label: "费用金额", required: true, type: "decimal", precision: 2 },
|
||||
{ key: "wrTim", label: "消费日期", required: false, type: "date", format: "yyyy-MM-dd" },
|
||||
|
||||
Reference in New Issue
Block a user