Files
SupplierSystem/miniprogram/components/cost-management-panel/index.js
T
Ubuntu deb3e72750
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
chore: 以 AI 生鲜配送系统 当前版本作为 SupplierSystem 起点
来源仓库:jxc/ai-fresh-delivery
来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d
快照树:  09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件)

按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据
(生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、
deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值),
整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。
供应商系统后续开发自本提交开始。
2026-10-08 17:35:43 +08:00

950 lines
32 KiB
JavaScript

const {
fetchFreeCostTypes,
fetchFreeCostSettings,
addFreeCostType,
fetchFreeCostEntries,
createFreeCostEntry,
extractFreeCostVoucherAmount,
uploadFreeCostVoucher,
extractFreeCostInvoice,
saveFreeCostInvoice,
uploadFreeCostInvoice,
} = require('../../utils/request');
const { compressOrderImage, readFileAsBase64 } = require('../../utils/orderImage');
const { beginPanelShow, endPanelShow } = require('../../utils/panelShowGate');
const {
PERIOD_OPTIONS,
HISTORY_PAGE_SIZE,
resolvePeriodRange,
dateRangeToCycleCode,
formatMoney,
formatDateTime,
resolveFreeCostRemarkText,
statusMeta,
suggestedGroupKey,
validateFreeCostGroup,
expandFreeCostGroupToEntries,
normalizeDocumentKind,
MAX_VOUCHERS,
CHOOSE_MAX,
} = require('../../utils/costManagement');
const config = require('../../config');
/** 相对 /api/storage 签名路径 → 小程序可加载的绝对地址 */
function absolutizeMediaUrl(url) {
const raw = String(url || '').trim();
if (!raw) return '';
if (/^https?:\/\//i.test(raw)) return raw;
const apiBase = String(config.apiBase || '').replace(/\/+$/, '');
const origin = apiBase.replace(/\/api$/i, '');
if (raw.startsWith('/')) return `${origin}${raw}`;
return `${apiBase}/${raw.replace(/^\/+/, '')}`;
}
function voucherCaption(item) {
if (!item) return '';
if (item.aiStatus === 'extracting') return '识别中';
if (item.aiStatus === 'ok' && Number(item.amount) > 0) return `¥${formatMoney(item.amount)}`;
if (item.aiStatus === 'ok' || item.aiStatus === 'fail') return '未识别';
return '';
}
function sumVoucherAmounts(vouchers) {
return (vouchers || []).reduce((acc, item) => acc + (Number(item.amount) || 0), 0);
}
function findTypeIndex(types, code) {
const idx = (types || []).findIndex((item) => item.code === code);
return Math.max(0, idx);
}
Component({
options: { addGlobalClass: true },
data: {
tab: 'add',
periodKey: 'today',
periodOptions: PERIOD_OPTIONS,
types: [],
typeLabels: [],
groups: [],
voucherCount: 0,
maxVouchers: MAX_VOUCHERS,
requireVoucher: true,
submitting: false,
loading: false,
addingType: false,
showAddType: false,
showTypePicker: false,
typePickerIndex: 0,
typePickerGroupKey: '',
newTypeName: '',
addTypeGroupKey: '',
error: '',
historyRows: [],
historyPage: 1,
historyTotal: 0,
historyPageCount: 1,
postedAmountText: '0.00',
rejectedAmountText: '0.00',
canHistoryPrev: false,
canHistoryNext: false,
invoiceBusy: false,
showInvoiceSheet: false,
invoicePath: '',
invoiceOcr: null,
invoiceOcrText: '',
invoiceCandidates: [],
invoiceSubmitting: false,
},
lifetimes: {
attached() {
this.onPanelShow();
},
},
methods: {
async onPanelShow() {
if (!beginPanelShow(this)) return;
try {
if (this.data.tab === 'history') {
await this.loadHistory();
} else {
await this.loadFormMeta();
}
} finally {
endPanelShow(this);
}
},
applyTypes(types, preferredCode) {
const list = Array.isArray(types) ? types : [];
const labels = list.map((item) => item.label || item.code);
this.setData({
types: list,
typeLabels: labels,
});
if (preferredCode) {
// keep preferred for create-type flow; groups update separately
}
},
recountVouchers(groups) {
return (groups || []).reduce((acc, g) => acc + ((g.vouchers && g.vouchers.length) || 0), 0);
},
setGroups(groups) {
const next = (groups || []).filter((g) => (g.vouchers || []).length > 0);
this.setData({
groups: next,
voucherCount: this.recountVouchers(next),
});
},
findGroupIndex(groupKey, groups) {
const list = groups || this.data.groups || [];
return list.findIndex((g) => g.groupKey === groupKey);
},
buildMatchedGroup(subtype, subtypeLabel, types) {
return {
groupKey: subtype,
matched: true,
subtype,
subtypeLabel: subtypeLabel || subtype,
suggestedLabel: '',
typeIndex: findTypeIndex(types, subtype),
amount: '0.00',
remark: '',
vouchers: [],
unmatchedHint: '',
};
},
buildUnmatchedGroup(suggestedLabel) {
const label = String(suggestedLabel || '未知类型').trim() || '未知类型';
return {
groupKey: suggestedGroupKey(label),
matched: false,
subtype: '',
subtypeLabel: label,
suggestedLabel: label,
typeIndex: 0,
amount: '0.00',
remark: '',
vouchers: [],
unmatchedHint: `「${label}」不在现有类型中`,
};
},
refreshGroupAmount(group, preferKeepManual) {
if (preferKeepManual && group._amountTouched) {
return group;
}
const sum = sumVoucherAmounts(group.vouchers);
return { ...group, amount: formatMoney(sum) };
},
mergeVoucherIntoGroups(groups, voucher, meta, types) {
let list = (groups || []).map((g) => ({ ...g, vouchers: [...(g.vouchers || [])] }));
let groupKey;
let group;
if (meta.matched && meta.subtype) {
groupKey = meta.subtype;
let idx = list.findIndex((g) => g.groupKey === groupKey && g.matched);
if (idx < 0) {
group = this.buildMatchedGroup(meta.subtype, meta.subtypeLabel, types);
list.push(group);
idx = list.length - 1;
}
list[idx].vouchers.push(voucher);
list[idx] = this.refreshGroupAmount(list[idx], true);
} else {
const suggested = meta.suggestedLabel || '未知类型';
groupKey = suggestedGroupKey(suggested);
let idx = list.findIndex((g) => g.groupKey === groupKey);
if (idx < 0) {
group = this.buildUnmatchedGroup(suggested);
list.push(group);
idx = list.length - 1;
}
list[idx].vouchers.push(voucher);
list[idx] = this.refreshGroupAmount(list[idx], true);
}
return list;
},
moveVouchersToSubtype(groups, fromGroupKey, subtype, subtypeLabel, types) {
const list = (groups || []).map((g) => ({ ...g, vouchers: [...(g.vouchers || [])] }));
const fromIdx = list.findIndex((g) => g.groupKey === fromGroupKey);
if (fromIdx < 0) return list;
const moving = list[fromIdx].vouchers.slice();
list.splice(fromIdx, 1);
let targetIdx = list.findIndex((g) => g.matched && g.subtype === subtype);
if (targetIdx < 0) {
list.push(this.buildMatchedGroup(subtype, subtypeLabel, types));
targetIdx = list.length - 1;
}
list[targetIdx].vouchers = list[targetIdx].vouchers.concat(moving);
list[targetIdx] = this.refreshGroupAmount(list[targetIdx], false);
list[targetIdx]._amountTouched = false;
return list.filter((g) => (g.vouchers || []).length > 0);
},
async loadFormMeta() {
try {
const [typesResult, settingsResult] = await Promise.all([
fetchFreeCostTypes(),
fetchFreeCostSettings().catch(() => ({ data: null })),
]);
const settings = settingsResult && settingsResult.data ? settingsResult.data : {};
const requireVoucher = settings.require_voucher !== false;
this.setData({ requireVoucher });
this.applyTypes(typesResult.data || []);
} catch (err) {
this.setData({ error: err.message || '加载类型失败' });
}
},
async loadTypes() {
await this.loadFormMeta();
},
onTabAdd() {
this.setData({ tab: 'add', error: '' });
},
onTabHistory() {
this.setData({ tab: 'history', error: '', historyPage: 1 }, () => this.loadHistory(1));
},
onPeriodTap(e) {
const key = e.currentTarget.dataset.key;
this.setData({ periodKey: key, historyPage: 1 }, () => this.loadHistory(1));
},
onHistoryPrev() {
if (!this.data.canHistoryPrev) return;
const page = Math.max(1, this.data.historyPage - 1);
this.setData({ historyPage: page }, () => this.loadHistory(page));
},
onHistoryNext() {
if (!this.data.canHistoryNext) return;
const page = this.data.historyPage + 1;
this.setData({ historyPage: page }, () => this.loadHistory(page));
},
openTypePicker(e) {
const groupKey = e.currentTarget.dataset.groupKey;
const group = (this.data.groups || []).find((g) => g.groupKey === groupKey);
if (!group) return;
this.setData({
showTypePicker: true,
typePickerGroupKey: groupKey,
typePickerIndex: Number(group.typeIndex) || 0,
});
},
closeTypePicker() {
if (this.data.addingType) return;
this.setData({ showTypePicker: false, typePickerGroupKey: '' });
},
onTypePickerItemTap(e) {
this.setData({ typePickerIndex: Number(e.currentTarget.dataset.index) || 0 });
},
confirmTypePicker() {
const groupKey = this.data.typePickerGroupKey;
const typeIndex = Number(this.data.typePickerIndex);
this.setData({ showTypePicker: false, typePickerGroupKey: '' });
if (!groupKey) return;
const type = this.data.types[typeIndex];
if (!type) return;
this.applyPickedType(groupKey, typeIndex, type);
},
openAddTypeFromPicker() {
const groupKey = this.data.typePickerGroupKey || '';
this.setData({
showTypePicker: false,
showAddType: true,
newTypeName: '',
addTypeGroupKey: groupKey,
});
},
closeAddType() {
if (this.data.addingType) return;
this.setData({ showAddType: false, newTypeName: '', addTypeGroupKey: '' });
},
onNewTypeInput(e) {
this.setData({ newTypeName: e.detail.value });
},
confirmCreateSuggested(e) {
const groupKey = e.currentTarget.dataset.groupKey;
const group = (this.data.groups || []).find((g) => g.groupKey === groupKey);
if (!group) return;
this.setData({
showAddType: true,
newTypeName: group.suggestedLabel || '',
addTypeGroupKey: groupKey,
});
},
async confirmAddType() {
const label = String(this.data.newTypeName || '').trim();
if (!label) {
wx.showToast({ title: '请填写类型名称', icon: 'none' });
return;
}
if (this.data.addingType) return;
this.setData({ addingType: true });
try {
const result = await addFreeCostType(label);
const types = result.data || [];
const created = types.find((item) => item.label === label) || types[types.length - 1];
const groupKey = this.data.addTypeGroupKey;
const prevGroups = this.data.groups;
this.applyTypes(types);
this.setData({ showAddType: false, newTypeName: '', addingType: false, addTypeGroupKey: '', error: '' });
if (groupKey && created && created.code) {
this.setGroups(
this.moveVouchersToSubtype(
prevGroups,
groupKey,
created.code,
created.label || created.code,
types
)
);
}
wx.showToast({ title: '已新增类型', icon: 'success' });
} catch (err) {
this.setData({ addingType: false });
wx.showToast({ title: err.message || '新增失败', icon: 'none' });
}
},
applyPickedType(groupKey, typeIndex, type) {
const group = (this.data.groups || []).find((g) => g.groupKey === groupKey);
if (!group || !type) return;
if (group.matched && group.subtype === type.code) {
const groups = (this.data.groups || []).map((g) =>
g.groupKey === groupKey ? { ...g, typeIndex } : g
);
this.setGroups(groups);
return;
}
this.setGroups(
this.moveVouchersToSubtype(
this.data.groups,
groupKey,
type.code,
type.label || type.code,
this.data.types
)
);
},
onGroupAmountInput(e) {
const groupKey = e.currentTarget.dataset.groupKey;
const groups = (this.data.groups || []).map((g) => {
if (g.groupKey !== groupKey) return g;
return { ...g, amount: e.detail.value, _amountTouched: true };
});
this.setGroups(groups);
},
onGroupRemarkInput(e) {
const groupKey = e.currentTarget.dataset.groupKey;
const groups = (this.data.groups || []).map((g) =>
g.groupKey === groupKey ? { ...g, remark: e.detail.value } : g
);
this.setGroups(groups);
},
noop() {},
patchVoucherAi(id, patch) {
const groups = (this.data.groups || []).map((g) => {
const vouchers = (g.vouchers || []).map((item) => {
if (item.id !== id) return item;
const next = { ...item, ...patch };
next.amountCaption = voucherCaption(next);
return next;
});
const changed = vouchers.some((v, i) => v !== g.vouchers[i]);
if (!changed) return g;
let group = { ...g, vouchers };
if (!g._amountTouched) {
group = this.refreshGroupAmount(group, false);
}
return group;
});
this.setGroups(groups);
},
/** 识别完成后:从暂存组移到按类型分组 */
relocateVoucherAfterAi(id, meta) {
if (this._extractGen && this._extractGen[id] === 'skipped') return;
let voucher = null;
let groups = (this.data.groups || []).map((g) => ({
...g,
vouchers: [...(g.vouchers || [])],
}));
for (const g of groups) {
const idx = g.vouchers.findIndex((v) => v.id === id);
if (idx >= 0) {
voucher = { ...g.vouchers[idx] };
g.vouchers.splice(idx, 1);
break;
}
}
if (!voucher) return;
groups = groups.filter((g) => (g.vouchers || []).length > 0);
voucher.amount = Number(meta.amount) || 0;
voucher.aiStatus = voucher.amount > 0 ? 'ok' : 'fail';
voucher.amountCaption = voucherCaption(voucher);
voucher.matched = !!meta.matched;
voucher.subtype = meta.subtype || '';
voucher.suggestedLabel = meta.suggestedLabel || '';
if (!voucher.kindTouched) {
voucher.document_kind = normalizeDocumentKind(meta.documentKind);
}
groups = this.mergeVoucherIntoGroups(groups, voucher, meta, this.data.types);
this.setGroups(groups);
},
bumpExtractGen(id) {
if (!this._extractGen) this._extractGen = {};
const token = `${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
this._extractGen[id] = token;
return token;
},
isExtractCurrent(id, token) {
return this._extractGen && this._extractGen[id] === token;
},
isPayloadTooLarge(err) {
const code = Number(err && err.statusCode) || 0;
const msg = String((err && err.message) || '');
return code === 413 || /entity too large|payload too large|request entity|2mb/i.test(msg);
},
async extractVoucherAmount(id, { path: voucherPath, imageBase64 }) {
const token = this.bumpExtractGen(id);
this.patchVoucherAi(id, { aiStatus: 'extracting', amount: 0 });
try {
if (!imageBase64 && !voucherPath) {
throw new Error('缺少凭证图片');
}
let result;
try {
result = imageBase64
? await extractFreeCostVoucherAmount({ image_base64: imageBase64 })
: await extractFreeCostVoucherAmount({ voucher_path: voucherPath });
} catch (firstErr) {
if (imageBase64 && voucherPath && this.isPayloadTooLarge(firstErr)) {
result = await extractFreeCostVoucherAmount({ voucher_path: voucherPath });
} else {
throw firstErr;
}
}
if (!this.isExtractCurrent(id, token)) return;
const data = result && result.data ? result.data : {};
const amount = Number(data.amount) || 0;
const matched = !!data.matched;
const subtype = String(data.subtype || '').trim();
const subtypeLabel = String(data.subtype_label || '').trim();
const suggestedLabel = String(data.suggested_label || '').trim();
if (!amount && !matched) {
wx.showToast({ title: '未识别到金额,请手填', icon: 'none' });
}
this.relocateVoucherAfterAi(id, {
amount,
matched: matched && !!subtype,
subtype,
subtypeLabel,
suggestedLabel: suggestedLabel || subtypeLabel || '未识别类型',
documentKind: data.document_kind,
});
} catch (err) {
if (!this.isExtractCurrent(id, token)) return;
const msg = (err && err.message) || '识别失败,请手填';
wx.showToast({ title: msg.length > 20 ? '识别失败,请手填金额' : msg, icon: 'none' });
this.relocateVoucherAfterAi(id, {
amount: 0,
matched: false,
subtype: '',
subtypeLabel: '',
suggestedLabel: '未识别类型',
documentKind: 'voucher',
});
}
},
/** 跳过 AI:把识别中组改为可手填的未匹配组 */
skipPendingAi() {
const pending = (this.data.groups || []).find((g) => g.isPending);
if (!pending || !(pending.vouchers || []).length) return;
if (!this._extractGen) this._extractGen = {};
const moving = (pending.vouchers || []).map((v) => {
this._extractGen[v.id] = 'skipped';
return {
...v,
amount: 0,
aiStatus: 'fail',
amountCaption: voucherCaption({ ...v, aiStatus: 'fail', amount: 0 }),
};
});
let groups = (this.data.groups || [])
.filter((g) => g.groupKey !== 'pending')
.map((g) => ({ ...g, vouchers: [...(g.vouchers || [])] }));
const label = '未识别类型';
for (const voucher of moving) {
groups = this.mergeVoucherIntoGroups(
groups,
voucher,
{
amount: 0,
matched: false,
subtype: '',
subtypeLabel: '',
suggestedLabel: label,
},
this.data.types
);
}
this.setGroups(groups);
wx.showToast({ title: '已改为手填,请填金额并选类型', icon: 'none' });
},
chooseVoucher() {
const used = this.data.voucherCount || 0;
if (used >= MAX_VOUCHERS) {
wx.showToast({ title: `最多 ${MAX_VOUCHERS} 张凭证`, icon: 'none' });
return;
}
wx.chooseImage({
count: Math.min(CHOOSE_MAX, MAX_VOUCHERS - used),
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success: async (res) => {
const paths = res.tempFilePaths || [];
wx.showLoading({ title: '上传中', mask: true });
const added = [];
try {
let groups = (this.data.groups || []).map((g) => ({
...g,
vouchers: [...(g.vouchers || [])],
}));
let pending = groups.find((g) => g.groupKey === 'pending');
if (!pending) {
pending = {
groupKey: 'pending',
matched: false,
subtype: '',
subtypeLabel: '识别中',
suggestedLabel: '',
typeIndex: 0,
amount: '0.00',
remark: '',
vouchers: [],
unmatchedHint: '正在识别金额与类型…',
isPending: true,
};
groups.push(pending);
}
for (const filePath of paths) {
if (this.recountVouchers(groups) >= MAX_VOUCHERS) break;
// 与代客录单相同:先压图再读 base64,避免 uploadFile 后真机临时文件失效
const compressed = await compressOrderImage(filePath);
const imageBase64 = await readFileAsBase64(compressed);
const uploaded = await uploadFreeCostVoucher(compressed);
const item = {
id: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
path: uploaded.path,
preview: absolutizeMediaUrl(uploaded.signedUrl) || compressed,
localPath: compressed,
amount: 0,
aiStatus: 'extracting',
amountCaption: '识别中',
document_kind: 'voucher',
kindTouched: false,
};
pending.vouchers.push(item);
added.push({ id: item.id, path: item.path, imageBase64 });
}
this.setGroups(groups);
} catch (err) {
wx.showToast({ title: err.message || '上传失败', icon: 'none' });
} finally {
wx.hideLoading();
}
for (const item of added) {
await this.extractVoucherAmount(item.id, {
path: item.path,
imageBase64: item.imageBase64,
});
}
},
});
},
toggleDocumentKind(e) {
const groupKey = e.currentTarget.dataset.groupKey;
const voucherId = e.currentTarget.dataset.id;
const kind = normalizeDocumentKind(e.currentTarget.dataset.kind);
const groups = (this.data.groups || []).map((g) => {
if (g.groupKey !== groupKey) return g;
return {
...g,
vouchers: (g.vouchers || []).map((item) =>
item.id === voucherId ? { ...item, document_kind: kind, kindTouched: true } : item
),
};
});
this.setGroups(groups);
},
removeVoucher(e) {
const groupKey = e.currentTarget.dataset.groupKey;
const voucherId = e.currentTarget.dataset.id;
const groups = (this.data.groups || [])
.map((g) => {
if (g.groupKey !== groupKey) return g;
const vouchers = (g.vouchers || []).filter((v) => v.id !== voucherId);
let next = { ...g, vouchers };
if (!g._amountTouched) next = this.refreshGroupAmount(next, false);
return next;
})
.filter((g) => (g.vouchers || []).length > 0);
this.setGroups(groups);
},
previewVoucher(e) {
const url = e.currentTarget.dataset.url;
const urls = [];
(this.data.groups || []).forEach((g) => {
(g.vouchers || []).forEach((item) => {
if (item.preview) urls.push(item.preview);
});
});
if (!url) return;
wx.previewImage({ current: url, urls: urls.length ? urls : [url] });
},
previewHistoryVoucher(e) {
const url = e.currentTarget.dataset.url;
const urls = e.currentTarget.dataset.urls || [];
if (!url) {
wx.showToast({ title: '暂无凭证图', icon: 'none' });
return;
}
wx.previewImage({ current: url, urls: Array.isArray(urls) && urls.length ? urls : [url] });
},
previewHistoryInvoice(e) {
const urls = e.currentTarget.dataset.urls || [];
const url = (Array.isArray(urls) && urls[0]) || '';
if (!url) return;
wx.previewImage({ current: url, urls: Array.isArray(urls) && urls.length ? urls : [url] });
},
chooseInvoice() {
if (this.data.invoiceBusy || this.data.invoiceSubmitting) return;
wx.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success: async (res) => {
const filePath = (res.tempFilePaths || [])[0];
if (!filePath) return;
this.setData({ invoiceBusy: true, error: '' });
wx.showLoading({ title: '识别中', mask: true });
try {
const compressed = await compressOrderImage(filePath);
const uploaded = await uploadFreeCostInvoice(compressed);
const result = await extractFreeCostInvoice({ invoice_path: uploaded.path });
const data = result.data || {};
const ocr = data.ocr || {};
const suggested = data.suggested_ids || [];
const candidates = (data.candidates || []).map((row) => {
const createdAtText = formatDateTime(row.created_at);
const description = String(row.description || '').trim();
return {
...row,
amountText: formatMoney(row.amount),
selected: suggested.indexOf(row.id) >= 0,
createdAtText,
subText: [description, createdAtText].filter(Boolean).join(' · '),
};
});
const bits = [];
if (ocr.invoice_no) bits.push(ocr.invoice_no);
if (ocr.total_amount != null && ocr.total_amount !== '') bits.push(`¥${formatMoney(ocr.total_amount)}`);
else if (ocr.amount != null && ocr.amount !== '') bits.push(`¥${formatMoney(ocr.amount)}`);
if (ocr.invoice_date) bits.push(String(ocr.invoice_date));
if (ocr.seller_name) bits.push(String(ocr.seller_name));
this.setData({
showInvoiceSheet: true,
invoicePath: data.invoice_path || uploaded.path,
invoiceOcr: ocr,
invoiceOcrText: bits.join(' · ') || '未识别到票面信息',
invoiceCandidates: candidates,
});
} catch (err) {
wx.showToast({ title: err.message || '识别失败', icon: 'none' });
} finally {
this.setData({ invoiceBusy: false });
wx.hideLoading();
}
},
});
},
closeInvoiceSheet() {
if (this.data.invoiceSubmitting) return;
this.setData({
showInvoiceSheet: false,
invoicePath: '',
invoiceOcr: null,
invoiceOcrText: '',
invoiceCandidates: [],
});
},
toggleInvoiceCandidate(e) {
const id = e.currentTarget.dataset.id;
const invoiceCandidates = (this.data.invoiceCandidates || []).map((row) => ({
...row,
selected: row.id === id ? !row.selected : false,
}));
this.setData({ invoiceCandidates });
},
async confirmInvoiceSheet() {
if (this.data.invoiceSubmitting) return;
const path = this.data.invoicePath;
if (!path) return;
const selected = (this.data.invoiceCandidates || []).filter((row) => row.selected).map((row) => row.id);
const costDetailIds = selected.slice(0, 1);
this.setData({ invoiceSubmitting: true });
try {
await saveFreeCostInvoice({
invoice_path: path,
cost_detail_ids: costDetailIds,
ocr: this.data.invoiceOcr,
});
this.setData({
invoiceSubmitting: false,
showInvoiceSheet: false,
invoicePath: '',
invoiceOcr: null,
invoiceOcrText: '',
invoiceCandidates: [],
});
wx.showToast({ title: '已提交', icon: 'success' });
await this.loadHistory(this.data.historyPage);
} catch (err) {
this.setData({ invoiceSubmitting: false });
wx.showToast({ title: err.message || '保存失败', icon: 'none' });
}
},
anyExtracting() {
return (this.data.groups || []).some((g) =>
(g.vouchers || []).some((v) => v.aiStatus === 'extracting')
);
},
async linkInvoiceAfterCreate(created, invoiceLocalPath) {
const localPath = String(invoiceLocalPath || '').trim();
if (!localPath) return;
const payload = created && created.data ? created.data : created;
const row = payload && payload.row ? payload.row : payload;
const id = String((row && row.id) || '').trim();
if (!id) return;
try {
const uploaded = await uploadFreeCostInvoice(localPath);
await saveFreeCostInvoice({
invoice_path: uploaded.path,
cost_detail_ids: [id],
ocr: {},
});
} catch (_) {
/* 挂票失败不回滚已提交费用 */
}
},
async submitFreeCost() {
if (this.data.submitting) return;
if (this.anyExtracting()) {
wx.showToast({ title: '识别中,可点「改为手填」', icon: 'none' });
return;
}
const groups = this.data.groups || [];
if (this.data.requireVoucher && this.recountVouchers(groups) < 1) {
wx.showToast({ title: '请上传凭证', icon: 'none' });
return;
}
const unmatched = groups.filter((g) => !g.matched && !g.isPending);
if (unmatched.length) {
wx.showToast({ title: '请先处理未匹配的类型', icon: 'none' });
return;
}
const pending = groups.filter((g) => g.isPending);
if (pending.length) {
wx.showToast({ title: '识别中,可点「改为手填」', icon: 'none' });
return;
}
const ready = groups.filter((g) => g.matched);
if (!ready.length) {
wx.showToast({ title: '暂无可提交的成本组', icon: 'none' });
return;
}
for (const g of ready) {
const checked = validateFreeCostGroup(g);
if (!checked.ok) {
wx.showToast({ title: checked.message, icon: 'none' });
return;
}
}
this.setData({ submitting: true, error: '' });
let okCount = 0;
const remain = [...ready];
try {
for (let i = 0; i < ready.length; i += 1) {
const g = ready[i];
const payloads = expandFreeCostGroupToEntries(g);
for (let j = 0; j < payloads.length; j += 1) {
const { invoice_local_path: invoiceLocalPath, ...body } = payloads[j];
const created = await createFreeCostEntry({
...body,
invoice_photo: !!invoiceLocalPath,
});
okCount += 1;
await this.linkInvoiceAfterCreate(created, invoiceLocalPath);
}
remain.shift();
}
wx.showToast({ title: okCount > 1 ? `已提交 ${okCount} 条` : '已提交', icon: 'success' });
this.setGroups([]);
} catch (err) {
this.setGroups(remain.concat(groups.filter((g) => !g.matched)));
this.setData({ error: err.message || '提交失败' });
wx.showToast({
title: okCount ? `已提交 ${okCount} 条,其余失败` : err.message || '提交失败',
icon: 'none',
});
} finally {
this.setData({ submitting: false });
}
},
async loadHistory(pageOverride) {
const page = Math.max(1, Number(pageOverride != null ? pageOverride : this.data.historyPage) || 1);
this.setData({ loading: true, error: '' });
try {
const range = resolvePeriodRange(this.data.periodKey);
const result = await fetchFreeCostEntries({
cycle_code: dateRangeToCycleCode(range.dateFrom, range.dateTo),
page,
page_size: HISTORY_PAGE_SIZE,
});
const historyRows = (result.data || []).map((row) => {
const meta = statusMeta(row.status);
const voucherUrls = (row.voucher_urls || []).map(absolutizeMediaUrl).filter(Boolean);
return {
...row,
amountText: formatMoney(row.amount),
statusText: meta.text,
statusTone: meta.tone,
typeLabel: row.subtype_label || row.cost_subtype || '其他',
remarkText: resolveFreeCostRemarkText(row),
createdAtText: formatDateTime(row.created_at),
voucherUrls,
coverUrl: voucherUrls[0] || '',
voucherCount: voucherUrls.length,
invoiceUrls: (row.invoice_urls || []).map(absolutizeMediaUrl).filter(Boolean),
};
});
const amounts = result.status_amounts || {};
const total = Number(result.total) || 0;
const pageSize = Number(result.page_size) || HISTORY_PAGE_SIZE;
const currentPage = Number(result.page) || page;
const historyPageCount = Math.max(1, Math.ceil(total / pageSize) || 1);
this.setData({
historyRows,
loading: false,
historyTotal: total,
historyPage: currentPage,
historyPageCount,
postedAmountText: formatMoney(amounts.posted),
rejectedAmountText: formatMoney(amounts.rejected),
canHistoryPrev: currentPage > 1,
canHistoryNext: currentPage < historyPageCount && total > 0,
});
} catch (err) {
this.setData({
loading: false,
error: err.message || '加载历史失败',
historyRows: [],
historyTotal: 0,
historyPageCount: 1,
postedAmountText: '0.00',
rejectedAmountText: '0.00',
canHistoryPrev: false,
canHistoryNext: false,
});
}
},
},
});