第4项:对页面、表单及两版共享规则启用严格类型检查
This commit is contained in:
1 parent
389952f31c
commit
f570929cfe
77 files changed
+7629
-2981
No files matched your search
@@ -23,6 +23,9 @@ if [ "$WITH_NEXT" = 1 ]; then
|
|||||||
LEDGER_REFERENCE_APP=$(node e2e/lib/write-reference.mjs "$reference_tmp") || exit 1
|
LEDGER_REFERENCE_APP=$(node e2e/lib/write-reference.mjs "$reference_tmp") || exit 1
|
||||||
export LEDGER_REFERENCE_APP
|
export LEDGER_REFERENCE_APP
|
||||||
# 已提交的 web/dist 必须与源码重新构建的结果一致(需先在 web/ 下 npm ci)。
|
# 已提交的 web/dist 必须与源码重新构建的结果一致(需先在 web/ 下 npm ci)。
|
||||||
|
run "新版严格类型与覆盖" npm --prefix web run typecheck
|
||||||
|
run "新版代码检查" npm --prefix web run lint
|
||||||
|
run "新版前端测试" npm --prefix web test
|
||||||
if [ -d "$APP/web/node_modules" ]; then
|
if [ -d "$APP/web/node_modules" ]; then
|
||||||
run "新版构建与提交一致(web/dist)" bash -c 'cd web && npx vite build --logLevel error && git diff --quiet --exit-code -- dist && test -z "$(git ls-files --others --exclude-standard -- dist)"'
|
run "新版构建与提交一致(web/dist)" bash -c 'cd web && npx vite build --logLevel error && git diff --quiet --exit-code -- dist && test -z "$(git ls-files --others --exclude-standard -- dist)"'
|
||||||
fi
|
fi
|
||||||
|
|||||||
+130
-47
@@ -1,9 +1,54 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
// 浏览器预览和服务器记账共用整数算法;每行销售额最后统一四舍五入到分。
|
// 浏览器预览和服务器记账共用整数算法;每行销售额最后统一四舍五入到分。
|
||||||
|
/**
|
||||||
|
* @typedef {{id?: string, name?: string, amount?: string|number|null, costRemoved?: boolean}} ChargeInput
|
||||||
|
* @typedef {{mode?: string, rate?: string|number|null, poolId?: string}} CostEntry
|
||||||
|
* @typedef {{
|
||||||
|
* unit?: string, name?: string, quantity?: string|number, pricingMode?: string,
|
||||||
|
* baseSale?: string|number, sale?: string|number, charges?: ChargeInput[], goldPrice?: string|number,
|
||||||
|
* laborRate?: string|number, laborMode?: string, pieces?: string|number,
|
||||||
|
* costParts?: Record<string,string|number|null>, costMaterial?: CostEntry, costLabor?: CostEntry,
|
||||||
|
* materialPool?: {amount?: number|null}
|
||||||
|
* }} SaleInput
|
||||||
|
* @typedef {{mg: number, active?: boolean, order_id?: string, line_index?: number,
|
||||||
|
* created?: string, fifo_sequence?: number}} PoolUsage
|
||||||
|
* @typedef {{appended: true, previewIndex: number, mg: number}} NewUsage
|
||||||
|
* @typedef {PoolUsage & {appended?: false, previewIndex?: number}} ExistingUsage
|
||||||
|
* @typedef {ExistingUsage | NewUsage} PreviewUsage
|
||||||
|
* @typedef {(ExistingUsage & {created: string, fifo_sequence: number}) | NewUsage} SortedUsage
|
||||||
|
* @typedef {{totalMg: number, totalAmount: number|null, usages: PoolUsage[]}} PreviewPool
|
||||||
|
* @typedef {{key: string, note: string, payer: string, amount: number|null, status?: string}} RecordedFee
|
||||||
|
* @typedef {{rate?: number|null, mode?: string, poolId?: string}} RecordedCostMode
|
||||||
|
* @typedef {{poolId: string, amount: number|null}} LockPool
|
||||||
|
* @typedef {{payer: string, amount: number}} Allocation
|
||||||
|
* @typedef {{
|
||||||
|
* name: string, payer: string, quantity: number, cost?: number|null, costParts?: Record<string,number|null>,
|
||||||
|
* costPayers?: Record<string,string>, priceLockPool?: LockPool, priceLockExtraPool?: LockPool,
|
||||||
|
* costMaterial?: RecordedCostMode, costLabor?: RecordedCostMode,
|
||||||
|
* materialPool?: {allocations: Allocation[], averageRate: number|null, quantity?: number, revision?: string|number},
|
||||||
|
* materialAllocations?: (Allocation & {source: string, quantity: number, rate: number, weighted?: boolean, poolId?: string})[],
|
||||||
|
* returnedStock?: boolean, returnedStockId?: string, recovery_id?: string, recoveryMaterialMg?: number,
|
||||||
|
* charges?: {id:string}[]
|
||||||
|
* }} RecordedLine
|
||||||
|
* @typedef {{status: string, lines: RecordedLine[], corrections?: {type:string,target:string}[],
|
||||||
|
* expenses?: {id:string,note:string,date:string,amount:number,payer:string}[],
|
||||||
|
* pendingFees?: RecordedFee[], fee_items?: RecordedFee[]}} RecordedOrder
|
||||||
|
* @typedef {({kind: 'paid'|'zero', amount: number} | {kind: 'goods'|'pending', amount: number|null}) & {
|
||||||
|
* payer: string, name: string, source: string, excluded?: boolean, component?: string,
|
||||||
|
* materialPoolId?: string, materialPoolRevision?: string|number, poolPending?: boolean,
|
||||||
|
* calculation?: {rate?: number|null, quantity?: number, weighted?: boolean}|null,
|
||||||
|
* priceLockSource?: string, inheritedStockCost?: boolean, returnedStockId?: string
|
||||||
|
* }} CostRow
|
||||||
|
*/
|
||||||
(function (root) {
|
(function (root) {
|
||||||
const validMember = value =>
|
const validMember = (/** @type {string} */ value) =>
|
||||||
['owner', 'assistant', 'assistant2'].includes(value) ||
|
['owner', 'assistant', 'assistant2'].includes(value) ||
|
||||||
/^staff_[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value);
|
/^staff_[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value);
|
||||||
|
/**
|
||||||
|
* @param {unknown} value
|
||||||
|
* @param {number} places
|
||||||
|
* @param {string} name
|
||||||
|
*/
|
||||||
function fixed(value, places, name) {
|
function fixed(value, places, name) {
|
||||||
const s = String(value ?? '').trim();
|
const s = String(value ?? '').trim();
|
||||||
if (!new RegExp('^\\d+(?:\\.\\d{1,' + places + '})?$').test(s))
|
if (!new RegExp('^\\d+(?:\\.\\d{1,' + places + '})?$').test(s))
|
||||||
@@ -13,10 +58,12 @@
|
|||||||
if (n > 100000000000n) throw new Error(name + '超出支持范围');
|
if (n > 100000000000n) throw new Error(name + '超出支持范围');
|
||||||
return n;
|
return n;
|
||||||
}
|
}
|
||||||
|
/** @param {unknown} v */
|
||||||
function cents(v, name = '金额') {
|
function cents(v, name = '金额') {
|
||||||
return Number(fixed(v, 2, name));
|
return Number(fixed(v, 2, name));
|
||||||
}
|
}
|
||||||
const isSilver = name => ['足银999', '纯银925'].includes(name);
|
const isSilver = (/** @type {string|undefined} */ name) => name === '足银999' || name === '纯银925';
|
||||||
|
/** @param {ChargeInput[]} [raw] */
|
||||||
function charges(raw = []) {
|
function charges(raw = []) {
|
||||||
if (!Array.isArray(raw) || raw.length > 100) throw new Error('每行最多填写100项附加项目');
|
if (!Array.isArray(raw) || raw.length > 100) throw new Error('每行最多填写100项附加项目');
|
||||||
const items = [];
|
const items = [];
|
||||||
@@ -38,6 +85,7 @@
|
|||||||
if (total > 100000000000) throw new Error('附加项目合计超出支持范围');
|
if (total > 100000000000) throw new Error('附加项目合计超出支持范围');
|
||||||
return { items, total };
|
return { items, total };
|
||||||
}
|
}
|
||||||
|
/** @param {SaleInput} line */
|
||||||
function sale(line) {
|
function sale(line) {
|
||||||
const pricing = line.pricingMode === 'auto' ? calculate(line) : null;
|
const pricing = line.pricingMode === 'auto' ? calculate(line) : null;
|
||||||
const baseSale = pricing ? pricing.sale : cents(line.baseSale ?? line.sale, '商品基础金额');
|
const baseSale = pricing ? pricing.sale : cents(line.baseSale ?? line.sale, '商品基础金额');
|
||||||
@@ -46,6 +94,7 @@
|
|||||||
if (total > 100000000000) throw new Error('本行销售额超出支持范围');
|
if (total > 100000000000) throw new Error('本行销售额超出支持范围');
|
||||||
return { ...(pricing || {}), baseSale, charges: extra.items, chargesTotal: extra.total, sale: total };
|
return { ...(pricing || {}), baseSale, charges: extra.items, chargesTotal: extra.total, sale: total };
|
||||||
}
|
}
|
||||||
|
/** @param {number[]} lineAmounts */
|
||||||
function orderTotal(lineAmounts, discount = 0, roundingMode = 'yuan') {
|
function orderTotal(lineAmounts, discount = 0, roundingMode = 'yuan') {
|
||||||
const limit = 100000000000n;
|
const limit = 100000000000n;
|
||||||
if (!Array.isArray(lineAmounts) || lineAmounts.length < 1 || lineAmounts.length > 60)
|
if (!Array.isArray(lineAmounts) || lineAmounts.length < 1 || lineAmounts.length > 60)
|
||||||
@@ -75,13 +124,14 @@
|
|||||||
rounding_adjustment: Number(total - unroundedTotal),
|
rounding_adjustment: Number(total - unroundedTotal),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
/** @param {SaleInput} line */
|
||||||
function calculate(line) {
|
function calculate(line) {
|
||||||
if (line.unit !== 'g') throw new Error('按金价计算需要填写克重;按件报价请选择直接填金额');
|
if (line.unit !== 'g') throw new Error('按金价计算需要填写克重;按件报价请选择直接填金额');
|
||||||
const mg = fixed(line.quantity, 3, '克重');
|
const mg = fixed(line.quantity, 3, '克重');
|
||||||
if (mg <= 0n) throw new Error('克重必须大于0');
|
if (mg <= 0n) throw new Error('克重必须大于0');
|
||||||
const gold = fixed(line.goldPrice, 2, '金价'),
|
const gold = fixed(line.goldPrice, 2, '金价'),
|
||||||
labor = fixed(line.laborRate, 2, '销售工费');
|
labor = fixed(line.laborRate, 2, '销售工费');
|
||||||
if (!['gram', 'piece'].includes(line.laborMode)) throw new Error('请选择克工费或件工费');
|
if (line.laborMode !== 'gram' && line.laborMode !== 'piece') throw new Error('请选择克工费或件工费');
|
||||||
let pieces = 1n;
|
let pieces = 1n;
|
||||||
if (line.laborMode === 'piece') {
|
if (line.laborMode === 'piece') {
|
||||||
if (!/^\d+$/.test(String(line.pieces ?? '1'))) throw new Error('件数须为正整数');
|
if (!/^\d+$/.test(String(line.pieces ?? '1'))) throw new Error('件数须为正整数');
|
||||||
@@ -99,7 +149,10 @@
|
|||||||
pieces: Number(pieces),
|
pieces: Number(pieces),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
/** @type {Record<string,string>} */
|
||||||
const costLabels = { material: '料费成本', labor: '进货工费', accessories: '配件成本', other: '其他货品成本' };
|
const costLabels = { material: '料费成本', labor: '进货工费', accessories: '配件成本', other: '其他货品成本' };
|
||||||
|
/** @param {Record<string,string> | undefined} raw
|
||||||
|
* @returns {{material:string,labor:string,[key:string]:string|undefined} | undefined} */
|
||||||
function costPayers(raw) {
|
function costPayers(raw) {
|
||||||
// 旧行不补写分项付款人;显式传入时必须完整、有效,不能把无效值当作缺省。
|
// 旧行不补写分项付款人;显式传入时必须完整、有效,不能把无效值当作缺省。
|
||||||
if (raw === undefined) return undefined;
|
if (raw === undefined) return undefined;
|
||||||
@@ -114,7 +167,9 @@
|
|||||||
if (!Object.hasOwn(raw, key) || !validMember(raw[key])) throw new Error(costLabels[key] + '付款人无效');
|
if (!Object.hasOwn(raw, key) || !validMember(raw[key])) throw new Error(costLabels[key] + '付款人无效');
|
||||||
return { material: raw.material, labor: raw.labor };
|
return { material: raw.material, labor: raw.labor };
|
||||||
}
|
}
|
||||||
|
/** @param {Record<string,string|number|null>|undefined} raw */
|
||||||
function costs(raw) {
|
function costs(raw) {
|
||||||
|
/** @type {Record<string,number|null>} */
|
||||||
const parts = {};
|
const parts = {};
|
||||||
let total = 0,
|
let total = 0,
|
||||||
missing = false;
|
missing = false;
|
||||||
@@ -126,12 +181,20 @@
|
|||||||
if (total > 100000000000) throw new Error('货品成本超出支持范围');
|
if (total > 100000000000) throw new Error('货品成本超出支持范围');
|
||||||
return { parts, total: missing ? null : total };
|
return { parts, total: missing ? null : total };
|
||||||
}
|
}
|
||||||
|
/** @param {SaleInput} line */
|
||||||
function purchaseCosts(line) {
|
function purchaseCosts(line) {
|
||||||
const parts = { ...line.costParts };
|
const parts = { ...line.costParts };
|
||||||
|
/** @param {string} key
|
||||||
|
* @param {CostEntry|undefined} metadata
|
||||||
|
* @param {string} rateLabel
|
||||||
|
* @param {string} totalLabel
|
||||||
|
* @param {string} modeError
|
||||||
|
* @param {string} unitError */
|
||||||
const perGram = (key, metadata, rateLabel, totalLabel, modeError, unitError) => {
|
const perGram = (key, metadata, rateLabel, totalLabel, modeError, unitError) => {
|
||||||
// 旧单没有计价元数据时,原分项金额始终是总额,不能再乘克重。
|
// 旧单没有计价元数据时,原分项金额始终是总额,不能再乘克重。
|
||||||
const mode = metadata?.mode || 'total';
|
const mode = metadata?.mode || 'total';
|
||||||
if (!['gram', 'total'].includes(mode)) throw new Error(modeError);
|
if (!['gram', 'total'].includes(mode)) throw new Error(modeError);
|
||||||
|
/** @type {{mode:string,rate?:number|null}} */
|
||||||
const result = { mode };
|
const result = { mode };
|
||||||
if (mode === 'gram') {
|
if (mode === 'gram') {
|
||||||
if (line.unit !== 'g') throw new Error(unitError);
|
if (line.unit !== 'g') throw new Error(unitError);
|
||||||
@@ -157,7 +220,9 @@
|
|||||||
costMaterial = { mode: 'pool', poolId };
|
costMaterial = { mode: 'pool', poolId };
|
||||||
const previewAmount = line.materialPool?.amount;
|
const previewAmount = line.materialPool?.amount;
|
||||||
parts.material =
|
parts.material =
|
||||||
Number.isSafeInteger(previewAmount) && previewAmount >= 0 ? (previewAmount / 100).toFixed(2) : '';
|
typeof previewAmount === 'number' && Number.isSafeInteger(previewAmount) && previewAmount >= 0
|
||||||
|
? (previewAmount / 100).toFixed(2)
|
||||||
|
: '';
|
||||||
} else
|
} else
|
||||||
costMaterial = perGram(
|
costMaterial = perGram(
|
||||||
'material',
|
'material',
|
||||||
@@ -178,6 +243,11 @@
|
|||||||
return { ...costs(parts), costMaterial, costLabor };
|
return { ...costs(parts), costMaterial, costLabor };
|
||||||
}
|
}
|
||||||
// 先用实际总金额与总毫克计算,展示用均价不可参与成本分摊。
|
// 先用实际总金额与总毫克计算,展示用均价不可参与成本分摊。
|
||||||
|
/**
|
||||||
|
* @param {number} totalAmount
|
||||||
|
* @param {number} totalMg
|
||||||
|
* @param {number} quantityMg
|
||||||
|
*/
|
||||||
function poolMaterialAmount(totalAmount, totalMg, quantityMg) {
|
function poolMaterialAmount(totalAmount, totalMg, quantityMg) {
|
||||||
for (const value of [totalAmount, totalMg, quantityMg])
|
for (const value of [totalAmount, totalMg, quantityMg])
|
||||||
if (!Number.isSafeInteger(value) || value < 0 || value > 100000000000) throw new Error('日购料金额或克重无效');
|
if (!Number.isSafeInteger(value) || value < 0 || value > 100000000000) throw new Error('日购料金额或克重无效');
|
||||||
@@ -187,8 +257,14 @@
|
|||||||
return Number(amount);
|
return Number(amount);
|
||||||
}
|
}
|
||||||
// 同池先按完整耗用顺序累计取整,再取相邻差额;编辑沿用原行身份,新增行追加。
|
// 同池先按完整耗用顺序累计取整,再取相邻差额;编辑沿用原行身份,新增行追加。
|
||||||
|
/**
|
||||||
|
* @param {PreviewPool} pool
|
||||||
|
* @param {{lineIndex:number,mg:number}[]} entries
|
||||||
|
* @param {{orderId?:string|null,allUsages?:PoolUsage[]}} [options]
|
||||||
|
*/
|
||||||
function poolMaterialPreview(pool, entries, { orderId = null, allUsages = pool.usages || [] } = {}) {
|
function poolMaterialPreview(pool, entries, { orderId = null, allUsages = pool.usages || [] } = {}) {
|
||||||
const valid = value => Number.isSafeInteger(value) && value >= 0 && value <= 100000000000;
|
/** @param {number|null} value @returns {value is number} */
|
||||||
|
const valid = value => value !== null && Number.isSafeInteger(value) && value >= 0 && value <= 100000000000;
|
||||||
if (
|
if (
|
||||||
!valid(pool.totalAmount) ||
|
!valid(pool.totalAmount) ||
|
||||||
!valid(pool.totalMg) ||
|
!valid(pool.totalMg) ||
|
||||||
@@ -197,7 +273,7 @@
|
|||||||
!Array.isArray(allUsages)
|
!Array.isArray(allUsages)
|
||||||
)
|
)
|
||||||
throw new Error('日购料预估记录无效,请刷新料价');
|
throw new Error('日购料预估记录无效,请刷新料价');
|
||||||
const indices = new Set();
|
const indices = /** @type {Set<number>} */ (new Set());
|
||||||
for (const entry of entries) {
|
for (const entry of entries) {
|
||||||
if (
|
if (
|
||||||
!Number.isSafeInteger(entry.lineIndex) ||
|
!Number.isSafeInteger(entry.lineIndex) ||
|
||||||
@@ -210,40 +286,40 @@
|
|||||||
indices.add(entry.lineIndex);
|
indices.add(entry.lineIndex);
|
||||||
}
|
}
|
||||||
const originals = orderId ? allUsages.filter(usage => usage.order_id === orderId) : [];
|
const originals = orderId ? allUsages.filter(usage => usage.order_id === orderId) : [];
|
||||||
|
/** @type {PreviewUsage[]} */
|
||||||
const usages = pool.usages
|
const usages = pool.usages
|
||||||
.filter(usage => usage.active && (!orderId || usage.order_id !== orderId))
|
.filter(usage => usage.active && (!orderId || usage.order_id !== orderId))
|
||||||
.map(usage => ({ ...usage }));
|
.map(usage => ({ ...usage }));
|
||||||
const usedMg = usages.reduce((total, usage) => total + usage.mg, 0),
|
const usedMg = usages.reduce((total, usage) => total + usage.mg, 0),
|
||||||
wantedMg = entries.reduce((total, entry) => total + entry.mg, 0);
|
wantedMg = entries.reduce((total, entry) => total + entry.mg, 0);
|
||||||
const covered = pool.totalMg > 0 && usedMg + wantedMg <= pool.totalMg,
|
const covered = pool.totalMg > 0 && usedMg + wantedMg <= pool.totalMg,
|
||||||
amounts = Object.fromEntries(entries.map(entry => [entry.lineIndex, null]));
|
amounts = /** @type {Record<number,number|null>} */ (
|
||||||
|
Object.fromEntries(entries.map(entry => [entry.lineIndex, null]))
|
||||||
|
);
|
||||||
for (const entry of entries) {
|
for (const entry of entries) {
|
||||||
const original = originals.find(usage => usage.line_index === entry.lineIndex);
|
const original = originals.find(usage => usage.line_index === entry.lineIndex);
|
||||||
usages.push({ ...original, mg: entry.mg, previewIndex: entry.lineIndex, appended: !original });
|
usages.push(
|
||||||
|
original
|
||||||
|
? { ...original, mg: entry.mg, previewIndex: entry.lineIndex, appended: false }
|
||||||
|
: { mg: entry.mg, previewIndex: entry.lineIndex, appended: true },
|
||||||
|
);
|
||||||
}
|
}
|
||||||
for (const usage of usages) {
|
/** @param {PreviewUsage} usage @returns {usage is SortedUsage} */
|
||||||
if (
|
const sortable = usage =>
|
||||||
!valid(usage.mg) ||
|
valid(usage.mg) &&
|
||||||
!usage.mg ||
|
usage.mg > 0 &&
|
||||||
(!usage.appended &&
|
(usage.appended === true ||
|
||||||
(!Number.isSafeInteger(usage.fifo_sequence) ||
|
(typeof usage.fifo_sequence === 'number' &&
|
||||||
usage.fifo_sequence < 1 ||
|
Number.isSafeInteger(usage.fifo_sequence) &&
|
||||||
typeof usage.created !== 'string' ||
|
usage.fifo_sequence >= 1 &&
|
||||||
!usage.created))
|
typeof usage.created === 'string' &&
|
||||||
)
|
usage.created.length > 0));
|
||||||
throw new Error('日购料耗用顺序尚未读到,请刷新料价');
|
if (!usages.every(sortable)) throw new Error('日购料耗用顺序尚未读到,请刷新料价');
|
||||||
}
|
usages.sort((a, b) => {
|
||||||
usages.sort(
|
if (a.appended) return b.appended ? a.previewIndex - b.previewIndex : 1;
|
||||||
(a, b) =>
|
if (b.appended) return -1;
|
||||||
Number(!!a.appended) - Number(!!b.appended) ||
|
return a.created < b.created ? -1 : a.created > b.created ? 1 : a.fifo_sequence - b.fifo_sequence;
|
||||||
(a.appended
|
});
|
||||||
? a.previewIndex - b.previewIndex
|
|
||||||
: a.created < b.created
|
|
||||||
? -1
|
|
||||||
: a.created > b.created
|
|
||||||
? 1
|
|
||||||
: a.fifo_sequence - b.fifo_sequence),
|
|
||||||
);
|
|
||||||
if (covered) {
|
if (covered) {
|
||||||
let cumulativeMg = 0,
|
let cumulativeMg = 0,
|
||||||
previousAmount = 0;
|
previousAmount = 0;
|
||||||
@@ -256,6 +332,7 @@
|
|||||||
}
|
}
|
||||||
return { amounts, usedMg, wantedMg, covered };
|
return { amounts, usedMg, wantedMg, covered };
|
||||||
}
|
}
|
||||||
|
/** @param {{lockedQuantity:unknown,quantity:unknown,buyRate:unknown,extraBuyRate?:unknown}} input */
|
||||||
function priceLockCost(input) {
|
function priceLockCost(input) {
|
||||||
const locked = fixed(input.lockedQuantity, 3, '锁定克重'),
|
const locked = fixed(input.lockedQuantity, 3, '锁定克重'),
|
||||||
actual = fixed(input.quantity, 3, '实际克重');
|
actual = fixed(input.quantity, 3, '实际克重');
|
||||||
@@ -266,7 +343,7 @@
|
|||||||
extra = actual > locked ? actual - locked : 0n;
|
extra = actual > locked ? actual - locked : 0n;
|
||||||
const extraRate = extra ? fixed(input.extraBuyRate, 2, '补重进货料价') : 0n;
|
const extraRate = extra ? fixed(input.extraBuyRate, 2, '补重进货料价') : 0n;
|
||||||
if (extra && extraRate <= 0n) throw new Error('补重进货料价必须大于0');
|
if (extra && extraRate <= 0n) throw new Error('补重进货料价必须大于0');
|
||||||
const amount = (quantity, rate) => (quantity * rate + 500n) / 1000n;
|
const amount = (/** @type {bigint} */ quantity, /** @type {bigint} */ rate) => (quantity * rate + 500n) / 1000n;
|
||||||
const originalPurchase = amount(locked, originalRate),
|
const originalPurchase = amount(locked, originalRate),
|
||||||
originalUsedCost = amount(used, originalRate),
|
originalUsedCost = amount(used, originalRate),
|
||||||
extraCost = amount(extra, extraRate);
|
extraCost = amount(extra, extraRate);
|
||||||
@@ -286,6 +363,7 @@
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
// 订单内部对账用,输入为账本已保存的整数分;预估费用与实际支出分开。
|
// 订单内部对账用,输入为账本已保存的整数分;预估费用与实际支出分开。
|
||||||
|
/** @param {RecordedOrder} order */
|
||||||
function orderCosts(order) {
|
function orderCosts(order) {
|
||||||
const empty = () => ({
|
const empty = () => ({
|
||||||
goods: 0,
|
goods: 0,
|
||||||
@@ -296,10 +374,14 @@
|
|||||||
total: 0,
|
total: 0,
|
||||||
missing: 0,
|
missing: 0,
|
||||||
});
|
});
|
||||||
const byPayer = { owner: empty(), assistant: empty(), assistant2: empty() },
|
const byPayer = /** @type {Record<string, ReturnType<typeof empty>>} */ ({
|
||||||
rows = [];
|
owner: empty(),
|
||||||
|
assistant: empty(),
|
||||||
|
assistant2: empty(),
|
||||||
|
}),
|
||||||
|
rows = /** @type {CostRow[]} */ ([]);
|
||||||
const goodsExcluded = ['returned', 'cancelled'].includes(order.status);
|
const goodsExcluded = ['returned', 'cancelled'].includes(order.status);
|
||||||
const add = row => {
|
const add = (/** @type {CostRow} */ row) => {
|
||||||
rows.push(row);
|
rows.push(row);
|
||||||
if (row.excluded) return;
|
if (row.excluded) return;
|
||||||
if (!validMember(row.payer)) throw new Error('成本付款人无效');
|
if (!validMember(row.payer)) throw new Error('成本付款人无效');
|
||||||
@@ -317,10 +399,14 @@
|
|||||||
for (const [i, line] of order.lines.entries()) {
|
for (const [i, line] of order.lines.entries()) {
|
||||||
const payers = costPayers(line.costPayers);
|
const payers = costPayers(line.costPayers);
|
||||||
const parts = line.costParts
|
const parts = line.costParts
|
||||||
? Object.entries(costLabels).map(([key, name]) => ({ key, name, amount: line.costParts[key] ?? null }))
|
? Object.entries(costLabels).map(([key, name]) => ({ key, name, amount: line.costParts?.[key] ?? null }))
|
||||||
: [{ key: 'total', name: '货品成本(原单未分项)', amount: line.cost ?? null }];
|
: [{ key: 'total', name: '货品成本(原单未分项)', amount: line.cost ?? null }];
|
||||||
|
const lockPool =
|
||||||
|
line.priceLockExtraPool?.amount === null
|
||||||
|
? line.priceLockExtraPool
|
||||||
|
: line.priceLockPool || line.priceLockExtraPool;
|
||||||
for (const part of parts) {
|
for (const part of parts) {
|
||||||
if (part.key === 'material' && (line.priceLockPool || line.priceLockExtraPool) && part.amount === null) {
|
if (part.key === 'material' && lockPool && part.amount === null) {
|
||||||
add({
|
add({
|
||||||
kind: 'goods',
|
kind: 'goods',
|
||||||
component: 'material',
|
component: 'material',
|
||||||
@@ -329,17 +415,13 @@
|
|||||||
amount: null,
|
amount: null,
|
||||||
payer: payers?.material ?? line.payer,
|
payer: payers?.material ?? line.payer,
|
||||||
excluded: goodsExcluded,
|
excluded: goodsExcluded,
|
||||||
materialPoolId: (line.priceLockExtraPool?.amount === null
|
materialPoolId: lockPool.poolId,
|
||||||
? line.priceLockExtraPool
|
|
||||||
: line.priceLockPool || line.priceLockExtraPool
|
|
||||||
).poolId,
|
|
||||||
poolPending: true,
|
poolPending: true,
|
||||||
calculation: null,
|
calculation: null,
|
||||||
});
|
});
|
||||||
} else if (part.key === 'material' && line.costMaterial?.mode === 'pool') {
|
} else if (part.key === 'material' && line.costMaterial?.mode === 'pool') {
|
||||||
const pool = line.materialPool,
|
const pool = line.materialPool;
|
||||||
allocations = pool?.allocations;
|
if (part.amount === null || !pool?.allocations?.length) {
|
||||||
if (part.amount === null || !allocations?.length) {
|
|
||||||
add({
|
add({
|
||||||
kind: 'goods',
|
kind: 'goods',
|
||||||
component: 'material',
|
component: 'material',
|
||||||
@@ -354,6 +436,7 @@
|
|||||||
calculation: null,
|
calculation: null,
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
|
const allocations = pool.allocations;
|
||||||
if (
|
if (
|
||||||
!Array.isArray(allocations) ||
|
!Array.isArray(allocations) ||
|
||||||
allocations.some(
|
allocations.some(
|
||||||
@@ -437,7 +520,7 @@
|
|||||||
for (const fee of order.expenses || [])
|
for (const fee of order.expenses || [])
|
||||||
if (fee.amount > 0 && !corrected.has(fee.id))
|
if (fee.amount > 0 && !corrected.has(fee.id))
|
||||||
add({ kind: 'paid', name: fee.note, source: fee.date, amount: fee.amount, payer: fee.payer });
|
add({ kind: 'paid', name: fee.note, source: fee.date, amount: fee.amount, payer: fee.payer });
|
||||||
const sourceFor = fee => {
|
const sourceFor = (/** @type {RecordedFee} */ fee) => {
|
||||||
const index = order.lines.findIndex(l => (l.charges || []).some(c => 'charge:' + c.id === fee.key));
|
const index = order.lines.findIndex(l => (l.charges || []).some(c => 'charge:' + c.id === fee.key));
|
||||||
return index < 0 ? '整单费用' : `商品 ${index + 1} · ${order.lines[index].name}`;
|
return index < 0 ? '整单费用' : `商品 ${index + 1} · ${order.lines[index].name}`;
|
||||||
};
|
};
|
||||||
@@ -451,7 +534,7 @@
|
|||||||
for (const s of Object.values(byPayer)) {
|
for (const s of Object.values(byPayer)) {
|
||||||
s.total = s.goods + s.paidFees + s.pendingFees;
|
s.total = s.goods + s.paidFees + s.pendingFees;
|
||||||
s.missing = s.goodsMissing + s.pendingMissing;
|
s.missing = s.goodsMissing + s.pendingMissing;
|
||||||
for (const key of Object.keys(total)) total[key] += s[key];
|
for (const key of /** @type {(keyof typeof total)[]} */ (Object.keys(total))) total[key] += s[key];
|
||||||
}
|
}
|
||||||
return { byPayer, total, rows, goodsExcluded, pendingCount: (order.pendingFees || []).length };
|
return { byPayer, total, rows, goodsExcluded, pendingCount: (order.pendingFees || []).length };
|
||||||
}
|
}
|
||||||
@@ -473,5 +556,5 @@
|
|||||||
orderCosts,
|
orderCosts,
|
||||||
};
|
};
|
||||||
if (typeof module === 'object' && module.exports) module.exports = api;
|
if (typeof module === 'object' && module.exports) module.exports = api;
|
||||||
else root.LedgerCalc = api;
|
else Object.assign(root, { LedgerCalc: api });
|
||||||
})(typeof globalThis === 'object' ? globalThis : this);
|
})(typeof globalThis === 'object' ? globalThis : this);
|
||||||
@@ -1,15 +1,19 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
// 手续费预览使用整数分;真实费用由服务端按每笔客户付款生成。
|
// 手续费预览使用整数分;真实费用由服务端按每笔客户付款生成。
|
||||||
(function (root) {
|
(function (root) {
|
||||||
|
/** @param {string} account */
|
||||||
const isAccount = account => ['助理信用卡', '助理1信用卡', '麦麦信用卡', '助理2信用卡'].includes(account);
|
const isAccount = account => ['助理信用卡', '助理1信用卡', '麦麦信用卡', '助理2信用卡'].includes(account);
|
||||||
const ratePermille = 6;
|
const ratePermille = 6;
|
||||||
function rate(value = ratePermille) {
|
function rate(value = ratePermille) {
|
||||||
if (!Number.isSafeInteger(value) || value < 0 || value > 1000) throw new Error('信用卡手续费率须为0~1000的整数‰');
|
if (!Number.isSafeInteger(value) || value < 0 || value > 1000) throw new Error('信用卡手续费率须为0~1000的整数‰');
|
||||||
return value;
|
return value;
|
||||||
}
|
}
|
||||||
|
/** @param {string} account */
|
||||||
const normalizeAccount = account => (isAccount(account) ? '麦麦信用卡' : account);
|
const normalizeAccount = account => (isAccount(account) ? '麦麦信用卡' : account);
|
||||||
const note = (value = ratePermille) => `信用卡手续费(${rate(value)}‰)`;
|
const note = (value = ratePermille) => `信用卡手续费(${rate(value)}‰)`;
|
||||||
|
/** @param {{system?: string; key?: string} | null | undefined} item */
|
||||||
const isFee = item => item?.system === 'credit_card' || String(item?.key || '').startsWith('card_fee:');
|
const isFee = item => item?.system === 'credit_card' || String(item?.key || '').startsWith('card_fee:');
|
||||||
|
/** @param {number} cents @param {number} [value] */
|
||||||
function amount(cents, value = ratePermille) {
|
function amount(cents, value = ratePermille) {
|
||||||
if (!Number.isSafeInteger(cents) || cents < 0 || cents > 100000000000) throw new Error('客户付款金额无效');
|
if (!Number.isSafeInteger(cents) || cents < 0 || cents > 100000000000) throw new Error('客户付款金额无效');
|
||||||
return Number((BigInt(cents) * BigInt(rate(value)) + 500n) / 1000n);
|
return Number((BigInt(cents) * BigInt(rate(value)) + 500n) / 1000n);
|
||||||
@@ -17,4 +21,4 @@
|
|||||||
const api = { isAccount, isFee, amount, rate, ratePermille, normalizeAccount, note };
|
const api = { isAccount, isFee, amount, rate, ratePermille, normalizeAccount, note };
|
||||||
if (typeof module === 'object' && module.exports) module.exports = api;
|
if (typeof module === 'object' && module.exports) module.exports = api;
|
||||||
else root.CreditCardFees = api;
|
else root.CreditCardFees = api;
|
||||||
})(typeof globalThis === 'object' ? globalThis : this);
|
})(typeof globalThis === 'object' ? globalThis : /** @type {typeof globalThis} */ (/** @type {unknown} */ (this)));
|
||||||
@@ -1,10 +1,30 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
// 只生成可修改的预估值,不写支付流水。金额输入与表单一致,使用元的字符串。
|
// 只生成可修改的预估值,不写支付流水。金额输入与表单一致,使用元的字符串。
|
||||||
|
/**
|
||||||
|
* @typedef {{amount:string,payer:string,name?:string,enabled?:boolean,byQuantity?:boolean}} CostPreset
|
||||||
|
* @typedef {Record<string,CostPreset>} Presets
|
||||||
|
*/
|
||||||
|
/**
|
||||||
|
* @template [Amount=string]
|
||||||
|
* @typedef {{
|
||||||
|
* key: string, note: string, amount: Amount|null, payer: string, edited?: boolean, status?: string,
|
||||||
|
* sourceName?: string, lineNumber?: number, expense_id?: string, funding?: Record<string,unknown>
|
||||||
|
* }} FeeItem
|
||||||
|
*/
|
||||||
|
/**
|
||||||
|
* @typedef {{id?:string,name?:string,costRemoved?:boolean}} SaleCharge
|
||||||
|
* @typedef {{certificate?:string,packaging?:string,shipping?:string,packagingPayer?:string}} ShopCosts
|
||||||
|
*/
|
||||||
(function (root) {
|
(function (root) {
|
||||||
const Calc = typeof module === 'object' && module.exports ? require('./calculations') : root.LedgerCalc;
|
const Calc =
|
||||||
|
typeof module === 'object' && module.exports
|
||||||
|
? require('./calculations')
|
||||||
|
: /** @type {typeof globalThis} */ (root).LedgerCalc;
|
||||||
const defaults = { 证书: '4', 包装: '3', 快递: '6' };
|
const defaults = { 证书: '4', 包装: '3', 快递: '6' };
|
||||||
const normalize = name => ({ 包装盒: '包装', 快递费: '快递', 运费: '快递' })[name] || name;
|
const normalize = (/** @type {string} */ name) =>
|
||||||
|
/** @type {Record<string,string>} */ ({ 包装盒: '包装', 快递费: '快递', 运费: '快递' })[name] || name;
|
||||||
// 勾选成本与客户收费分开。保留旧项目,只有明确勾选的新项目使用这些固定金额。
|
// 勾选成本与客户收费分开。保留旧项目,只有明确勾选的新项目使用这些固定金额。
|
||||||
|
/** @param {unknown} name */
|
||||||
function checkboxCategory(name) {
|
function checkboxCategory(name) {
|
||||||
const value = String(name || '').trim();
|
const value = String(name || '').trim();
|
||||||
if (['快递', '快递费', '运费', '京东快递', '圆通快递'].includes(value)) return 'shipping';
|
if (['快递', '快递费', '运费', '京东快递', '圆通快递'].includes(value)) return 'shipping';
|
||||||
@@ -13,6 +33,7 @@
|
|||||||
if (['银链', '银链(家里)', '银链(家里)'].includes(value)) return 'silverChain';
|
if (['银链', '银链(家里)', '银链(家里)'].includes(value)) return 'silverChain';
|
||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
|
/** @param {unknown} value */
|
||||||
function boxCount(value) {
|
function boxCount(value) {
|
||||||
const text = String(value ?? '').trim(),
|
const text = String(value ?? '').trim(),
|
||||||
count = Number(text);
|
count = Number(text);
|
||||||
@@ -20,6 +41,7 @@
|
|||||||
throw new Error('盒子数量须为支持范围内的正整数');
|
throw new Error('盒子数量须为支持范围内的正整数');
|
||||||
return count;
|
return count;
|
||||||
}
|
}
|
||||||
|
/** @type {Readonly<Presets>} */
|
||||||
const presetDefaults = Object.freeze({
|
const presetDefaults = Object.freeze({
|
||||||
jd: { amount: '8', payer: 'owner' },
|
jd: { amount: '8', payer: 'owner' },
|
||||||
yt: { amount: '6', payer: 'order' },
|
yt: { amount: '6', payer: 'order' },
|
||||||
@@ -27,9 +49,11 @@
|
|||||||
steel: { amount: '7', payer: 'owner' },
|
steel: { amount: '7', payer: 'owner' },
|
||||||
silver: { amount: '18', payer: 'owner' },
|
silver: { amount: '18', payer: 'owner' },
|
||||||
});
|
});
|
||||||
const validMember = value =>
|
const validMember = (/** @type {string} */ value) =>
|
||||||
['owner', 'assistant', 'assistant2'].includes(value) || /^staff_[a-f0-9-]{36}$/.test(value);
|
['owner', 'assistant', 'assistant2'].includes(value) || /^staff_[a-f0-9-]{36}$/.test(value);
|
||||||
|
/** @type {Record<string,string>} */
|
||||||
const presetNames = { jd: '京东快递', yt: '圆通快递', box: '盒子', steel: '钢绳(店里)', silver: '银链(家里)' };
|
const presetNames = { jd: '京东快递', yt: '圆通快递', box: '盒子', steel: '钢绳(店里)', silver: '银链(家里)' };
|
||||||
|
/** @param {Presets} [values] */
|
||||||
function presets(values) {
|
function presets(values) {
|
||||||
return Object.fromEntries(
|
return Object.fromEntries(
|
||||||
Object.entries(values === undefined ? presetDefaults : values)
|
Object.entries(values === undefined ? presetDefaults : values)
|
||||||
@@ -37,6 +61,7 @@
|
|||||||
.map(([kind, row]) => [kind, { ...presetDefaults[kind], ...row }]),
|
.map(([kind, row]) => [kind, { ...presetDefaults[kind], ...row }]),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
/** @param {Presets} [values] */
|
||||||
function presetCatalog(values) {
|
function presetCatalog(values) {
|
||||||
return Object.fromEntries(
|
return Object.fromEntries(
|
||||||
Object.entries(presets(values)).map(([kind, row]) => [
|
Object.entries(presets(values)).map(([kind, row]) => [
|
||||||
@@ -45,6 +70,7 @@
|
|||||||
]),
|
]),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
/** @param {Presets} [values] */
|
||||||
function customPresets(values) {
|
function customPresets(values) {
|
||||||
return (
|
return (
|
||||||
(values !== undefined && Object.keys(presetDefaults).some(kind => !Object.hasOwn(values, kind))) ||
|
(values !== undefined && Object.keys(presetDefaults).some(kind => !Object.hasOwn(values, kind))) ||
|
||||||
@@ -55,12 +81,24 @@
|
|||||||
)
|
)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
/** @param {string} kind */
|
||||||
function presetKey(kind) {
|
function presetKey(kind) {
|
||||||
return (
|
return (
|
||||||
{ jd: 'shipping', yt: 'shipping', box: 'box', steel: 'braiding', silver: 'other' }[kind] ||
|
/** @type {Record<string,string>} */ ({
|
||||||
'manual:' + kind.slice(7)
|
jd: 'shipping',
|
||||||
|
yt: 'shipping',
|
||||||
|
box: 'box',
|
||||||
|
steel: 'braiding',
|
||||||
|
silver: 'other',
|
||||||
|
})[kind] || 'manual:' + kind.slice(7)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* @param {string} kind
|
||||||
|
* @param {unknown} quantity
|
||||||
|
* @param {string} member
|
||||||
|
* @param {Presets} [values]
|
||||||
|
*/
|
||||||
function presetFee(kind, quantity, member, values) {
|
function presetFee(kind, quantity, member, values) {
|
||||||
const row = presetCatalog(values)[kind];
|
const row = presetCatalog(values)[kind];
|
||||||
if (!row || !row.enabled) throw new Error('成本项目已停用,请重新核对');
|
if (!row || !row.enabled) throw new Error('成本项目已停用,请重新核对');
|
||||||
@@ -76,6 +114,10 @@
|
|||||||
edited: true,
|
edited: true,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* @param {FeeItem<string|number>} item
|
||||||
|
* @param {Presets} [values]
|
||||||
|
*/
|
||||||
function configuredKind(item, values) {
|
function configuredKind(item, values) {
|
||||||
for (const [kind, row] of Object.entries(presetCatalog(values))) {
|
for (const [kind, row] of Object.entries(presetCatalog(values))) {
|
||||||
if (!row.enabled || item.key !== presetKey(kind)) continue;
|
if (!row.enabled || item.key !== presetKey(kind)) continue;
|
||||||
@@ -92,9 +134,13 @@
|
|||||||
}
|
}
|
||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* @param {FeeItem<string|number>} item
|
||||||
|
* @param {{recorded?:boolean,presets?:Presets}} [options]
|
||||||
|
*/
|
||||||
function presetKind(item, { recorded = false, presets: values } = {}) {
|
function presetKind(item, { recorded = false, presets: values } = {}) {
|
||||||
const config = presets(values),
|
const config = presets(values),
|
||||||
matchPayer = kind =>
|
matchPayer = (/** @type {string} */ kind) =>
|
||||||
config[kind].payer === 'order' ? validMember(item?.payer) : item?.payer === config[kind].payer;
|
config[kind].payer === 'order' ? validMember(item?.payer) : item?.payer === config[kind].payer;
|
||||||
if (!item || (item.expense_id && !recorded) || item.funding) return '';
|
if (!item || (item.expense_id && !recorded) || item.funding) return '';
|
||||||
if (customPresets(values)) return configuredKind(item, values);
|
if (customPresets(values)) return configuredKind(item, values);
|
||||||
@@ -139,16 +185,21 @@
|
|||||||
}
|
}
|
||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* @param {{shipping?:string,box?:boolean,quantity?:string,steel?:boolean,silver?:boolean}} [selection]
|
||||||
|
* @param {string} [member]
|
||||||
|
* @param {Presets} [values]
|
||||||
|
*/
|
||||||
function checkboxFees(
|
function checkboxFees(
|
||||||
{ shipping = '', box = false, quantity = '1', steel = false, silver = false } = {},
|
{ shipping = '', box = false, quantity = '1', steel = false, silver = false } = {},
|
||||||
member = 'assistant',
|
member = 'assistant',
|
||||||
values,
|
values,
|
||||||
) {
|
) {
|
||||||
const config = presets(values),
|
const config = presets(values),
|
||||||
items = [],
|
items = /** @type {FeeItem[]} */ ([]),
|
||||||
payer = kind =>
|
payer = (/** @type {string} */ kind) =>
|
||||||
config[kind].payer === 'order' ? (validMember(member) ? member : 'assistant') : config[kind].payer;
|
config[kind].payer === 'order' ? (validMember(member) ? member : 'assistant') : config[kind].payer;
|
||||||
const add = (kind, key, note, count = 1) => {
|
const add = (/** @type {string} */ kind, /** @type {string} */ key, /** @type {string} */ note, count = 1) => {
|
||||||
const amount = Calc.cents(String(config[kind].amount), '常用成本') * count;
|
const amount = Calc.cents(String(config[kind].amount), '常用成本') * count;
|
||||||
if (!Number.isSafeInteger(amount) || amount > 100000000000) throw new Error('常用成本金额超出支持范围');
|
if (!Number.isSafeInteger(amount) || amount > 100000000000) throw new Error('常用成本金额超出支持范围');
|
||||||
items.push({
|
items.push({
|
||||||
@@ -170,23 +221,32 @@
|
|||||||
if (silver) add('silver', 'other', '银链(家里)');
|
if (silver) add('silver', 'other', '银链(家里)');
|
||||||
return items;
|
return items;
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* @template Amount
|
||||||
|
* @param {FeeItem<Amount>[]} existing
|
||||||
|
* @param {{charges?:SaleCharge[]}[]} lines
|
||||||
|
* @param {{addShipping?:boolean,defaultPayer?:string,shopDefaults?:ShopCosts,checkboxCosts?:boolean}} [options]
|
||||||
|
*/
|
||||||
function sync(
|
function sync(
|
||||||
existing,
|
existing,
|
||||||
lines,
|
lines,
|
||||||
{ addShipping = false, defaultPayer = 'assistant', shopDefaults = {}, checkboxCosts = false } = {},
|
{ addShipping = false, defaultPayer = 'assistant', shopDefaults = {}, checkboxCosts = false } = {},
|
||||||
) {
|
) {
|
||||||
|
/** @type {Record<string,string>} */
|
||||||
const configured = {
|
const configured = {
|
||||||
证书: shopDefaults.certificate ?? defaults['证书'],
|
证书: shopDefaults.certificate ?? defaults['证书'],
|
||||||
包装: shopDefaults.packaging ?? defaults['包装'],
|
包装: shopDefaults.packaging ?? defaults['包装'],
|
||||||
快递: shopDefaults.shipping ?? defaults['快递'],
|
快递: shopDefaults.shipping ?? defaults['快递'],
|
||||||
};
|
};
|
||||||
const packagingPayer =
|
const packagingPayer =
|
||||||
['owner', 'assistant', 'assistant2'].includes(shopDefaults.packagingPayer) ||
|
typeof shopDefaults.packagingPayer === 'string' &&
|
||||||
/^staff_[a-f0-9-]{36}$/.test(shopDefaults.packagingPayer)
|
(['owner', 'assistant', 'assistant2'].includes(shopDefaults.packagingPayer) ||
|
||||||
|
/^staff_[a-f0-9-]{36}$/.test(shopDefaults.packagingPayer))
|
||||||
? shopDefaults.packagingPayer
|
? shopDefaults.packagingPayer
|
||||||
: 'owner';
|
: 'owner';
|
||||||
|
/** @type {FeeItem<string|Amount>[]} */
|
||||||
const remaining = existing.map(r => ({ ...r })),
|
const remaining = existing.map(r => ({ ...r })),
|
||||||
linked = [];
|
linked = /** @type {FeeItem<string|Amount>[]} */ ([]);
|
||||||
for (const [index, line] of lines.entries())
|
for (const [index, line] of lines.entries())
|
||||||
for (const charge of line.charges || []) {
|
for (const charge of line.charges || []) {
|
||||||
const name = String(charge.name || '').trim();
|
const name = String(charge.name || '').trim();
|
||||||
@@ -280,5 +340,5 @@
|
|||||||
checkboxFees,
|
checkboxFees,
|
||||||
};
|
};
|
||||||
if (typeof module === 'object' && module.exports) module.exports = api;
|
if (typeof module === 'object' && module.exports) module.exports = api;
|
||||||
else root.FeeEstimates = api;
|
else Object.assign(root, { FeeEstimates: api });
|
||||||
})(typeof globalThis === 'object' ? globalThis : this);
|
})(typeof globalThis === 'object' ? globalThis : this);
|
||||||
@@ -86,5 +86,5 @@
|
|||||||
accountIdentity,
|
accountIdentity,
|
||||||
};
|
};
|
||||||
if (typeof module === 'object' && module.exports) module.exports = api;
|
if (typeof module === 'object' && module.exports) module.exports = api;
|
||||||
else root.LedgerValues = api;
|
else Object.assign(root, { LedgerValues: api });
|
||||||
})(typeof globalThis === 'object' ? globalThis : this);
|
})(typeof globalThis === 'object' ? globalThis : this);
|
||||||
+291
-265
@@ -7,281 +7,307 @@
|
|||||||
);
|
);
|
||||||
if (typeof module === 'object' && module.exports) module.exports = api;
|
if (typeof module === 'object' && module.exports) module.exports = api;
|
||||||
else root.OrderCopy = api;
|
else root.OrderCopy = api;
|
||||||
})(typeof globalThis === 'object' ? globalThis : this, function (Fees, Cards) {
|
})(
|
||||||
const money = value => (value == null ? '' : (value / 100).toFixed(2));
|
typeof globalThis === 'object' ? globalThis : /** @type {typeof globalThis} */ (/** @type {unknown} */ (this)),
|
||||||
const nonblank = value => value != null && String(value).trim() !== '';
|
/** @param {typeof import('./fee-estimates')} Fees @param {typeof import('./credit-card-fees')} Cards */ function (
|
||||||
const normalizeAccount = account =>
|
Fees,
|
||||||
Cards?.normalizeAccount
|
Cards,
|
||||||
? Cards.normalizeAccount(account)
|
) {
|
||||||
: ['助理信用卡', '助理1信用卡', '助理2信用卡', '麦麦信用卡'].includes(account)
|
/** @param {number|null|undefined} value */
|
||||||
? '麦麦信用卡'
|
const money = value => (value == null ? '' : (value / 100).toFixed(2));
|
||||||
: account;
|
/** @param {unknown} value */
|
||||||
const cardFee = item => item?.system === 'credit_card' || String(item?.key || '').startsWith('card_fee:');
|
const nonblank = value => value != null && String(value).trim() !== '';
|
||||||
function inputs(order) {
|
/** @param {string} account */
|
||||||
return {
|
const normalizeAccount = account =>
|
||||||
...order,
|
Cards?.normalizeAccount
|
||||||
rounding_mode: order.rounding_mode || 'cent',
|
? Cards.normalizeAccount(account)
|
||||||
discount: money(order.discount),
|
: ['助理信用卡', '助理1信用卡', '助理2信用卡', '麦麦信用卡'].includes(account)
|
||||||
fee_items: (order.fee_items || []).map(item => ({ ...item, amount: money(item.amount) })),
|
? '麦麦信用卡'
|
||||||
lines: order.lines.map(line => ({
|
: account;
|
||||||
...line,
|
/** @param {{system?:string;key?:string}} item */
|
||||||
quantity: line.unit === 'g' ? (line.quantity / 1000).toFixed(3) : line.quantity,
|
const cardFee = item => item?.system === 'credit_card' || String(item?.key || '').startsWith('card_fee:');
|
||||||
sale: money(line.sale),
|
/** @param {import('../web/src/shared/orderPresets').CopySource} order */
|
||||||
baseSale: money(line.baseSale ?? line.sale),
|
function inputs(order) {
|
||||||
cost: money(line.cost),
|
return {
|
||||||
costMaterial:
|
...order,
|
||||||
line.costMaterial?.mode === 'pool'
|
rounding_mode: order.rounding_mode || 'cent',
|
||||||
? { ...line.costMaterial }
|
discount: money(order.discount),
|
||||||
: {
|
fee_items: (order.fee_items || []).map(item => ({ ...item, amount: money(item.amount) })),
|
||||||
mode:
|
lines: order.lines.map(line => ({
|
||||||
line.costMaterial?.mode ||
|
...line,
|
||||||
((line.unit || 'g') === 'g' && line.costParts?.material == null ? 'gram' : 'total'),
|
quantity: line.unit === 'g' ? (line.quantity / 1000).toFixed(3) : line.quantity,
|
||||||
...(line.costMaterial?.mode === 'gram' ? { rate: money(line.costMaterial.rate) } : {}),
|
sale: money(line.sale),
|
||||||
},
|
baseSale: money(line.baseSale ?? line.sale),
|
||||||
costLabor: { mode: line.costLabor?.mode || 'total', rate: money(line.costLabor?.rate) },
|
cost: money(line.cost),
|
||||||
charges: (line.charges || []).map(charge => ({ ...charge, amount: money(charge.amount) })),
|
costMaterial:
|
||||||
...(line.pricingMode === 'auto' ? { goldPrice: money(line.goldPrice), laborRate: money(line.laborRate) } : {}),
|
line.costMaterial?.mode === 'pool'
|
||||||
...(line.costParts
|
? { ...line.costMaterial }
|
||||||
? { costParts: Object.fromEntries(Object.entries(line.costParts).map(([key, value]) => [key, money(value)])) }
|
: {
|
||||||
: {}),
|
mode:
|
||||||
})),
|
line.costMaterial?.mode ||
|
||||||
};
|
((line.unit || 'g') === 'g' && line.costParts?.material == null ? 'gram' : 'total'),
|
||||||
}
|
...(line.costMaterial?.mode === 'gram' ? { rate: money(line.costMaterial.rate) } : {}),
|
||||||
function copyFees(order, lines, chargeIds, newId) {
|
},
|
||||||
const corrected = new Set((order.corrections || []).filter(row => row.type === 'expense').map(row => row.target));
|
costLabor: { mode: line.costLabor?.mode || 'total', rate: money(line.costLabor?.rate) },
|
||||||
const cardExpenseIds = new Set(
|
charges: (line.charges || []).map(charge => ({ ...charge, amount: money(charge.amount) })),
|
||||||
order.fee_items
|
...(line.pricingMode === 'auto'
|
||||||
.filter(cardFee)
|
? { goldPrice: money(line.goldPrice), laborRate: money(line.laborRate) }
|
||||||
.map(fee => fee.expense_id)
|
: {}),
|
||||||
.filter(Boolean),
|
...(line.costParts
|
||||||
);
|
? {
|
||||||
const positives = order.expenses.filter(
|
costParts: Object.fromEntries(
|
||||||
row =>
|
Object.entries(line.costParts).map(([key, value]) => [key, money(value)]),
|
||||||
row.amount > 0 &&
|
),
|
||||||
!String(row.note || '').startsWith('更正冲回:') &&
|
}
|
||||||
!cardFee(row) &&
|
: {}),
|
||||||
!cardExpenseIds.has(row.id),
|
})),
|
||||||
);
|
};
|
||||||
const active = positives.filter(row => !corrected.has(row.id)),
|
}
|
||||||
matched = new Set(),
|
/** @param {import('../web/src/shared/orderPresets').CopySource} order @param {import('../web/src/shared/orderPresets').DraftProduct[]} lines @param {Map<string,string>} chargeIds @param {()=>string} newId */
|
||||||
used = new Set(),
|
function copyFees(order, lines, chargeIds, newId) {
|
||||||
items = [];
|
const corrected = new Set((order.corrections || []).filter(row => row.type === 'expense').map(row => row.target));
|
||||||
const pending = new Set((order.pendingFees || []).map(item => item.key));
|
const cardExpenseIds = new Set(
|
||||||
const same = (expense, fee) =>
|
order.fee_items
|
||||||
expense.amount === fee.amount &&
|
.filter(cardFee)
|
||||||
expense.payer === fee.payer &&
|
.map(fee => fee.expense_id)
|
||||||
Fees.normalize(expense.note) === Fees.normalize(fee.note);
|
.filter(Boolean),
|
||||||
for (const fee of order.fee_items) {
|
);
|
||||||
if (cardFee(fee) || (fee.expense_id && cardExpenseIds.has(fee.expense_id))) continue;
|
const positives = order.expenses.filter(
|
||||||
const linked = chargeIds.get(String(fee.key).replace(/^charge:/, ''));
|
row =>
|
||||||
const key = linked ? 'charge:' + linked : fee.key === 'shipping' ? 'shipping' : 'manual:' + newId();
|
row.amount > 0 &&
|
||||||
let amount = fee.amount,
|
!String(row.note || '').startsWith('更正冲回:') &&
|
||||||
payer = fee.payer;
|
!cardFee(row) &&
|
||||||
// 已入账模板仍保留旧金额;实际流水和更正结果才是当前支出的依据。
|
!cardExpenseIds.has(row.id),
|
||||||
if (fee.status !== 'estimated' && !pending.has(fee.key)) {
|
);
|
||||||
const source = positives.find(expense => !matched.has(expense.id) && same(expense, fee));
|
const active = positives.filter(row => !corrected.has(row.id)),
|
||||||
if (source) {
|
matched = new Set(),
|
||||||
matched.add(source.id);
|
used = new Set(),
|
||||||
if (corrected.has(source.id)) amount = 0;
|
items = /** @type {import('../web/src/shared/orderPresets').TemplateFee[]} */ ([]);
|
||||||
else used.add(source.id);
|
const pending = new Set((order.pendingFees || []).map(item => item.key));
|
||||||
} else amount = 0;
|
/** @param {import('../web/src/shared/orderPresets').Expense} expense @param {import('../web/src/shared/orderPresets').SavedFee} fee */
|
||||||
|
const same = (expense, fee) =>
|
||||||
|
expense.amount === fee.amount &&
|
||||||
|
expense.payer === fee.payer &&
|
||||||
|
Fees.normalize(expense.note) === Fees.normalize(fee.note);
|
||||||
|
for (const fee of order.fee_items) {
|
||||||
|
if (cardFee(fee) || (fee.expense_id && cardExpenseIds.has(fee.expense_id))) continue;
|
||||||
|
const linked = chargeIds.get(String(fee.key).replace(/^charge:/, ''));
|
||||||
|
const key = linked ? 'charge:' + linked : fee.key === 'shipping' ? 'shipping' : 'manual:' + newId();
|
||||||
|
let amount = fee.amount,
|
||||||
|
payer = fee.payer;
|
||||||
|
// 已入账模板仍保留旧金额;实际流水和更正结果才是当前支出的依据。
|
||||||
|
if (fee.status !== 'estimated' && !pending.has(fee.key)) {
|
||||||
|
const source = positives.find(expense => !matched.has(expense.id) && same(expense, fee));
|
||||||
|
if (source) {
|
||||||
|
matched.add(source.id);
|
||||||
|
if (corrected.has(source.id)) amount = 0;
|
||||||
|
else used.add(source.id);
|
||||||
|
} else amount = 0;
|
||||||
|
}
|
||||||
|
items.push({
|
||||||
|
key,
|
||||||
|
note: fee.note,
|
||||||
|
amount: money(amount),
|
||||||
|
payer,
|
||||||
|
status: 'estimated',
|
||||||
|
edited: true,
|
||||||
|
...(linked ? { sourceName: fee.sourceName || fee.note } : {}),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
items.push({
|
for (const expense of active) {
|
||||||
key,
|
if (used.has(expense.id)) continue;
|
||||||
note: fee.note,
|
/** @type {string} */
|
||||||
amount: money(amount),
|
const key =
|
||||||
payer,
|
Fees.normalize(expense.note) === '快递' && !items.some(item => item.key === 'shipping')
|
||||||
status: 'estimated',
|
? 'shipping'
|
||||||
edited: true,
|
: 'manual:' + newId();
|
||||||
...(linked ? { sourceName: fee.sourceName || fee.note } : {}),
|
items.push({
|
||||||
});
|
key,
|
||||||
}
|
note: expense.note,
|
||||||
for (const expense of active) {
|
amount: money(expense.amount),
|
||||||
if (used.has(expense.id)) continue;
|
payer: expense.payer,
|
||||||
const key =
|
status: 'estimated',
|
||||||
Fees.normalize(expense.note) === '快递' && !items.some(item => item.key === 'shipping')
|
edited: true,
|
||||||
? 'shipping'
|
});
|
||||||
: 'manual:' + newId();
|
}
|
||||||
items.push({
|
const completed = ['delivered', 'returned', 'cancelled'].includes(order.status);
|
||||||
key,
|
for (const [index, line] of lines.entries())
|
||||||
note: expense.note,
|
for (const charge of line.charges || []) {
|
||||||
amount: money(expense.amount),
|
if (charge.costRemoved === true) continue;
|
||||||
payer: expense.payer,
|
const shipping = Fees.normalize(charge.name) === '快递',
|
||||||
status: 'estimated',
|
key = shipping ? 'shipping' : 'charge:' + charge.id;
|
||||||
edited: true,
|
if (items.some(item => item.key === key)) continue;
|
||||||
});
|
const found = items.find(
|
||||||
}
|
item => item.key.startsWith('manual:') && Fees.normalize(item.note) === Fees.normalize(charge.name),
|
||||||
const completed = ['delivered', 'returned', 'cancelled'].includes(order.status);
|
);
|
||||||
for (const [index, line] of lines.entries())
|
const item = found || {
|
||||||
for (const charge of line.charges) {
|
|
||||||
if (charge.costRemoved === true) continue;
|
|
||||||
const shipping = Fees.normalize(charge.name) === '快递',
|
|
||||||
key = shipping ? 'shipping' : 'charge:' + charge.id;
|
|
||||||
if (items.some(item => item.key === key)) continue;
|
|
||||||
const found = items.find(
|
|
||||||
item => item.key.startsWith('manual:') && Fees.normalize(item.note) === Fees.normalize(charge.name),
|
|
||||||
);
|
|
||||||
if (found) found.key = key;
|
|
||||||
else
|
|
||||||
items.push({
|
|
||||||
key,
|
key,
|
||||||
note: shipping ? '快递费' : charge.name,
|
note: shipping ? '快递费' : charge.name,
|
||||||
amount: completed ? '0.00' : '',
|
amount: completed ? '0.00' : '',
|
||||||
payer: Fees.normalize(charge.name) === '包装' ? 'owner' : 'assistant',
|
payer: Fees.normalize(charge.name) === '包装' ? 'owner' : 'assistant',
|
||||||
status: 'estimated',
|
status: 'estimated',
|
||||||
edited: true,
|
edited: true,
|
||||||
});
|
|
||||||
if (!shipping)
|
|
||||||
Object.assign(
|
|
||||||
items.find(item => item.key === key),
|
|
||||||
{ sourceName: charge.name, lineNumber: index + 1 },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
// 所有项都标记手填,后续同步项目名称时不重新套用默认成本。
|
|
||||||
return Fees.sync(items, lines);
|
|
||||||
}
|
|
||||||
function fromOrder(order, { today, newId = () => globalThis.crypto.randomUUID() } = {}) {
|
|
||||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(today || '')) throw new Error('未取得系统日期,请刷新后再复制。');
|
|
||||||
if (!order || !Array.isArray(order.lines) || !Array.isArray(order.fee_items) || !Array.isArray(order.expenses))
|
|
||||||
throw new Error('订单详情未完整返回,请重新读取后再复制。');
|
|
||||||
const source = inputs(order),
|
|
||||||
chargeIds = new Map(),
|
|
||||||
locked = !!order.price_lock_id || order.lines.some(line => line.materialAllocations?.length);
|
|
||||||
const lines = source.lines.map(line => {
|
|
||||||
const result = Object.fromEntries(
|
|
||||||
[
|
|
||||||
'name',
|
|
||||||
'nameType',
|
|
||||||
'customName',
|
|
||||||
'unit',
|
|
||||||
'quantity',
|
|
||||||
'pocket',
|
|
||||||
'stockCount',
|
|
||||||
'payer',
|
|
||||||
'pricingMode',
|
|
||||||
'goldPrice',
|
|
||||||
'laborMode',
|
|
||||||
'laborRate',
|
|
||||||
'pieces',
|
|
||||||
'priceNote',
|
|
||||||
'sale',
|
|
||||||
'baseSale',
|
|
||||||
]
|
|
||||||
.filter(key => Object.hasOwn(line, key))
|
|
||||||
.map(key => [key, line[key]]),
|
|
||||||
);
|
|
||||||
result.charges = line.charges.map(charge => {
|
|
||||||
const id = newId();
|
|
||||||
if (charge.id) chargeIds.set(charge.id, id);
|
|
||||||
return {
|
|
||||||
id,
|
|
||||||
name: charge.name,
|
|
||||||
amount: charge.amount,
|
|
||||||
...(charge.costRemoved === true ? { costRemoved: true } : {}),
|
|
||||||
};
|
|
||||||
});
|
|
||||||
if (line.costParts) {
|
|
||||||
result.costParts = { ...line.costParts };
|
|
||||||
result.costMaterial = { ...line.costMaterial };
|
|
||||||
result.costLabor = { ...line.costLabor };
|
|
||||||
result.costPayers = {
|
|
||||||
material: line.costPayers?.material ?? line.payer ?? 'owner',
|
|
||||||
labor: line.costPayers?.labor ?? line.payer ?? 'owner',
|
|
||||||
};
|
|
||||||
if (line.costMaterial?.mode === 'pool') {
|
|
||||||
// 同日池随新业务日期走;已经跨日选用的旧池保留选择,耗用快照必须重读。
|
|
||||||
const defaultDate = line.costMaterial.poolId === order.date,
|
|
||||||
poolId = defaultDate ? today : line.costMaterial.poolId;
|
|
||||||
result.costMaterial = { mode: 'pool', poolId };
|
|
||||||
result.costParts.material = '';
|
|
||||||
result.materialPoolDraft = {
|
|
||||||
poolId,
|
|
||||||
defaultDate,
|
|
||||||
manual: { mode: 'gram', rate: '', total: '', originalTotal: '', payer: result.costPayers.material },
|
|
||||||
};
|
};
|
||||||
|
item.key = key;
|
||||||
|
if (!found) items.push(item);
|
||||||
|
if (!shipping) Object.assign(item, { sourceName: charge.name, lineNumber: index + 1 });
|
||||||
}
|
}
|
||||||
if (locked) {
|
// 所有项都标记手填,后续同步项目名称时不重新套用默认成本。
|
||||||
result.costParts.material = '';
|
return Fees.sync(items, lines);
|
||||||
result.costMaterial = { mode: 'total' };
|
}
|
||||||
result.costPayers.material = '';
|
/** @param {import('../web/src/shared/orderPresets').CopySource} order @param {import('../web/src/shared/orderPresets').TemplateOptions} [options] */
|
||||||
delete result.materialPoolDraft;
|
function fromOrder(order, { today, newId = () => globalThis.crypto.randomUUID() } = {}) {
|
||||||
}
|
if (!/^\d{4}-\d{2}-\d{2}$/.test(today || '')) throw new Error('未取得系统日期,请刷新后再复制。');
|
||||||
} else result.cost = line.cost;
|
if (!order || !Array.isArray(order.lines) || !Array.isArray(order.fee_items) || !Array.isArray(order.expenses))
|
||||||
return result;
|
throw new Error('订单详情未完整返回,请重新读取后再复制。');
|
||||||
});
|
const source = inputs(order),
|
||||||
return {
|
chargeIds = new Map(),
|
||||||
date: today,
|
locked = !!order.price_lock_id || order.lines.some(line => line.materialAllocations?.length);
|
||||||
fees_date: today,
|
const lines = source.lines.map(line => {
|
||||||
customer: '',
|
/** @type {import('../web/src/shared/orderPresets').DraftProduct} */
|
||||||
salesperson: source.salesperson || '',
|
const result = Object.fromEntries(
|
||||||
payment_account: normalizeAccount(source.payment_account || '助理微信'),
|
/** @type {const} */ ([
|
||||||
discount: source.discount,
|
'name',
|
||||||
note: locked
|
'nameType',
|
||||||
? String(source.note || '').replace(/;?锁价单 [^;]*;按原锁定金价 [^;]*元\/克结算$/, '')
|
'customName',
|
||||||
: source.note || '',
|
'unit',
|
||||||
rounding_mode: 'yuan',
|
'quantity',
|
||||||
copy_kind: locked ? 'price-lock' : 'ordinary',
|
'pocket',
|
||||||
fee_auto_initialized: true,
|
'stockCount',
|
||||||
lines,
|
'payer',
|
||||||
fee_items: copyFees(order, lines, chargeIds, newId),
|
'pricingMode',
|
||||||
};
|
'goldPrice',
|
||||||
}
|
'laborMode',
|
||||||
function hasDraftContent(draft, { today, salesperson } = {}) {
|
'laborRate',
|
||||||
if (!draft || typeof draft !== 'object' || !Array.isArray(draft.lines)) return !!draft;
|
'pieces',
|
||||||
if (
|
'priceNote',
|
||||||
draft.id ||
|
'sale',
|
||||||
draft.copy_kind ||
|
'baseSale',
|
||||||
nonblank(draft.customer) ||
|
])
|
||||||
nonblank(draft.note) ||
|
.filter(key => Object.hasOwn(line, key))
|
||||||
nonblank(draft.internal_note) ||
|
.map(key => [key, line[key]]),
|
||||||
Number(draft.discount) ||
|
);
|
||||||
(draft.date && today && draft.date !== today) ||
|
result.charges = line.charges.map(charge => {
|
||||||
(draft.salesperson && salesperson && draft.salesperson !== salesperson) ||
|
const id = newId();
|
||||||
(draft.payment_account && draft.payment_account !== '助理微信')
|
if (charge.id) chargeIds.set(charge.id, id);
|
||||||
)
|
return {
|
||||||
return true;
|
id,
|
||||||
if (
|
name: charge.name,
|
||||||
(draft.fee_items || []).some(
|
amount: charge.amount,
|
||||||
item =>
|
...(charge.costRemoved === true ? { costRemoved: true } : {}),
|
||||||
item.key !== 'shipping' ||
|
};
|
||||||
item.edited ||
|
});
|
||||||
item.status !== 'estimated' ||
|
if (line.costParts) {
|
||||||
Number(item.amount) !== 6 ||
|
result.costParts = { ...line.costParts };
|
||||||
item.payer !== 'assistant',
|
result.costMaterial = { ...line.costMaterial };
|
||||||
|
result.costLabor = { ...line.costLabor };
|
||||||
|
result.costPayers = {
|
||||||
|
material: line.costPayers?.material ?? line.payer ?? 'owner',
|
||||||
|
labor: line.costPayers?.labor ?? line.payer ?? 'owner',
|
||||||
|
};
|
||||||
|
if (line.costMaterial?.mode === 'pool') {
|
||||||
|
// 同日池随新业务日期走;已经跨日选用的旧池保留选择,耗用快照必须重读。
|
||||||
|
const defaultDate = result.costMaterial.poolId === order.date,
|
||||||
|
poolId = defaultDate ? today : result.costMaterial.poolId;
|
||||||
|
result.costMaterial = { mode: 'pool', poolId };
|
||||||
|
result.costParts.material = '';
|
||||||
|
result.materialPoolDraft = {
|
||||||
|
poolId,
|
||||||
|
defaultDate,
|
||||||
|
manual: { mode: 'gram', rate: '', total: '', originalTotal: '', payer: result.costPayers.material },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (locked) {
|
||||||
|
result.costParts.material = '';
|
||||||
|
result.costMaterial = { mode: 'total' };
|
||||||
|
result.costPayers.material = '';
|
||||||
|
delete result.materialPoolDraft;
|
||||||
|
}
|
||||||
|
} else result.cost = line.cost;
|
||||||
|
return result;
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
date: today,
|
||||||
|
fees_date: today,
|
||||||
|
customer: '',
|
||||||
|
salesperson: source.salesperson || '',
|
||||||
|
payment_account: normalizeAccount(source.payment_account || '助理微信'),
|
||||||
|
discount: source.discount,
|
||||||
|
note: locked
|
||||||
|
? String(source.note || '').replace(/;?锁价单 [^;]*;按原锁定金价 [^;]*元\/克结算$/, '')
|
||||||
|
: source.note || '',
|
||||||
|
rounding_mode: 'yuan',
|
||||||
|
copy_kind: locked ? 'price-lock' : 'ordinary',
|
||||||
|
fee_auto_initialized: true,
|
||||||
|
lines,
|
||||||
|
fee_items: copyFees(order, lines, chargeIds, newId),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
/** @param {import('../web/src/shared/orderPresets').CopyDraft|null} draft @param {{today?:string;salesperson?:string}} [options] */
|
||||||
|
function hasDraftContent(draft, { today, salesperson } = {}) {
|
||||||
|
if (!draft || typeof draft !== 'object' || !Array.isArray(draft.lines)) return !!draft;
|
||||||
|
if (
|
||||||
|
draft.id ||
|
||||||
|
draft.copy_kind ||
|
||||||
|
nonblank(draft.customer) ||
|
||||||
|
nonblank(draft.note) ||
|
||||||
|
nonblank(draft.internal_note) ||
|
||||||
|
Number(draft.discount) ||
|
||||||
|
(draft.date && today && draft.date !== today) ||
|
||||||
|
(draft.salesperson && salesperson && draft.salesperson !== salesperson) ||
|
||||||
|
(draft.payment_account && draft.payment_account !== '助理微信')
|
||||||
)
|
)
|
||||||
)
|
return true;
|
||||||
return true;
|
if (
|
||||||
return (
|
(draft.fee_items || []).some(
|
||||||
draft.lines.length !== 1 ||
|
item =>
|
||||||
draft.lines.some(line => {
|
item.key !== 'shipping' ||
|
||||||
if (
|
item.edited ||
|
||||||
line.charges?.length ||
|
item.status !== 'estimated' ||
|
||||||
(line.name && line.name !== '足金999') ||
|
Number(item.amount) !== 6 ||
|
||||||
line.customName ||
|
item.payer !== 'assistant',
|
||||||
(line.unit && line.unit !== 'g') ||
|
|
||||||
(line.pocket != null && line.pocket !== '现货') ||
|
|
||||||
(line.payer && line.payer !== 'owner') ||
|
|
||||||
line.costMaterial?.mode === 'pool'
|
|
||||||
)
|
)
|
||||||
return true;
|
)
|
||||||
if (
|
return true;
|
||||||
['quantity', 'stockCount', 'sale', 'baseSale', 'goldPrice', 'laborRate', 'priceNote', 'cost'].some(key =>
|
return (
|
||||||
nonblank(line[key]),
|
draft.lines.length !== 1 ||
|
||||||
|
draft.lines.some(line => {
|
||||||
|
if (
|
||||||
|
line.charges?.length ||
|
||||||
|
(line.name && line.name !== '足金999') ||
|
||||||
|
line.customName ||
|
||||||
|
(line.unit && line.unit !== 'g') ||
|
||||||
|
(line.pocket != null && line.pocket !== '现货') ||
|
||||||
|
(line.payer && line.payer !== 'owner') ||
|
||||||
|
line.costMaterial?.mode === 'pool'
|
||||||
)
|
)
|
||||||
)
|
return true;
|
||||||
return true;
|
if (
|
||||||
if (
|
/** @type {const} */ ([
|
||||||
['material', 'labor'].some(
|
'quantity',
|
||||||
key =>
|
'stockCount',
|
||||||
nonblank(line.costParts?.[key]) ||
|
'sale',
|
||||||
nonblank(line[key === 'material' ? 'costMaterial' : 'costLabor']?.rate) ||
|
'baseSale',
|
||||||
(line.costPayers?.[key] && line.costPayers[key] !== 'owner'),
|
'goldPrice',
|
||||||
|
'laborRate',
|
||||||
|
'priceNote',
|
||||||
|
'cost',
|
||||||
|
]).some(key => nonblank(line[key]))
|
||||||
)
|
)
|
||||||
)
|
return true;
|
||||||
return true;
|
if (
|
||||||
return ['accessories', 'other'].some(key => Number(line.costParts?.[key]));
|
['material', 'labor'].some(
|
||||||
})
|
key =>
|
||||||
);
|
nonblank(line.costParts?.[key]) ||
|
||||||
}
|
nonblank(line[key === 'material' ? 'costMaterial' : 'costLabor']?.rate) ||
|
||||||
return { inputs, fromOrder, hasDraftContent };
|
(line.costPayers?.[key] && line.costPayers[key] !== 'owner'),
|
||||||
});
|
)
|
||||||
|
)
|
||||||
|
return true;
|
||||||
|
return ['accessories', 'other'].some(key => Number(line.costParts?.[key]));
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return { inputs, fromOrder, hasDraftContent };
|
||||||
|
},
|
||||||
|
);
|
||||||
+308
-113
File diff suppressed because it is too large.
Load diff
@@ -1,13 +1,16 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
// 只接受约定的销售公式,不执行输入代码。金额复用开单的整数计算。
|
// 只接受约定的销售公式,不执行输入代码。金额复用开单的整数计算。
|
||||||
(function (root) {
|
(function (root) {
|
||||||
|
/** @type {Pick<import('../web/src/shared/types').LedgerCalcApi, 'sale'|'cents'|'orderTotal'>} */
|
||||||
const Calc = typeof module === 'object' && module.exports ? require('./calculations') : root.LedgerCalc;
|
const Calc = typeof module === 'object' && module.exports ? require('./calculations') : root.LedgerCalc;
|
||||||
|
/** @param {string} value */
|
||||||
const decimal = value => {
|
const decimal = value => {
|
||||||
const [whole, fraction = ''] = value.split('.');
|
const [whole, fraction = ''] = value.split('.');
|
||||||
return (
|
return (
|
||||||
(whole.replace(/^0+(?=\d)/, '') || '0') + (fraction.replace(/0+$/, '') ? '.' + fraction.replace(/0+$/, '') : '')
|
(whole.replace(/^0+(?=\d)/, '') || '0') + (fraction.replace(/0+$/, '') ? '.' + fraction.replace(/0+$/, '') : '')
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
/** @param {string} input */
|
||||||
const normalize = input =>
|
const normalize = input =>
|
||||||
input
|
input
|
||||||
.normalize('NFKC')
|
.normalize('NFKC')
|
||||||
@@ -22,7 +25,9 @@
|
|||||||
weight = number + '(?:克|g)?\\*';
|
weight = number + '(?:克|g)?\\*';
|
||||||
const gramPattern = new RegExp('^' + weight + '\\(' + number + '\\+' + number + '\\)' + extras + ending, 'i');
|
const gramPattern = new RegExp('^' + weight + '\\(' + number + '\\+' + number + '\\)' + extras + ending, 'i');
|
||||||
const piecePattern = new RegExp('^' + weight + number + '\\+' + number + extras + ending, 'i');
|
const piecePattern = new RegExp('^' + weight + number + '\\+' + number + extras + ending, 'i');
|
||||||
|
/** @param {string} value */
|
||||||
const money = value => Calc.cents(decimal(value), '公式金额');
|
const money = value => Calc.cents(decimal(value), '公式金额');
|
||||||
|
/** @param {string} input @param {{roundingMode?: 'cent'|'yuan'}} [options] */
|
||||||
function parse(input, { roundingMode = 'yuan' } = {}) {
|
function parse(input, { roundingMode = 'yuan' } = {}) {
|
||||||
if (typeof input !== 'string' || input.length > 300) throw new Error('每行请填写300字以内的销售公式');
|
if (typeof input !== 'string' || input.length > 300) throw new Error('每行请填写300字以内的销售公式');
|
||||||
const formula = normalize(input),
|
const formula = normalize(input),
|
||||||
@@ -32,6 +37,7 @@
|
|||||||
const [, weight, gold, labor, extra, stated] = match;
|
const [, weight, gold, labor, extra, stated] = match;
|
||||||
const quantities = extra ? extra.slice(1).split('+') : [];
|
const quantities = extra ? extra.slice(1).split('+') : [];
|
||||||
if (quantities.length > 100) throw new Error('每件商品最多100项附加费');
|
if (quantities.length > 100) throw new Error('每件商品最多100项附加费');
|
||||||
|
/** @type {import('../web/src/shared/orderEntryTypes').FormulaLine} */
|
||||||
const line = {
|
const line = {
|
||||||
unit: 'g',
|
unit: 'g',
|
||||||
pricingMode: 'auto',
|
pricingMode: 'auto',
|
||||||
@@ -56,6 +62,7 @@
|
|||||||
mismatch: statedTotal !== null && statedTotal !== total.total,
|
mismatch: statedTotal !== null && statedTotal !== total.total,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
/** @param {string} input @param {{roundingMode?: 'cent'|'yuan'}} [options] */
|
||||||
function parseBatch(input, { roundingMode = 'yuan' } = {}) {
|
function parseBatch(input, { roundingMode = 'yuan' } = {}) {
|
||||||
if (typeof input !== 'string' || input.length > 18000) throw new Error('请填写18000字以内的公式,每件商品一行');
|
if (typeof input !== 'string' || input.length > 18000) throw new Error('请填写18000字以内的公式,每件商品一行');
|
||||||
const rows = input
|
const rows = input
|
||||||
@@ -63,10 +70,11 @@
|
|||||||
.map(value => value.trim())
|
.map(value => value.trim())
|
||||||
.filter(Boolean);
|
.filter(Boolean);
|
||||||
if (!rows.length || rows.length > 61) throw new Error('请填写1~60件商品公式,可在最后另写一行合计');
|
if (!rows.length || rows.length > 61) throw new Error('请填写1~60件商品公式,可在最后另写一行合计');
|
||||||
|
/** @type {ReturnType<typeof parse>[]} */
|
||||||
const items = [],
|
const items = [],
|
||||||
warnings = [];
|
warnings = [];
|
||||||
let summary = null;
|
let summary = null;
|
||||||
rows.forEach((raw, index) => {
|
for (const [index, raw] of rows.entries()) {
|
||||||
const normalized = normalize(raw).replace(/^(?:合计|总价|总计|总金额):?/, '');
|
const normalized = normalize(raw).replace(/^(?:合计|总价|总计|总金额):?/, '');
|
||||||
const sumMatch = normalized.match(/^(\d+(?:\.\d+)?(?:\+\d+(?:\.\d+)?)+)(?:=(\d+(?:\.\d+)?))?$/);
|
const sumMatch = normalized.match(/^(\d+(?:\.\d+)?(?:\+\d+(?:\.\d+)?)+)(?:=(\d+(?:\.\d+)?))?$/);
|
||||||
if (sumMatch) {
|
if (sumMatch) {
|
||||||
@@ -87,10 +95,10 @@
|
|||||||
try {
|
try {
|
||||||
item = parse(raw, { roundingMode });
|
item = parse(raw, { roundingMode });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
throw new Error('第' + (index + 1) + '行:' + err.message);
|
throw new Error('第' + (index + 1) + '行:' + (err instanceof Error ? err.message : String(err)));
|
||||||
}
|
}
|
||||||
items.push(item);
|
items.push(item);
|
||||||
if (item.mismatch)
|
if (item.mismatch && item.statedTotal !== null)
|
||||||
warnings.push(
|
warnings.push(
|
||||||
'商品 ' +
|
'商品 ' +
|
||||||
items.length +
|
items.length +
|
||||||
@@ -101,7 +109,7 @@
|
|||||||
'元。',
|
'元。',
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
});
|
}
|
||||||
const total = Calc.orderTotal(
|
const total = Calc.orderTotal(
|
||||||
items.map(item => item.subtotal),
|
items.map(item => item.subtotal),
|
||||||
0,
|
0,
|
||||||
@@ -130,4 +138,4 @@
|
|||||||
const api = { parse, parseBatch };
|
const api = { parse, parseBatch };
|
||||||
if (typeof module === 'object' && module.exports) module.exports = api;
|
if (typeof module === 'object' && module.exports) module.exports = api;
|
||||||
else root.OrderFormula = api;
|
else root.OrderFormula = api;
|
||||||
})(typeof globalThis === 'object' ? globalThis : this);
|
})(typeof globalThis === 'object' ? globalThis : /** @type {typeof globalThis} */ (/** @type {unknown} */ (this)));
|
||||||
+321
-281
@@ -7,288 +7,328 @@
|
|||||||
);
|
);
|
||||||
if (typeof module === 'object' && module.exports) module.exports = api;
|
if (typeof module === 'object' && module.exports) module.exports = api;
|
||||||
else root.OrderTemplates = api;
|
else root.OrderTemplates = api;
|
||||||
})(typeof globalThis === 'object' ? globalThis : this, function (Fees, Cards) {
|
})(
|
||||||
const products = ['足金999', '足银999', '纯银925'],
|
typeof globalThis === 'object' ? globalThis : /** @type {typeof globalThis} */ (/** @type {unknown} */ (this)),
|
||||||
charges = ['编绳', '证书', '包装', '快递', '附加费'];
|
/** @param {typeof import('./fee-estimates')} Fees @param {typeof import('./credit-card-fees')} Cards */ function (
|
||||||
const pockets = ['', '现货', '金料', '找金', '回收旧料', '君宝汇'];
|
Fees,
|
||||||
const accounts = [
|
Cards,
|
||||||
'助理2微信',
|
) {
|
||||||
'助理2支付宝',
|
const products = ['足金999', '足银999', '纯银925'],
|
||||||
'助理2现金',
|
charges = ['编绳', '证书', '包装', '快递', '附加费'];
|
||||||
'助理2信用卡',
|
const pockets = ['', '现货', '金料', '找金', '回收旧料', '君宝汇'];
|
||||||
'助理微信',
|
const accounts = [
|
||||||
'助理支付宝',
|
'助理2微信',
|
||||||
'助理现金',
|
'助理2支付宝',
|
||||||
'助理信用卡',
|
'助理2现金',
|
||||||
'麦麦微信',
|
'助理2信用卡',
|
||||||
'麦麦支付宝',
|
'助理微信',
|
||||||
'麦麦现金',
|
'助理支付宝',
|
||||||
'麦麦信用卡',
|
'助理现金',
|
||||||
];
|
'助理信用卡',
|
||||||
const normalizeAccount = account =>
|
'麦麦微信',
|
||||||
Cards?.normalizeAccount
|
'麦麦支付宝',
|
||||||
? Cards.normalizeAccount(account)
|
'麦麦现金',
|
||||||
: ['助理信用卡', '助理1信用卡', '助理2信用卡', '麦麦信用卡'].includes(account)
|
'麦麦信用卡',
|
||||||
? '麦麦信用卡'
|
];
|
||||||
: account;
|
/** @param {string} account */
|
||||||
const cardFee = item => item?.system === 'credit_card' || String(item?.key || '').startsWith('card_fee:');
|
const normalizeAccount = account =>
|
||||||
const uuid = /^[a-f0-9-]{36}$/;
|
Cards?.normalizeAccount
|
||||||
function object(value, name) {
|
? Cards.normalizeAccount(account)
|
||||||
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(name + '格式无效');
|
: ['助理信用卡', '助理1信用卡', '助理2信用卡', '麦麦信用卡'].includes(account)
|
||||||
return value;
|
? '麦麦信用卡'
|
||||||
}
|
: account;
|
||||||
function string(value, name, max = 100) {
|
/** @param {{system?:unknown;key?:unknown}} item */
|
||||||
if (value != null && !['string', 'number'].includes(typeof value)) throw new Error(name + '格式无效');
|
const cardFee = item => item?.system === 'credit_card' || String(item?.key || '').startsWith('card_fee:');
|
||||||
const result = String(value ?? '').trim();
|
/** @param {unknown} value */
|
||||||
if (result.length > max) throw new Error(name + '最多填写' + max + '字');
|
const properties = value =>
|
||||||
return result;
|
value && typeof value === 'object' ? /** @type {Record<string,unknown>} */ (value) : {};
|
||||||
}
|
const uuid = /^[a-f0-9-]{36}$/;
|
||||||
function pick(value, values, name, fallback) {
|
/** @param {unknown} value @param {string} name */
|
||||||
const result = value ?? fallback;
|
function object(value, name) {
|
||||||
if (!values.includes(result)) throw new Error(name + '无效');
|
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(name + '格式无效');
|
||||||
return result;
|
return /** @type {Record<string,unknown>} */ (value);
|
||||||
}
|
}
|
||||||
function numeric(value, name, places = 2) {
|
/** @param {unknown} value @param {string} name */
|
||||||
const result = string(value, name, 24);
|
function string(value, name, max = 100) {
|
||||||
if (!result) return '';
|
if (value != null && !['string', 'number'].includes(typeof value)) throw new Error(name + '格式无效');
|
||||||
if (!new RegExp('^\\d+(?:\\.\\d{1,' + places + '})?$').test(result))
|
const result = String(value ?? '').trim();
|
||||||
throw new Error(name + '须为非负数字,最多' + places + '位小数');
|
if (result.length > max) throw new Error(name + '最多填写' + max + '字');
|
||||||
const [whole, fraction = ''] = result.split('.');
|
|
||||||
if (BigInt(whole) * 10n ** BigInt(places) + BigInt(fraction.padEnd(places, '0')) > 100000000000n)
|
|
||||||
throw new Error(name + '超出支持范围');
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
function count(value, name) {
|
|
||||||
const result = string(value, name, 12);
|
|
||||||
if (result && !/^\d+$/.test(result)) throw new Error(name + '须为非负整数');
|
|
||||||
if (Number(result) > 1000000000) throw new Error(name + '超出支持范围');
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
const validMember = value =>
|
|
||||||
['owner', 'assistant', 'assistant2'].includes(value) ||
|
|
||||||
/^staff_[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value);
|
|
||||||
function payer(value, fallback = 'owner') {
|
|
||||||
const result = value ?? fallback;
|
|
||||||
if (result !== '' && !validMember(result)) throw new Error('成本付款人无效');
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
function paymentAccount(value) {
|
|
||||||
const result = normalizeAccount(value ?? '助理微信');
|
|
||||||
if (
|
|
||||||
!accounts.includes(result) &&
|
|
||||||
!/^staff_[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}(微信|支付宝|现金)$/.test(result)
|
|
||||||
)
|
|
||||||
throw new Error('收款账户无效');
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
function manualMaterial(value = {}, fallback = {}) {
|
|
||||||
object(value, '备用料费');
|
|
||||||
return {
|
|
||||||
mode: pick(value.mode, ['gram', 'total'], '备用料费方式', fallback.mode || 'gram'),
|
|
||||||
rate: numeric(value.rate ?? fallback.rate, '备用进货料价'),
|
|
||||||
total: numeric(value.total ?? fallback.total, '备用料费合计'),
|
|
||||||
originalTotal: '',
|
|
||||||
payer: payer(value.payer, fallback.payer ?? 'owner'),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
function fromDraft(draft, { newId = () => globalThis.crypto.randomUUID(), pocketKeys = pockets } = {}) {
|
|
||||||
object(draft, '开单预设');
|
|
||||||
if (!Array.isArray(draft.lines) || !draft.lines.length || draft.lines.length > 60)
|
|
||||||
throw new Error('模板需要1~60行商品');
|
|
||||||
const ids = new Map(),
|
|
||||||
seen = new Set();
|
|
||||||
const lines = draft.lines.map(raw => {
|
|
||||||
const line = object(raw, '模板商品'),
|
|
||||||
unit = pick(line.unit, ['g', '件'], '商品单位', 'g');
|
|
||||||
const name = string(line.name, '商品名称', 60),
|
|
||||||
nameType = pick(
|
|
||||||
line.nameType,
|
|
||||||
[...products, '其他'],
|
|
||||||
'商品名称',
|
|
||||||
products.includes(name) ? name : name ? '其他' : '足金999',
|
|
||||||
);
|
|
||||||
const result = {
|
|
||||||
nameType,
|
|
||||||
customName: string(line.customName ?? (nameType === '其他' ? name : ''), '其他商品名称', 60),
|
|
||||||
unit,
|
|
||||||
quantity: unit === 'g' ? numeric(line.quantity, '商品克重', 3) : count(line.quantity, '商品件数'),
|
|
||||||
pocket:
|
|
||||||
unit === '件' || ['足银999', '纯银925'].includes(nameType)
|
|
||||||
? ''
|
|
||||||
: pick(line.pocket, ['', ...pocketKeys], '出库货盘', nameType === '足金999' ? '现货' : ''),
|
|
||||||
payer: payer(line.payer, 'owner'),
|
|
||||||
pricingMode:
|
|
||||||
unit === '件'
|
|
||||||
? 'manual'
|
|
||||||
: pick(line.pricingMode, ['auto', 'manual'], '计价方式', line.sale != null ? 'manual' : 'auto'),
|
|
||||||
goldPrice: numeric(line.goldPrice, '销售金价'),
|
|
||||||
laborMode: pick(line.laborMode, ['gram', 'piece'], '销售工费方式', 'gram'),
|
|
||||||
laborRate: numeric(line.laborRate, '销售工费'),
|
|
||||||
pieces: count(line.pieces ?? '1', '计工费件数'),
|
|
||||||
priceNote: string(line.priceNote, '销售单价说明', 100),
|
|
||||||
sale: numeric(line.sale, '本行销售额'),
|
|
||||||
baseSale: numeric(line.baseSale ?? line.sale, '商品基础金额'),
|
|
||||||
};
|
|
||||||
result.name = nameType === '其他' ? result.customName : nameType;
|
|
||||||
if (line.stockCount != null && String(line.stockCount).trim() !== '') {
|
|
||||||
result.stockCount = count(line.stockCount, '出库数量(对)');
|
|
||||||
if (Number(result.stockCount) < 1) throw new Error('出库数量(对)须为正整数,一对填1');
|
|
||||||
}
|
|
||||||
const rawCharges = line.charges ?? [];
|
|
||||||
if (!Array.isArray(rawCharges) || rawCharges.length > 100) throw new Error('每行最多填写100项附加项目');
|
|
||||||
result.charges = rawCharges.map(rawCharge => {
|
|
||||||
const c = object(rawCharge, '附加项目'),
|
|
||||||
old = string(c.id, '附加项目标识', 36);
|
|
||||||
if (old && (!uuid.test(old) || seen.has(old))) throw new Error('附加项目标识无效或重复');
|
|
||||||
if (old) seen.add(old);
|
|
||||||
const name = string(c.name, '附加项目名称', 40),
|
|
||||||
nameType = pick(
|
|
||||||
c.nameType,
|
|
||||||
[...charges, '其他'],
|
|
||||||
'附加项目',
|
|
||||||
charges.includes(name) ? name : name ? '其他' : '编绳',
|
|
||||||
);
|
|
||||||
if (c.costRemoved !== undefined && typeof c.costRemoved !== 'boolean') throw new Error('内部成本移除标记无效');
|
|
||||||
const id = newId();
|
|
||||||
if (old) ids.set(old, id);
|
|
||||||
const customName = string(c.customName ?? (nameType === '其他' ? name : ''), '附加项目名称', 40),
|
|
||||||
amount = numeric(c.amount, '附加金额');
|
|
||||||
const prices = {};
|
|
||||||
if (c.chargePrices != null) {
|
|
||||||
object(c.chargePrices, '附加项目预设报价');
|
|
||||||
for (const key of [...charges, '其他'])
|
|
||||||
if (Object.hasOwn(c.chargePrices, key)) prices[key] = numeric(c.chargePrices[key], '附加项目报价');
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
id,
|
|
||||||
nameType,
|
|
||||||
customName,
|
|
||||||
name: nameType === '其他' ? customName : nameType,
|
|
||||||
amount,
|
|
||||||
chargePrices: { ...prices, [nameType]: amount },
|
|
||||||
...(c.costRemoved === true ? { costRemoved: true } : {}),
|
|
||||||
};
|
|
||||||
});
|
|
||||||
if (line.costParts != null) {
|
|
||||||
object(line.costParts, '分项成本');
|
|
||||||
const parts = Object.fromEntries(
|
|
||||||
['material', 'labor', 'accessories', 'other'].map(key => [key, numeric(line.costParts[key], '货品成本')]),
|
|
||||||
);
|
|
||||||
const material = object(line.costMaterial ?? {}, '料费方式'),
|
|
||||||
labor = object(line.costLabor ?? {}, '进货工费方式');
|
|
||||||
const mode = pick(
|
|
||||||
material.mode,
|
|
||||||
['gram', 'total', 'pool'],
|
|
||||||
'进货料费方式',
|
|
||||||
unit === 'g' && parts.material === '' ? 'gram' : 'total',
|
|
||||||
);
|
|
||||||
result.costParts = parts;
|
|
||||||
result.costPayers = {
|
|
||||||
material: payer(line.costPayers?.material, result.payer),
|
|
||||||
labor: payer(line.costPayers?.labor, result.payer),
|
|
||||||
};
|
|
||||||
result.costMaterial = {
|
|
||||||
mode: unit === '件' ? 'total' : mode,
|
|
||||||
...(mode === 'gram' ? { rate: numeric(material.rate, '进货料价') } : {}),
|
|
||||||
};
|
|
||||||
result.costLabor = {
|
|
||||||
mode: unit === '件' ? 'total' : pick(labor.mode, ['gram', 'total'], '进货工费方式', 'total'),
|
|
||||||
rate: numeric(labor.rate, '进货克工费'),
|
|
||||||
};
|
|
||||||
if (result.costMaterial.mode === 'pool') {
|
|
||||||
if (['足银999', '纯银925'].includes(nameType)) throw new Error('银饰模板请手动填写料费');
|
|
||||||
parts.material = '';
|
|
||||||
result.materialPoolDraft = { defaultDate: true, manual: manualMaterial(line.materialPoolDraft?.manual) };
|
|
||||||
} else if (line.costMaterialDraft) {
|
|
||||||
const remembered = manualMaterial(line.costMaterialDraft, {
|
|
||||||
mode: result.costMaterial.mode,
|
|
||||||
rate: material.rate,
|
|
||||||
total: parts.material,
|
|
||||||
payer: result.costPayers.material,
|
|
||||||
});
|
|
||||||
result.costMaterialDraft = {
|
|
||||||
mode: remembered.mode,
|
|
||||||
rate: remembered.rate,
|
|
||||||
total: remembered.total,
|
|
||||||
originalTotal: '',
|
|
||||||
};
|
|
||||||
}
|
|
||||||
} else if (Object.hasOwn(line, 'cost')) result.cost = numeric(line.cost, '货品成本');
|
|
||||||
return result;
|
return result;
|
||||||
});
|
}
|
||||||
const fees = draft.fee_items ?? [];
|
/** @param {unknown} value @param {readonly string[]} values @param {string} name @param {unknown} fallback */
|
||||||
if (!Array.isArray(fees) || fees.length > 6100) throw new Error('模板费用项目过多');
|
function pick(value, values, name, fallback) {
|
||||||
const cardExpenseIds = new Set(
|
const result = value ?? fallback;
|
||||||
fees
|
if (typeof result !== 'string' || !values.includes(result)) throw new Error(name + '无效');
|
||||||
.filter(cardFee)
|
return result;
|
||||||
.map(fee => fee.expense_id)
|
}
|
||||||
.filter(Boolean),
|
/** @param {unknown} value @param {string} name */
|
||||||
);
|
function numeric(value, name, places = 2) {
|
||||||
const keys = new Set(),
|
const result = string(value, name, 24);
|
||||||
items = fees
|
if (!result) return '';
|
||||||
.map(raw => {
|
if (!new RegExp('^\\d+(?:\\.\\d{1,' + places + '})?$').test(result))
|
||||||
const fee = object(raw, '模板费用');
|
throw new Error(name + '须为非负数字,最多' + places + '位小数');
|
||||||
if (cardFee(fee) || (fee.expense_id && cardExpenseIds.has(fee.expense_id))) return null;
|
const [whole, fraction = ''] = result.split('.');
|
||||||
if (Fees.presetKind(fee) === 'box') {
|
if (BigInt(whole) * 10n ** BigInt(places) + BigInt(fraction.padEnd(places, '0')) > 100000000000n)
|
||||||
Fees.boxCount(fee.note.match(/(([^)]*)个 ×/)[1]);
|
throw new Error(name + '超出支持范围');
|
||||||
if (fee.amount === '') throw new Error('请先填写正整数的盒子数量');
|
return result;
|
||||||
|
}
|
||||||
|
/** @param {unknown} value @param {string} name */
|
||||||
|
function count(value, name) {
|
||||||
|
const result = string(value, name, 12);
|
||||||
|
if (result && !/^\d+$/.test(result)) throw new Error(name + '须为非负整数');
|
||||||
|
if (Number(result) > 1000000000) throw new Error(name + '超出支持范围');
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
/** @param {string} value */
|
||||||
|
const validMember = value =>
|
||||||
|
['owner', 'assistant', 'assistant2'].includes(value) ||
|
||||||
|
/^staff_[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value);
|
||||||
|
/** @param {unknown} value @param {unknown} [fallback] */
|
||||||
|
function payer(value, fallback = 'owner') {
|
||||||
|
const result = value ?? fallback;
|
||||||
|
if (typeof result !== 'string' || (result !== '' && !validMember(result))) throw new Error('成本付款人无效');
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
/** @param {unknown} value */
|
||||||
|
function paymentAccount(value) {
|
||||||
|
if (value != null && typeof value !== 'string') throw new Error('收款账户无效');
|
||||||
|
const result = normalizeAccount(value ?? '助理微信');
|
||||||
|
if (
|
||||||
|
!accounts.includes(result) &&
|
||||||
|
!/^staff_[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}(微信|支付宝|现金)$/.test(result)
|
||||||
|
)
|
||||||
|
throw new Error('收款账户无效');
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
/** @param {unknown} [input] @param {Record<string,unknown>} [fallback] */
|
||||||
|
function manualMaterial(input = {}, fallback = {}) {
|
||||||
|
const value = object(input, '备用料费');
|
||||||
|
return {
|
||||||
|
mode: pick(value.mode, ['gram', 'total'], '备用料费方式', fallback.mode || 'gram'),
|
||||||
|
rate: numeric(value.rate ?? fallback.rate, '备用进货料价'),
|
||||||
|
total: numeric(value.total ?? fallback.total, '备用料费合计'),
|
||||||
|
originalTotal: '',
|
||||||
|
payer: payer(value.payer, fallback.payer ?? 'owner'),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
/** @param {Record<string,unknown>} draft @param {import('../web/src/shared/orderPresets').TemplateOptions} [options] */
|
||||||
|
function fromDraft(draft, { newId = () => globalThis.crypto.randomUUID(), pocketKeys = pockets } = {}) {
|
||||||
|
object(draft, '开单预设');
|
||||||
|
if (!Array.isArray(draft.lines) || !draft.lines.length || draft.lines.length > 60)
|
||||||
|
throw new Error('模板需要1~60行商品');
|
||||||
|
const ids = new Map(),
|
||||||
|
seen = new Set();
|
||||||
|
const lines = draft.lines.map(raw => {
|
||||||
|
const line = object(raw, '模板商品'),
|
||||||
|
unit = pick(line.unit, ['g', '件'], '商品单位', 'g');
|
||||||
|
const name = string(line.name, '商品名称', 60),
|
||||||
|
nameType = pick(
|
||||||
|
line.nameType,
|
||||||
|
[...products, '其他'],
|
||||||
|
'商品名称',
|
||||||
|
products.includes(name) ? name : name ? '其他' : '足金999',
|
||||||
|
);
|
||||||
|
/** @type {Omit<import('../web/src/shared/orderPresets').TemplateProduct, 'charges'>} */
|
||||||
|
const product = {
|
||||||
|
nameType,
|
||||||
|
customName: string(line.customName ?? (nameType === '其他' ? name : ''), '其他商品名称', 60),
|
||||||
|
unit,
|
||||||
|
quantity: unit === 'g' ? numeric(line.quantity, '商品克重', 3) : count(line.quantity, '商品件数'),
|
||||||
|
pocket:
|
||||||
|
unit === '件' || ['足银999', '纯银925'].includes(nameType)
|
||||||
|
? ''
|
||||||
|
: pick(line.pocket, ['', ...pocketKeys], '出库货盘', nameType === '足金999' ? '现货' : ''),
|
||||||
|
payer: payer(line.payer, 'owner'),
|
||||||
|
pricingMode:
|
||||||
|
unit === '件'
|
||||||
|
? 'manual'
|
||||||
|
: pick(line.pricingMode, ['auto', 'manual'], '计价方式', line.sale != null ? 'manual' : 'auto'),
|
||||||
|
goldPrice: numeric(line.goldPrice, '销售金价'),
|
||||||
|
laborMode: pick(line.laborMode, ['gram', 'piece'], '销售工费方式', 'gram'),
|
||||||
|
laborRate: numeric(line.laborRate, '销售工费'),
|
||||||
|
pieces: count(line.pieces ?? '1', '计工费件数'),
|
||||||
|
priceNote: string(line.priceNote, '销售单价说明', 100),
|
||||||
|
sale: numeric(line.sale, '本行销售额'),
|
||||||
|
baseSale: numeric(line.baseSale ?? line.sale, '商品基础金额'),
|
||||||
|
};
|
||||||
|
product.name = nameType === '其他' ? product.customName : nameType;
|
||||||
|
if (line.stockCount != null && String(line.stockCount).trim() !== '') {
|
||||||
|
product.stockCount = count(line.stockCount, '出库数量(对)');
|
||||||
|
if (Number(product.stockCount) < 1) throw new Error('出库数量(对)须为正整数,一对填1');
|
||||||
|
}
|
||||||
|
const rawCharges = line.charges ?? [];
|
||||||
|
if (!Array.isArray(rawCharges) || rawCharges.length > 100) throw new Error('每行最多填写100项附加项目');
|
||||||
|
/** @type {import('../web/src/shared/orderPresets').TemplateProduct['charges']} */
|
||||||
|
const normalizedCharges = rawCharges.map(rawCharge => {
|
||||||
|
const c = object(rawCharge, '附加项目'),
|
||||||
|
old = string(c.id, '附加项目标识', 36);
|
||||||
|
if (old && (!uuid.test(old) || seen.has(old))) throw new Error('附加项目标识无效或重复');
|
||||||
|
if (old) seen.add(old);
|
||||||
|
const name = string(c.name, '附加项目名称', 40),
|
||||||
|
nameType = pick(
|
||||||
|
c.nameType,
|
||||||
|
[...charges, '其他'],
|
||||||
|
'附加项目',
|
||||||
|
charges.includes(name) ? name : name ? '其他' : '编绳',
|
||||||
|
);
|
||||||
|
if (c.costRemoved !== undefined && typeof c.costRemoved !== 'boolean')
|
||||||
|
throw new Error('内部成本移除标记无效');
|
||||||
|
const id = newId();
|
||||||
|
if (old) ids.set(old, id);
|
||||||
|
const customName = string(c.customName ?? (nameType === '其他' ? name : ''), '附加项目名称', 40),
|
||||||
|
amount = numeric(c.amount, '附加金额');
|
||||||
|
/** @type {Record<string,string>} */
|
||||||
|
const prices = {};
|
||||||
|
if (c.chargePrices != null) {
|
||||||
|
const values = object(c.chargePrices, '附加项目预设报价');
|
||||||
|
for (const key of [...charges, '其他'])
|
||||||
|
if (Object.hasOwn(values, key)) prices[key] = numeric(values[key], '附加项目报价');
|
||||||
}
|
}
|
||||||
const old = string(fee.key, '费用标识', 80);
|
|
||||||
if (
|
|
||||||
!['shipping', 'box', 'certificate', 'braiding', 'sticker', 'other'].includes(old) &&
|
|
||||||
!/^(charge|manual):[a-f0-9-]{36}$/.test(old)
|
|
||||||
)
|
|
||||||
throw new Error('模板费用项目无效');
|
|
||||||
if (keys.has(old)) throw new Error('模板费用项目不能重复');
|
|
||||||
keys.add(old);
|
|
||||||
const linked = old.startsWith('charge:') ? ids.get(old.slice(7)) : null;
|
|
||||||
if (old.startsWith('charge:') && !linked) return null;
|
|
||||||
return {
|
return {
|
||||||
key: linked ? 'charge:' + linked : old === 'shipping' || Fees.presetKind(fee) ? old : 'manual:' + newId(),
|
id,
|
||||||
note: string(fee.note, '费用名称', 150),
|
nameType,
|
||||||
amount: numeric(fee.amount, '实际费用'),
|
customName,
|
||||||
payer: payer(fee.payer, 'assistant'),
|
name: nameType === '其他' ? customName : nameType,
|
||||||
status: 'estimated',
|
amount,
|
||||||
edited: fee.edited !== false,
|
chargePrices: { ...prices, [nameType]: amount },
|
||||||
...(linked ? { sourceName: string(fee.sourceName || fee.note, '附加项目名称', 40) } : {}),
|
...(c.costRemoved === true ? { costRemoved: true } : {}),
|
||||||
};
|
};
|
||||||
})
|
});
|
||||||
.filter(Boolean);
|
const result = {...product, charges:normalizedCharges};
|
||||||
const preset = {
|
if (line.costParts != null) {
|
||||||
salesperson: string(draft.salesperson, '开单人', 30),
|
const costs = object(line.costParts, '分项成本');
|
||||||
payment_account: paymentAccount(draft.payment_account),
|
const parts = Object.fromEntries(
|
||||||
credit_card_fee_payer: payer(draft.credit_card_fee_payer, 'owner'),
|
['material', 'labor', 'accessories', 'other'].map(key => [key, numeric(costs[key], '货品成本')]),
|
||||||
discount: numeric(draft.discount ?? '0', '整单优惠'),
|
);
|
||||||
note: string(draft.note, '客户单备注', 240),
|
const material = object(line.costMaterial ?? {}, '料费方式'),
|
||||||
fee_auto_initialized: true,
|
labor = object(line.costLabor ?? {}, '进货工费方式');
|
||||||
...(draft.fee_cost_mode === 'checkboxes' ? { fee_cost_mode: 'checkboxes' } : {}),
|
const mode = pick(
|
||||||
lines,
|
material.mode,
|
||||||
fee_items: Fees.sync(items, lines, { checkboxCosts: draft.fee_cost_mode === 'checkboxes' }),
|
['gram', 'total', 'pool'],
|
||||||
};
|
'进货料费方式',
|
||||||
if (JSON.stringify(preset).length > 240000) throw new Error('模板内容过大,请减少商品或附加项目');
|
unit === 'g' && parts.material === '' ? 'gram' : 'total',
|
||||||
return preset;
|
);
|
||||||
}
|
result.costParts = parts;
|
||||||
function apply(preset, { today, salesperson = '', newId, pocketKeys } = {}) {
|
result.costPayers = {
|
||||||
if (
|
material: payer(properties(line.costPayers).material, result.payer),
|
||||||
!/^\d{4}-\d{2}-\d{2}$/.test(today || '') ||
|
labor: payer(properties(line.costPayers).labor, result.payer),
|
||||||
!Number.isFinite(Date.parse(today + 'T00:00:00Z')) ||
|
};
|
||||||
new Date(today + 'T00:00:00Z').toISOString().slice(0, 10) !== today
|
result.costMaterial = {
|
||||||
)
|
mode: unit === '件' ? 'total' : mode,
|
||||||
throw new Error('未取得有效系统日期,请刷新后再套用模板。');
|
...(mode === 'gram' ? { rate: numeric(material.rate, '进货料价') } : {}),
|
||||||
const draft = fromDraft({ ...preset, fee_cost_mode: 'checkboxes' }, { newId, pocketKeys });
|
};
|
||||||
for (const line of draft.lines)
|
result.costLabor = {
|
||||||
if (line.costMaterial?.mode === 'pool') {
|
mode: unit === '件' ? 'total' : pick(labor.mode, ['gram', 'total'], '进货工费方式', 'total'),
|
||||||
line.costMaterial = { mode: 'pool', poolId: today };
|
rate: numeric(labor.rate, '进货克工费'),
|
||||||
line.materialPoolDraft = { ...line.materialPoolDraft, poolId: today, defaultDate: true };
|
};
|
||||||
}
|
if (result.costMaterial.mode === 'pool') {
|
||||||
return {
|
if (['足银999', '纯银925'].includes(nameType)) throw new Error('银饰模板请手动填写料费');
|
||||||
...draft,
|
parts.material = '';
|
||||||
date: today,
|
result.materialPoolDraft = {
|
||||||
fees_date: today,
|
defaultDate: true,
|
||||||
customer: '',
|
manual: manualMaterial(properties(line.materialPoolDraft).manual),
|
||||||
salesperson: draft.salesperson || salesperson,
|
};
|
||||||
rounding_mode: 'yuan',
|
} else if (line.costMaterialDraft) {
|
||||||
};
|
const remembered = manualMaterial(line.costMaterialDraft, {
|
||||||
}
|
mode: result.costMaterial.mode,
|
||||||
return { fromDraft, apply };
|
rate: material.rate,
|
||||||
});
|
total: parts.material,
|
||||||
|
payer: result.costPayers.material,
|
||||||
|
});
|
||||||
|
result.costMaterialDraft = {
|
||||||
|
mode: remembered.mode,
|
||||||
|
rate: remembered.rate,
|
||||||
|
total: remembered.total,
|
||||||
|
originalTotal: '',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} else if (Object.hasOwn(line, 'cost')) result.cost = numeric(line.cost, '货品成本');
|
||||||
|
return result;
|
||||||
|
});
|
||||||
|
const fees = draft.fee_items ?? [];
|
||||||
|
if (!Array.isArray(fees) || fees.length > 6100) throw new Error('模板费用项目过多');
|
||||||
|
const cardExpenseIds = new Set(
|
||||||
|
fees
|
||||||
|
.filter(cardFee)
|
||||||
|
.map(fee => fee.expense_id)
|
||||||
|
.filter(Boolean),
|
||||||
|
);
|
||||||
|
const keys = new Set(),
|
||||||
|
items = fees
|
||||||
|
.map(raw => {
|
||||||
|
const fee = object(raw, '模板费用');
|
||||||
|
if (cardFee(fee) || (fee.expense_id && cardExpenseIds.has(fee.expense_id))) return null;
|
||||||
|
const kind =
|
||||||
|
!fee.expense_id &&
|
||||||
|
!fee.funding &&
|
||||||
|
typeof fee.key === 'string' &&
|
||||||
|
typeof fee.note === 'string' &&
|
||||||
|
typeof fee.payer === 'string' &&
|
||||||
|
(typeof fee.amount === 'string' || typeof fee.amount === 'number')
|
||||||
|
? Fees.presetKind({ key: fee.key, note: fee.note, amount: fee.amount, payer: fee.payer })
|
||||||
|
: '';
|
||||||
|
if (kind === 'box') {
|
||||||
|
Fees.boxCount(String(fee.note).match(/(([^)]*)个 ×/)?.[1]);
|
||||||
|
if (fee.amount === '') throw new Error('请先填写正整数的盒子数量');
|
||||||
|
}
|
||||||
|
const old = string(fee.key, '费用标识', 80);
|
||||||
|
if (
|
||||||
|
!['shipping', 'box', 'certificate', 'braiding', 'sticker', 'other'].includes(old) &&
|
||||||
|
!/^(charge|manual):[a-f0-9-]{36}$/.test(old)
|
||||||
|
)
|
||||||
|
throw new Error('模板费用项目无效');
|
||||||
|
if (keys.has(old)) throw new Error('模板费用项目不能重复');
|
||||||
|
keys.add(old);
|
||||||
|
const linked = old.startsWith('charge:') ? ids.get(old.slice(7)) : null;
|
||||||
|
if (old.startsWith('charge:') && !linked) return null;
|
||||||
|
return {
|
||||||
|
key: linked ? 'charge:' + linked : old === 'shipping' || kind ? old : 'manual:' + newId(),
|
||||||
|
note: string(fee.note, '费用名称', 150),
|
||||||
|
amount: numeric(fee.amount, '实际费用'),
|
||||||
|
payer: payer(fee.payer, 'assistant'),
|
||||||
|
status: 'estimated',
|
||||||
|
edited: fee.edited !== false,
|
||||||
|
...(linked ? { sourceName: string(fee.sourceName || fee.note, '附加项目名称', 40) } : {}),
|
||||||
|
};
|
||||||
|
})
|
||||||
|
.filter(row => row !== null);
|
||||||
|
const preset = {
|
||||||
|
salesperson: string(draft.salesperson, '开单人', 30),
|
||||||
|
payment_account: paymentAccount(draft.payment_account),
|
||||||
|
credit_card_fee_payer: payer(draft.credit_card_fee_payer, 'owner'),
|
||||||
|
discount: numeric(draft.discount ?? '0', '整单优惠'),
|
||||||
|
note: string(draft.note, '客户单备注', 240),
|
||||||
|
fee_auto_initialized: true,
|
||||||
|
...(draft.fee_cost_mode === 'checkboxes' ? { fee_cost_mode: 'checkboxes' } : {}),
|
||||||
|
lines,
|
||||||
|
fee_items: Fees.sync(items, lines, { checkboxCosts: draft.fee_cost_mode === 'checkboxes' }),
|
||||||
|
};
|
||||||
|
if (JSON.stringify(preset).length > 240000) throw new Error('模板内容过大,请减少商品或附加项目');
|
||||||
|
return preset;
|
||||||
|
}
|
||||||
|
/** @param {Record<string,unknown>} preset @param {import('../web/src/shared/orderPresets').TemplateOptions} [options] */
|
||||||
|
function apply(preset, { today, salesperson = '', newId, pocketKeys } = {}) {
|
||||||
|
if (
|
||||||
|
!/^\d{4}-\d{2}-\d{2}$/.test(today || '') ||
|
||||||
|
!Number.isFinite(Date.parse(today + 'T00:00:00Z')) ||
|
||||||
|
new Date(today + 'T00:00:00Z').toISOString().slice(0, 10) !== today
|
||||||
|
)
|
||||||
|
throw new Error('未取得有效系统日期,请刷新后再套用模板。');
|
||||||
|
const draft = fromDraft({ ...preset, fee_cost_mode: 'checkboxes' }, { newId, pocketKeys });
|
||||||
|
for (const line of draft.lines)
|
||||||
|
if (line.costMaterial?.mode === 'pool') {
|
||||||
|
line.costMaterial = { mode: 'pool', poolId: today };
|
||||||
|
line.materialPoolDraft = { ...line.materialPoolDraft, poolId: today, defaultDate: true };
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
...draft,
|
||||||
|
date: today,
|
||||||
|
fees_date: today,
|
||||||
|
customer: '',
|
||||||
|
salesperson: draft.salesperson || salesperson,
|
||||||
|
rounding_mode: 'yuan',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return { fromDraft, apply };
|
||||||
|
},
|
||||||
|
);
|
||||||
+148
-59
@@ -1,9 +1,24 @@
|
|||||||
|
// @ts-check
|
||||||
'use strict';
|
'use strict';
|
||||||
|
/** @typedef {import('../web/src/pages/Recoveries/types').Draft} Draft */
|
||||||
|
/** @typedef {import('../web/src/pages/Recoveries/types').OldLine} OldLine */
|
||||||
|
/** @typedef {import('../web/src/pages/Recoveries/types').Input} Input */
|
||||||
|
/** @typedef {import('../web/src/pages/Recoveries/types').Product} Product */
|
||||||
|
/** @typedef {import('../web/src/pages/Recoveries/types').Calculation} Calculation */
|
||||||
|
/** @typedef {import('../web/src/pages/Recoveries/types').EditDetail} EditDetail */
|
||||||
|
/** @typedef {import('../web/src/pages/Recoveries/types').ChangeRequest} ChangeRequest */
|
||||||
|
/** @typedef {import('../web/src/pages/Recoveries/types').ItemInput} ItemInput */
|
||||||
|
/** @typedef {import('../web/src/pages/Recoveries/types').Exchange} Exchange */
|
||||||
|
/** @typedef {import('../web/src/pages/Recoveries/types').Material} Material */
|
||||||
|
/** @typedef {import('../web/src/pages/Recoveries/types').RecoveryContext} RecoveryContext */
|
||||||
|
/** @typedef {import('../web/src/pages/Recoveries/types').RecoveryModel} RecoveryModel */
|
||||||
|
/** @typedef {import('../web/src/pages/Recoveries/types').Totals} Totals */
|
||||||
// 两种前端共用的回收规则。金额为分、重量为毫克,新版与历史两种多件置换格式分别结算。
|
// 两种前端共用的回收规则。金额为分、重量为毫克,新版与历史两种多件置换格式分别结算。
|
||||||
(function (root) {
|
(function (root) {
|
||||||
const recoveryModeNames = { direct: '直接回收', exchange: '置换' };
|
const recoveryModeNames = { direct: '直接回收', exchange: '置换' };
|
||||||
|
/** @param {unknown} value */
|
||||||
const recoveryText = value => String(value ?? '').trim();
|
const recoveryText = value => String(value ?? '').trim();
|
||||||
const recoveryProductFields = [
|
const recoveryProductFields = /** @type {const} */ ([
|
||||||
'new_name',
|
'new_name',
|
||||||
'new_quantity',
|
'new_quantity',
|
||||||
'pocket',
|
'pocket',
|
||||||
@@ -13,8 +28,9 @@
|
|||||||
'cost_labor_mode',
|
'cost_labor_mode',
|
||||||
'cost_labor_value',
|
'cost_labor_value',
|
||||||
'labor_payer',
|
'labor_payer',
|
||||||
];
|
]);
|
||||||
|
|
||||||
|
/** @param {unknown} value @param {number} places @param {string} title @returns {number} */
|
||||||
function recoveryUnits(value, places, title, { zero = true } = {}) {
|
function recoveryUnits(value, places, title, { zero = true } = {}) {
|
||||||
const raw = recoveryText(value),
|
const raw = recoveryText(value),
|
||||||
pattern = new RegExp('^\\d+(?:\\.\\d{1,' + places + '})?$');
|
pattern = new RegExp('^\\d+(?:\\.\\d{1,' + places + '})?$');
|
||||||
@@ -26,16 +42,19 @@
|
|||||||
return Number(units);
|
return Number(units);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {number} value @returns {number} */
|
||||||
function recoveryLimit(value, title = '回收/置换合计') {
|
function recoveryLimit(value, title = '回收/置换合计') {
|
||||||
if (!Number.isSafeInteger(value) || Math.abs(value) > 100000000000)
|
if (!Number.isSafeInteger(value) || Math.abs(value) > 100000000000)
|
||||||
throw new Error(title + '超出支持范围,请核对。');
|
throw new Error(title + '超出支持范围,请核对。');
|
||||||
return value;
|
return value;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {number} weight @param {number} rate @returns {number} */
|
||||||
function recoveryMul(weight, rate) {
|
function recoveryMul(weight, rate) {
|
||||||
return recoveryLimit(Number((BigInt(weight) * BigInt(rate) + 500n) / 1000n));
|
return recoveryLimit(Number((BigInt(weight) * BigInt(rate) + 500n) / 1000n));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {Product} row */
|
||||||
function recoveryProductDraft(row) {
|
function recoveryProductDraft(row) {
|
||||||
return {
|
return {
|
||||||
new_name: row.name,
|
new_name: row.name,
|
||||||
@@ -50,6 +69,7 @@
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {Draft} draft @returns {number} */
|
||||||
function recoveryNewWeight(draft) {
|
function recoveryNewWeight(draft) {
|
||||||
return [draft, ...(draft.extra_products || [])].reduce(
|
return [draft, ...(draft.extra_products || [])].reduce(
|
||||||
(n, row) => recoveryLimit(n + recoveryUnits(row.new_quantity, 3, '新货克重', { zero: false })),
|
(n, row) => recoveryLimit(n + recoveryUnits(row.new_quantity, 3, '新货克重', { zero: false })),
|
||||||
@@ -57,13 +77,34 @@
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {Draft} draft @returns {Draft} */
|
||||||
function recoverySharedOldDraft(draft) {
|
function recoverySharedOldDraft(draft) {
|
||||||
if (!draft.independent_products) return draft;
|
if (!draft.independent_products) return draft;
|
||||||
return {
|
return {
|
||||||
...draft,
|
...draft,
|
||||||
independent_products: false,
|
independent_products: false,
|
||||||
extra_products: (draft.extra_products || []).map(row =>
|
extra_products: (draft.extra_products || []).map(
|
||||||
Object.fromEntries(recoveryProductFields.map(k => [k, row[k]])),
|
({
|
||||||
|
new_name,
|
||||||
|
new_quantity,
|
||||||
|
pocket,
|
||||||
|
stockCount,
|
||||||
|
labor_mode,
|
||||||
|
labor_rate,
|
||||||
|
cost_labor_mode,
|
||||||
|
cost_labor_value,
|
||||||
|
labor_payer,
|
||||||
|
}) => ({
|
||||||
|
new_name,
|
||||||
|
new_quantity,
|
||||||
|
pocket,
|
||||||
|
stockCount,
|
||||||
|
labor_mode,
|
||||||
|
labor_rate,
|
||||||
|
cost_labor_mode,
|
||||||
|
cost_labor_value,
|
||||||
|
labor_payer,
|
||||||
|
}),
|
||||||
),
|
),
|
||||||
...(draft.extra_products?.length ? { buy_total_manual: false, buy_total: '', depreciation_manual: false } : {}),
|
...(draft.extra_products?.length ? { buy_total_manual: false, buy_total: '', depreciation_manual: false } : {}),
|
||||||
verified: false,
|
verified: false,
|
||||||
@@ -71,8 +112,10 @@
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {Input} input @returns {Calculation} */
|
||||||
function recoveryCalculate(input) {
|
function recoveryCalculate(input) {
|
||||||
if (input.mode === 'exchange' && input.exchange?.items) return recoveryItemsCalculate(input);
|
if (input.mode === 'exchange' && input.exchange?.items)
|
||||||
|
return recoveryItemsCalculate(input, input.exchange, input.exchange.items);
|
||||||
if (!Object.hasOwn(recoveryModeNames, input.mode)) throw new Error('请选择直接回收或置换。');
|
if (!Object.hasOwn(recoveryModeNames, input.mode)) throw new Error('请选择直接回收或置换。');
|
||||||
const oldLines = (input.old_lines || []).map(line => {
|
const oldLines = (input.old_lines || []).map(line => {
|
||||||
const incomingMg = recoveryUnits(line.incoming_weight, 3, '来料重量', { zero: false }),
|
const incomingMg = recoveryUnits(line.incoming_weight, 3, '来料重量', { zero: false }),
|
||||||
@@ -103,6 +146,7 @@
|
|||||||
receivable = 0,
|
receivable = 0,
|
||||||
roundingAdjustment = 0;
|
roundingAdjustment = 0;
|
||||||
if (input.mode === 'exchange') {
|
if (input.mode === 'exchange') {
|
||||||
|
/** @type {Partial<Exchange>} */
|
||||||
const x = input.exchange || {};
|
const x = input.exchange || {};
|
||||||
newMg = x.products
|
newMg = x.products
|
||||||
? recoveryLimit(
|
? recoveryLimit(
|
||||||
@@ -179,8 +223,9 @@
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function recoveryItemsCalculate(input) {
|
/** @param {Input} input @param {Exchange} exchange @param {ItemInput[]} items @returns {Calculation} */
|
||||||
const parts = input.exchange.items.map(row =>
|
function recoveryItemsCalculate(input, exchange, items) {
|
||||||
|
const parts = items.map(row =>
|
||||||
recoveryCalculate({
|
recoveryCalculate({
|
||||||
...input,
|
...input,
|
||||||
...row,
|
...row,
|
||||||
@@ -192,37 +237,48 @@
|
|||||||
exchange: row.exchange,
|
exchange: row.exchange,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
const q = { mode: 'exchange', old_lines: parts.flatMap(p => p.old_lines), exchangeItems: parts };
|
/** @param {keyof Pick<Calculation,'oldMg'|'newMg'|'matchedMg'|'differenceMg'|'surplusMg'|'depositMg'|'purchaseMg'|'goldAmount'|'laborAmount'|'depreciationMg'|'depreciationAmount'|'purchaseAmount'|'defaultPurchaseAmount'>} key */
|
||||||
for (const key of [
|
const sum = key => recoveryLimit(parts.reduce((n, p) => n + p[key], 0));
|
||||||
'oldMg',
|
const sums = {
|
||||||
'newMg',
|
oldMg: sum('oldMg'),
|
||||||
'matchedMg',
|
newMg: sum('newMg'),
|
||||||
'differenceMg',
|
matchedMg: sum('matchedMg'),
|
||||||
'surplusMg',
|
differenceMg: sum('differenceMg'),
|
||||||
'depositMg',
|
surplusMg: sum('surplusMg'),
|
||||||
'purchaseMg',
|
depositMg: sum('depositMg'),
|
||||||
'goldAmount',
|
purchaseMg: sum('purchaseMg'),
|
||||||
'laborAmount',
|
goldAmount: sum('goldAmount'),
|
||||||
'depreciationMg',
|
laborAmount: sum('laborAmount'),
|
||||||
'depreciationAmount',
|
depreciationMg: sum('depreciationMg'),
|
||||||
'purchaseAmount',
|
depreciationAmount: sum('depreciationAmount'),
|
||||||
'defaultPurchaseAmount',
|
purchaseAmount: sum('purchaseAmount'),
|
||||||
])
|
defaultPurchaseAmount: sum('defaultPurchaseAmount'),
|
||||||
q[key] = recoveryLimit(parts.reduce((n, p) => n + p[key], 0));
|
};
|
||||||
q.chargesAmount = recoveryLimit(
|
const chargesAmount = recoveryLimit(
|
||||||
(input.exchange.charges || []).reduce((n, r) => n + recoveryUnits(r.amount, 2, '其他收费'), 0),
|
(exchange.charges || []).reduce((n, r) => n + recoveryUnits(r.amount, 2, '其他收费'), 0),
|
||||||
);
|
);
|
||||||
q.discount = recoveryUnits(input.exchange.discount || '0', 2, '整单优惠');
|
const discount = recoveryUnits(exchange.discount || '0', 2, '整单优惠');
|
||||||
const before = recoveryLimit(q.goldAmount + q.laborAmount + q.depreciationAmount + q.chargesAmount) - q.discount;
|
const before =
|
||||||
|
recoveryLimit(sums.goldAmount + sums.laborAmount + sums.depreciationAmount + chargesAmount) - discount;
|
||||||
if (before < 0) throw new Error('优惠金额不能大于置换费用');
|
if (before < 0) throw new Error('优惠金额不能大于置换费用');
|
||||||
q.receivable = input.exchange.rounding_mode === 'yuan' ? Math.floor((before + 50) / 100) * 100 : before;
|
const receivable = exchange.rounding_mode === 'yuan' ? Math.floor((before + 50) / 100) * 100 : before;
|
||||||
q.roundingAdjustment = q.receivable - before;
|
const netSettlement = receivable - sums.purchaseAmount;
|
||||||
q.netSettlement = q.receivable - q.purchaseAmount;
|
return {
|
||||||
q.cashReceipt = Math.max(0, q.netSettlement);
|
mode: 'exchange',
|
||||||
q.cashPayment = Math.max(0, -q.netSettlement);
|
old_lines: parts.flatMap(p => p.old_lines),
|
||||||
return q;
|
exchangeItems: parts,
|
||||||
|
...sums,
|
||||||
|
chargesAmount,
|
||||||
|
discount,
|
||||||
|
receivable,
|
||||||
|
roundingAdjustment: receivable - before,
|
||||||
|
netSettlement,
|
||||||
|
cashReceipt: Math.max(0, netSettlement),
|
||||||
|
cashPayment: Math.max(0, -netSettlement),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {Draft} draft @returns {OldLine[]} */
|
||||||
function customerMaterialOldLines(draft) {
|
function customerMaterialOldLines(draft) {
|
||||||
return [
|
return [
|
||||||
{ name: '客户寄存料', incoming_weight: draft.deposit_weight, melted_weight: draft.deposit_weight, purity: '100' },
|
{ name: '客户寄存料', incoming_weight: draft.deposit_weight, melted_weight: draft.deposit_weight, purity: '100' },
|
||||||
@@ -230,7 +286,12 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 页面的成员、货盘和账户策略由调用方提供。originalInput 只在编辑既有单据时参与历史值校验。
|
// 页面的成员、货盘和账户策略由调用方提供。originalInput 只在编辑既有单据时参与历史值校验。
|
||||||
|
/**
|
||||||
|
* @param {import('../web/src/pages/Recoveries/types').RecoveryContext} context
|
||||||
|
* @returns {import('../web/src/pages/Recoveries/types').RecoveryModel}
|
||||||
|
*/
|
||||||
function createModel(context) {
|
function createModel(context) {
|
||||||
|
/** @param {import('../web/src/pages/Recoveries/types').ProductDraft} draft @returns {Product} */
|
||||||
function recoveryProductInput(draft) {
|
function recoveryProductInput(draft) {
|
||||||
return {
|
return {
|
||||||
name: draft.new_name,
|
name: draft.new_name,
|
||||||
@@ -251,6 +312,7 @@
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {import('../web/src/pages/Recoveries/types').Mode} [mode] @returns {Draft} */
|
||||||
function recoveryDefaults(mode = 'direct') {
|
function recoveryDefaults(mode = 'direct') {
|
||||||
const member = context.currentMember();
|
const member = context.currentMember();
|
||||||
return {
|
return {
|
||||||
@@ -307,11 +369,15 @@
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @overload @param {Draft & {mode:'exchange'}} draft @param {{quote?:boolean}} [options] @returns {Input & {exchange:Exchange}} */
|
||||||
|
/** @overload @param {Draft} draft @param {{quote?:boolean}} [options] @returns {Input} */
|
||||||
|
/** @param {Draft} draft @returns {Input} */
|
||||||
function recoveryInput(draft, { quote = false } = {}) {
|
function recoveryInput(draft, { quote = false } = {}) {
|
||||||
if (draft.mode === 'exchange' && draft.independent_products) return recoveryItemsInput(draft, { quote });
|
if (draft.mode === 'exchange' && draft.independent_products) return recoveryItemsInput(draft, { quote });
|
||||||
if (draft.mode === 'exchange' && draft.old_source === 'deposit')
|
if (draft.mode === 'exchange' && draft.old_source === 'deposit')
|
||||||
draft = { ...draft, old_lines: customerMaterialOldLines(draft) };
|
draft = { ...draft, old_lines: customerMaterialOldLines(draft) };
|
||||||
const member = context.state.user.role === 'owner' ? draft.member : context.currentMember();
|
const member = context.state.user.role === 'owner' ? draft.member : context.currentMember();
|
||||||
|
/** @type {Input} */
|
||||||
const input = {
|
const input = {
|
||||||
mode: draft.mode,
|
mode: draft.mode,
|
||||||
date: draft.date,
|
date: draft.date,
|
||||||
@@ -354,12 +420,14 @@
|
|||||||
buy_total: '0',
|
buy_total: '0',
|
||||||
});
|
});
|
||||||
if (draft.mode === 'exchange') {
|
if (draft.mode === 'exchange') {
|
||||||
|
/** @type {import('../web/src/pages/Recoveries/types').Labor|undefined} */
|
||||||
const costLabor =
|
const costLabor =
|
||||||
draft.cost_labor_value === ''
|
draft.cost_labor_value === ''
|
||||||
? undefined
|
? undefined
|
||||||
: draft.cost_labor_mode === 'total'
|
: draft.cost_labor_mode === 'total'
|
||||||
? { mode: 'total', amount: draft.cost_labor_value }
|
? { mode: 'total', amount: draft.cost_labor_value }
|
||||||
: { mode: 'gram', rate: draft.cost_labor_value };
|
: { mode: 'gram', rate: draft.cost_labor_value };
|
||||||
|
/** @type {Material|undefined} */
|
||||||
const costMaterial =
|
const costMaterial =
|
||||||
draft.material_source === 'pool'
|
draft.material_source === 'pool'
|
||||||
? { mode: 'pool', poolId: draft.material_pool_id || draft.date }
|
? { mode: 'pool', poolId: draft.material_pool_id || draft.date }
|
||||||
@@ -428,19 +496,22 @@
|
|||||||
return input;
|
return input;
|
||||||
}
|
}
|
||||||
|
|
||||||
function validateRecoveryInput(input) {
|
/** @param {Input} input @returns {Input} */
|
||||||
|
function validateRecoveryInput(input, itemIndex = -1) {
|
||||||
if (input.exchange?.items) {
|
if (input.exchange?.items) {
|
||||||
for (const [index, row] of input.exchange.items.entries())
|
for (const [index, row] of input.exchange.items.entries())
|
||||||
validateRecoveryInput({
|
validateRecoveryInput(
|
||||||
...input,
|
{
|
||||||
...row,
|
...input,
|
||||||
_recoveryItemIndex: index,
|
...row,
|
||||||
buy_total: row.buy_total,
|
buy_total: row.buy_total,
|
||||||
buy_rate: row.buy_rate,
|
buy_rate: row.buy_rate,
|
||||||
exchange: row.exchange,
|
exchange: row.exchange,
|
||||||
payment_account: context.memberAccountPrefix(input.payer) + '微信',
|
payment_account: context.memberAccountPrefix(input.payer) + '微信',
|
||||||
});
|
},
|
||||||
if (!context.state.accounts.includes(input.payment_account)) throw new Error('请选择有效收付款账户');
|
index,
|
||||||
|
);
|
||||||
|
if (!context.state.accounts?.includes(input.payment_account)) throw new Error('请选择有效收付款账户');
|
||||||
return input;
|
return input;
|
||||||
}
|
}
|
||||||
if (!context.validOrderDate(input.date) || input.date > context.state.today)
|
if (!context.validOrderDate(input.date) || input.date > context.state.today)
|
||||||
@@ -452,7 +523,7 @@
|
|||||||
throw new Error('请选择归属成员和实际付款人。');
|
throw new Error('请选择归属成员和实际付款人。');
|
||||||
const calculation = recoveryCalculate(input);
|
const calculation = recoveryCalculate(input);
|
||||||
const source = context.originalInput,
|
const source = context.originalInput,
|
||||||
item = source?.exchange?.items?.[input._recoveryItemIndex],
|
item = source?.exchange?.items?.[itemIndex],
|
||||||
oldOriginal = item ? { ...source, ...item } : source;
|
oldOriginal = item ? { ...source, ...item } : source;
|
||||||
const oldPocket = input.old_pocket ?? '回收旧料';
|
const oldPocket = input.old_pocket ?? '回收旧料';
|
||||||
if (
|
if (
|
||||||
@@ -477,10 +548,10 @@
|
|||||||
if (recoveryUnits(input.deposit_weight, 3, '使用寄存克重', { zero: false }) > calculation.newMg)
|
if (recoveryUnits(input.deposit_weight, 3, '使用寄存克重', { zero: false }) > calculation.newMg)
|
||||||
throw new Error('本次寄存用量不能超过新货克重,剩余继续寄存');
|
throw new Error('本次寄存用量不能超过新货克重,剩余继续寄存');
|
||||||
}
|
}
|
||||||
if (input.mode === 'exchange') {
|
if (input.mode === 'exchange' && input.exchange) {
|
||||||
const x = input.exchange,
|
const x = input.exchange,
|
||||||
original = oldOriginal?.exchange;
|
original = oldOriginal?.exchange;
|
||||||
if (context.pocketCountsEnabled(x.pocket))
|
if (context.pocketCountsEnabled(x.pocket ?? ''))
|
||||||
context.stockCountValue(x.stockCount, {
|
context.stockCountValue(x.stockCount, {
|
||||||
optional:
|
optional:
|
||||||
!!original &&
|
!!original &&
|
||||||
@@ -492,7 +563,7 @@
|
|||||||
if (!x.name || x.name.length > 60) throw new Error('请填写1~60字的新货商品名称。');
|
if (!x.name || x.name.length > 60) throw new Error('请填写1~60字的新货商品名称。');
|
||||||
if (
|
if (
|
||||||
x.pocket !== '' &&
|
x.pocket !== '' &&
|
||||||
!context.activePocketKeys().includes(x.pocket) &&
|
!context.activePocketKeys().includes(x.pocket ?? '') &&
|
||||||
!(source && original?.pocket === x.pocket)
|
!(source && original?.pocket === x.pocket)
|
||||||
)
|
)
|
||||||
throw new Error('请选择新货实际出库的已启用货盘。');
|
throw new Error('请选择新货实际出库的已启用货盘。');
|
||||||
@@ -524,18 +595,19 @@
|
|||||||
throw new Error('料池日期不能晚于业务日期。');
|
throw new Error('料池日期不能晚于业务日期。');
|
||||||
}
|
}
|
||||||
for (const payer of [x.cost_material_payer, x.cost_labor_payer, ...x.fee_items.map(row => row.payer)])
|
for (const payer of [x.cost_material_payer, x.cost_labor_payer, ...x.fee_items.map(row => row.payer)])
|
||||||
if (!context.teamMemberKeys().includes(payer)) throw new Error('请选择内部成本的实际付款人。');
|
if (!payer || !context.teamMemberKeys().includes(payer)) throw new Error('请选择内部成本的实际付款人。');
|
||||||
}
|
}
|
||||||
if (calculation.netSettlement < 0 && context.isCreditCardAccount(input.payment_account))
|
if (calculation.netSettlement < 0 && context.isCreditCardAccount(input.payment_account))
|
||||||
throw new Error('向客户付款不能使用信用卡收款账户。');
|
throw new Error('向客户付款不能使用信用卡收款账户。');
|
||||||
if (!context.state.accounts.includes(input.payment_account)) throw new Error('请选择有效的收付款方式。');
|
if (!context.state.accounts?.includes(input.payment_account)) throw new Error('请选择有效的收付款方式。');
|
||||||
if (input.verified !== true) throw new Error('请核实重量、结算金额和实际收付款后,勾选确认再保存。');
|
if (input.verified !== true) throw new Error('请核实重量、结算金额和实际收付款后,勾选确认再保存。');
|
||||||
return input;
|
return input;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {Draft} draft @returns {Input} */
|
||||||
function recoveryItemsInput(draft, { quote = false } = {}) {
|
function recoveryItemsInput(draft, { quote = false } = {}) {
|
||||||
const common = {
|
const common = {
|
||||||
mode: 'exchange',
|
mode: /** @type {const} */ ('exchange'),
|
||||||
date: draft.date,
|
date: draft.date,
|
||||||
customer: draft.customer,
|
customer: draft.customer,
|
||||||
customer_type: draft.customer_type,
|
customer_type: draft.customer_type,
|
||||||
@@ -579,7 +651,14 @@
|
|||||||
};
|
};
|
||||||
});
|
});
|
||||||
const first = recoveryInput(
|
const first = recoveryInput(
|
||||||
{ ...draft, independent_products: false, extra_products: [], discount: '0', rounding_mode: 'cent' },
|
{
|
||||||
|
...draft,
|
||||||
|
mode: 'exchange',
|
||||||
|
independent_products: false,
|
||||||
|
extra_products: [],
|
||||||
|
discount: '0',
|
||||||
|
rounding_mode: 'cent',
|
||||||
|
},
|
||||||
{ quote: true },
|
{ quote: true },
|
||||||
),
|
),
|
||||||
input = {
|
input = {
|
||||||
@@ -609,6 +688,7 @@
|
|||||||
return input;
|
return input;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {Input|null} input */
|
||||||
function recoveryInputShape(input) {
|
function recoveryInputShape(input) {
|
||||||
return (
|
return (
|
||||||
input &&
|
input &&
|
||||||
@@ -621,13 +701,17 @@
|
|||||||
input.old_lines.length > 0 &&
|
input.old_lines.length > 0 &&
|
||||||
input.old_lines.every(
|
input.old_lines.every(
|
||||||
row =>
|
row =>
|
||||||
row && ['name', 'incoming_weight', 'melted_weight', 'purity'].every(key => typeof row[key] === 'string'),
|
row &&
|
||||||
|
/** @type {const} */ (['name', 'incoming_weight', 'melted_weight', 'purity']).every(
|
||||||
|
key => typeof row[key] === 'string',
|
||||||
|
),
|
||||||
) &&
|
) &&
|
||||||
(input.mode === 'direct' ||
|
(input.mode === 'direct' ||
|
||||||
(input.exchange && Array.isArray(input.exchange.charges) && Array.isArray(input.exchange.fee_items)))
|
(input.exchange && Array.isArray(input.exchange.charges) && Array.isArray(input.exchange.fee_items)))
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {EditDetail} data @param {string} id @returns {EditDetail} */
|
||||||
function validateRecoveryEditDetail(data, id) {
|
function validateRecoveryEditDetail(data, id) {
|
||||||
if (
|
if (
|
||||||
!data ||
|
!data ||
|
||||||
@@ -638,8 +722,10 @@
|
|||||||
!['active', 'cancelled'].includes(data.status) ||
|
!['active', 'cancelled'].includes(data.status) ||
|
||||||
!recoveryInputShape(data.inputs) ||
|
!recoveryInputShape(data.inputs) ||
|
||||||
!data.permissions ||
|
!data.permissions ||
|
||||||
!['canEdit', 'canCancel', 'canDirect', 'requiresApproval'].every(
|
!(
|
||||||
key => typeof data.permissions[key] === 'boolean',
|
/** @type {const} */ (['canEdit', 'canCancel', 'canDirect', 'requiresApproval']).every(
|
||||||
|
key => typeof data.permissions[key] === 'boolean',
|
||||||
|
)
|
||||||
) ||
|
) ||
|
||||||
!Array.isArray(data.blockedUsages) ||
|
!Array.isArray(data.blockedUsages) ||
|
||||||
!Array.isArray(data.history) ||
|
!Array.isArray(data.history) ||
|
||||||
@@ -655,6 +741,7 @@
|
|||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {ChangeRequest} request @returns {ChangeRequest} */
|
||||||
function validateRecoveryChangeRequest(request) {
|
function validateRecoveryChangeRequest(request) {
|
||||||
if (
|
if (
|
||||||
!request ||
|
!request ||
|
||||||
@@ -680,6 +767,7 @@
|
|||||||
return request;
|
return request;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {Input} input @returns {Draft} */
|
||||||
function recoveryEditDraft(input) {
|
function recoveryEditDraft(input) {
|
||||||
if (input.exchange?.items) {
|
if (input.exchange?.items) {
|
||||||
const rows = input.exchange.items.map(row => recoveryEditDraft({ ...input, ...row, exchange: row.exchange })),
|
const rows = input.exchange.items.map(row => recoveryEditDraft({ ...input, ...row, exchange: row.exchange })),
|
||||||
@@ -700,8 +788,9 @@
|
|||||||
rounding_mode: x.rounding_mode,
|
rounding_mode: x.rounding_mode,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
/** @type {Partial<Exchange>} */
|
||||||
|
const x = input.exchange || {};
|
||||||
const first = input.old_lines[0],
|
const first = input.old_lines[0],
|
||||||
x = input.exchange || {},
|
|
||||||
charge = x.charges?.[0],
|
charge = x.charges?.[0],
|
||||||
fee = x.fee_items?.[0],
|
fee = x.fee_items?.[0],
|
||||||
account = input.payment_account || '',
|
account = input.payment_account || '',
|
||||||
@@ -739,7 +828,7 @@
|
|||||||
payout_method: method === '信用卡' ? '微信' : method,
|
payout_method: method === '信用卡' ? '微信' : method,
|
||||||
new_name: x.name || '足金999',
|
new_name: x.name || '足金999',
|
||||||
new_quantity: x.quantity || '',
|
new_quantity: x.quantity || '',
|
||||||
pocket: x.pocket ?? context.state.pockets[0] ?? '',
|
pocket: x.pocket ?? context.state.pockets?.[0] ?? '',
|
||||||
stockCount: x.stockCount ?? '',
|
stockCount: x.stockCount ?? '',
|
||||||
gold_price: x.gold_price || '0',
|
gold_price: x.gold_price || '0',
|
||||||
labor_mode: x.labor_mode || 'gram',
|
labor_mode: x.labor_mode || 'gram',
|
||||||
@@ -785,5 +874,5 @@
|
|||||||
}
|
}
|
||||||
const api = { createModel, recoveryModeNames, recoveryProductFields, customerMaterialOldLines };
|
const api = { createModel, recoveryModeNames, recoveryProductFields, customerMaterialOldLines };
|
||||||
if (typeof module === 'object' && module.exports) module.exports = api;
|
if (typeof module === 'object' && module.exports) module.exports = api;
|
||||||
else root.RecoveryRules = api;
|
else /** @type {{RecoveryRules?:object}} */ (root).RecoveryRules = api;
|
||||||
})(typeof globalThis === 'object' ? globalThis : this);
|
})(typeof globalThis === 'object' ? globalThis : this);
|
||||||
+220
-99
@@ -1,14 +1,40 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
// 两版对账共用的校验和归集规则。成员、当前查询以及日期校验由调用方提供。
|
// 两版对账共用的校验和归集规则。成员、当前查询以及日期校验由调用方提供。
|
||||||
|
/** @typedef {import('../web/src/pages/Report/contracts').Business} Business */
|
||||||
|
/** @typedef {import('../web/src/pages/Report/contracts').DailyFunds} DailyFunds */
|
||||||
|
/** @typedef {import('../web/src/pages/Report/contracts').OwnershipReceipts} OwnershipReceipts */
|
||||||
|
/** @typedef {import('../web/src/pages/Report/contracts').PayerCosts} PayerCosts */
|
||||||
|
/** @typedef {import('../web/src/pages/Report/contracts').Range} Range */
|
||||||
|
/** @typedef {import('../web/src/pages/Report/contracts').RecoveryCosts} RecoveryCosts */
|
||||||
|
/** @typedef {import('../web/src/pages/Report/contracts').Reimbursement} Reimbursement */
|
||||||
|
/** @typedef {import('../web/src/pages/Report/contracts').ReimbursementList} ReimbursementList */
|
||||||
|
/** @typedef {import('../web/src/pages/Report/contracts').Report} Report */
|
||||||
|
/** @typedef {import('../web/src/pages/Report/contracts').Row} Row */
|
||||||
|
/** @typedef {import('../web/src/pages/Report/contracts').RuleContext} RuleContext */
|
||||||
|
/** @typedef {import('../web/src/pages/Report/contracts').Team} Team */
|
||||||
|
/** @typedef {import('../web/src/pages/Report/contracts').CostItem} CostItem */
|
||||||
|
/** @typedef {import('../web/src/pages/Report/contracts').ReceiptItem} ReceiptItem */
|
||||||
|
/** @typedef {import('../web/src/pages/Report/contracts').Profit} Profit */
|
||||||
|
/** @typedef {import('../web/src/pages/Report/contracts').MaterialValue} MaterialValue */
|
||||||
|
/** @typedef {import('../web/src/pages/Report/contracts').AdvanceItem} AdvanceItem */
|
||||||
(function (root) {
|
(function (root) {
|
||||||
function reportAfterSaleAmount(cost) {
|
/** @param {unknown} value
|
||||||
return cost.items.filter(item => item.kind === 'afterSale').reduce((sum, item) => sum + item.amount, 0);
|
* @returns {value is number} */
|
||||||
|
function integer(value) {
|
||||||
|
return Number.isSafeInteger(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {PayerCosts} cost */
|
||||||
|
function reportAfterSaleAmount(cost) {
|
||||||
|
return cost.items.filter(item => item.kind === 'afterSale').reduce((sum, item) => sum + (item.amount ?? 0), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param {PayerCosts} cost */
|
||||||
function reportCostItems(cost) {
|
function reportCostItems(cost) {
|
||||||
return cost.items.filter(item => item.kind !== 'goods' || item.amount !== 0);
|
return cost.items.filter(item => item.kind !== 'goods' || item.amount !== 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {Row} row */
|
||||||
function reportRowCost(row) {
|
function reportRowCost(row) {
|
||||||
const goods = (row.costItems || []).filter(item => item.kind === 'goods');
|
const goods = (row.costItems || []).filter(item => item.kind === 'goods');
|
||||||
return {
|
return {
|
||||||
@@ -16,10 +42,11 @@
|
|||||||
missing: goods.filter(item => item.amount == null).length,
|
missing: goods.filter(item => item.amount == null).length,
|
||||||
paidFees: (row.costItems || [])
|
paidFees: (row.costItems || [])
|
||||||
.filter(item => ['paid', 'afterSale'].includes(item.kind))
|
.filter(item => ['paid', 'afterSale'].includes(item.kind))
|
||||||
.reduce((sum, item) => sum + item.amount, 0),
|
.reduce((sum, item) => sum + (item.amount ?? 0), 0),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {Business} business */
|
||||||
function reportCurrentAccountDays(business) {
|
function reportCurrentAccountDays(business) {
|
||||||
const account = business.currentAccount;
|
const account = business.currentAccount;
|
||||||
return account.days.length
|
return account.days.length
|
||||||
@@ -42,6 +69,10 @@
|
|||||||
: [];
|
: [];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {{amount:string}[]} items
|
||||||
|
* @param {(value: string) => number} cents
|
||||||
|
*/
|
||||||
function reimbursementAmounts(items, cents) {
|
function reimbursementAmounts(items, cents) {
|
||||||
let total = 0,
|
let total = 0,
|
||||||
complete = true;
|
complete = true;
|
||||||
@@ -63,6 +94,7 @@
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {RuleContext} context */
|
||||||
function forContext({
|
function forContext({
|
||||||
teamDataKeys,
|
teamDataKeys,
|
||||||
validOrderDate,
|
validOrderDate,
|
||||||
@@ -73,7 +105,13 @@
|
|||||||
state,
|
state,
|
||||||
reportMember,
|
reportMember,
|
||||||
}) {
|
}) {
|
||||||
function validateReport(r, range) {
|
/**
|
||||||
|
* @param {unknown} input
|
||||||
|
* @param {Range} range
|
||||||
|
* @returns {asserts input is Report}
|
||||||
|
*/
|
||||||
|
function validateReport(input, range) {
|
||||||
|
const r = /** @type {Report} */ (input);
|
||||||
if (r.basis !== 'orderDate' || r.date !== range.date || r.from !== range.from)
|
if (r.basis !== 'orderDate' || r.date !== range.date || r.from !== range.from)
|
||||||
throw new Error('返回口径或日期与当前选择不一致,请重新读取。');
|
throw new Error('返回口径或日期与当前选择不一致,请重新读取。');
|
||||||
if (
|
if (
|
||||||
@@ -87,7 +125,9 @@
|
|||||||
return (
|
return (
|
||||||
c &&
|
c &&
|
||||||
Array.isArray(c.items) &&
|
Array.isArray(c.items) &&
|
||||||
['goods', 'paidFees', 'total', 'missingCount', 'pendingCount'].every(name => Number.isSafeInteger(c[name]))
|
/** @type {const} */ (['goods', 'paidFees', 'total', 'missingCount', 'pendingCount']).every(name =>
|
||||||
|
Number.isSafeInteger(c[name]),
|
||||||
|
)
|
||||||
);
|
);
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
@@ -103,7 +143,7 @@
|
|||||||
typeof person.name === 'string' &&
|
typeof person.name === 'string' &&
|
||||||
person.name &&
|
person.name &&
|
||||||
Array.isArray(person.items) &&
|
Array.isArray(person.items) &&
|
||||||
['receipt', 'refund', 'net'].every(key => Number.isSafeInteger(person[key])) &&
|
/** @type {const} */ (['receipt', 'refund', 'net']).every(key => Number.isSafeInteger(person[key])) &&
|
||||||
person.items.every(
|
person.items.every(
|
||||||
item =>
|
item =>
|
||||||
item &&
|
item &&
|
||||||
@@ -113,14 +153,16 @@
|
|||||||
validOrderDate(item.date),
|
validOrderDate(item.date),
|
||||||
) &&
|
) &&
|
||||||
person.net === person.receipt - person.refund &&
|
person.net === person.receipt - person.refund &&
|
||||||
['receipt', 'refund'].every(
|
/** @type {const} */ (['receipt', 'refund']).every(
|
||||||
kind =>
|
kind =>
|
||||||
person.items.filter(item => item.kind === kind).reduce((sum, item) => sum + item.amount, 0) ===
|
person.items.filter(item => item.kind === kind).reduce((sum, item) => sum + (item.amount ?? 0), 0) ===
|
||||||
person[kind],
|
person[kind],
|
||||||
),
|
),
|
||||||
) ||
|
) ||
|
||||||
!['receipt', 'refund', 'net'].every(
|
!(
|
||||||
key => recipients.reduce((sum, person) => sum + person[key], 0) === r.receiptsByOrderDate[key],
|
/** @type {const} */ (['receipt', 'refund', 'net']).every(
|
||||||
|
key => recipients.reduce((sum, person) => sum + person[key], 0) === r.receiptsByOrderDate[key],
|
||||||
|
)
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
throw new Error('收款人汇总与明细未完整返回或金额不一致,请重新读取。');
|
throw new Error('收款人汇总与明细未完整返回或金额不一致,请重新读取。');
|
||||||
@@ -129,7 +171,12 @@
|
|||||||
validateDailyProfits(r);
|
validateDailyProfits(r);
|
||||||
}
|
}
|
||||||
|
|
||||||
function validateDailyFunds(data, range) {
|
/**
|
||||||
|
* @param {unknown} input
|
||||||
|
* @param {Range} range
|
||||||
|
*/
|
||||||
|
function validateDailyFunds(input, range) {
|
||||||
|
const data = /** @type {DailyFunds} */ (input);
|
||||||
if (data?.team) {
|
if (data?.team) {
|
||||||
if (data.date !== range.date || data.from !== range.from || !Array.isArray(data.reimbursements))
|
if (data.date !== range.date || data.from !== range.from || !Array.isArray(data.reimbursements))
|
||||||
throw new Error('团队日期或报销资料未完整返回,请重新读取。');
|
throw new Error('团队日期或报销资料未完整返回,请重新读取。');
|
||||||
@@ -137,15 +184,15 @@
|
|||||||
data.reimbursements.forEach(validateReimbursement);
|
data.reimbursements.forEach(validateReimbursement);
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
const money = value => Number.isSafeInteger(value),
|
const money = integer,
|
||||||
nullable = value => value === null || money(value);
|
nullable = (/** @type {unknown} */ value) => value === null || money(value);
|
||||||
if (
|
if (
|
||||||
!data ||
|
!data ||
|
||||||
data.date !== range.date ||
|
data.date !== range.date ||
|
||||||
data.from !== range.from ||
|
data.from !== range.from ||
|
||||||
typeof data.readOnly !== 'boolean' ||
|
typeof data.readOnly !== 'boolean' ||
|
||||||
typeof data.ready !== 'boolean' ||
|
typeof data.ready !== 'boolean' ||
|
||||||
!['receipt', 'refund', 'net'].every(key => money(data.ownerReceipts?.[key])) ||
|
!(/** @type {const} */ (['receipt', 'refund', 'net']).every(key => money(data.ownerReceipts?.[key]))) ||
|
||||||
data.ownerReceipts.net !== data.ownerReceipts.receipt - data.ownerReceipts.refund ||
|
data.ownerReceipts.net !== data.ownerReceipts.receipt - data.ownerReceipts.refund ||
|
||||||
!money(data.approvedReimbursements) ||
|
!money(data.approvedReimbursements) ||
|
||||||
!nullable(data.actualOutlay) ||
|
!nullable(data.actualOutlay) ||
|
||||||
@@ -169,7 +216,7 @@
|
|||||||
item.payer === 'owner' &&
|
item.payer === 'owner' &&
|
||||||
typeof item.name === 'string',
|
typeof item.name === 'string',
|
||||||
) ||
|
) ||
|
||||||
data.sources.items.reduce((sum, item) => sum + item.amount, 0) !== data.sources.total
|
data.sources.items.reduce((sum, item) => sum + (item.amount ?? 0), 0) !== data.sources.total
|
||||||
)
|
)
|
||||||
throw new Error('转账核对资料未完整返回,请重新读取。');
|
throw new Error('转账核对资料未完整返回,请重新读取。');
|
||||||
data.reimbursements.forEach(validateReimbursement);
|
data.reimbursements.forEach(validateReimbursement);
|
||||||
@@ -194,7 +241,9 @@
|
|||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
function validateDailyReimbursements(data) {
|
/** @param {unknown} input */
|
||||||
|
function validateDailyReimbursements(input) {
|
||||||
|
const data = /** @type {ReimbursementList} */ (input);
|
||||||
if (
|
if (
|
||||||
!data ||
|
!data ||
|
||||||
!Array.isArray(data.requests) ||
|
!Array.isArray(data.requests) ||
|
||||||
@@ -202,13 +251,18 @@
|
|||||||
!Number.isSafeInteger(data.offset) ||
|
!Number.isSafeInteger(data.offset) ||
|
||||||
!Number.isSafeInteger(data.limit) ||
|
!Number.isSafeInteger(data.limit) ||
|
||||||
typeof data.hasMore !== 'boolean' ||
|
typeof data.hasMore !== 'boolean' ||
|
||||||
!['pending', 'approved', 'rejected'].every(key => Number.isSafeInteger(data.counts?.[key]))
|
!(
|
||||||
|
/** @type {const} */ (['pending', 'approved', 'rejected']).every(key =>
|
||||||
|
Number.isSafeInteger(data.counts?.[key]),
|
||||||
|
)
|
||||||
|
)
|
||||||
)
|
)
|
||||||
throw new Error('全日期报销列表未完整返回,请重新读取。');
|
throw new Error('全日期报销列表未完整返回,请重新读取。');
|
||||||
data.requests.forEach(validateReimbursement);
|
data.requests.forEach(validateReimbursement);
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {Report} r */
|
||||||
function validateOwnershipReceipts(r) {
|
function validateOwnershipReceipts(r) {
|
||||||
const fail = () => {
|
const fail = () => {
|
||||||
throw new Error('所属订单净收入与账户明细未完整返回或金额不一致,请重新读取。');
|
throw new Error('所属订单净收入与账户明细未完整返回或金额不一致,请重新读取。');
|
||||||
@@ -225,9 +279,10 @@
|
|||||||
!expected.every(key => keys.includes(key))
|
!expected.every(key => keys.includes(key))
|
||||||
)
|
)
|
||||||
fail();
|
fail();
|
||||||
const receipts = [],
|
const receipts = /** @type {OwnershipReceipts[]} */ ([]),
|
||||||
owned = [],
|
owned = [],
|
||||||
sum = (items, kind) => items.filter(item => item.kind === kind).reduce((total, item) => total + item.amount, 0);
|
sum = (/** @type {ReceiptItem[]} */ items, /** @type {string} */ kind) =>
|
||||||
|
items.filter(item => item.kind === kind).reduce((total, item) => total + (item.amount ?? 0), 0);
|
||||||
for (const key of keys) {
|
for (const key of keys) {
|
||||||
const person = r.ownershipReceipts[key];
|
const person = r.ownershipReceipts[key];
|
||||||
if (
|
if (
|
||||||
@@ -237,7 +292,7 @@
|
|||||||
!person.name ||
|
!person.name ||
|
||||||
!Array.isArray(person.accounts) ||
|
!Array.isArray(person.accounts) ||
|
||||||
!Array.isArray(person.items) ||
|
!Array.isArray(person.items) ||
|
||||||
!['receipt', 'refund', 'net'].every(name => Number.isSafeInteger(person[name])) ||
|
!(/** @type {const} */ (['receipt', 'refund', 'net']).every(name => Number.isSafeInteger(person[name]))) ||
|
||||||
person.net !== person.receipt - person.refund
|
person.net !== person.receipt - person.refund
|
||||||
)
|
)
|
||||||
fail();
|
fail();
|
||||||
@@ -250,10 +305,10 @@
|
|||||||
typeof item.account === 'string' &&
|
typeof item.account === 'string' &&
|
||||||
validOrderDate(item.date),
|
validOrderDate(item.date),
|
||||||
) ||
|
) ||
|
||||||
!['receipt', 'refund'].every(kind => sum(person.items, kind) === person[kind])
|
!(/** @type {const} */ (['receipt', 'refund']).every(kind => sum(person.items, kind) === person[kind]))
|
||||||
)
|
)
|
||||||
fail();
|
fail();
|
||||||
const accounts = new Set();
|
const accounts = /** @type {Set<string>} */ (new Set());
|
||||||
for (const account of person.accounts) {
|
for (const account of person.accounts) {
|
||||||
if (
|
if (
|
||||||
!account ||
|
!account ||
|
||||||
@@ -262,7 +317,11 @@
|
|||||||
accounts.has(account.account) ||
|
accounts.has(account.account) ||
|
||||||
!teamMemberKeys().includes(account.recipient) ||
|
!teamMemberKeys().includes(account.recipient) ||
|
||||||
!['wechat', 'alipay', 'cash', 'credit_card'].includes(account.channel) ||
|
!['wechat', 'alipay', 'cash', 'credit_card'].includes(account.channel) ||
|
||||||
!['receipt', 'refund', 'net', 'entryCount'].every(name => Number.isSafeInteger(account[name])) ||
|
!(
|
||||||
|
/** @type {const} */ (['receipt', 'refund', 'net', 'entryCount']).every(name =>
|
||||||
|
Number.isSafeInteger(account[name]),
|
||||||
|
)
|
||||||
|
) ||
|
||||||
account.entryCount < 1 ||
|
account.entryCount < 1 ||
|
||||||
account.net !== account.receipt - account.refund
|
account.net !== account.receipt - account.refund
|
||||||
)
|
)
|
||||||
@@ -270,15 +329,17 @@
|
|||||||
const items = person.items.filter(item => item.account === account.account);
|
const items = person.items.filter(item => item.account === account.account);
|
||||||
if (
|
if (
|
||||||
items.length !== account.entryCount ||
|
items.length !== account.entryCount ||
|
||||||
!['receipt', 'refund'].every(kind => sum(items, kind) === account[kind])
|
!(/** @type {const} */ (['receipt', 'refund']).every(kind => sum(items, kind) === account[kind]))
|
||||||
)
|
)
|
||||||
fail();
|
fail();
|
||||||
accounts.add(account.account);
|
accounts.add(account.account);
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
person.items.some(item => !accounts.has(item.account)) ||
|
person.items.some(item => !accounts.has(item.account)) ||
|
||||||
!['receipt', 'refund', 'net'].every(
|
!(
|
||||||
name => person.accounts.reduce((total, account) => total + account[name], 0) === person[name],
|
/** @type {const} */ (['receipt', 'refund', 'net']).every(
|
||||||
|
name => person.accounts.reduce((total, account) => total + account[name], 0) === person[name],
|
||||||
|
)
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
fail();
|
fail();
|
||||||
@@ -286,12 +347,14 @@
|
|||||||
owned.push(...person.items);
|
owned.push(...person.items);
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
!['receipt', 'refund', 'net'].every(
|
!(
|
||||||
name => receipts.reduce((total, person) => total + person[name], 0) === r.receiptsByOrderDate[name],
|
/** @type {const} */ (['receipt', 'refund', 'net']).every(
|
||||||
|
name => receipts.reduce((total, person) => total + person[name], 0) === r.receiptsByOrderDate[name],
|
||||||
|
)
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
fail();
|
fail();
|
||||||
const identity = item =>
|
const identity = (/** @type {ReceiptItem} */ item) =>
|
||||||
JSON.stringify([item.id, item.kind, item.amount, item.account, item.date, item.order_id, item.price_lock_id]),
|
JSON.stringify([item.id, item.kind, item.amount, item.account, item.date, item.order_id, item.price_lock_id]),
|
||||||
actual = teamDataKeys(r.recipientReceipts)
|
actual = teamDataKeys(r.recipientReceipts)
|
||||||
.flatMap(key => r.recipientReceipts[key].items)
|
.flatMap(key => r.recipientReceipts[key].items)
|
||||||
@@ -301,13 +364,14 @@
|
|||||||
if (actual.length !== copies.length || actual.some((value, index) => value !== copies[index])) fail();
|
if (actual.length !== copies.length || actual.some((value, index) => value !== copies[index])) fail();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {Report} r */
|
||||||
function validateOwnershipBusiness(r) {
|
function validateOwnershipBusiness(r) {
|
||||||
const fail = () => {
|
const fail = () => {
|
||||||
throw new Error('所属订单成本、利润或待转资料未完整返回,请重新读取。');
|
throw new Error('所属订单成本、利润或待转资料未完整返回,请重新读取。');
|
||||||
},
|
},
|
||||||
money = value => Number.isSafeInteger(value),
|
money = integer,
|
||||||
nullable = value => value === null || money(value),
|
nullable = (/** @type {unknown} */ value) => value === null || money(value),
|
||||||
count = value => money(value) && value >= 0,
|
count = (/** @type {unknown} */ value) => money(value) && value >= 0,
|
||||||
keys = teamDataKeys(r.ownershipReceipts);
|
keys = teamDataKeys(r.ownershipReceipts);
|
||||||
if (
|
if (
|
||||||
!r.ownershipBusiness ||
|
!r.ownershipBusiness ||
|
||||||
@@ -328,19 +392,28 @@
|
|||||||
b.from !== r.from ||
|
b.from !== r.from ||
|
||||||
b.date !== r.date ||
|
b.date !== r.date ||
|
||||||
b.netReceipts !== r.ownershipReceipts[member].net ||
|
b.netReceipts !== r.ownershipReceipts[member].net ||
|
||||||
!['sales', 'netReceipts', 'knownTotalCost', 'knownSelfCost', 'knownOtherCost', 'knownProfit'].every(key =>
|
!(
|
||||||
money(b[key]),
|
/** @type {const} */ ([
|
||||||
|
'sales',
|
||||||
|
'netReceipts',
|
||||||
|
'knownTotalCost',
|
||||||
|
'knownSelfCost',
|
||||||
|
'knownOtherCost',
|
||||||
|
'knownProfit',
|
||||||
|
]).every(key => money(b[key]))
|
||||||
|
) ||
|
||||||
|
!(/** @type {const} */ (['totalCost', 'selfCost', 'otherCost', 'profit']).every(key => nullable(b[key]))) ||
|
||||||
|
!(
|
||||||
|
/** @type {const} */ ([
|
||||||
|
'missingCostCount',
|
||||||
|
'pendingCostCount',
|
||||||
|
'unknownProfitCount',
|
||||||
|
'draftCount',
|
||||||
|
'recordCount',
|
||||||
|
'orderCount',
|
||||||
|
'afterSaleCount',
|
||||||
|
]).every(key => count(b[key]))
|
||||||
) ||
|
) ||
|
||||||
!['totalCost', 'selfCost', 'otherCost', 'profit'].every(key => nullable(b[key])) ||
|
|
||||||
![
|
|
||||||
'missingCostCount',
|
|
||||||
'pendingCostCount',
|
|
||||||
'unknownProfitCount',
|
|
||||||
'draftCount',
|
|
||||||
'recordCount',
|
|
||||||
'orderCount',
|
|
||||||
'afterSaleCount',
|
|
||||||
].every(key => count(b[key])) ||
|
|
||||||
typeof b.incomplete !== 'boolean' ||
|
typeof b.incomplete !== 'boolean' ||
|
||||||
typeof b.hasActivity !== 'boolean'
|
typeof b.hasActivity !== 'boolean'
|
||||||
)
|
)
|
||||||
@@ -424,7 +497,7 @@
|
|||||||
: settlement.dueOut !== null || settlement.dueIn !== null
|
: settlement.dueOut !== null || settlement.dueIn !== null
|
||||||
)
|
)
|
||||||
fail();
|
fail();
|
||||||
const seen = new Set();
|
const seen = /** @type {Set<string>} */ (new Set());
|
||||||
for (const row of settlement.counterparts) {
|
for (const row of settlement.counterparts) {
|
||||||
if (
|
if (
|
||||||
!row ||
|
!row ||
|
||||||
@@ -433,8 +506,12 @@
|
|||||||
seen.has(row.member) ||
|
seen.has(row.member) ||
|
||||||
typeof row.name !== 'string' ||
|
typeof row.name !== 'string' ||
|
||||||
!row.name ||
|
!row.name ||
|
||||||
!['dueOut', 'dueIn', 'offset'].every(key => count(row[key])) ||
|
!(/** @type {const} */ (['dueOut', 'dueIn', 'offset']).every(key => count(row[key]))) ||
|
||||||
!['openingDue', 'periodNew', 'periodTransferred', 'closingDue'].every(key => money(row[key])) ||
|
!(
|
||||||
|
/** @type {const} */ (['openingDue', 'periodNew', 'periodTransferred', 'closingDue']).every(key =>
|
||||||
|
money(row[key]),
|
||||||
|
)
|
||||||
|
) ||
|
||||||
row.openingDue + row.periodNew - row.periodTransferred !== row.closingDue ||
|
row.openingDue + row.periodNew - row.periodTransferred !== row.closingDue ||
|
||||||
row.dueOut !== Math.max(0, row.closingDue) ||
|
row.dueOut !== Math.max(0, row.closingDue) ||
|
||||||
row.dueIn !== Math.max(0, -row.closingDue) ||
|
row.dueIn !== Math.max(0, -row.closingDue) ||
|
||||||
@@ -450,7 +527,7 @@
|
|||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
settlement.available &&
|
settlement.available &&
|
||||||
['dueOut', 'dueIn'].some(
|
/** @type {const} */ (['dueOut', 'dueIn']).some(
|
||||||
key => settlement.counterparts.reduce((total, row) => total + row[key], 0) !== settlement[key],
|
key => settlement.counterparts.reduce((total, row) => total + row[key], 0) !== settlement[key],
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
@@ -458,25 +535,26 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {Report} r */
|
||||||
function validateDailyProfits(r) {
|
function validateDailyProfits(r) {
|
||||||
const fail = () => {
|
const fail = () => {
|
||||||
throw new Error('每日利润表未完整返回或与当前对账金额不一致,请重新读取。');
|
throw new Error('每日利润表未完整返回或与当前对账金额不一致,请重新读取。');
|
||||||
},
|
},
|
||||||
table = r.dailyProfits,
|
table = r.dailyProfits,
|
||||||
money = Number.isSafeInteger,
|
money = integer,
|
||||||
count = value => money(value) && value >= 0,
|
count = (/** @type {unknown} */ value) => money(value) && value >= 0,
|
||||||
nullable = value => value === null || money(value),
|
nullable = (/** @type {unknown} */ value) => value === null || money(value),
|
||||||
members = teamDataKeys(r.ownershipReceipts);
|
members = teamDataKeys(r.ownershipReceipts);
|
||||||
const amounts = ['sales', 'knownTotalCost', 'knownProfit'],
|
const amounts = /** @type {const} */ (['sales', 'knownTotalCost', 'knownProfit']),
|
||||||
counts = [
|
counts = /** @type {const} */ ([
|
||||||
'recordCount',
|
'recordCount',
|
||||||
'orderCount',
|
'orderCount',
|
||||||
'afterSaleCount',
|
'afterSaleCount',
|
||||||
'draftCount',
|
'draftCount',
|
||||||
'unknownCostCount',
|
'unknownCostCount',
|
||||||
'unknownProfitCount',
|
'unknownProfitCount',
|
||||||
];
|
]);
|
||||||
const valid = row =>
|
const valid = (/** @type {Profit} */ row) =>
|
||||||
row &&
|
row &&
|
||||||
amounts.every(key => money(row[key])) &&
|
amounts.every(key => money(row[key])) &&
|
||||||
counts.every(key => count(row[key])) &&
|
counts.every(key => count(row[key])) &&
|
||||||
@@ -534,8 +612,9 @@
|
|||||||
fail();
|
fail();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {Team} report */
|
||||||
function validateTeamFunds(report) {
|
function validateTeamFunds(report) {
|
||||||
const money = value => Number.isSafeInteger(value);
|
const money = integer;
|
||||||
if (
|
if (
|
||||||
!report ||
|
!report ||
|
||||||
!Array.isArray(report.pairs) ||
|
!Array.isArray(report.pairs) ||
|
||||||
@@ -553,7 +632,7 @@
|
|||||||
pair.members.length !== 2 ||
|
pair.members.length !== 2 ||
|
||||||
pair.members[0] === pair.members[1] ||
|
pair.members[0] === pair.members[1] ||
|
||||||
!pair.members.every(member => teamMemberKeys().includes(member)) ||
|
!pair.members.every(member => teamMemberKeys().includes(member)) ||
|
||||||
!['net', 'obligationNet', 'transferred', 'due'].every(key => money(pair[key])) ||
|
!(/** @type {const} */ (['net', 'obligationNet', 'transferred', 'due']).every(key => money(pair[key]))) ||
|
||||||
pair.due < 0 ||
|
pair.due < 0 ||
|
||||||
Math.abs(pair.net) !== pair.due ||
|
Math.abs(pair.net) !== pair.due ||
|
||||||
!Array.isArray(pair.entries)
|
!Array.isArray(pair.entries)
|
||||||
@@ -565,6 +644,7 @@
|
|||||||
return report;
|
return report;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {Reimbursement} row */
|
||||||
function validateReimbursement(row) {
|
function validateReimbursement(row) {
|
||||||
if (
|
if (
|
||||||
!row ||
|
!row ||
|
||||||
@@ -583,18 +663,24 @@
|
|||||||
item => typeof item.name === 'string' && item.name && Number.isSafeInteger(item.amount) && item.amount > 0,
|
item => typeof item.name === 'string' && item.name && Number.isSafeInteger(item.amount) && item.amount > 0,
|
||||||
) ||
|
) ||
|
||||||
!Number.isSafeInteger(row.total) ||
|
!Number.isSafeInteger(row.total) ||
|
||||||
row.items.reduce((sum, item) => sum + item.amount, 0) !== row.total
|
row.items.reduce((sum, item) => sum + (item.amount ?? 0), 0) !== row.total
|
||||||
)
|
)
|
||||||
throw new Error('报销单未完整返回,请重新读取。');
|
throw new Error('报销单未完整返回,请重新读取。');
|
||||||
return row;
|
return row;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {Report} r
|
||||||
|
* @param {Business} b
|
||||||
|
* @param {() => never} fail
|
||||||
|
* @returns {RecoveryCosts}
|
||||||
|
*/
|
||||||
function reportAfterSaleRecoveryCosts(r, b, fail) {
|
function reportAfterSaleRecoveryCosts(r, b, fail) {
|
||||||
const money = Number.isSafeInteger,
|
const money = integer,
|
||||||
count = value => money(value) && value >= 0,
|
count = (/** @type {unknown} */ value) => money(value) && value >= 0,
|
||||||
items = [],
|
items = [],
|
||||||
byPayer = Object.fromEntries(teamMemberKeys().map(key => [key, 0]));
|
byPayer = Object.fromEntries(teamMemberKeys().map(key => [key, 0]));
|
||||||
const identity = item =>
|
const identity = (/** @type {Pick<CostItem,'component'|'payer'|'amount'|'source'|'materialPoolId'>} */ item) =>
|
||||||
JSON.stringify([item.component, item.payer, item.amount, item.source, item.materialPoolId ?? null]);
|
JSON.stringify([item.component, item.payer, item.amount, item.source, item.materialPoolId ?? null]);
|
||||||
for (const row of r.orderRows.filter(
|
for (const row of r.orderRows.filter(
|
||||||
row => row.kind === 'orderAfterSale' && (row.member ?? (teamMode() ? null : 'assistant')) === b.member,
|
row => row.kind === 'orderAfterSale' && (row.member ?? (teamMode() ? null : 'assistant')) === b.member,
|
||||||
@@ -620,10 +706,10 @@
|
|||||||
fail();
|
fail();
|
||||||
for (const line of summary.lines) {
|
for (const line of summary.lines) {
|
||||||
if (!line || !count(line.lineIndex) || typeof line.name !== 'string') fail();
|
if (!line || !count(line.lineIndex) || typeof line.name !== 'string') fail();
|
||||||
for (const [component, key, totalKey] of [
|
for (const [component, key, totalKey] of /** @type {const} */ ([
|
||||||
['material', 'materialAllocations', 'materialReturnedCost'],
|
['material', 'materialAllocations', 'materialReturnedCost'],
|
||||||
['labor', 'restockedLaborAllocations', 'laborRestockedCost'],
|
['labor', 'restockedLaborAllocations', 'laborRestockedCost'],
|
||||||
]) {
|
])) {
|
||||||
const parts = line[key];
|
const parts = line[key];
|
||||||
if (
|
if (
|
||||||
!Array.isArray(parts) ||
|
!Array.isArray(parts) ||
|
||||||
@@ -644,7 +730,7 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
['materialReturnedCost', 'laborRestockedCost'].some(
|
/** @type {const} */ (['materialReturnedCost', 'laborRestockedCost']).some(
|
||||||
key => summary.lines.reduce((sum, line) => sum + line[key], 0) !== summary[key],
|
key => summary.lines.reduce((sum, line) => sum + line[key], 0) !== summary[key],
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
@@ -667,7 +753,7 @@
|
|||||||
item.afterSaleExpense !== true ||
|
item.afterSaleExpense !== true ||
|
||||||
item.amount < 0),
|
item.amount < 0),
|
||||||
) ||
|
) ||
|
||||||
row.costItems.reduce((sum, item) => sum + item.amount, 0) !== row.known?.totalCost ||
|
row.costItems.reduce((sum, item) => sum + (item.amount ?? 0), 0) !== row.known?.totalCost ||
|
||||||
row.totalCost !== row.known.totalCost ||
|
row.totalCost !== row.known.totalCost ||
|
||||||
!money(original?.total) ||
|
!money(original?.total) ||
|
||||||
!money(summary.retainedAmount) ||
|
!money(summary.retainedAmount) ||
|
||||||
@@ -678,7 +764,7 @@
|
|||||||
)
|
)
|
||||||
fail();
|
fail();
|
||||||
for (const item of recovered) {
|
for (const item of recovered) {
|
||||||
byPayer[item.payer] += item.amount;
|
byPayer[item.payer] += item.amount ?? 0;
|
||||||
items.push({
|
items.push({
|
||||||
...item,
|
...item,
|
||||||
id: row.id,
|
id: row.id,
|
||||||
@@ -692,14 +778,21 @@
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {Business} b
|
||||||
|
* @param {RecoveryCosts} recoveries
|
||||||
|
* @param {() => never} fail
|
||||||
|
*/
|
||||||
function validatePoolMaterialCosts(b, recoveries, fail) {
|
function validatePoolMaterialCosts(b, recoveries, fail) {
|
||||||
const money = Number.isSafeInteger,
|
const money = integer,
|
||||||
count = value => money(value) && value >= 0,
|
count = (/** @type {unknown} */ value) => money(value) && value >= 0,
|
||||||
nullable = value => value === null || count(value),
|
nullable = (/** @type {unknown} */ value) => value === null || count(value),
|
||||||
pool = b.poolMaterial;
|
pool = b.poolMaterial;
|
||||||
const valid = value =>
|
const valid = (
|
||||||
|
/** @type {Pick<import('../web/src/pages/Report/contracts').PoolMaterial,'mg'|'amount'|'knownAmount'|'missingCount'|'byPayer'>} */ value,
|
||||||
|
) =>
|
||||||
value &&
|
value &&
|
||||||
['mg', 'knownAmount', 'missingCount'].every(key => count(value[key])) &&
|
/** @type {const} */ (['mg', 'knownAmount', 'missingCount']).every(key => count(value[key])) &&
|
||||||
nullable(value.amount) &&
|
nullable(value.amount) &&
|
||||||
value.amount === (value.missingCount ? null : value.knownAmount) &&
|
value.amount === (value.missingCount ? null : value.knownAmount) &&
|
||||||
value.byPayer &&
|
value.byPayer &&
|
||||||
@@ -725,7 +818,7 @@
|
|||||||
(pool.otherCosts.amount !== null && pool.otherCosts.amount !== pool.otherCosts.knownAmount)
|
(pool.otherCosts.amount !== null && pool.otherCosts.amount !== pool.otherCosts.knownAmount)
|
||||||
)
|
)
|
||||||
fail();
|
fail();
|
||||||
const seen = new Set();
|
const seen = /** @type {Set<string>} */ (new Set());
|
||||||
for (const day of pool.days) {
|
for (const day of pool.days) {
|
||||||
if (
|
if (
|
||||||
!valid(day) ||
|
!valid(day) ||
|
||||||
@@ -769,7 +862,7 @@
|
|||||||
seen.add(key);
|
seen.add(key);
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
['mg', 'knownAmount', 'missingCount'].some(
|
/** @type {const} */ (['mg', 'knownAmount', 'missingCount']).some(
|
||||||
key => pool.days.reduce((sum, day) => sum + day[key], 0) !== pool[key],
|
key => pool.days.reduce((sum, day) => sum + day[key], 0) !== pool[key],
|
||||||
) ||
|
) ||
|
||||||
teamMemberKeys().some(
|
teamMemberKeys().some(
|
||||||
@@ -787,12 +880,19 @@
|
|||||||
fail();
|
fail();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {Business} b
|
||||||
|
* @param {RecoveryCosts} recoveries
|
||||||
|
* @param {() => never} fail
|
||||||
|
*/
|
||||||
function validateOwnerAdvances(b, recoveries, fail) {
|
function validateOwnerAdvances(b, recoveries, fail) {
|
||||||
const money = Number.isSafeInteger,
|
const money = integer,
|
||||||
count = value => money(value) && value >= 0,
|
count = (/** @type {unknown} */ value) => money(value) && value >= 0,
|
||||||
nullable = value => value === null || money(value),
|
nullable = (/** @type {unknown} */ value) => value === null || money(value),
|
||||||
advances = b.ownerAdvances;
|
advances = b.ownerAdvances;
|
||||||
const identity = item =>
|
const identity = (
|
||||||
|
/** @type {{id:string; date:string; source:string; component:string; amount:number|null;poolId?:string|null;materialPoolId?:string|null}} */ item,
|
||||||
|
) =>
|
||||||
JSON.stringify([
|
JSON.stringify([
|
||||||
item.id,
|
item.id,
|
||||||
item.date,
|
item.date,
|
||||||
@@ -822,9 +922,11 @@
|
|||||||
!/^\d{4}-\d{2}-\d{2}$/.test(day.date) ||
|
!/^\d{4}-\d{2}-\d{2}$/.test(day.date) ||
|
||||||
!Array.isArray(day.items) ||
|
!Array.isArray(day.items) ||
|
||||||
!day.items.length ||
|
!day.items.length ||
|
||||||
!['knownAmount', 'knownPoolAmount', 'knownOtherAmount'].every(key => money(day[key])) ||
|
!(
|
||||||
!['missingCount', 'pendingCount'].every(key => count(day[key])) ||
|
/** @type {const} */ (['knownAmount', 'knownPoolAmount', 'knownOtherAmount']).every(key => money(day[key]))
|
||||||
!['amount', 'poolAmount', 'otherAmount'].every(key => nullable(day[key]))
|
) ||
|
||||||
|
!(/** @type {const} */ (['missingCount', 'pendingCount']).every(key => count(day[key]))) ||
|
||||||
|
!(/** @type {const} */ (['amount', 'poolAmount', 'otherAmount']).every(key => nullable(day[key])))
|
||||||
)
|
)
|
||||||
fail();
|
fail();
|
||||||
for (const item of day.items) {
|
for (const item of day.items) {
|
||||||
@@ -832,8 +934,10 @@
|
|||||||
!item ||
|
!item ||
|
||||||
item.date !== day.date ||
|
item.date !== day.date ||
|
||||||
!['order', 'afterSale'].includes(item.kind) ||
|
!['order', 'afterSale'].includes(item.kind) ||
|
||||||
!['id', 'number', 'paperNumber', 'customer', 'name', 'source', 'component'].every(
|
!(
|
||||||
key => typeof item[key] === 'string',
|
/** @type {const} */ (['id', 'number', 'paperNumber', 'customer', 'name', 'source', 'component']).every(
|
||||||
|
key => typeof item[key] === 'string',
|
||||||
|
)
|
||||||
) ||
|
) ||
|
||||||
!item.id ||
|
!item.id ||
|
||||||
!item.name ||
|
!item.name ||
|
||||||
@@ -856,13 +960,13 @@
|
|||||||
(item.allocationPending && (!item.poolMaterial || item.status !== 'missing')))
|
(item.allocationPending && (!item.poolMaterial || item.status !== 'missing')))
|
||||||
)
|
)
|
||||||
fail();
|
fail();
|
||||||
if (item.amount < 0 || item.nonCash === true) {
|
if ((item.amount ?? 0) < 0 || item.nonCash === true) {
|
||||||
const index = remaining.indexOf(identity(item));
|
const index = remaining.indexOf(identity(item));
|
||||||
if (
|
if (
|
||||||
item.kind !== 'order' ||
|
item.kind !== 'order' ||
|
||||||
item.status !== 'recorded' ||
|
item.status !== 'recorded' ||
|
||||||
item.nonCash !== true ||
|
item.nonCash !== true ||
|
||||||
item.amount >= 0 ||
|
(item.amount ?? 0) >= 0 ||
|
||||||
index < 0
|
index < 0
|
||||||
)
|
)
|
||||||
fail();
|
fail();
|
||||||
@@ -871,7 +975,7 @@
|
|||||||
}
|
}
|
||||||
const recorded = day.items.filter(item => item.status === 'recorded'),
|
const recorded = day.items.filter(item => item.status === 'recorded'),
|
||||||
missing = day.items.filter(item => item.status === 'missing'),
|
missing = day.items.filter(item => item.status === 'missing'),
|
||||||
total = rows => rows.reduce((sum, item) => sum + item.amount, 0),
|
total = (/** @type {AdvanceItem[]} */ rows) => rows.reduce((sum, item) => sum + (item.amount ?? 0), 0),
|
||||||
poolMissing = missing.some(item => item.poolMaterial),
|
poolMissing = missing.some(item => item.poolMaterial),
|
||||||
otherMissing = missing.some(item => !item.poolMaterial);
|
otherMissing = missing.some(item => !item.poolMaterial);
|
||||||
if (
|
if (
|
||||||
@@ -891,11 +995,16 @@
|
|||||||
if (remaining.length || knownTotal > b.costByPayer.owner.knownTotalCost) fail();
|
if (remaining.length || knownTotal > b.costByPayer.owner.knownTotalCost) fail();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {Business} b
|
||||||
|
* @param {OwnershipReceipts} income
|
||||||
|
* @param {() => never} fail
|
||||||
|
*/
|
||||||
function validateCurrentAccount(b, income, fail) {
|
function validateCurrentAccount(b, income, fail) {
|
||||||
const account = b.currentAccount,
|
const account = b.currentAccount,
|
||||||
money = Number.isSafeInteger,
|
money = integer,
|
||||||
count = value => money(value) && value >= 0,
|
count = (/** @type {unknown} */ value) => money(value) && value >= 0,
|
||||||
nullable = value => value === null || money(value);
|
nullable = (/** @type {unknown} */ value) => value === null || money(value);
|
||||||
if (
|
if (
|
||||||
!account ||
|
!account ||
|
||||||
account.basis !== 'orderDate' ||
|
account.basis !== 'orderDate' ||
|
||||||
@@ -905,14 +1014,14 @@
|
|||||||
)
|
)
|
||||||
fail();
|
fail();
|
||||||
const ownerAccounts = new Set(income.accounts.filter(row => row.recipient === 'owner').map(row => row.account)),
|
const ownerAccounts = new Set(income.accounts.filter(row => row.recipient === 'owner').map(row => row.account)),
|
||||||
received = new Map();
|
received = /** @type {Map<string,number>} */ (new Map());
|
||||||
for (const item of income.items) {
|
for (const item of income.items) {
|
||||||
const date = item.price_lock_id || item.order_after_sale ? item.date : item.order_date;
|
const date = item.price_lock_id || item.order_after_sale ? item.date : item.order_date;
|
||||||
if (!date || date < b.from || date > b.date) continue;
|
if (!date || date < b.from || date > b.date) continue;
|
||||||
if (ownerAccounts.has(item.account))
|
if (ownerAccounts.has(item.account))
|
||||||
received.set(date, (received.get(date) || 0) + (item.kind === 'receipt' ? item.amount : -item.amount));
|
received.set(date, (received.get(date) || 0) + (item.kind === 'receipt' ? item.amount : -item.amount));
|
||||||
}
|
}
|
||||||
const seen = new Set();
|
const seen = /** @type {Set<string>} */ (new Set());
|
||||||
let previous = '';
|
let previous = '';
|
||||||
for (const day of account.days) {
|
for (const day of account.days) {
|
||||||
if (
|
if (
|
||||||
@@ -921,13 +1030,23 @@
|
|||||||
day.date < b.from ||
|
day.date < b.from ||
|
||||||
day.date > b.date ||
|
day.date > b.date ||
|
||||||
day.date <= previous ||
|
day.date <= previous ||
|
||||||
!['recordCount', 'missingCostCount', 'pendingCostCount', 'unknownProfitCount'].every(key =>
|
!(
|
||||||
count(day[key]),
|
/** @type {const} */ (['recordCount', 'missingCostCount', 'pendingCostCount', 'unknownProfitCount']).every(
|
||||||
|
key => count(day[key]),
|
||||||
|
)
|
||||||
) ||
|
) ||
|
||||||
!['knownMaterialCost', 'knownOtherCost', 'knownProfit', 'ownerNetReceipts', 'knownAmount'].every(key =>
|
!(
|
||||||
money(day[key]),
|
/** @type {const} */ ([
|
||||||
|
'knownMaterialCost',
|
||||||
|
'knownOtherCost',
|
||||||
|
'knownProfit',
|
||||||
|
'ownerNetReceipts',
|
||||||
|
'knownAmount',
|
||||||
|
]).every(key => money(day[key]))
|
||||||
|
) ||
|
||||||
|
!(
|
||||||
|
/** @type {const} */ (['materialCost', 'otherCost', 'profit', 'amount']).every(key => nullable(day[key]))
|
||||||
) ||
|
) ||
|
||||||
!['materialCost', 'otherCost', 'profit', 'amount'].every(key => nullable(day[key])) ||
|
|
||||||
typeof day.incomplete !== 'boolean'
|
typeof day.incomplete !== 'boolean'
|
||||||
)
|
)
|
||||||
fail();
|
fail();
|
||||||
@@ -944,9 +1063,9 @@
|
|||||||
const advance = b.ownerAdvances.days.find(row => row.date === day.date),
|
const advance = b.ownerAdvances.days.find(row => row.date === day.date),
|
||||||
items = advance?.items || [],
|
items = advance?.items || [],
|
||||||
recorded = items.filter(item => item.status === 'recorded');
|
recorded = items.filter(item => item.status === 'recorded');
|
||||||
const material = rows => rows.filter(item => item.component === 'material'),
|
const material = (/** @type {AdvanceItem[]} */ rows) => rows.filter(item => item.component === 'material'),
|
||||||
other = rows => rows.filter(item => item.component !== 'material'),
|
other = (/** @type {AdvanceItem[]} */ rows) => rows.filter(item => item.component !== 'material'),
|
||||||
sum = rows => rows.reduce((total, item) => total + item.amount, 0),
|
sum = (/** @type {AdvanceItem[]} */ rows) => rows.reduce((total, item) => total + (item.amount ?? 0), 0),
|
||||||
missing = items.filter(item => item.status === 'missing');
|
missing = items.filter(item => item.status === 'missing');
|
||||||
if (
|
if (
|
||||||
day.knownMaterialCost !== sum(material(recorded)) ||
|
day.knownMaterialCost !== sum(material(recorded)) ||
|
||||||
@@ -969,6 +1088,7 @@
|
|||||||
)
|
)
|
||||||
fail();
|
fail();
|
||||||
}
|
}
|
||||||
|
/** @param {Report} r */
|
||||||
function reportActiveAccounts(r) {
|
function reportActiveAccounts(r) {
|
||||||
const recorded = new Set(
|
const recorded = new Set(
|
||||||
teamDataKeys(r.recipientReceipts).flatMap(key => r.recipientReceipts[key].items.map(item => item.account)),
|
teamDataKeys(r.recipientReceipts).flatMap(key => r.recipientReceipts[key].items.map(item => item.account)),
|
||||||
@@ -983,6 +1103,7 @@
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {Report} r */
|
||||||
function reportOwnershipKeys(r) {
|
function reportOwnershipKeys(r) {
|
||||||
const keys = teamDataKeys(r.ownershipReceipts);
|
const keys = teamDataKeys(r.ownershipReceipts);
|
||||||
return state.user.role === 'owner' && !reportMember
|
return state.user.role === 'owner' && !reportMember
|
||||||
@@ -1018,5 +1139,5 @@
|
|||||||
reimbursementAmounts,
|
reimbursementAmounts,
|
||||||
};
|
};
|
||||||
if (typeof module === 'object' && module.exports) module.exports = api;
|
if (typeof module === 'object' && module.exports) module.exports = api;
|
||||||
else root.ReportRules = api;
|
else Object.assign(root, { ReportRules: api });
|
||||||
})(typeof globalThis === 'object' ? globalThis : this);
|
})(typeof globalThis === 'object' ? globalThis : this);
|
||||||
-20
@@ -1,20 +0,0 @@
|
|||||||
import{n as e,t}from"./rolldown-runtime-Dl_DZoUm.js";import{A as n,B as r,C as i,D as a,E as o,F as s,H as c,I as l,L as u,M as d,N as f,O as p,P as m,R as h,S as g,T as _,_ as v,a as y,b,c as x,d as S,f as C,g as w,h as T,i as E,j as D,k as O,l as k,m as A,n as j,o as M,p as N,r as P,s as F,t as I,u as L,v as R,w as z,x as B,y as V,z as H}from"./antd-Bh8pVx-K.js";import{n as U,t as ee}from"./react-BvkltZ40.js";var W=t(((e,t,n)=>{var r;(function(n,i){typeof e==`object`&&t!==void 0?t.exports=i():typeof r==`function`&&r.amd?r(i):(n=typeof globalThis<`u`?globalThis:n||self).dayjs=i()})(n,(function(){var e=1e3,t=6e4,n=36e5,r=`millisecond`,i=`second`,a=`minute`,o=`hour`,s=`day`,c=`week`,l=`month`,u=`quarter`,d=`year`,f=`date`,p=`Invalid Date`,m=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,h=/\[([^\]]+)]|YYYY|YY|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,g={name:`en`,weekdays:`Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday`.split(`_`),months:`January_February_March_April_May_June_July_August_September_October_November_December`.split(`_`),ordinal:function(e){var t=[`th`,`st`,`nd`,`rd`],n=e%100;return`[`+e+(t[(n-20)%10]||t[n]||t[0])+`]`}},_=function(e,t,n){var r=String(e);return!r||r.length>=t?e:``+Array(t+1-r.length).join(n)+e},v={s:_,z:function(e){var t=-e.utcOffset(),n=Math.abs(t),r=Math.floor(n/60),i=n%60;return(t<=0?`+`:`-`)+_(r,2,`0`)+`:`+_(i,2,`0`)},m:function e(t,n){if(t.date()<n.date())return-e(n,t);var r=12*(n.year()-t.year())+(n.month()-t.month()),i=t.clone().add(r,l),a=n-i<0,o=t.clone().add(r+(a?-1:1),l);return+(-(r+(n-i)/(a?i-o:o-i))||0)},a:function(e){return e<0?Math.ceil(e)||0:Math.floor(e)},p:function(e){return{M:l,y:d,w:c,d:s,D:f,h:o,m:a,s:i,ms:r,Q:u}[e]||String(e||``).toLowerCase().replace(/s$/,``)},u:function(e){return e===void 0}},y=`en`,b={};b[y]=g;var x=`$isDayjsObject`,S=function(e){return e instanceof E||!(!e||!e[x])},C=function e(t,n,r){var i;if(!t)return y;if(typeof t==`string`){var a=t.toLowerCase();b[a]&&(i=a),n&&(b[a]=n,i=a);var o=t.split(`-`);if(!i&&o.length>1)return e(o[0])}else{var s=t.name;b[s]=t,i=s}return!r&&i&&(y=i),i||!r&&y},w=function(e,t){if(S(e))return e.clone();var n=typeof t==`object`?t:{};return n.date=e,n.args=arguments,new E(n)},T=v;T.l=C,T.i=S,T.w=function(e,t){return w(e,{locale:t.$L,utc:t.$u,x:t.$x,$offset:t.$offset})};var E=function(){function g(e){this.$L=C(e.locale,null,!0),this.parse(e),this.$x=this.$x||e.x||{},this[x]=!0}var _=g.prototype;return _.parse=function(e){this.$d=function(e){var t=e.date,n=e.utc;if(t===null)return new Date(NaN);if(T.u(t))return new Date;if(t instanceof Date)return new Date(t);if(typeof t==`string`&&!/Z$/i.test(t)){var r=t.match(m);if(r){var i=r[2]-1||0,a=(r[7]||`0`).substring(0,3);return n?new Date(Date.UTC(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,a)):new Date(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,a)}}return new Date(t)}(e),this.init()},_.init=function(){var e=this.$d;this.$y=e.getFullYear(),this.$M=e.getMonth(),this.$D=e.getDate(),this.$W=e.getDay(),this.$H=e.getHours(),this.$m=e.getMinutes(),this.$s=e.getSeconds(),this.$ms=e.getMilliseconds()},_.$utils=function(){return T},_.isValid=function(){return this.$d.toString()!==p},_.isSame=function(e,t){var n=w(e);return this.startOf(t)<=n&&n<=this.endOf(t)},_.isAfter=function(e,t){return w(e)<this.startOf(t)},_.isBefore=function(e,t){return this.endOf(t)<w(e)},_.$g=function(e,t,n){return T.u(e)?this[t]:this.set(n,e)},_.unix=function(){return Math.floor(this.valueOf()/1e3)},_.valueOf=function(){return this.$d.getTime()},_.startOf=function(e,t){var n=this,r=!!T.u(t)||t,u=T.p(e),p=function(e,t){var i=T.w(n.$u?Date.UTC(n.$y,t,e):new Date(n.$y,t,e),n);return r?i:i.endOf(s)},m=function(e,t){return T.w(n.toDate()[e].apply(n.toDate(`s`),(r?[0,0,0,0]:[23,59,59,999]).slice(t)),n)},h=this.$W,g=this.$M,_=this.$D,v=`set`+(this.$u?`UTC`:``);switch(u){case d:return r?p(1,0):p(31,11);case l:return r?p(1,g):p(0,g+1);case c:var y=this.$locale().weekStart||0,b=(h<y?h+7:h)-y;return p(r?_-b:_+(6-b),g);case s:case f:return m(v+`Hours`,0);case o:return m(v+`Minutes`,1);case a:return m(v+`Seconds`,2);case i:return m(v+`Milliseconds`,3);default:return this.clone()}},_.endOf=function(e){return this.startOf(e,!1)},_.$set=function(e,t){var n,c=T.p(e),u=`set`+(this.$u?`UTC`:``),p=(n={},n[s]=u+`Date`,n[f]=u+`Date`,n[l]=u+`Month`,n[d]=u+`FullYear`,n[o]=u+`Hours`,n[a]=u+`Minutes`,n[i]=u+`Seconds`,n[r]=u+`Milliseconds`,n)[c],m=c===s?this.$D+(t-this.$W):t;if(c===l||c===d){var h=this.clone().set(f,1);h.$d[p](m),h.init(),this.$d=h.set(f,Math.min(this.$D,h.daysInMonth())).$d}else p&&this.$d[p](m);return this.init(),this},_.set=function(e,t){return this.clone().$set(e,t)},_.get=function(e){return this[T.p(e)]()},_.add=function(r,u){var f,p=this;r=Number(r);var m=T.p(u),h=function(e){var t=w(p);return T.w(t.date(t.date()+Math.round(e*r)),p)};if(m===l)return this.set(l,this.$M+r);if(m===d)return this.set(d,this.$y+r);if(m===s)return h(1);if(m===c)reLine truncated
|
|
||||||
0.58×(822+45)+55=558
|
|
||||||
769+558=1327`,value:r,onChange:e=>i(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&e.key===`Enter`&&r.trim()&&(e.preventDefault(),s(!1))}}),(0,q.jsxs)(_,{wrap:!0,style:{marginTop:8},children:[(0,q.jsx)(l,{type:`primary`,onClick:()=>s(!1),children:`识别并预填`}),a?.kind===`warning`&&(0,q.jsx)(l,{onClick:()=>s(!0),children:`按计算金额预填`}),r&&(0,q.jsx)(l,{onClick:()=>{i(``),o(null)},children:`清空公式`})]}),(0,q.jsx)(`p`,{className:`small muted`,children:`括号内是克工费;金价乘克重后加的是一件工费,再加的金额记为附加费。合计行只校验,不增加商品。客户、货盘及内部成本仍按实际填写。`}),a&&(0,q.jsx)(h,{role:`status`,type:a.kind===`note`?`success`:a.kind,message:a.title||(a.kind===`error`?a.lines[0]:``),description:a.kind===`error`?void 0:(0,q.jsx)(`div`,{children:a.lines.filter(Boolean).map((e,t)=>(0,q.jsx)(`p`,{children:e},t))})})]})}function $t({order:e,error:t,onRetry:r,onPreview:i,onNew:a}){let{message:o}=s.useApp(),[c,u]=(0,G.useState)(!1),f=e.total!==void 0;async function p(){if(e.paper_number)try{await navigator.clipboard.writeText(e.paper_number),u(!0),o.success(`已复制纸单号 `+e.paper_number),window.setTimeout(()=>u(!1),1800)}catch{u(!1),o.info(`请手动选择纸单号复制`)}}return(0,q.jsx)(`div`,{className:`issued-page`,children:(0,q.jsx)(O,{className:`issued-card`,children:(0,q.jsx)(w,{status:`success`,title:`销售单据已生成`,subTitle:f?e.materialCostPending?`收款、费用和出库已记账;料费待补,补足购料后自动核算利润。`:`收款、费用、出库和利润已记账。`:t||`正在读取已生成的销售单…`,extra:(0,q.jsxs)(_,{direction:`vertical`,size:`large`,style:{width:`100%`},children:[f&&(0,q.jsxs)(`dl`,{className:`issued-summary`,"data-testid":`issued-summary`,children:[(0,q.jsxs)(`div`,{className:`issued-item`,children:[(0,q.jsx)(`dt`,{children:(0,q.jsx)(S.Text,{type:`secondary`,children:`纸单号`})}),(0,q.jsxs)(`dd`,{className:`issued-value-row`,children:[(0,q.jsx)(`span`,{className:`issued-value num`,"data-testid":`issued-paper-number`,children:e.paper_number||`未分配`}),e.paper_number&&(0,q.jsx)(d,{title:c?`已复制`:`复制纸单号`,children:(0,q.jsx)(l,{type:`text`,size:`small`,className:`issued-copy-btn`,"aria-label":`复制纸单号`,icon:c?(0,q.jsx)(m,{}):(0,q.jsx)(C,{}),onClick:()=>void p()})})]})]}),(0,q.jsxs)(`div`,{className:`issued-item`,children:[(0,q.jsx)(`dt`,{children:(0,q.jsx)(S.Text,{type:`secondary`,children:`成交合计`})}),(0,q.jsx)(`dd`,{className:`issued-value issued-total num`,"data-testid":`issued-total`,children:dt(e.total??null,e.rounding_mode||`cent`)})]}),e.customer&&(0,q.jsxs)(`div`,{className:`issued-item`,children:[(0,q.jsx)(`dt`,{children:(0,q.jsx)(S.Text,{type:`secondary`,children:`客户`})}),(0,q.jsx)(`dd`,{className:`issued-value small`,children:e.customer})]})]}),(0,q.jsxs)(`div`,{className:`issued-actions`,children:[(0,q.jsx)(l,{type:`primary`,size:`large`,icon:(0,q.jsx)(P,{}),href:`/print/`+encodeURIComponent(e.id)+`?mode=full`,onClick:()=>{i().catch(e=>o.error(e.message))},target:`_blank`,rel:`noopener`,"data-action":`print-preview`,children:`打开打印预览`}),(0,q.jsx)(l,{size:`large`,icon:(0,q.jsx)(n,{}),onClick:a,"data-action":`new-order`,children:`开始新的一单`}),!f&&(0,q.jsx)(l,{size:`large`,onClick:r,children:`重新读取订单`})]}),(0,q.jsx)(l,{href:be(`orders`)+`?order=`+encodeURIComponent(e.id),onClick:t=>{t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||(t.preventDefault(),K(`orders`,{search:`?order=`+encodeURIComponent(e.id)}))},type:`link`,icon:(0,q.jsx)(z,{}),children:`查看订单详情`})]})})})})}function en(e){let{client:t,state:n}=e,r=Ae(`draft`),[i,a]=(0,G.useState)(r?null:{draft:oe(window.localStorage,n.user.id),note:``});return(0,G.useEffect)(()=>{if(!r)return;let e=!0;return(async()=>{try{if(n.user.role!==`owner`)throw Error(`已有草稿由店主继续填写并开单;无单号的新开单流程照常使用。`);let i=await t.api(`/api/orders/`+encodeURIComponent(r));if(i.status!==`draft`)throw Error(`这张订单不是未开单的旧草稿,请在订单页查看。`);e&&a({draft:Y.draftInputs(i),note:`正在继续填写旧草稿,生成销售单据后完成记账。`})}catch(t){e&&a({draft:oe(window.localStorage,n.user.id),note:`旧草稿未能打开:`+t.message})}})(),()=>{e=!1}},[t,r,n.user.id,n.user.role]),i?(0,q.jsx)(tn,{...e,initialDraft:i.draft,initialNote:i.note}):(0,q.jsx)(`div`,{className:`page-loading`,children:(0,q.jsx)(b,{tip:`正在读取旧草稿…`,children:(0,q.jsx)(`div`,{style:{height:60}})})})}function tn({client:e,state:t,session:n,refreshState:r,onAccountChanged:i,onRecoverOther:a,initialDraft:o,initialNote:c}){let{message:u}=s.useApp();je(e);let{store:d,update:f,reset:p,ctx:m,poolError:g,loadPools:_}=_t({client:e,state:t,session:n,initialDraft:o}),{form:v,summary:y}=d,[b,C]=(0,G.useState)(``),[w,T]=(0,G.useState)(!1),[E,D]=(0,G.useState)(null),O=E!==null,k
Line truncated
|
|
||||||
`),u=e=>e?.exchange?.fee_items.map(e=>`${e.note}:${e.amount}元 · ${o(e.payer)}付款`).join(`
|
|
||||||
`)||`无`,d=e=>e?.exchange?.charges.map(e=>`${e.name}:${e.amount}元`).join(`
|
|
||||||
`)||`无`,f=n.exchange||{},p=r?.exchange||{},m=e=>e?.mode===`pool`?`料池 `+e.poolId:e?`手填 `+e.rate+`元/克`:`无补金差重`,h=e=>e?e.mode===`gram`?e.rate+`元/克`:e.amount+`元总工费`:`未提供`;if(i.push(a(`业务日期`,n.date,r?.date||`取消原记录`),a(`客户`,n.customer,r?.customer),a(`开单人`,n.salesperson,r?.salesperson),a(`归属`,o(n.member),r?o(r.member):`沿用原身份留档`),a(`旧料逐项称重`,l(n),r?l(r):`冲正原库存及关联购料`),a(`旧料入库货盘`,s(n.old_pocket??`回收旧料`),r?s(r.old_pocket??`回收旧料`):`冲回原入库货盘`),a(`旧料入库数量(对)`,Tn(n.old_stock_count==null?null:Number(n.old_stock_count)),r?Tn(r.old_stock_count==null?null:Number(r.old_stock_count)):`冲回原入库数量`),a(`回收单价(元/克)`,n.buy_rate,r?.buy_rate),a(`回收结算额(元)`,n.buy_total,r?.buy_total),a(`实际收付款账户`,c(n.payment_account),r?c(r.payment_account):`冲正原收付记录`),a(`付款人`,o(n.payer),r?o(r.payer):`原付款流水保留`),a(`备注`,n.note,r?.note)),(n.surplus_mode===`deposit`||r?.surplus_mode===`deposit`)&&i.push(a(`余料处理`,n.surplus_mode===`deposit`?`寄存,暂不结算`:`按回收价结算`,r?r.surplus_mode===`deposit`?`寄存,暂不结算`:`按回收价结算`:`撤回本单寄存余料`)),(n.old_source===`deposit`||r?.old_source===`deposit`)&&i.push(a(`使用客户寄存料`,n.old_source===`deposit`?n.deposit_id+` · `+n.deposit_weight+`g`:`本次交来旧料`,r?.old_source===`deposit`?r.deposit_id+` · `+r.deposit_weight+`g`:r?`本次交来旧料`:`退回寄存账户`)),n.exchange?.items||r?.exchange?.items){let e=e=>(e?.exchange?.items||[]).map((e,t)=>t+1+` · `+e.exchange.name+(e.old_source===`deposit`?` · 寄存记录 `+e.deposit_id+` 使用 `+e.deposit_weight+`g`:``)+(e.surplus_mode===`deposit`?` · 余料寄存,暂不结算`:``)+` · 旧料 `+e.old_lines.map(e=>e.melted_weight+`g × `+e.purity+`%`).join(`+`)+` 入`+s(e.old_pocket)+` · 新货 `+e.exchange.quantity+`g `+(s(e.exchange.pocket)||`外配`)+` · 补金 `+e.exchange.gold_price+`元/g · 折旧 `+e.exchange.depreciation_weight+`g × `+e.exchange.depreciation_rate+`元/g · 回收 `+e.buy_rate+`元/g,`+e.buy_total+`元 · 料费 `+JSON.stringify(e.exchange.cost_material)+` · 料费付款 `+o(e.exchange.cost_material_payer)+` · 进货工费 `+JSON.stringify(e.exchange.cost_labor)+`,`+o(e.exchange.cost_labor_payer)).join(`;`);i.push(a(`逐件置换完整资料`,e(n),r?e(r):`全部冲回`))}if(n.exchange?.products||r?.exchange?.products){let e=e=>(e?.products??(e?[e]:[])).map((e,t)=>t+1+` · `+e.name+` · `+e.quantity+`g · `+(s(e.pocket)||`外配`)+` · 销售工费 `+e.labor_rate+(e.labor_mode===`total`?`元`:`元/克`)+` · 进货工费 `+(e.cost_labor?.rate??e.cost_labor?.amount??`待补`)+` · `+o(e.cost_labor_payer)+(e.stockCount==null?``:` · `+e.stockCount+`对`)).join(`;`);i.push(a(`逐件置换商品`,e(n.exchange),r?e(r.exchange):`冲回全部新货出库`))}n.mode===`exchange`&&i.push(a(`置换新货`,f.name,p.name),a(`新货克重(g)`,f.quantity,p.quantity),a(`实际货盘`,s(f.pocket)||`外配`,r?s(p.pocket)||`外配`:`冲回原出库货盘`),a(`出库数量(对)`,Tn(f.stockCount==null?null:Number(f.stockCount)),Tn(p.stockCount==null?null:Number(p.stockCount))),a(`销售金价(元/克)`,f.gold_price,p.gold_price),a(`销售工费`,f.labor_rate+`元/`+(f.labor_mode===`gram`?`克`:`总额`),r?p.labor_rate+`元/`+(p.labor_mode===`gram`?`克`:`总额`):`取消`),a(`折旧计费克重/单价`,f.depreciation_weight+`g × `+f.depreciation_rate+`元/克`,r?p.depreciation_weight+`g × `+p.depreciation_rate+`元/克`:`取消`),a(`附加收费`,d(n),r?d(r):`取消`),a(`优惠(元)`,f.discount,p.discount),a(`取整方式`,f.rounding_mode===`yuan`?`四舍五入到元`:`保留到分`,r?p.rounding_mode===`yuan`?`四舍五入到元`:`保留到分`:`取消`),a(`补金差重进货来源`,m(f.cost_material),r?m(p.cost_material):`释放原耗用`),a(`料费付款人`,o(f.cost_material_payer),r?o(p.cost_material_payer):`原来源留档`),a(`进货工费`,h(f.cost_labor),r?h(p.cost_labor):`取消`),a(`工费付款人`,o(f.cost_labor_payer),r?o(p.cost_labor_payer):`原来源留档`),a(`实际费用`,u(n),r?u(r):`冲正原费用`));let g=e.summary.before||{},_=e.summary.after||{};return i.push(...[[`实际收客户`,`cashReceipt`],[`实际付客户`,`cashPayment`],[`购料成本`,`purchaseAmount`],[`订单货品成本`,`goodsCost`],[`实际费用`,`directCost`],[`原账利润`,`profit`]].map(([e,t])=>a(e,g[t]==null?`待核实`:`¥`+ut(g[t]),r?_[t]==null?`待核实`:`¥`+ut(_[t]):`取消后冲正`))),(0,q.jsxs)(q.Fragment,{children:[e.summary.legacyCountNotice&&(0,q.jsxs)(`p`,{children:[e.summary.legacyCountNotice,e.summary.legacyCountVerified&&`(申请人已确认)`]}),(0,q.jsx)(`div`,{className:`table-wrap`,children:(0,q.jsxs)(`table`,{"aria-label":`回收更正原值与申请值`,children:[(0,q.jsx)
Line truncated
|
|
||||||
|
|
||||||
`)||`无已记费用`}function N(e){let t=new Set((e.corrections||[]).filter(e=>e.type===`payment`).map(e=>e.target));return e.payments.filter(e=>e.amount>0&&!t.has(e.id)).map(e=>`${e.date} · ${e.kind===`receipt`?`客户收款`:`客户退款`}\n${H(e.amount)} · ${e.account?fe(e.account):`账户未提供`}`).join(`
|
|
||||||
|
|
||||||
`)||`无有效收退款`}function P(e,t,n=`锁价购料成本`){if(!e.priceLockCosts&&!t.priceLockCosts)return``;if(e.priceLockCosts?.lines||t.priceLockCosts?.lines){let n=e.priceLockCosts||{},r=t.priceLockCosts||{},i=n.lines||r.lines;return G.Children.toArray(i.map((e,t)=>{let i=n.lines?.find(t=>t.lineId===e.lineId)||{},a=r.lines?.find(t=>t.lineId===e.lineId)||{};return P({priceLockCosts:{...i,date:n.date}},{priceLockCosts:{...a,date:r.date}},`商品 `+(t+1)+` · 锁价购料成本`)}))}let r=e.priceLockCosts||{},i=t.priceLockCosts||{},a=e=>e===`pool`?`原锁料池`:e===`manual`?`手填原锁料价`:`未提供`;return(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(`tr`,{className:`change-section-row`,children:(0,q.jsx)(`th`,{colSpan:`3`,scope:`colgroup`,children:n})}),I(`原锁日期`,r.date,i.date),I(`原锁料费来源`,a(r.materialSource),a(i.materialSource)),I(`原锁进货料价(每克)`,H(r.buyRate),H(i.buyRate)),I(`原锁料费付款人`,r.materialSource===`pool`?`按原锁料池分摊`:V(r.buyPayer),i.materialSource===`pool`?`按原锁料池分摊`:V(i.buyPayer)),I(`原锁整批料费`,H(r.materialAmount),H(i.materialAmount)),I(`补重进货料价(每克)`,H(r.extraRate),H(i.extraRate)),I(`补重料费付款人`,r.extraPayer?V(r.extraPayer):`无补重`,i.extraPayer?V(i.extraPayer):`无补重`)]})}function F(e,t){if(!e)return`无此商品`;let n=H;if(t===`name`)return`${e.name||`未填写`}${e.priceNote?`
|
|
||||||
`+e.priceNote:``}`;if(t===`code`)return e.code||`未填写`;if(t===`quantity`)return e.unit===`g`?Oe(e.quantity)+`g`:String(e.quantity)+`件`;if(t===`sale`)return n(e.sale);if(t===`pricing`)return e.goldPrice==null?`手填基础金额 ${n(e.baseSale??e.sale)}`:`销售金价 ${n(e.goldPrice)}/克\n${e.laborMode===`gram`?`销售克工费`:`销售件工费`} ${n(e.laborRate)}${e.laborMode===`gram`?`/克`:`/件`}\n件数 ${e.pieces??`未填写`}`;if(t===`stockCount`)return Number.isSafeInteger(e.stockCount)||W(e.pocket)?ee(e.stockCount):`不记录对数`;if(t===`pocket`)return te(e.pocket)||`外配/不扣黄金`;if(t===`charges`)return e.charges?.length?e.charges.map(e=>`${e.name}:${n(e.amount)}`).join(`
|
|
||||||
`):`无附加收费`;if(t===`cost`)return n(e.cost);if(t===`material`){let t=e.costMaterial;return t?.mode===`pool`?`每日购料:${t.poolId}\n本行料费:${n(e.costParts?.material)}${e.materialPool?.allocations?.length?`
|
|
||||||
`+e.materialPool.allocations.map(e=>V(e.payer)+` `+n(e.amount)).join(`;`):e.costParts?.material==null?`
|
|
||||||
待补采购后分摊`:``}`:`${t?.mode===`gram`?`每克料价 `+n(t.rate)+`/克`:`料费总额`}\n${n(e.costParts?.material)}`}return t===`labor`?`${e.costLabor?.mode===`gram`?`进货克工费 `+n(e.costLabor.rate)+`/克`:`进货总工费`}\n${n(e.costParts?.labor)}`:t===`extra`?e.costParts?`配件 ${n(e.costParts.accessories)}\n其他 ${n(e.costParts.other)}`:`原货品成本未分项`:t===`payers`?`料费:${e.costMaterial?.mode===`pool`?e.materialPool?.allocations?.map(e=>V(e.payer)+` `+n(e.amount)).join(`;`)||`按真实采购分摊`:V(e.costPayers?.material??e.payer)}\n进货工费:${V(e.costPayers?.labor??e.payer)}\n配件及其他:${V(e.payer)}`:``}function I(e,t,n){let r=String(t??``)!==String(n??``);return(0,q.jsxs)(`tr`,{...r?{className:`order-change-modified`}:{},children:[(0,q.jsxs)(`th`,{scope:`row`,children:[e,r?(0,q.jsx)(`span`,{className:`change-mark`,children:`已修改`}):``]}),(0,q.jsx)(`td`,{children:B(t)}),(0,q.jsx)(`td`,{children:B(n)})]})}function L(e){if(e===void 0)return[];let t=e=>e===null||Number.isSafeInteger(e)&&e>=0,n=e=>e&&t(e.materialAmount)&&[`usedMaterialAmount`,`leftoverCost`].every(n=>!Object.hasOwn(e,n)||t(e[n]))&&Array.isArray(e.allocations)&&e.allocations.every(e=>Be().includes(e.payer)&&Number.isSafeInteger(e.amount)&&e.amount>=0)&&(e.materialAmount===null||e.allocations.reduce((e,t)=>e+t.amount,0)===e.materialAmount);if(!Array.isArray(e)||!e.every(e=>e&&typeof e.id==`string`&&e.id&&je(e.date)&&n(e.before)&&n(e.after)))throw Error(`关联锁价单的成本影响未完整返回,请重新读取后复核。`);return e}function R(e,t){let n=t=>t&&t.id===e.order_id&&Number.isSafeInteger(t.total)&&Array.isArray(t.lines)&&Array.isArray(t.expenses)&&Array.isArray(t.payments),r=e=>e===null||Number.isSafeInteger(e);if(!e||typeof e.id!=`string`||!e.id||typeof e.order_id!=`string`||t&&e.order_id!==t||!Object.hasOwn(oe,e.status)||!Number.isSafeInteger(e.order_revision)||typeof e.reason!=`string`||typeof e.requester_name!=`string`||typeof e.created!=`string`||typeof e.stale!=`boolean`||typeof e.canApprove!=`boolean`||!n(e.before)||!n(e.after)||![`before`,`after`].every(t=>e.summary?.[t]&&[`total`,`netReceived`,`directCost`].every(n=>Number.isSafeInteger(e.summary[t][n]))&&[`goodsCost`,`profit`,`settlementDue`].every(n=>r(e.summary[t][n]))))throw Error(`修改申请资料未完整返回,请重新读取订单后复核。`);if(e.relatedOrders!==void 0){if(!Array.isArray(e.relatedOrders))throw Error(`关联订单的修改影响未完整返回,请重新读取后复核。`);e.relatedOrders.forEach(t=>R({...e,order_id:t.id,before:t.before,after:t.after,summary:t.summary,relatedOrders:[]}))}if(L(e.relatedPriceLocks),e.action!==void 0&&!Object.hasOwn(se,e.action))throw Error(`变更申请类型未完整返回,请重新读取后复核。`);let i=e.summary.inventory;if(i!==void 0&&(!i||![`before`,`after`,`changes`].every(e=>Array.isArray(i[e])&&i[e].every(e=>typeof e.date==`string`&&typeof e.pocket==`string`&&Number.isSafeInteger(e.mg)))))throw Error(`变更申请库存摘要未完整返回,请重新读取后复核。`);return e}function z(e){let t=R(e),n=t.before,r=t.after,i=(0,q.jsxs)(q.Fragment,{children:[(0,q.jsxs)(q.Fragment,{children:[(0,q.jsxs)(q.Fragment,{children:[G.Children.toArray([[`业务日期`,`date`],[`客户称呼/代号`,`customer`],[`开单人`,`salesperson`],[`收款方式与收款人`,`payment_account`],[`客户单备注`,`note`],[`内部备注(客户不可见)`,`internal_note`]].map(([e,t])=>I(e,t===`payment_account`?fe(n[t]):n[t],t===`payment_account`?fe(r[t]):r[t]))),I(`成交取整方式`,n.rounding_mode===`yuan`?`四舍五入到整数元`:`保留到分`,r.rounding_mode===`yuan`?`四舍五入到整数元`:`保留到分`)]}),I(`新增费用默认支付日期`,n.fees_date||n.date,r.fees_date||r.date)]}),I(`交付日期`,n.delivered_date,r.delivered_date)]}),a=G.Children.toArray([[`成交金额`,`total`],[`收款净额`,`netReceived`],[`货品成本`,`goodsCost`],[`实际费用合计`,`directCost`],[`利润`,`profit`],[`双方待结净额`,`settlementDue`]].map(([e,n])=>I(e,H(t.summary.before[n]),H(t.summary.after[n])))),o=G.Children.toArray(Array.from({length:Math.max(n.lines.length,r.lines.length)},(e,t)=>(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(`tr`,{className:`change-section-row`,children:(0,q.jsxs)(`th`,{colSpan:`3`,scope:`colgroup`,children:[`商品 `,t+1]})}),G.Children.toArray([[`商品与销售计价说明`,`name`],[`商品编号`,`code`],[`克重/数量`,`quantity`],[`销售金价、工费与件数`,`pricing`],[`成交金额(含附加收费)`,`sale`],[`客户附加收费`,`charges`],[`货盘`,`pocket`],[`出库数量(对)`,`stockCount`],[`货品成本合计`,`cost`],[`进货料价与料费`,`material`],[`进货工费`,`labor`],[`其他货品成本`,`extra`],[`成本付款人`,`payers`]].map(([e,i])=>I(e,F(n.lines[t],i),F(r.lines[t],i))))]}))),s=G.Children.toArray((t.relatedOrders||[]).map(e=>(0,q.jsxs)(`section`,{classNameLine truncated
|
|
||||||
`).map((e,t)=>(0,q.jsxs)(G.Fragment,{children:[t>0&&(0,q.jsx)(`br`,{}),e]},t))}function V(e){return e?ze(e):`待补齐`}function H(e){return e==null?`待补齐`:`¥`+He(e)}function U(e){try{return H(J.cents(e))}catch{return`金额未提供`}}function ee(e,{signed:t=!1,unknown:n=`未记录对数`}={}){return Number.isSafeInteger(e)?(t&&e>0?`+`:``)+e+`对`:n}function W(t){return!!t&&e?.pocketCatalog?.some(e=>e.key===t&&e.countUnit===`pair`)===!0}function te(t){return e?.pocketCatalog?.find(e=>e.key===t)?.name||String(t??``)}function ne(e){if(!e||!Array.isArray(e.lines)||!e.lines.length||!e.lines.every(e=>[`quantity`,`materialReturnedCost`,`laborRestockedCost`,`costLoss`].every(t=>Number.isSafeInteger(e[t])))||!e.summary||![`refundAmount`,`retainedAmount`,`materialReturnedCost`,`laborRestockedCost`,`costLoss`,`directCost`,`profit`,`profitAdjustment`].every(t=>Number.isSafeInteger(e.summary[t])))throw Error(`售后核算资料未完整返回,请重新读取订单。`);return e}function re(e,{preview:t=!1}={}){let n=ne(e),r=n.summary,i=e=>`¥`+He(e),a=[[`实际退款`,r.refundAmount],[`扣留客户款`,r.retainedAmount],[`回料池原料成本`,r.materialReturnedCost],[`现货保留工费`,r.laborRestockedCost],[`本单货品成本损失`,r.costLoss],[`售后最终利润`,r.profit],[`本次售后利润调整`,r.profitAdjustment]];return(0,q.jsxs)(`section`,{className:`order-after-sale-summary`+(t?` is-preview`:``),"aria-label":t?`售后核对预览`:`已保存售后详情`,children:[(0,q.jsxs)(`div`,{className:`panel-title`,children:[(0,q.jsx)(`h3`,{children:t?`售后核对预览`:`售后处理结果`}),(0,q.jsx)(`span`,{className:`badge`,children:t?`尚未保存`:`已记账`})]}),(0,q.jsx)(`dl`,{className:`order-after-sale-totals`,children:G.Children.toArray(a.map(([e,t])=>(0,q.jsxs)(`div`,{children:[(0,q.jsx)(`dt`,{children:e}),(0,q.jsx)(`dd`,{...t<0?{className:`danger-text`}:{},children:i(t)})]})))}),(0,q.jsx)(`div`,{className:`table-wrap`,children:(0,q.jsxs)(`table`,{"aria-label":`逐件售后回库与成本`,children:[(0,q.jsx)(`thead`,{children:(0,q.jsxs)(`tr`,{children:[(0,q.jsx)(`th`,{children:`商品与实际去向`}),(0,q.jsx)(`th`,{children:`实际退回`}),(0,q.jsx)(`th`,{children:`回料成本`}),(0,q.jsx)(`th`,{children:`保留工费`}),(0,q.jsx)(`th`,{children:`成本损失`})]})}),(0,q.jsx)(`tbody`,{children:G.Children.toArray(n.lines.map(e=>(0,q.jsxs)(`tr`,{children:[(0,q.jsxs)(`td`,{children:[e.name||`商品 `+(e.lineIndex+1),(0,q.jsxs)(`div`,{className:`small muted`,children:[te(e.pocket),` · `,e.disposition===`stock`?`完好现货`:`旧料/损坏`]})]}),(0,q.jsxs)(`td`,{children:[Oe(e.quantity),`g`,e.disposition===`stock`&&W(e.pocket)?(0,q.jsx)(`div`,{className:`small`,children:ee(e.stockCount)}):``]}),(0,q.jsx)(`td`,{children:i(e.materialReturnedCost)}),(0,q.jsx)(`td`,{children:i(e.laborRestockedCost)}),(0,q.jsx)(`td`,{children:i(e.costLoss)})]})))})]})}),(0,q.jsx)(`p`,{className:`small muted`,children:`实退材料按原成本回售后日料池,不新增采购付款。完好现货工费留在退回现货批次;旧料工费与未退回材料成本计损失。原单实际费用继续保留。`})]})}function ie(e){let t=e.action||`edit`,n=e.action_input||e.action_details||{};if(t===`edit`)return``;if(n.afterSale){let t=ve(e.after);return(0,q.jsxs)(`section`,{className:`order-change-action-summary`,children:[(0,q.jsx)(`h3`,{children:`本次售后申请`}),(0,q.jsxs)(`p`,{children:[`售后日期:`,n.date,` · 申请原因:`,e.reason]}),re(t,{preview:!0})]})}let r=[[`申请动作`,ce(e)],[`业务日期`,n.date||e.after.returned_date||e.after.date]];return n.amount!==void 0&&r.push([`本次金额`,U(n.amount)]),n.account&&r.push([`退款账户`,fe(n.account)]),n.payer&&r.push([`实际付款人`,V(n.payer)]),n.note&&r.push([`费用项目/说明`,n.note]),n.reference&&r.push([`退款凭据备注`,n.reference]),Array.isArray(n.returnCounts)&&r.push([`实际退回数量(对)`,n.returnCounts.map((e,t)=>`商品 `+(t+1)+`:`+ee(e==null?null:Number(e))).join(`
|
|
||||||
`)]),Array.isArray(n.returnPockets)&&r.push([`退货实物去向`,n.returnPockets.map((t,n)=>`${e.before.lines[n]?.name||`商品 `+(n+1)}:${te(t)||`退供应商/不留黄金货盘`}`).join(`
|
|
||||||
`)]),Array.isArray(n.fee_items)&&r.push([`本次旧费用`,n.fee_items.map(e=>`${e.note||`费用`}:${U(e.amount)} · ${V(e.payer)}支付`).join(`
|
|
||||||
`)]),(0,q.jsxs)(`section`,{className:`order-change-action-summary`,children:[(0,q.jsx)(`h3`,{children:`本次申请动作`}),(0,q.jsx)(`dl`,{className:`order-change-action-facts`,children:G.Children.toArray(r.map(([e,t])=>(0,q.jsxs)(`div`,{children:[(0,q.jsx)(`dt`,{children:e}),(0,q.jsx)(`dd`,{children:B(t)})]})))}),(0,q.jsx)(`p`,{className:`small muted`,children:`下方对照为服务器试算;批准后才登记这笔变更,不会由系统发起真实收款、退款或转账。`})]})}function ae(e){let t=new Date(e);return Number.isNaN(t.getTime())?`时间未提供`:t.toLocaleString(`zh-CN`)}let oe={pending:`待店主复核`,approved:`已同意变更`,rejected:`已驳回`},se={edit:`修改订单`,expense:`费用补记`,fees:`旧费用核实`,refund:`退款`,return:`退货`,cost:`成本补录`};function ce(e){return(e.action_input||e.action_details)?.afterSale?`处理订单售后`:e.action_label||se[e.action||`edit`]||`订单变更`}let le={pending:`待店主复核`,approved:`已同意取消`,rejected:`已驳回`};function ue(e){let t=new Date(e);return Number.isNaN(t.getTime())?`时间未提供`:t.toLocaleString(`zh-CN`)}let de=e=>Ie.accountIdentity(Be(),e);function fe(e){let t=de(e);return t?ze(t.member)+t.channel:e}function pe(e){if(!e||![`total`,`netReceived`,`directCost`].every(t=>Number.isSafeInteger(e[t]))||![`goodsCost`,`profit`,`settlementDue`].every(t=>e[t]===null||Number.isSafeInteger(e[t]))||!Array.isArray(e.inventory)||!e.inventory.every(e=>typeof e.date==`string`&&typeof e.pocket==`string`&&Number.isSafeInteger(e.mg)))throw Error(`取消撤销摘要未完整返回,请重新读取订单。`);return e}function me(e=n){let t=Ee(e)?.data;if(!t?.eligible||t.pending||t.directToday!==!0||!/^\d{4}-\d{2}-\d{2}$/.test(t.directActionDate||``)||e.date!==t.directActionDate||e.price_lock_id||![`draft`,`confirmed`,`delivered`].includes(e.status))return!1;try{return pe(t.summary),!0}catch{return!1}}function he(t,r=e.today,i=n){let a=Ce(i)?.data;return[`expense`,`fees`,`refund`,`return`].includes(t)&&!!a&&!a.pending&&/^\d{4}-\d{2}-\d{2}$/.test(a.directActionDate||``)&&a.actions?.[t]?.directToday===!0&&i.date===a.directActionDate&&r===a.directActionDate&&!(o.action===t&&o.forceApproval)}function ge(t){return e.user.role===`assistant`&&[`expense`,`fees`,`refund`,`return`,`cost`].includes(t)}function _e(t,n=e.today){return ge(t)&&!he(t,n)}function ve(e){return e?.orderAfterSale||null}function ye(){return t?.user?.id||``}function be(e=n){return e&&i?.id===e.id&&i.user===ye()&&i.revision===e.revision?i:null}function xe(e=n){return be(e)?.data?.pending||e?.ownershipPending||null}function Se(){return t?.user?.id||``}function Ce(e=n){return e&&r?.id===e.id&&r.user===Se()&&r.revision===e.revision?r:null}function we(e){return Ce(e)?.data?.pending||e?.changePending||null}function Te(){return t?.user?.id||``}function Ee(e=n){return e&&a?.id===e.id&&a.user===Te()&&a.revision===e.revision?a:null}function De(e){return Ee(e)?.data?.pending||e.cancellationPending||null}function K(e){if([`afterSale`,`orderAfterSale`].includes(e.kind))return``;let t=e.printStatus?.printed;return(0,q.jsx)(`span`,{"data-print-kind":e.printStatus?.kind||(e.kind===`recovery`?`recovery`:`order`),"data-print-id":e.printStatus?.id||e.id,className:`document-print-badge `+(t?`is-printed`:`is-unprinted`),title:t?`已记录打印操作`:`尚未记录打印操作`,children:t?`✓ 已打印`:`未打印`})}let Oe=Ie.grams,ke=e=>String(e??``),Ae=new Intl.DateTimeFormat(`zh-CN`,{timeZone:`Asia/Shanghai`,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,hourCycle:`h23`}),je=Ie.validDate;function Me(e){if(typeof e!=`string`||!/^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d{1,3})?)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/.test(e)||!je(e.slice(0,10)))return`未记录`;let t=new Date(e);if(Number.isNaN(t.getTime()))return`未记录`;let n=Object.fromEntries(Ae.formatToParts(t).map(e=>[e.type,e.value]));return`${n.year}-${n.month}-${n.day} ${n.hour}:${n.minute}`}function Ne(e){return(0,q.jsxs)(`div`,{className:`small muted order-entry-time`,children:[`录入时间(北京时间):`,Me(e.created)]})}function Pe(e){return![`afterSale`,`orderAfterSale`,`recovery`].includes(e.kind)&&Number.isSafeInteger(e.revision)&&e.revision>0&&e.reviewed_revision===e.revision}let Fe={draft:`旧草稿`,confirmed:`旧单待补齐`,delivered:`已完成`,returned:`已退货`,cancelled:`已取消`,after_sale:`售后`,recovery:`回收`},Le=e=>(0,q.jsx)(`span`,{className:`order-status `+([`draft`,`confirmed`].includes(e.status)?`danger-text`:`muted`),children:Fe[e.status]||e.status}),Re=(e,t,n=``,r={})=>(0,q.jsx)(`button`,{type:`button`,"data-action":t,className:n,...r,children:e});function ze(n){return e?.shopSettings?.members?.find(e=>e.member===n)?.label||e?.members?.find(e=>e.member===n)?.label||t?.loginOptions?.find(e=>e.member===n)?.label||{owner:`麦麦`,assistant:`娜娜`,assistant2:`小昊`}[n]||`待确认`}function Be(){return Ie.m
Line truncated
|
|
||||||
`)}function a(){return e?.shopSettings?.storeName||e?.printing?.store||t?.brand?.storeName||`珠宝台账`}function o(e=!1,{historical:t=!1,selected:n=``}={}){let r=(t?V():H()).filter(e=>c()||e!==`assistant2`);e&&(r=[...r.filter(e=>e!==`owner`),...r.filter(e=>e===`owner`)]);let i=r.map(e=>[e,R(e)+(t&&!U(e)?`(已停用)`:``)]);return n&&V().includes(n)&&!r.includes(n)&&i.push([n,R(n)+`(已停用 · 原记录)`]),i}function s(){return e?.user?.member||t?.user?.member||(e?.user?.role===`owner`?`owner`:`assistant`)}function c(){return!!(e?.user?.member||e?.members?.some(e=>e.member===`assistant2`))}let l=Ie.validDate;function u(e){return e==null?`待确认`:`¥`+m(e)}function d(e){let{total:t,complete:n,amounts:r}=Oi.reimbursementAmounts(e,J.cents);return{total:t,complete:n,formula:r.map(e=>`¥`+m(e)).join(` + `)}}function f(e){return[...ee(),`owner`].filter(t=>e&&Object.hasOwn(e,t))}function p(e,t){let n=e.unknownCounts?.[t]||0;return n&&e.knownCounts?.[t]===0&&!e[t]&&!e.afterSaleCount?`待补齐`:(n?`已知 `:``)+`¥`+m(e[t])}let m=e=>e==null?`待补`:Ie.yuan(e);function h(e){return e.from===e.date?e.date:e.from+` 至 `+e.date}function g(e){let t=W(e);return t?R(t.member)+t.channel:e}function _(e,t,n=!1){return e===null?(n?`待核算(已核算 ¥`:`待补齐(已知 ¥`)+m(t)+`)`:`¥`+m(e)}function v(e){let t=e.summary,n=e.receiptsByOrderDate;return[a()+`三人账 · `+h(e),`利润留在店里,按订单归属分别记业绩。经营款各自管理;未导入真实期初经营款。`,...ne(e.peopleCount),`销售净额:`+p(t,`sale`),`本期净利润:`+p(t,`profit`),`本期实收:¥`+m(n.receipt)+`;本期实退:¥`+m(n.refund),...D(e),...O(e),...k(e),...A(e),`按实际付款人核对成本`,...f(e.payerCosts).flatMap(t=>{let n=e.payerCosts[t];return[R(t)+`:实际货品支出 `+y(n.goods,n.missingCount)+`;已付费用 ¥`+m(n.paidFees),...Ai(n).map(e=>e.date+` / `+x(e)+` / `+e.name+` / `+C(e))]}),`订单与售后`,...e.orderRows.map(e=>e.date+` / `+(e.paper_number||e.number||e.project)+` / `+(e.customer||`未填客户`)+` / `+R(e.member)+` / 销售 `+E(e,`sale`)+` / 净利润 `+E(e,`profit`)),`历史两人结算不计入团队新债务。`].join(`
|
|
||||||
`)}function y(e,t=0){return t&&e===0?`待补齐`:(t?`已知 `:``)+`¥`+m(e)}function b(e){return[e.missingCount?e.missingCount+` 项成本待补齐`:``,e.pendingCount?e.pendingCount+` 项费用未入账,不计合计`:``].filter(Boolean).join(`;`)}function x(e){return e.materialPoolId?e.materialPoolId+` 购料`:e.kind===`afterSale`?`售后 · `+(e.customer||`未填客户`):(e.price_lock_id?`锁价 · `:``)+(e.paper_number||e.number||`锁价记录`)+(e.customer?` · `+e.customer:``)}function S(e){let t=e.calculation;return t?M(t.quantity)+`g × `+(t.rate==null?e.component===`material`?`每克料价待补齐`:`每克工费待补齐`:m(t.rate)+`元/克`)+(e.amount==null?``:` = `+m(e.amount)+`元`):``}function C(e){return e.kind===`pending`?`未入账`+(e.amount==null?`(金额待补)`:`(登记 ¥`+m(e.amount)+`)`):e.amount==null?`待补齐`:`¥`+m(e.amount)}function w(e){return e.costItems?.[0]?.payer?R(e.costItems[0].payer):`付款人待补`}let T={draft:`旧草稿`,confirmed:`旧单待补齐`,delivered:`已完成`,returned:`已退货`,cancelled:`已取消`,after_sale:`售后`,recovery:`回收`};function E(e,t){if(e.status===`draft`)return`未开单`;if(t===`goods`){let t=ji(e);return y(t.goods,t.missing)}return t===`paidFees`?`¥`+m(ji(e).paidFees):e[t]==null?e.known?.[t]?`已知 ¥`+m(e.known[t])+`(待补齐)`:`待补齐`:`¥`+m(e[t])}function D(e){let t=e.dailyProfits,n=e=>`销售净额 ¥${m(e.sales)} / 成本 ${_(e.totalCost,e.knownTotalCost)} / 利润 ${_(e.profit,e.knownProfit,!0)}`;return[`每日利润表(按日期与订单归属人;普通订单按开单日、锁价成单按交付日、售后按记录日)`,...t.rows.length?t.rows.map(e=>`${e.date} / ${e.name} / ${n(e)}`):[`所选范围暂无订单或售后记录。`],`所选范围合计:${n(t.summary)}`,``]}function O(e){return[`按订单归属核对净收入(收款减退款,已含他人代收,尚未扣成本与费用)`,...ke(e).flatMap(t=>{let n=e.ownershipReceipts[t];return[`${n.name}所属订单净收入:¥${m(n.net)};实收 ¥${m(n.receipt)};实退 ¥${m(n.refund)}`,...n.accounts.map(e=>`${e.recipient===n.member?`本人收款`:`他人代收`} / ${g(e.account)}:实收 ¥${m(e.receipt)},实退 ¥${m(e.refund)},净额 ¥${m(e.net)}`),...re(e.ownershipBusiness[t]),``]})]}function k(e){let t={date:e.date,from:e.from,month:n},r=e.dailyFunds;if(r?.team)return[`每日报销单(按报销日期归集,已批准报销不在当日订单往来重复相加)`,...r.reimbursements.flatMap(e=>[`${e.date} / ${e.requester_name} / ${z[e.status]} / 合计 ¥${m(e.total)}`,...e.items.map(e=>`${e.name}:¥${m(e.amount)}`)]),``];if(!r||r.rangeUnsupported)return[`每天转账核对`,`尚未取得完整转账资料,不输出应转金额。`,``];try{Ee(r,t)}catch{return[`每天转账核对`,`资料未完整返回,不输出应转金额。`,``]}let i=[`每天转账核对(应转合计,未扣已转)`,`${R(`owner`)}实收 ¥${m(r.ownerReceipts.receipt)} − 实退 ¥${m(r.ownerReceipts.refund)} = 净收款 ¥${m(r.ownerReceipts.net)}`];r.ready?i.push(`${R(`owner`)}净收款 ¥${m(r.ownerReceipts.net)} − 确认完整对外支出 ¥${m(r.actualOutlay)} + 已批准报销 ¥${m(r.approvedReimbursements)} = 应转合计 ¥${m(r.transferAmount)}`,r.transferAmount>0?`方向:`+R(`owner`)+`转`+R(`assistant`):r.transferAmount<0?`方向:`+R(`assistant`)+`转`+R(`owner`):`方向:无需转款`):i.push(`当天完整支出尚未全部确认,暂不输出完整应转合计。`,...r.missingDates.length?[`待确认日期:`+r.missingDates.join(`、`)]:[],...r.staleDates.length?[`来源变动待重新确认:`+r.staleDates.join(`、`)]:[]),i.push(`不要与旧按单/剩料待结重复相加;报销与确认不扣订单利润。`,`已批准报销项目(按报销日期归集)`);let a=r.reimbursements.filter(e=>e.status===`approved`);return i.push(...a.length?a.flatMap(e=>[`${e.date} / ${e.requester_name} / 合计 ¥${m(e.total)} / ${e.reviewer_name||R(`owner`)}复核`,...e.items.map(e=>`${e.name}:¥${m(e.amount)}`)]):[`本期暂无已批准报销。`],``),i}function A(e){return[`按收款人汇总(普通订单按开单日归集当前收付,锁价按实际收付日归集;负数为冲回)`,...f(e.recipientReceipts).flatMap(t=>{let n=e.recipientReceipts[t];return[`${n.name}总收款:¥${m(n.receipt)};退款 ¥${m(n.refund)};净收款 ¥${m(n.net)}`,...[`receipt`,`refund`].flatMap(e=>{let t=n.items.filter(t=>t.kind===e),r=e===`receipt`?`收款`:`退款`;return[`${n.name}${r}明细(日期为实际${r}日):`,...t.length?t.map(e=>`${e.date} / ${ie(e)} / ${e.paper_number||e.number||(e.price_lock_id?`锁价记录`:`订单记录`)} / 客户 ${e.customer||`未填客户称呼`} / ${g(e.account)} / ${ae(e)} ¥${m(e.amount)}${e.reference||e.note?` / `+(e.reference||e.note):``}`):[`所选范围没有`+n.name+r+`记录。`],`${r}明细合计:¥${m(n[e])}`]}),``]})]}function j(e){if(!e?.summary?.eventCount)retu
Line truncated
|
|
||||||
+20
@@ -0,0 +1,20 @@
|
|||||||
|
import{n as e,t}from"./rolldown-runtime-Dl_DZoUm.js";import{A as n,B as r,C as i,D as a,E as o,F as s,H as c,I as l,L as u,M as d,N as f,O as p,P as m,R as h,S as g,T as _,_ as v,a as y,b,c as x,d as S,f as C,g as w,h as T,i as E,j as D,k as O,l as k,m as A,n as j,o as M,p as N,r as P,s as F,t as I,u as L,v as R,w as z,x as B,y as V,z as ee}from"./antd-Bh8pVx-K.js";import{n as H,t as U}from"./react-BvkltZ40.js";var W=t(((e,t,n)=>{var r;(function(n,i){typeof e==`object`&&t!==void 0?t.exports=i():typeof r==`function`&&r.amd?r(i):(n=typeof globalThis<`u`?globalThis:n||self).dayjs=i()})(n,(function(){var e=1e3,t=6e4,n=36e5,r=`millisecond`,i=`second`,a=`minute`,o=`hour`,s=`day`,c=`week`,l=`month`,u=`quarter`,d=`year`,f=`date`,p=`Invalid Date`,m=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,h=/\[([^\]]+)]|YYYY|YY|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,g={name:`en`,weekdays:`Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday`.split(`_`),months:`January_February_March_April_May_June_July_August_September_October_November_December`.split(`_`),ordinal:function(e){var t=[`th`,`st`,`nd`,`rd`],n=e%100;return`[`+e+(t[(n-20)%10]||t[n]||t[0])+`]`}},_=function(e,t,n){var r=String(e);return!r||r.length>=t?e:``+Array(t+1-r.length).join(n)+e},v={s:_,z:function(e){var t=-e.utcOffset(),n=Math.abs(t),r=Math.floor(n/60),i=n%60;return(t<=0?`+`:`-`)+_(r,2,`0`)+`:`+_(i,2,`0`)},m:function e(t,n){if(t.date()<n.date())return-e(n,t);var r=12*(n.year()-t.year())+(n.month()-t.month()),i=t.clone().add(r,l),a=n-i<0,o=t.clone().add(r+(a?-1:1),l);return+(-(r+(n-i)/(a?i-o:o-i))||0)},a:function(e){return e<0?Math.ceil(e)||0:Math.floor(e)},p:function(e){return{M:l,y:d,w:c,d:s,D:f,h:o,m:a,s:i,ms:r,Q:u}[e]||String(e||``).toLowerCase().replace(/s$/,``)},u:function(e){return e===void 0}},y=`en`,b={};b[y]=g;var x=`$isDayjsObject`,S=function(e){return e instanceof E||!(!e||!e[x])},C=function e(t,n,r){var i;if(!t)return y;if(typeof t==`string`){var a=t.toLowerCase();b[a]&&(i=a),n&&(b[a]=n,i=a);var o=t.split(`-`);if(!i&&o.length>1)return e(o[0])}else{var s=t.name;b[s]=t,i=s}return!r&&i&&(y=i),i||!r&&y},w=function(e,t){if(S(e))return e.clone();var n=typeof t==`object`?t:{};return n.date=e,n.args=arguments,new E(n)},T=v;T.l=C,T.i=S,T.w=function(e,t){return w(e,{locale:t.$L,utc:t.$u,x:t.$x,$offset:t.$offset})};var E=function(){function g(e){this.$L=C(e.locale,null,!0),this.parse(e),this.$x=this.$x||e.x||{},this[x]=!0}var _=g.prototype;return _.parse=function(e){this.$d=function(e){var t=e.date,n=e.utc;if(t===null)return new Date(NaN);if(T.u(t))return new Date;if(t instanceof Date)return new Date(t);if(typeof t==`string`&&!/Z$/i.test(t)){var r=t.match(m);if(r){var i=r[2]-1||0,a=(r[7]||`0`).substring(0,3);return n?new Date(Date.UTC(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,a)):new Date(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,a)}}return new Date(t)}(e),this.init()},_.init=function(){var e=this.$d;this.$y=e.getFullYear(),this.$M=e.getMonth(),this.$D=e.getDate(),this.$W=e.getDay(),this.$H=e.getHours(),this.$m=e.getMinutes(),this.$s=e.getSeconds(),this.$ms=e.getMilliseconds()},_.$utils=function(){return T},_.isValid=function(){return this.$d.toString()!==p},_.isSame=function(e,t){var n=w(e);return this.startOf(t)<=n&&n<=this.endOf(t)},_.isAfter=function(e,t){return w(e)<this.startOf(t)},_.isBefore=function(e,t){return this.endOf(t)<w(e)},_.$g=function(e,t,n){return T.u(e)?this[t]:this.set(n,e)},_.unix=function(){return Math.floor(this.valueOf()/1e3)},_.valueOf=function(){return this.$d.getTime()},_.startOf=function(e,t){var n=this,r=!!T.u(t)||t,u=T.p(e),p=function(e,t){var i=T.w(n.$u?Date.UTC(n.$y,t,e):new Date(n.$y,t,e),n);return r?i:i.endOf(s)},m=function(e,t){return T.w(n.toDate()[e].apply(n.toDate(`s`),(r?[0,0,0,0]:[23,59,59,999]).slice(t)),n)},h=this.$W,g=this.$M,_=this.$D,v=`set`+(this.$u?`UTC`:``);switch(u){case d:return r?p(1,0):p(31,11);case l:return r?p(1,g):p(0,g+1);case c:var y=this.$locale().weekStart||0,b=(h<y?h+7:h)-y;return p(r?_-b:_+(6-b),g);case s:case f:return m(v+`Hours`,0);case o:return m(v+`Minutes`,1);case a:return m(v+`Seconds`,2);case i:return m(v+`Milliseconds`,3);default:return this.clone()}},_.endOf=function(e){return this.startOf(e,!1)},_.$set=function(e,t){var n,c=T.p(e),u=`set`+(this.$u?`UTC`:``),p=(n={},n[s]=u+`Date`,n[f]=u+`Date`,n[l]=u+`Month`,n[d]=u+`FullYear`,n[o]=u+`Hours`,n[a]=u+`Minutes`,n[i]=u+`Seconds`,n[r]=u+`Milliseconds`,n)[c],m=c===s?this.$D+(t-this.$W):t;if(c===l||c===d){var h=this.clone().set(f,1);h.$d[p](m),h.init(),this.$d=h.set(f,Math.min(this.$D,h.daysInMonth())).$d}else p&&this.$d[p](m);return this.init(),this},_.set=function(e,t){return this.clone().$set(e,t)},_.get=function(e){return this[T.p(e)]()},_.add=function(r,u){var f,p=this;r=Number(r);var m=T.p(u),h=function(e){var t=w(p);return T.w(t.date(t.date()+Math.round(e*r)),p)};if(m===l)return this.set(l,this.$M+r);if(m===d)return this.set(d,this.$y+r);if(m===s)return h(1);if(m===c)reLine truncated
|
||||||
|
0.58×(822+45)+55=558
|
||||||
|
769+558=1327`,value:r,onChange:e=>i(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&e.key===`Enter`&&r.trim()&&(e.preventDefault(),s(!1))}}),(0,J.jsxs)(_,{wrap:!0,style:{marginTop:8},children:[(0,J.jsx)(l,{type:`primary`,onClick:()=>s(!1),children:`识别并预填`}),a?.kind===`warning`&&(0,J.jsx)(l,{onClick:()=>s(!0),children:`按计算金额预填`}),r&&(0,J.jsx)(l,{onClick:()=>{i(``),o(null)},children:`清空公式`})]}),(0,J.jsx)(`p`,{className:`small muted`,children:`括号内是克工费;金价乘克重后加的是一件工费,再加的金额记为附加费。合计行只校验,不增加商品。客户、货盘及内部成本仍按实际填写。`}),a&&(0,J.jsx)(h,{role:`status`,type:a.kind===`note`?`success`:a.kind,message:a.title||(a.kind===`error`?a.lines[0]:``),description:a.kind===`error`?void 0:(0,J.jsx)(`div`,{children:a.lines.filter(Boolean).map((e,t)=>(0,J.jsx)(`p`,{children:e},t))})})]})}function un({order:e,error:t,onRetry:r,onPreview:i,onNew:a}){let{message:o}=s.useApp(),[c,u]=(0,G.useState)(!1),f=e.total!==void 0;async function p(){if(e.paper_number)try{await navigator.clipboard.writeText(e.paper_number),u(!0),o.success(`已复制纸单号 `+e.paper_number),window.setTimeout(()=>u(!1),1800)}catch{u(!1),o.info(`请手动选择纸单号复制`)}}return(0,J.jsx)(`div`,{className:`issued-page`,children:(0,J.jsx)(O,{className:`issued-card`,children:(0,J.jsx)(w,{status:`success`,title:`销售单据已生成`,subTitle:f?e.materialCostPending?`收款、费用和出库已记账;料费待补,补足购料后自动核算利润。`:`收款、费用、出库和利润已记账。`:t||`正在读取已生成的销售单…`,extra:(0,J.jsxs)(_,{direction:`vertical`,size:`large`,style:{width:`100%`},children:[f&&(0,J.jsxs)(`dl`,{className:`issued-summary`,"data-testid":`issued-summary`,children:[(0,J.jsxs)(`div`,{className:`issued-item`,children:[(0,J.jsx)(`dt`,{children:(0,J.jsx)(S.Text,{type:`secondary`,children:`纸单号`})}),(0,J.jsxs)(`dd`,{className:`issued-value-row`,children:[(0,J.jsx)(`span`,{className:`issued-value num`,"data-testid":`issued-paper-number`,children:e.paper_number||`未分配`}),e.paper_number&&(0,J.jsx)(d,{title:c?`已复制`:`复制纸单号`,children:(0,J.jsx)(l,{type:`text`,size:`small`,className:`issued-copy-btn`,"aria-label":`复制纸单号`,icon:c?(0,J.jsx)(m,{}):(0,J.jsx)(C,{}),onClick:()=>void p()})})]})]}),(0,J.jsxs)(`div`,{className:`issued-item`,children:[(0,J.jsx)(`dt`,{children:(0,J.jsx)(S.Text,{type:`secondary`,children:`成交合计`})}),(0,J.jsx)(`dd`,{className:`issued-value issued-total num`,"data-testid":`issued-total`,children:ut(e.total??null,e.rounding_mode||`cent`)})]}),e.customer&&(0,J.jsxs)(`div`,{className:`issued-item`,children:[(0,J.jsx)(`dt`,{children:(0,J.jsx)(S.Text,{type:`secondary`,children:`客户`})}),(0,J.jsx)(`dd`,{className:`issued-value small`,children:e.customer})]})]}),(0,J.jsxs)(`div`,{className:`issued-actions`,children:[(0,J.jsx)(l,{type:`primary`,size:`large`,icon:(0,J.jsx)(P,{}),href:`/print/`+encodeURIComponent(e.id)+`?mode=full`,onClick:()=>{i().catch(e=>o.error(e.message))},target:`_blank`,rel:`noopener`,"data-action":`print-preview`,children:`打开打印预览`}),(0,J.jsx)(l,{size:`large`,icon:(0,J.jsx)(n,{}),onClick:a,"data-action":`new-order`,children:`开始新的一单`}),!f&&(0,J.jsx)(l,{size:`large`,onClick:r,children:`重新读取订单`})]}),(0,J.jsx)(l,{href:ye(`orders`)+`?order=`+encodeURIComponent(e.id),onClick:t=>{t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||(t.preventDefault(),q(`orders`,{search:`?order=`+encodeURIComponent(e.id)}))},type:`link`,icon:(0,J.jsx)(z,{}),children:`查看订单详情`})]})})})})}function dn(e){let{client:t,state:n}=e,r=ke(`draft`),[i,a]=(0,G.useState)(r?null:{draft:oe(window.localStorage,n.user.id),note:``});return(0,G.useEffect)(()=>{if(!r)return;let e=!0;return(async()=>{try{if(n.user.role!==`owner`)throw Error(`已有草稿由店主继续填写并开单;无单号的新开单流程照常使用。`);let i=await t.api(`/api/orders/`+encodeURIComponent(r));if(i.status!==`draft`)throw Error(`这张订单不是未开单的旧草稿,请在订单页查看。`);e&&a({draft:X.draftInputs(i),note:`正在继续填写旧草稿,生成销售单据后完成记账。`})}catch(t){e&&a({draft:oe(window.localStorage,n.user.id),note:`旧草稿未能打开:`+t.message})}})(),()=>{e=!1}},[t,r,n.user.id,n.user.role]),i?(0,J.jsx)(fn,{...e,initialDraft:i.draft,initialNote:i.note}):(0,J.jsx)(`div`,{className:`page-loading`,children:(0,J.jsx)(b,{tip:`正在读取旧草稿…`,children:(0,J.jsx)(`div`,{style:{height:60}})})})}function fn({client:e,state:t,session:n,refreshState:r,onAccountChanged:i,onRecoverOther:a,initialDraft:o,initialNote:c}){let{message:u}=s.useApp();Ae(e);let{store:d,update:f,reset:p,ctx:m,poolError:g,loadPools:_}=Dt({client:e,state:t,session:n,initialDraft:o}),{form:v,summary:y}=d,[b,C]=(0,G.useState)(``),[w,T]=(0,G.useState)(!1),[E,D]=(0,G.useState)(null),O=E!==null,k
Line truncated
|
||||||
|
`),u=e=>e?.exchange?.fee_items.map(e=>`${e.note}:${e.amount}元 · ${o(e.payer)}付款`).join(`
|
||||||
|
`)||`无`,d=e=>e?.exchange?.charges.map(e=>`${e.name}:${e.amount}元`).join(`
|
||||||
|
`)||`无`,f=n.exchange||{},p=r?.exchange||{},m=e=>e?.mode===`pool`?`料池 `+e.poolId:e?`手填 `+e.rate+`元/克`:`无补金差重`,h=e=>e?e.mode===`gram`?e.rate+`元/克`:e.amount+`元总工费`:`未提供`;if(i.push(a(`业务日期`,n.date,r?.date||`取消原记录`),a(`客户`,n.customer,r?.customer),a(`开单人`,n.salesperson,r?.salesperson),a(`归属`,o(n.member),r?o(r.member):`沿用原身份留档`),a(`旧料逐项称重`,l(n),r?l(r):`冲正原库存及关联购料`),a(`旧料入库货盘`,s(n.old_pocket??`回收旧料`),r?s(r.old_pocket??`回收旧料`):`冲回原入库货盘`),a(`旧料入库数量(对)`,Fn(n.old_stock_count==null?null:Number(n.old_stock_count)),r?Fn(r.old_stock_count==null?null:Number(r.old_stock_count)):`冲回原入库数量`),a(`回收单价(元/克)`,n.buy_rate,r?.buy_rate),a(`回收结算额(元)`,n.buy_total,r?.buy_total),a(`实际收付款账户`,c(n.payment_account),r?c(r.payment_account):`冲正原收付记录`),a(`付款人`,o(n.payer),r?o(r.payer):`原付款流水保留`),a(`备注`,n.note,r?.note)),(n.surplus_mode===`deposit`||r?.surplus_mode===`deposit`)&&i.push(a(`余料处理`,n.surplus_mode===`deposit`?`寄存,暂不结算`:`按回收价结算`,r?r.surplus_mode===`deposit`?`寄存,暂不结算`:`按回收价结算`:`撤回本单寄存余料`)),(n.old_source===`deposit`||r?.old_source===`deposit`)&&i.push(a(`使用客户寄存料`,n.old_source===`deposit`?n.deposit_id+` · `+n.deposit_weight+`g`:`本次交来旧料`,r?.old_source===`deposit`?r.deposit_id+` · `+r.deposit_weight+`g`:r?`本次交来旧料`:`退回寄存账户`)),n.exchange?.items||r?.exchange?.items){let e=e=>(e?.exchange?.items||[]).map((e,t)=>t+1+` · `+e.exchange.name+(e.old_source===`deposit`?` · 寄存记录 `+e.deposit_id+` 使用 `+e.deposit_weight+`g`:``)+(e.surplus_mode===`deposit`?` · 余料寄存,暂不结算`:``)+` · 旧料 `+e.old_lines.map(e=>e.melted_weight+`g × `+e.purity+`%`).join(`+`)+` 入`+s(e.old_pocket)+` · 新货 `+e.exchange.quantity+`g `+(s(e.exchange.pocket)||`外配`)+` · 补金 `+e.exchange.gold_price+`元/g · 折旧 `+e.exchange.depreciation_weight+`g × `+e.exchange.depreciation_rate+`元/g · 回收 `+e.buy_rate+`元/g,`+e.buy_total+`元 · 料费 `+JSON.stringify(e.exchange.cost_material)+` · 料费付款 `+o(e.exchange.cost_material_payer)+` · 进货工费 `+JSON.stringify(e.exchange.cost_labor)+`,`+o(e.exchange.cost_labor_payer)).join(`;`);i.push(a(`逐件置换完整资料`,e(n),r?e(r):`全部冲回`))}if(n.exchange?.products||r?.exchange?.products){let e=e=>(e?.products??(e?[e]:[])).map((e,t)=>t+1+` · `+e.name+` · `+e.quantity+`g · `+(s(e.pocket)||`外配`)+` · 销售工费 `+e.labor_rate+(e.labor_mode===`total`?`元`:`元/克`)+` · 进货工费 `+(e.cost_labor?.rate??e.cost_labor?.amount??`待补`)+` · `+o(e.cost_labor_payer)+(e.stockCount==null?``:` · `+e.stockCount+`对`)).join(`;`);i.push(a(`逐件置换商品`,e(n.exchange),r?e(r.exchange):`冲回全部新货出库`))}n.mode===`exchange`&&i.push(a(`置换新货`,f.name,p.name),a(`新货克重(g)`,f.quantity,p.quantity),a(`实际货盘`,s(f.pocket)||`外配`,r?s(p.pocket)||`外配`:`冲回原出库货盘`),a(`出库数量(对)`,Fn(f.stockCount==null?null:Number(f.stockCount)),Fn(p.stockCount==null?null:Number(p.stockCount))),a(`销售金价(元/克)`,f.gold_price,p.gold_price),a(`销售工费`,f.labor_rate+`元/`+(f.labor_mode===`gram`?`克`:`总额`),r?p.labor_rate+`元/`+(p.labor_mode===`gram`?`克`:`总额`):`取消`),a(`折旧计费克重/单价`,f.depreciation_weight+`g × `+f.depreciation_rate+`元/克`,r?p.depreciation_weight+`g × `+p.depreciation_rate+`元/克`:`取消`),a(`附加收费`,d(n),r?d(r):`取消`),a(`优惠(元)`,f.discount,p.discount),a(`取整方式`,f.rounding_mode===`yuan`?`四舍五入到元`:`保留到分`,r?p.rounding_mode===`yuan`?`四舍五入到元`:`保留到分`:`取消`),a(`补金差重进货来源`,m(f.cost_material),r?m(p.cost_material):`释放原耗用`),a(`料费付款人`,o(f.cost_material_payer),r?o(p.cost_material_payer):`原来源留档`),a(`进货工费`,h(f.cost_labor),r?h(p.cost_labor):`取消`),a(`工费付款人`,o(f.cost_labor_payer),r?o(p.cost_labor_payer):`原来源留档`),a(`实际费用`,u(n),r?u(r):`冲正原费用`));let g=e.summary.before||{},_=e.summary.after||{};return i.push(...[[`实际收客户`,`cashReceipt`],[`实际付客户`,`cashPayment`],[`购料成本`,`purchaseAmount`],[`订单货品成本`,`goodsCost`],[`实际费用`,`directCost`],[`原账利润`,`profit`]].map(([e,t])=>a(e,g[t]==null?`待核实`:`¥`+lt(g[t]),r?_[t]==null?`待核实`:`¥`+lt(_[t]):`取消后冲正`))),(0,J.jsxs)(J.Fragment,{children:[e.summary.legacyCountNotice&&(0,J.jsxs)(`p`,{children:[e.summary.legacyCountNotice,e.summary.legacyCountVerified&&`(申请人已确认)`]}),(0,J.jsx)(`div`,{className:`table-wrap`,children:(0,J.jsxs)(`table`,{"aria-label":`回收更正原值与申请值`,children:[(0,J.jsx)
Line truncated
|
||||||
|
`)}function a(){return e?.shopSettings?.storeName||e?.printing?.store||t?.brand?.storeName||`珠宝台账`}function o(e=!1,{historical:t=!1,selected:n=``}={}){let r=(t?V():ee()).filter(e=>c()||e!==`assistant2`);e&&(r=[...r.filter(e=>e!==`owner`),...r.filter(e=>e===`owner`)]);let i=r.map(e=>[e,R(e)+(t&&!H(e)?`(已停用)`:``)]);return n&&V().includes(n)&&!r.includes(n)&&i.push([n,R(n)+`(已停用 · 原记录)`]),i}function s(){return e?.user?.member||t?.user?.member||(e?.user?.role===`owner`?`owner`:`assistant`)}function c(){return!!(e?.user?.member||e?.members?.some(e=>e.member===`assistant2`))}let l=Fe.validDate;function u(e){return e==null?`待确认`:`¥`+m(e)}function d(e){let{total:t,complete:n,amounts:r}=Si.reimbursementAmounts(e,Y.cents);return{total:t,complete:n,formula:r.map(e=>`¥`+m(e)).join(` + `)}}function f(e){return[...U(),`owner`].filter(t=>e&&Object.hasOwn(e,t))}function p(e,t){let n=e.unknownCounts?.[t]||0;return n&&e.knownCounts?.[t]===0&&!e[t]&&!e.afterSaleCount?`待补齐`:(n?`已知 `:``)+`¥`+m(e[t])}let m=e=>e==null?`待补`:Fe.yuan(e);function h(e){return e.from===e.date?e.date:e.from+` 至 `+e.date}function g(e){let t=W(e);return t?R(t.member)+t.channel:e}function _(e,t,n=!1){return e===null?(n?`待核算(已核算 ¥`:`待补齐(已知 ¥`)+m(t)+`)`:`¥`+m(e)}function v(e){let t=e.summary,n=e.receiptsByOrderDate;return[a()+`三人账 · `+h(e),`利润留在店里,按订单归属分别记业绩。经营款各自管理;未导入真实期初经营款。`,...ne(e.peopleCount),`销售净额:`+p(t,`sale`),`本期净利润:`+p(t,`profit`),`本期实收:¥`+m(n.receipt)+`;本期实退:¥`+m(n.refund),...D(e),...O(e),...k(e),...A(e),`按实际付款人核对成本`,...f(e.payerCosts).flatMap(t=>{let n=e.payerCosts[t];return[R(t)+`:实际货品支出 `+y(n.goods,n.missingCount)+`;已付费用 ¥`+m(n.paidFees),...wi(n).map(e=>e.date+` / `+x(e)+` / `+e.name+` / `+C(e))]}),`订单与售后`,...e.orderRows.map(e=>e.date+` / `+(e.paper_number||e.number||e.project)+` / `+(e.customer||`未填客户`)+` / `+R(e.member)+` / 销售 `+E(e,`sale`)+` / 净利润 `+E(e,`profit`)),`历史两人结算不计入团队新债务。`].join(`
|
||||||
|
`)}function y(e,t=0){return t&&e===0?`待补齐`:(t?`已知 `:``)+`¥`+m(e)}function b(e){return[e.missingCount?e.missingCount+` 项成本待补齐`:``,e.pendingCount?e.pendingCount+` 项费用未入账,不计合计`:``].filter(Boolean).join(`;`)}function x(e){return e.materialPoolId?e.materialPoolId+` 购料`:e.kind===`afterSale`?`售后 · `+(e.customer||`未填客户`):(e.price_lock_id?`锁价 · `:``)+(e.paper_number||e.number||`锁价记录`)+(e.customer?` · `+e.customer:``)}function S(e){let t=e.calculation;return t?M(t.quantity)+`g × `+(t.rate==null?e.component===`material`?`每克料价待补齐`:`每克工费待补齐`:m(t.rate)+`元/克`)+(e.amount==null?``:` = `+m(e.amount)+`元`):``}function C(e){return e.kind===`pending`?`未入账`+(e.amount==null?`(金额待补)`:`(登记 ¥`+m(e.amount)+`)`):e.amount==null?`待补齐`:`¥`+m(e.amount)}function w(e){return e.costItems?.[0]?.payer?R(e.costItems[0].payer):`付款人待补`}let T={draft:`旧草稿`,confirmed:`旧单待补齐`,delivered:`已完成`,returned:`已退货`,cancelled:`已取消`,after_sale:`售后`,recovery:`回收`};function E(e,t){if(e.status===`draft`)return`未开单`;if(t===`goods`){let t=Ti(e);return y(t.goods,t.missing)}return t===`paidFees`?`¥`+m(Ti(e).paidFees):e[t]==null?e.known?.[t]?`已知 ¥`+m(e.known[t])+`(待补齐)`:`待补齐`:`¥`+m(e[t])}function D(e){let t=e.dailyProfits,n=e=>`销售净额 ¥${m(e.sales)} / 成本 ${_(e.totalCost,e.knownTotalCost)} / 利润 ${_(e.profit,e.knownProfit,!0)}`;return[`每日利润表(按日期与订单归属人;普通订单按开单日、锁价成单按交付日、售后按记录日)`,...t.rows.length?t.rows.map(e=>`${e.date} / ${e.name} / ${n(e)}`):[`所选范围暂无订单或售后记录。`],`所选范围合计:${n(t.summary)}`,``]}function O(e){return[`按订单归属核对净收入(收款减退款,已含他人代收,尚未扣成本与费用)`,...ke(e).flatMap(t=>{let n=e.ownershipReceipts[t];return[`${n.name}所属订单净收入:¥${m(n.net)};实收 ¥${m(n.receipt)};实退 ¥${m(n.refund)}`,...n.accounts.map(e=>`${e.recipient===n.member?`本人收款`:`他人代收`} / ${g(e.account)}:实收 ¥${m(e.receipt)},实退 ¥${m(e.refund)},净额 ¥${m(e.net)}`),...re(e.ownershipBusiness[t]),``]})]}function k(e){let t={date:e.date,from:e.from,month:n},r=e.dailyFunds;if(r?.team)return[`每日报销单(按报销日期归集,已批准报销不在当日订单往来重复相加)`,...r.reimbursements.flatMap(e=>[`${e.date} / ${e.requester_name} / ${z[e.status]} / 合计 ¥${m(e.total)}`,...e.items.map(e=>`${e.name}:¥${m(e.amount)}`)]),``];if(!r||r.rangeUnsupported)return[`每天转账核对`,`尚未取得完整转账资料,不输出应转金额。`,``];try{Ee(r,t)}catch{return[`每天转账核对`,`资料未完整返回,不输出应转金额。`,``]}let i=[`每天转账核对(应转合计,未扣已转)`,`${R(`owner`)}实收 ¥${m(r.ownerReceipts.receipt)} − 实退 ¥${m(r.ownerReceipts.refund)} = 净收款 ¥${m(r.ownerReceipts.net)}`];r.ready?i.push(`${R(`owner`)}净收款 ¥${m(r.ownerReceipts.net)} − 确认完整对外支出 ¥${m(r.actualOutlay)} + 已批准报销 ¥${m(r.approvedReimbursements)} = 应转合计 ¥${m(r.transferAmount)}`,(r.transferAmount??0)>0?`方向:`+R(`owner`)+`转`+R(`assistant`):(r.transferAmount??0)<0?`方向:`+R(`assistant`)+`转`+R(`owner`):`方向:无需转款`):i.push(`当天完整支出尚未全部确认,暂不输出完整应转合计。`,...r.missingDates.length?[`待确认日期:`+r.missingDates.join(`、`)]:[],...r.staleDates.length?[`来源变动待重新确认:`+r.staleDates.join(`、`)]:[]),i.push(`不要与旧按单/剩料待结重复相加;报销与确认不扣订单利润。`,`已批准报销项目(按报销日期归集)`);let a=r.reimbursements.filter(e=>e.status===`approved`);return i.push(...a.length?a.flatMap(e=>[`${e.date} / ${e.requester_name} / 合计 ¥${m(e.total)} / ${e.reviewer_name||R(`owner`)}复核`,...e.items.map(e=>`${e.name}:¥${m(e.amount)}`)]):[`本期暂无已批准报销。`],``),i}function A(e){return[`按收款人汇总(普通订单按开单日归集当前收付,锁价按实际收付日归集;负数为冲回)`,...f(e.recipientReceipts).flatMap(t=>{let n=e.recipientReceipts[t];return[`${n.name}总收款:¥${m(n.receipt)};退款 ¥${m(n.refund)};净收款 ¥${m(n.net)}`,...[`receipt`,`refund`].flatMap(e=>{let t=n.items.filter(t=>t.kind===e),r=e===`receipt`?`收款`:`退款`;return[`${n.name}${r}明细(日期为实际${r}日):`,...t.length?t.map(e=>`${e.date} / ${ie(e)} / ${e.paper_number||e.number||(e.price_lock_id?`锁价记录`:`订单记录`)} / 客户 ${e.customer||`未填客户称呼`} / ${g(e.account)} / ${ae(e)} ¥${m(e.amount)}${e.reference||e.note?` / `+(e.reference||e.note):``}`):[`所选范围没有`+n.name+r+`记录。`],`${r}明细合计:¥${m(n[e])}`]}),``]})]}function j(e){if(!e?.summary?.event
Line truncated
|
||||||
|
|
||||||
|
`)||`无已记费用`}function M(e){let t=new Set((e.corrections||[]).filter(e=>e.type===`payment`).map(e=>e.target));return e.payments.filter(e=>e.amount>0&&!t.has(e.id)).map(e=>`${e.date} · ${e.kind===`receipt`?`客户收款`:`客户退款`}\n${V(e.amount)} · ${e.account?ue(e.account):`账户未提供`}`).join(`
|
||||||
|
|
||||||
|
`)||`无有效收退款`}function N(e,t,n=`锁价购料成本`){if(!e.priceLockCosts&&!t.priceLockCosts)return``;if(e.priceLockCosts?.lines||t.priceLockCosts?.lines){let n=e.priceLockCosts||{},r=t.priceLockCosts||{},i=n.lines||r.lines;return G.Children.toArray(i.map((e,t)=>{let i=n.lines?.find(t=>t.lineId===e.lineId)||{},a=r.lines?.find(t=>t.lineId===e.lineId)||{};return N({priceLockCosts:{...i,date:n.date}},{priceLockCosts:{...a,date:r.date}},`商品 `+(t+1)+` · 锁价购料成本`)}))}let r=e.priceLockCosts||{},i=t.priceLockCosts||{},a=e=>e===`pool`?`原锁料池`:e===`manual`?`手填原锁料价`:`未提供`;return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`tr`,{className:`change-section-row`,children:(0,J.jsx)(`th`,{colSpan:3,scope:`colgroup`,children:n})}),F(`原锁日期`,r.date,i.date),F(`原锁料费来源`,a(r.materialSource),a(i.materialSource)),F(`原锁进货料价(每克)`,V(r.buyRate),V(i.buyRate)),F(`原锁料费付款人`,r.materialSource===`pool`?`按原锁料池分摊`:B(r.buyPayer),i.materialSource===`pool`?`按原锁料池分摊`:B(i.buyPayer)),F(`原锁整批料费`,V(r.materialAmount),V(i.materialAmount)),F(`补重进货料价(每克)`,V(r.extraRate),V(i.extraRate)),F(`补重料费付款人`,r.extraPayer?B(r.extraPayer):`无补重`,i.extraPayer?B(i.extraPayer):`无补重`)]})}function P(e,t){if(!e)return`无此商品`;let n=V;if(t===`name`)return`${e.name||`未填写`}${e.priceNote?`
|
||||||
|
`+e.priceNote:``}`;if(t===`code`)return e.code||`未填写`;if(t===`quantity`)return e.unit===`g`?q(e.quantity)+`g`:String(e.quantity)+`件`;if(t===`sale`)return n(e.sale);if(t===`pricing`)return e.goldPrice==null?`手填基础金额 ${n(e.baseSale??e.sale)}`:`销售金价 ${n(e.goldPrice)}/克\n${e.laborMode===`gram`?`销售克工费`:`销售件工费`} ${n(e.laborRate)}${e.laborMode===`gram`?`/克`:`/件`}\n件数 ${e.pieces??`未填写`}`;if(t===`stockCount`)return Number.isSafeInteger(e.stockCount)||U(e.pocket)?H(e.stockCount):`不记录对数`;if(t===`pocket`)return W(e.pocket)||`外配/不扣黄金`;if(t===`charges`)return e.charges?.length?e.charges.map(e=>`${e.name}:${n(e.amount)}`).join(`
|
||||||
|
`):`无附加收费`;if(t===`cost`)return n(e.cost);if(t===`material`){let t=e.costMaterial;return t?.mode===`pool`?`每日购料:${t.poolId}\n本行料费:${n(e.costParts?.material)}${e.materialPool?.allocations?.length?`
|
||||||
|
`+e.materialPool.allocations.map(e=>B(e.payer)+` `+n(e.amount)).join(`;`):e.costParts?.material==null?`
|
||||||
|
待补采购后分摊`:``}`:`${t?.mode===`gram`?`每克料价 `+n(t.rate)+`/克`:`料费总额`}\n${n(e.costParts?.material)}`}return t===`labor`?`${e.costLabor?.mode===`gram`?`进货克工费 `+n(e.costLabor.rate)+`/克`:`进货总工费`}\n${n(e.costParts?.labor)}`:t===`extra`?e.costParts?`配件 ${n(e.costParts.accessories)}\n其他 ${n(e.costParts.other)}`:`原货品成本未分项`:t===`payers`?`料费:${e.costMaterial?.mode===`pool`?e.materialPool?.allocations?.map(e=>B(e.payer)+` `+n(e.amount)).join(`;`)||`按真实采购分摊`:B(e.costPayers?.material??e.payer)}\n进货工费:${B(e.costPayers?.labor??e.payer)}\n配件及其他:${B(e.payer)}`:``}function F(e,t,n){let r=String(t??``)!==String(n??``);return(0,J.jsxs)(`tr`,{...r?{className:`order-change-modified`}:{},children:[(0,J.jsxs)(`th`,{scope:`row`,children:[e,r?(0,J.jsx)(`span`,{className:`change-mark`,children:`已修改`}):``]}),(0,J.jsx)(`td`,{children:z(t)}),(0,J.jsx)(`td`,{children:z(n)})]})}function I(e){if(e===void 0)return[];let t=e=>e===null||Number.isSafeInteger(e)&&e>=0,n=e=>e&&t(e.materialAmount)&&[`usedMaterialAmount`,`leftoverCost`].every(n=>!Object.hasOwn(e,n)||t(e[n]))&&Array.isArray(e.allocations)&&e.allocations.every(e=>Re().includes(e.payer)&&Number.isSafeInteger(e.amount)&&e.amount>=0)&&(e.materialAmount===null||e.allocations.reduce((e,t)=>e+t.amount,0)===e.materialAmount);if(!Array.isArray(e)||!e.every(e=>e&&typeof e.id==`string`&&e.id&&ke(e.date)&&n(e.before)&&n(e.after)))throw Error(`关联锁价单的成本影响未完整返回,请重新读取后复核。`);return e}function L(e,t=void 0){let n=t=>t&&t.id===e.order_id&&Number.isSafeInteger(t.total)&&Array.isArray(t.lines)&&Array.isArray(t.expenses)&&Array.isArray(t.payments),r=e=>e===null||Number.isSafeInteger(e);if(!e||typeof e.id!=`string`||!e.id||typeof e.order_id!=`string`||t&&e.order_id!==t||!Object.hasOwn(ae,e.status)||!Number.isSafeInteger(e.order_revision)||typeof e.reason!=`string`||typeof e.requester_name!=`string`||typeof e.created!=`string`||typeof e.stale!=`boolean`||typeof e.canApprove!=`boolean`||!n(e.before)||!n(e.after)||![`before`,`after`].every(t=>e.summary?.[t]&&[`total`,`netReceived`,`directCost`].every(n=>Number.isSafeInteger(e.summary[t][n]))&&[`goodsCost`,`profit`,`settlementDue`].every(n=>r(e.summary[t][n]))))throw Error(`修改申请资料未完整返回,请重新读取订单后复核。`);if(e.relatedOrders!==void 0){if(!Array.isArray(e.relatedOrders))throw Error(`关联订单的修改影响未完整返回,请重新读取后复核。`);e.relatedOrders.forEach(t=>L({...e,order_id:t.id,before:t.before,after:t.after,summary:t.summary,relatedOrders:[]}))}if(I(e.relatedPriceLocks),e.action!==void 0&&!Object.hasOwn(oe,e.action))throw Error(`变更申请类型未完整返回,请重新读取后复核。`);let i=e.summary.inventory;if(i!==void 0&&(!i||![`before`,`after`,`changes`].every(e=>Array.isArray(i[e])&&i[e].every(e=>typeof e.date==`string`&&typeof e.pocket==`string`&&Number.isSafeInteger(e.mg)))))throw Error(`变更申请库存摘要未完整返回,请重新读取后复核。`);return e}function R(e){let t=L(e),n=t.before,r=t.after,i=(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(J.Fragment,{children:[G.Children.toArray([[`业务日期`,`date`],[`客户称呼/代号`,`customer`],[`开单人`,`salesperson`],[`收款方式与收款人`,`payment_account`],[`客户单备注`,`note`],[`内部备注(客户不可见)`,`internal_note`]].map(([e,t])=>F(e,t===`payment_account`?ue(n[t]):n[t],t===`payment_account`?ue(r[t]):r[t]))),F(`成交取整方式`,n.rounding_mode===`yuan`?`四舍五入到整数元`:`保留到分`,r.rounding_mode===`yuan`?`四舍五入到整数元`:`保留到分`)]}),F(`新增费用默认支付日期`,n.fees_date||n.date,r.fees_date||r.date)]}),F(`交付日期`,n.delivered_date,r.delivered_date)]}),a=G.Children.toArray([[`成交金额`,`total`],[`收款净额`,`netReceived`],[`货品成本`,`goodsCost`],[`实际费用合计`,`directCost`],[`利润`,`profit`],[`双方待结净额`,`settlementDue`]].map(([e,n])=>F(e,V(t.summary.before[n]),V(t.summary.after[n])))),o=G.Children.toArray(Array.from({length:Math.max(n.lines.length,r.lines.length)},(e,t)=>(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`tr`,{className:`change-section-row`,children:(0,J.jsxs)(`th`,{colSpan:3,scope:`colgroup`,children:[`商品 `,t+1]})}),G.Children.toArray([[`商品与销售计价说明`,`name`],[`商品编号`,`code`],[`克重/数量`,`quantity`],[`销售金价、工费与件数`,`pricing`],[`成交金额(含附加收费)`,`sale`],[`客户附加收费`,`charges`],[`货盘`,`pocket`],[`出库数量(对)`,`stockCount`],[`货品成本合计`,`cost`],[`进货料价与料费`,`material`],[`进货工费`,`labor`],[`其他货品成本`,`extra`],[`成本付款人`,`payers`]].map(([e,i])=>F(e,P(n.lines[t],i),P(r.lines[t],i))))]}))),s=G.Children.toArray((t.relatedOrders||[]).map(e=>(0,J.jsxs)(`section`,{clasLine truncated
|
||||||
|
`).map((e,t)=>(0,J.jsxs)(G.Fragment,{children:[t>0&&(0,J.jsx)(`br`,{}),e]},t))}function B(e){return e?Le(e):`待补齐`}function V(e){return e==null?`待补齐`:`¥`+Ve(e)}function ee(e){try{return V(Y.cents(e))}catch{return`金额未提供`}}function H(e,{signed:t=!1,unknown:n=`未记录对数`}={}){return Number.isSafeInteger(e)?(t&&Number(e)>0?`+`:``)+e+`对`:n}function U(t){return!!t&&e?.pocketCatalog?.some(e=>e.key===t&&e.countUnit===`pair`)===!0}function W(t){return e?.pocketCatalog?.find(e=>e.key===t)?.name||String(t??``)}function te(e){if(!e||!Array.isArray(e.lines)||!e.lines.length||!e.lines.every(e=>[`quantity`,`materialReturnedCost`,`laborRestockedCost`,`costLoss`].every(t=>Number.isSafeInteger(e[t])))||!e.summary||![`refundAmount`,`retainedAmount`,`materialReturnedCost`,`laborRestockedCost`,`costLoss`,`directCost`,`profit`,`profitAdjustment`].every(t=>Number.isSafeInteger(e.summary[t])))throw Error(`售后核算资料未完整返回,请重新读取订单。`);return e}function ne(e,{preview:t=!1}={}){let n=te(e),r=n.summary,i=e=>`¥`+Ve(e),a=[[`实际退款`,r.refundAmount],[`扣留客户款`,r.retainedAmount],[`回料池原料成本`,r.materialReturnedCost],[`现货保留工费`,r.laborRestockedCost],[`本单货品成本损失`,r.costLoss],[`售后最终利润`,r.profit],[`本次售后利润调整`,r.profitAdjustment]];return(0,J.jsxs)(`section`,{className:`order-after-sale-summary`+(t?` is-preview`:``),"aria-label":t?`售后核对预览`:`已保存售后详情`,children:[(0,J.jsxs)(`div`,{className:`panel-title`,children:[(0,J.jsx)(`h3`,{children:t?`售后核对预览`:`售后处理结果`}),(0,J.jsx)(`span`,{className:`badge`,children:t?`尚未保存`:`已记账`})]}),(0,J.jsx)(`dl`,{className:`order-after-sale-totals`,children:G.Children.toArray(a.map(([e,t])=>(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`dt`,{children:e}),(0,J.jsx)(`dd`,{...t<0?{className:`danger-text`}:{},children:i(t)})]})))}),(0,J.jsx)(`div`,{className:`table-wrap`,children:(0,J.jsxs)(`table`,{"aria-label":`逐件售后回库与成本`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:`商品与实际去向`}),(0,J.jsx)(`th`,{children:`实际退回`}),(0,J.jsx)(`th`,{children:`回料成本`}),(0,J.jsx)(`th`,{children:`保留工费`}),(0,J.jsx)(`th`,{children:`成本损失`})]})}),(0,J.jsx)(`tbody`,{children:G.Children.toArray(n.lines.map(e=>(0,J.jsxs)(`tr`,{children:[(0,J.jsxs)(`td`,{children:[e.name||`商品 `+(e.lineIndex+1),(0,J.jsxs)(`div`,{className:`small muted`,children:[W(e.pocket),` · `,e.disposition===`stock`?`完好现货`:`旧料/损坏`]})]}),(0,J.jsxs)(`td`,{children:[q(e.quantity),`g`,e.disposition===`stock`&&U(e.pocket)?(0,J.jsx)(`div`,{className:`small`,children:H(e.stockCount)}):``]}),(0,J.jsx)(`td`,{children:i(e.materialReturnedCost)}),(0,J.jsx)(`td`,{children:i(e.laborRestockedCost)}),(0,J.jsx)(`td`,{children:i(e.costLoss)})]})))})]})}),(0,J.jsx)(`p`,{className:`small muted`,children:`实退材料按原成本回售后日料池,不新增采购付款。完好现货工费留在退回现货批次;旧料工费与未退回材料成本计损失。原单实际费用继续保留。`})]})}function re(e){let t=e.action||`edit`,n=e.action_input||e.action_details||{};if(t===`edit`)return``;if(n.afterSale){let t=ge(e.after);return(0,J.jsxs)(`section`,{className:`order-change-action-summary`,children:[(0,J.jsx)(`h3`,{children:`本次售后申请`}),(0,J.jsxs)(`p`,{children:[`售后日期:`,n.date,` · 申请原因:`,e.reason]}),ne(t,{preview:!0})]})}let r=[[`申请动作`,se(e)],[`业务日期`,n.date||e.after.returned_date||e.after.date]];return n.amount!==void 0&&r.push([`本次金额`,ee(n.amount)]),n.account&&r.push([`退款账户`,ue(n.account)]),n.payer&&r.push([`实际付款人`,B(n.payer)]),n.note&&r.push([`费用项目/说明`,n.note]),n.reference&&r.push([`退款凭据备注`,n.reference]),Array.isArray(n.returnCounts)&&r.push([`实际退回数量(对)`,n.returnCounts.map((e,t)=>`商品 `+(t+1)+`:`+H(e==null?null:Number(e))).join(`
|
||||||
|
`)]),Array.isArray(n.returnPockets)&&r.push([`退货实物去向`,n.returnPockets.map((t,n)=>`${e.before.lines[n]?.name||`商品 `+(n+1)}:${W(t)||`退供应商/不留黄金货盘`}`).join(`
|
||||||
|
`)]),Array.isArray(n.fee_items)&&r.push([`本次旧费用`,n.fee_items.map(e=>`${e.note||`费用`}:${ee(e.amount)} · ${B(e.payer)}支付`).join(`
|
||||||
|
`)]),(0,J.jsxs)(`section`,{className:`order-change-action-summary`,children:[(0,J.jsx)(`h3`,{children:`本次申请动作`}),(0,J.jsx)(`dl`,{className:`order-change-action-facts`,children:G.Children.toArray(r.map(([e,t])=>(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`dt`,{children:e}),(0,J.jsx)(`dd`,{children:z(t)})]})))}),(0,J.jsx)(`p`,{className:`small muted`,children:`下方对照为服务器试算;批准后才登记这笔变更,不会由系统发起真实收款、退款或转账。`})]})}function ie(e){let t=new Date(e);return Number.isNaN(t.getTime())?`时间未提供`:t.toLocaleString(`zh-CN`)}let ae={pending:`待店主复核`,approved:`已同意变更`,rejected:`已驳回`},oe={edit:`修改订单`,expense:`费用补记`,fees:`旧费用核实`,refund:`退款`,return:`退货`,cost:`成本补录`};function se(e){return(e.action_input||e.action_details)?.afterSale?`处理订单售后`:e.action_label||oe[e.action||`edit`]||`订单变更`}let K={pending:`待店主复核`,approved:`已同意取消`,rejected:`已驳回`};function ce(e){let t=new Date(e);return Number.isNaN(t.getTime())?`时间未提供`:t.toLocaleString(`zh-CN`)}let le=e=>Fe.accountIdentity(Re(),e);function ue(e){let t=le(e);return t?Le(t.member)+t.channel:e}function de(e){if(!e||![`total`,`netReceived`,`directCost`].every(t=>Number.isSafeInteger(e[t]))||![`goodsCost`,`profit`,`settlementDue`].every(t=>e[t]===null||Number.isSafeInteger(e[t]))||!Array.isArray(e.inventory)||!e.inventory.every(e=>typeof e.date==`string`&&typeof e.pocket==`string`&&Number.isSafeInteger(e.mg)))throw Error(`取消撤销摘要未完整返回,请重新读取订单。`);return e}function fe(e=n){let t=we(e)?.data;if(!t?.eligible||t.pending||t.directToday!==!0||!/^\d{4}-\d{2}-\d{2}$/.test(t.directActionDate||``)||e?.date!==t.directActionDate||e?.price_lock_id||![`draft`,`confirmed`,`delivered`].includes(e?.status||``))return!1;try{return de(t.summary),!0}catch{return!1}}function pe(t,r=e.today,i=n){let a=xe(i)?.data;return[`expense`,`fees`,`refund`,`return`].includes(t)&&!!a&&!a.pending&&/^\d{4}-\d{2}-\d{2}$/.test(a.directActionDate||``)&&a.actions?.[t]?.directToday===!0&&i?.date===a.directActionDate&&r===a.directActionDate&&!(o.action===t&&o.forceApproval)}function me(t){return e.user.role===`assistant`&&[`expense`,`fees`,`refund`,`return`,`cost`].includes(t)}function he(t,n=e.today){return me(t)&&!pe(t,n)}function ge(e){return e?.orderAfterSale||null}function _e(){return t?.user?.id||``}function ve(e=n){return e&&i?.id===e.id&&i.user===_e()&&i.revision===e.revision?i:null}function ye(e=n){return ve(e)?.data?.pending||e?.ownershipPending||null}function be(){return t?.user?.id||``}function xe(e=n){return e&&r?.id===e.id&&r.user===be()&&r.revision===e.revision?r:null}function Se(e){return xe(e)?.data?.pending||e?.changePending||null}function Ce(){return t?.user?.id||``}function we(e=n){return e&&a?.id===e.id&&a.user===Ce()&&a.revision===e.revision?a:null}function Te(e){return we(e)?.data?.pending||e.cancellationPending||null}function Ee(e){if([`afterSale`,`orderAfterSale`].includes(e.kind??``))return``;let t=e.printStatus?.printed;return(0,J.jsx)(`span`,{"data-print-kind":e.printStatus?.kind||(e.kind===`recovery`?`recovery`:`order`),"data-print-id":e.printStatus?.id||e.id,className:`document-print-badge `+(t?`is-printed`:`is-unprinted`),title:t?`已记录打印操作`:`尚未记录打印操作`,children:t?`✓ 已打印`:`未打印`})}let q=Fe.grams,De=e=>String(e??``),Oe=new Intl.DateTimeFormat(`zh-CN`,{timeZone:`Asia/Shanghai`,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,hourCycle:`h23`}),ke=Fe.validDate;function Ae(e){if(typeof e!=`string`||!/^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d{1,3})?)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/.test(e)||!ke(e.slice(0,10)))return`未记录`;let t=new Date(e);if(Number.isNaN(t.getTime()))return`未记录`;let n=Object.fromEntries(Oe.formatToParts(t).map(e=>[e.type,e.value]));return`${n.year}-${n.month}-${n.day} ${n.hour}:${n.minute}`}function je(e){return(0,J.jsxs)(`div`,{className:`small muted order-entry-time`,children:[`录入时间(北京时间):`,Ae(e.created)]})}function Me(e){return![`afterSale`,`orderAfterSale`,`recovery`].includes(e.kind??``)&&Number.isSafeInteger(e.revision)&&e.revision>0&&e.reviewed_revision===e.revision}let Ne={draft:`旧草稿`,confirmed:`旧单待补齐`,delivered:`已完成`,returned:`已退货`,cancelled:`已取消`,after_sale:`售后`,recovery:`回收`},Pe=e=>(0,J.jsx)(`span`,{className:`order-status `+([`draft`,`confirmed`].includes(e.status)?`danger-text`:`muted`),children:Ne[e.status]||e.status}),Ie=(e,t,n=``,r={})=>(0,J.jsx)(`button`,{type:`button`,"data-action":t,className:n,...r,children:e});function Le(n){return e?.shopSettings?.members?.find(e=>e.member===n)?.label||e?.members?.find(e=>e.member===n)?.label||t?.loginOptions?.find(e=>e.member===n)?.label||{owner:`麦麦`,assistant:`娜娜`,assistant2:`小昊`}[n??``]||`待确认`}let Re
Line truncated
|
||||||
Vendored
+1
-1
@@ -4,7 +4,7 @@
|
|||||||
<meta charset="utf-8" />
|
<meta charset="utf-8" />
|
||||||
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover" />
|
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover" />
|
||||||
<title>珠宝台账 · 新账系统</title>
|
<title>珠宝台账 · 新账系统</title>
|
||||||
<script type="module" crossorigin src="/next/assets/index-DZWLfWyz.js"></script>
|
<script type="module" crossorigin src="/next/assets/index-YO0PLbVu.js"></script>
|
||||||
<link rel="modulepreload" crossorigin href="/next/assets/rolldown-runtime-Dl_DZoUm.js">
|
<link rel="modulepreload" crossorigin href="/next/assets/rolldown-runtime-Dl_DZoUm.js">
|
||||||
<link rel="modulepreload" crossorigin href="/next/assets/antd-Bh8pVx-K.js">
|
<link rel="modulepreload" crossorigin href="/next/assets/antd-Bh8pVx-K.js">
|
||||||
<link rel="modulepreload" crossorigin href="/next/assets/react-BvkltZ40.js">
|
<link rel="modulepreload" crossorigin href="/next/assets/react-BvkltZ40.js">
|
||||||
|
|||||||
@@ -14,18 +14,19 @@ export default tseslint.config(
|
|||||||
plugins: { 'react-hooks': reactHooks, 'react-refresh': reactRefresh },
|
plugins: { 'react-hooks': reactHooks, 'react-refresh': reactRefresh },
|
||||||
rules: {
|
rules: {
|
||||||
...reactHooks.configs.recommended.rules,
|
...reactHooks.configs.recommended.rules,
|
||||||
|
'react-hooks/exhaustive-deps': 'error',
|
||||||
'react-refresh/only-export-components': ['warn', { allowConstantExport: true }],
|
'react-refresh/only-export-components': ['warn', { allowConstantExport: true }],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{ files: ['src/**/*.{js,jsx}'], languageOptions: { globals: { ...globals.browser } } },
|
// TypeScript requires var for declarations installed as properties of globalThis by classic scripts.
|
||||||
|
{ files: ['src/shared/browserGlobals.d.ts'], rules: { 'no-var': 'off' } },
|
||||||
{
|
{
|
||||||
files: ['**/*.jsx'],
|
files: ['src/**/*.{ts,tsx}'],
|
||||||
languageOptions: {
|
|
||||||
parserOptions: { ecmaFeatures: { jsx: true } },
|
|
||||||
},
|
|
||||||
plugins: { 'react-hooks': reactHooks },
|
|
||||||
rules: {
|
rules: {
|
||||||
'react-hooks/rules-of-hooks': 'error',
|
'@typescript-eslint/ban-ts-comment': [
|
||||||
|
'error',
|
||||||
|
{ 'ts-check': false, 'ts-expect-error': true, 'ts-ignore': true, 'ts-nocheck': true },
|
||||||
|
],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -5,10 +5,10 @@
|
|||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
"build": "tsc --noEmit && vite build",
|
"build": "npm run typecheck && vite build",
|
||||||
"test": "vitest run",
|
"test": "vitest run",
|
||||||
"lint": "eslint .",
|
"lint": "eslint .",
|
||||||
"typecheck": "tsc --noEmit"
|
"typecheck": "tsc --noEmit && node scripts/check-type-coverage.mjs"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ant-design/icons": "^5.6.1",
|
"@ant-design/icons": "^5.6.1",
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
// 检查实际编译文件和共享 JS 的 JSDoc,避免新页面再次掉出严格检查。
|
||||||
|
import process from 'node:process';
|
||||||
|
import console from 'node:console';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import ts from 'typescript';
|
||||||
|
const config = ts.readConfigFile('tsconfig.json', ts.sys.readFile);
|
||||||
|
const { options, fileNames } = ts.parseJsonConfigFileContent(config.config, ts.sys, process.cwd());
|
||||||
|
const inputs = new Set(fileNames.map(file => path.resolve(file)));
|
||||||
|
const errors = [];
|
||||||
|
if (!options.strict || !options.noImplicitAny || !options.checkJs) errors.push('严格类型检查未启用');
|
||||||
|
for (const name of fs.readdirSync('src', { recursive: true })) {
|
||||||
|
if (!/\.[jt]sx?$/.test(name)) continue;
|
||||||
|
if (!inputs.has(path.resolve('src', name))) errors.push('未检查 src/' + name);
|
||||||
|
if (/\.jsx?$/.test(name)) errors.push('React 业务代码需使用 TS/TSX:' + name);
|
||||||
|
}
|
||||||
|
for (const file of inputs) {
|
||||||
|
const local = path.relative(process.cwd(), file);
|
||||||
|
if (!local.startsWith('src/') && !local.startsWith('../public/')) continue;
|
||||||
|
const source = ts.createSourceFile(file, fs.readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true);
|
||||||
|
if (/@ts-(?:ignore|expect-error|nocheck)\b/.test(source.text)) errors.push(local + ' 有类型检查豁免');
|
||||||
|
function visit(node) {
|
||||||
|
if (node.kind === ts.SyntaxKind.AnyKeyword || node.kind === ts.SyntaxKind.JSDocAllType) {
|
||||||
|
errors.push(local + ':' + (source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1) + ' 显式 any');
|
||||||
|
}
|
||||||
|
for (const doc of node.jsDoc ?? []) visit(doc);
|
||||||
|
ts.forEachChild(node, visit);
|
||||||
|
}
|
||||||
|
visit(source);
|
||||||
|
}
|
||||||
|
if (errors.length) throw new Error(errors.join('\n'));
|
||||||
|
console.log('前端类型覆盖与禁止豁免检查通过');
|
||||||
@@ -1,90 +0,0 @@
|
|||||||
import { grams, yuan } from './format';
|
|
||||||
|
|
||||||
export function validateMaterialQuote(result, input, memberKeys) {
|
|
||||||
const integer = value => Number.isSafeInteger(value) && value >= 0,
|
|
||||||
amount = value => value === null || integer(value);
|
|
||||||
if (
|
|
||||||
!result ||
|
|
||||||
result.date !== input.date ||
|
|
||||||
result.member !== input.member ||
|
|
||||||
!Array.isArray(result.entries) ||
|
|
||||||
result.entries.length !== input.entries.length ||
|
|
||||||
!Array.isArray(result.pools)
|
|
||||||
)
|
|
||||||
throw new Error('分来源料费未完整返回,请刷新料价。');
|
|
||||||
for (const original of input.entries) {
|
|
||||||
const row = result.entries.find(row => row.lineIndex === original.lineIndex);
|
|
||||||
if (
|
|
||||||
!row ||
|
|
||||||
row.poolId !== original.poolId ||
|
|
||||||
row.mg !== original.mg ||
|
|
||||||
!amount(row.amount) ||
|
|
||||||
!Array.isArray(row.allocations) ||
|
|
||||||
!Array.isArray(row.materialSources) ||
|
|
||||||
row.materialSources.reduce((sum, source) => sum + source.quantity, 0) !== row.mg
|
|
||||||
)
|
|
||||||
throw new Error('分来源料费与当前商品不一致,请重新核对。');
|
|
||||||
for (const source of row.materialSources)
|
|
||||||
if (
|
|
||||||
!['personal_recovery', 'public'].includes(source.kind) ||
|
|
||||||
(source.kind === 'personal_recovery' && source.member !== input.member) ||
|
|
||||||
!integer(source.quantity) ||
|
|
||||||
!amount(source.amount) ||
|
|
||||||
!Array.isArray(source.allocations) ||
|
|
||||||
source.allocations.some(part => !memberKeys.includes(part.payer) || !integer(part.amount)) ||
|
|
||||||
(source.amount !== null && source.allocations.reduce((sum, part) => sum + part.amount, 0) !== source.amount)
|
|
||||||
)
|
|
||||||
throw new Error('个人回收料或付款来源不完整,请重新读取。');
|
|
||||||
if (
|
|
||||||
row.amount !== null &&
|
|
||||||
(row.materialSources.some(source => source.amount === null) ||
|
|
||||||
row.materialSources.reduce((sum, source) => sum + source.amount, 0) !== row.amount ||
|
|
||||||
row.allocations.reduce((sum, part) => sum + part.amount, 0) !== row.amount)
|
|
||||||
)
|
|
||||||
throw new Error('分来源料费合计不一致,请重新读取。');
|
|
||||||
}
|
|
||||||
if (
|
|
||||||
result.pools.length !== new Set(input.entries.map(row => row.poolId)).size ||
|
|
||||||
result.pools.some(
|
|
||||||
pool =>
|
|
||||||
!input.entries.some(row => row.poolId === pool.poolId) ||
|
|
||||||
!['personalRemainingMg', 'publicRemainingMg', 'eligibleRemainingMg'].every(key => integer(pool[key])) ||
|
|
||||||
!amount(pool.personalRemainingAmount) ||
|
|
||||||
!amount(pool.publicRemainingAmount),
|
|
||||||
)
|
|
||||||
)
|
|
||||||
throw new Error('个人与公共可用克重未完整返回,请重新读取。');
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function describeMaterialSources(sources = [], memberName) {
|
|
||||||
return sources
|
|
||||||
.map(source => {
|
|
||||||
const label =
|
|
||||||
source.kind === 'personal_recovery'
|
|
||||||
? (source.member ? memberName(source.member) : '待补') + '个人回收料'
|
|
||||||
: '公共料';
|
|
||||||
const amount = source.amount == null ? '料费待补' : '¥' + yuan(source.amount);
|
|
||||||
const rate = source.averageRate == null ? '' : '(加权约 ¥' + yuan(source.averageRate) + '/克)';
|
|
||||||
return label + ' ' + grams(source.quantity) + 'g · ' + amount + rate;
|
|
||||||
})
|
|
||||||
.join(';');
|
|
||||||
}
|
|
||||||
|
|
||||||
export function describeMaterialBalance(pool) {
|
|
||||||
const before = pool.before
|
|
||||||
? '本次前可用:个人 ' +
|
|
||||||
grams(pool.before.personalRemainingMg) +
|
|
||||||
'g,公共 ' +
|
|
||||||
grams(pool.before.publicRemainingMg) +
|
|
||||||
'g;'
|
|
||||||
: '';
|
|
||||||
return (
|
|
||||||
before +
|
|
||||||
'本次后余:个人回收料 ' +
|
|
||||||
grams(pool.personalRemainingMg) +
|
|
||||||
'g,公共料 ' +
|
|
||||||
grams(pool.publicRemainingMg) +
|
|
||||||
'g。'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
import { grams, yuan } from './format';
|
||||||
|
import type { Allocation } from '../pages/MaterialPools/model';
|
||||||
|
|
||||||
|
export interface QuoteEntry {
|
||||||
|
lineIndex: number;
|
||||||
|
poolId: string;
|
||||||
|
mg: number;
|
||||||
|
lineId?: string;
|
||||||
|
}
|
||||||
|
export interface QuoteRequest {
|
||||||
|
date: string;
|
||||||
|
member: string;
|
||||||
|
entries: QuoteEntry[];
|
||||||
|
orderId?: string;
|
||||||
|
priceLockId?: string;
|
||||||
|
}
|
||||||
|
export interface SourceDescription {
|
||||||
|
kind: string;
|
||||||
|
member?: string | null;
|
||||||
|
quantity: number;
|
||||||
|
amount: number | null;
|
||||||
|
averageRate?: number | null;
|
||||||
|
}
|
||||||
|
export interface QuoteSource extends SourceDescription {
|
||||||
|
allocations: Allocation[];
|
||||||
|
}
|
||||||
|
export interface QuoteRow extends QuoteEntry {
|
||||||
|
amount: number | null;
|
||||||
|
materialSources: QuoteSource[];
|
||||||
|
allocations: Allocation[];
|
||||||
|
}
|
||||||
|
interface Remaining {
|
||||||
|
personalRemainingMg: number;
|
||||||
|
publicRemainingMg: number;
|
||||||
|
eligibleRemainingMg: number;
|
||||||
|
}
|
||||||
|
export interface QuoteBalance extends Remaining {
|
||||||
|
poolId: string;
|
||||||
|
revision: string;
|
||||||
|
before?: Remaining;
|
||||||
|
}
|
||||||
|
interface Quote {
|
||||||
|
date: string;
|
||||||
|
member: string;
|
||||||
|
entries: QuoteRow[];
|
||||||
|
pools: QuoteBalance[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const record = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null;
|
||||||
|
const integer = (v: unknown): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
|
||||||
|
const amount = (v: unknown): v is number | null => v === null || integer(v);
|
||||||
|
function allocation(v: unknown): v is Allocation {
|
||||||
|
return record(v) && typeof v.payer === 'string' && integer(v.amount);
|
||||||
|
}
|
||||||
|
function source(v: unknown): v is QuoteSource {
|
||||||
|
return (
|
||||||
|
record(v) &&
|
||||||
|
(v.kind === 'personal_recovery' || v.kind === 'public') &&
|
||||||
|
(v.member == null || typeof v.member === 'string') &&
|
||||||
|
integer(v.quantity) &&
|
||||||
|
amount(v.amount) &&
|
||||||
|
(v.averageRate == null || integer(v.averageRate)) &&
|
||||||
|
Array.isArray(v.allocations) &&
|
||||||
|
v.allocations.every(allocation)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
function row(v: unknown): v is QuoteRow {
|
||||||
|
return (
|
||||||
|
record(v) &&
|
||||||
|
integer(v.lineIndex) &&
|
||||||
|
typeof v.poolId === 'string' &&
|
||||||
|
integer(v.mg) &&
|
||||||
|
amount(v.amount) &&
|
||||||
|
Array.isArray(v.allocations) &&
|
||||||
|
v.allocations.every(allocation) &&
|
||||||
|
Array.isArray(v.materialSources) &&
|
||||||
|
v.materialSources.every(source)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
function remaining(v: unknown): v is Remaining {
|
||||||
|
return record(v) && integer(v.personalRemainingMg) && integer(v.publicRemainingMg) && integer(v.eligibleRemainingMg);
|
||||||
|
}
|
||||||
|
function balance(v: unknown): v is QuoteBalance {
|
||||||
|
return (
|
||||||
|
record(v) &&
|
||||||
|
typeof v.poolId === 'string' &&
|
||||||
|
typeof v.revision === 'string' &&
|
||||||
|
amount(v.personalRemainingAmount) &&
|
||||||
|
amount(v.publicRemainingAmount) &&
|
||||||
|
(!v.before || remaining(v.before)) &&
|
||||||
|
remaining(v)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
export function validateMaterialQuote(result: unknown, input: QuoteRequest, memberKeys: string[]): Quote {
|
||||||
|
if (
|
||||||
|
!record(result) ||
|
||||||
|
result.date !== input.date ||
|
||||||
|
result.member !== input.member ||
|
||||||
|
!Array.isArray(result.entries) ||
|
||||||
|
result.entries.length !== input.entries.length ||
|
||||||
|
!Array.isArray(result.pools)
|
||||||
|
)
|
||||||
|
throw new Error('分来源料费未完整返回,请刷新料价。');
|
||||||
|
const entries: unknown[] = result.entries;
|
||||||
|
if (!entries.every(row)) throw new Error('分来源料费与当前商品不一致,请重新核对。');
|
||||||
|
for (const original of input.entries) {
|
||||||
|
const item = entries.find(v => v.lineIndex === original.lineIndex);
|
||||||
|
if (
|
||||||
|
!item ||
|
||||||
|
item.poolId !== original.poolId ||
|
||||||
|
item.mg !== original.mg ||
|
||||||
|
item.materialSources.reduce((sum, s) => sum + s.quantity, 0) !== item.mg
|
||||||
|
)
|
||||||
|
throw new Error('分来源料费与当前商品不一致,请重新核对。');
|
||||||
|
for (const s of item.materialSources)
|
||||||
|
if (
|
||||||
|
(s.kind === 'personal_recovery' && s.member !== input.member) ||
|
||||||
|
s.allocations.some(p => !memberKeys.includes(p.payer)) ||
|
||||||
|
(s.amount !== null && s.allocations.reduce((sum, p) => sum + p.amount, 0) !== s.amount)
|
||||||
|
)
|
||||||
|
throw new Error('个人回收料或付款来源不完整,请重新读取。');
|
||||||
|
if (
|
||||||
|
item.amount !== null &&
|
||||||
|
(item.materialSources.some(s => s.amount === null) ||
|
||||||
|
item.materialSources.reduce((sum, s) => sum + (s.amount ?? 0), 0) !== item.amount ||
|
||||||
|
item.allocations.reduce((sum, p) => sum + p.amount, 0) !== item.amount)
|
||||||
|
)
|
||||||
|
throw new Error('分来源料费合计不一致,请重新读取。');
|
||||||
|
}
|
||||||
|
const pools: unknown[] = result.pools;
|
||||||
|
if (
|
||||||
|
!pools.every(balance) ||
|
||||||
|
pools.length !== new Set(input.entries.map(e => e.poolId)).size ||
|
||||||
|
pools.some(p => !input.entries.some(e => e.poolId === p.poolId))
|
||||||
|
)
|
||||||
|
throw new Error('个人与公共可用克重未完整返回,请重新读取。');
|
||||||
|
return { date: input.date, member: input.member, entries, pools };
|
||||||
|
}
|
||||||
|
export function describeMaterialSources(
|
||||||
|
sources: readonly SourceDescription[] = [],
|
||||||
|
memberName: (key: string) => string,
|
||||||
|
) {
|
||||||
|
return sources
|
||||||
|
.map(source => {
|
||||||
|
const label =
|
||||||
|
source.kind === 'personal_recovery'
|
||||||
|
? (source.member ? memberName(source.member) : '待补') + '个人回收料'
|
||||||
|
: '公共料';
|
||||||
|
const amount = source.amount == null ? '料费待补' : '¥' + yuan(source.amount);
|
||||||
|
const rate = source.averageRate == null ? '' : '(加权约 ¥' + yuan(source.averageRate) + '/克)';
|
||||||
|
return label + ' ' + grams(source.quantity) + 'g · ' + amount + rate;
|
||||||
|
})
|
||||||
|
.join(';');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function describeMaterialBalance(pool: QuoteBalance) {
|
||||||
|
const before = pool.before
|
||||||
|
? '本次前可用:个人 ' +
|
||||||
|
grams(pool.before.personalRemainingMg) +
|
||||||
|
'g,公共 ' +
|
||||||
|
grams(pool.before.publicRemainingMg) +
|
||||||
|
'g;'
|
||||||
|
: '';
|
||||||
|
return (
|
||||||
|
before +
|
||||||
|
'本次后余:个人回收料 ' +
|
||||||
|
grams(pool.personalRemainingMg) +
|
||||||
|
'g,公共料 ' +
|
||||||
|
grams(pool.publicRemainingMg) +
|
||||||
|
'g。'
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -38,67 +38,67 @@ export function ChargeList({ index, line, update }: { index: number; line: LineS
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
{line.charges.length > 0 && (
|
{line.charges.length > 0 && (
|
||||||
<div className="charge-list">
|
<div className="charge-list">
|
||||||
{line.charges.map((charge, j) => (
|
{line.charges.map((charge, j) => (
|
||||||
<div className="charge-row" key={charge.id} data-charge={j}>
|
<div className="charge-row" key={charge.id} data-charge={j}>
|
||||||
<ChoiceField
|
<ChoiceField
|
||||||
label="附加项目"
|
label="附加项目"
|
||||||
field="chargeType"
|
field="chargeType"
|
||||||
value={charge.type}
|
value={charge.type}
|
||||||
options={[...Model.chargeNames, '其他'].map(name => [name, name] as [string, string])}
|
options={[...Model.chargeNames, '其他'].map(name => [name, name] as [string, string])}
|
||||||
onChange={type => setCharge(j, c => Model.changeChargeType(c, type))}
|
onChange={type => setCharge(j, c => Model.changeChargeType(c, type))}
|
||||||
/>
|
/>
|
||||||
<TextField
|
<TextField
|
||||||
label="附加项目名称"
|
label="附加项目名称"
|
||||||
field="chargeName"
|
field="chargeName"
|
||||||
hidden={charge.type !== '其他'}
|
hidden={charge.type !== '其他'}
|
||||||
value={charge.customName}
|
value={charge.customName ?? ''}
|
||||||
maxLength={40}
|
maxLength={40}
|
||||||
onChange={value => setCharge(j, c => ({ ...c, customName: value }))}
|
onChange={value => setCharge(j, c => ({ ...c, customName: value }))}
|
||||||
/>
|
/>
|
||||||
<TextField
|
<TextField
|
||||||
label="附加金额(元)"
|
label="附加金额(元)"
|
||||||
field="chargeAmount"
|
field="chargeAmount"
|
||||||
numeric
|
numeric
|
||||||
value={charge.amount}
|
value={charge.amount}
|
||||||
placeholder="没有收费填0,可修改金额"
|
placeholder="没有收费填0,可修改金额"
|
||||||
onChange={value => setCharge(j, c => Model.setChargeAmount(c, value))}
|
onChange={value => setCharge(j, c => Model.setChargeAmount(c, value))}
|
||||||
/>
|
/>
|
||||||
<div className="charge-actions">
|
<div className="charge-actions">
|
||||||
<Button
|
<Button
|
||||||
type="text"
|
type="text"
|
||||||
size="small"
|
size="small"
|
||||||
icon={<CloseOutlined />}
|
icon={<CloseOutlined />}
|
||||||
data-action="remove-charge"
|
data-action="remove-charge"
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
update(form => {
|
update(form => {
|
||||||
const current = form.lines[index];
|
const current = form.lines[index];
|
||||||
return Model.updateLine(form, index, {
|
return Model.updateLine(form, index, {
|
||||||
...current,
|
...current,
|
||||||
charges: current.charges.filter((_, k) => k !== j),
|
charges: current.charges.filter((_, k) => k !== j),
|
||||||
});
|
});
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
移除附加项
|
移除附加项
|
||||||
</Button>
|
</Button>
|
||||||
{charge.costRemoved && (
|
{charge.costRemoved && (
|
||||||
<small className="muted">
|
<small className="muted">
|
||||||
内部成本已移除{' '}
|
内部成本已移除{' '}
|
||||||
<Button
|
<Button
|
||||||
type="link"
|
type="link"
|
||||||
size="small"
|
size="small"
|
||||||
data-action="restore-charge-cost"
|
data-action="restore-charge-cost"
|
||||||
onClick={() => update(form => Model.restoreChargeCost(form, index, j))}
|
onClick={() => update(form => Model.restoreChargeCost(form, index, j))}
|
||||||
>
|
>
|
||||||
恢复内部成本
|
恢复内部成本
|
||||||
</Button>
|
</Button>
|
||||||
</small>
|
</small>
|
||||||
)}
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
))}
|
||||||
))}
|
</div>
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||||
import type { LedgerClient } from '../../lib/api';
|
import type { LedgerClient } from '../../lib/api';
|
||||||
import { Model } from '../../shared';
|
import { Model } from '../../shared';
|
||||||
|
import { validateMaterialQuote, type QuoteRequest } from '../../lib/materialQuote';
|
||||||
import type {
|
import type {
|
||||||
FormSummary,
|
FormSummary,
|
||||||
LedgerState,
|
LedgerState,
|
||||||
@@ -98,7 +99,7 @@ export function useOrderForm({
|
|||||||
const input = Model.poolQuoteInput(store.form, ctx);
|
const input = Model.poolQuoteInput(store.form, ctx);
|
||||||
const rows = (pools?.rows || []) as { id: string; personalPools?: unknown }[];
|
const rows = (pools?.rows || []) as { id: string; personalPools?: unknown }[];
|
||||||
const personal = input.entries.some(entry =>
|
const personal = input.entries.some(entry =>
|
||||||
rows.some(row => row.id === (entry as { poolId: string }).poolId && row.personalPools !== undefined),
|
rows.some(row => row.id === entry.poolId && row.personalPools !== undefined),
|
||||||
);
|
);
|
||||||
return personal ? JSON.stringify(input) : '';
|
return personal ? JSON.stringify(input) : '';
|
||||||
}, [store.form, ctx, pools]);
|
}, [store.form, ctx, pools]);
|
||||||
@@ -106,9 +107,13 @@ export function useOrderForm({
|
|||||||
if (!quoteInput || (quote && JSON.stringify(quote.input) === quoteInput)) return;
|
if (!quoteInput || (quote && JSON.stringify(quote.input) === quoteInput)) return;
|
||||||
let current = true;
|
let current = true;
|
||||||
const timer = window.setTimeout(async () => {
|
const timer = window.setTimeout(async () => {
|
||||||
const input = JSON.parse(quoteInput);
|
const input: QuoteRequest = JSON.parse(quoteInput);
|
||||||
try {
|
try {
|
||||||
const result = await client.api('/api/material-pools/quote', input);
|
const result = validateMaterialQuote(
|
||||||
|
await client.api('/api/material-pools/quote', input),
|
||||||
|
input,
|
||||||
|
Model.memberKeys(state),
|
||||||
|
);
|
||||||
if (current) setQuote({ input, result, error: '' });
|
if (current) setQuote({ input, result, error: '' });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (current) setQuote({ input, result: null, error: (err as Error).message });
|
if (current) setQuote({ input, result: null, error: (err as Error).message });
|
||||||
@@ -118,7 +123,7 @@ export function useOrderForm({
|
|||||||
current = false;
|
current = false;
|
||||||
window.clearTimeout(timer);
|
window.clearTimeout(timer);
|
||||||
};
|
};
|
||||||
}, [quoteInput, quote, client]);
|
}, [quoteInput, quote, client, state]);
|
||||||
|
|
||||||
return { store, update, reset, ctx, pools, poolError, loadPools };
|
return { store, update, reset, ctx, pools, poolError, loadPools };
|
||||||
}
|
}
|
||||||
@@ -9,6 +9,7 @@ export interface Purchase {
|
|||||||
revision: number;
|
revision: number;
|
||||||
note: string;
|
note: string;
|
||||||
payer?: string;
|
payer?: string;
|
||||||
|
allocations?: Allocation[];
|
||||||
actualpayer?: string;
|
actualpayer?: string;
|
||||||
actualPayer?: string;
|
actualPayer?: string;
|
||||||
sourceKind?: string;
|
sourceKind?: string;
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import { useRef, useEffect, type ReactNode } from 'react';
|
||||||
|
export function Dialog({
|
||||||
|
id,
|
||||||
|
label,
|
||||||
|
close,
|
||||||
|
children,
|
||||||
|
ownClose = false,
|
||||||
|
}: {
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
close: () => void;
|
||||||
|
children: ReactNode;
|
||||||
|
ownClose?: boolean;
|
||||||
|
}) {
|
||||||
|
const ref = useRef<HTMLDialogElement>(null);
|
||||||
|
useEffect(() => {
|
||||||
|
const node = ref.current!;
|
||||||
|
node.showModal();
|
||||||
|
return () => node.close();
|
||||||
|
}, []);
|
||||||
|
return (
|
||||||
|
<dialog
|
||||||
|
id={id}
|
||||||
|
ref={ref}
|
||||||
|
aria-label={label}
|
||||||
|
onCancel={event => {
|
||||||
|
event.preventDefault();
|
||||||
|
close();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{!ownClose && (
|
||||||
|
<button type="button" className="dialog-close" data-action="close-dialog" aria-label={label} onClick={close}>
|
||||||
|
×
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{children}
|
||||||
|
</dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
+67
-29
@@ -1,8 +1,24 @@
|
|||||||
import { Fragment } from 'react';
|
import { Fragment, type InputHTMLAttributes, type SelectHTMLAttributes, type ReactNode } from 'react';
|
||||||
|
import type { ChargeState, OrderForm, LineState, PurchaseState, SyncContext, LedgerState } from '../../shared';
|
||||||
|
import type { FormStore } from '../CreateOrder/useOrderForm';
|
||||||
|
|
||||||
|
interface FieldProps {
|
||||||
|
label: ReactNode;
|
||||||
|
help?: ReactNode;
|
||||||
|
onChange?: (value: string) => void;
|
||||||
|
value?: string | number | null;
|
||||||
|
}
|
||||||
|
type InputProps = FieldProps & Omit<InputHTMLAttributes<HTMLInputElement>, keyof FieldProps>;
|
||||||
|
type Option = string | readonly [string, string, boolean?];
|
||||||
|
type ChoiceProps = FieldProps &
|
||||||
|
Omit<SelectHTMLAttributes<HTMLSelectElement>, keyof FieldProps> & { options: readonly Option[] };
|
||||||
|
type UpdateForm = (change: (form: OrderForm) => OrderForm) => void;
|
||||||
|
type TextKey<T> = { [K in keyof T]-?: T[K] extends string ? K : never }[keyof T];
|
||||||
|
|
||||||
import { Fees, Model } from '../../shared';
|
import { Fees, Model } from '../../shared';
|
||||||
import { uuid } from '../CreateOrder/useOrderForm';
|
import { uuid } from '../CreateOrder/useOrderForm';
|
||||||
|
|
||||||
export function Input({ label, name, value, type = 'text', hidden, help, onChange, ...props }) {
|
export function Input({ label, name, value, type = 'text', hidden, help, onChange, ...props }: InputProps) {
|
||||||
return (
|
return (
|
||||||
<label hidden={hidden}>
|
<label hidden={hidden}>
|
||||||
{label}
|
{label}
|
||||||
@@ -18,7 +34,7 @@ export function Input({ label, name, value, type = 'text', hidden, help, onChang
|
|||||||
</label>
|
</label>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
export function Choice({ label, name, value, options, hidden, help, onChange, ...props }) {
|
export function Choice({ label, name, value, options, hidden, help, onChange, ...props }: ChoiceProps) {
|
||||||
return (
|
return (
|
||||||
<label hidden={hidden}>
|
<label hidden={hidden}>
|
||||||
{label}
|
{label}
|
||||||
@@ -26,11 +42,11 @@ export function Choice({ label, name, value, options, hidden, help, onChange, ..
|
|||||||
{...props}
|
{...props}
|
||||||
name={name}
|
name={name}
|
||||||
value={value ?? ''}
|
value={value ?? ''}
|
||||||
onChange={e => onChange(e.target.value)}
|
onChange={e => onChange?.(e.target.value)}
|
||||||
disabled={hidden || props.disabled}
|
disabled={hidden || props.disabled}
|
||||||
>
|
>
|
||||||
{options.map(option => {
|
{options.map(option => {
|
||||||
const [key, name, disabled] = Array.isArray(option) ? option : [option, option];
|
const [key, name, disabled] = typeof option === 'string' ? [option, option] : option;
|
||||||
return (
|
return (
|
||||||
<option key={key} value={key} disabled={!!disabled}>
|
<option key={key} value={key} disabled={!!disabled}>
|
||||||
{name}
|
{name}
|
||||||
@@ -43,27 +59,52 @@ export function Choice({ label, name, value, options, hidden, help, onChange, ..
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
const money = { type: 'number', step: '0.01', min: '0' };
|
const money = { type: 'number', step: '0.01', min: '0' };
|
||||||
|
const categories: Record<string, string> = {
|
||||||
|
jd: 'shipping',
|
||||||
|
yt: 'shipping',
|
||||||
|
box: 'box',
|
||||||
|
steel: 'braiding',
|
||||||
|
silver: 'silverChain',
|
||||||
|
};
|
||||||
const amountPlaceholder = '开单前必填,没有填0';
|
const amountPlaceholder = '开单前必填,没有填0';
|
||||||
export function EditLine({ index, line, state, ctx, form, update, reloadPools, error }) {
|
export function EditLine({
|
||||||
|
index,
|
||||||
|
line,
|
||||||
|
state,
|
||||||
|
ctx,
|
||||||
|
form,
|
||||||
|
update,
|
||||||
|
reloadPools,
|
||||||
|
error,
|
||||||
|
}: {
|
||||||
|
index: number;
|
||||||
|
line: LineState;
|
||||||
|
state: LedgerState;
|
||||||
|
ctx: SyncContext;
|
||||||
|
form: OrderForm;
|
||||||
|
update: UpdateForm;
|
||||||
|
reloadPools: () => void;
|
||||||
|
error: (message: string) => void;
|
||||||
|
}) {
|
||||||
const v = Model.lineVisibility(line, state),
|
const v = Model.lineVisibility(line, state),
|
||||||
p = line.purchase,
|
p = line.purchase,
|
||||||
pool = line.pool,
|
pool = line.pool,
|
||||||
pooled = pool?.source === 'pool',
|
pooled = pool?.source === 'pool',
|
||||||
prefix = 'cost-';
|
prefix = 'cost-';
|
||||||
const change = fn => update(f => Model.updateLine(f, index, fn(f.lines[index])));
|
const change = (fn: (line: LineState) => LineState) => update(f => Model.updateLine(f, index, fn(f.lines[index])));
|
||||||
const prop = name => ({
|
const prop = (name: TextKey<LineState>) => ({
|
||||||
name,
|
name,
|
||||||
value: line[name],
|
value: line[name],
|
||||||
onChange: value => change(l => Model.setLineField(l, name, value)),
|
onChange: (value: string) => change(l => Model.setLineField(l, name, value)),
|
||||||
});
|
});
|
||||||
const cost = name => ({
|
const cost = (name: TextKey<PurchaseState>) => ({
|
||||||
name: prefix + name,
|
name: prefix + name,
|
||||||
value: p[name],
|
value: p![name],
|
||||||
onChange: value => change(l => Model.setPurchaseField(l, name, value)),
|
onChange: (value: string) => change(l => Model.setPurchaseField(l, name, value)),
|
||||||
});
|
});
|
||||||
const laborFunding = p?.costFundings?.labor;
|
const laborFunding = p?.costFundings?.labor;
|
||||||
const members = value => Model.memberOptions(state, false, { selected: value });
|
const members = (value: string) => Model.memberOptions(state, false, { selected: value });
|
||||||
function updateCharge(i, fn) {
|
function updateCharge(i: number, fn: (charge: ChargeState) => ChargeState) {
|
||||||
change(l => ({ ...l, charges: l.charges.map((c, j) => (j === i ? fn(c) : c)) }));
|
change(l => ({ ...l, charges: l.charges.map((c, j) => (j === i ? fn(c) : c)) }));
|
||||||
}
|
}
|
||||||
return (
|
return (
|
||||||
@@ -77,7 +118,7 @@ export function EditLine({ index, line, state, ctx, form, update, reloadPools, e
|
|||||||
try {
|
try {
|
||||||
update(f => Model.removeLine(f, index));
|
update(f => Model.removeLine(f, index));
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
error(err.message);
|
error(err instanceof Error ? err.message : String(err));
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
@@ -226,7 +267,7 @@ export function EditLine({ index, line, state, ctx, form, update, reloadPools, e
|
|||||||
]}
|
]}
|
||||||
value={pool.source}
|
value={pool.source}
|
||||||
disabled={!v.poolAllowed}
|
disabled={!v.poolAllowed}
|
||||||
onChange={source => change(l => Model.setPoolSource(l, source))}
|
onChange={source => change(l => Model.setPoolSource(l, source as 'manual' | 'pool'))}
|
||||||
/>
|
/>
|
||||||
<Choice
|
<Choice
|
||||||
label="料价日期"
|
label="料价日期"
|
||||||
@@ -234,7 +275,7 @@ export function EditLine({ index, line, state, ctx, form, update, reloadPools, e
|
|||||||
value={pool.poolId}
|
value={pool.poolId}
|
||||||
options={pool.options.map(x => [x.value, x.label])}
|
options={pool.options.map(x => [x.value, x.label])}
|
||||||
hidden={!pooled}
|
hidden={!pooled}
|
||||||
onChange={poolId => change(l => ({ ...l, pool: { ...l.pool, poolId, defaultDate: false } }))}
|
onChange={poolId => change(l => ({ ...l, pool: { ...l.pool!, poolId, defaultDate: false } }))}
|
||||||
/>
|
/>
|
||||||
<button type="button" onClick={reloadPools}>
|
<button type="button" onClick={reloadPools}>
|
||||||
刷新料价
|
刷新料价
|
||||||
@@ -272,7 +313,7 @@ export function EditLine({ index, line, state, ctx, form, update, reloadPools, e
|
|||||||
label="料费付款人"
|
label="料费付款人"
|
||||||
{...cost('materialPayer')}
|
{...cost('materialPayer')}
|
||||||
required
|
required
|
||||||
options={members(p.materialPayer)}
|
options={members(p!.materialPayer)}
|
||||||
hidden={!v.materialPayer}
|
hidden={!v.materialPayer}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -308,7 +349,7 @@ export function EditLine({ index, line, state, ctx, form, update, reloadPools, e
|
|||||||
{...cost('laborPayer')}
|
{...cost('laborPayer')}
|
||||||
required
|
required
|
||||||
disabled={!!laborFunding}
|
disabled={!!laborFunding}
|
||||||
options={members(p.laborPayer)}
|
options={members(p!.laborPayer)}
|
||||||
/>
|
/>
|
||||||
{laborFunding && (
|
{laborFunding && (
|
||||||
<input
|
<input
|
||||||
@@ -329,8 +370,8 @@ export function EditLine({ index, line, state, ctx, form, update, reloadPools, e
|
|||||||
</details>
|
</details>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
{['accessories', 'other'].map(key => (
|
{(['accessories', 'other'] as const).map(key => (
|
||||||
<input key={key} type="hidden" name={prefix + key} value={p[key]} />
|
<input key={key} type="hidden" name={prefix + key} value={p![key]} />
|
||||||
))}
|
))}
|
||||||
<input type="hidden" name="payer" value={line.payer} />
|
<input type="hidden" name="payer" value={line.payer} />
|
||||||
</>
|
</>
|
||||||
@@ -341,16 +382,12 @@ export function EditLine({ index, line, state, ctx, form, update, reloadPools, e
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
export function EditFees({ store, state, update }) {
|
export function EditFees({ store, state, update }: { store: FormStore; state: LedgerState; update: UpdateForm }) {
|
||||||
const { form, summary } = store,
|
const { form, summary } = store,
|
||||||
presets = form.presets;
|
presets = form.presets;
|
||||||
const hasLinkedCost = kind =>
|
const hasLinkedCost = (kind: string) =>
|
||||||
form.feeRows.some(
|
form.feeRows.some(
|
||||||
row =>
|
row => row.funding && (row.key === Fees.presetKey(kind) || Fees.checkboxCategory(row.note) === categories[kind]),
|
||||||
row.funding &&
|
|
||||||
(row.key === Fees.presetKey(kind) ||
|
|
||||||
Fees.checkboxCategory(row.note) ===
|
|
||||||
{ jd: 'shipping', yt: 'shipping', box: 'box', steel: 'braiding', silver: 'silverChain' }[kind]),
|
|
||||||
);
|
);
|
||||||
return (
|
return (
|
||||||
<section className="panel internal">
|
<section className="panel internal">
|
||||||
@@ -406,7 +443,8 @@ export function EditFees({ store, state, update }) {
|
|||||||
)}
|
)}
|
||||||
<div id="fee-rows">
|
<div id="fee-rows">
|
||||||
{form.feeRows.map((row, i) => {
|
{form.feeRows.map((row, i) => {
|
||||||
const edit = (key, value) => update(f => Model.editFeeRow(f, i, key, value));
|
const edit = (key: 'note' | 'payer' | 'amount' | 'date', value: string) =>
|
||||||
|
update(f => Model.editFeeRow(f, i, key, value));
|
||||||
const ref = row.funding;
|
const ref = row.funding;
|
||||||
return (
|
return (
|
||||||
<div key={row.key} className="fee-row grid four">
|
<div key={row.key} className="fee-row grid four">
|
||||||
@@ -0,0 +1,310 @@
|
|||||||
|
import { App as AntApp } from 'antd';
|
||||||
|
import { useEffect, useRef, useState, type FormEvent, type MouseEvent } from 'react';
|
||||||
|
import { Calc, type LedgerState, type SessionInfo } from '../../shared';
|
||||||
|
import type { LedgerClient } from '../../lib/api';
|
||||||
|
import { orderViews } from './orderViews';
|
||||||
|
import { Dialog } from './Dialog';
|
||||||
|
import { useRead } from './orderReads';
|
||||||
|
import type { IndependentRequest } from './orderData';
|
||||||
|
|
||||||
|
interface SaleProps {
|
||||||
|
client: LedgerClient;
|
||||||
|
state: LedgerState;
|
||||||
|
session: SessionInfo;
|
||||||
|
sale: { action: string; id?: string };
|
||||||
|
refreshState: () => Promise<unknown>;
|
||||||
|
refreshBook: () => void;
|
||||||
|
openList: () => void;
|
||||||
|
close: () => void;
|
||||||
|
saved: (date?: string) => void;
|
||||||
|
}
|
||||||
|
const object = (v: unknown): v is Record<string, unknown> => v !== null && typeof v === 'object';
|
||||||
|
const messageOf = (err: unknown) => (err instanceof Error ? err.message : String(err));
|
||||||
|
const staleError = (err: unknown) => object(err) && (err.status === 403 || err.status === 404 || err.status === 409);
|
||||||
|
export function IndependentAfterSale({
|
||||||
|
client,
|
||||||
|
state,
|
||||||
|
session,
|
||||||
|
sale,
|
||||||
|
refreshState,
|
||||||
|
refreshBook,
|
||||||
|
openList,
|
||||||
|
close,
|
||||||
|
saved,
|
||||||
|
}: SaleProps) {
|
||||||
|
const { message } = AntApp.useApp();
|
||||||
|
const [review, setReview] = useState(sale.action === 'after-sale-change-open' ? sale.id || '' : '');
|
||||||
|
const [kind, setKind] = useState('');
|
||||||
|
const [error, setError] = useState('');
|
||||||
|
const [invalid, setInvalid] = useState(false);
|
||||||
|
const [date, setDate] = useState<string | null>(null);
|
||||||
|
const [savedRequest, setSavedRequest] = useState<IndependentRequest | null>(null);
|
||||||
|
const [receipt, setReceipt] = useState('');
|
||||||
|
const [generation, reload] = useState(0);
|
||||||
|
const version = useRef(0);
|
||||||
|
useEffect(
|
||||||
|
() => () => {
|
||||||
|
version.current++;
|
||||||
|
},
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
const id = review || sale.id;
|
||||||
|
const path = review
|
||||||
|
? '/api/after-sales/changes/' + encodeURIComponent(review)
|
||||||
|
: sale.id
|
||||||
|
? '/api/after-sales/' + encodeURIComponent(sale.id)
|
||||||
|
: '';
|
||||||
|
const views = orderViews({ state, session });
|
||||||
|
const read = useRead(
|
||||||
|
async () => {
|
||||||
|
if (!review) await refreshState();
|
||||||
|
const data = await client.api(path);
|
||||||
|
if (!review) return { kind: 'record' as const, data: views.validateAfterSaleDetail(data, sale.id || '') };
|
||||||
|
const request = views.validateAfterSaleRequest(data);
|
||||||
|
if (request.id !== review) throw new Error('申请编号不一致,请重新读取。');
|
||||||
|
return { kind: 'request' as const, data: request };
|
||||||
|
},
|
||||||
|
path && state.user.id + '/' + path + '/' + generation,
|
||||||
|
);
|
||||||
|
const detail = read.value?.kind === 'record' ? read.value.data : undefined;
|
||||||
|
const request = savedRequest ?? (read.value?.kind === 'request' ? read.value.data : undefined);
|
||||||
|
const approval =
|
||||||
|
!!detail?.permissions &&
|
||||||
|
(detail.permissions.requiresApproval ||
|
||||||
|
!detail.permissions.canDirectEdit ||
|
||||||
|
(state.user.role !== 'owner' &&
|
||||||
|
(detail.record.date !== state.today || (date ?? detail.record.date) !== state.today)));
|
||||||
|
const blocked = !!(invalid || client.busy || client.pending());
|
||||||
|
|
||||||
|
function reset() {
|
||||||
|
version.current++;
|
||||||
|
setKind('');
|
||||||
|
setError('');
|
||||||
|
setDate(null);
|
||||||
|
setSavedRequest(null);
|
||||||
|
setReceipt('');
|
||||||
|
setInvalid(false);
|
||||||
|
reload(value => value + 1);
|
||||||
|
}
|
||||||
|
function dismiss() {
|
||||||
|
version.current++;
|
||||||
|
close();
|
||||||
|
}
|
||||||
|
function fail(err: unknown) {
|
||||||
|
const text = messageOf(err).replace('不要重新开单', id ? '不要重复提交售后修改' : '不要重复新增售后');
|
||||||
|
if (staleError(err) && id) setInvalid(true);
|
||||||
|
setError(text);
|
||||||
|
message.error(text);
|
||||||
|
}
|
||||||
|
async function finish(url: string, input: unknown, result: unknown, at: number) {
|
||||||
|
if (client.user !== state.user.id) return;
|
||||||
|
const savedDate = object(input) && typeof input.date === 'string' ? input.date : undefined;
|
||||||
|
const active = () => version.current === at && client.user === state.user.id;
|
||||||
|
if (url === '/api/after-sales') {
|
||||||
|
if (active()) saved(savedDate);
|
||||||
|
else refreshBook();
|
||||||
|
message.success('售后已保存,已计入 ' + savedDate + ' 的费用与利润');
|
||||||
|
await refreshState();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const update = url.endsWith('/update');
|
||||||
|
const applied = update && object(result) && result.applied === true;
|
||||||
|
const text = update
|
||||||
|
? applied
|
||||||
|
? '售后修改已保存'
|
||||||
|
: '售后修改申请已提交,待店主审批'
|
||||||
|
: url.endsWith('/approve')
|
||||||
|
? '已同意售后修改'
|
||||||
|
: '已驳回售后修改申请';
|
||||||
|
if (active()) {
|
||||||
|
setKind('');
|
||||||
|
setError('');
|
||||||
|
setReceipt(text);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await refreshState();
|
||||||
|
if (client.user !== state.user.id) return;
|
||||||
|
if (active() && applied)
|
||||||
|
saved(
|
||||||
|
object(result.record) && object(result.record.record) && typeof result.record.record.date === 'string'
|
||||||
|
? result.record.record.date
|
||||||
|
: savedDate,
|
||||||
|
);
|
||||||
|
else {
|
||||||
|
refreshBook();
|
||||||
|
if (active() && update) reset();
|
||||||
|
if (active() && !update) {
|
||||||
|
const finalRequest = views.validateAfterSaleRequest(result);
|
||||||
|
if (finalRequest.id !== review) throw new Error('申请编号不一致,请重新读取。');
|
||||||
|
setSavedRequest(finalRequest);
|
||||||
|
setReceipt('');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
message.success(text);
|
||||||
|
} catch (err) {
|
||||||
|
if (active()) setError('结果已保存,刷新失败:' + messageOf(err) + '。请重新读取查看结果。');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async function handle(event: MouseEvent<HTMLDivElement>) {
|
||||||
|
const button = event.target instanceof Element && event.target.closest<HTMLElement>('[data-action]');
|
||||||
|
if (!button) return;
|
||||||
|
event.stopPropagation();
|
||||||
|
const { action, id: requestedId, kind: choice } = button.dataset;
|
||||||
|
if (action === 'close-after-sale' || action === 'after-sale-changes-close') return dismiss();
|
||||||
|
if (action === 'after-sale-changes-reload') {
|
||||||
|
version.current++;
|
||||||
|
openList();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (action === 'after-sale-change-open' || action === 'after-sale-edit') {
|
||||||
|
if (client.busy) return;
|
||||||
|
if (action === 'after-sale-change-open' && requestedId) setReview(requestedId);
|
||||||
|
reset();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (action === 'after-sale-review-decision') {
|
||||||
|
if (invalid || request?.status !== 'pending') return fail(new Error('请重新读取申请后再复核。'));
|
||||||
|
if (choice === 'approve' || choice === 'reject') setKind(choice);
|
||||||
|
setError('');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (action === 'after-sale-review-cancel') {
|
||||||
|
setKind('');
|
||||||
|
setError('');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (action === 'retry') {
|
||||||
|
const at = version.current;
|
||||||
|
try {
|
||||||
|
const restored = await client.retryPending();
|
||||||
|
if (restored) await finish(restored.job.url, restored.job.data, restored.result, at);
|
||||||
|
} catch (err) {
|
||||||
|
if (at === version.current) fail(err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async function submit(event: FormEvent<HTMLDivElement>) {
|
||||||
|
event.stopPropagation();
|
||||||
|
event.preventDefault();
|
||||||
|
const node = event.target;
|
||||||
|
if (!(node instanceof HTMLFormElement)) return;
|
||||||
|
const values = Object.fromEntries(Array.from(new FormData(node), ([key, value]) => [key, String(value)]));
|
||||||
|
const at = version.current;
|
||||||
|
try {
|
||||||
|
let url, input;
|
||||||
|
if (review) {
|
||||||
|
if (state.user.role !== 'owner') throw new Error('请使用店主账号复核。');
|
||||||
|
if (blocked || request?.status !== 'pending' || node.dataset.id !== request.id || node.dataset.kind !== kind)
|
||||||
|
throw new Error('请重新读取申请后再复核。');
|
||||||
|
const note = values.note.trim();
|
||||||
|
if (kind === 'approve' && (!request.canApprove || request.stale))
|
||||||
|
throw new Error('原记录已有变动,请重新读取并核对。');
|
||||||
|
if (kind === 'reject' && !note) throw new Error('请填写驳回意见。');
|
||||||
|
if (note.length > 200) throw new Error('复核意见最多200字。');
|
||||||
|
if (kind === 'approve' && !values.verified) throw new Error('请核对修改前后内容并勾选确认。');
|
||||||
|
url = path + '/' + kind;
|
||||||
|
input = { revision: request.revision, note, ...(kind === 'approve' ? { verified: true } : {}) };
|
||||||
|
} else {
|
||||||
|
if (id && (blocked || !detail || !detail.permissions.canEdit || detail.pending || node.dataset.id !== id))
|
||||||
|
throw new Error('请重新读取售后记录后再修改。');
|
||||||
|
input = {
|
||||||
|
date: values.date,
|
||||||
|
project: values.project.trim(),
|
||||||
|
customer: values.customer.trim(),
|
||||||
|
amount: values.amount.trim(),
|
||||||
|
payer: values.payer,
|
||||||
|
};
|
||||||
|
if (!views.validOrderDate(input.date) || input.date > state.today)
|
||||||
|
throw new Error('售后日期请选择今天或之前的有效日期。');
|
||||||
|
if (!input.project || input.project.length > 100) throw new Error('售后项目请填写1~100字。');
|
||||||
|
if (!input.customer || input.customer.length > 60) throw new Error('客户请填写1~60字的称呼或代号。');
|
||||||
|
if (!views.teamMemberKeys().includes(input.payer)) throw new Error('请选择这笔售后由谁支付。');
|
||||||
|
Calc.cents(input.amount, '售后金额');
|
||||||
|
if (id && detail) {
|
||||||
|
const reason = values.reason.trim();
|
||||||
|
if (reason.length > 200) throw new Error('修改说明最多200字。');
|
||||||
|
url = path + '/update';
|
||||||
|
input = { revision: detail.revision, ...input, reason };
|
||||||
|
} else {
|
||||||
|
url = '/api/after-sales';
|
||||||
|
if (views.teamMode()) Object.assign(input, { member: values.member || views.currentMember() });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setError('');
|
||||||
|
const result = await client.mutate(url, input);
|
||||||
|
await finish(url, input, result, at);
|
||||||
|
} catch (err) {
|
||||||
|
if (at !== version.current) return;
|
||||||
|
const verified = node.elements.namedItem('verified');
|
||||||
|
if (staleError(err) && verified instanceof HTMLInputElement) verified.checked = false;
|
||||||
|
fail(err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const reread = (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={client.busy}
|
||||||
|
data-action={review ? 'after-sale-change-open' : 'after-sale-edit'}
|
||||||
|
data-id={id}
|
||||||
|
>
|
||||||
|
{review ? '重新读取申请并复核' : '重新读取售后'}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
const feedback = error && (
|
||||||
|
<div className="error" role="alert">
|
||||||
|
{error}{' '}
|
||||||
|
{id &&
|
||||||
|
(client.pending() ? (
|
||||||
|
<button type="button" data-action="retry" disabled={client.busy}>
|
||||||
|
恢复原操作
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
reread
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
const ui = { approval, blocked, busy: client.busy, feedback };
|
||||||
|
const panel = orderViews({ state, session, ui });
|
||||||
|
let content;
|
||||||
|
if (receipt || (path && (review ? !request : !detail))) {
|
||||||
|
content = (
|
||||||
|
<>
|
||||||
|
<button
|
||||||
|
className="dialog-close"
|
||||||
|
data-action={review ? 'after-sale-changes-close' : 'close-after-sale'}
|
||||||
|
aria-label={review ? '关闭售后修改复核' : '关闭售后记录'}
|
||||||
|
>
|
||||||
|
×
|
||||||
|
</button>
|
||||||
|
<h2>{receipt || (review ? '售后修改复核' : '修改售后')}</h2>
|
||||||
|
{read.error || error ? (
|
||||||
|
<div className="error" role="alert">
|
||||||
|
{read.error || error} {reread}
|
||||||
|
{review && <button data-action="after-sale-changes-reload">返回申请列表</button>}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<p role="status">{receipt ? '正在刷新…' : review ? '正在读取申请…' : '正在读取售后记录…'}</p>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
} else if (review && request) content = panel.independentReview(request, kind);
|
||||||
|
else content = id && detail ? panel.editIndependentSale(detail) : panel.newIndependentSale();
|
||||||
|
return (
|
||||||
|
<Dialog
|
||||||
|
id={review ? 'after-sale-changes-dialog' : 'after-sale-dialog'}
|
||||||
|
ownClose
|
||||||
|
label={review ? '售后修改复核' : '售后记录'}
|
||||||
|
close={dismiss}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
onClick={handle}
|
||||||
|
onSubmit={submit}
|
||||||
|
onChange={event => {
|
||||||
|
if (event.target instanceof HTMLInputElement && event.target.name === 'date') setDate(event.target.value);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{content}
|
||||||
|
</div>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
+161
-79
@@ -1,29 +1,70 @@
|
|||||||
import { useEffect, useRef, useState } from 'react';
|
import { useEffect, useRef, useState, type FormEvent } from 'react';
|
||||||
|
import type { EditInputs, EditFee, EditItem, LockMaterial, LockEntry, LockEditorProps } from './editTypes';
|
||||||
|
import type { LedgerState, PresetState } from '../../shared';
|
||||||
|
|
||||||
|
type CostKey = 'material' | 'labor' | 'accessories' | 'other';
|
||||||
|
type Preview = Record<CostKey | 'total' | 'profit' | 'fees', number>;
|
||||||
|
interface CostForm {
|
||||||
|
presets: PresetState;
|
||||||
|
originals: Record<string, EditFee>;
|
||||||
|
rows: EditFee[];
|
||||||
|
originalChecked: Record<string, boolean>;
|
||||||
|
}
|
||||||
|
type FinancialInput = Pick<EditInputs, 'lines' | 'fee_items' | 'price_lock_material' | 'price_lock_extra_material'> &
|
||||||
|
Partial<Pick<EditInputs, 'date' | 'fees_date' | 'fee_cost_mode'>>;
|
||||||
|
type FeeSnapshot = {
|
||||||
|
key: string;
|
||||||
|
expense_id: string;
|
||||||
|
date?: string;
|
||||||
|
note: string;
|
||||||
|
payer: string;
|
||||||
|
amount: string | number;
|
||||||
|
funding: Record<string, unknown> | null;
|
||||||
|
};
|
||||||
|
interface FinancialSnapshot {
|
||||||
|
fees: FeeSnapshot[];
|
||||||
|
date?: string;
|
||||||
|
fees_date?: string;
|
||||||
|
fee_cost_mode: string;
|
||||||
|
lines?: (FinancialSnapshot & { lineId?: string })[];
|
||||||
|
material?: object;
|
||||||
|
extra?: object | null;
|
||||||
|
costs?: object;
|
||||||
|
}
|
||||||
|
type UpdateInput = (fields: Partial<EditInputs>) => void;
|
||||||
|
|
||||||
import { Calc as LedgerCalc, Fees, Model, Values } from '../../shared';
|
import { Calc as LedgerCalc, Fees, Model, Values } from '../../shared';
|
||||||
import { Button } from '../Settings/controls';
|
import { Button } from '../Settings/controls';
|
||||||
import { Input, Choice } from './EditFields';
|
import { Input, Choice } from './EditFields';
|
||||||
const { yuan, grams, validateOrderIdentity } = Model;
|
const { yuan, grams, validateOrderIdentity } = Model;
|
||||||
const feeCategories = { jd: 'shipping', yt: 'shipping', box: 'box', steel: 'braiding', silver: 'silverChain' };
|
const feeCategories: Record<string, string> = {
|
||||||
|
jd: 'shipping',
|
||||||
|
yt: 'shipping',
|
||||||
|
box: 'box',
|
||||||
|
steel: 'braiding',
|
||||||
|
silver: 'silverChain',
|
||||||
|
};
|
||||||
const validOrderDate = Values.validDate;
|
const validOrderDate = Values.validDate;
|
||||||
function priceLockEditAmount(value) {
|
function priceLockEditAmount(value: unknown) {
|
||||||
try {
|
try {
|
||||||
return LedgerCalc.cents(String(value), '成本');
|
return LedgerCalc.cents(String(value), '成本');
|
||||||
} catch {
|
} catch {
|
||||||
return String(value ?? '');
|
return String(value ?? '');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
function priceLockOrderEditMeta(entry, index) {
|
function priceLockOrderEditMeta(entry: LockEntry, index: number) {
|
||||||
return entry.priceLock.lines?.[index] || entry.priceLock;
|
return entry.priceLock.lines?.[index] || entry.priceLock;
|
||||||
}
|
}
|
||||||
function priceLockOrderEditMaterial(input, index) {
|
function priceLockOrderEditMaterial(input: FinancialInput, index: number) {
|
||||||
return input.lines[index].price_lock_material || (input.lines.length === 1 ? input.price_lock_material : null);
|
return input.lines[index].price_lock_material || (input.lines.length === 1 ? input.price_lock_material : undefined);
|
||||||
}
|
}
|
||||||
function priceLockOrderEditExtra(input, index) {
|
function priceLockOrderEditExtra(input: FinancialInput, index: number) {
|
||||||
return (
|
return (
|
||||||
input.lines[index].price_lock_extra_material || (input.lines.length === 1 ? input.price_lock_extra_material : null)
|
input.lines[index].price_lock_extra_material ||
|
||||||
|
(input.lines.length === 1 ? input.price_lock_extra_material : undefined)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function priceLockEditFinancialValue(input) {
|
function priceLockEditFinancialValue(input: FinancialInput): FinancialSnapshot {
|
||||||
if (input?.lines?.length > 1)
|
if (input?.lines?.length > 1)
|
||||||
return {
|
return {
|
||||||
date: input.date,
|
date: input.date,
|
||||||
@@ -40,8 +81,8 @@ function priceLockEditFinancialValue(input) {
|
|||||||
})),
|
})),
|
||||||
fees: priceLockEditFinancialValue({ ...input, lines: [] }).fees,
|
fees: priceLockEditFinancialValue({ ...input, lines: [] }).fees,
|
||||||
};
|
};
|
||||||
const line = input?.lines?.[0] || {},
|
const line: Partial<EditItem> = input?.lines?.[0] || {},
|
||||||
material = input?.price_lock_material || {},
|
material: Partial<LockMaterial> = input?.price_lock_material || {},
|
||||||
extra = input?.price_lock_extra_material;
|
extra = input?.price_lock_extra_material;
|
||||||
return {
|
return {
|
||||||
date: input?.date,
|
date: input?.date,
|
||||||
@@ -80,22 +121,22 @@ function priceLockEditFinancialValue(input) {
|
|||||||
.sort((a, b) => String(a.key).localeCompare(String(b.key))),
|
.sort((a, b) => String(a.key).localeCompare(String(b.key))),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
function priceLockEditFinancialChanged(entry, input = entry?.inputs) {
|
function priceLockEditFinancialChanged(entry: LockEntry, input: EditInputs = entry.inputs) {
|
||||||
return (
|
return (
|
||||||
JSON.stringify(priceLockEditFinancialValue(input)) !==
|
JSON.stringify(priceLockEditFinancialValue(input)) !==
|
||||||
JSON.stringify(priceLockEditFinancialValue(entry?.originalInputs))
|
JSON.stringify(priceLockEditFinancialValue(entry?.originalInputs))
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function priceLockEditGramCost(mg, rate) {
|
function priceLockEditGramCost(mg: number, rate: string) {
|
||||||
return LedgerCalc.purchaseCosts({
|
return LedgerCalc.purchaseCosts({
|
||||||
unit: 'g',
|
unit: 'g',
|
||||||
quantity: grams(mg),
|
quantity: grams(mg),
|
||||||
costParts: { material: '0', labor: '0', accessories: '0', other: '0' },
|
costParts: { material: '0', labor: '0', accessories: '0', other: '0' },
|
||||||
costMaterial: { mode: 'gram', rate },
|
costMaterial: { mode: 'gram', rate },
|
||||||
costLabor: { mode: 'total' },
|
costLabor: { mode: 'total' },
|
||||||
}).parts.material;
|
}).parts.material!;
|
||||||
}
|
}
|
||||||
function priceLockOrderEditPreview(input, entry) {
|
function priceLockOrderEditPreview(input: EditInputs, entry: LockEntry): Preview {
|
||||||
if (input.lines.length > 1) {
|
if (input.lines.length > 1) {
|
||||||
const costs = {
|
const costs = {
|
||||||
material: 0,
|
material: 0,
|
||||||
@@ -126,29 +167,28 @@ function priceLockOrderEditPreview(input, entry) {
|
|||||||
order: { ...entry.order, lines: [entry.order.lines[index]] },
|
order: { ...entry.order, lines: [entry.order.lines[index]] },
|
||||||
};
|
};
|
||||||
const value = priceLockOrderEditPreview(singleInput, singleEntry);
|
const value = priceLockOrderEditPreview(singleInput, singleEntry);
|
||||||
for (const key of ['material', 'labor', 'accessories', 'other']) costs[key] += value[key];
|
for (const key of ['material', 'labor', 'accessories', 'other'] as const) costs[key] += value[key];
|
||||||
});
|
});
|
||||||
costs.total = Object.values(costs).reduce((sum, value) => sum + value, 0);
|
const total = Object.values(costs).reduce((sum, value) => sum + value, 0);
|
||||||
costs.profit = entry.order.total - costs.total;
|
return { ...costs, total, profit: entry.order.total - total };
|
||||||
return costs;
|
|
||||||
}
|
}
|
||||||
const original = entry.originalInputs,
|
const original = entry.originalInputs,
|
||||||
line = input.lines[0],
|
line = input.lines[0],
|
||||||
extraMg = entry.priceLock.extraMg,
|
extraMg = entry.priceLock.extraMg,
|
||||||
usedMg = entry.order.lines[0].quantity - extraMg,
|
usedMg = entry.order.lines[0].quantity - extraMg,
|
||||||
oldExtra = extraMg
|
oldExtra = extraMg
|
||||||
? original.price_lock_extra_material.source === 'pool'
|
? original.price_lock_extra_material!.source === 'pool'
|
||||||
? original.price_lock_extra_material.amount
|
? original.price_lock_extra_material!.amount!
|
||||||
: priceLockEditGramCost(extraMg, original.price_lock_extra_material.rate)
|
: priceLockEditGramCost(extraMg, original.price_lock_extra_material!.rate)
|
||||||
: 0;
|
: 0;
|
||||||
const originalMaterial =
|
const originalMaterial =
|
||||||
input.price_lock_material.source === 'pool'
|
input.price_lock_material!.source === 'pool'
|
||||||
? LedgerCalc.cents(original.lines[0].costParts.material, '原料费') - oldExtra
|
? LedgerCalc.cents(original.lines[0].costParts.material, '原料费') - oldExtra
|
||||||
: priceLockEditGramCost(usedMg, input.price_lock_material.rate),
|
: priceLockEditGramCost(usedMg, input.price_lock_material!.rate),
|
||||||
extra = extraMg
|
extra = extraMg
|
||||||
? input.price_lock_extra_material.source === 'pool'
|
? input.price_lock_extra_material!.source === 'pool'
|
||||||
? original.price_lock_extra_material.amount
|
? original.price_lock_extra_material!.amount!
|
||||||
: priceLockEditGramCost(extraMg, input.price_lock_extra_material.rate)
|
: priceLockEditGramCost(extraMg, input.price_lock_extra_material!.rate)
|
||||||
: 0;
|
: 0;
|
||||||
if (!Number.isSafeInteger(originalMaterial) || originalMaterial < 0 || !Number.isSafeInteger(extra))
|
if (!Number.isSafeInteger(originalMaterial) || originalMaterial < 0 || !Number.isSafeInteger(extra))
|
||||||
throw new Error('原锁料费尚未完整,请核对原料价与补重料价。');
|
throw new Error('原锁料费尚未完整,请核对原料价与补重料价。');
|
||||||
@@ -159,14 +199,13 @@ function priceLockOrderEditPreview(input, entry) {
|
|||||||
other: LedgerCalc.cents(line.costParts.other, '其他货品成本'),
|
other: LedgerCalc.cents(line.costParts.other, '其他货品成本'),
|
||||||
fees: input.fee_items.reduce((total, fee) => total + LedgerCalc.cents(fee.amount, '实际费用'), 0),
|
fees: input.fee_items.reduce((total, fee) => total + LedgerCalc.cents(fee.amount, '实际费用'), 0),
|
||||||
};
|
};
|
||||||
costs.total = Object.values(costs).reduce((total, amount) => total + amount, 0);
|
const total = Object.values(costs).reduce((sum, amount) => sum + amount, 0);
|
||||||
costs.profit = entry.order.total - costs.total;
|
return { ...costs, total, profit: entry.order.total - total };
|
||||||
return costs;
|
|
||||||
}
|
}
|
||||||
function materialPoolRate(value) {
|
function materialPoolRate(value: number | null | undefined) {
|
||||||
return value == null ? '待补采购' : yuan(value);
|
return value == null ? '待补采购' : yuan(value);
|
||||||
}
|
}
|
||||||
function validatePriceLockOrderEdit(input, entry, state) {
|
function validatePriceLockOrderEdit(input: EditInputs, entry: LockEntry, state: LedgerState): EditInputs {
|
||||||
if (input.lines.length > 1) {
|
if (input.lines.length > 1) {
|
||||||
if (input.lines.length !== entry.order.lines.length) throw new Error('商品成本资料未完整读到,请重新读取订单。');
|
if (input.lines.length !== entry.order.lines.length) throw new Error('商品成本资料未完整读到,请重新读取订单。');
|
||||||
input.lines.forEach((line, index) => {
|
input.lines.forEach((line, index) => {
|
||||||
@@ -205,7 +244,7 @@ function validatePriceLockOrderEdit(input, entry, state) {
|
|||||||
line = input.lines[0];
|
line = input.lines[0];
|
||||||
if (
|
if (
|
||||||
!material ||
|
!material ||
|
||||||
!['pool', 'manual'].includes(material.source) ||
|
!['pool', 'manual'].includes(material.source || '') ||
|
||||||
(material.source === 'pool' && entry.priceLock.materialSource !== 'pool') ||
|
(material.source === 'pool' && entry.priceLock.materialSource !== 'pool') ||
|
||||||
(material.source === 'manual' && entry.priceLock.materialSource === 'pool' && !entry.priceLock.canSwitchToManual)
|
(material.source === 'manual' && entry.priceLock.materialSource === 'pool' && !entry.priceLock.canSwitchToManual)
|
||||||
)
|
)
|
||||||
@@ -229,7 +268,7 @@ function validatePriceLockOrderEdit(input, entry, state) {
|
|||||||
['labor', '进货总工费'],
|
['labor', '进货总工费'],
|
||||||
['accessories', '配件成本'],
|
['accessories', '配件成本'],
|
||||||
['other', '其他货品成本'],
|
['other', '其他货品成本'],
|
||||||
])
|
] as const)
|
||||||
LedgerCalc.cents(line.costParts[key], name);
|
LedgerCalc.cents(line.costParts[key], name);
|
||||||
for (const fee of input.fee_items) {
|
for (const fee of input.fee_items) {
|
||||||
LedgerCalc.cents(fee.amount, '实际费用');
|
LedgerCalc.cents(fee.amount, '实际费用');
|
||||||
@@ -247,18 +286,18 @@ function validatePriceLockOrderEdit(input, entry, state) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const moneyProps = { type: 'number', min: '0', step: '0.01', required: true };
|
const moneyProps = { type: 'number', min: '0', step: '0.01', required: true };
|
||||||
const automaticFee = fee => fee?.system === 'credit_card' || String(fee?.key || '').startsWith('card_fee:');
|
const automaticFee = (fee: EditFee) => fee?.system === 'credit_card' || String(fee?.key || '').startsWith('card_fee:');
|
||||||
const categoryOf = kind => feeCategories[kind] || kind;
|
const categoryOf = (kind: string) => feeCategories[kind] || kind;
|
||||||
function feeCategory(fee, config) {
|
function feeCategory(fee: EditFee, config: Record<string, unknown>) {
|
||||||
if (fee.key.startsWith('manual:') && config['custom_' + fee.key.slice(7)]) return 'custom_' + fee.key.slice(7);
|
if (fee.key.startsWith('manual:') && config['custom_' + fee.key.slice(7)]) return 'custom_' + fee.key.slice(7);
|
||||||
if (fee.key === 'shipping' || fee.key === 'box') return fee.key;
|
if (fee.key === 'shipping' || fee.key === 'box') return fee.key;
|
||||||
if (String(fee.note || '').trim() === '编绳') return '';
|
if (String(fee.note || '').trim() === '编绳') return '';
|
||||||
return Fees.checkboxCategory(fee.note) || Fees.checkboxCategory(fee.sourceName);
|
return Fees.checkboxCategory(fee.note) || Fees.checkboxCategory(fee.sourceName ?? '');
|
||||||
}
|
}
|
||||||
function costSetup(input, state) {
|
function costSetup(input: EditInputs, state: LedgerState): CostForm {
|
||||||
const config = Model.costConfig(state),
|
const config = Model.costConfig(state),
|
||||||
presets = Model.newPresets(state, input.fee_items, true),
|
presets = Model.newPresets(state, input.fee_items, true),
|
||||||
originals = {},
|
originals: Record<string, EditFee> = {},
|
||||||
rows = [];
|
rows = [];
|
||||||
for (const raw of input.fee_items || []) {
|
for (const raw of input.fee_items || []) {
|
||||||
const fee = { ...raw, note: raw.note || Model.feeLabels[raw.key], edited: raw.edited ?? true };
|
const fee = { ...raw, note: raw.note || Model.feeLabels[raw.key], edited: raw.edited ?? true };
|
||||||
@@ -268,7 +307,7 @@ function costSetup(input, state) {
|
|||||||
}
|
}
|
||||||
return { presets, originals, rows, originalChecked: { ...presets.checked } };
|
return { presets, originals, rows, originalChecked: { ...presets.checked } };
|
||||||
}
|
}
|
||||||
function feeTotals(cost, input, state) {
|
function feeTotals(cost: CostForm, input: EditInputs, state: LedgerState) {
|
||||||
const { items, notes } = Model.readPresets({ presets: cost.presets, member: input.member }, state);
|
const { items, notes } = Model.readPresets({ presets: cost.presets, member: input.member }, state);
|
||||||
const config = Model.costConfig(state);
|
const config = Model.costConfig(state);
|
||||||
const presets = items.map(item => {
|
const presets = items.map(item => {
|
||||||
@@ -294,7 +333,21 @@ function feeTotals(cost, input, state) {
|
|||||||
});
|
});
|
||||||
return { items: [...others, ...presets], notes };
|
return { items: [...others, ...presets], notes };
|
||||||
}
|
}
|
||||||
function EditableFees({ input, state, cost, update, inputChange, removeFee }) {
|
function EditableFees({
|
||||||
|
input,
|
||||||
|
state,
|
||||||
|
cost,
|
||||||
|
update,
|
||||||
|
inputChange,
|
||||||
|
removeFee,
|
||||||
|
}: {
|
||||||
|
input: EditInputs;
|
||||||
|
state: LedgerState;
|
||||||
|
cost: CostForm;
|
||||||
|
update: (cost: CostForm) => void;
|
||||||
|
inputChange: UpdateInput;
|
||||||
|
removeFee: (index: number) => void;
|
||||||
|
}) {
|
||||||
const config = Model.costConfig(state),
|
const config = Model.costConfig(state),
|
||||||
catalog = Fees.presetCatalog(config),
|
catalog = Fees.presetCatalog(config),
|
||||||
{ presets, rows, originals } = cost,
|
{ presets, rows, originals } = cost,
|
||||||
@@ -302,11 +355,11 @@ function EditableFees({ input, state, cost, update, inputChange, removeFee }) {
|
|||||||
const { notes } = feeTotals(cost, input, state),
|
const { notes } = feeTotals(cost, input, state),
|
||||||
own = Model.formMember(input, state);
|
own = Model.formMember(input, state);
|
||||||
// 交付后改单沿用已入账项目的付款流水和日期。数量控件保留打开本单时的录入状态。
|
// 交付后改单沿用已入账项目的付款流水和日期。数量控件保留打开本单时的录入状态。
|
||||||
const setPreset = (kind, quantity, value) => {
|
const setPreset = (kind: string, quantity: boolean, value: string | boolean) => {
|
||||||
const name = quantity ? 'quantity' : 'checked';
|
const name = quantity ? 'quantity' : 'checked';
|
||||||
update({ ...cost, presets: { ...presets, [name]: { ...presets[name], [kind]: value } } });
|
update({ ...cost, presets: { ...presets, [name]: { ...presets[name], [kind]: value } } });
|
||||||
};
|
};
|
||||||
const patchRow = (index, patch) =>
|
const patchRow = (index: number, patch: Partial<EditFee>) =>
|
||||||
update({ ...cost, rows: rows.map((row, i) => (i === index ? { ...row, ...patch, edited: true } : row)) });
|
update({ ...cost, rows: rows.map((row, i) => (i === index ? { ...row, ...patch, edited: true } : row)) });
|
||||||
return (
|
return (
|
||||||
<section className="panel internal">
|
<section className="panel internal">
|
||||||
@@ -511,7 +564,7 @@ function EditableFees({ input, state, cost, update, inputChange, removeFee }) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function editPayload(input, fees, state, entry) {
|
function editPayload(input: EditInputs, fees: CostForm, state: LedgerState, entry: LockEntry): EditInputs {
|
||||||
const lines = input.lines.map(line => ({
|
const lines = input.lines.map(line => ({
|
||||||
...line,
|
...line,
|
||||||
costLabor: line.costLabor?.mode === 'gram' ? line.costLabor : { mode: 'total' },
|
costLabor: line.costLabor?.mode === 'gram' ? line.costLabor : { mode: 'total' },
|
||||||
@@ -523,17 +576,34 @@ function editPayload(input, fees, state, entry) {
|
|||||||
fee_items: feeTotals(fees, { ...input, member: entry.order.member }, state).items,
|
fee_items: feeTotals(fees, { ...input, member: entry.order.member }, state).items,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
function LockLine({ entry, state, input, multi, index, update }) {
|
function LockLine({
|
||||||
|
entry,
|
||||||
|
state,
|
||||||
|
input,
|
||||||
|
multi,
|
||||||
|
index,
|
||||||
|
update,
|
||||||
|
}: {
|
||||||
|
entry: LockEntry;
|
||||||
|
state: LedgerState;
|
||||||
|
input: EditInputs;
|
||||||
|
multi: boolean;
|
||||||
|
index: number;
|
||||||
|
update: UpdateInput;
|
||||||
|
}) {
|
||||||
const line = input.lines[index],
|
const line = input.lines[index],
|
||||||
raw = entry.order.lines[index],
|
raw = entry.order.lines[index],
|
||||||
meta = priceLockOrderEditMeta(entry, index);
|
meta = priceLockOrderEditMeta(entry, index);
|
||||||
const mat = multi ? priceLockOrderEditMaterial(input, index) : input.price_lock_material,
|
const mat = (multi ? priceLockOrderEditMaterial(input, index) : input.price_lock_material)!,
|
||||||
extra = multi ? priceLockOrderEditExtra(input, index) : input.price_lock_extra_material,
|
extra = multi ? priceLockOrderEditExtra(input, index) : input.price_lock_extra_material,
|
||||||
manual = mat.source === 'manual',
|
manual = mat.source === 'manual',
|
||||||
pooledExtra = extra?.source === 'pool' && !!raw.priceLockExtraPool;
|
pooledExtra = extra?.source === 'pool' && !!raw.priceLockExtraPool;
|
||||||
const gram = line.costLabor?.mode === 'gram',
|
const gram = line.costLabor?.mode === 'gram',
|
||||||
payers = value => [['', '请选择'], ...Model.memberOptions(state, false, { selected: value })];
|
payers = (value: string): [string, string][] => [
|
||||||
function change(linePatch = {}, material = mat, extraCost = extra) {
|
['', '请选择'],
|
||||||
|
...Model.memberOptions(state, false, { selected: value }),
|
||||||
|
];
|
||||||
|
function change(linePatch: Partial<EditItem> = {}, material = mat, extraCost = extra) {
|
||||||
const next = { ...line, ...linePatch };
|
const next = { ...line, ...linePatch };
|
||||||
const lines = input.lines.map((r, i) =>
|
const lines = input.lines.map((r, i) =>
|
||||||
i === index
|
i === index
|
||||||
@@ -549,7 +619,7 @@ function LockLine({ entry, state, input, multi, index, update }) {
|
|||||||
: {}),
|
: {}),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
function labor(mode, value) {
|
function labor(mode: string, value?: string) {
|
||||||
const costLabor = { mode, ...(mode === 'gram' ? { rate: value ?? line.costLabor?.rate ?? '' } : {}) };
|
const costLabor = { mode, ...(mode === 'gram' ? { rate: value ?? line.costLabor?.rate ?? '' } : {}) };
|
||||||
let total = line.costParts.labor;
|
let total = line.costParts.labor;
|
||||||
if (mode === 'gram') {
|
if (mode === 'gram') {
|
||||||
@@ -601,7 +671,7 @@ function LockLine({ entry, state, input, multi, index, update }) {
|
|||||||
value={mat.source}
|
value={mat.source}
|
||||||
options={
|
options={
|
||||||
meta.materialSource === 'pool'
|
meta.materialSource === 'pool'
|
||||||
? [['pool', '保留原锁料池'], ...(meta.canSwitchToManual ? [['manual', '改为手填原锁料价']] : [])]
|
? [['pool', '保留原锁料池'], ...(meta.canSwitchToManual ? [['manual', '改为手填原锁料价'] as const] : [])]
|
||||||
: [['manual', '手填原锁料价']]
|
: [['manual', '手填原锁料价']]
|
||||||
}
|
}
|
||||||
onChange={source =>
|
onChange={source =>
|
||||||
@@ -630,7 +700,7 @@ function LockLine({ entry, state, input, multi, index, update }) {
|
|||||||
sources
|
sources
|
||||||
.map(
|
.map(
|
||||||
s =>
|
s =>
|
||||||
(s.kind === 'personal_recovery' ? Model.memberName(state, s.member) + '个人回收料' : '公共料') +
|
(s.kind === 'personal_recovery' ? Model.memberName(state, s.member!) + '个人回收料' : '公共料') +
|
||||||
' ' +
|
' ' +
|
||||||
grams(s.quantity) +
|
grams(s.quantity) +
|
||||||
'g · ' +
|
'g · ' +
|
||||||
@@ -792,24 +862,33 @@ function LockLine({ entry, state, input, multi, index, update }) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function LockOrderEditor({ client, state, session, entry, serverFeedback, onDraft, onSave, onCancel }) {
|
export function LockOrderEditor({
|
||||||
|
client,
|
||||||
|
state,
|
||||||
|
session,
|
||||||
|
entry,
|
||||||
|
serverFeedback,
|
||||||
|
onDraft,
|
||||||
|
onSave,
|
||||||
|
onCancel,
|
||||||
|
}: LockEditorProps) {
|
||||||
const [input, setInput] = useState(() => entry.inputs),
|
const [input, setInput] = useState(() => entry.inputs),
|
||||||
[fees, setFees] = useState(() => costSetup(entry.inputs, state));
|
[fees, setFees] = useState(() => costSetup(entry.inputs, state));
|
||||||
const [reason, setReason] = useState(entry.reason || ''),
|
const [reason, setReason] = useState(entry.reason || ''),
|
||||||
[verified, setVerified] = useState(!!entry.verified),
|
[verified, setVerified] = useState(!!entry.verified),
|
||||||
[error, setError] = useState(''),
|
[error, setError] = useState(''),
|
||||||
[tags, setTags] = useState([]);
|
[tags, setTags] = useState<string[]>([]);
|
||||||
const textarea = useRef(null),
|
const textarea = useRef<HTMLTextAreaElement>(null),
|
||||||
lastEntry = useRef(entry.id);
|
lastEntry = useRef(entry.id);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let active = true;
|
let active = true;
|
||||||
client
|
client
|
||||||
.api('/api/order-note-tags')
|
.api<{ tags: string[] }>('/api/order-note-tags')
|
||||||
.then(r => {
|
.then(r => {
|
||||||
if (active) setTags(r.tags);
|
if (active) setTags(r.tags);
|
||||||
})
|
})
|
||||||
.catch(err => {
|
.catch(err => {
|
||||||
if (active) setError(err.message);
|
if (active) setError(err instanceof Error ? err.message : String(err));
|
||||||
});
|
});
|
||||||
return () => {
|
return () => {
|
||||||
active = false;
|
active = false;
|
||||||
@@ -819,30 +898,30 @@ export function LockOrderEditor({ client, state, session, entry, serverFeedback,
|
|||||||
const wire = editPayload(input, fees, state, entry);
|
const wire = editPayload(input, fees, state, entry);
|
||||||
const approvedFinance = entry.priceLock.financeRequiresApproval && priceLockEditFinancialChanged(entry, wire);
|
const approvedFinance = entry.priceLock.financeRequiresApproval && priceLockEditFinancialChanged(entry, wire);
|
||||||
const approval =
|
const approval =
|
||||||
session.user.role === 'assistant' &&
|
session.user?.role === 'assistant' &&
|
||||||
(!entry.sameDayDirectEdit ||
|
(!entry.sameDayDirectEdit ||
|
||||||
!entry.directEditDate ||
|
!entry.directEditDate ||
|
||||||
entry.order.date !== entry.directEditDate ||
|
entry.order.date !== entry.directEditDate ||
|
||||||
wire.date !== entry.directEditDate ||
|
wire.date !== entry.directEditDate ||
|
||||||
approvedFinance);
|
approvedFinance);
|
||||||
function persist(next, nextFees, newReason, checked) {
|
function persist(next: EditInputs, nextFees: CostForm, newReason: string, checked: boolean) {
|
||||||
const draft = editPayload(next, nextFees, state, entry);
|
const draft = editPayload(next, nextFees, state, entry);
|
||||||
onDraft(draft, newReason, checked);
|
onDraft(draft, newReason, checked);
|
||||||
}
|
}
|
||||||
function update(fields) {
|
function update(fields: Partial<EditInputs>) {
|
||||||
const next = { ...input, ...fields };
|
const next = { ...input, ...fields };
|
||||||
setInput(next);
|
setInput(next);
|
||||||
setVerified(false);
|
setVerified(false);
|
||||||
setError('');
|
setError('');
|
||||||
persist(next, fees, reason, false);
|
persist(next, fees, reason, false);
|
||||||
}
|
}
|
||||||
function updateFees(value) {
|
function updateFees(value: CostForm) {
|
||||||
setFees(value);
|
setFees(value);
|
||||||
setVerified(false);
|
setVerified(false);
|
||||||
setError('');
|
setError('');
|
||||||
persist(input, value, reason, false);
|
persist(input, value, reason, false);
|
||||||
}
|
}
|
||||||
function removeFee(index) {
|
function removeFee(index: number) {
|
||||||
const key = fees.rows[index].key;
|
const key = fees.rows[index].key;
|
||||||
const next = {
|
const next = {
|
||||||
...input,
|
...input,
|
||||||
@@ -851,7 +930,7 @@ export function LockOrderEditor({ client, state, session, entry, serverFeedback,
|
|||||||
...(line.charges
|
...(line.charges
|
||||||
? {
|
? {
|
||||||
charges: line.charges.map(charge =>
|
charges: line.charges.map(charge =>
|
||||||
key === 'charge:' + charge.id || (key === 'shipping' && Fees.normalize(charge.name) === '快递')
|
key === 'charge:' + charge.id || (key === 'shipping' && Fees.normalize(charge.name ?? '') === '快递')
|
||||||
? { ...charge, costRemoved: true }
|
? { ...charge, costRemoved: true }
|
||||||
: charge,
|
: charge,
|
||||||
),
|
),
|
||||||
@@ -866,21 +945,22 @@ export function LockOrderEditor({ client, state, session, entry, serverFeedback,
|
|||||||
setError('');
|
setError('');
|
||||||
persist(next, nextFees, reason, false);
|
persist(next, nextFees, reason, false);
|
||||||
}
|
}
|
||||||
function editReason(value) {
|
function editReason(value: string) {
|
||||||
setReason(value);
|
setReason(value);
|
||||||
persist(input, fees, value, verified);
|
persist(input, fees, value, verified);
|
||||||
}
|
}
|
||||||
function verify(value) {
|
function verify(value: boolean) {
|
||||||
setVerified(value);
|
setVerified(value);
|
||||||
persist(input, fees, reason, value);
|
persist(input, fees, reason, value);
|
||||||
}
|
}
|
||||||
let costs, previewError;
|
let costs: Preview | undefined,
|
||||||
|
previewError = '';
|
||||||
try {
|
try {
|
||||||
costs = priceLockOrderEditPreview(wire, entry);
|
costs = priceLockOrderEditPreview(wire, entry);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
previewError = err.message;
|
previewError = err instanceof Error ? err.message : String(err);
|
||||||
}
|
}
|
||||||
async function save(event) {
|
async function save(event: FormEvent<HTMLFormElement>) {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
try {
|
try {
|
||||||
if (entry.user !== client.user || lastEntry.current !== entry.id)
|
if (entry.user !== client.user || lastEntry.current !== entry.id)
|
||||||
@@ -892,7 +972,7 @@ export function LockOrderEditor({ client, state, session, entry, serverFeedback,
|
|||||||
setError('');
|
setError('');
|
||||||
await onSave(payload, reason.trim(), true, approval);
|
await onSave(payload, reason.trim(), true, approval);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err.message);
|
setError(err instanceof Error ? err.message : String(err));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const filteredTags = Model.filterNoteTags(tags, input.internal_note || '');
|
const filteredTags = Model.filterNoteTags(tags, input.internal_note || '');
|
||||||
@@ -1015,7 +1095,7 @@ export function LockOrderEditor({ client, state, session, entry, serverFeedback,
|
|||||||
update({ internal_note: Model.insertNoteTag(input.internal_note, tag) });
|
update({ internal_note: Model.insertNoteTag(input.internal_note, tag) });
|
||||||
textarea.current?.focus();
|
textarea.current?.focus();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err.message);
|
setError(err instanceof Error ? err.message : String(err));
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
@@ -1052,14 +1132,16 @@ export function LockOrderEditor({ client, state, session, entry, serverFeedback,
|
|||||||
aria-live="polite"
|
aria-live="polite"
|
||||||
>
|
>
|
||||||
{costs
|
{costs
|
||||||
? [
|
? (
|
||||||
['料费', costs.material],
|
[
|
||||||
['进货工费', costs.labor],
|
['料费', costs.material],
|
||||||
['配件及其他', costs.accessories + costs.other],
|
['进货工费', costs.labor],
|
||||||
['实际费用', costs.fees],
|
['配件及其他', costs.accessories + costs.other],
|
||||||
['成本合计', costs.total],
|
['实际费用', costs.fees],
|
||||||
['利润预览', costs.profit],
|
['成本合计', costs.total],
|
||||||
].map(([text, value]) => (
|
['利润预览', costs.profit],
|
||||||
|
] as const
|
||||||
|
).map(([text, value]) => (
|
||||||
<span key={text}>
|
<span key={text}>
|
||||||
{text} <strong>¥{yuan(value)}</strong>
|
{text} <strong>¥{yuan(value)}</strong>
|
||||||
</span>
|
</span>
|
||||||
@@ -1069,7 +1151,7 @@ export function LockOrderEditor({ client, state, session, entry, serverFeedback,
|
|||||||
{!multi && <p className="small muted">按本页成本预估,保存或复核同意后按原账更新利润。</p>}
|
{!multi && <p className="small muted">按本页成本预估,保存或复核同意后按原账更新利润。</p>}
|
||||||
</section>
|
</section>
|
||||||
<section className="panel">
|
<section className="panel">
|
||||||
<div className="note" data-order-edit-approval-note hidden={session.user.role !== 'assistant'}>
|
<div className="note" data-order-edit-approval-note hidden={state.user.role !== 'assistant'}>
|
||||||
{approval
|
{approval
|
||||||
? approvedFinance
|
? approvedFinance
|
||||||
? entry.priceLock.approvalReason || entry.approvalReason || '涉及历史锁价购料或料池,请提交店主复核。'
|
? entry.priceLock.approvalReason || entry.approvalReason || '涉及历史锁价购料或料池,请提交店主复核。'
|
||||||
+144
-357
@@ -1,18 +1,60 @@
|
|||||||
import { App as AntApp } from 'antd';
|
import type { FormEvent, MouseEvent, SyntheticEvent } from 'react';
|
||||||
|
import type { LedgerState, SessionInfo } from '../../shared';
|
||||||
|
import type { LedgerClient } from '../../lib/api';
|
||||||
|
import type { usePrintStatuses } from '../../lib/printStatus';
|
||||||
|
import type {
|
||||||
|
ChangeData,
|
||||||
|
OwnershipData,
|
||||||
|
CancellationData,
|
||||||
|
ChangeRequest,
|
||||||
|
OwnershipRequest,
|
||||||
|
CancellationRequest,
|
||||||
|
DetailEntry,
|
||||||
|
OrderRecord,
|
||||||
|
OrderAfterSaleData,
|
||||||
|
OrderAfterSale,
|
||||||
|
} from './orderData';
|
||||||
|
import type { OrderUi } from './viewTypes';
|
||||||
|
import { readOrderRecord, errorStatus, errorMessage as messageOf } from './readOrder';
|
||||||
|
interface DialogProps {
|
||||||
|
selected: string;
|
||||||
|
client: LedgerClient;
|
||||||
|
state: LedgerState;
|
||||||
|
session: SessionInfo;
|
||||||
|
refresh: () => void;
|
||||||
|
refreshState: () => Promise<unknown>;
|
||||||
|
listIds: string[] | null;
|
||||||
|
openOrder: (id: string) => void;
|
||||||
|
close: () => void;
|
||||||
|
onLost: (message: string) => void;
|
||||||
|
printStatuses: ReturnType<typeof usePrintStatuses>;
|
||||||
|
}
|
||||||
|
type FormKind = { type: 'after' } | { type: 'action' | 'change' | 'ownership' | 'cancellation'; kind: string };
|
||||||
|
type DetailForm = HTMLFormElement & { elements: HTMLFormControlsCollection & Record<string, HTMLInputElement> };
|
||||||
import { useOrderAccess } from './useOrderAccess';
|
import { useOrderAccess } from './useOrderAccess';
|
||||||
import { useEffect, useRef, useState } from 'react';
|
import { useEffect, useRef, useState } from 'react';
|
||||||
import { Calc } from '../../shared';
|
import { Calc } from '../../shared';
|
||||||
import { navigate } from '../../lib/router';
|
import { navigate } from '../../lib/router';
|
||||||
import { orderViews } from './orderViews';
|
import { orderViews } from './orderViews';
|
||||||
import { Dialog, queues, useRead } from './OrdersPage';
|
import { Dialog } from './Dialog';
|
||||||
|
import { queues, useRead } from './orderReads';
|
||||||
|
|
||||||
const stop = e => {
|
const stop = (e: SyntheticEvent) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
};
|
};
|
||||||
const messageOf = err => (err instanceof Error ? err.message : String(err));
|
const readForm = (form: HTMLFormElement) => Object.fromEntries(new FormData(form)) as Record<string, string>;
|
||||||
const readForm = form => Object.fromEntries(new FormData(form));
|
function DetailNavigation({
|
||||||
function DetailNavigation({ ids, id, open, blocked }) {
|
ids,
|
||||||
|
id,
|
||||||
|
open,
|
||||||
|
blocked,
|
||||||
|
}: {
|
||||||
|
ids: string[] | null;
|
||||||
|
id: string;
|
||||||
|
open: (id: string) => void;
|
||||||
|
blocked: boolean;
|
||||||
|
}) {
|
||||||
if (!ids) return null;
|
if (!ids) return null;
|
||||||
const i = ids.indexOf(id);
|
const i = ids.indexOf(id);
|
||||||
return (
|
return (
|
||||||
@@ -47,13 +89,13 @@ export function OrderActionDialog({
|
|||||||
close,
|
close,
|
||||||
onLost,
|
onLost,
|
||||||
printStatuses,
|
printStatuses,
|
||||||
}) {
|
}: DialogProps) {
|
||||||
const base = '/api/orders/' + encodeURIComponent(id);
|
const base = '/api/orders/' + encodeURIComponent(id);
|
||||||
const [generation, reload] = useState(0),
|
const [generation, reload] = useState(0),
|
||||||
[form, setForm] = useState(null),
|
[form, setForm] = useState<FormKind | null>(null),
|
||||||
[error, setError] = useState('');
|
[error, setError] = useState('');
|
||||||
const [ui, setUi] = useState({}),
|
const [ui, setUi] = useState<OrderUi>({}),
|
||||||
[expenses, setExpenses] = useState([]);
|
[expenses, setExpenses] = useState<string[]>([]);
|
||||||
const current = useRef(0);
|
const current = useRef(0);
|
||||||
useEffect(
|
useEffect(
|
||||||
() => () => {
|
() => () => {
|
||||||
@@ -62,37 +104,43 @@ export function OrderActionDialog({
|
|||||||
[],
|
[],
|
||||||
);
|
);
|
||||||
const details = useRead(async () => {
|
const details = useRead(async () => {
|
||||||
const [order, ...results] = await Promise.allSettled(
|
const [detail, change, ownership, cancellation] = await Promise.allSettled([
|
||||||
['', '/change', '/ownership', '/cancellation'].map(path => client.api(base + path)),
|
client.api<unknown>(base),
|
||||||
);
|
client.api<ChangeData>(base + '/change'),
|
||||||
if (order.status === 'rejected') {
|
client.api<OwnershipData>(base + '/ownership'),
|
||||||
access.revoke(order.reason);
|
client.api<CancellationData>(base + '/cancellation'),
|
||||||
throw order.reason;
|
]);
|
||||||
|
if (detail.status === 'rejected') {
|
||||||
|
access.revoke(detail.reason);
|
||||||
|
throw detail.reason;
|
||||||
}
|
}
|
||||||
if (order.value.id !== id) throw new Error('返回的订单与所选订单不一致,请重试读取。');
|
const order = readOrderRecord(detail.value, id);
|
||||||
const checks = orderViews({ state, session });
|
const checks = orderViews({ state, session });
|
||||||
const validators = [
|
function entry<Request, T extends { revision: number; requests: Request[] }>(
|
||||||
checks.validateOrderChangeRequest,
|
result: PromiseSettledResult<T>,
|
||||||
checks.validateOrderOwnershipRequest,
|
validate: (request: Request, id: string) => unknown,
|
||||||
checks.validateOrderCancellationRequest,
|
): DetailEntry<T> {
|
||||||
];
|
const identity = { id, user: state.user.id, revision: order!.revision };
|
||||||
const entries = results.map((r, i) => {
|
if (result.status === 'rejected') {
|
||||||
const entry = { id, user: state.user.id, revision: order.value.revision };
|
if (access.revoke(result.reason)) throw result.reason;
|
||||||
if (r.status === 'rejected') {
|
return { ...identity, error: messageOf(result.reason) };
|
||||||
if (access.revoke(r.reason)) throw r.reason;
|
|
||||||
return { ...entry, error: r.reason.message };
|
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const data = r.value;
|
const data = result.value;
|
||||||
if (data.revision !== order.value.revision || !Array.isArray(data.requests))
|
if (data.revision !== order!.revision || !Array.isArray(data.requests))
|
||||||
throw new Error('订单已有新记录,请重新读取订单后复核。');
|
throw new Error('订单已有新记录,请重新读取订单后复核。');
|
||||||
data.requests.forEach(request => validators[i](request, id));
|
data.requests.forEach(request => validate(request, id));
|
||||||
return { ...entry, data };
|
return { ...identity, data };
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return { ...entry, error: err.message };
|
return { ...identity, error: messageOf(err) };
|
||||||
}
|
}
|
||||||
});
|
}
|
||||||
return { order: order.value, entries };
|
const entries = [
|
||||||
|
entry<ChangeRequest, ChangeData>(change, checks.validateOrderChangeRequest),
|
||||||
|
entry<OwnershipRequest, OwnershipData>(ownership, checks.validateOrderOwnershipRequest),
|
||||||
|
entry<CancellationRequest, CancellationData>(cancellation, checks.validateOrderCancellationRequest),
|
||||||
|
] as const;
|
||||||
|
return { order, entries };
|
||||||
}, [id, generation, state.user.id].join('/'));
|
}, [id, generation, state.user.id].join('/'));
|
||||||
const original = details.value?.order;
|
const original = details.value?.order;
|
||||||
const access = useOrderAccess({ client, state, id, watch: !!original, onLost });
|
const access = useOrderAccess({ client, state, id, watch: !!original, onLost });
|
||||||
@@ -109,7 +157,7 @@ export function OrderActionDialog({
|
|||||||
orderCancellationDetail: cancellation,
|
orderCancellationDetail: cancellation,
|
||||||
orderAfterSaleFormEntry: order && {
|
orderAfterSaleFormEntry: order && {
|
||||||
id,
|
id,
|
||||||
revision: order.revision,
|
revision: order!.revision,
|
||||||
user: state.user.id,
|
user: state.user.id,
|
||||||
forceApproval: ui.forceApproval,
|
forceApproval: ui.forceApproval,
|
||||||
},
|
},
|
||||||
@@ -131,7 +179,10 @@ export function OrderActionDialog({
|
|||||||
setExpenses([]);
|
setExpenses([]);
|
||||||
setUi({});
|
setUi({});
|
||||||
}
|
}
|
||||||
const loadAfter = useRead(() => client.api(base + '/after-sale'), form?.type === 'after' && id + '/' + generation);
|
const loadAfter = useRead(
|
||||||
|
() => client.api<OrderAfterSaleData>(base + '/after-sale'),
|
||||||
|
form?.type === 'after' && id + '/' + generation,
|
||||||
|
);
|
||||||
let panel,
|
let panel,
|
||||||
visibleError = error;
|
visibleError = error;
|
||||||
try {
|
try {
|
||||||
@@ -140,11 +191,11 @@ export function OrderActionDialog({
|
|||||||
else if (!loadAfter.value) panel = <p role="status">正在读取售后资料…</p>;
|
else if (!loadAfter.value) panel = <p role="status">正在读取售后资料…</p>;
|
||||||
else if (
|
else if (
|
||||||
loadAfter.value.orderId !== id ||
|
loadAfter.value.orderId !== id ||
|
||||||
loadAfter.value.revision !== order.revision ||
|
loadAfter.value.revision !== order!.revision ||
|
||||||
!loadAfter.value.eligible ||
|
!loadAfter.value.eligible ||
|
||||||
loadAfter.value.record ||
|
loadAfter.value.record ||
|
||||||
!views.orderAfterSalePocketKeys().length ||
|
!views.orderAfterSalePocketKeys().length ||
|
||||||
order.lines.some(
|
order!.lines.some(
|
||||||
l => l.unit !== 'g' || !l.costParts || l.costParts.material == null || l.costParts.labor == null,
|
l => l.unit !== 'g' || !l.costParts || l.costParts.material == null || l.costParts.labor == null,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
@@ -160,7 +211,7 @@ export function OrderActionDialog({
|
|||||||
</div>
|
</div>
|
||||||
)),
|
)),
|
||||||
},
|
},
|
||||||
}).orderAfterSaleFormHTML(order);
|
}).orderAfterSaleFormHTML(order!);
|
||||||
} else if (form?.type === 'action') panel = views.showAction(form.kind);
|
} else if (form?.type === 'action') panel = views.showAction(form.kind);
|
||||||
else if (form)
|
else if (form)
|
||||||
panel = {
|
panel = {
|
||||||
@@ -176,11 +227,12 @@ export function OrderActionDialog({
|
|||||||
reload(v => v + 1);
|
reload(v => v + 1);
|
||||||
refresh();
|
refresh();
|
||||||
}
|
}
|
||||||
async function onClick(event) {
|
async function onClick(event: MouseEvent<HTMLDivElement>) {
|
||||||
const target = event.target.closest('[data-action]');
|
if (!(event.target instanceof Element)) return;
|
||||||
|
const target = event.target.closest<HTMLButtonElement>('[data-action]');
|
||||||
if (!target) return;
|
if (!target) return;
|
||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
const { action, id: targetId } = target.dataset;
|
const { action = '', id: targetId = '' } = target.dataset;
|
||||||
try {
|
try {
|
||||||
if (action === 'close-dialog' || action === 'order-detail-prev' || action === 'order-detail-next') return;
|
if (action === 'close-dialog' || action === 'order-detail-prev' || action === 'order-detail-next') return;
|
||||||
if (action === 'print') {
|
if (action === 'print') {
|
||||||
@@ -201,7 +253,7 @@ export function OrderActionDialog({
|
|||||||
if (action.includes('close') || action === 'hide-action') return clearForm();
|
if (action.includes('close') || action === 'hide-action') return clearForm();
|
||||||
if (client.busy || client.pending()) throw new Error('请先恢复原操作。');
|
if (client.busy || client.pending()) throw new Error('请先恢复原操作。');
|
||||||
if (action === 'order-after-sale-preview') {
|
if (action === 'order-after-sale-preview') {
|
||||||
const node = target.form;
|
const node = target.form as DetailForm;
|
||||||
const input = views.orderAfterSaleInput(node);
|
const input = views.orderAfterSaleInput(node);
|
||||||
const version = ++current.current;
|
const version = ++current.current;
|
||||||
const signature = JSON.stringify(input);
|
const signature = JSON.stringify(input);
|
||||||
@@ -216,15 +268,18 @@ export function OrderActionDialog({
|
|||||||
}));
|
}));
|
||||||
let result;
|
let result;
|
||||||
try {
|
try {
|
||||||
result = await client.api(base + '/after-sale-preview', input);
|
result = await client.api<{ before: OrderRecord; after: OrderRecord; afterSale?: OrderAfterSale }>(
|
||||||
|
base + '/after-sale-preview',
|
||||||
|
input,
|
||||||
|
);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (current.current === version) throw err;
|
if (current.current === version) throw err;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (current.current !== version) return;
|
if (current.current !== version) return;
|
||||||
if (result.before?.id !== id || result.after?.id !== id || result.before.revision !== order.revision)
|
if (result.before?.id !== id || result.after?.id !== id || result.before.revision !== order!.revision)
|
||||||
throw new Error('售后预览与当前订单不一致,请重新读取。');
|
throw new Error('售后预览与当前订单不一致,请重新读取。');
|
||||||
const record = result.afterSale || result.after.orderAfterSale;
|
const record = result.afterSale || result.after.orderAfterSale!;
|
||||||
views.orderAfterSaleSummaryHTML(record, { preview: true });
|
views.orderAfterSaleSummaryHTML(record, { preview: true });
|
||||||
setUi(old => ({
|
setUi(old => ({
|
||||||
...old,
|
...old,
|
||||||
@@ -236,7 +291,8 @@ export function OrderActionDialog({
|
|||||||
}
|
}
|
||||||
if (action === 'order-after-sale-add-expense' || action === 'order-after-sale-remove-expense') {
|
if (action === 'order-after-sale-add-expense' || action === 'order-after-sale-remove-expense') {
|
||||||
current.current++;
|
current.current++;
|
||||||
if (target.form?.elements.verified) target.form.elements.verified.checked = false;
|
const form = target.form as DetailForm | null;
|
||||||
|
if (form?.elements.verified) form.elements.verified.checked = false;
|
||||||
setUi(v => ({
|
setUi(v => ({
|
||||||
...v,
|
...v,
|
||||||
preview: null,
|
preview: null,
|
||||||
@@ -244,7 +300,7 @@ export function OrderActionDialog({
|
|||||||
verified: false,
|
verified: false,
|
||||||
previewStatus: '资料已修改,请重新核对售后预览。',
|
previewStatus: '资料已修改,请重新核对售后预览。',
|
||||||
}));
|
}));
|
||||||
const key = target.closest('[data-expense-id]')?.dataset.expenseId;
|
const key = target.closest<HTMLElement>('[data-expense-id]')?.dataset.expenseId;
|
||||||
setExpenses(items =>
|
setExpenses(items =>
|
||||||
action.endsWith('add-expense') ? [...items, crypto.randomUUID()] : items.filter(x => x !== key),
|
action.endsWith('add-expense') ? [...items, crypto.randomUUID()] : items.filter(x => x !== key),
|
||||||
);
|
);
|
||||||
@@ -262,7 +318,7 @@ export function OrderActionDialog({
|
|||||||
const data = change?.data;
|
const data = change?.data;
|
||||||
if (!data || change.error) throw new Error('请重新读取订单并核对修改申请。');
|
if (!data || change.error) throw new Error('请重新读取订单并核对修改申请。');
|
||||||
const eligibility = data.actions?.[kind] || data;
|
const eligibility = data.actions?.[kind] || data;
|
||||||
if (!eligibility.eligible || data.pending || order.cancellationPending)
|
if (!eligibility.eligible || data.pending || order!.cancellationPending)
|
||||||
throw new Error(eligibility.reason || '本单暂不能提交变更申请,请重新读取。');
|
throw new Error(eligibility.reason || '本单暂不能提交变更申请,请重新读取。');
|
||||||
}
|
}
|
||||||
setUi({ action: kind, formKey: current.current });
|
setUi({ action: kind, formKey: current.current });
|
||||||
@@ -275,16 +331,22 @@ export function OrderActionDialog({
|
|||||||
preview: null,
|
preview: null,
|
||||||
previewLoading: false,
|
previewLoading: false,
|
||||||
verified: false,
|
verified: false,
|
||||||
stale: [403, 404, 409].includes(err.status),
|
stale: [403, 404, 409].includes(errorStatus(err)),
|
||||||
afterError: messageOf(err),
|
afterError: messageOf(err),
|
||||||
previewStatus: '预览未完成,请核对提示后重新预览。',
|
previewStatus: '预览未完成,请核对提示后重新预览。',
|
||||||
}));
|
}));
|
||||||
else setError(messageOf(err));
|
else setError(messageOf(err));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
function onChange(e) {
|
function onChange(e: FormEvent<HTMLDivElement>) {
|
||||||
const target = e.target,
|
const target = e.target;
|
||||||
node = target.form;
|
if (!(
|
||||||
|
target instanceof HTMLInputElement ||
|
||||||
|
target instanceof HTMLSelectElement ||
|
||||||
|
target instanceof HTMLTextAreaElement
|
||||||
|
))
|
||||||
|
return;
|
||||||
|
const node = target.form as DetailForm | null;
|
||||||
if (!node) return;
|
if (!node) return;
|
||||||
if (form?.type === 'action') {
|
if (form?.type === 'action') {
|
||||||
const values = readForm(node);
|
const values = readForm(node);
|
||||||
@@ -310,14 +372,14 @@ export function OrderActionDialog({
|
|||||||
}
|
}
|
||||||
if (form?.type !== 'after') return;
|
if (form?.type !== 'after') return;
|
||||||
if (target.name === 'verified') {
|
if (target.name === 'verified') {
|
||||||
setUi(old => ({ ...old, verified: target.checked }));
|
setUi(old => ({ ...old, verified: (target as HTMLInputElement).checked }));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
current.current++;
|
current.current++;
|
||||||
const data = readForm(node);
|
const data = readForm(node);
|
||||||
let cents = null;
|
let cents = null;
|
||||||
try {
|
try {
|
||||||
cents = order.netReceived - Calc.cents(data.refund_amount);
|
cents = order!.netReceived - Calc.cents(data.refund_amount);
|
||||||
} catch {
|
} catch {
|
||||||
/* 未填写时保留待填写提示。 */
|
/* 未填写时保留待填写提示。 */
|
||||||
}
|
}
|
||||||
@@ -325,8 +387,8 @@ export function OrderActionDialog({
|
|||||||
node.elements.refund_payer.value = views.orderAfterSaleAccountPayer(target.value);
|
node.elements.refund_payer.value = views.orderAfterSaleAccountPayer(target.value);
|
||||||
node.elements.verified.checked = false;
|
node.elements.verified.checked = false;
|
||||||
const lines = Array.from(node.querySelectorAll('[data-after-sale-line]'), row => ({
|
const lines = Array.from(node.querySelectorAll('[data-after-sale-line]'), row => ({
|
||||||
pocket: row.querySelector('[name=return_pocket]').value,
|
pocket: row.querySelector<HTMLSelectElement>('[name=return_pocket]')!.value,
|
||||||
disposition: row.querySelector('[name=return_disposition]').value,
|
disposition: row.querySelector<HTMLSelectElement>('[name=return_disposition]')!.value,
|
||||||
}));
|
}));
|
||||||
setUi(old => ({
|
setUi(old => ({
|
||||||
...old,
|
...old,
|
||||||
@@ -336,18 +398,19 @@ export function OrderActionDialog({
|
|||||||
verified: false,
|
verified: false,
|
||||||
date: data.date,
|
date: data.date,
|
||||||
previewStatus: '资料已修改,请重新核对售后预览。',
|
previewStatus: '资料已修改,请重新核对售后预览。',
|
||||||
reasonRequired: cents > 0,
|
reasonRequired: cents !== null && cents > 0,
|
||||||
retained: cents === null ? '待填写退款金额' : cents < 0 ? '退款超出净实收' : '¥' + (cents / 100).toFixed(2),
|
retained: cents === null ? '待填写退款金额' : cents < 0 ? '退款超出净实收' : '¥' + (cents / 100).toFixed(2),
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
async function submit(e) {
|
async function submit(e: FormEvent<HTMLDivElement>) {
|
||||||
stop(e);
|
stop(e);
|
||||||
const node = e.target,
|
if (!form || !(e.target instanceof HTMLFormElement)) return;
|
||||||
|
const node = e.target as DetailForm,
|
||||||
data = readForm(node),
|
data = readForm(node),
|
||||||
kind = node.dataset.kind;
|
kind = node.dataset.kind!;
|
||||||
let submittedDirect = false;
|
let submittedDirect = false;
|
||||||
let submittedKey;
|
let submittedKey: string | undefined;
|
||||||
const retryKey = e.nativeEvent.submitter?.dataset.retryKey;
|
const retryKey = ((e.nativeEvent as SubmitEvent).submitter as HTMLElement | null)?.dataset.retryKey;
|
||||||
try {
|
try {
|
||||||
if (client.busy) return;
|
if (client.busy) return;
|
||||||
if (retryKey) {
|
if (retryKey) {
|
||||||
@@ -363,15 +426,16 @@ export function OrderActionDialog({
|
|||||||
if (client.pending()) return;
|
if (client.pending()) return;
|
||||||
let url, payload;
|
let url, payload;
|
||||||
if (form.type === 'after') {
|
if (form.type === 'after') {
|
||||||
payload = views.orderAfterSaleInput(node);
|
const input = views.orderAfterSaleInput(node);
|
||||||
|
payload = input;
|
||||||
if (ui.stale || ui.previewLoading || ui.preview?.signature !== JSON.stringify(payload))
|
if (ui.stale || ui.previewLoading || ui.preview?.signature !== JSON.stringify(payload))
|
||||||
throw new Error('请先重新核对本次售后预览。');
|
throw new Error('请先重新核对本次售后预览。');
|
||||||
if (change?.data?.pending || order.cancellationPending || views.orderAfterSaleRecord(order))
|
if (change?.data?.pending || order!.cancellationPending || views.orderAfterSaleRecord(order))
|
||||||
throw new Error('本单已变动或有待复核申请,请重新读取。');
|
throw new Error('本单已变动或有待复核申请,请重新读取。');
|
||||||
if (!ui.verified) throw new Error('请核对售后预览,并勾选实物、实际退款和成本确认。');
|
if (!ui.verified) throw new Error('请核对售后预览,并勾选实物、实际退款和成本确认。');
|
||||||
const approve = views.orderAfterSaleApproval(payload.date);
|
const approve = views.orderAfterSaleApproval(payload.date);
|
||||||
submittedDirect = !approve;
|
submittedDirect = !approve;
|
||||||
if (approve) payload.action = 'return';
|
if (approve) payload = { ...input, action: 'return' };
|
||||||
url = base + (approve ? '/change' : '/return');
|
url = base + (approve ? '/change' : '/return');
|
||||||
} else if (form.type === 'action') {
|
} else if (form.type === 'action') {
|
||||||
payload = views.actionInput(node);
|
payload = views.actionInput(node);
|
||||||
@@ -382,7 +446,7 @@ export function OrderActionDialog({
|
|||||||
payload = {
|
payload = {
|
||||||
...payload,
|
...payload,
|
||||||
...(approve ? { action: kind } : {}),
|
...(approve ? { action: kind } : {}),
|
||||||
revision: order.revision,
|
revision: order!.revision,
|
||||||
verified: data.verified === 'on',
|
verified: data.verified === 'on',
|
||||||
reason: (data.change_reason || data.reason || '').trim(),
|
reason: (data.change_reason || data.reason || '').trim(),
|
||||||
};
|
};
|
||||||
@@ -393,32 +457,32 @@ export function OrderActionDialog({
|
|||||||
if (approve) url = base + '/change';
|
if (approve) url = base + '/change';
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
const info = { change, ownership, cancellation }[form.type].data,
|
const info = { change, ownership, cancellation }[form.type]!.data!,
|
||||||
req = info.pending;
|
req = info.pending;
|
||||||
if (kind === 'approve' || kind === 'reject') {
|
if (kind === 'approve' || kind === 'reject') {
|
||||||
if (!req || req.status !== 'pending' || !info.canApprove) throw new Error('请重新读取后复核。');
|
if (!req || req.status !== 'pending' || !info.canApprove) throw new Error('请重新读取后复核。');
|
||||||
if (
|
if (
|
||||||
kind === 'approve' &&
|
kind === 'approve' &&
|
||||||
(!req.canApprove || req.stale || req.order_revision !== order.revision || !data.verified)
|
(!req.canApprove || req.stale || req.order_revision !== order!.revision || !data.verified)
|
||||||
)
|
)
|
||||||
throw new Error('订单已有变动,请重新读取后复核。');
|
throw new Error('订单已有变动,请重新读取后复核。');
|
||||||
url = queues.find(([type]) => type === form.type)[1] + '/' + encodeURIComponent(req.id) + '/' + kind;
|
url = queues.find(([type]) => type === form.type)![1] + '/' + encodeURIComponent(req.id) + '/' + kind;
|
||||||
payload = {
|
payload = {
|
||||||
...(kind === 'approve' ? { revision: req.order_revision, verified: true } : {}),
|
...(kind === 'approve' ? { revision: req.order_revision, verified: true } : {}),
|
||||||
note: data.note.trim(),
|
note: data.note.trim(),
|
||||||
};
|
};
|
||||||
} else if (form.type === 'ownership') {
|
} else if (form.type === 'ownership') {
|
||||||
payload = { member: data.member, revision: order.revision, reason: data.reason.trim(), verified: true };
|
payload = { member: data.member, revision: order!.revision, reason: data.reason.trim(), verified: true };
|
||||||
url = base + '/ownership';
|
url = base + '/ownership';
|
||||||
} else {
|
} else {
|
||||||
payload = {
|
payload = {
|
||||||
revision: order.revision,
|
revision: order!.revision,
|
||||||
reason: data.reason.trim(),
|
reason: data.reason.trim(),
|
||||||
...(kind === 'direct' ? { date: info.directActionDate, verified: true } : {}),
|
...(kind === 'direct' ? { date: cancellation!.data!.directActionDate, verified: true } : {}),
|
||||||
};
|
};
|
||||||
url = base + (kind === 'direct' ? '/canceltoday' : '/cancellation');
|
url = base + (kind === 'direct' ? '/canceltoday' : '/cancellation');
|
||||||
}
|
}
|
||||||
if (data.legacyCountVerified) payload.legacyCountVerified = true;
|
if (data.legacyCountVerified) payload = { ...payload, legacyCountVerified: true };
|
||||||
}
|
}
|
||||||
const saving = client.mutate(url, payload);
|
const saving = client.mutate(url, payload);
|
||||||
submittedKey = client.pending()?.key;
|
submittedKey = client.pending()?.key;
|
||||||
@@ -428,8 +492,8 @@ export function OrderActionDialog({
|
|||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (await access.checkFailure(err)) return;
|
if (await access.checkFailure(err)) return;
|
||||||
if (form.type === 'after') {
|
if (form.type === 'after') {
|
||||||
const forceApproval = err.status === 403 && submittedDirect && !client.pending();
|
const forceApproval = errorStatus(err) === 403 && submittedDirect && !client.pending();
|
||||||
const stale = !forceApproval && [403, 404, 409].includes(err.status);
|
const stale = !forceApproval && [403, 404, 409].includes(errorStatus(err));
|
||||||
if (forceApproval || stale) node.elements.verified.checked = false;
|
if (forceApproval || stale) node.elements.verified.checked = false;
|
||||||
setUi(old => ({
|
setUi(old => ({
|
||||||
...old,
|
...old,
|
||||||
@@ -443,10 +507,10 @@ export function OrderActionDialog({
|
|||||||
} else if (
|
} else if (
|
||||||
form.type === 'action' &&
|
form.type === 'action' &&
|
||||||
views.orderActionUsesChangeForm(kind) &&
|
views.orderActionUsesChangeForm(kind) &&
|
||||||
([403, 404, 409].includes(err.status) || (submittedKey && submittedKey === client.pending()?.key))
|
([403, 404, 409].includes(errorStatus(err)) || (submittedKey && submittedKey === client.pending()?.key))
|
||||||
) {
|
) {
|
||||||
const forceApproval = err.status === 403 && submittedDirect && !client.pending();
|
const forceApproval = errorStatus(err) === 403 && submittedDirect && !client.pending();
|
||||||
const rejected = [403, 404, 409].includes(err.status);
|
const rejected = [403, 404, 409].includes(errorStatus(err));
|
||||||
if (rejected && node.elements.verified) node.elements.verified.checked = false;
|
if (rejected && node.elements.verified) node.elements.verified.checked = false;
|
||||||
setUi(old => ({
|
setUi(old => ({
|
||||||
...old,
|
...old,
|
||||||
@@ -487,281 +551,4 @@ export function OrderActionDialog({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function IndependentAfterSale({
|
export { IndependentAfterSale } from './IndependentAfterSale';
|
||||||
client,
|
|
||||||
state,
|
|
||||||
session,
|
|
||||||
sale,
|
|
||||||
refreshState,
|
|
||||||
refreshBook,
|
|
||||||
openList,
|
|
||||||
close,
|
|
||||||
saved,
|
|
||||||
}) {
|
|
||||||
const { message } = AntApp.useApp();
|
|
||||||
const [review, setReview] = useState(sale.action === 'after-sale-change-open' ? sale.id : '');
|
|
||||||
const [kind, setKind] = useState('');
|
|
||||||
const [error, setError] = useState('');
|
|
||||||
const [invalid, setInvalid] = useState(false);
|
|
||||||
const [date, setDate] = useState(null);
|
|
||||||
const [savedRequest, setSavedRequest] = useState(null);
|
|
||||||
const [receipt, setReceipt] = useState('');
|
|
||||||
const [generation, reload] = useState(0);
|
|
||||||
const version = useRef(0);
|
|
||||||
useEffect(
|
|
||||||
() => () => {
|
|
||||||
version.current++;
|
|
||||||
},
|
|
||||||
[],
|
|
||||||
);
|
|
||||||
const id = review || sale.id;
|
|
||||||
const path = review
|
|
||||||
? '/api/after-sales/changes/' + encodeURIComponent(review)
|
|
||||||
: sale.id
|
|
||||||
? '/api/after-sales/' + encodeURIComponent(sale.id)
|
|
||||||
: '';
|
|
||||||
const views = orderViews({ state, session });
|
|
||||||
const read = useRead(
|
|
||||||
async () => {
|
|
||||||
if (!review) await refreshState();
|
|
||||||
const data = await client.api(path);
|
|
||||||
if (!review) return views.validateAfterSaleDetail(data, sale.id);
|
|
||||||
const request = views.validateAfterSaleRequest(data);
|
|
||||||
if (request.id !== review) throw new Error('申请编号不一致,请重新读取。');
|
|
||||||
return request;
|
|
||||||
},
|
|
||||||
path && state.user.id + '/' + path + '/' + generation,
|
|
||||||
);
|
|
||||||
const detail = read.value;
|
|
||||||
const request = review && (savedRequest || detail);
|
|
||||||
const approval =
|
|
||||||
!!detail?.permissions &&
|
|
||||||
(detail.permissions.requiresApproval ||
|
|
||||||
!detail.permissions.canDirectEdit ||
|
|
||||||
(state.user.role !== 'owner' &&
|
|
||||||
(detail.record.date !== state.today || (date ?? detail.record.date) !== state.today)));
|
|
||||||
const blocked = !!(invalid || client.busy || client.pending());
|
|
||||||
|
|
||||||
function reset() {
|
|
||||||
version.current++;
|
|
||||||
setKind('');
|
|
||||||
setError('');
|
|
||||||
setDate(null);
|
|
||||||
setSavedRequest(null);
|
|
||||||
setReceipt('');
|
|
||||||
setInvalid(false);
|
|
||||||
reload(value => value + 1);
|
|
||||||
}
|
|
||||||
function dismiss() {
|
|
||||||
version.current++;
|
|
||||||
close();
|
|
||||||
}
|
|
||||||
function fail(err) {
|
|
||||||
const text = messageOf(err).replace('不要重新开单', id ? '不要重复提交售后修改' : '不要重复新增售后');
|
|
||||||
if ([403, 404, 409].includes(err.status) && id) setInvalid(true);
|
|
||||||
setError(text);
|
|
||||||
message.error(text);
|
|
||||||
}
|
|
||||||
async function finish(url, input, result, at) {
|
|
||||||
if (client.user !== state.user.id) return;
|
|
||||||
const active = () => version.current === at && client.user === state.user.id;
|
|
||||||
if (url === '/api/after-sales') {
|
|
||||||
if (active()) saved(input.date);
|
|
||||||
else refreshBook();
|
|
||||||
message.success('售后已保存,已计入 ' + input.date + ' 的费用与利润');
|
|
||||||
await refreshState();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const update = url.endsWith('/update');
|
|
||||||
const applied = update && result.applied === true;
|
|
||||||
const text = update
|
|
||||||
? applied
|
|
||||||
? '售后修改已保存'
|
|
||||||
: '售后修改申请已提交,待店主审批'
|
|
||||||
: url.endsWith('/approve')
|
|
||||||
? '已同意售后修改'
|
|
||||||
: '已驳回售后修改申请';
|
|
||||||
if (active()) {
|
|
||||||
setKind('');
|
|
||||||
setError('');
|
|
||||||
setReceipt(text);
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
await refreshState();
|
|
||||||
if (client.user !== state.user.id) return;
|
|
||||||
if (active() && applied) saved(result.record?.record?.date || input.date);
|
|
||||||
else {
|
|
||||||
refreshBook();
|
|
||||||
if (active() && update) reset();
|
|
||||||
if (active() && !update) {
|
|
||||||
const finalRequest = views.validateAfterSaleRequest(result);
|
|
||||||
if (finalRequest.id !== review) throw new Error('申请编号不一致,请重新读取。');
|
|
||||||
setSavedRequest(finalRequest);
|
|
||||||
setReceipt('');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
message.success(text);
|
|
||||||
} catch (err) {
|
|
||||||
if (active()) setError('结果已保存,刷新失败:' + messageOf(err) + '。请重新读取查看结果。');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
async function handle(event) {
|
|
||||||
const button = event.target.closest('[data-action]');
|
|
||||||
if (!button) return;
|
|
||||||
event.stopPropagation();
|
|
||||||
const { action, id: requestedId, kind: choice } = button.dataset;
|
|
||||||
if (action === 'close-after-sale' || action === 'after-sale-changes-close') return dismiss();
|
|
||||||
if (action === 'after-sale-changes-reload') {
|
|
||||||
version.current++;
|
|
||||||
openList();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (action === 'after-sale-change-open' || action === 'after-sale-edit') {
|
|
||||||
if (client.busy) return;
|
|
||||||
if (action === 'after-sale-change-open') setReview(requestedId);
|
|
||||||
reset();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (action === 'after-sale-review-decision') {
|
|
||||||
if (invalid || request?.status !== 'pending') return fail(new Error('请重新读取申请后再复核。'));
|
|
||||||
setKind(choice);
|
|
||||||
setError('');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (action === 'after-sale-review-cancel') {
|
|
||||||
setKind('');
|
|
||||||
setError('');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (action === 'retry') {
|
|
||||||
const at = version.current;
|
|
||||||
try {
|
|
||||||
const restored = await client.retryPending();
|
|
||||||
if (restored) await finish(restored.job.url, restored.job.data, restored.result, at);
|
|
||||||
} catch (err) {
|
|
||||||
if (at === version.current) fail(err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
async function submit(event) {
|
|
||||||
stop(event);
|
|
||||||
const node = event.target;
|
|
||||||
const values = readForm(node);
|
|
||||||
const at = version.current;
|
|
||||||
try {
|
|
||||||
let url, input;
|
|
||||||
if (review) {
|
|
||||||
if (state.user.role !== 'owner') throw new Error('请使用店主账号复核。');
|
|
||||||
if (blocked || request?.status !== 'pending' || node.dataset.id !== request.id || node.dataset.kind !== kind)
|
|
||||||
throw new Error('请重新读取申请后再复核。');
|
|
||||||
const note = values.note.trim();
|
|
||||||
if (kind === 'approve' && (!request.canApprove || request.stale))
|
|
||||||
throw new Error('原记录已有变动,请重新读取并核对。');
|
|
||||||
if (kind === 'reject' && !note) throw new Error('请填写驳回意见。');
|
|
||||||
if (note.length > 200) throw new Error('复核意见最多200字。');
|
|
||||||
if (kind === 'approve' && !values.verified) throw new Error('请核对修改前后内容并勾选确认。');
|
|
||||||
url = path + '/' + kind;
|
|
||||||
input = { revision: request.revision, note, ...(kind === 'approve' ? { verified: true } : {}) };
|
|
||||||
} else {
|
|
||||||
if (id && (blocked || !detail.permissions.canEdit || detail.pending || node.dataset.id !== id))
|
|
||||||
throw new Error('请重新读取售后记录后再修改。');
|
|
||||||
input = {
|
|
||||||
date: values.date,
|
|
||||||
project: values.project.trim(),
|
|
||||||
customer: values.customer.trim(),
|
|
||||||
amount: values.amount.trim(),
|
|
||||||
payer: values.payer,
|
|
||||||
};
|
|
||||||
if (!views.validOrderDate(input.date) || input.date > state.today)
|
|
||||||
throw new Error('售后日期请选择今天或之前的有效日期。');
|
|
||||||
if (!input.project || input.project.length > 100) throw new Error('售后项目请填写1~100字。');
|
|
||||||
if (!input.customer || input.customer.length > 60) throw new Error('客户请填写1~60字的称呼或代号。');
|
|
||||||
if (!views.teamMemberKeys().includes(input.payer)) throw new Error('请选择这笔售后由谁支付。');
|
|
||||||
Calc.cents(input.amount, '售后金额');
|
|
||||||
if (id) {
|
|
||||||
const reason = values.reason.trim();
|
|
||||||
if (reason.length > 200) throw new Error('修改说明最多200字。');
|
|
||||||
url = path + '/update';
|
|
||||||
input = { revision: detail.revision, ...input, reason };
|
|
||||||
} else {
|
|
||||||
url = '/api/after-sales';
|
|
||||||
if (views.teamMode()) input.member = values.member || views.currentMember();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
setError('');
|
|
||||||
const result = await client.mutate(url, input);
|
|
||||||
await finish(url, input, result, at);
|
|
||||||
} catch (err) {
|
|
||||||
if (at !== version.current) return;
|
|
||||||
if ([403, 404, 409].includes(err.status) && node.elements.verified) node.elements.verified.checked = false;
|
|
||||||
fail(err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const reread = (
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
disabled={client.busy}
|
|
||||||
data-action={review ? 'after-sale-change-open' : 'after-sale-edit'}
|
|
||||||
data-id={id}
|
|
||||||
>
|
|
||||||
{review ? '重新读取申请并复核' : '重新读取售后'}
|
|
||||||
</button>
|
|
||||||
);
|
|
||||||
const feedback = error && (
|
|
||||||
<div className="error" role="alert">
|
|
||||||
{error}{' '}
|
|
||||||
{id &&
|
|
||||||
(client.pending() ? (
|
|
||||||
<button type="button" data-action="retry" disabled={client.busy}>
|
|
||||||
恢复原操作
|
|
||||||
</button>
|
|
||||||
) : (
|
|
||||||
reread
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
const ui = { approval, blocked, busy: client.busy, feedback };
|
|
||||||
const panel = orderViews({ state, session, ui });
|
|
||||||
let content;
|
|
||||||
if (receipt || (path && !detail)) {
|
|
||||||
content = (
|
|
||||||
<>
|
|
||||||
<button
|
|
||||||
className="dialog-close"
|
|
||||||
data-action={review ? 'after-sale-changes-close' : 'close-after-sale'}
|
|
||||||
aria-label={review ? '关闭售后修改复核' : '关闭售后记录'}
|
|
||||||
>
|
|
||||||
×
|
|
||||||
</button>
|
|
||||||
<h2>{receipt || (review ? '售后修改复核' : '修改售后')}</h2>
|
|
||||||
{read.error || error ? (
|
|
||||||
<div className="error" role="alert">
|
|
||||||
{read.error || error} {reread}
|
|
||||||
{review && <button data-action="after-sale-changes-reload">返回申请列表</button>}
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<p role="status">{receipt ? '正在刷新…' : review ? '正在读取申请…' : '正在读取售后记录…'}</p>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
} else if (review) content = panel.independentReview(request, kind);
|
|
||||||
else content = id ? panel.editIndependentSale(detail) : panel.newIndependentSale();
|
|
||||||
return (
|
|
||||||
<Dialog
|
|
||||||
id={review ? 'after-sale-changes-dialog' : 'after-sale-dialog'}
|
|
||||||
ownClose
|
|
||||||
label={review ? '售后修改复核' : '售后记录'}
|
|
||||||
close={dismiss}
|
|
||||||
>
|
|
||||||
<div
|
|
||||||
onClick={handle}
|
|
||||||
onSubmit={submit}
|
|
||||||
onChange={event => {
|
|
||||||
if (event.target.name === 'date') setDate(event.target.value);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{content}
|
|
||||||
</div>
|
|
||||||
</Dialog>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
+124
-37
@@ -1,21 +1,66 @@
|
|||||||
import { useOrderAccess, ownershipNoticeKey } from './useOrderAccess';
|
import { useOrderAccess, ownershipNoticeKey } from './useOrderAccess';
|
||||||
import { useCallback, useEffect, useEffectEvent, useRef, useState } from 'react';
|
import { useCallback, useEffect, useEffectEvent, useRef, useState } from 'react';
|
||||||
|
import type { ReactNode, FormEvent, ComponentType } from 'react';
|
||||||
|
import type { LedgerClient } from '../../lib/api';
|
||||||
|
import type {
|
||||||
|
EditEntry,
|
||||||
|
EditInputs,
|
||||||
|
EditResponse,
|
||||||
|
EditPayload,
|
||||||
|
LockEditorProps,
|
||||||
|
SaveDraft,
|
||||||
|
SaveOrder,
|
||||||
|
} from './editTypes';
|
||||||
|
import type { LedgerState, OrderForm, SessionInfo } from '../../shared';
|
||||||
import { Model } from '../../shared';
|
import { Model } from '../../shared';
|
||||||
import { navigate, searchParam } from '../../lib/router';
|
import { navigate, searchParam } from '../../lib/router';
|
||||||
import { useOrderForm } from '../CreateOrder/useOrderForm';
|
import { useOrderForm } from '../CreateOrder/useOrderForm';
|
||||||
import { EditLine, EditFees, Input, Choice } from './EditFields';
|
import { EditLine, EditFees, Input, Choice } from './EditFields';
|
||||||
import { useRead } from './OrdersPage';
|
import { isRecord, errorMessage, errorStatus } from './readOrder';
|
||||||
|
import { useRead } from './orderReads';
|
||||||
|
|
||||||
function storedDraft(key, id) {
|
interface SavedEdit {
|
||||||
let saved;
|
id: string;
|
||||||
|
revision: number;
|
||||||
|
inputs: EditInputs;
|
||||||
|
reason?: string;
|
||||||
|
verified?: boolean;
|
||||||
|
}
|
||||||
|
type DraftMode = 'open' | 'reset' | 'keep' | 'review';
|
||||||
|
interface PageProps {
|
||||||
|
client: LedgerClient;
|
||||||
|
state: LedgerState;
|
||||||
|
session: SessionInfo;
|
||||||
|
refreshState: () => Promise<LedgerState>;
|
||||||
|
registerLeaveGuard: (check: () => boolean) => () => void;
|
||||||
|
LockEditor: ComponentType<LockEditorProps>;
|
||||||
|
}
|
||||||
|
function storedDraft(key: string, id: string): SavedEdit | null {
|
||||||
|
let saved: unknown;
|
||||||
try {
|
try {
|
||||||
saved = JSON.parse(localStorage.getItem(key));
|
saved = JSON.parse(localStorage.getItem(key) || 'null');
|
||||||
} catch {
|
} catch {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
return saved?.id === id && Number.isSafeInteger(saved.revision) && Array.isArray(saved.inputs?.lines) ? saved : null;
|
if (
|
||||||
|
!isRecord(saved) ||
|
||||||
|
saved.id !== id ||
|
||||||
|
typeof saved.revision !== 'number' ||
|
||||||
|
!Number.isSafeInteger(saved.revision) ||
|
||||||
|
!isRecord(saved.inputs) ||
|
||||||
|
!Array.isArray(saved.inputs.lines)
|
||||||
|
)
|
||||||
|
return null;
|
||||||
|
// Older local drafts can omit item metadata. The form loads its normal defaults when restoring those drafts.
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
revision: saved.revision,
|
||||||
|
inputs: saved.inputs as EditInputs,
|
||||||
|
...(typeof saved.reason === 'string' ? { reason: saved.reason } : {}),
|
||||||
|
verified: saved.verified === true,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
function makeEntry(result, id, saved, state) {
|
function makeEntry(result: EditResponse, id: string, saved: SavedEdit | null, state: LedgerState): EditEntry {
|
||||||
if (result.eligible !== true) throw new Error(result.reason || '这张订单暂不能修改,请重新读取订单后核对。');
|
if (result.eligible !== true) throw new Error(result.reason || '这张订单暂不能修改,请重新读取订单后核对。');
|
||||||
if (
|
if (
|
||||||
result.order?.id !== id ||
|
result.order?.id !== id ||
|
||||||
@@ -42,13 +87,16 @@ function makeEntry(result, id, saved, state) {
|
|||||||
for (const [index, line] of lines.entries()) {
|
for (const [index, line] of lines.entries()) {
|
||||||
const meta = metas[index],
|
const meta = metas[index],
|
||||||
lineId = meta?.lineId || meta?.id;
|
lineId = meta?.lineId || meta?.id;
|
||||||
const material = line.price_lock_material || (lines.length === 1 && result.inputs.price_lock_material);
|
const material = line.price_lock_material || (lines.length === 1 ? result.inputs.price_lock_material : undefined);
|
||||||
const extra = line.price_lock_extra_material || (lines.length === 1 && result.inputs.price_lock_extra_material);
|
const extra =
|
||||||
|
line.price_lock_extra_material || (lines.length === 1 ? result.inputs.price_lock_extra_material : undefined);
|
||||||
if (
|
if (
|
||||||
!['pool', 'manual'].includes(meta?.materialSource) ||
|
!meta ||
|
||||||
|
!['pool', 'manual'].includes(meta.materialSource) ||
|
||||||
!Number.isSafeInteger(meta.extraMg) ||
|
!Number.isSafeInteger(meta.extraMg) ||
|
||||||
meta.extraMg < 0 ||
|
meta.extraMg < 0 ||
|
||||||
!['pool', 'manual'].includes(material?.source) ||
|
!material?.source ||
|
||||||
|
!['pool', 'manual'].includes(material.source) ||
|
||||||
(meta.extraMg > 0 && !extra) ||
|
(meta.extraMg > 0 && !extra) ||
|
||||||
(lines.length > 1 && (!line.lineId || line.lineId !== lineId || seen.has(lineId)))
|
(lines.length > 1 && (!line.lineId || line.lineId !== lineId || seen.has(lineId)))
|
||||||
)
|
)
|
||||||
@@ -89,7 +137,15 @@ function makeEntry(result, id, saved, state) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function ConflictPanel({ entry, read, disabled }) {
|
function ConflictPanel({
|
||||||
|
entry,
|
||||||
|
read,
|
||||||
|
disabled,
|
||||||
|
}: {
|
||||||
|
entry: EditEntry;
|
||||||
|
read: (mode: DraftMode) => void;
|
||||||
|
disabled: boolean;
|
||||||
|
}) {
|
||||||
const order = entry.latest?.order;
|
const order = entry.latest?.order;
|
||||||
return (
|
return (
|
||||||
<section className="panel" id="order-edit-conflict" role="status">
|
<section className="panel" id="order-edit-conflict" role="status">
|
||||||
@@ -147,18 +203,18 @@ function ConflictPanel({ entry, read, disabled }) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function OrderEditPage({ client, state, session, refreshState, registerLeaveGuard, LockEditor }) {
|
export function OrderEditPage({ client, state, session, refreshState, registerLeaveGuard, LockEditor }: PageProps) {
|
||||||
const activeKey = 'mm-order-edit-active-' + state.user.id;
|
const activeKey = 'mm-order-edit-active-' + state.user.id;
|
||||||
const id = searchParam('order') || searchParam('id') || localStorage.getItem(activeKey) || '';
|
const id = searchParam('order') || searchParam('id') || localStorage.getItem(activeKey) || '';
|
||||||
const key = 'mm-order-edit-' + state.user.id + '-' + id;
|
const key = 'mm-order-edit-' + state.user.id + '-' + id;
|
||||||
const [entry, setEntry] = useState(null),
|
const [entry, setEntry] = useState<EditEntry | null>(null),
|
||||||
[epoch, reset] = useState(0),
|
[epoch, reset] = useState(0),
|
||||||
[error, setError] = useState(''),
|
[error, setError] = useState(''),
|
||||||
[success, setSuccess] = useState(false),
|
[success, setSuccess] = useState(false),
|
||||||
[reading, setReading] = useState(false);
|
[reading, setReading] = useState(false);
|
||||||
const live = useRef(false),
|
const live = useRef(false),
|
||||||
generation = useRef(0);
|
generation = useRef(0);
|
||||||
const onDraft = useCallback(
|
const onDraft = useCallback<SaveDraft>(
|
||||||
(inputs, reason, verified) => {
|
(inputs, reason, verified) => {
|
||||||
if (!live.current || client.user !== state.user.id) return;
|
if (!live.current || client.user !== state.user.id) return;
|
||||||
localStorage.setItem(key, JSON.stringify({ id, revision: inputs.revision, inputs, reason, verified }));
|
localStorage.setItem(key, JSON.stringify({ id, revision: inputs.revision, inputs, reason, verified }));
|
||||||
@@ -166,7 +222,7 @@ export function OrderEditPage({ client, state, session, refreshState, registerLe
|
|||||||
},
|
},
|
||||||
[id, key, activeKey, client, state.user.id],
|
[id, key, activeKey, client, state.user.id],
|
||||||
);
|
);
|
||||||
const lost = message => {
|
const lost = (message: string) => {
|
||||||
live.current = false;
|
live.current = false;
|
||||||
sessionStorage.setItem(ownershipNoticeKey(state.user.id), message);
|
sessionStorage.setItem(ownershipNoticeKey(state.user.id), message);
|
||||||
navigate('orders', { replace: true, fromPage: true });
|
navigate('orders', { replace: true, fromPage: true });
|
||||||
@@ -177,13 +233,13 @@ export function OrderEditPage({ client, state, session, refreshState, registerLe
|
|||||||
};
|
};
|
||||||
const { checkFailure } = useOrderAccess({ client, state, id, watch: !!entry && !reading, onLost: lost });
|
const { checkFailure } = useOrderAccess({ client, state, id, watch: !!entry && !reading, onLost: lost });
|
||||||
const active = () => live.current && client.user === state.user.id;
|
const active = () => live.current && client.user === state.user.id;
|
||||||
async function read(mode = 'open') {
|
async function read(mode: DraftMode = 'open') {
|
||||||
if (!id || (mode !== 'open' && (client.busy || client.pending() || reading))) return;
|
if (!id || (mode !== 'open' && (client.busy || client.pending() || reading))) return;
|
||||||
if (mode === 'reset' && !window.confirm('改用当前已保存的订单内容?这张订单尚未保存的修改草稿将被替换。')) return;
|
if (mode === 'reset' && !window.confirm('改用当前已保存的订单内容?这张订单尚未保存的修改草稿将被替换。')) return;
|
||||||
const request = ++generation.current;
|
const request = ++generation.current;
|
||||||
setReading(true);
|
setReading(true);
|
||||||
try {
|
try {
|
||||||
const result = await client.api('/api/orders/' + encodeURIComponent(id) + '/edit');
|
const result = await client.api<EditResponse>('/api/orders/' + encodeURIComponent(id) + '/edit');
|
||||||
if (!active() || request !== generation.current) return;
|
if (!active() || request !== generation.current) return;
|
||||||
let draft = storedDraft(key, id);
|
let draft = storedDraft(key, id);
|
||||||
if (mode === 'reset') draft = null;
|
if (mode === 'reset') draft = null;
|
||||||
@@ -195,7 +251,7 @@ export function OrderEditPage({ client, state, session, refreshState, registerLe
|
|||||||
inputs: { ...draft.inputs, revision: result.revision },
|
inputs: { ...draft.inputs, revision: result.revision },
|
||||||
};
|
};
|
||||||
const fresh = makeEntry(result, id, draft, state);
|
const fresh = makeEntry(result, id, draft, state);
|
||||||
if (mode === 'review' || (mode === 'keep' && result.revision !== entry.latest?.revision)) {
|
if (mode === 'review' || (mode === 'keep' && result.revision !== entry?.latest?.revision)) {
|
||||||
fresh.conflicted = true;
|
fresh.conflicted = true;
|
||||||
fresh.verified = false;
|
fresh.verified = false;
|
||||||
}
|
}
|
||||||
@@ -205,23 +261,32 @@ export function OrderEditPage({ client, state, session, refreshState, registerLe
|
|||||||
reset(n => n + 1);
|
reset(n => n + 1);
|
||||||
setError('');
|
setError('');
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (active() && request === generation.current && !(await checkFailure(err)) && active()) setError(err.message);
|
if (active() && request === generation.current && !(await checkFailure(err)) && active())
|
||||||
|
setError(err instanceof Error ? err.message : String(err));
|
||||||
} finally {
|
} finally {
|
||||||
if (active() && request === generation.current) setReading(false);
|
if (active() && request === generation.current) setReading(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const firstRead = useEffectEvent(() => read());
|
const firstRead = useEffectEvent(() => read());
|
||||||
|
const cancelRead = useEffectEvent(() => {
|
||||||
|
live.current = false;
|
||||||
|
generation.current++;
|
||||||
|
});
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
let disposed = false;
|
||||||
live.current = true;
|
live.current = true;
|
||||||
void firstRead();
|
void Promise.resolve().then(() => {
|
||||||
|
if (!disposed) return firstRead();
|
||||||
|
});
|
||||||
return () => {
|
return () => {
|
||||||
live.current = false;
|
disposed = true;
|
||||||
generation.current++;
|
cancelRead();
|
||||||
if (localStorage.getItem(activeKey) === id) localStorage.removeItem(activeKey);
|
if (localStorage.getItem(activeKey) === id) localStorage.removeItem(activeKey);
|
||||||
};
|
};
|
||||||
}, [id, activeKey]);
|
}, [id, activeKey]);
|
||||||
const go = () => navigate('orders', { search: '?order=' + encodeURIComponent(id) });
|
const go = () => navigate('orders', { search: '?order=' + encodeURIComponent(id) });
|
||||||
async function save(inputs, reason, verified, approval) {
|
async function save(inputs: EditPayload, reason: string, verified: boolean, approval: boolean) {
|
||||||
|
if (!entry) return;
|
||||||
try {
|
try {
|
||||||
if (entry.conflicted) throw new Error('订单已有新记录,请先读取最新订单并核对,填写内容已经保留。');
|
if (entry.conflicted) throw new Error('订单已有新记录,请先读取最新订单并核对,填写内容已经保留。');
|
||||||
if (!reason.trim() || reason.trim().length > 200) throw new Error('请填写1~200字的修改原因。');
|
if (!reason.trim() || reason.trim().length > 200) throw new Error('请填写1~200字的修改原因。');
|
||||||
@@ -234,9 +299,9 @@ export function OrderEditPage({ client, state, session, refreshState, registerLe
|
|||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (!active() || (await checkFailure(err)) || !active()) return;
|
if (!active() || (await checkFailure(err)) || !active()) return;
|
||||||
let message = err.message.replace('不要重新开单', '不要重复保存修改');
|
let message = errorMessage(err).replace('不要重新开单', '不要重复保存修改');
|
||||||
const forceApproval = err.status === 403 && session.user.role === 'assistant';
|
const forceApproval = errorStatus(err) === 403 && state.user.role === 'assistant';
|
||||||
if (forceApproval || err.status === 409) {
|
if (forceApproval || errorStatus(err) === 409) {
|
||||||
const saved = storedDraft(key, id);
|
const saved = storedDraft(key, id);
|
||||||
const next = {
|
const next = {
|
||||||
...entry,
|
...entry,
|
||||||
@@ -244,7 +309,7 @@ export function OrderEditPage({ client, state, session, refreshState, registerLe
|
|||||||
reason: saved?.reason ?? reason,
|
reason: saved?.reason ?? reason,
|
||||||
verified: false,
|
verified: false,
|
||||||
sameDayDirectEdit: forceApproval ? false : entry.sameDayDirectEdit,
|
sameDayDirectEdit: forceApproval ? false : entry.sameDayDirectEdit,
|
||||||
conflicted: err.status === 409,
|
conflicted: errorStatus(err) === 409,
|
||||||
latest: null,
|
latest: null,
|
||||||
};
|
};
|
||||||
if (forceApproval) message += '。填写内容已保留,请重新核对并勾选后提交修改申请。';
|
if (forceApproval) message += '。填写内容已保留,请重新核对并勾选后提交修改申请。';
|
||||||
@@ -262,7 +327,7 @@ export function OrderEditPage({ client, state, session, refreshState, registerLe
|
|||||||
if (approval) navigate('orders', { search: '?order=' + encodeURIComponent(id), fromPage: true });
|
if (approval) navigate('orders', { search: '?order=' + encodeURIComponent(id), fromPage: true });
|
||||||
else {
|
else {
|
||||||
setSuccess(true);
|
setSuccess(true);
|
||||||
const date = inputs.date || entry.order.date;
|
const date = ('date' in inputs && inputs.date) || entry.order.date;
|
||||||
const bookKey = 'mm-order-book-' + state.user.id;
|
const bookKey = 'mm-order-book-' + state.user.id;
|
||||||
let before = {};
|
let before = {};
|
||||||
try {
|
try {
|
||||||
@@ -275,7 +340,7 @@ export function OrderEditPage({ client, state, session, refreshState, registerLe
|
|||||||
try {
|
try {
|
||||||
await refreshState();
|
await refreshState();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError('修改已保存,最新订单暂未读到。' + err.message);
|
setError('修改已保存,最新订单暂未读到。' + (err instanceof Error ? err.message : String(err)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (success)
|
if (success)
|
||||||
@@ -327,7 +392,7 @@ export function OrderEditPage({ client, state, session, refreshState, registerLe
|
|||||||
client,
|
client,
|
||||||
state,
|
state,
|
||||||
session,
|
session,
|
||||||
entry,
|
entry: { ...entry, priceLock: entry.priceLock },
|
||||||
serverFeedback,
|
serverFeedback,
|
||||||
onDraft,
|
onDraft,
|
||||||
onSave: save,
|
onSave: save,
|
||||||
@@ -347,7 +412,27 @@ export function OrderEditPage({ client, state, session, refreshState, registerLe
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function EditForm({ client, state, session, entry, serverFeedback, onDraft, save, go, blocked }) {
|
function EditForm({
|
||||||
|
client,
|
||||||
|
state,
|
||||||
|
session,
|
||||||
|
entry,
|
||||||
|
serverFeedback,
|
||||||
|
onDraft,
|
||||||
|
save,
|
||||||
|
go,
|
||||||
|
blocked,
|
||||||
|
}: {
|
||||||
|
client: LedgerClient;
|
||||||
|
state: LedgerState;
|
||||||
|
session: SessionInfo;
|
||||||
|
entry: EditEntry;
|
||||||
|
serverFeedback: ReactNode;
|
||||||
|
onDraft: SaveDraft;
|
||||||
|
save: SaveOrder;
|
||||||
|
go: () => void;
|
||||||
|
blocked: boolean;
|
||||||
|
}) {
|
||||||
const { store, update, ctx, loadPools, poolError } = useOrderForm({
|
const { store, update, ctx, loadPools, poolError } = useOrderForm({
|
||||||
client,
|
client,
|
||||||
state,
|
state,
|
||||||
@@ -360,9 +445,9 @@ function EditForm({ client, state, session, entry, serverFeedback, onDraft, save
|
|||||||
const [reason, setReason] = useState(entry.reason),
|
const [reason, setReason] = useState(entry.reason),
|
||||||
[verified, setVerified] = useState(entry.verified),
|
[verified, setVerified] = useState(entry.verified),
|
||||||
[error, setError] = useState('');
|
[error, setError] = useState('');
|
||||||
const tags = useRead(() => client.api('/api/order-note-tags'), state.user.id);
|
const tags = useRead(() => client.api<{ tags: string[] }>('/api/order-note-tags'), state.user.id);
|
||||||
const set = key => value => change(f => ({ ...f, [key]: value }));
|
const set = (key: keyof OrderForm) => (value: string) => change(f => ({ ...f, [key]: value }));
|
||||||
const change = fn => {
|
const change = (fn: (form: OrderForm) => OrderForm) => {
|
||||||
setVerified(false);
|
setVerified(false);
|
||||||
update(fn);
|
update(fn);
|
||||||
};
|
};
|
||||||
@@ -375,7 +460,7 @@ function EditForm({ client, state, session, entry, serverFeedback, onDraft, save
|
|||||||
!entry.directEditDate ||
|
!entry.directEditDate ||
|
||||||
entry.order.date !== entry.directEditDate ||
|
entry.order.date !== entry.directEditDate ||
|
||||||
(finance ? form.date : entry.order.date) !== entry.directEditDate);
|
(finance ? form.date : entry.order.date) !== entry.directEditDate);
|
||||||
function submit(event) {
|
function submit(event: FormEvent<HTMLFormElement>) {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
try {
|
try {
|
||||||
let input;
|
let input;
|
||||||
@@ -386,7 +471,9 @@ function EditForm({ client, state, session, entry, serverFeedback, onDraft, save
|
|||||||
input = {
|
input = {
|
||||||
...input,
|
...input,
|
||||||
lines: input.lines.map((line, index) => {
|
lines: input.lines.map((line, index) => {
|
||||||
const controls = Array.from(rows[index].querySelectorAll('input[name],select[name]')).filter(
|
const controls = Array.from(
|
||||||
|
rows[index].querySelectorAll<HTMLInputElement | HTMLSelectElement>('input[name],select[name]'),
|
||||||
|
).filter(
|
||||||
field =>
|
field =>
|
||||||
!field.closest('.charge-row') && (field.name !== 'stockCount' || Object.hasOwn(line, 'stockCount')),
|
!field.closest('.charge-row') && (field.name !== 'stockCount' || Object.hasOwn(line, 'stockCount')),
|
||||||
);
|
);
|
||||||
@@ -406,7 +493,7 @@ function EditForm({ client, state, session, entry, serverFeedback, onDraft, save
|
|||||||
setError('');
|
setError('');
|
||||||
void save(input, reason, verified, approval);
|
void save(input, reason, verified, approval);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err.message);
|
setError(err instanceof Error ? err.message : String(err));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const card = form.payment.method === '信用卡';
|
const card = form.payment.method === '信用卡';
|
||||||
+87
-105
@@ -1,90 +1,64 @@
|
|||||||
|
import { Dialog } from './Dialog';
|
||||||
|
import { useRead, queues, type Queue } from './orderReads';
|
||||||
|
import type { MouseEvent } from 'react';
|
||||||
|
import type { LedgerClient } from '../../lib/api';
|
||||||
|
import type { LedgerState, SessionInfo } from '../../shared';
|
||||||
|
import type {
|
||||||
|
BookData,
|
||||||
|
BookRow,
|
||||||
|
Filters,
|
||||||
|
ReviewList,
|
||||||
|
ChangeRequest,
|
||||||
|
OwnershipRequest,
|
||||||
|
CancellationRequest,
|
||||||
|
IndependentRequest,
|
||||||
|
} from './orderData';
|
||||||
|
interface OrdersProps {
|
||||||
|
client: LedgerClient;
|
||||||
|
state: LedgerState;
|
||||||
|
session: SessionInfo;
|
||||||
|
refreshState: () => Promise<unknown>;
|
||||||
|
saleListStatus: string;
|
||||||
|
setSaleListStatus: (status: string) => void;
|
||||||
|
}
|
||||||
import { ownershipNoticeKey } from './useOrderAccess';
|
import { ownershipNoticeKey } from './useOrderAccess';
|
||||||
import { usePrintStatuses } from '../../lib/printStatus';
|
import { usePrintStatuses } from '../../lib/printStatus';
|
||||||
import { useCallback, useEffect, useEffectEvent, useRef, useState } from 'react';
|
import { useCallback, useEffect, useState } from 'react';
|
||||||
import { navigate, searchParam } from '../../lib/router';
|
import { navigate, searchParam } from '../../lib/router';
|
||||||
import { orderViews } from './orderViews';
|
import { orderViews } from './orderViews';
|
||||||
import { OrderActionDialog, IndependentAfterSale } from './OrderDialogs';
|
import { OrderActionDialog, IndependentAfterSale } from './OrderDialogs';
|
||||||
|
|
||||||
export const queues = [
|
function initialFilters(state: LedgerState): Filters {
|
||||||
['change', '/api/order-changes', '待变更复核', 'open-order-changes', 'order-changes-entry'],
|
const defaults: Filters = { mode: 'today', date: '', from: '', to: '', q: '', status: '', member: '', pocket: '' };
|
||||||
['ownership', '/api/order-ownership-changes', '归属复核', 'order-ownership-open-list', 'order-ownership-entry'],
|
const raw = sessionStorage.getItem('mm-order-book-' + state.user.id);
|
||||||
['cancellation', '/api/order-cancellations', '待取消复核', 'open-order-cancellations', 'order-cancellations-entry'],
|
if (!raw) return defaults;
|
||||||
['after-sale', '/api/after-sales/changes', '售后修改', 'after-sale-changes-open', 'after-sale-changes-entry'],
|
let values: unknown;
|
||||||
];
|
|
||||||
|
|
||||||
export function Dialog({ id, label, close, children, ownClose = false }) {
|
|
||||||
const ref = useRef(null);
|
|
||||||
useEffect(() => {
|
|
||||||
const node = ref.current;
|
|
||||||
node.showModal();
|
|
||||||
return () => node.close();
|
|
||||||
}, []);
|
|
||||||
return (
|
|
||||||
<dialog
|
|
||||||
id={id}
|
|
||||||
ref={ref}
|
|
||||||
aria-label={label}
|
|
||||||
onCancel={event => {
|
|
||||||
event.preventDefault();
|
|
||||||
close();
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{!ownClose && (
|
|
||||||
<button type="button" className="dialog-close" data-action="close-dialog" aria-label={label} onClick={close}>
|
|
||||||
×
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
{children}
|
|
||||||
</dialog>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useRead(read, key) {
|
|
||||||
const [entry, set] = useState(null);
|
|
||||||
const task = useEffectEvent(read);
|
|
||||||
useEffect(() => {
|
|
||||||
if (!key) return;
|
|
||||||
let active = true;
|
|
||||||
Promise.resolve()
|
|
||||||
.then(() => task())
|
|
||||||
.then(
|
|
||||||
value => {
|
|
||||||
if (active) set({ key, value });
|
|
||||||
},
|
|
||||||
error => {
|
|
||||||
if (active) set({ key, error: error.message });
|
|
||||||
},
|
|
||||||
);
|
|
||||||
return () => {
|
|
||||||
active = false;
|
|
||||||
};
|
|
||||||
}, [key]);
|
|
||||||
return entry?.key === key ? entry : {};
|
|
||||||
}
|
|
||||||
|
|
||||||
function initialFilters(state) {
|
|
||||||
let saved;
|
|
||||||
try {
|
try {
|
||||||
saved = JSON.parse(sessionStorage.getItem('mm-order-book-' + state.user.id));
|
values = JSON.parse(raw);
|
||||||
} catch {
|
} catch {
|
||||||
saved = null;
|
return defaults;
|
||||||
}
|
}
|
||||||
return { mode: 'today', date: '', from: '', to: '', q: '', status: '', member: '', pocket: '', ...saved };
|
if (!values || typeof values !== 'object') return defaults;
|
||||||
|
for (const key of Object.keys(defaults) as (keyof Filters)[]) {
|
||||||
|
const value: unknown = Reflect.get(values, key);
|
||||||
|
if (typeof value === 'string') defaults[key] = value;
|
||||||
|
}
|
||||||
|
return defaults;
|
||||||
}
|
}
|
||||||
const options = rows =>
|
const options = (rows: readonly (readonly string[])[]) =>
|
||||||
rows.map(([value, name]) => (
|
rows.map(([value, name]) => (
|
||||||
<option key={value} value={value}>
|
<option key={value} value={value}>
|
||||||
{name}
|
{name}
|
||||||
</option>
|
</option>
|
||||||
));
|
));
|
||||||
|
|
||||||
export function OrdersPage({ client, state, session, refreshState, saleListStatus, setSaleListStatus }) {
|
export function OrdersPage({ client, state, session, refreshState, saleListStatus, setSaleListStatus }: OrdersProps) {
|
||||||
const [filters, setFilters] = useState(() => initialFilters(state));
|
const [filters, setFilters] = useState(() => initialFilters(state));
|
||||||
const noticeKey = ownershipNoticeKey(state.user.id);
|
const noticeKey = ownershipNoticeKey(state.user.id);
|
||||||
const [error, setError] = useState(() => sessionStorage.getItem(noticeKey) || '');
|
const [error, setError] = useState(() => sessionStorage.getItem(noticeKey) || '');
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
sessionStorage.removeItem(noticeKey);
|
sessionStorage.removeItem(noticeKey);
|
||||||
const failed = event => setError(previous => previous + ' ' + event.detail);
|
const failed = (event: Event) => setError(previous => previous + ' ' + (event as CustomEvent<string>).detail);
|
||||||
window.addEventListener('order-access-refresh-error', failed);
|
window.addEventListener('order-access-refresh-error', failed);
|
||||||
return () => window.removeEventListener('order-access-refresh-error', failed);
|
return () => window.removeEventListener('order-access-refresh-error', failed);
|
||||||
}, [noticeKey]);
|
}, [noticeKey]);
|
||||||
@@ -96,10 +70,10 @@ export function OrdersPage({ client, state, session, refreshState, saleListStatu
|
|||||||
if (document.hidden || checking || client.busy) return;
|
if (document.hidden || checking || client.busy) return;
|
||||||
checking = true;
|
checking = true;
|
||||||
try {
|
try {
|
||||||
const latest = await client.api('/api/state');
|
const latest = await client.api<LedgerState>('/api/state');
|
||||||
if (active && latest.user.id === state.user.id && latest.today !== state.today) await refreshState();
|
if (active && latest.user.id === state.user.id && latest.today !== state.today) await refreshState();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (active) setError(err.message);
|
if (active) setError(err instanceof Error ? err.message : String(err));
|
||||||
} finally {
|
} finally {
|
||||||
checking = false;
|
checking = false;
|
||||||
}
|
}
|
||||||
@@ -114,19 +88,15 @@ export function OrdersPage({ client, state, session, refreshState, saleListStatu
|
|||||||
}, [client, state.user.id, state.today, refreshState]);
|
}, [client, state.user.id, state.today, refreshState]);
|
||||||
const [generation, reload] = useState(0);
|
const [generation, reload] = useState(0);
|
||||||
const [selected, setSelected] = useState(searchParam('order'));
|
const [selected, setSelected] = useState(searchParam('order'));
|
||||||
const [listIds, setListIds] = useState(null);
|
const [listIds, setListIds] = useState<string[] | null>(null);
|
||||||
const [queue, setQueue] = useState('');
|
const [queue, setQueue] = useState<Queue | ''>('');
|
||||||
const [orderStatus, setOrderStatus] = useState('pending');
|
const [orderStatus, setOrderStatus] = useState('pending');
|
||||||
const status = queue === 'after-sale' ? saleListStatus : orderStatus;
|
const status = queue === 'after-sale' ? saleListStatus : orderStatus;
|
||||||
const [sale, setSale] = useState(() =>
|
const [sale, setSale] = useState<{ action: string; id?: string } | null>(() =>
|
||||||
searchParam('afterSale') ? { action: 'after-sale-edit', id: searchParam('afterSale') } : null,
|
searchParam('afterSale') ? { action: 'after-sale-edit', id: searchParam('afterSale') } : null,
|
||||||
);
|
);
|
||||||
const refresh = useCallback(() => reload(i => i + 1), []);
|
const refresh = useCallback(() => reload(i => i + 1), []);
|
||||||
const currentQuery = searchParam('order');
|
function filter(values: Partial<Filters>) {
|
||||||
useEffect(() => {
|
|
||||||
setSelected(currentQuery);
|
|
||||||
}, [currentQuery]);
|
|
||||||
function filter(values) {
|
|
||||||
const next = { ...filters, ...values };
|
const next = { ...filters, ...values };
|
||||||
setFilters(next);
|
setFilters(next);
|
||||||
sessionStorage.setItem('mm-order-book-' + state.user.id, JSON.stringify(next));
|
sessionStorage.setItem('mm-order-book-' + state.user.id, JSON.stringify(next));
|
||||||
@@ -140,11 +110,11 @@ export function OrdersPage({ client, state, session, refreshState, saleListStatu
|
|||||||
orderCancellationListStatus: status,
|
orderCancellationListStatus: status,
|
||||||
afterSaleChangesStatus: status,
|
afterSaleChangesStatus: status,
|
||||||
});
|
});
|
||||||
let range, invalid;
|
let range: ReturnType<typeof views.orderBookRange> | undefined, invalid: string | undefined;
|
||||||
try {
|
try {
|
||||||
range = views.orderBookRange();
|
range = views.orderBookRange();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
invalid = err.message;
|
invalid = err instanceof Error ? err.message : String(err);
|
||||||
}
|
}
|
||||||
const params =
|
const params =
|
||||||
range &&
|
range &&
|
||||||
@@ -158,8 +128,8 @@ export function OrdersPage({ client, state, session, refreshState, saleListStatu
|
|||||||
});
|
});
|
||||||
const book = useRead(
|
const book = useRead(
|
||||||
async () => {
|
async () => {
|
||||||
const data = await client.api('/api/order-book?' + params);
|
const data = await client.api<BookData>('/api/order-book?' + params);
|
||||||
if (data.from !== range.from || data.date !== range.date || (data.pocket ?? '') !== filters.pocket)
|
if (data.from !== range!.from || data.date !== range!.date || (data.pocket ?? '') !== filters.pocket)
|
||||||
throw new Error('返回账本与所选日期或货盘不一致,请重新读取。');
|
throw new Error('返回账本与所选日期或货盘不一致,请重新读取。');
|
||||||
return data;
|
return data;
|
||||||
},
|
},
|
||||||
@@ -170,7 +140,7 @@ export function OrdersPage({ client, state, session, refreshState, saleListStatu
|
|||||||
Promise.all(
|
Promise.all(
|
||||||
queues.map(async ([, url]) => {
|
queues.map(async ([, url]) => {
|
||||||
try {
|
try {
|
||||||
return (await client.api(url + '?status=pending')).counts.pending;
|
return (await client.api<ReviewList<unknown>>(url + '?status=pending')).counts.pending;
|
||||||
} catch {
|
} catch {
|
||||||
return '读取失败';
|
return '读取失败';
|
||||||
}
|
}
|
||||||
@@ -179,21 +149,28 @@ export function OrdersPage({ client, state, session, refreshState, saleListStatu
|
|||||||
state.user.id + '/' + generation,
|
state.user.id + '/' + generation,
|
||||||
);
|
);
|
||||||
const qdef = queues.find(([kind]) => kind === queue);
|
const qdef = queues.find(([kind]) => kind === queue);
|
||||||
const list = useRead(() => client.api(qdef[1] + '?status=' + status), queue && [queue, status, generation].join('/'));
|
const list = useRead(
|
||||||
const review =
|
async () => {
|
||||||
qdef &&
|
const url = qdef![1] + '?status=' + status;
|
||||||
list.value &&
|
switch (queue) {
|
||||||
{
|
case 'change':
|
||||||
change: views.orderChangeListHTML,
|
return views.orderChangeListHTML(await client.api<ReviewList<ChangeRequest>>(url));
|
||||||
ownership: views.orderOwnershipListHTML,
|
case 'ownership':
|
||||||
cancellation: views.orderCancellationListHTML,
|
return views.orderOwnershipListHTML(await client.api<ReviewList<OwnershipRequest>>(url));
|
||||||
'after-sale': views.afterSaleChangeListHTML,
|
case 'cancellation':
|
||||||
}[queue](list.value);
|
return views.orderCancellationListHTML(await client.api<ReviewList<CancellationRequest>>(url));
|
||||||
|
case 'after-sale':
|
||||||
|
return views.afterSaleChangeListHTML(await client.api<ReviewList<IndependentRequest>>(url));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
queue && [queue, status, generation].join('/'),
|
||||||
|
);
|
||||||
|
const review = list.value;
|
||||||
let content,
|
let content,
|
||||||
bookError = invalid || book.error;
|
bookError = invalid || book.error;
|
||||||
if (book.value) {
|
if (book.value) {
|
||||||
try {
|
try {
|
||||||
const withPrint = rows =>
|
const withPrint = (rows: BookRow[]) =>
|
||||||
rows.map(row =>
|
rows.map(row =>
|
||||||
printStatuses[row.printStatus?.id || row.id]
|
printStatuses[row.printStatus?.id || row.id]
|
||||||
? { ...row, printStatus: printStatuses[row.printStatus?.id || row.id] }
|
? { ...row, printStatus: printStatuses[row.printStatus?.id || row.id] }
|
||||||
@@ -205,20 +182,22 @@ export function OrdersPage({ client, state, session, refreshState, saleListStatu
|
|||||||
rows: withPrint(book.value.rows),
|
rows: withPrint(book.value.rows),
|
||||||
...(book.value.displayRows ? { displayRows: withPrint(book.value.displayRows) } : {}),
|
...(book.value.displayRows ? { displayRows: withPrint(book.value.displayRows) } : {}),
|
||||||
},
|
},
|
||||||
range,
|
range!,
|
||||||
);
|
);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
bookError = err.message;
|
bookError = err instanceof Error ? err.message : String(err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const openOrder = (id, fromList = false) => {
|
const openOrder = (id: string, fromList = false) => {
|
||||||
setQueue('');
|
setQueue('');
|
||||||
setError('');
|
setError('');
|
||||||
setListIds(
|
setListIds(
|
||||||
fromList
|
fromList
|
||||||
? [
|
? [
|
||||||
...new Set(
|
...new Set(
|
||||||
book.value.rows.filter(row => !['afterSale', 'orderAfterSale'].includes(row.kind)).map(row => row.id),
|
book
|
||||||
|
.value!.rows.filter(row => !['afterSale', 'orderAfterSale'].includes(row.kind ?? ''))
|
||||||
|
.map(row => row.id),
|
||||||
),
|
),
|
||||||
]
|
]
|
||||||
: null,
|
: null,
|
||||||
@@ -229,7 +208,7 @@ export function OrdersPage({ client, state, session, refreshState, saleListStatu
|
|||||||
setSelected('');
|
setSelected('');
|
||||||
if (searchParam('order')) navigate('orders', { replace: true, fromPage: true });
|
if (searchParam('order')) navigate('orders', { replace: true, fromPage: true });
|
||||||
}
|
}
|
||||||
function lostAccess(message) {
|
function lostAccess(message: string) {
|
||||||
setListIds(null);
|
setListIds(null);
|
||||||
setQueue('');
|
setQueue('');
|
||||||
setSelected('');
|
setSelected('');
|
||||||
@@ -239,12 +218,13 @@ export function OrdersPage({ client, state, session, refreshState, saleListStatu
|
|||||||
navigate('orders', { replace: true, fromPage: true });
|
navigate('orders', { replace: true, fromPage: true });
|
||||||
}
|
}
|
||||||
refresh();
|
refresh();
|
||||||
void refreshState().catch(err => setError(message + ' ' + err.message));
|
void refreshState().catch(err => setError(message + ' ' + (err instanceof Error ? err.message : String(err))));
|
||||||
}
|
}
|
||||||
function click(event) {
|
function click(event: MouseEvent<HTMLElement>) {
|
||||||
const node = event.target.closest('[data-action]');
|
if (!(event.target instanceof Element)) return;
|
||||||
if (!node || event.defaultPrevented) return;
|
const node = event.target.closest<HTMLElement>('[data-action]');
|
||||||
const { action, id, period, status: newStatus } = node.dataset;
|
if (!node || !node.dataset.action || event.defaultPrevented) return;
|
||||||
|
const { action = '', id = '', period, status: newStatus } = node.dataset;
|
||||||
const match = queues.find(row => row[3] === action);
|
const match = queues.find(row => row[3] === action);
|
||||||
if (match) {
|
if (match) {
|
||||||
setQueue(match[0]);
|
setQueue(match[0]);
|
||||||
@@ -273,7 +253,9 @@ export function OrdersPage({ client, state, session, refreshState, saleListStatu
|
|||||||
});
|
});
|
||||||
if (action === 'refresh' || action.includes('retry') || action.includes('reload')) refresh();
|
if (action === 'refresh' || action.includes('retry') || action.includes('reload')) refresh();
|
||||||
}
|
}
|
||||||
const countSum = counts.value?.every(Number.isInteger) ? counts.value.reduce((acc, n) => acc + n, 0) : null;
|
const countSum = counts.value?.every((n): n is number => typeof n === 'number' && Number.isInteger(n))
|
||||||
|
? counts.value.reduce((acc, n) => acc + n, 0)
|
||||||
|
: null;
|
||||||
const memberOptions = (state.members || []).map(m => [
|
const memberOptions = (state.members || []).map(m => [
|
||||||
m.member,
|
m.member,
|
||||||
views.teamMemberName(m.member) + (m.enabled === false ? '(已停用)' : ''),
|
views.teamMemberName(m.member) + (m.enabled === false ? '(已停用)' : ''),
|
||||||
@@ -306,7 +288,7 @@ export function OrdersPage({ client, state, session, refreshState, saleListStatu
|
|||||||
(state.user.role === 'owner' ? '跨日期查看售后修改,核对原值与申请值后复核。' : '查看自己归属售后的修改申请。') +
|
(state.user.role === 'owner' ? '跨日期查看售后修改,核对原值与申请值后复核。' : '查看自己归属售后的修改申请。') +
|
||||||
'待审批期间仍按原记录计账。',
|
'待审批期间仍按原记录计账。',
|
||||||
],
|
],
|
||||||
}[queue];
|
}[queue || 'change'];
|
||||||
return (
|
return (
|
||||||
<div className="business-pages" onClick={click}>
|
<div className="business-pages" onClick={click}>
|
||||||
<div className="page-heading">
|
<div className="page-heading">
|
||||||
@@ -365,7 +347,7 @@ export function OrdersPage({ client, state, session, refreshState, saleListStatu
|
|||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
<div id="order-range-fields" hidden={filters.mode !== 'range'}>
|
<div id="order-range-fields" hidden={filters.mode !== 'range'}>
|
||||||
{['from', 'to'].map((key, i) => (
|
{(['from', 'to'] as const).map((key, i) => (
|
||||||
<label key={key}>
|
<label key={key}>
|
||||||
{i ? '结束' : '开始'}日期
|
{i ? '结束' : '开始'}日期
|
||||||
<input
|
<input
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
import type { ReactNode } from 'react';
|
||||||
|
import type { LedgerClient } from '../../lib/api';
|
||||||
|
import type { LedgerState, OrderDraft, SessionInfo } from '../../shared';
|
||||||
|
|
||||||
|
export interface EditFee extends Record<string, unknown> {
|
||||||
|
key: string;
|
||||||
|
note: string;
|
||||||
|
payer: string;
|
||||||
|
amount: string;
|
||||||
|
status?: string;
|
||||||
|
date?: string;
|
||||||
|
edited?: boolean;
|
||||||
|
funding?: Record<string, unknown>;
|
||||||
|
sourceName?: string;
|
||||||
|
lineNumber?: number;
|
||||||
|
system?: string;
|
||||||
|
expense_id?: string;
|
||||||
|
chargeId?: string;
|
||||||
|
source_kind?: string;
|
||||||
|
source_id?: string;
|
||||||
|
}
|
||||||
|
export interface LockMaterial {
|
||||||
|
source?: string;
|
||||||
|
rate: string;
|
||||||
|
payer: string;
|
||||||
|
amount?: number;
|
||||||
|
verified: boolean;
|
||||||
|
}
|
||||||
|
export interface EditItem extends Record<string, unknown> {
|
||||||
|
lineId?: string;
|
||||||
|
name: string;
|
||||||
|
unit: string;
|
||||||
|
quantity: string;
|
||||||
|
payer: string;
|
||||||
|
costParts: { material: string; labor: string; accessories: string; other: string };
|
||||||
|
costPayers: { material: string; labor: string };
|
||||||
|
costLabor: { mode: string; rate?: string };
|
||||||
|
charges?: { id?: string; costRemoved?: boolean; name?: string }[];
|
||||||
|
costFundings?: { labor?: Record<string, unknown> };
|
||||||
|
price_lock_material?: LockMaterial;
|
||||||
|
price_lock_extra_material?: LockMaterial;
|
||||||
|
}
|
||||||
|
export interface EditInputs extends OrderDraft {
|
||||||
|
note: string;
|
||||||
|
date: string;
|
||||||
|
fees_date: string;
|
||||||
|
fee_cost_mode: string;
|
||||||
|
member?: string;
|
||||||
|
customer_type?: string;
|
||||||
|
lines: EditItem[];
|
||||||
|
fee_items: EditFee[];
|
||||||
|
price_lock_material?: LockMaterial;
|
||||||
|
price_lock_extra_material?: LockMaterial;
|
||||||
|
}
|
||||||
|
export interface LockLineMeta {
|
||||||
|
id: string;
|
||||||
|
lineId?: string;
|
||||||
|
line_index?: number;
|
||||||
|
lockedMg: number;
|
||||||
|
materialSource: string;
|
||||||
|
materialLocked: boolean;
|
||||||
|
canSwitchToManual: boolean;
|
||||||
|
extraMg: number;
|
||||||
|
}
|
||||||
|
export interface LockEditMeta extends LockLineMeta {
|
||||||
|
date: string;
|
||||||
|
lines?: LockLineMeta[];
|
||||||
|
financeRequiresApproval: boolean;
|
||||||
|
approvalReason?: string;
|
||||||
|
}
|
||||||
|
export interface PoolCost {
|
||||||
|
poolId: string;
|
||||||
|
date: string;
|
||||||
|
amount: number | null;
|
||||||
|
averageRate: number | null;
|
||||||
|
allocations: { payer: string; amount: number }[];
|
||||||
|
materialSources?: {
|
||||||
|
kind: string;
|
||||||
|
quantity: number;
|
||||||
|
amount: number | null;
|
||||||
|
averageRate?: number | null;
|
||||||
|
member?: string;
|
||||||
|
}[];
|
||||||
|
}
|
||||||
|
export interface EditOrderRecord {
|
||||||
|
id: string;
|
||||||
|
number: string;
|
||||||
|
date: string;
|
||||||
|
paper_date: string;
|
||||||
|
paper_number: string;
|
||||||
|
member: string;
|
||||||
|
customer: string;
|
||||||
|
salesperson: string;
|
||||||
|
note: string;
|
||||||
|
internal_note?: string;
|
||||||
|
payment_account: string;
|
||||||
|
total: number;
|
||||||
|
directCost: number;
|
||||||
|
rounding_mode: string;
|
||||||
|
price_lock_id?: string;
|
||||||
|
lines: {
|
||||||
|
name: string;
|
||||||
|
unit: string;
|
||||||
|
quantity: number;
|
||||||
|
sale: number;
|
||||||
|
cost: number | null;
|
||||||
|
pocket: string;
|
||||||
|
goldPrice?: number;
|
||||||
|
priceLockPool?: PoolCost;
|
||||||
|
materialPool?: PoolCost;
|
||||||
|
priceLockExtraPool?: PoolCost;
|
||||||
|
}[];
|
||||||
|
}
|
||||||
|
export interface EditResponse {
|
||||||
|
eligible: boolean;
|
||||||
|
reason: string;
|
||||||
|
revision: number;
|
||||||
|
inputs: EditInputs;
|
||||||
|
order: EditOrderRecord;
|
||||||
|
priceLock?: LockEditMeta | null;
|
||||||
|
requiresApproval?: boolean;
|
||||||
|
financialEditable: boolean;
|
||||||
|
directEditDate?: string;
|
||||||
|
approvalReason?: string;
|
||||||
|
requiresLegacyCountVerified?: boolean;
|
||||||
|
legacyCountNotice?: string;
|
||||||
|
}
|
||||||
|
export interface EditEntry extends EditResponse {
|
||||||
|
id: string;
|
||||||
|
user: string;
|
||||||
|
reason: string;
|
||||||
|
verified: boolean;
|
||||||
|
originalInputs: EditInputs;
|
||||||
|
sameDayDirectEdit: boolean;
|
||||||
|
conflicted: boolean;
|
||||||
|
latest?: EditResponse | null;
|
||||||
|
}
|
||||||
|
export type LockEntry = EditEntry & { priceLock: LockEditMeta };
|
||||||
|
export type SaveDraft = (inputs: OrderDraft, reason: string, verified: boolean) => void;
|
||||||
|
export type EditPayload =
|
||||||
|
OrderDraft | { customer: string; salesperson: string; customer_type?: string; note: string; internal_note: string };
|
||||||
|
export type SaveOrder = (inputs: EditPayload, reason: string, verified: boolean, approval: boolean) => Promise<void>;
|
||||||
|
export interface LockEditorProps {
|
||||||
|
client: LedgerClient;
|
||||||
|
state: LedgerState;
|
||||||
|
session: SessionInfo;
|
||||||
|
entry: LockEntry;
|
||||||
|
serverFeedback: ReactNode;
|
||||||
|
onDraft: SaveDraft;
|
||||||
|
onSave: SaveOrder;
|
||||||
|
onCancel: () => void;
|
||||||
|
}
|
||||||
@@ -0,0 +1,774 @@
|
|||||||
|
export interface OrderRecord {
|
||||||
|
id: string;
|
||||||
|
number: string;
|
||||||
|
date: string;
|
||||||
|
customer: string;
|
||||||
|
salesperson: string;
|
||||||
|
note: string;
|
||||||
|
paper_number: string;
|
||||||
|
status: string;
|
||||||
|
lines: OrderLine[];
|
||||||
|
discount: number;
|
||||||
|
total: number;
|
||||||
|
revision: number;
|
||||||
|
reviewed_revision: number;
|
||||||
|
created: string;
|
||||||
|
delivered_date: null | string;
|
||||||
|
returned_date: null | string;
|
||||||
|
paper_date: string;
|
||||||
|
payment_account: string;
|
||||||
|
fee_items: Fee[];
|
||||||
|
fees_date: string;
|
||||||
|
rounding_mode: string;
|
||||||
|
internal_note: string;
|
||||||
|
fee_cost_mode: string;
|
||||||
|
customer_type: string;
|
||||||
|
member: string;
|
||||||
|
cancellationPending?: CancellationRequest | null;
|
||||||
|
cancellationApproved?: null | CancellationRequest;
|
||||||
|
changePending?: ChangeRequest | null;
|
||||||
|
ownershipPending: OwnershipRequest | null;
|
||||||
|
payments: Payment[];
|
||||||
|
expenses: Expense[];
|
||||||
|
settlements: Settlement[];
|
||||||
|
corrections: Correction[];
|
||||||
|
netReceived: number;
|
||||||
|
balance: number;
|
||||||
|
rounding_adjustment: number;
|
||||||
|
goodsCost: number | null;
|
||||||
|
directCost: number;
|
||||||
|
materialCostPending: boolean;
|
||||||
|
knownGoodsCost: number;
|
||||||
|
pendingFees: Fee[];
|
||||||
|
profit: number | null;
|
||||||
|
ownerCost: number;
|
||||||
|
ownerDirect: number;
|
||||||
|
ownerCredit: number;
|
||||||
|
costTransferred: number;
|
||||||
|
profitTransferred: number;
|
||||||
|
costDue: number;
|
||||||
|
profitDue: number;
|
||||||
|
settlementDue: number | null;
|
||||||
|
audit?: OrderRecordAudit[];
|
||||||
|
funds_mode: string;
|
||||||
|
credit_card_rate_permille?: number;
|
||||||
|
printStatus?: PrintStatus;
|
||||||
|
orderAfterSale?: OrderAfterSale;
|
||||||
|
assistantInventoryCredit?: number;
|
||||||
|
assistantInventoryCreditExplanation?: string;
|
||||||
|
kind?: string;
|
||||||
|
price_lock_id?: string;
|
||||||
|
recovery_id?: string;
|
||||||
|
recovery_mode?: string;
|
||||||
|
priceLockCosts?: LockCosts;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BookData {
|
||||||
|
from: string;
|
||||||
|
date: string;
|
||||||
|
pocket: string;
|
||||||
|
rows: BookRow[];
|
||||||
|
displayRows?: BookRow[];
|
||||||
|
recoveryCount: number;
|
||||||
|
summary: BookSummary;
|
||||||
|
priceLockActivity: LockActivity;
|
||||||
|
summaryWithoutCancelled: BookSummary;
|
||||||
|
receiptsWithoutCancelled: ReceiptSummary;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ChangeRequest {
|
||||||
|
id: string;
|
||||||
|
order_id: string;
|
||||||
|
order_revision: number;
|
||||||
|
action: string;
|
||||||
|
reason: string;
|
||||||
|
status: 'pending' | 'approved' | 'rejected';
|
||||||
|
requester_name: string;
|
||||||
|
created: string;
|
||||||
|
reviewer_name: null | string;
|
||||||
|
reviewed: null | string;
|
||||||
|
note: string;
|
||||||
|
action_label: string;
|
||||||
|
order_number?: string;
|
||||||
|
order_date?: string;
|
||||||
|
stale?: boolean;
|
||||||
|
canApprove?: boolean;
|
||||||
|
before: OrderRecord;
|
||||||
|
after: OrderRecord;
|
||||||
|
summary: ChangeSummary;
|
||||||
|
relatedOrders?: RelatedOrder[];
|
||||||
|
action_details?: ChangeActionInput;
|
||||||
|
action_input?: ChangeActionInput;
|
||||||
|
relatedPriceLocks?: RelatedLock[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OwnershipRequest {
|
||||||
|
id: string;
|
||||||
|
order_id: string;
|
||||||
|
order_revision: number;
|
||||||
|
reason: string;
|
||||||
|
status: 'pending' | 'approved' | 'rejected';
|
||||||
|
direct: boolean;
|
||||||
|
requester_name: string;
|
||||||
|
created: string;
|
||||||
|
reviewer_name: null | string;
|
||||||
|
reviewed: null | string;
|
||||||
|
note: string;
|
||||||
|
before: Member;
|
||||||
|
after: Member;
|
||||||
|
order_number?: string;
|
||||||
|
order_customer?: string;
|
||||||
|
order_date?: string;
|
||||||
|
stale?: boolean;
|
||||||
|
canApprove?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CancellationRequest {
|
||||||
|
executedAt?: string;
|
||||||
|
operator_name?: string;
|
||||||
|
id: string;
|
||||||
|
order_id: string;
|
||||||
|
order_revision: number;
|
||||||
|
reason: string;
|
||||||
|
status: 'pending' | 'approved' | 'rejected';
|
||||||
|
requester_name: string;
|
||||||
|
created: string;
|
||||||
|
reviewer_name: null | string;
|
||||||
|
reviewed: null | string;
|
||||||
|
note: string;
|
||||||
|
order_number?: string;
|
||||||
|
order_date?: string;
|
||||||
|
requiresLegacyCountVerified?: boolean;
|
||||||
|
legacyCountNotice?: string;
|
||||||
|
stale?: boolean;
|
||||||
|
canApprove?: boolean;
|
||||||
|
summary: CancelSummary;
|
||||||
|
direct?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ChangeData {
|
||||||
|
eligible: boolean;
|
||||||
|
reason: string;
|
||||||
|
actions: ActionRules;
|
||||||
|
directActionDate: string;
|
||||||
|
revision: number;
|
||||||
|
pending: ChangeRequest | null;
|
||||||
|
requests: ChangeRequest[];
|
||||||
|
canApprove: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OwnershipData {
|
||||||
|
eligible: boolean;
|
||||||
|
reason: string;
|
||||||
|
revision: number;
|
||||||
|
member: string;
|
||||||
|
members: Member[];
|
||||||
|
requiresApproval: boolean;
|
||||||
|
canDirect: boolean;
|
||||||
|
canApprove: boolean;
|
||||||
|
pending: OwnershipRequest | null;
|
||||||
|
requests: OwnershipRequest[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CancellationData {
|
||||||
|
eligible: boolean;
|
||||||
|
reason: string;
|
||||||
|
revision: number;
|
||||||
|
requiresLegacyCountVerified: boolean;
|
||||||
|
legacyCountNotice: string;
|
||||||
|
directActionDate: string;
|
||||||
|
directToday: boolean;
|
||||||
|
pending: CancellationRequest | null;
|
||||||
|
requests: CancellationRequest[];
|
||||||
|
canApprove: boolean;
|
||||||
|
summary?: CancelSummary;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OrderAfterSaleData {
|
||||||
|
orderId: string;
|
||||||
|
revision: number;
|
||||||
|
eligible: boolean;
|
||||||
|
blockedReason: string;
|
||||||
|
record: null | OrderAfterSale;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IndependentDetail {
|
||||||
|
id: string;
|
||||||
|
revision: number;
|
||||||
|
record: IndependentRecord;
|
||||||
|
values: IndependentValues;
|
||||||
|
permissions: AfterPermissions;
|
||||||
|
pending: IndependentRequest | null;
|
||||||
|
history: IndependentRequest[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IndependentRequest {
|
||||||
|
id: string;
|
||||||
|
afterSaleId: string;
|
||||||
|
revision: number;
|
||||||
|
recordRevision: number;
|
||||||
|
status: 'pending' | 'approved' | 'rejected';
|
||||||
|
reason: string;
|
||||||
|
before: IndependentValues;
|
||||||
|
after: IndependentValues;
|
||||||
|
member: string;
|
||||||
|
requesterName: string;
|
||||||
|
created: string;
|
||||||
|
reviewerName: string | null;
|
||||||
|
reviewed: string | null;
|
||||||
|
note: string;
|
||||||
|
stale: boolean;
|
||||||
|
staleReason: string;
|
||||||
|
canApprove: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OrderLine {
|
||||||
|
name: string;
|
||||||
|
code: string;
|
||||||
|
unit: string;
|
||||||
|
quantity: number;
|
||||||
|
pocket: string;
|
||||||
|
payer: string;
|
||||||
|
cost: number;
|
||||||
|
sale: number;
|
||||||
|
baseSale: number;
|
||||||
|
charges: Charge[];
|
||||||
|
pricingMode: string;
|
||||||
|
priceNote: string;
|
||||||
|
costPayers?: OrderLineCostPayers;
|
||||||
|
costParts?: CostParts;
|
||||||
|
costMaterial?: CostMode;
|
||||||
|
costLabor?: CostMode;
|
||||||
|
goldPrice?: number;
|
||||||
|
laborRate?: number;
|
||||||
|
laborMode?: string;
|
||||||
|
pieces?: number;
|
||||||
|
materialPool?: LinePool;
|
||||||
|
stockCount?: number | null;
|
||||||
|
priceLockPool?: LinePool;
|
||||||
|
priceLockExtraPool?: LinePool;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OrderRecordAudit {
|
||||||
|
action: string;
|
||||||
|
actor: string;
|
||||||
|
detail: { reason?: string };
|
||||||
|
created: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PrintStatus {
|
||||||
|
kind: string;
|
||||||
|
id: string;
|
||||||
|
printed: boolean;
|
||||||
|
revision?: number;
|
||||||
|
actor?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Fee {
|
||||||
|
key: string;
|
||||||
|
system?: string;
|
||||||
|
source_kind?: string;
|
||||||
|
source_id?: string;
|
||||||
|
date?: string;
|
||||||
|
amount: number;
|
||||||
|
payer: string;
|
||||||
|
note: string;
|
||||||
|
status: string;
|
||||||
|
expense_id?: string;
|
||||||
|
edited?: boolean;
|
||||||
|
lineNumber?: number;
|
||||||
|
sourceName?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Payment {
|
||||||
|
price_lock_event_id?: string;
|
||||||
|
id: string;
|
||||||
|
order_id: string;
|
||||||
|
date: string;
|
||||||
|
kind: string;
|
||||||
|
amount: number;
|
||||||
|
account: string;
|
||||||
|
reference: string;
|
||||||
|
actor: string;
|
||||||
|
created: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Expense {
|
||||||
|
id: string;
|
||||||
|
order_id: string;
|
||||||
|
date: string;
|
||||||
|
amount: number;
|
||||||
|
payer: string;
|
||||||
|
note: string;
|
||||||
|
actor: string;
|
||||||
|
created: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Correction {
|
||||||
|
target: string;
|
||||||
|
type: string;
|
||||||
|
reason: string;
|
||||||
|
actor: string;
|
||||||
|
created: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BookRow {
|
||||||
|
[key: `${string}Cost`]: number | null | undefined;
|
||||||
|
assistant2Cost?: number;
|
||||||
|
id: string;
|
||||||
|
order_id?: string;
|
||||||
|
kind?: string;
|
||||||
|
orderAfterSale?: OrderAfterSale;
|
||||||
|
member?: string;
|
||||||
|
number: string;
|
||||||
|
paper_number: string;
|
||||||
|
date: string;
|
||||||
|
order_date?: string;
|
||||||
|
created: string;
|
||||||
|
customer: string;
|
||||||
|
salesperson: string;
|
||||||
|
status: string;
|
||||||
|
note: string;
|
||||||
|
project?: string;
|
||||||
|
types: string[];
|
||||||
|
mg: number;
|
||||||
|
pieces: number;
|
||||||
|
originalSale?: number;
|
||||||
|
sale?: number;
|
||||||
|
material?: number | null;
|
||||||
|
laborAndFees?: number | null;
|
||||||
|
unallocated?: number;
|
||||||
|
totalCost?: number;
|
||||||
|
profit?: number;
|
||||||
|
ownerCost?: number;
|
||||||
|
assistantCost?: number;
|
||||||
|
known?: Known;
|
||||||
|
costItems?: BookCost[];
|
||||||
|
laborAndFeeItems?: BookCost[];
|
||||||
|
pendingCosts?: number;
|
||||||
|
unknownCosts?: number;
|
||||||
|
legacyUnallocated?: boolean;
|
||||||
|
incomplete?: boolean;
|
||||||
|
costHint: string;
|
||||||
|
balance?: number;
|
||||||
|
revision?: number;
|
||||||
|
reviewed_revision?: number;
|
||||||
|
funds_mode?: string;
|
||||||
|
price_lock_id?: string;
|
||||||
|
recovery_id?: string;
|
||||||
|
recovery_mode?: string;
|
||||||
|
cancellationApproved?: CancellationRequest | null;
|
||||||
|
materialCostPending?: boolean;
|
||||||
|
printStatus?: PrintStatus;
|
||||||
|
after_sale_id?: string;
|
||||||
|
amount?: number;
|
||||||
|
payer?: string;
|
||||||
|
cashPayment?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BookSummary {
|
||||||
|
[key: `${string}Cost`]: number;
|
||||||
|
assistant2Cost: number;
|
||||||
|
orderCount: number;
|
||||||
|
completedCount: number;
|
||||||
|
draftCount: number;
|
||||||
|
cancelledCount: number;
|
||||||
|
incompleteCount: number;
|
||||||
|
pendingCosts: number;
|
||||||
|
unknownCosts: number;
|
||||||
|
unknownCostCount: number;
|
||||||
|
unknownProfitCount: number;
|
||||||
|
sale: number;
|
||||||
|
material: number;
|
||||||
|
laborAndFees: number;
|
||||||
|
unallocated: number;
|
||||||
|
totalCost: number;
|
||||||
|
profit: number;
|
||||||
|
ownerCost: number;
|
||||||
|
assistantCost: number;
|
||||||
|
mg: number;
|
||||||
|
pieces: number;
|
||||||
|
knownCounts: Counts;
|
||||||
|
unknownCounts: Counts;
|
||||||
|
afterSaleCount: number;
|
||||||
|
recordCount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LockActivity {
|
||||||
|
basis: string;
|
||||||
|
from: string;
|
||||||
|
date: string;
|
||||||
|
customerCash: LockActivityRow[];
|
||||||
|
orderPayments: LockActivityRow[];
|
||||||
|
materialOutlays: LockActivityRow[];
|
||||||
|
directOutlays: LockActivityRow[];
|
||||||
|
deliveryGoodsOutlays: LockActivityRow[];
|
||||||
|
summary: LockActivitySummary;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ReceiptSummary {
|
||||||
|
basis: string;
|
||||||
|
filterScope: string;
|
||||||
|
from: string;
|
||||||
|
date: string;
|
||||||
|
receipt: number;
|
||||||
|
refund: number;
|
||||||
|
net: number;
|
||||||
|
channels: ReceiptSummaryChannels[];
|
||||||
|
orderCount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ChangeSummary {
|
||||||
|
before: CostSummary;
|
||||||
|
after: CostSummary;
|
||||||
|
inventory: InventoryChange;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Member {
|
||||||
|
member: string;
|
||||||
|
label: string;
|
||||||
|
enabled?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CancelSummary extends CostSummary {
|
||||||
|
legacyCountNotice?: string;
|
||||||
|
requiresLegacyCountVerified?: boolean;
|
||||||
|
inventory: InventoryRow[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ActionRules {
|
||||||
|
[kind: string]: ActionRule;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OrderAfterSale {
|
||||||
|
orderId: string;
|
||||||
|
date: string;
|
||||||
|
reason: string;
|
||||||
|
deductionReason: string;
|
||||||
|
refund: Refund;
|
||||||
|
expenses: { note: string; amount: number; payer: string }[];
|
||||||
|
summary: AfterSummary;
|
||||||
|
lines: AfterSaleLine[];
|
||||||
|
order_id?: string;
|
||||||
|
created?: string;
|
||||||
|
number?: string;
|
||||||
|
paper_number?: string;
|
||||||
|
customer?: string;
|
||||||
|
salesperson?: string;
|
||||||
|
note?: string;
|
||||||
|
order_date?: string;
|
||||||
|
member?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IndependentRecord {
|
||||||
|
id: string;
|
||||||
|
date: string;
|
||||||
|
project: string;
|
||||||
|
customer: string;
|
||||||
|
amount: number;
|
||||||
|
payer: string;
|
||||||
|
actor: string;
|
||||||
|
created: string;
|
||||||
|
member: string;
|
||||||
|
revision: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IndependentValues {
|
||||||
|
date: string;
|
||||||
|
project: string;
|
||||||
|
customer: string;
|
||||||
|
amount: string | number;
|
||||||
|
payer: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AfterPermissions {
|
||||||
|
canEdit: boolean;
|
||||||
|
canDirectEdit: boolean;
|
||||||
|
requiresApproval: boolean;
|
||||||
|
reason: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OrderLineCostPayers {
|
||||||
|
[component: string]: string;
|
||||||
|
material: string;
|
||||||
|
labor: string;
|
||||||
|
accessories: string;
|
||||||
|
other: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CostParts {
|
||||||
|
[component: string]: number | null;
|
||||||
|
material: number | null;
|
||||||
|
labor: number | null;
|
||||||
|
accessories: number | null;
|
||||||
|
other: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CostMode {
|
||||||
|
mode: string;
|
||||||
|
rate?: number | null;
|
||||||
|
poolId?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Charge {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
amount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LinePool {
|
||||||
|
poolId: string;
|
||||||
|
date: string;
|
||||||
|
status: string;
|
||||||
|
amount: number;
|
||||||
|
quantity: number;
|
||||||
|
averageRate: number;
|
||||||
|
allocations: LinePoolAllocations[];
|
||||||
|
revision: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Known {
|
||||||
|
[key: `${string}Cost`]: number | undefined;
|
||||||
|
assistant2Cost?: number;
|
||||||
|
sale: number;
|
||||||
|
material: number;
|
||||||
|
laborAndFees: number;
|
||||||
|
unallocated: number;
|
||||||
|
totalCost: number;
|
||||||
|
profit: number;
|
||||||
|
ownerCost: number;
|
||||||
|
assistantCost: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BookCost {
|
||||||
|
kind: string;
|
||||||
|
component: string;
|
||||||
|
name: string;
|
||||||
|
source: string;
|
||||||
|
amount: number;
|
||||||
|
payer: string;
|
||||||
|
materialPoolId?: string;
|
||||||
|
calculation?: BookCostCalculation;
|
||||||
|
excluded?: boolean;
|
||||||
|
priceLockSource?: string;
|
||||||
|
after_sale_id?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Counts {
|
||||||
|
[key: `${string}Cost`]: number;
|
||||||
|
assistant2Cost: number;
|
||||||
|
sale: number;
|
||||||
|
material: number;
|
||||||
|
laborAndFees: number;
|
||||||
|
unallocated: number;
|
||||||
|
totalCost: number;
|
||||||
|
profit: number;
|
||||||
|
ownerCost: number;
|
||||||
|
assistantCost: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LockActivityRow {
|
||||||
|
id: string;
|
||||||
|
price_lock_id: string;
|
||||||
|
date: string;
|
||||||
|
kind: string;
|
||||||
|
amount: number;
|
||||||
|
account?: string;
|
||||||
|
number: string;
|
||||||
|
customer: string;
|
||||||
|
product?: string;
|
||||||
|
actor?: string;
|
||||||
|
created?: string;
|
||||||
|
line_index?: null | number;
|
||||||
|
voided?: number;
|
||||||
|
payer?: string;
|
||||||
|
source?: string;
|
||||||
|
quantity?: number;
|
||||||
|
rate?: number;
|
||||||
|
component?: string;
|
||||||
|
order_id?: string;
|
||||||
|
note?: string;
|
||||||
|
name?: string;
|
||||||
|
excluded?: boolean;
|
||||||
|
calculation?: null;
|
||||||
|
paper_number?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LockActivitySummary {
|
||||||
|
receipt: number;
|
||||||
|
refund: number;
|
||||||
|
net: number;
|
||||||
|
ownerOutlay: number;
|
||||||
|
assistantOutlay: number;
|
||||||
|
eventCount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ReceiptSummaryChannels {
|
||||||
|
channel: string;
|
||||||
|
name: string;
|
||||||
|
receipt: number;
|
||||||
|
refund: number;
|
||||||
|
net: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CostSummary {
|
||||||
|
total: number;
|
||||||
|
netReceived: number;
|
||||||
|
directCost: number;
|
||||||
|
goodsCost: number | null;
|
||||||
|
profit: number | null;
|
||||||
|
settlementDue: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface InventoryChange {
|
||||||
|
legacyCountNotice?: string;
|
||||||
|
before: InventoryRow[];
|
||||||
|
after: InventoryRow[];
|
||||||
|
changes: InventoryRow[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface InventoryRow {
|
||||||
|
stockCount?: number | null;
|
||||||
|
date: string;
|
||||||
|
pocket: string;
|
||||||
|
mg: number;
|
||||||
|
kind?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ActionRule {
|
||||||
|
eligible: boolean;
|
||||||
|
reason: string;
|
||||||
|
directToday?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Refund {
|
||||||
|
amount: number;
|
||||||
|
account: string;
|
||||||
|
payer: string;
|
||||||
|
reference: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AfterSummary {
|
||||||
|
refundAmount: number;
|
||||||
|
retainedAmount: number;
|
||||||
|
materialReturnedCost: number;
|
||||||
|
laborRestockedCost: number;
|
||||||
|
costLoss: number;
|
||||||
|
directCost: number;
|
||||||
|
profit: number;
|
||||||
|
profitAdjustment: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AfterSaleLine {
|
||||||
|
lineIndex: number;
|
||||||
|
name: string;
|
||||||
|
code: string;
|
||||||
|
quantity: number;
|
||||||
|
pocket: string;
|
||||||
|
disposition: string;
|
||||||
|
stockCount: null;
|
||||||
|
materialReturnedCost: number;
|
||||||
|
laborRestockedCost: number;
|
||||||
|
laborPayer: string;
|
||||||
|
costLoss: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LinePoolAllocations {
|
||||||
|
payer: string;
|
||||||
|
amount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BookCostCalculation {
|
||||||
|
rate: number;
|
||||||
|
quantity: number;
|
||||||
|
weighted?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Settlement {
|
||||||
|
bucket: string;
|
||||||
|
id: string;
|
||||||
|
date: string;
|
||||||
|
amount: number;
|
||||||
|
kind: string;
|
||||||
|
note: string;
|
||||||
|
actor: string;
|
||||||
|
}
|
||||||
|
export interface RelatedOrder {
|
||||||
|
id: string;
|
||||||
|
number: string;
|
||||||
|
date: string;
|
||||||
|
customer: string;
|
||||||
|
before: OrderRecord;
|
||||||
|
after: OrderRecord;
|
||||||
|
summary: ChangeSummary;
|
||||||
|
}
|
||||||
|
export interface LockImpact {
|
||||||
|
materialAmount: number | null;
|
||||||
|
usedMaterialAmount?: number | null;
|
||||||
|
leftoverCost?: number | null;
|
||||||
|
allocations: { payer: string; amount: number }[];
|
||||||
|
}
|
||||||
|
export interface RelatedLock {
|
||||||
|
id: string;
|
||||||
|
number: string;
|
||||||
|
date: string;
|
||||||
|
customer: string;
|
||||||
|
before: LockImpact;
|
||||||
|
after: LockImpact;
|
||||||
|
}
|
||||||
|
export interface LockCosts {
|
||||||
|
date?: string;
|
||||||
|
lines?: LockCosts[];
|
||||||
|
lineId?: string;
|
||||||
|
materialSource?: string;
|
||||||
|
buyRate?: number;
|
||||||
|
buyPayer?: string;
|
||||||
|
materialAmount?: number | null;
|
||||||
|
extraRate?: number;
|
||||||
|
extraPayer?: string;
|
||||||
|
}
|
||||||
|
export interface Filters {
|
||||||
|
mode: string;
|
||||||
|
date: string;
|
||||||
|
from: string;
|
||||||
|
to: string;
|
||||||
|
q: string;
|
||||||
|
status: string;
|
||||||
|
member: string;
|
||||||
|
pocket: string;
|
||||||
|
}
|
||||||
|
export interface ReviewList<T> {
|
||||||
|
requests: T[];
|
||||||
|
counts: Record<string, number>;
|
||||||
|
canApprove?: boolean;
|
||||||
|
}
|
||||||
|
export interface DetailEntry<T> {
|
||||||
|
id: string;
|
||||||
|
revision: number;
|
||||||
|
user: string;
|
||||||
|
data?: T;
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type MoneyKey =
|
||||||
|
| 'sale'
|
||||||
|
| 'material'
|
||||||
|
| 'laborAndFees'
|
||||||
|
| 'unallocated'
|
||||||
|
| 'totalCost'
|
||||||
|
| 'profit'
|
||||||
|
| 'ownerCost'
|
||||||
|
| 'assistantCost'
|
||||||
|
| `${string}Cost`;
|
||||||
|
export interface ChangeActionInput {
|
||||||
|
date?: string;
|
||||||
|
amount?: string;
|
||||||
|
account?: string;
|
||||||
|
payer?: string;
|
||||||
|
note?: string;
|
||||||
|
reference?: string;
|
||||||
|
afterSale?: object;
|
||||||
|
returnCounts?: (string | number | null)[];
|
||||||
|
returnPockets?: string[];
|
||||||
|
fee_items?: { note: string; amount: string; payer: string }[];
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { useState, useEffect, useEffectEvent } from 'react';
|
||||||
|
export type Queue = 'change' | 'ownership' | 'cancellation' | 'after-sale';
|
||||||
|
export const queues: readonly (readonly [Queue, string, string, string, string])[] = [
|
||||||
|
['change', '/api/order-changes', '待变更复核', 'open-order-changes', 'order-changes-entry'],
|
||||||
|
['ownership', '/api/order-ownership-changes', '归属复核', 'order-ownership-open-list', 'order-ownership-entry'],
|
||||||
|
['cancellation', '/api/order-cancellations', '待取消复核', 'open-order-cancellations', 'order-cancellations-entry'],
|
||||||
|
['after-sale', '/api/after-sales/changes', '售后修改', 'after-sale-changes-open', 'after-sale-changes-entry'],
|
||||||
|
];
|
||||||
|
|
||||||
|
export function useRead<T>(
|
||||||
|
read: () => Promise<T>,
|
||||||
|
key: string | false | null | undefined,
|
||||||
|
): { value?: T; error?: string } {
|
||||||
|
const [entry, set] = useState<{ key: string; value?: T; error?: string } | null>(null);
|
||||||
|
const task = useEffectEvent(read);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!key) return;
|
||||||
|
let active = true;
|
||||||
|
Promise.resolve()
|
||||||
|
.then(() => task())
|
||||||
|
.then(
|
||||||
|
value => {
|
||||||
|
if (active) set({ key, value });
|
||||||
|
},
|
||||||
|
error => {
|
||||||
|
if (active) set({ key, error: error.message });
|
||||||
|
},
|
||||||
|
);
|
||||||
|
return () => {
|
||||||
|
active = false;
|
||||||
|
};
|
||||||
|
}, [key]);
|
||||||
|
return entry && entry.key === key ? entry : {};
|
||||||
|
}
|
||||||
@@ -1,10 +1,11 @@
|
|||||||
|
import type { OrderContext } from './viewTypes';
|
||||||
import { sharedViews } from './views/sharedViews';
|
import { sharedViews } from './views/sharedViews';
|
||||||
import { orderBook } from './views/orderBook';
|
import { orderBook } from './views/orderBook';
|
||||||
import { orderDetail } from './views/orderDetail';
|
import { orderDetail } from './views/orderDetail';
|
||||||
import { orderActions } from './views/orderActions';
|
import { orderActions } from './views/orderActions';
|
||||||
import { orderReviews } from './views/orderReviews';
|
import { orderReviews } from './views/orderReviews';
|
||||||
import { afterSales } from './views/afterSales';
|
import { afterSales } from './views/afterSales';
|
||||||
export function orderViews(context) {
|
export function orderViews(context: OrderContext) {
|
||||||
const shared = sharedViews(context);
|
const shared = sharedViews(context);
|
||||||
return {
|
return {
|
||||||
...shared,
|
...shared,
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import type { OrderRecord } from './orderData';
|
||||||
|
|
||||||
|
export const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||||
|
value !== null && typeof value === 'object';
|
||||||
|
export const errorStatus = (error: unknown) => (isRecord(error) && typeof error.status === 'number' ? error.status : 0);
|
||||||
|
export const errorMessage = (error: unknown) => (error instanceof Error ? error.message : String(error));
|
||||||
|
|
||||||
|
function isOrderDetail(value: Record<string, unknown>): value is Record<string, unknown> & OrderRecord {
|
||||||
|
return (
|
||||||
|
['date', 'number', 'status', 'member'].every(key => typeof value[key] === 'string') &&
|
||||||
|
['revision', 'total', 'balance', 'netReceived'].every(key => Number.isSafeInteger(value[key])) &&
|
||||||
|
['lines', 'payments', 'expenses', 'settlements', 'corrections', 'fee_items', 'pendingFees', 'audit'].every(key =>
|
||||||
|
Array.isArray(value[key]),
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
export function readOrderRecord(value: unknown, id: string): OrderRecord {
|
||||||
|
if (!isRecord(value) || value.id !== id) throw new Error('返回的订单与所选订单不一致,请重试读取。');
|
||||||
|
if (!isOrderDetail(value)) throw new Error('订单详情未完整返回,请重新读取订单。');
|
||||||
|
return value;
|
||||||
|
}
|
||||||
+22
-6
@@ -1,13 +1,29 @@
|
|||||||
import { useCallback, useEffect, useRef } from 'react';
|
import { useCallback, useEffect, useRef } from 'react';
|
||||||
|
|
||||||
|
import type { LedgerState } from '../../shared';
|
||||||
|
|
||||||
|
interface OrderAccess {
|
||||||
|
client: { user: string; busy: boolean; pending: () => unknown; api: (url: string) => Promise<unknown> };
|
||||||
|
state: { user: Pick<LedgerState['user'], 'id' | 'role'> };
|
||||||
|
id: string;
|
||||||
|
watch: boolean;
|
||||||
|
onLost: (message: string) => void;
|
||||||
|
}
|
||||||
|
interface ActiveOrder {
|
||||||
|
user: string;
|
||||||
|
id: string;
|
||||||
|
request: number;
|
||||||
|
}
|
||||||
|
|
||||||
export const ownershipNotice = '订单归属或权限已更新,本账号已不能查看这张订单。';
|
export const ownershipNotice = '订单归属或权限已更新,本账号已不能查看这张订单。';
|
||||||
export const ownershipNoticeKey = user => 'mm-order-access-notice-' + user;
|
export const ownershipNoticeKey = (user: string) => 'mm-order-access-notice-' + user;
|
||||||
const denied = error => [403, 404].includes(error?.status);
|
const denied = (error: unknown) =>
|
||||||
|
!!error && typeof error === 'object' && 'status' in error && (error.status === 403 || error.status === 404);
|
||||||
|
|
||||||
// 同一账号可以从“当天直接修改”降为“须申请”。只有订单归属查询也拒绝访问,才清除该账号的该单草稿。
|
// 同一账号可以从“当天直接修改”降为“须申请”。只有订单归属查询也拒绝访问,才清除该账号的该单草稿。
|
||||||
export function useOrderAccess({ client, state, id, watch, onLost }) {
|
export function useOrderAccess({ client, state, id, watch, onLost }: OrderAccess) {
|
||||||
const user = state.user.id;
|
const user = state.user.id;
|
||||||
const scope = useRef(null);
|
const scope = useRef<ActiveOrder | null>(null);
|
||||||
const lost = useRef(onLost);
|
const lost = useRef(onLost);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
lost.current = onLost;
|
lost.current = onLost;
|
||||||
@@ -20,7 +36,7 @@ export function useOrderAccess({ client, state, id, watch, onLost }) {
|
|||||||
};
|
};
|
||||||
}, [user, id]);
|
}, [user, id]);
|
||||||
const revoke = useCallback(
|
const revoke = useCallback(
|
||||||
(error, current = scope.current) => {
|
(error: unknown, current = scope.current) => {
|
||||||
if (state.user.role !== 'assistant' || !denied(error)) return false;
|
if (state.user.role !== 'assistant' || !denied(error)) return false;
|
||||||
if (!current || scope.current !== current || client.user !== current.user) return true;
|
if (!current || scope.current !== current || client.user !== current.user) return true;
|
||||||
localStorage.removeItem('mm-order-edit-' + user + '-' + id);
|
localStorage.removeItem('mm-order-edit-' + user + '-' + id);
|
||||||
@@ -45,7 +61,7 @@ export function useOrderAccess({ client, state, id, watch, onLost }) {
|
|||||||
}
|
}
|
||||||
return scope.current !== current || client.user !== user || request !== current.request;
|
return scope.current !== current || client.user !== user || request !== current.request;
|
||||||
}, [client, id, state.user.role, user, revoke]);
|
}, [client, id, state.user.role, user, revoke]);
|
||||||
const checkFailure = useCallback(error => (denied(error) ? check() : Promise.resolve(false)), [check]);
|
const checkFailure = useCallback((error: unknown) => (denied(error) ? check() : Promise.resolve(false)), [check]);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!watch || state.user.role !== 'assistant') return;
|
if (!watch || state.user.role !== 'assistant') return;
|
||||||
const focus = () => {
|
const focus = () => {
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import type { ReactNode } from 'react';
|
||||||
|
import type { LedgerState, SessionInfo } from '../../shared';
|
||||||
|
import type {
|
||||||
|
CancellationData,
|
||||||
|
ChangeData,
|
||||||
|
DetailEntry,
|
||||||
|
Filters,
|
||||||
|
OrderAfterSale,
|
||||||
|
OrderRecord,
|
||||||
|
OwnershipData,
|
||||||
|
} from './orderData';
|
||||||
|
import type { sharedViews } from './views/sharedViews';
|
||||||
|
|
||||||
|
export type SharedViews = ReturnType<typeof sharedViews>;
|
||||||
|
export type Options = ReadonlyArray<string | readonly [string, string, boolean?]>;
|
||||||
|
export interface OrderUi {
|
||||||
|
action?: string;
|
||||||
|
forceApproval?: boolean;
|
||||||
|
actionBlocked?: boolean;
|
||||||
|
retryBusy?: boolean;
|
||||||
|
retryKey?: string | null;
|
||||||
|
pendingKey?: string;
|
||||||
|
actionError?: string;
|
||||||
|
stale?: boolean;
|
||||||
|
formKey?: string | number;
|
||||||
|
date?: string;
|
||||||
|
lastCardBasis?: string;
|
||||||
|
values?: Record<string, string>;
|
||||||
|
paymentMethod?: string;
|
||||||
|
recipient?: string;
|
||||||
|
afterError?: string;
|
||||||
|
busy?: boolean;
|
||||||
|
approval?: boolean;
|
||||||
|
blocked?: boolean;
|
||||||
|
lines?: { pocket: string; disposition: string }[];
|
||||||
|
reasonRequired?: boolean;
|
||||||
|
retained?: string;
|
||||||
|
previewLoading?: boolean;
|
||||||
|
previewStatus?: string;
|
||||||
|
expenses?: ReactNode;
|
||||||
|
feedback?: ReactNode;
|
||||||
|
verified?: boolean;
|
||||||
|
preview?: { record: OrderAfterSale; signature?: string } | null;
|
||||||
|
}
|
||||||
|
export interface OrderContext {
|
||||||
|
state: LedgerState;
|
||||||
|
session: SessionInfo;
|
||||||
|
currentOrder?: OrderRecord;
|
||||||
|
orderBookFilters?: Filters;
|
||||||
|
detailForm?: ReactNode;
|
||||||
|
navigation?: ReactNode;
|
||||||
|
error?: string;
|
||||||
|
orderChangeDetail?: DetailEntry<ChangeData>;
|
||||||
|
orderCancellationDetail?: DetailEntry<CancellationData>;
|
||||||
|
orderOwnershipDetail?: DetailEntry<OwnershipData>;
|
||||||
|
orderAfterSaleFormEntry?: { id: string; revision: number; user: string; forceApproval?: boolean };
|
||||||
|
ui?: OrderUi;
|
||||||
|
orderChangeListStatus?: string;
|
||||||
|
orderOwnershipListStatus?: string;
|
||||||
|
orderCancellationListStatus?: string;
|
||||||
|
afterSaleChangesStatus?: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,201 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { Calc as LedgerCalc } from '../../../shared';
|
||||||
|
import type { OrderLine } from '../orderData';
|
||||||
|
import type { SharedViews } from '../viewTypes';
|
||||||
|
type CostModeKey = 'material' | 'labor';
|
||||||
|
type CostInputs = Record<string, string>;
|
||||||
|
type LineProps = { line: OrderLine; index: number; members: SharedViews['teamMemberOptions']; fallback: string } & Pick<
|
||||||
|
SharedViews,
|
||||||
|
'choice' | 'opts' | 'grams' | 'yuan'
|
||||||
|
>;
|
||||||
|
const asMoney = (value?: number | null) => (value == null ? '' : (value / 100).toFixed(2));
|
||||||
|
const costKeys = Object.keys(LedgerCalc.costLabels);
|
||||||
|
function costBreakdown(
|
||||||
|
line: OrderLine,
|
||||||
|
quantity: string | number,
|
||||||
|
parts: CostInputs,
|
||||||
|
modes: CostInputs,
|
||||||
|
rates: CostInputs,
|
||||||
|
) {
|
||||||
|
const input: {
|
||||||
|
unit: string;
|
||||||
|
quantity: string | number;
|
||||||
|
costParts: CostInputs;
|
||||||
|
costMaterial?: { mode: string; rate?: string };
|
||||||
|
costLabor?: { mode: string; rate?: string };
|
||||||
|
} = { unit: line.unit, quantity, costParts: parts };
|
||||||
|
for (const [key, property] of [
|
||||||
|
['material', 'costMaterial'],
|
||||||
|
['labor', 'costLabor'],
|
||||||
|
] as const) {
|
||||||
|
input[property] = modes[key] === 'gram' ? { mode: 'gram', rate: rates[key] } : { mode: 'total' };
|
||||||
|
}
|
||||||
|
return LedgerCalc.purchaseCosts(input);
|
||||||
|
}
|
||||||
|
export function LegacyCostRow({ line, index, members, fallback, choice, opts, grams, yuan }: LineProps) {
|
||||||
|
const prefix = 'cost-' + index + '-';
|
||||||
|
const quantity = line.unit === 'g' ? (line.quantity / 1000).toFixed(3) : line.quantity;
|
||||||
|
const initialParts = Object.fromEntries(
|
||||||
|
costKeys.map(key => [
|
||||||
|
key,
|
||||||
|
line.costParts ? asMoney(line.costParts[key]) : ['accessories', 'other'].includes(key) ? '0' : '',
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
const originalMode = ['gram', 'total'].includes(line.costMaterial?.mode ?? '')
|
||||||
|
? line.costMaterial!.mode
|
||||||
|
: initialParts.material === ''
|
||||||
|
? 'gram'
|
||||||
|
: 'total';
|
||||||
|
const [parts, setParts] = useState(initialParts);
|
||||||
|
const [modes, setModes] = useState({
|
||||||
|
material: line.unit === 'g' ? originalMode : 'total',
|
||||||
|
labor: line.unit === 'g' ? line.costLabor?.mode || 'total' : 'total',
|
||||||
|
});
|
||||||
|
const [rates, setRates] = useState({
|
||||||
|
material: asMoney(line.costMaterial?.rate),
|
||||||
|
labor: asMoney(line.costLabor?.rate),
|
||||||
|
});
|
||||||
|
const originalTotal = line.unit !== 'g' || originalMode === 'total' ? initialParts.material : '';
|
||||||
|
const changePart = (key: string, value: string) => setParts(old => ({ ...old, [key]: value }));
|
||||||
|
const updateMode = (key: CostModeKey, value: string, computed: string) => {
|
||||||
|
if (value === 'total' && (key === 'labor' || parts.material === '')) changePart(key, computed);
|
||||||
|
setModes(old => ({ ...old, [key]: value }));
|
||||||
|
};
|
||||||
|
const amount = (key: string, title: string, value: string, gram = false) => (
|
||||||
|
<label>
|
||||||
|
{title}
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
name={prefix + key}
|
||||||
|
min="0"
|
||||||
|
step="0.01"
|
||||||
|
placeholder="开单前必填,没有填0"
|
||||||
|
required={!gram}
|
||||||
|
readOnly={gram}
|
||||||
|
value={value}
|
||||||
|
onChange={event => changePart(key, event.target.value)}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
);
|
||||||
|
function group(key: CostModeKey) {
|
||||||
|
const material = key === 'material',
|
||||||
|
gram = modes[key] === 'gram';
|
||||||
|
const payer = line.costPayers?.[key] ?? line.payer ?? fallback;
|
||||||
|
let value = parts[key],
|
||||||
|
formula;
|
||||||
|
if (gram) {
|
||||||
|
try {
|
||||||
|
const result = costBreakdown(
|
||||||
|
line,
|
||||||
|
quantity,
|
||||||
|
{ material: '0', labor: '0', accessories: '0', other: '0' },
|
||||||
|
{ material: 'total', labor: 'total', [key]: 'gram' },
|
||||||
|
rates,
|
||||||
|
).parts[key];
|
||||||
|
value = asMoney(result);
|
||||||
|
formula =
|
||||||
|
result == null
|
||||||
|
? material
|
||||||
|
? '填写每克进货料价后,系统自动乘以本行克重。'
|
||||||
|
: '填写每克工费后自动乘以克重。'
|
||||||
|
: quantity + 'g × ' + rates[key] + '元/克 = ' + yuan(result) + '元';
|
||||||
|
} catch (err) {
|
||||||
|
value = '';
|
||||||
|
formula = err instanceof Error ? err.message : String(err);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
formula = material
|
||||||
|
? line.unit === 'g'
|
||||||
|
? '直接填写本行料费合计,不再乘以克重。'
|
||||||
|
: '按件商品请填写本行料费合计' + (rates.material ? ';每克料价已保留,切回g可恢复' : '') + '。'
|
||||||
|
: '直接填写本行总工费。';
|
||||||
|
}
|
||||||
|
const options = members(false, { selected: payer });
|
||||||
|
return (
|
||||||
|
<div className={'purchase-' + key} data-prefix={prefix} data-mode={modes[key]}>
|
||||||
|
<div className="grid purchase-cost-grid">
|
||||||
|
<label>
|
||||||
|
{material ? '进货料费方式' : '进货工费方式'}
|
||||||
|
<select
|
||||||
|
name={prefix + key + 'Mode'}
|
||||||
|
value={modes[key]}
|
||||||
|
onChange={event => updateMode(key, event.target.value, value)}
|
||||||
|
>
|
||||||
|
<option value="gram" disabled={line.unit !== 'g'}>
|
||||||
|
{material ? '按克料价' : '克工费'}
|
||||||
|
</option>
|
||||||
|
<option value="total">{material ? '直接填总料费' : '总工费'}</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label hidden={!gram}>
|
||||||
|
{material ? '进货料价(元/克)' : '进货克工费(元/克)'}
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
name={prefix + key + 'Rate'}
|
||||||
|
min="0"
|
||||||
|
step="0.01"
|
||||||
|
value={rates[key]}
|
||||||
|
placeholder={material ? '填写每克进货料价' : '填写每克工费'}
|
||||||
|
disabled={!gram}
|
||||||
|
required={gram}
|
||||||
|
onChange={event => setRates(old => ({ ...old, [key]: event.target.value }))}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
{amount(key, material ? '料费成本合计(元)' : '进货总工费(元)', value, gram)}
|
||||||
|
<label className="purchase-payer">
|
||||||
|
{material ? '料费付款人' : '进货工费付款人'}
|
||||||
|
<select
|
||||||
|
required
|
||||||
|
name={prefix + key + 'Payer'}
|
||||||
|
defaultValue={options.some(([id]) => id === payer) ? payer : ''}
|
||||||
|
>
|
||||||
|
{options.some(([id]) => id === payer) ? null : (
|
||||||
|
<option value="" disabled>
|
||||||
|
请选择
|
||||||
|
</option>
|
||||||
|
)}
|
||||||
|
{opts(options)}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<p className="purchase-formula small muted" aria-live="polite">
|
||||||
|
{formula}
|
||||||
|
</p>
|
||||||
|
{material && (
|
||||||
|
<p className="purchase-original small muted" hidden={!originalTotal}>
|
||||||
|
{originalTotal &&
|
||||||
|
'已保留原料费合计 ' + originalTotal + '元。原金额不会当成每克料价;切换按克后请填写实际进货料价。'}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let summary;
|
||||||
|
try {
|
||||||
|
summary = costBreakdown(line, quantity, parts, modes, rates).total;
|
||||||
|
} catch {
|
||||||
|
summary = null;
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div className="internal cost-editor">
|
||||||
|
<h3>
|
||||||
|
{line.name} · {line.unit === 'g' ? grams(line.quantity) + 'g' : line.quantity + '件'}
|
||||||
|
</h3>
|
||||||
|
<div className="cost-fallback-payer">
|
||||||
|
{choice('配件及其他成本付款人', 'goodsPayer', members(), line.payer || 'owner')}
|
||||||
|
</div>
|
||||||
|
{!line.costParts && line.cost !== null && (
|
||||||
|
<p className="small">原记录未分项,总额 ¥{yuan(line.cost)};请按凭据拆分,不要把总额再填入每个项目。</p>
|
||||||
|
)}
|
||||||
|
<div className="cost-fields grid">
|
||||||
|
{group('material')}
|
||||||
|
{group('labor')}
|
||||||
|
{amount('accessories', '配件成本(元,本行合计)', parts.accessories)}
|
||||||
|
{amount('other', '其他货品成本(元,本行合计)', parts.other)}
|
||||||
|
</div>
|
||||||
|
<div className="cost-summary small">
|
||||||
|
本行货品成本合计:{summary == null ? '请补齐(没有的项目填0)' : '¥' + yuan(summary)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
+134
-77
@@ -1,7 +1,23 @@
|
|||||||
|
import type {
|
||||||
|
IndependentDetail,
|
||||||
|
IndependentRecord,
|
||||||
|
IndependentRequest,
|
||||||
|
IndependentValues,
|
||||||
|
OrderRecord,
|
||||||
|
OrderLine,
|
||||||
|
ReviewList,
|
||||||
|
} from '../orderData';
|
||||||
|
import type { OrderContext, SharedViews } from '../viewTypes';
|
||||||
import { Children } from 'react';
|
import { Children } from 'react';
|
||||||
import { Calc as LedgerCalc, Values } from '../../../shared';
|
import { Calc as LedgerCalc, Values } from '../../../shared';
|
||||||
|
function object(value: unknown): value is Record<string, unknown> {
|
||||||
|
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||||
|
}
|
||||||
|
function revision(value: unknown): value is number {
|
||||||
|
return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
|
||||||
|
}
|
||||||
export function afterSales(
|
export function afterSales(
|
||||||
{ afterSaleChangesStatus, state, ui, orderAfterSaleFormEntry, currentOrder },
|
{ afterSaleChangesStatus, state, ui = {}, orderAfterSaleFormEntry, currentOrder }: OrderContext,
|
||||||
{
|
{
|
||||||
button,
|
button,
|
||||||
validOrderDate,
|
validOrderDate,
|
||||||
@@ -28,39 +44,47 @@ export function afterSales(
|
|||||||
activePocketKeys,
|
activePocketKeys,
|
||||||
orderChangeUser,
|
orderChangeUser,
|
||||||
stockCountValue,
|
stockCountValue,
|
||||||
},
|
}: SharedViews,
|
||||||
) {
|
) {
|
||||||
function validateAfterSaleDetail(detail, id) {
|
function readAfterSaleDetail(detail: unknown, id: string): detail is IndependentDetail {
|
||||||
const record = detail?.record,
|
if (!object(detail) || detail.id !== id || !revision(detail.revision) || !object(detail.record)) return false;
|
||||||
permissions = detail?.permissions;
|
const record = detail.record,
|
||||||
if (
|
permissions = detail.permissions;
|
||||||
!record ||
|
return (
|
||||||
detail.id !== id ||
|
record.id === id &&
|
||||||
record.id !== id ||
|
record.revision === detail.revision &&
|
||||||
!Number.isSafeInteger(detail.revision) ||
|
typeof record.actor === 'string' &&
|
||||||
detail.revision < 1 ||
|
typeof record.created === 'string' &&
|
||||||
record.revision !== detail.revision ||
|
typeof record.member === 'string' &&
|
||||||
!afterSaleValuesValid(record) ||
|
teamMemberKeys().includes(record.member) &&
|
||||||
!teamMemberKeys().includes(record.member) ||
|
afterSaleValuesValid(record) &&
|
||||||
typeof permissions?.canEdit !== 'boolean' ||
|
object(permissions) &&
|
||||||
typeof permissions.canDirectEdit !== 'boolean' ||
|
typeof permissions.canEdit === 'boolean' &&
|
||||||
typeof permissions.requiresApproval !== 'boolean' ||
|
typeof permissions.canDirectEdit === 'boolean' &&
|
||||||
!Array.isArray(detail.history)
|
typeof permissions.requiresApproval === 'boolean' &&
|
||||||
)
|
typeof permissions.reason === 'string' &&
|
||||||
throw new Error('售后记录资料未完整返回,请重新读取后再修改。');
|
object(detail.values) &&
|
||||||
if (detail.pending && (validateAfterSaleRequest(detail.pending).afterSaleId !== id || permissions.canEdit))
|
typeof detail.values.amount === 'string' &&
|
||||||
|
Array.isArray(detail.history) &&
|
||||||
|
detail.history.every(request => validateAfterSaleRequest(request)) &&
|
||||||
|
(detail.pending === null || !!validateAfterSaleRequest(detail.pending))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
function validateAfterSaleDetail(detail: unknown, id: string) {
|
||||||
|
if (!readAfterSaleDetail(detail, id)) throw new Error('售后记录资料未完整返回,请重新读取后再修改。');
|
||||||
|
if (detail.pending && (detail.pending.afterSaleId !== id || detail.permissions.canEdit))
|
||||||
throw new Error('售后修改状态不一致,请重新读取。');
|
throw new Error('售后修改状态不一致,请重新读取。');
|
||||||
for (const request of detail.history)
|
for (const request of detail.history)
|
||||||
if (validateAfterSaleRequest(request).afterSaleId !== id) throw new Error('售后修改历史不一致,请重新读取。');
|
if (request.afterSaleId !== id) throw new Error('售后修改历史不一致,请重新读取。');
|
||||||
return detail;
|
return detail;
|
||||||
}
|
}
|
||||||
function independentReviewForm(kind, request) {
|
function independentReviewForm(kind: string, request: IndependentRequest) {
|
||||||
return (
|
return (
|
||||||
<form id="after-sale-review-form" data-id={request.id} data-kind={kind}>
|
<form id="after-sale-review-form" data-id={request.id} data-kind={kind}>
|
||||||
<h3>{kind === 'approve' ? '同意售后修改' : '驳回售后修改'}</h3>
|
<h3>{kind === 'approve' ? '同意售后修改' : '驳回售后修改'}</h3>
|
||||||
<label>
|
<label>
|
||||||
{kind === 'approve' ? '复核备注(选填)' : '驳回意见'}
|
{kind === 'approve' ? '复核备注(选填)' : '驳回意见'}
|
||||||
<textarea disabled={ui.blocked} name="note" rows="2" maxLength="200" required={kind === 'reject'}></textarea>
|
<textarea disabled={ui.blocked} name="note" rows={2} maxLength={200} required={kind === 'reject'}></textarea>
|
||||||
</label>
|
</label>
|
||||||
{kind === 'approve' ? (
|
{kind === 'approve' ? (
|
||||||
<label className="check">
|
<label className="check">
|
||||||
@@ -79,7 +103,7 @@ export function afterSales(
|
|||||||
</form>
|
</form>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function independentReview(request, kind) {
|
function independentReview(request: IndependentRequest, kind?: string | null) {
|
||||||
const canReview = state.user.role === 'owner' && request.status === 'pending';
|
const canReview = state.user.role === 'owner' && request.status === 'pending';
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -144,7 +168,7 @@ export function afterSales(
|
|||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function afterSaleHistoryHTML(request) {
|
function afterSaleHistoryHTML(request: IndependentRequest) {
|
||||||
return (
|
return (
|
||||||
<li>
|
<li>
|
||||||
<strong>{afterSaleStatus(request)}</strong>
|
<strong>{afterSaleStatus(request)}</strong>
|
||||||
@@ -175,7 +199,7 @@ export function afterSales(
|
|||||||
</li>
|
</li>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function afterSaleRecordHTML(record) {
|
function afterSaleRecordHTML(record: IndependentRecord) {
|
||||||
return (
|
return (
|
||||||
<dl className="after-sale-facts">
|
<dl className="after-sale-facts">
|
||||||
{Children.toArray(
|
{Children.toArray(
|
||||||
@@ -196,9 +220,13 @@ export function afterSales(
|
|||||||
</dl>
|
</dl>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function afterSaleComparisonHTML(raw) {
|
function afterSaleComparisonHTML(raw: IndependentRequest) {
|
||||||
const request = validateAfterSaleRequest(raw),
|
const request = validateAfterSaleRequest(raw),
|
||||||
pair = (title, key, format = value => value) => {
|
pair = <K extends keyof IndependentValues>(
|
||||||
|
title: string,
|
||||||
|
key: K,
|
||||||
|
format: (value: IndependentValues[K]) => string | number = value => value,
|
||||||
|
) => {
|
||||||
const changed = request.before[key] !== request.after[key];
|
const changed = request.before[key] !== request.after[key];
|
||||||
return (
|
return (
|
||||||
<tr
|
<tr
|
||||||
@@ -231,14 +259,14 @@ export function afterSales(
|
|||||||
{pair('售后日期', 'date')}
|
{pair('售后日期', 'date')}
|
||||||
{pair('售后项目', 'project')}
|
{pair('售后项目', 'project')}
|
||||||
{pair('客户', 'customer')}
|
{pair('客户', 'customer')}
|
||||||
{pair('金额', 'amount', value => '¥' + yuan(value))}
|
{pair('金额', 'amount', value => '¥' + yuan(Number(value)))}
|
||||||
{pair('谁支付', 'payer', teamMemberName)}
|
{pair('谁支付', 'payer', teamMemberName)}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function editIndependentSale(detail) {
|
function editIndependentSale(detail: IndependentDetail) {
|
||||||
const record = detail.record,
|
const record = detail.record,
|
||||||
request = detail.pending;
|
request = detail.pending;
|
||||||
const pendingHTML = request ? (
|
const pendingHTML = request ? (
|
||||||
@@ -274,11 +302,11 @@ export function afterSales(
|
|||||||
})}
|
})}
|
||||||
{field('售后项目', 'project', record.project, 'text', {
|
{field('售后项目', 'project', record.project, 'text', {
|
||||||
required: true,
|
required: true,
|
||||||
maxLength: '100',
|
maxLength: 100,
|
||||||
})}
|
})}
|
||||||
{field('客户', 'customer', record.customer, 'text', {
|
{field('客户', 'customer', record.customer, 'text', {
|
||||||
required: true,
|
required: true,
|
||||||
maxLength: '60',
|
maxLength: 60,
|
||||||
})}
|
})}
|
||||||
{moneyField('金额(元)', 'amount', (record.amount / 100).toFixed(2))}
|
{moneyField('金额(元)', 'amount', (record.amount / 100).toFixed(2))}
|
||||||
{orderMemberField(record.member, true)}
|
{orderMemberField(record.member, true)}
|
||||||
@@ -293,7 +321,7 @@ export function afterSales(
|
|||||||
</div>
|
</div>
|
||||||
<label>
|
<label>
|
||||||
修改说明(选填)
|
修改说明(选填)
|
||||||
<textarea name="reason" rows="2" maxLength="200" placeholder="例如:售后金额或付款人录错。"></textarea>
|
<textarea name="reason" rows={2} maxLength={200} placeholder="例如:售后金额或付款人录错。"></textarea>
|
||||||
</label>
|
</label>
|
||||||
</fieldset>
|
</fieldset>
|
||||||
<div id="after-sale-edit-error" aria-live="polite">
|
<div id="after-sale-edit-error" aria-live="polite">
|
||||||
@@ -357,12 +385,12 @@ export function afterSales(
|
|||||||
})}
|
})}
|
||||||
{field('售后项目', 'project', '', 'text', {
|
{field('售后项目', 'project', '', 'text', {
|
||||||
required: true,
|
required: true,
|
||||||
maxLength: '100',
|
maxLength: 100,
|
||||||
placeholder: '例如:维修、补寄快递',
|
placeholder: '例如:维修、补寄快递',
|
||||||
})}
|
})}
|
||||||
{field('客户', 'customer', '', 'text', {
|
{field('客户', 'customer', '', 'text', {
|
||||||
required: true,
|
required: true,
|
||||||
maxLength: '60',
|
maxLength: 60,
|
||||||
placeholder: '客户称呼或代号',
|
placeholder: '客户称呼或代号',
|
||||||
})}
|
})}
|
||||||
{moneyField('金额(元)', 'amount', '')}
|
{moneyField('金额(元)', 'amount', '')}
|
||||||
@@ -373,7 +401,7 @@ export function afterSales(
|
|||||||
<option value="" disabled>
|
<option value="" disabled>
|
||||||
请选择
|
请选择
|
||||||
</option>
|
</option>
|
||||||
{opts(teamMemberOptions(), '')}
|
{opts(teamMemberOptions())}
|
||||||
</select>
|
</select>
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
@@ -393,16 +421,21 @@ export function afterSales(
|
|||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function orderAfterSaleAccountPayer(account) {
|
function orderAfterSaleAccountPayer(account: string) {
|
||||||
return accountIdentity(account)?.member || currentMember();
|
return accountIdentity(account)?.member || currentMember();
|
||||||
}
|
}
|
||||||
const materialPoolMg = Values.positiveMg;
|
const materialPoolMg = Values.positiveMg;
|
||||||
function orderAfterSaleInput(form) {
|
function orderAfterSaleInput(form: HTMLFormElement) {
|
||||||
const order = currentOrder,
|
const order = currentOrder,
|
||||||
entry = orderAfterSaleFormEntry,
|
entry = orderAfterSaleFormEntry,
|
||||||
get = name => String(form.querySelector(`[name="${name}"]`)?.value ?? '').trim();
|
get = (name: string) =>
|
||||||
|
String(
|
||||||
|
form.querySelector<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>(`[name="${name}"]`)?.value ??
|
||||||
|
'',
|
||||||
|
).trim();
|
||||||
if (
|
if (
|
||||||
!entry ||
|
!entry ||
|
||||||
|
!order ||
|
||||||
entry.id !== order?.id ||
|
entry.id !== order?.id ||
|
||||||
entry.user !== orderChangeUser() ||
|
entry.user !== orderChangeUser() ||
|
||||||
entry.revision !== order.revision ||
|
entry.revision !== order.revision ||
|
||||||
@@ -417,7 +450,11 @@ export function afterSales(
|
|||||||
const rows = [...form.querySelectorAll('[data-after-sale-line]')];
|
const rows = [...form.querySelectorAll('[data-after-sale-line]')];
|
||||||
if (rows.length !== order.lines.length) throw new Error('请核对全部退回商品后再提交。');
|
if (rows.length !== order.lines.length) throw new Error('请核对全部退回商品后再提交。');
|
||||||
const lines = rows.map((row, lineIndex) => {
|
const lines = rows.map((row, lineIndex) => {
|
||||||
const read = name => String(row.querySelector(`[name="${name}"]`)?.value ?? '').trim(),
|
const read = (name: string) =>
|
||||||
|
String(
|
||||||
|
row.querySelector<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>(`[name="${name}"]`)?.value ??
|
||||||
|
'',
|
||||||
|
).trim(),
|
||||||
original = order.lines[lineIndex],
|
original = order.lines[lineIndex],
|
||||||
quantity = read('return_quantity'),
|
quantity = read('return_quantity'),
|
||||||
mg = materialPoolMg(quantity),
|
mg = materialPoolMg(quantity),
|
||||||
@@ -436,7 +473,12 @@ export function afterSales(
|
|||||||
title: '商品 ' + (lineIndex + 1) + '实际退回数量(对)',
|
title: '商品 ' + (lineIndex + 1) + '实际退回数量(对)',
|
||||||
})
|
})
|
||||||
: null;
|
: null;
|
||||||
if (Number.isSafeInteger(original.stockCount) && stockCount > original.stockCount)
|
if (
|
||||||
|
original.stockCount != null &&
|
||||||
|
stockCount != null &&
|
||||||
|
Number.isSafeInteger(original.stockCount) &&
|
||||||
|
stockCount > original.stockCount
|
||||||
|
)
|
||||||
throw new Error('商品 ' + (lineIndex + 1) + '实际退回对数不能超过原出库对数。');
|
throw new Error('商品 ' + (lineIndex + 1) + '实际退回对数不能超过原出库对数。');
|
||||||
return {
|
return {
|
||||||
lineIndex,
|
lineIndex,
|
||||||
@@ -459,7 +501,11 @@ export function afterSales(
|
|||||||
const reference = get('refund_reference');
|
const reference = get('refund_reference');
|
||||||
if (reference.length > 100) throw new Error('退款凭据备注最多100字。');
|
if (reference.length > 100) throw new Error('退款凭据备注最多100字。');
|
||||||
const expenses = [...form.querySelectorAll('.order-after-sale-expense')].map(row => {
|
const expenses = [...form.querySelectorAll('.order-after-sale-expense')].map(row => {
|
||||||
const read = name => String(row.querySelector(`[name="${name}"]`)?.value ?? '').trim(),
|
const read = (name: string) =>
|
||||||
|
String(
|
||||||
|
row.querySelector<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>(`[name="${name}"]`)?.value ??
|
||||||
|
'',
|
||||||
|
).trim(),
|
||||||
amount = read('expense_amount'),
|
amount = read('expense_amount'),
|
||||||
note = read('expense_note'),
|
note = read('expense_note'),
|
||||||
payer = read('expense_payer');
|
payer = read('expense_payer');
|
||||||
@@ -491,12 +537,12 @@ export function afterSales(
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
function orderAfterSaleExpenseHTML(value = {}) {
|
function orderAfterSaleExpenseHTML(value: Partial<{ amount: string; note: string; payer: string }> = {}) {
|
||||||
return (
|
return (
|
||||||
<div className="order-after-sale-expense grid four">
|
<div className="order-after-sale-expense grid four">
|
||||||
{field('售后成本项目', 'expense_note', value.note || '', 'text', {
|
{field('售后成本项目', 'expense_note', value.note || '', 'text', {
|
||||||
required: true,
|
required: true,
|
||||||
maxLength: '150',
|
maxLength: 150,
|
||||||
placeholder: '如寄件费、重新编绳',
|
placeholder: '如寄件费、重新编绳',
|
||||||
})}
|
})}
|
||||||
{moneyField('实际成本(元)', 'expense_amount', value.amount ?? '')}
|
{moneyField('实际成本(元)', 'expense_amount', value.amount ?? '')}
|
||||||
@@ -508,7 +554,7 @@ export function afterSales(
|
|||||||
function orderAfterSalePocketKeys() {
|
function orderAfterSalePocketKeys() {
|
||||||
return activePocketKeys().filter(key => state.pocketCatalog?.some(row => row.key === key && row.self === true));
|
return activePocketKeys().filter(key => state.pocketCatalog?.some(row => row.key === key && row.self === true));
|
||||||
}
|
}
|
||||||
function orderAfterSaleLineHTML(line, index) {
|
function orderAfterSaleLineHTML(line: OrderLine, index: number) {
|
||||||
const pockets = orderAfterSalePocketKeys();
|
const pockets = orderAfterSalePocketKeys();
|
||||||
const pocket = ui.lines?.[index]?.pocket ?? (pockets.includes(line.pocket) ? line.pocket : pockets[0] || '');
|
const pocket = ui.lines?.[index]?.pocket ?? (pockets.includes(line.pocket) ? line.pocket : pockets[0] || '');
|
||||||
const disposition = ui.lines?.[index]?.disposition || 'stock';
|
const disposition = ui.lines?.[index]?.disposition || 'stock';
|
||||||
@@ -550,7 +596,7 @@ export function afterSales(
|
|||||||
pockets.map(key => [key, pocketLabel(key)]),
|
pockets.map(key => [key, pocketLabel(key)]),
|
||||||
pocket,
|
pocket,
|
||||||
)}
|
)}
|
||||||
{stockCountField(pocket, line.stockCount, {
|
{stockCountField(pocket, String(line.stockCount ?? ''), {
|
||||||
name: 'return_count',
|
name: 'return_count',
|
||||||
visible: disposition === 'stock' && pocketCountsEnabled(pocket),
|
visible: disposition === 'stock' && pocketCountsEnabled(pocket),
|
||||||
title: '实际退回数量(对)',
|
title: '实际退回数量(对)',
|
||||||
@@ -576,7 +622,7 @@ export function afterSales(
|
|||||||
? '本次提交原订单售后申请,店主同意后一次登记退货、退款、费用与利润调整。复核前原账保持原值。'
|
? '本次提交原订单售后申请,店主同意后一次登记退货、退款、费用与利润调整。复核前原账保持原值。'
|
||||||
: '核实后一次登记退货、实际退款与售后成本。系统只记账,退款须已在实际账户完成。';
|
: '核实后一次登记退货、实际退款与售后成本。系统只记账,退款须已在实际账户完成。';
|
||||||
}
|
}
|
||||||
function orderAfterSaleFormHTML(order) {
|
function orderAfterSaleFormHTML(order: OrderRecord) {
|
||||||
const receipts = order.payments?.filter(row => row.kind === 'receipt') || [],
|
const receipts = order.payments?.filter(row => row.kind === 'receipt') || [],
|
||||||
account =
|
account =
|
||||||
receipts.find(
|
receipts.find(
|
||||||
@@ -604,8 +650,8 @@ export function afterSales(
|
|||||||
售后原因
|
售后原因
|
||||||
<textarea
|
<textarea
|
||||||
name="reason"
|
name="reason"
|
||||||
rows="2"
|
rows={2}
|
||||||
maxLength="200"
|
maxLength={200}
|
||||||
required
|
required
|
||||||
placeholder="填写客户实际退货退款原因。"
|
placeholder="填写客户实际退货退款原因。"
|
||||||
></textarea>
|
></textarea>
|
||||||
@@ -623,7 +669,7 @@ export function afterSales(
|
|||||||
{choice('实际退款付款人', 'refund_payer', teamMemberOptions(), payer)}
|
{choice('实际退款付款人', 'refund_payer', teamMemberOptions(), payer)}
|
||||||
</div>
|
</div>
|
||||||
{field('退款凭据备注(选填)', 'refund_reference', '', 'text', {
|
{field('退款凭据备注(选填)', 'refund_reference', '', 'text', {
|
||||||
maxLength: '100',
|
maxLength: 100,
|
||||||
})}
|
})}
|
||||||
<div className="order-after-sale-retained">
|
<div className="order-after-sale-retained">
|
||||||
<span>本次扣留客户款(系统计算)</span>
|
<span>本次扣留客户款(系统计算)</span>
|
||||||
@@ -635,8 +681,8 @@ export function afterSales(
|
|||||||
<textarea
|
<textarea
|
||||||
name="deduction_reason"
|
name="deduction_reason"
|
||||||
required={ui.reasonRequired}
|
required={ui.reasonRequired}
|
||||||
rows="2"
|
rows={2}
|
||||||
maxLength="200"
|
maxLength={200}
|
||||||
placeholder="有扣留款时填写,如约定扣除不可退工费或实际损耗。"
|
placeholder="有扣留款时填写,如约定扣除不可退工费或实际损耗。"
|
||||||
></textarea>
|
></textarea>
|
||||||
</label>
|
</label>
|
||||||
@@ -687,7 +733,7 @@ export function afterSales(
|
|||||||
</form>
|
</form>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function afterSaleStatus(request) {
|
function afterSaleStatus(request: IndependentRequest) {
|
||||||
return (
|
return (
|
||||||
{
|
{
|
||||||
pending: '待店主审批',
|
pending: '待店主审批',
|
||||||
@@ -696,47 +742,58 @@ export function afterSales(
|
|||||||
}[request.status] || '状态待确认'
|
}[request.status] || '状态待确认'
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function afterSaleTime(value) {
|
function afterSaleTime(value: string | null) {
|
||||||
return String(value || '未提供')
|
return String(value || '未提供')
|
||||||
.replace('T', ' ')
|
.replace('T', ' ')
|
||||||
.replace(/\.\d{3}Z$/, ' UTC')
|
.replace(/\.\d{3}Z$/, ' UTC')
|
||||||
.replace(/Z$/, ' UTC');
|
.replace(/Z$/, ' UTC');
|
||||||
}
|
}
|
||||||
function afterSaleValuesValid(record) {
|
function afterSaleValuesValid(record: unknown): record is IndependentValues & { amount: number } {
|
||||||
return (
|
return (
|
||||||
record &&
|
object(record) &&
|
||||||
validOrderDate(record.date) &&
|
validOrderDate(record.date) &&
|
||||||
typeof record.project === 'string' &&
|
typeof record.project === 'string' &&
|
||||||
record.project.trim() &&
|
!!record.project.trim() &&
|
||||||
record.project.length <= 100 &&
|
record.project.length <= 100 &&
|
||||||
typeof record.customer === 'string' &&
|
typeof record.customer === 'string' &&
|
||||||
record.customer.trim() &&
|
!!record.customer.trim() &&
|
||||||
record.customer.length <= 60 &&
|
record.customer.length <= 60 &&
|
||||||
|
typeof record.amount === 'number' &&
|
||||||
Number.isSafeInteger(record.amount) &&
|
Number.isSafeInteger(record.amount) &&
|
||||||
record.amount >= 0 &&
|
record.amount >= 0 &&
|
||||||
|
typeof record.payer === 'string' &&
|
||||||
teamMemberKeys().includes(record.payer)
|
teamMemberKeys().includes(record.payer)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function validateAfterSaleRequest(request) {
|
function isRequest(request: unknown): request is IndependentRequest {
|
||||||
if (
|
return (
|
||||||
!request ||
|
object(request) &&
|
||||||
typeof request.id !== 'string' ||
|
typeof request.id === 'string' &&
|
||||||
!request.id ||
|
!!request.id &&
|
||||||
typeof request.afterSaleId !== 'string' ||
|
typeof request.afterSaleId === 'string' &&
|
||||||
!request.afterSaleId ||
|
!!request.afterSaleId &&
|
||||||
!Number.isSafeInteger(request.revision) ||
|
revision(request.revision) &&
|
||||||
request.revision < 1 ||
|
revision(request.recordRevision) &&
|
||||||
!Number.isSafeInteger(request.recordRevision) ||
|
(request.status === 'pending' || request.status === 'approved' || request.status === 'rejected') &&
|
||||||
request.recordRevision < 1 ||
|
afterSaleValuesValid(request.before) &&
|
||||||
!['pending', 'approved', 'rejected'].includes(request.status) ||
|
afterSaleValuesValid(request.after) &&
|
||||||
!afterSaleValuesValid(request.before) ||
|
typeof request.canApprove === 'boolean' &&
|
||||||
!afterSaleValuesValid(request.after) ||
|
typeof request.stale === 'boolean' &&
|
||||||
typeof request.canApprove !== 'boolean'
|
typeof request.staleReason === 'string' &&
|
||||||
)
|
typeof request.member === 'string' &&
|
||||||
throw new Error('售后修改申请资料未完整返回,请重新读取。');
|
typeof request.created === 'string' &&
|
||||||
|
typeof request.requesterName === 'string' &&
|
||||||
|
(request.reviewed == null || typeof request.reviewed === 'string') &&
|
||||||
|
(request.reviewerName == null || typeof request.reviewerName === 'string') &&
|
||||||
|
(request.note == null || typeof request.note === 'string') &&
|
||||||
|
typeof request.reason === 'string'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
function validateAfterSaleRequest(request: unknown) {
|
||||||
|
if (!isRequest(request)) throw new Error('售后修改申请资料未完整返回,请重新读取。');
|
||||||
return request;
|
return request;
|
||||||
}
|
}
|
||||||
function afterSaleChangeListHTML(data) {
|
function afterSaleChangeListHTML(data: ReviewList<IndependentRequest>) {
|
||||||
if (
|
if (
|
||||||
!Array.isArray(data.requests) ||
|
!Array.isArray(data.requests) ||
|
||||||
!data.counts ||
|
!data.counts ||
|
||||||
+92
-251
@@ -1,187 +1,20 @@
|
|||||||
import { Children, useState } from 'react';
|
import type { ReactNode } from 'react';
|
||||||
|
import { LegacyCostRow } from './LegacyCostRow';
|
||||||
|
interface ActionInput extends Record<string, unknown> {
|
||||||
|
date: string;
|
||||||
|
verified: boolean;
|
||||||
|
feesVerified: boolean;
|
||||||
|
account?: string;
|
||||||
|
revision?: number;
|
||||||
|
returnPockets?: string[];
|
||||||
|
returnCounts?: (number | null)[];
|
||||||
|
stockCounts?: Record<number, number | null>;
|
||||||
|
}
|
||||||
|
import type { OrderContext, SharedViews } from '../viewTypes';
|
||||||
|
import { Children } from 'react';
|
||||||
import { Cards as CreditCardFees, Calc as LedgerCalc } from '../../../shared';
|
import { Cards as CreditCardFees, Calc as LedgerCalc } from '../../../shared';
|
||||||
const asMoney = value => (value == null ? '' : (value / 100).toFixed(2));
|
|
||||||
const costKeys = ['material', 'labor', 'accessories', 'other'];
|
|
||||||
function costBreakdown(line, quantity, parts, modes, rates) {
|
|
||||||
const input = { unit: line.unit, quantity, costParts: parts };
|
|
||||||
for (const [key, property] of [
|
|
||||||
['material', 'costMaterial'],
|
|
||||||
['labor', 'costLabor'],
|
|
||||||
]) {
|
|
||||||
input[property] = modes[key] === 'gram' ? { mode: 'gram', rate: rates[key] } : { mode: 'total' };
|
|
||||||
}
|
|
||||||
return LedgerCalc.purchaseCosts(input);
|
|
||||||
}
|
|
||||||
function LegacyCostRow({ line, index, members, fallback, choice, opts, grams, yuan }) {
|
|
||||||
const prefix = 'cost-' + index + '-';
|
|
||||||
const quantity = line.unit === 'g' ? (line.quantity / 1000).toFixed(3) : line.quantity;
|
|
||||||
const initialParts = Object.fromEntries(
|
|
||||||
costKeys.map(key => [
|
|
||||||
key,
|
|
||||||
line.costParts ? asMoney(line.costParts[key]) : ['accessories', 'other'].includes(key) ? '0' : '',
|
|
||||||
]),
|
|
||||||
);
|
|
||||||
const originalMode = ['gram', 'total'].includes(line.costMaterial?.mode)
|
|
||||||
? line.costMaterial.mode
|
|
||||||
: initialParts.material === ''
|
|
||||||
? 'gram'
|
|
||||||
: 'total';
|
|
||||||
const [parts, setParts] = useState(initialParts);
|
|
||||||
const [modes, setModes] = useState({
|
|
||||||
material: line.unit === 'g' ? originalMode : 'total',
|
|
||||||
labor: line.unit === 'g' ? line.costLabor?.mode || 'total' : 'total',
|
|
||||||
});
|
|
||||||
const [rates, setRates] = useState({
|
|
||||||
material: asMoney(line.costMaterial?.rate),
|
|
||||||
labor: asMoney(line.costLabor?.rate),
|
|
||||||
});
|
|
||||||
const originalTotal = line.unit !== 'g' || originalMode === 'total' ? initialParts.material : '';
|
|
||||||
const changePart = (key, value) => setParts(old => ({ ...old, [key]: value }));
|
|
||||||
const updateMode = (key, value, computed) => {
|
|
||||||
if (value === 'total' && (key === 'labor' || parts.material === '')) changePart(key, computed);
|
|
||||||
setModes(old => ({ ...old, [key]: value }));
|
|
||||||
};
|
|
||||||
const amount = (key, title, value, gram = false) => (
|
|
||||||
<label>
|
|
||||||
{title}
|
|
||||||
<input
|
|
||||||
type="number"
|
|
||||||
name={prefix + key}
|
|
||||||
min="0"
|
|
||||||
step="0.01"
|
|
||||||
placeholder="开单前必填,没有填0"
|
|
||||||
required={!gram}
|
|
||||||
readOnly={gram}
|
|
||||||
value={value}
|
|
||||||
onChange={event => changePart(key, event.target.value)}
|
|
||||||
/>
|
|
||||||
</label>
|
|
||||||
);
|
|
||||||
function group(key) {
|
|
||||||
const material = key === 'material',
|
|
||||||
gram = modes[key] === 'gram';
|
|
||||||
const payer = line.costPayers?.[key] ?? line.payer ?? fallback;
|
|
||||||
let value = parts[key],
|
|
||||||
formula;
|
|
||||||
if (gram) {
|
|
||||||
try {
|
|
||||||
const result = costBreakdown(
|
|
||||||
line,
|
|
||||||
quantity,
|
|
||||||
{ material: '0', labor: '0', accessories: '0', other: '0' },
|
|
||||||
{ material: 'total', labor: 'total', [key]: 'gram' },
|
|
||||||
rates,
|
|
||||||
).parts[key];
|
|
||||||
value = asMoney(result);
|
|
||||||
formula =
|
|
||||||
result == null
|
|
||||||
? material
|
|
||||||
? '填写每克进货料价后,系统自动乘以本行克重。'
|
|
||||||
: '填写每克工费后自动乘以克重。'
|
|
||||||
: quantity + 'g × ' + rates[key] + '元/克 = ' + yuan(result) + '元';
|
|
||||||
} catch (err) {
|
|
||||||
value = '';
|
|
||||||
formula = err.message;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
formula = material
|
|
||||||
? line.unit === 'g'
|
|
||||||
? '直接填写本行料费合计,不再乘以克重。'
|
|
||||||
: '按件商品请填写本行料费合计' + (rates.material ? ';每克料价已保留,切回g可恢复' : '') + '。'
|
|
||||||
: '直接填写本行总工费。';
|
|
||||||
}
|
|
||||||
const options = members(false, { selected: payer });
|
|
||||||
return (
|
|
||||||
<div className={'purchase-' + key} data-prefix={prefix} data-mode={modes[key]}>
|
|
||||||
<div className="grid purchase-cost-grid">
|
|
||||||
<label>
|
|
||||||
{material ? '进货料费方式' : '进货工费方式'}
|
|
||||||
<select
|
|
||||||
name={prefix + key + 'Mode'}
|
|
||||||
value={modes[key]}
|
|
||||||
onChange={event => updateMode(key, event.target.value, value)}
|
|
||||||
>
|
|
||||||
<option value="gram" disabled={line.unit !== 'g'}>
|
|
||||||
{material ? '按克料价' : '克工费'}
|
|
||||||
</option>
|
|
||||||
<option value="total">{material ? '直接填总料费' : '总工费'}</option>
|
|
||||||
</select>
|
|
||||||
</label>
|
|
||||||
<label hidden={!gram}>
|
|
||||||
{material ? '进货料价(元/克)' : '进货克工费(元/克)'}
|
|
||||||
<input
|
|
||||||
type="number"
|
|
||||||
name={prefix + key + 'Rate'}
|
|
||||||
min="0"
|
|
||||||
step="0.01"
|
|
||||||
value={rates[key]}
|
|
||||||
placeholder={material ? '填写每克进货料价' : '填写每克工费'}
|
|
||||||
disabled={!gram}
|
|
||||||
required={gram}
|
|
||||||
onChange={event => setRates(old => ({ ...old, [key]: event.target.value }))}
|
|
||||||
/>
|
|
||||||
</label>
|
|
||||||
{amount(key, material ? '料费成本合计(元)' : '进货总工费(元)', value, gram)}
|
|
||||||
<label className="purchase-payer">
|
|
||||||
{material ? '料费付款人' : '进货工费付款人'}
|
|
||||||
<select
|
|
||||||
required
|
|
||||||
name={prefix + key + 'Payer'}
|
|
||||||
defaultValue={options.some(([id]) => id === payer) ? payer : ''}
|
|
||||||
>
|
|
||||||
{options.some(([id]) => id === payer) ? null : (
|
|
||||||
<option value="" disabled>
|
|
||||||
请选择
|
|
||||||
</option>
|
|
||||||
)}
|
|
||||||
{opts(options)}
|
|
||||||
</select>
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
<p className="purchase-formula small muted" aria-live="polite">
|
|
||||||
{formula}
|
|
||||||
</p>
|
|
||||||
{material && (
|
|
||||||
<p className="purchase-original small muted" hidden={!originalTotal}>
|
|
||||||
{originalTotal &&
|
|
||||||
'已保留原料费合计 ' + originalTotal + '元。原金额不会当成每克料价;切换按克后请填写实际进货料价。'}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
let summary;
|
|
||||||
try {
|
|
||||||
summary = costBreakdown(line, quantity, parts, modes, rates).total;
|
|
||||||
} catch {
|
|
||||||
summary = null;
|
|
||||||
}
|
|
||||||
return (
|
|
||||||
<div className="internal cost-editor">
|
|
||||||
<h3>
|
|
||||||
{line.name} · {line.unit === 'g' ? grams(line.quantity) + 'g' : line.quantity + '件'}
|
|
||||||
</h3>
|
|
||||||
<div className="cost-fallback-payer">
|
|
||||||
{choice('配件及其他成本付款人', 'goodsPayer', members(), line.payer || 'owner')}
|
|
||||||
</div>
|
|
||||||
{!line.costParts && line.cost !== null && (
|
|
||||||
<p className="small">原记录未分项,总额 ¥{yuan(line.cost)};请按凭据拆分,不要把总额再填入每个项目。</p>
|
|
||||||
)}
|
|
||||||
<div className="cost-fields grid">
|
|
||||||
{group('material')}
|
|
||||||
{group('labor')}
|
|
||||||
{amount('accessories', '配件成本(元,本行合计)', parts.accessories)}
|
|
||||||
{amount('other', '其他货品成本(元,本行合计)', parts.other)}
|
|
||||||
</div>
|
|
||||||
<div className="cost-summary small">
|
|
||||||
本行货品成本合计:{summary == null ? '请补齐(没有的项目填0)' : '¥' + yuan(summary)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function orderActions(
|
export function orderActions(
|
||||||
{ currentOrder, ui, state },
|
{ currentOrder, ui = {}, state }: OrderContext,
|
||||||
{
|
{
|
||||||
orderActionUsesChangeForm,
|
orderActionUsesChangeForm,
|
||||||
orderActionRequiresApproval,
|
orderActionRequiresApproval,
|
||||||
@@ -213,12 +46,12 @@ export function orderActions(
|
|||||||
activePocketKeys,
|
activePocketKeys,
|
||||||
pocketLabel,
|
pocketLabel,
|
||||||
stockCountValue,
|
stockCountValue,
|
||||||
},
|
}: SharedViews,
|
||||||
) {
|
) {
|
||||||
function readReturnCounts(form, pockets) {
|
function readReturnCounts(form: HTMLFormElement, pockets: string[]) {
|
||||||
return pockets.map((pocket, index) => {
|
return pockets.map((pocket, index) => {
|
||||||
if (!pocketCountsEnabled(pocket)) return null;
|
if (!pocketCountsEnabled(pocket)) return null;
|
||||||
const count = stockCountValue(form.querySelector('[name="returnCount-' + index + '"]')?.value, {
|
const count = stockCountValue(form.querySelector<HTMLInputElement>('[name="returnCount-' + index + '"]')?.value, {
|
||||||
title: '商品 ' + (index + 1) + '实际退回数量(对)',
|
title: '商品 ' + (index + 1) + '实际退回数量(对)',
|
||||||
}),
|
}),
|
||||||
original = currentOrder?.lines?.[index]?.stockCount;
|
original = currentOrder?.lines?.[index]?.stockCount;
|
||||||
@@ -227,28 +60,28 @@ export function orderActions(
|
|||||||
return count;
|
return count;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
function readPaymentAccount(form) {
|
function readPaymentAccount(form: HTMLFormElement) {
|
||||||
return normalizePaymentAccount(
|
return normalizePaymentAccount(
|
||||||
(form?.querySelector?.('[name="payment_recipient"]')?.value || '') +
|
(form?.querySelector?.<HTMLInputElement>('[name="payment_recipient"]')?.value || '') +
|
||||||
(form?.querySelector?.('[name="payment_method"]')?.value || ''),
|
(form?.querySelector?.<HTMLInputElement>('[name="payment_method"]')?.value || ''),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function actionInput(form) {
|
function actionInput(form: HTMLFormElement) {
|
||||||
const data = Object.fromEntries(new FormData(form));
|
const data = Object.fromEntries(new FormData(form)) as Record<string, string>;
|
||||||
const kind = form.dataset.kind;
|
const kind = form.dataset.kind!;
|
||||||
const input = {
|
const input: ActionInput = {
|
||||||
...data,
|
...data,
|
||||||
date: data.date || state.today,
|
date: data.date || state.today,
|
||||||
verified: data.verified === 'on',
|
verified: data.verified === 'on',
|
||||||
feesVerified: data.feesVerified === 'on',
|
feesVerified: data.feesVerified === 'on',
|
||||||
};
|
};
|
||||||
if (kind === 'fees') {
|
if (kind === 'fees') {
|
||||||
input.revision = currentOrder.revision;
|
input.revision = currentOrder!.revision;
|
||||||
input.fee_items = [...form.querySelectorAll('.fee-verify-row')].map(row => ({
|
input.fee_items = [...form.querySelectorAll<HTMLElement>('.fee-verify-row')].map(row => ({
|
||||||
...currentOrder.pendingFees.find(f => f.key === row.dataset.key),
|
...currentOrder!.pendingFees.find(f => f.key === row.dataset.key),
|
||||||
status: 'estimated',
|
status: 'estimated',
|
||||||
amount: row.querySelector('[name="verifiedAmount"]').value,
|
amount: row.querySelector<HTMLInputElement>('[name="verifiedAmount"]')!.value,
|
||||||
payer: row.querySelector('[name="verifiedPayer"]').value,
|
payer: row.querySelector<HTMLInputElement>('[name="verifiedPayer"]')!.value,
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
if (kind === 'correct') {
|
if (kind === 'correct') {
|
||||||
@@ -257,47 +90,48 @@ export function orderActions(
|
|||||||
input.target = target;
|
input.target = target;
|
||||||
}
|
}
|
||||||
if (kind === 'cost')
|
if (kind === 'cost')
|
||||||
input.costs = Array.from(form.querySelectorAll('.cost-editor'), (row, index) => {
|
input.costs = Array.from(form.querySelectorAll<HTMLElement>('.cost-editor'), (row, index) => {
|
||||||
const get = key => row.querySelector('[name="cost-' + index + '-' + key + '"]').value;
|
const get = (key: string) =>
|
||||||
const mode = key =>
|
row.querySelector<HTMLInputElement>('[name="cost-' + index + '-' + key + '"]')!.value;
|
||||||
|
const mode = (key: string) =>
|
||||||
get(key + 'Mode') === 'gram' ? { mode: 'gram', rate: get(key + 'Rate') } : { mode: 'total' };
|
get(key + 'Mode') === 'gram' ? { mode: 'gram', rate: get(key + 'Rate') } : { mode: 'total' };
|
||||||
return {
|
return {
|
||||||
parts: Object.fromEntries(costKeys.map(key => [key, get(key)])),
|
parts: Object.fromEntries(Object.keys(LedgerCalc.costLabels).map(key => [key, get(key)])),
|
||||||
costMaterial: mode('material'),
|
costMaterial: mode('material'),
|
||||||
costLabor: mode('labor'),
|
costLabor: mode('labor'),
|
||||||
costPayers: { material: get('materialPayer'), labor: get('laborPayer') },
|
costPayers: { material: get('materialPayer'), labor: get('laborPayer') },
|
||||||
payer: row.querySelector('[name="goodsPayer"]').value,
|
payer: row.querySelector<HTMLInputElement>('[name="goodsPayer"]')!.value,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
if (kind === 'receipt' || kind === 'refund') input.account = readPaymentAccount(form);
|
if (kind === 'receipt' || kind === 'refund') input.account = readPaymentAccount(form);
|
||||||
if (kind === 'correct' && input.account) input.account = normalizePaymentAccount(input.account);
|
if (kind === 'correct' && input.account) input.account = normalizePaymentAccount(input.account);
|
||||||
if (kind === 'return') {
|
if (kind === 'return') {
|
||||||
input.returnPockets = currentOrder.lines.map(
|
input.returnPockets = currentOrder!.lines.map(
|
||||||
(_, i) => form.querySelector('[name="return-' + i + '"]')?.value ?? data['return-' + i],
|
(_, i) => form.querySelector<HTMLInputElement>('[name="return-' + i + '"]')?.value ?? data['return-' + i],
|
||||||
);
|
);
|
||||||
input.returnCounts = readReturnCounts(form, input.returnPockets);
|
input.returnCounts = readReturnCounts(form, input.returnPockets);
|
||||||
}
|
}
|
||||||
if (kind === 'complete') {
|
if (kind === 'complete') {
|
||||||
input.stockCounts = {};
|
input.stockCounts = {};
|
||||||
currentOrder.lines.forEach((line, index) => {
|
currentOrder!.lines.forEach((line, index) => {
|
||||||
if (line.unit === 'g' && pocketCountsEnabled(line.pocket) && line.stockCount == null)
|
if (line.unit === 'g' && pocketCountsEnabled(line.pocket) && line.stockCount == null)
|
||||||
input.stockCounts[index] = stockCountValue(
|
input.stockCounts![index] = stockCountValue(
|
||||||
form.querySelector('[name="completeCount-' + index + '"]')?.value,
|
form.querySelector<HTMLInputElement>('[name="completeCount-' + index + '"]')?.value,
|
||||||
{
|
{
|
||||||
title: '商品 ' + (index + 1) + '实际出库数量(对)',
|
title: '商品 ' + (index + 1) + '实际出库数量(对)',
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (['review', 'complete'].includes(kind)) input.revision = currentOrder.revision;
|
if (['review', 'complete'].includes(kind)) input.revision = currentOrder!.revision;
|
||||||
return input;
|
return input;
|
||||||
}
|
}
|
||||||
function orderActionModeText(kind, approval) {
|
function orderActionModeText(kind: string, approval: boolean) {
|
||||||
return approval
|
return approval
|
||||||
? `本次提交${orderChangeActionLabels[kind]}申请。店主同意后才记账;待批期间原订单、收退款、费用、库存和利润均不变。系统不会发起真实付款。`
|
? `本次提交${orderChangeActionLabels[kind]}申请。店主同意后才记账;待批期间原订单、收退款、费用、库存和利润均不变。系统不会发起真实付款。`
|
||||||
: '原单与本次业务日期均为今天,核实后直接记账,无需店主审批。改为其他业务日期须提交申请。系统不会发起真实付款。';
|
: '原单与本次业务日期均为今天,核实后直接记账,无需店主审批。改为其他业务日期须提交申请。系统不会发起真实付款。';
|
||||||
}
|
}
|
||||||
function orderActionChangeReviewHTML(kind) {
|
function orderActionChangeReviewHTML(kind: string) {
|
||||||
const approval = orderActionRequiresApproval(kind, ui.date);
|
const approval = orderActionRequiresApproval(kind, ui.date);
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -311,8 +145,8 @@ export function orderActions(
|
|||||||
<span id="order-action-reason-label">{approval ? '申请原因' : '登记原因'}</span>
|
<span id="order-action-reason-label">{approval ? '申请原因' : '登记原因'}</span>
|
||||||
<textarea
|
<textarea
|
||||||
name="change_reason"
|
name="change_reason"
|
||||||
maxLength="200"
|
maxLength={200}
|
||||||
rows="2"
|
rows={2}
|
||||||
required
|
required
|
||||||
placeholder="写清本次需要登记或更正的原因。"
|
placeholder="写清本次需要登记或更正的原因。"
|
||||||
></textarea>
|
></textarea>
|
||||||
@@ -329,19 +163,19 @@ export function orderActions(
|
|||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function creditCardPreviewHTML(id, payer = 'owner', basis = '客户付款金额') {
|
function creditCardPreviewHTML(id: string, payer = 'owner', basis = '客户付款金额') {
|
||||||
const values = ui.values || {};
|
const values = ui.values || {};
|
||||||
const original = currentOrder.payment_account;
|
const original = currentOrder!.payment_account;
|
||||||
const method = ui.paymentMethod ?? accountIdentity(original)?.channel;
|
const method = ui.paymentMethod ?? accountIdentity(original)?.channel;
|
||||||
const corrected = currentOrder.payments.find(p => p.id === (values.entry || '').split(':')[1]);
|
const corrected = currentOrder!.payments.find(p => p.id === (values.entry || '').split(':')[1]);
|
||||||
const correction = ui.action === 'correct';
|
const correction = ui.action === 'correct';
|
||||||
const visible = correction
|
const visible = correction
|
||||||
? corrected?.kind === 'receipt' && isCreditCardAccount(values.account)
|
? corrected?.kind === 'receipt' && isCreditCardAccount(values.account)
|
||||||
: method === '信用卡' && ui.action === 'receipt';
|
: method === '信用卡' && ui.action === 'receipt';
|
||||||
const rate = currentOrder.credit_card_rate_permille ?? state.shopSettings?.creditCardRatePermille;
|
const rate = currentOrder!.credit_card_rate_permille ?? state.shopSettings?.creditCardRatePermille;
|
||||||
let amount, formula;
|
let amount, formula;
|
||||||
if (visible || ui.lastCardBasis !== undefined) {
|
if (visible || ui.lastCardBasis !== undefined) {
|
||||||
const basisAmount = visible ? (values.amount ?? (currentOrder.balance / 100).toFixed(2)) : ui.lastCardBasis;
|
const basisAmount = visible ? (values.amount ?? (currentOrder!.balance / 100).toFixed(2)) : ui.lastCardBasis;
|
||||||
let cents, fee;
|
let cents, fee;
|
||||||
try {
|
try {
|
||||||
cents = LedgerCalc.cents(basisAmount);
|
cents = LedgerCalc.cents(basisAmount);
|
||||||
@@ -406,12 +240,12 @@ export function orderActions(
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function isAutomaticCardFee(item) {
|
function isAutomaticCardFee(item: { system?: string; key?: string; id?: string }) {
|
||||||
return item?.system === 'credit_card' || String(item?.key || '').startsWith('card_fee:');
|
return item?.system === 'credit_card' || String(item?.key || '').startsWith('card_fee:');
|
||||||
}
|
}
|
||||||
function pocketOptions(selected = '', historical = false) {
|
function pocketOptions(selected = '', historical = false) {
|
||||||
const keys = activePocketKeys(),
|
const keys = activePocketKeys(),
|
||||||
options = keys.map(key => [key, pocketLabel(key)]);
|
options = keys.map((key): [string, string, boolean?] => [key, pocketLabel(key)]);
|
||||||
if (selected && !keys.includes(selected))
|
if (selected && !keys.includes(selected))
|
||||||
options.push([
|
options.push([
|
||||||
selected,
|
selected,
|
||||||
@@ -420,10 +254,10 @@ export function orderActions(
|
|||||||
]);
|
]);
|
||||||
return options;
|
return options;
|
||||||
}
|
}
|
||||||
function isCreditCardAccount(account) {
|
function isCreditCardAccount(account: string | undefined) {
|
||||||
return typeof CreditCardFees === 'object' && typeof CreditCardFees.isAccount === 'function'
|
return typeof CreditCardFees === 'object' && typeof CreditCardFees.isAccount === 'function'
|
||||||
? CreditCardFees.isAccount(account)
|
? CreditCardFees.isAccount(account ?? '')
|
||||||
: ['助理信用卡', '助理1信用卡', '麦麦信用卡', '助理2信用卡'].includes(account);
|
: ['助理信用卡', '助理1信用卡', '麦麦信用卡', '助理2信用卡'].includes(account ?? '');
|
||||||
}
|
}
|
||||||
const orderFormMember = () => currentOrder?.member || currentMember();
|
const orderFormMember = () => currentOrder?.member || currentMember();
|
||||||
function defaultPaymentRecipient() {
|
function defaultPaymentRecipient() {
|
||||||
@@ -433,13 +267,16 @@ export function orderActions(
|
|||||||
function creditCardAvailable() {
|
function creditCardAvailable() {
|
||||||
return typeof CreditCardFees === 'object' && state?.accounts?.includes('麦麦信用卡');
|
return typeof CreditCardFees === 'object' && state?.accounts?.includes('麦麦信用卡');
|
||||||
}
|
}
|
||||||
function accountFields(account) {
|
function accountFields(account: string) {
|
||||||
const methods = ['微信', '支付宝', '现金', ...(creditCardAvailable() ? ['信用卡'] : [])];
|
const methods = ['微信', '支付宝', '现金', ...(creditCardAvailable() ? ['信用卡'] : [])];
|
||||||
account = normalizePaymentAccount(account || defaultPaymentRecipient() + '微信');
|
account = normalizePaymentAccount(account || defaultPaymentRecipient() + '微信');
|
||||||
const card = ui.paymentMethod ? ui.paymentMethod === '信用卡' : isCreditCardAccount(account),
|
const card = ui.paymentMethod ? ui.paymentMethod === '信用卡' : isCreditCardAccount(account),
|
||||||
identity = accountIdentity(account),
|
identity = accountIdentity(account),
|
||||||
prefix = identity ? memberAccountPrefix(identity.member) : defaultPaymentRecipient();
|
prefix = identity ? memberAccountPrefix(identity.member) : defaultPaymentRecipient();
|
||||||
const recipients = teamMemberOptions(!teamMode()).map(([member, name]) => [memberAccountPrefix(member), name]);
|
const recipients = teamMemberOptions(!teamMode()).map(([member, name]): [string, string] => [
|
||||||
|
memberAccountPrefix(member),
|
||||||
|
name,
|
||||||
|
]);
|
||||||
if (identity && !teamMemberEnabled(identity.member))
|
if (identity && !teamMemberEnabled(identity.member))
|
||||||
recipients.push([prefix, teamMemberName(identity.member) + '(已停用 · 原记录)']);
|
recipients.push([prefix, teamMemberName(identity.member) + '(已停用 · 原记录)']);
|
||||||
return (
|
return (
|
||||||
@@ -455,7 +292,7 @@ export function orderActions(
|
|||||||
data-card-locked={card}
|
data-card-locked={card}
|
||||||
disabled={card}
|
disabled={card}
|
||||||
>
|
>
|
||||||
{opts(recipients, card ? '麦麦' : prefix)}
|
{opts(recipients)}
|
||||||
</select>
|
</select>
|
||||||
{creditCardAvailable() ? (
|
{creditCardAvailable() ? (
|
||||||
<small className="small muted payment-account-note" hidden={!card}>
|
<small className="small muted payment-account-note" hidden={!card}>
|
||||||
@@ -468,14 +305,14 @@ export function orderActions(
|
|||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
const dateField = (name = 'date', value) =>
|
const dateField = (name = 'date', value?: string) =>
|
||||||
field('业务日期', name, value || state.today, 'date', {
|
field('业务日期', name, value || state.today, 'date', {
|
||||||
max: state.today,
|
max: state.today,
|
||||||
required: true,
|
required: true,
|
||||||
});
|
});
|
||||||
function showAction(action) {
|
function showAction(action: string) {
|
||||||
const o = currentOrder;
|
const o = currentOrder!;
|
||||||
let html = '';
|
let html: ReactNode = '';
|
||||||
const dt = dateField(),
|
const dt = dateField(),
|
||||||
changeForm = orderActionUsesChangeForm(action),
|
changeForm = orderActionUsesChangeForm(action),
|
||||||
requiresApproval = orderActionRequiresApproval(action, ui.date);
|
requiresApproval = orderActionRequiresApproval(action, ui.date);
|
||||||
@@ -537,7 +374,7 @@ export function orderActions(
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{field('凭据备注(选填)', 'reference', '', 'text', {
|
{field('凭据备注(选填)', 'reference', '', 'text', {
|
||||||
maxLength: '100',
|
maxLength: 100,
|
||||||
placeholder: '交易凭据末几位或说明',
|
placeholder: '交易凭据末几位或说明',
|
||||||
})}
|
})}
|
||||||
<label className="check">
|
<label className="check">
|
||||||
@@ -564,7 +401,7 @@ export function orderActions(
|
|||||||
</div>
|
</div>
|
||||||
{field('费用项目与说明', 'note', '', 'text', {
|
{field('费用项目与说明', 'note', '', 'text', {
|
||||||
required: true,
|
required: true,
|
||||||
maxLength: '150',
|
maxLength: 150,
|
||||||
})}
|
})}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
@@ -619,7 +456,7 @@ export function orderActions(
|
|||||||
{dt}
|
{dt}
|
||||||
{field('退货原因', 'reason', '', 'text', {
|
{field('退货原因', 'reason', '', 'text', {
|
||||||
required: true,
|
required: true,
|
||||||
maxLength: '200',
|
maxLength: 200,
|
||||||
})}
|
})}
|
||||||
<div className="grid two">
|
<div className="grid two">
|
||||||
{Children.toArray(
|
{Children.toArray(
|
||||||
@@ -630,15 +467,17 @@ export function orderActions(
|
|||||||
'return-' + i,
|
'return-' + i,
|
||||||
l.unit === 'g'
|
l.unit === 'g'
|
||||||
? [
|
? [
|
||||||
...(l.pocket || l.costMaterial?.mode === 'pool' ? [] : [['', '已退供应商,不留店内']]),
|
...(l.pocket || l.costMaterial?.mode === 'pool'
|
||||||
|
? []
|
||||||
|
: [['', '已退供应商,不留店内'] as const]),
|
||||||
...pocketOptions(l.pocket, true),
|
...pocketOptions(l.pocket, true),
|
||||||
]
|
]
|
||||||
: [['', '按件商品,不记黄金货盘']],
|
: [['', '按件商品,不记黄金货盘']],
|
||||||
l.pocket || (l.costMaterial?.mode === 'pool' ? state.pockets[0] : ''),
|
l.pocket || (l.costMaterial?.mode === 'pool' ? state.pockets![0] : ''),
|
||||||
)}
|
)}
|
||||||
{stockCountField(
|
{stockCountField(
|
||||||
ui.values?.['return-' + i] ??
|
ui.values?.['return-' + i] ??
|
||||||
(l.pocket || (l.costMaterial?.mode === 'pool' ? state.pockets[0] : '')),
|
(l.pocket || (l.costMaterial?.mode === 'pool' ? state.pockets![0] : '')),
|
||||||
l.stockCount,
|
l.stockCount,
|
||||||
{
|
{
|
||||||
readOnly: Number.isSafeInteger(l.stockCount),
|
readOnly: Number.isSafeInteger(l.stockCount),
|
||||||
@@ -675,7 +514,7 @@ export function orderActions(
|
|||||||
['toOwner', teamMemberName('assistant') + ' → ' + teamMemberName('owner')],
|
['toOwner', teamMemberName('assistant') + ' → ' + teamMemberName('owner')],
|
||||||
['toAssistant', teamMemberName('owner') + ' → ' + teamMemberName('assistant')],
|
['toAssistant', teamMemberName('owner') + ' → ' + teamMemberName('assistant')],
|
||||||
],
|
],
|
||||||
o.settlementDue < 0 ? 'toAssistant' : 'toOwner',
|
o.settlementDue! < 0 ? 'toAssistant' : 'toOwner',
|
||||||
)}
|
)}
|
||||||
{choice(
|
{choice(
|
||||||
'本笔归属',
|
'本笔归属',
|
||||||
@@ -691,7 +530,7 @@ export function orderActions(
|
|||||||
{moneyField('实际转账金额', 'amount')}
|
{moneyField('实际转账金额', 'amount')}
|
||||||
{field('转账凭据/说明', 'note', '', 'text', {
|
{field('转账凭据/说明', 'note', '', 'text', {
|
||||||
required: true,
|
required: true,
|
||||||
maxLength: '150',
|
maxLength: 150,
|
||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
<p className="small muted">
|
<p className="small muted">
|
||||||
@@ -706,29 +545,31 @@ export function orderActions(
|
|||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
if (action === 'correct') {
|
if (action === 'correct') {
|
||||||
const valid = r =>
|
const valid = (r: { id: string; price_lock_event_id?: string; note?: string; reference?: string }) =>
|
||||||
!r.price_lock_event_id &&
|
!r.price_lock_event_id &&
|
||||||
!o.corrections.some(c => c.target === r.id) &&
|
!o.corrections.some(c => c.target === r.id) &&
|
||||||
!String(r.note || r.reference || '').startsWith('更正冲回:');
|
!String(r.note || r.reference || '').startsWith('更正冲回:');
|
||||||
const cardExpenseIds = new Set((o.fee_items || []).filter(isAutomaticCardFee).map(item => item.expense_id));
|
const cardExpenseIds = new Set((o.fee_items || []).filter(isAutomaticCardFee).map(item => item.expense_id));
|
||||||
const entries = [
|
const entries = [
|
||||||
...(o.cancellationApproved || orderAfterSaleRecord(o) ? [] : o.payments.filter(valid)).map(r => [
|
...(o.cancellationApproved || orderAfterSaleRecord(o) ? [] : o.payments.filter(valid)).map(
|
||||||
'payment:' + r.id,
|
(r): [string, string] => [
|
||||||
r.date +
|
'payment:' + r.id,
|
||||||
' ' +
|
r.date +
|
||||||
(r.kind === 'receipt' ? '客户收款' : '客户退款') +
|
' ' +
|
||||||
' ' +
|
(r.kind === 'receipt' ? '客户收款' : '客户退款') +
|
||||||
yuan(r.amount) +
|
' ' +
|
||||||
'元 ' +
|
yuan(r.amount) +
|
||||||
accountDisplayName(r.account),
|
'元 ' +
|
||||||
]),
|
accountDisplayName(r.account),
|
||||||
|
],
|
||||||
|
),
|
||||||
...(o.cancellationApproved || orderAfterSaleRecord(o)
|
...(o.cancellationApproved || orderAfterSaleRecord(o)
|
||||||
? []
|
? []
|
||||||
: o.expenses.filter(r => valid(r) && !isAutomaticCardFee(r) && !cardExpenseIds.has(r.id))
|
: o.expenses.filter(r => valid(r) && !isAutomaticCardFee(r) && !cardExpenseIds.has(r.id))
|
||||||
).map(r => ['expense:' + r.id, r.date + ' 直接费用 ' + yuan(r.amount) + '元 ' + r.note]),
|
).map((r): [string, string] => ['expense:' + r.id, r.date + ' 直接费用 ' + yuan(r.amount) + '元 ' + r.note]),
|
||||||
...o.settlements
|
...o.settlements
|
||||||
.filter(valid)
|
.filter(valid)
|
||||||
.map(r => [
|
.map((r): [string, string] => [
|
||||||
'settlement:' + r.id,
|
'settlement:' + r.id,
|
||||||
r.date +
|
r.date +
|
||||||
' ' +
|
' ' +
|
||||||
@@ -778,7 +619,7 @@ export function orderActions(
|
|||||||
</div>
|
</div>
|
||||||
{field('更正原因', 'reason', '', 'text', {
|
{field('更正原因', 'reason', '', 'text', {
|
||||||
required: true,
|
required: true,
|
||||||
maxLength: '200',
|
maxLength: 200,
|
||||||
})}
|
})}
|
||||||
<label className="check">
|
<label className="check">
|
||||||
<input type="checkbox" name="verified" required />
|
<input type="checkbox" name="verified" required />
|
||||||
+44
-39
@@ -1,7 +1,10 @@
|
|||||||
|
import type { ReactNode } from 'react';
|
||||||
|
import type { BookData, BookRow, BookSummary, LockActivity, MoneyKey } from '../orderData';
|
||||||
|
import type { OrderContext, SharedViews } from '../viewTypes';
|
||||||
import { Children, Fragment } from 'react';
|
import { Children, Fragment } from 'react';
|
||||||
import { Values } from '../../../shared';
|
import { Values } from '../../../shared';
|
||||||
export function orderBook(
|
export function orderBook(
|
||||||
{ orderBookFilters, state },
|
{ orderBookFilters, state }: OrderContext,
|
||||||
{
|
{
|
||||||
yuan,
|
yuan,
|
||||||
teamMode,
|
teamMode,
|
||||||
@@ -19,16 +22,16 @@ export function orderBook(
|
|||||||
activePocketKeys,
|
activePocketKeys,
|
||||||
pocketLabel,
|
pocketLabel,
|
||||||
accountDisplayName,
|
accountDisplayName,
|
||||||
},
|
}: SharedViews,
|
||||||
) {
|
) {
|
||||||
const priceLockPayerName = payer => (payer ? teamMemberName(payer) : '待补');
|
const priceLockPayerName = (payer?: string) => (payer ? teamMemberName(payer) : '待补');
|
||||||
function priceLockActivityRows(activity) {
|
function priceLockActivityRows(activity: LockActivity) {
|
||||||
if (!activity) return [];
|
if (!activity) return [];
|
||||||
return [...(activity.customerCash || []), ...(activity.orderPayments || [])]
|
return [...(activity.customerCash || []), ...(activity.orderPayments || [])]
|
||||||
.map(item => ({
|
.map(item => ({
|
||||||
...item,
|
...item,
|
||||||
activityType: item.kind === 'receipt' ? '客户收款' : '客户退款',
|
activityType: item.kind === 'receipt' ? '客户收款' : '客户退款',
|
||||||
who: accountDisplayName(item.account),
|
who: accountDisplayName(item.account!),
|
||||||
activityName: item.product || '客户收退款',
|
activityName: item.product || '客户收退款',
|
||||||
}))
|
}))
|
||||||
.concat(
|
.concat(
|
||||||
@@ -36,24 +39,24 @@ export function orderBook(
|
|||||||
...item,
|
...item,
|
||||||
activityType: item.source === 'extra' ? '补重料费付款' : '原锁料费付款',
|
activityType: item.source === 'extra' ? '补重料费付款' : '原锁料费付款',
|
||||||
who: priceLockPayerName(item.payer),
|
who: priceLockPayerName(item.payer),
|
||||||
activityName: (item.product || '黄金') + ' · ' + grams(item.quantity) + 'g × ' + yuan(item.rate) + '元/克',
|
activityName: (item.product || '黄金') + ' · ' + grams(item.quantity!) + 'g × ' + yuan(item.rate) + '元/克',
|
||||||
})),
|
})),
|
||||||
(activity.deliveryGoodsOutlays || []).map(item => ({
|
(activity.deliveryGoodsOutlays || []).map(item => ({
|
||||||
...item,
|
...item,
|
||||||
activityType: '交付货品支出',
|
activityType: '交付货品支出',
|
||||||
who: priceLockPayerName(item.payer),
|
who: priceLockPayerName(item.payer),
|
||||||
activityName: item.name,
|
activityName: item.name!,
|
||||||
})),
|
})),
|
||||||
(activity.directOutlays || []).map(item => ({
|
(activity.directOutlays || []).map(item => ({
|
||||||
...item,
|
...item,
|
||||||
activityType: '实际费用',
|
activityType: '实际费用',
|
||||||
who: priceLockPayerName(item.payer),
|
who: priceLockPayerName(item.payer),
|
||||||
activityName: item.note,
|
activityName: item.note!,
|
||||||
})),
|
})),
|
||||||
)
|
)
|
||||||
.sort((a, b) => a.date.localeCompare(b.date));
|
.sort((a, b) => a.date.localeCompare(b.date));
|
||||||
}
|
}
|
||||||
function priceLockActivityHTML(activity) {
|
function priceLockActivityHTML(activity: LockActivity) {
|
||||||
if (!activity?.summary?.eventCount) return '';
|
if (!activity?.summary?.eventCount) return '';
|
||||||
const s = activity.summary,
|
const s = activity.summary,
|
||||||
rows = priceLockActivityRows(activity);
|
rows = priceLockActivityRows(activity);
|
||||||
@@ -136,7 +139,7 @@ export function orderBook(
|
|||||||
return '销售与利润按开单/交付日期,售后与回收按记录日期筛选。普通订单收款显示当前累计;锁价收退款按实际发生日期计入,待交付不计销售和利润。已取消订单不计本页销售汇总;直接回收付款计入每日购料,不计销售和利润。';
|
return '销售与利润按开单/交付日期,售后与回收按记录日期筛选。普通订单收款显示当前累计;锁价收退款按实际发生日期计入,待交付不计销售和利润。已取消订单不计本页销售汇总;直接回收付款计入每日购料,不计销售和利润。';
|
||||||
}
|
}
|
||||||
const previousOrderDate = Values.previousDate;
|
const previousOrderDate = Values.previousDate;
|
||||||
const getOrderBookFilters = () => orderBookFilters;
|
const getOrderBookFilters = () => orderBookFilters!;
|
||||||
function orderBookRange() {
|
function orderBookRange() {
|
||||||
const f = getOrderBookFilters(),
|
const f = getOrderBookFilters(),
|
||||||
today = state.today;
|
today = state.today;
|
||||||
@@ -193,7 +196,7 @@ export function orderBook(
|
|||||||
...historical.map(pocket => [pocket, pocketLabel(pocket) + '(已停用 · 历史)']),
|
...historical.map(pocket => [pocket, pocketLabel(pocket) + '(已停用 · 历史)']),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
function orderBookMobileCards(rows, version, showCopy) {
|
function orderBookMobileCards(rows: BookRow[], version: number, showCopy: boolean) {
|
||||||
return (
|
return (
|
||||||
<div className="order-mobile-list">
|
<div className="order-mobile-list">
|
||||||
{Children.toArray(
|
{Children.toArray(
|
||||||
@@ -218,7 +221,7 @@ export function orderBook(
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{row.status === 'cancelled' ? <p className="small muted">已取消,未计入汇总</p> : ''}
|
{row.status === 'cancelled' ? <p className="small muted">已取消,未计入汇总</p> : ''}
|
||||||
{row.balance < 0 ? <p className="small danger-text">退款待处理</p> : ''}
|
{(row.balance ?? 0) < 0 ? <p className="small danger-text">退款待处理</p> : ''}
|
||||||
<details className="order-mobile-breakdown">
|
<details className="order-mobile-breakdown">
|
||||||
<summary>成本、利润与备注</summary>
|
<summary>成本、利润与备注</summary>
|
||||||
<dl>
|
<dl>
|
||||||
@@ -263,8 +266,8 @@ export function orderBook(
|
|||||||
) : (
|
) : (
|
||||||
''
|
''
|
||||||
)}
|
)}
|
||||||
{!['afterSale', 'orderAfterSale', 'recovery'].includes(row.kind) ? orderEntryTimeHTML(row) : ''}
|
{!['afterSale', 'orderAfterSale', 'recovery'].includes(row.kind ?? '') ? orderEntryTimeHTML(row) : ''}
|
||||||
{showCopy && !['afterSale', 'orderAfterSale', 'recovery'].includes(row.kind)
|
{showCopy && !['afterSale', 'orderAfterSale', 'recovery'].includes(row.kind ?? '')
|
||||||
? button('复制新增', 'copy-order', 'order-copy-button', {
|
? button('复制新增', 'copy-order', 'order-copy-button', {
|
||||||
'data-id': row.id,
|
'data-id': row.id,
|
||||||
})
|
})
|
||||||
@@ -276,7 +279,7 @@ export function orderBook(
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function orderBookSummaryQuantity(summary) {
|
function orderBookSummaryQuantity(summary: BookSummary) {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{grams(summary.mg) + 'g' + (summary.pieces ? ' / ' + summary.pieces + '件' : '')}
|
{grams(summary.mg) + 'g' + (summary.pieces ? ' / ' + summary.pieces + '件' : '')}
|
||||||
@@ -284,10 +287,10 @@ export function orderBook(
|
|||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function afterSalePayerName(row) {
|
function afterSalePayerName(row: BookRow) {
|
||||||
return row.costItems?.[0]?.payer ? teamMemberName(row.costItems[0].payer) : '付款人待补';
|
return row.costItems?.[0]?.payer ? teamMemberName(row.costItems[0].payer) : '付款人待补';
|
||||||
}
|
}
|
||||||
function orderBookFeeParts(row) {
|
function orderBookFeeParts(row: BookRow) {
|
||||||
if (row.kind === 'recovery') return '';
|
if (row.kind === 'recovery') return '';
|
||||||
if (row.status === 'draft') return '';
|
if (row.status === 'draft') return '';
|
||||||
if (row.kind === 'afterSale')
|
if (row.kind === 'afterSale')
|
||||||
@@ -302,7 +305,7 @@ export function orderBook(
|
|||||||
<span>原单售后成本调整</span>
|
<span>原单售后成本调整</span>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
const grouped = new Map();
|
const grouped = new Map<string, { name: string; amount: number; missing: boolean }>();
|
||||||
for (const item of row.laborAndFeeItems || []) {
|
for (const item of row.laborAndFeeItems || []) {
|
||||||
const key = item.component + ':' + item.name,
|
const key = item.component + ':' + item.name,
|
||||||
previous = grouped.get(key);
|
previous = grouped.get(key);
|
||||||
@@ -332,7 +335,7 @@ export function orderBook(
|
|||||||
''
|
''
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function orderBookMoney(row, key) {
|
function orderBookMoney(row: BookRow, key: MoneyKey) {
|
||||||
if (row.kind === 'recovery') return <span className="muted">—</span>;
|
if (row.kind === 'recovery') return <span className="muted">—</span>;
|
||||||
if (row.status === 'draft')
|
if (row.status === 'draft')
|
||||||
return (
|
return (
|
||||||
@@ -362,22 +365,22 @@ export function orderBook(
|
|||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function orderBookQuantity(value) {
|
function orderBookQuantity(value: Pick<BookRow, 'mg' | 'pieces'>) {
|
||||||
return (
|
return (
|
||||||
[value.mg ? grams(value.mg) + 'g' : '', value.pieces ? value.pieces + '件' : ''].filter(Boolean).join(' / ') ||
|
[value.mg ? grams(value.mg) + 'g' : '', value.pieces ? value.pieces + '件' : ''].filter(Boolean).join(' / ') ||
|
||||||
'—'
|
'—'
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function orderReviewBadge(row) {
|
function orderReviewBadge(row: BookRow) {
|
||||||
return orderIsReviewed(row) ? <span className="order-review-status">已复核</span> : '';
|
return orderIsReviewed(row) ? <span className="order-review-status">已复核</span> : '';
|
||||||
}
|
}
|
||||||
function afterSaleEditButton(row) {
|
function afterSaleEditButton(row: BookRow) {
|
||||||
return button('修改', 'after-sale-edit', 'after-sale-edit-button', {
|
return button('修改', 'after-sale-edit', 'after-sale-edit-button', {
|
||||||
'data-id': row.after_sale_id || row.id,
|
'data-id': row.after_sale_id || row.id,
|
||||||
'aria-label': '修改 ' + row.customer + ' 的售后记录',
|
'aria-label': '修改 ' + row.customer + ' 的售后记录',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
function orderBookIdentity(row, version) {
|
function orderBookIdentity(row: BookRow, version: number | undefined = undefined) {
|
||||||
if (row.kind === 'orderAfterSale')
|
if (row.kind === 'orderAfterSale')
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
@@ -462,14 +465,14 @@ export function orderBook(
|
|||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
const card = (title, value, hint = '', emphasis = false) => (
|
const card = (title: string, value: ReactNode, hint: ReactNode = '', emphasis = false) => (
|
||||||
<div className={'stat ' + (emphasis ? 'emphasis' : '')}>
|
<div className={'stat ' + (emphasis ? 'emphasis' : '')}>
|
||||||
<small>{title}</small>
|
<small>{title}</small>
|
||||||
<strong>{value}</strong>
|
<strong>{value}</strong>
|
||||||
<div className="hint">{hint}</div>
|
<div className="hint">{hint}</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
function orderBookSummaryAmount(summary, key) {
|
function orderBookSummaryAmount(summary: BookSummary, key: MoneyKey) {
|
||||||
const missing = summary.unknownCounts?.[key] || 0,
|
const missing = summary.unknownCounts?.[key] || 0,
|
||||||
known = summary.knownCounts?.[key];
|
known = summary.knownCounts?.[key];
|
||||||
if (missing && known === 0 && !summary[key] && !summary.afterSaleCount)
|
if (missing && known === 0 && !summary[key] && !summary.afterSaleCount)
|
||||||
@@ -480,7 +483,7 @@ export function orderBook(
|
|||||||
);
|
);
|
||||||
return (missing ? '已知 ' : '') + '¥' + yuan(summary[key]);
|
return (missing ? '已知 ' : '') + '¥' + yuan(summary[key]);
|
||||||
}
|
}
|
||||||
function validateOrderBook(book) {
|
function validateOrderBook(book: BookData) {
|
||||||
const s = book?.summaryWithoutCancelled,
|
const s = book?.summaryWithoutCancelled,
|
||||||
r = book?.receiptsWithoutCancelled;
|
r = book?.receiptsWithoutCancelled;
|
||||||
const amounts = [
|
const amounts = [
|
||||||
@@ -492,7 +495,7 @@ export function orderBook(
|
|||||||
'profit',
|
'profit',
|
||||||
'ownerCost',
|
'ownerCost',
|
||||||
'assistantCost',
|
'assistantCost',
|
||||||
];
|
] as const;
|
||||||
const counts = [
|
const counts = [
|
||||||
'orderCount',
|
'orderCount',
|
||||||
'completedCount',
|
'completedCount',
|
||||||
@@ -505,7 +508,7 @@ export function orderBook(
|
|||||||
'unknownCosts',
|
'unknownCosts',
|
||||||
'unknownCostCount',
|
'unknownCostCount',
|
||||||
'unknownProfitCount',
|
'unknownProfitCount',
|
||||||
];
|
] as const;
|
||||||
if (
|
if (
|
||||||
!Array.isArray(book?.rows) ||
|
!Array.isArray(book?.rows) ||
|
||||||
(book.displayRows !== undefined && !Array.isArray(book.displayRows)) ||
|
(book.displayRows !== undefined && !Array.isArray(book.displayRows)) ||
|
||||||
@@ -525,20 +528,20 @@ export function orderBook(
|
|||||||
s.unknownCounts[key] >= 0,
|
s.unknownCounts[key] >= 0,
|
||||||
) ||
|
) ||
|
||||||
!counts.every(key => Number.isSafeInteger(s[key]) && s[key] >= 0) ||
|
!counts.every(key => Number.isSafeInteger(s[key]) && s[key] >= 0) ||
|
||||||
!['receipt', 'refund', 'net'].every(key => Number.isSafeInteger(r[key])) ||
|
!(['receipt', 'refund', 'net'] as const).every(key => Number.isSafeInteger(r[key])) ||
|
||||||
!Array.isArray(r.channels) ||
|
!Array.isArray(r.channels) ||
|
||||||
!r.channels.every(
|
!r.channels.every(
|
||||||
channel =>
|
channel =>
|
||||||
channel &&
|
channel &&
|
||||||
typeof channel.name === 'string' &&
|
typeof channel.name === 'string' &&
|
||||||
['receipt', 'refund', 'net'].every(key => Number.isSafeInteger(channel[key])),
|
(['receipt', 'refund', 'net'] as const).every(key => Number.isSafeInteger(channel[key])),
|
||||||
) ||
|
) ||
|
||||||
!['wechat', 'alipay', 'cash'].every(channel => r.channels.some(item => item.channel === channel))
|
!(['wechat', 'alipay', 'cash'] as const).every(channel => r.channels.some(item => item.channel === channel))
|
||||||
)
|
)
|
||||||
throw new Error('订单汇总数据尚未完整返回,请刷新后重新读取。');
|
throw new Error('订单汇总数据尚未完整返回,请刷新后重新读取。');
|
||||||
return book;
|
return book;
|
||||||
}
|
}
|
||||||
function renderOrderBook(book, range) {
|
function renderOrderBook(book: BookData, range: { from: string; date: string; name: string }) {
|
||||||
validateOrderBook(book);
|
validateOrderBook(book);
|
||||||
const s = book.summaryWithoutCancelled,
|
const s = book.summaryWithoutCancelled,
|
||||||
receipts = book.receiptsWithoutCancelled,
|
receipts = book.receiptsWithoutCancelled,
|
||||||
@@ -598,7 +601,7 @@ export function orderBook(
|
|||||||
(teamMode() ? teamMemberKeys() : ['owner', 'assistant']).map(member => (
|
(teamMode() ? teamMemberKeys() : ['owner', 'assistant']).map(member => (
|
||||||
<span>
|
<span>
|
||||||
<b>{teamMemberName(member)}</b>
|
<b>{teamMemberName(member)}</b>
|
||||||
<span>{orderBookSummaryAmount(s, member + 'Cost')}</span>
|
<span>{orderBookSummaryAmount(s, `${member}Cost`)}</span>
|
||||||
</span>
|
</span>
|
||||||
)),
|
)),
|
||||||
)}
|
)}
|
||||||
@@ -640,7 +643,7 @@ export function orderBook(
|
|||||||
{card(range.name + '成本' + (costPartial ? '(已知部分)' : ''), costValue, costDetails)}
|
{card(range.name + '成本' + (costPartial ? '(已知部分)' : ''), costValue, costDetails)}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
const count = `${range.name} · 汇总 ${s.orderCount} 单${recoveryCount ? ' · 回收 ' + recoveryCount + ' 笔' : ''}${s.afterSaleCount ? ' · 售后 ' + s.afterSaleCount + ' 笔' : ''}${cancelledCount ? ',另有 ' + cancelledCount + ' 单取消未计' : ''}${orderBookFilters.q || orderBookFilters.status || orderBookFilters.pocket || orderBookFilters.member ? '(已筛选)' : ''}`;
|
const count = `${range.name} · 汇总 ${s.orderCount} 单${recoveryCount ? ' · 回收 ' + recoveryCount + ' 笔' : ''}${s.afterSaleCount ? ' · 售后 ' + s.afterSaleCount + ' 笔' : ''}${cancelledCount ? ',另有 ' + cancelledCount + ' 单取消未计' : ''}${orderBookFilters!.q || orderBookFilters!.status || orderBookFilters!.pocket || orderBookFilters!.member ? '(已筛选)' : ''}`;
|
||||||
const rows = book.displayRows ?? book.rows;
|
const rows = book.displayRows ?? book.rows;
|
||||||
if (!rows.length) {
|
if (!rows.length) {
|
||||||
const list = (
|
const list = (
|
||||||
@@ -677,7 +680,7 @@ export function orderBook(
|
|||||||
rows.map((row, i) => (
|
rows.map((row, i) => (
|
||||||
<tr
|
<tr
|
||||||
className={
|
className={
|
||||||
['afterSale', 'orderAfterSale'].includes(row.kind)
|
['afterSale', 'orderAfterSale'].includes(row.kind ?? '')
|
||||||
? 'order-after-sale'
|
? 'order-after-sale'
|
||||||
: row.kind === 'recovery'
|
: row.kind === 'recovery'
|
||||||
? 'order-recovery'
|
? 'order-recovery'
|
||||||
@@ -696,8 +699,10 @@ export function orderBook(
|
|||||||
{row.kind === 'recovery' ? <span className="order-status muted">已记录</span> : badge(row)}
|
{row.kind === 'recovery' ? <span className="order-status muted">已记录</span> : badge(row)}
|
||||||
{orderReviewBadge(row)}
|
{orderReviewBadge(row)}
|
||||||
</div>
|
</div>
|
||||||
{!['afterSale', 'orderAfterSale', 'recovery'].includes(row.kind) ? orderEntryTimeHTML(row) : ''}
|
{!['afterSale', 'orderAfterSale', 'recovery'].includes(row.kind ?? '')
|
||||||
{showOrderCopyEntry && !['afterSale', 'orderAfterSale', 'recovery'].includes(row.kind)
|
? orderEntryTimeHTML(row)
|
||||||
|
: ''}
|
||||||
|
{showOrderCopyEntry && !['afterSale', 'orderAfterSale', 'recovery'].includes(row.kind ?? '')
|
||||||
? button(
|
? button(
|
||||||
<>
|
<>
|
||||||
<span aria-hidden="true">+</span>复制新增
|
<span aria-hidden="true">+</span>复制新增
|
||||||
@@ -711,7 +716,7 @@ export function orderBook(
|
|||||||
)
|
)
|
||||||
: ''}
|
: ''}
|
||||||
{row.status === 'cancelled' ? <div className="small muted">未计入汇总</div> : ''}
|
{row.status === 'cancelled' ? <div className="small muted">未计入汇总</div> : ''}
|
||||||
{row.balance < 0 ? <div className="small danger-text">退款待处理</div> : ''}
|
{(row.balance ?? 0) < 0 ? <div className="small danger-text">退款待处理</div> : ''}
|
||||||
</td>
|
</td>
|
||||||
<td className="order-type">
|
<td className="order-type">
|
||||||
{row.types.map(e).map((part, i) => (
|
{row.types.map(e).map((part, i) => (
|
||||||
@@ -758,7 +763,7 @@ export function orderBook(
|
|||||||
</tbody>
|
</tbody>
|
||||||
<tfoot>
|
<tfoot>
|
||||||
<tr>
|
<tr>
|
||||||
<td colSpan="2">
|
<td colSpan={2}>
|
||||||
汇总 {s.orderCount} 单
|
汇总 {s.orderCount} 单
|
||||||
{recoveryCount ? (
|
{recoveryCount ? (
|
||||||
<>
|
<>
|
||||||
+66
-56
@@ -1,7 +1,13 @@
|
|||||||
|
import type { ReactNode } from 'react';
|
||||||
|
import type { OrderRecord, OrderLine, OwnershipRequest, ChangeRequest, CancellationRequest } from '../orderData';
|
||||||
|
type CostRow = ReturnType<typeof import('../../../../../public/calculations.js').orderCosts>['rows'][number] & {
|
||||||
|
allocations?: { payer: string; amount: number | null }[];
|
||||||
|
};
|
||||||
|
import type { OrderContext, SharedViews } from '../viewTypes';
|
||||||
import { Children, Fragment } from 'react';
|
import { Children, Fragment } from 'react';
|
||||||
import { Calc as LedgerCalc } from '../../../shared';
|
import { Calc as LedgerCalc } from '../../../shared';
|
||||||
export function orderDetail(
|
export function orderDetail(
|
||||||
{ currentOrder, state, detailForm, error, navigation },
|
{ currentOrder, state, detailForm, error, navigation }: OrderContext,
|
||||||
{
|
{
|
||||||
orderCancellationPending,
|
orderCancellationPending,
|
||||||
orderChangePending,
|
orderChangePending,
|
||||||
@@ -41,9 +47,9 @@ export function orderDetail(
|
|||||||
stockCountText,
|
stockCountText,
|
||||||
pocketCountsEnabled,
|
pocketCountsEnabled,
|
||||||
teamMemberKeys,
|
teamMemberKeys,
|
||||||
},
|
}: SharedViews,
|
||||||
) {
|
) {
|
||||||
function transactionTable(o) {
|
function transactionTable(o: OrderRecord) {
|
||||||
const rows = [
|
const rows = [
|
||||||
...o.payments.map(p => ({
|
...o.payments.map(p => ({
|
||||||
date: p.date,
|
date: p.date,
|
||||||
@@ -107,7 +113,7 @@ export function orderDetail(
|
|||||||
<p className="muted">还没有收退款、费用或交款记录。</p>
|
<p className="muted">还没有收退款、费用或交款记录。</p>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function priceLockInventoryCreditHTML(order) {
|
function priceLockInventoryCreditHTML(order: OrderRecord) {
|
||||||
if (!order.assistantInventoryCredit) return '';
|
if (!order.assistantInventoryCredit) return '';
|
||||||
return (
|
return (
|
||||||
<div className="note">
|
<div className="note">
|
||||||
@@ -125,7 +131,7 @@ export function orderDetail(
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function orderTeamFundsHTML(order) {
|
function orderTeamFundsHTML(order: OrderRecord) {
|
||||||
return (
|
return (
|
||||||
<section className="panel">
|
<section className="panel">
|
||||||
<h2>{teamMemberName(order.member)}的经营订单</h2>
|
<h2>{teamMemberName(order.member)}的经营订单</h2>
|
||||||
@@ -134,7 +140,7 @@ export function orderDetail(
|
|||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function orderProductTraceHTML(o) {
|
function orderProductTraceHTML(o: OrderRecord) {
|
||||||
return (
|
return (
|
||||||
<details className="panel detail-product-trace">
|
<details className="panel detail-product-trace">
|
||||||
<summary>商品来源与原始说明</summary>
|
<summary>商品来源与原始说明</summary>
|
||||||
@@ -158,8 +164,8 @@ export function orderDetail(
|
|||||||
</details>
|
</details>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function orderAfterSaleProfitHTML(order) {
|
function orderAfterSaleProfitHTML(order: OrderRecord) {
|
||||||
const summary = orderAfterSaleRecord(order).summary,
|
const summary = orderAfterSaleRecord(order)!.summary,
|
||||||
direct = Number.isSafeInteger(summary.directCost) ? summary.directCost : order.directCost;
|
direct = Number.isSafeInteger(summary.directCost) ? summary.directCost : order.directCost;
|
||||||
return (
|
return (
|
||||||
<section className="panel detail-profit detail-profit-known" aria-label="售后最终利润">
|
<section className="panel detail-profit detail-profit-known" aria-label="售后最终利润">
|
||||||
@@ -177,7 +183,11 @@ export function orderDetail(
|
|||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function orderProfitHTML(o, summary, { voided = false } = {}) {
|
function orderProfitHTML(
|
||||||
|
o: OrderRecord,
|
||||||
|
summary: ReturnType<typeof orderDetailCostSummary>,
|
||||||
|
{ voided = false } = {},
|
||||||
|
) {
|
||||||
if (orderAfterSaleRecord(o)) return orderAfterSaleProfitHTML(o);
|
if (orderAfterSaleRecord(o)) return orderAfterSaleProfitHTML(o);
|
||||||
const { total, missing } = summary,
|
const { total, missing } = summary,
|
||||||
done = ['delivered', 'returned', 'cancelled'].includes(o.status),
|
done = ['delivered', 'returned', 'cancelled'].includes(o.status),
|
||||||
@@ -197,7 +207,7 @@ export function orderDetail(
|
|||||||
: !known
|
: !known
|
||||||
? `成交金额 ¥${yuan(o.total)} − 完整成本待补,利润暂不确认。`
|
? `成交金额 ¥${yuan(o.total)} − 完整成本待补,利润暂不确认。`
|
||||||
: `${historical ? '销售净额' : '成交金额'} ¥${yuan(sale)} − ${historical ? '保留成本' : '成本合计'} ¥${yuan(total)} = ${title} ¥${yuan(o.profit)}`;
|
: `${historical ? '销售净额' : '成交金额'} ¥${yuan(sale)} − ${historical ? '保留成本' : '成本合计'} ¥${yuan(total)} = ${title} ¥${yuan(o.profit)}`;
|
||||||
if (known && sale - total !== o.profit)
|
if (known && sale - total! !== o.profit)
|
||||||
equation = `${historical ? '销售净额' : '成交金额'} ¥${yuan(sale)};成本合计 ¥${yuan(total)}。利润沿用已记账金额,历史差异请核对下方流水。`;
|
equation = `${historical ? '销售净额' : '成交金额'} ¥${yuan(sale)};成本合计 ¥${yuan(total)}。利润沿用已记账金额,历史差异请核对下方流水。`;
|
||||||
return (
|
return (
|
||||||
<section className={'panel detail-profit' + (known ? ' detail-profit-known' : '')} aria-label={title}>
|
<section className={'panel detail-profit' + (known ? ' detail-profit-known' : '')} aria-label={title}>
|
||||||
@@ -210,7 +220,7 @@ export function orderDetail(
|
|||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function orderCostRowsHTML(rows, label) {
|
function orderCostRowsHTML(rows: CostRow[], label: string) {
|
||||||
const names = Object.fromEntries(teamMemberKeys().map(member => [member, teamMemberName(member)]));
|
const names = Object.fromEntries(teamMemberKeys().map(member => [member, teamMemberName(member)]));
|
||||||
return (
|
return (
|
||||||
<div className="table-wrap">
|
<div className="table-wrap">
|
||||||
@@ -229,8 +239,8 @@ export function orderDetail(
|
|||||||
weighted = calculation?.weighted;
|
weighted = calculation?.weighted;
|
||||||
const formula = calculation
|
const formula = calculation
|
||||||
? weighted
|
? weighted
|
||||||
? `耗用 ${grams(calculation.quantity)}g${calculation.rate == null ? '' : ' · 加权均价约 ' + yuan(calculation.rate) + '元/克'};按实际购料分摊`
|
? `耗用 ${grams(calculation.quantity!)}g${calculation.rate == null ? '' : ' · 加权均价约 ' + yuan(calculation.rate) + '元/克'};按实际购料分摊`
|
||||||
: `${grams(calculation.quantity)}g × ${calculation.rate == null ? '单价待补' : yuan(calculation.rate) + '元/克'}`
|
: `${grams(calculation.quantity!)}g × ${calculation.rate == null ? '单价待补' : yuan(calculation.rate) + '元/克'}`
|
||||||
: '';
|
: '';
|
||||||
const payer = row.poolPending
|
const payer = row.poolPending
|
||||||
? '待补采购后分摊'
|
? '待补采购后分摊'
|
||||||
@@ -278,9 +288,9 @@ export function orderDetail(
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function orderAfterSaleCostsHTML(order) {
|
function orderAfterSaleCostsHTML(order: OrderRecord) {
|
||||||
const record = orderAfterSaleRecord(order),
|
const record = orderAfterSaleRecord(order),
|
||||||
summary = record.summary,
|
summary = record!.summary,
|
||||||
direct = Number.isSafeInteger(summary.directCost) ? summary.directCost : order.directCost,
|
direct = Number.isSafeInteger(summary.directCost) ? summary.directCost : order.directCost,
|
||||||
total = summary.costLoss + direct;
|
total = summary.costLoss + direct;
|
||||||
return (
|
return (
|
||||||
@@ -312,13 +322,13 @@ export function orderDetail(
|
|||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function orderCostsHTML(o, summary = orderDetailCostSummary(o), { voided = false } = {}) {
|
function orderCostsHTML(o: OrderRecord, summary = orderDetailCostSummary(o), { voided = false } = {}) {
|
||||||
if (orderAfterSaleRecord(o)) return orderAfterSaleCostsHTML(o);
|
if (orderAfterSaleRecord(o)) return orderAfterSaleCostsHTML(o);
|
||||||
const { costs, rows, knownTotal, missing, knownGoods, paidFees } = summary;
|
const { costs, rows, knownTotal, missing, knownGoods, paidFees } = summary;
|
||||||
const actual = rows.filter(row => !row.excluded && row.kind !== 'pending' && row.amount !== 0),
|
const actual = rows.filter(row => !row.excluded && row.kind !== 'pending' && row.amount !== 0),
|
||||||
pending = rows.filter(row => row.kind === 'pending' && row.amount !== 0),
|
pending = rows.filter(row => row.kind === 'pending' && row.amount !== 0),
|
||||||
historical = rows.filter(row => row.excluded && row.amount !== 0);
|
historical = rows.filter(row => row.excluded && row.amount !== 0);
|
||||||
const numbers = actual.filter(row => row.amount != null).map(row => row.amount),
|
const numbers = actual.filter(row => row.amount != null).map(row => row.amount!),
|
||||||
rowTotal = numbers.reduce((sum, amount) => sum + amount, 0);
|
rowTotal = numbers.reduce((sum, amount) => sum + amount, 0);
|
||||||
const terms = rowTotal === knownTotal ? numbers : [knownGoods, paidFees].filter(amount => amount !== 0);
|
const terms = rowTotal === knownTotal ? numbers : [knownGoods, paidFees].filter(amount => amount !== 0);
|
||||||
const equation = (terms.length ? terms : [0]).map(amount => '¥' + yuan(amount)).join(' + ');
|
const equation = (terms.length ? terms : [0]).map(amount => '¥' + yuan(amount)).join(' + ');
|
||||||
@@ -395,7 +405,7 @@ export function orderDetail(
|
|||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function orderAmount(value, mode) {
|
function orderAmount(value: number | null, mode: string) {
|
||||||
return value == null
|
return value == null
|
||||||
? '待补'
|
? '待补'
|
||||||
: '¥' +
|
: '¥' +
|
||||||
@@ -406,7 +416,7 @@ export function orderDetail(
|
|||||||
})
|
})
|
||||||
: yuan(value));
|
: yuan(value));
|
||||||
}
|
}
|
||||||
function orderLinePocketHTML(order, line) {
|
function orderLinePocketHTML(order: OrderRecord, line: OrderLine) {
|
||||||
const pocket = pocketLabel(String(line.pocket || '').trim()) || '配货';
|
const pocket = pocketLabel(String(line.pocket || '').trim()) || '配货';
|
||||||
const title =
|
const title =
|
||||||
order.status === 'delivered'
|
order.status === 'delivered'
|
||||||
@@ -429,7 +439,7 @@ export function orderDetail(
|
|||||||
</span>
|
</span>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function orderSalesHTML(o, { voided = false } = {}) {
|
function orderSalesHTML(o: OrderRecord, { voided = false } = {}) {
|
||||||
const historical = voided || ['returned', 'cancelled'].includes(o.status),
|
const historical = voided || ['returned', 'cancelled'].includes(o.status),
|
||||||
unbooked = ['draft', 'confirmed'].includes(o.status);
|
unbooked = ['draft', 'confirmed'].includes(o.status);
|
||||||
const subtotal = o.lines.reduce((sum, line) => sum + line.sale, 0),
|
const subtotal = o.lines.reduce((sum, line) => sum + line.sale, 0),
|
||||||
@@ -461,8 +471,8 @@ export function orderDetail(
|
|||||||
line.unit === 'g' &&
|
line.unit === 'g' &&
|
||||||
Number.isSafeInteger(line.goldPrice) &&
|
Number.isSafeInteger(line.goldPrice) &&
|
||||||
Number.isSafeInteger(line.laborRate) &&
|
Number.isSafeInteger(line.laborRate) &&
|
||||||
['gram', 'piece'].includes(line.laborMode) &&
|
['gram', 'piece'].includes(line.laborMode ?? '') &&
|
||||||
(line.laborMode !== 'piece' || (Number.isSafeInteger(line.pieces) && line.pieces > 0));
|
(line.laborMode !== 'piece' || (Number.isSafeInteger(line.pieces) && line.pieces! > 0));
|
||||||
const quantity = line.unit === 'g' ? grams(line.quantity) + 'g' : line.quantity + '件';
|
const quantity = line.unit === 'g' ? grams(line.quantity) + 'g' : line.quantity + '件';
|
||||||
const formula = auto
|
const formula = auto
|
||||||
? line.laborMode === 'gram'
|
? line.laborMode === 'gram'
|
||||||
@@ -553,7 +563,7 @@ export function orderDetail(
|
|||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function orderAfterSaleDetailHTML(order) {
|
function orderAfterSaleDetailHTML(order: OrderRecord) {
|
||||||
const record = orderAfterSaleRecord(order);
|
const record = orderAfterSaleRecord(order);
|
||||||
if (!record) return '';
|
if (!record) return '';
|
||||||
try {
|
try {
|
||||||
@@ -611,7 +621,7 @@ export function orderDetail(
|
|||||||
return (
|
return (
|
||||||
<section className="panel">
|
<section className="panel">
|
||||||
<h2>已处理售后</h2>
|
<h2>已处理售后</h2>
|
||||||
<p className="danger-text">{err.message}</p>
|
<p className="danger-text">{err instanceof Error ? err.message : String(err)}</p>
|
||||||
{button('重新读取订单', 'reload-order-change', '', {
|
{button('重新读取订单', 'reload-order-change', '', {
|
||||||
'data-id': order.id,
|
'data-id': order.id,
|
||||||
})}
|
})}
|
||||||
@@ -619,7 +629,7 @@ export function orderDetail(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
function orderOwnershipHistoryHTML(request) {
|
function orderOwnershipHistoryHTML(request: OwnershipRequest) {
|
||||||
return (
|
return (
|
||||||
<li>
|
<li>
|
||||||
<div className="change-record-title">
|
<div className="change-record-title">
|
||||||
@@ -651,7 +661,7 @@ export function orderDetail(
|
|||||||
</li>
|
</li>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function orderOwnershipDetailHTML(order) {
|
function orderOwnershipDetailHTML(order: OrderRecord) {
|
||||||
const entry = currentOrderOwnership(order),
|
const entry = currentOrderOwnership(order),
|
||||||
data = entry?.data,
|
data = entry?.data,
|
||||||
request = orderOwnershipPending(order);
|
request = orderOwnershipPending(order);
|
||||||
@@ -730,14 +740,14 @@ export function orderDetail(
|
|||||||
) : (
|
) : (
|
||||||
''
|
''
|
||||||
)}
|
)}
|
||||||
<details open={request}>
|
<details open={!!request}>
|
||||||
<summary>归属修改与复核记录({data.requests.length})</summary>
|
<summary>归属修改与复核记录({data.requests.length})</summary>
|
||||||
<ul className="timeline change-history">{Children.toArray(data.requests.map(orderOwnershipHistoryHTML))}</ul>
|
<ul className="timeline change-history">{Children.toArray(data.requests.map(orderOwnershipHistoryHTML))}</ul>
|
||||||
</details>
|
</details>
|
||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function orderChangeHistoryHTML(request) {
|
function orderChangeHistoryHTML(request: ChangeRequest) {
|
||||||
return (
|
return (
|
||||||
<li>
|
<li>
|
||||||
<div className="change-record-title">
|
<div className="change-record-title">
|
||||||
@@ -771,7 +781,7 @@ export function orderDetail(
|
|||||||
</li>
|
</li>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function orderChangeDetailHTML(order) {
|
function orderChangeDetailHTML(order: OrderRecord) {
|
||||||
const entry = currentOrderChange(order),
|
const entry = currentOrderChange(order),
|
||||||
data = entry?.data,
|
data = entry?.data,
|
||||||
request = orderChangePending(order);
|
request = orderChangePending(order);
|
||||||
@@ -826,14 +836,14 @@ export function orderDetail(
|
|||||||
) : (
|
) : (
|
||||||
''
|
''
|
||||||
)}
|
)}
|
||||||
<details open={request}>
|
<details open={!!request}>
|
||||||
<summary>变更申请与复核记录({data.requests.length})</summary>
|
<summary>变更申请与复核记录({data.requests.length})</summary>
|
||||||
<ul className="timeline change-history">{Children.toArray(data.requests.map(orderChangeHistoryHTML))}</ul>
|
<ul className="timeline change-history">{Children.toArray(data.requests.map(orderChangeHistoryHTML))}</ul>
|
||||||
</details>
|
</details>
|
||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function orderCancellationHistoryHTML(request) {
|
function orderCancellationHistoryHTML(request: CancellationRequest) {
|
||||||
if (request.direct === true)
|
if (request.direct === true)
|
||||||
return (
|
return (
|
||||||
<li>
|
<li>
|
||||||
@@ -875,7 +885,7 @@ export function orderDetail(
|
|||||||
</li>
|
</li>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function orderCancellationDetailHTML(order) {
|
function orderCancellationDetailHTML(order: OrderRecord) {
|
||||||
if (order.price_lock_id) return '';
|
if (order.price_lock_id) return '';
|
||||||
const entry = currentOrderCancellation(order),
|
const entry = currentOrderCancellation(order),
|
||||||
data = entry?.data,
|
data = entry?.data,
|
||||||
@@ -939,7 +949,7 @@ export function orderDetail(
|
|||||||
) : (
|
) : (
|
||||||
''
|
''
|
||||||
)}
|
)}
|
||||||
<details open={request}>
|
<details open={!!request}>
|
||||||
<summary>取消申请与处理记录({data.requests.length})</summary>
|
<summary>取消申请与处理记录({data.requests.length})</summary>
|
||||||
<ul className="timeline cancellation-history">
|
<ul className="timeline cancellation-history">
|
||||||
{Children.toArray(data.requests.map(orderCancellationHistoryHTML))}
|
{Children.toArray(data.requests.map(orderCancellationHistoryHTML))}
|
||||||
@@ -948,7 +958,7 @@ export function orderDetail(
|
|||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function printStatusControls(value) {
|
function printStatusControls(value: OrderRecord) {
|
||||||
return (
|
return (
|
||||||
<div className="document-print-controls">
|
<div className="document-print-controls">
|
||||||
{printStatusBadge(value)}
|
{printStatusBadge(value)}
|
||||||
@@ -956,7 +966,7 @@ export function orderDetail(
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function recoveryLinkedOrderNoticeHTML(order) {
|
function recoveryLinkedOrderNoticeHTML(order: OrderRecord) {
|
||||||
return order.recovery_id ? (
|
return order.recovery_id ? (
|
||||||
<div className="note">
|
<div className="note">
|
||||||
这张销售单由置换结算自动生成。重量、抵扣与收付款请在关联置换单核对;修改或取消请从关联置换单进入,整套收付款、购料与库存一起更正。
|
这张销售单由置换结算自动生成。重量、抵扣与收付款请在关联置换单核对;修改或取消请从关联置换单进入,整套收付款、购料与库存一起更正。
|
||||||
@@ -965,10 +975,10 @@ export function orderDetail(
|
|||||||
''
|
''
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function materialPoolOrderNoticeHTML(order) {
|
function materialPoolOrderNoticeHTML(order: OrderRecord) {
|
||||||
if (!order.materialCostPending) return '';
|
if (!order.materialCostPending) return '';
|
||||||
const dates = [
|
const dates = [
|
||||||
...new Set(order.lines.filter(line => line.costMaterial?.mode === 'pool').map(line => line.costMaterial.poolId)),
|
...new Set(order.lines.filter(line => line.costMaterial?.mode === 'pool').map(line => line.costMaterial!.poolId)),
|
||||||
];
|
];
|
||||||
return (
|
return (
|
||||||
<div className="note material-order-pending">
|
<div className="note material-order-pending">
|
||||||
@@ -978,10 +988,10 @@ export function orderDetail(
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function orderOwnershipOtherPending(order) {
|
function orderOwnershipOtherPending(order: OrderRecord) {
|
||||||
return orderChangePending(order) || orderCancellationPending(order);
|
return orderChangePending(order) || orderCancellationPending(order);
|
||||||
}
|
}
|
||||||
function orderOwnershipActionHTML(order) {
|
function orderOwnershipActionHTML(order: OrderRecord) {
|
||||||
const data = currentOrderOwnership(order)?.data;
|
const data = currentOrderOwnership(order)?.data;
|
||||||
if (!data?.eligible || data.pending || orderOwnershipPending(order) || orderOwnershipOtherPending(order)) return '';
|
if (!data?.eligible || data.pending || orderOwnershipPending(order) || orderOwnershipOtherPending(order)) return '';
|
||||||
const direct = state.user.role === 'owner' && data.canDirect;
|
const direct = state.user.role === 'owner' && data.canDirect;
|
||||||
@@ -989,7 +999,7 @@ export function orderDetail(
|
|||||||
'data-id': order.id,
|
'data-id': order.id,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
function orderInternalNoteHTML(order) {
|
function orderInternalNoteHTML(order: OrderRecord) {
|
||||||
return (
|
return (
|
||||||
<aside className="detail-internal-note" aria-label="内部备注(客户不可见)">
|
<aside className="detail-internal-note" aria-label="内部备注(客户不可见)">
|
||||||
<span className="detail-internal-note-label">内部备注 · 客户不可见</span>
|
<span className="detail-internal-note-label">内部备注 · 客户不可见</span>
|
||||||
@@ -1008,16 +1018,16 @@ export function orderDetail(
|
|||||||
</aside>
|
</aside>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function orderDetailCostSummary(o) {
|
function orderDetailCostSummary(o: OrderRecord) {
|
||||||
const costs = LedgerCalc.orderCosts(o),
|
const costs = LedgerCalc.orderCosts(o),
|
||||||
rows = [],
|
rows: CostRow[] = [],
|
||||||
pools = new Map();
|
pools = new Map<string, CostRow & { allocations: { payer: string; amount: number | null }[] }>();
|
||||||
for (const row of costs.rows) {
|
for (const row of costs.rows) {
|
||||||
if ((row.materialPoolId || row.priceLockSource) && row.calculation?.weighted) {
|
if ((row.materialPoolId || row.priceLockSource) && row.calculation?.weighted) {
|
||||||
const key = row.source,
|
const key = row.source,
|
||||||
existing = pools.get(key);
|
existing = pools.get(key);
|
||||||
if (existing) {
|
if (existing) {
|
||||||
existing.amount += row.amount;
|
existing.amount = Number(existing.amount) + Number(row.amount);
|
||||||
existing.allocations.push({
|
existing.allocations.push({
|
||||||
payer: row.payer,
|
payer: row.payer,
|
||||||
amount: row.amount,
|
amount: row.amount,
|
||||||
@@ -1051,7 +1061,7 @@ export function orderDetail(
|
|||||||
knownGoods = costs.goodsExcluded
|
knownGoods = costs.goodsExcluded
|
||||||
? 0
|
? 0
|
||||||
: Number.isSafeInteger(goods)
|
: Number.isSafeInteger(goods)
|
||||||
? goods
|
? goods!
|
||||||
: Number.isSafeInteger(o.knownGoodsCost)
|
: Number.isSafeInteger(o.knownGoodsCost)
|
||||||
? o.knownGoodsCost
|
? o.knownGoodsCost
|
||||||
: costs.total.goods;
|
: costs.total.goods;
|
||||||
@@ -1070,7 +1080,7 @@ export function orderDetail(
|
|||||||
total: missing ? null : knownGoods + paidFees,
|
total: missing ? null : knownGoods + paidFees,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
function recoveryLinkedOrderActionsHTML(order, { reviewAllowed = false } = {}) {
|
function recoveryLinkedOrderActionsHTML(order: OrderRecord, { reviewAllowed = false } = {}) {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{button('查看置换结算单', 'recovery-open', 'primary', {
|
{button('查看置换结算单', 'recovery-open', 'primary', {
|
||||||
@@ -1083,7 +1093,7 @@ export function orderDetail(
|
|||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function orderAfterSaleLegacyActionHTML(order, needsApproval) {
|
function orderAfterSaleLegacyActionHTML(order: OrderRecord, needsApproval: boolean) {
|
||||||
if (order.lines.some(line => line.priceLockPool)) return '';
|
if (order.lines.some(line => line.priceLockPool)) return '';
|
||||||
const action = button(needsApproval ? '申请整单退货' : '整单退货', 'show-return', 'quiet', {
|
const action = button(needsApproval ? '申请整单退货' : '整单退货', 'show-return', 'quiet', {
|
||||||
title: '旧入口:仅登记退货,实际退款另行登记',
|
title: '旧入口:仅登记退货,实际退款另行登记',
|
||||||
@@ -1099,7 +1109,7 @@ export function orderDetail(
|
|||||||
</details>
|
</details>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function orderAfterSaleActionHTML(order, { blocked = false } = {}) {
|
function orderAfterSaleActionHTML(order: OrderRecord, { blocked = false } = {}) {
|
||||||
if (
|
if (
|
||||||
order.status !== 'delivered' ||
|
order.status !== 'delivered' ||
|
||||||
blocked ||
|
blocked ||
|
||||||
@@ -1112,7 +1122,7 @@ export function orderDetail(
|
|||||||
'data-id': order.id,
|
'data-id': order.id,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
function orderCancellationActionHTML(order) {
|
function orderCancellationActionHTML(order: OrderRecord) {
|
||||||
const entry = currentOrderCancellation(order),
|
const entry = currentOrderCancellation(order),
|
||||||
data = entry?.data;
|
data = entry?.data;
|
||||||
if (orderOwnershipPending(order)) return '';
|
if (orderOwnershipPending(order)) return '';
|
||||||
@@ -1128,7 +1138,7 @@ export function orderDetail(
|
|||||||
'data-id': order.id,
|
'data-id': order.id,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
function orderCancellationApproved(order) {
|
function orderCancellationApproved(order: OrderRecord) {
|
||||||
return (
|
return (
|
||||||
order.cancellationApproved ||
|
order.cancellationApproved ||
|
||||||
currentOrderCancellation(order)?.data?.requests.find(request => request.status === 'approved') ||
|
currentOrderCancellation(order)?.data?.requests.find(request => request.status === 'approved') ||
|
||||||
@@ -1136,17 +1146,17 @@ export function orderDetail(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
function renderDetail() {
|
function renderDetail() {
|
||||||
const o = currentOrder,
|
const o = currentOrder!,
|
||||||
done = ['delivered', 'returned', 'cancelled'].includes(o.status);
|
done = ['delivered', 'returned', 'cancelled'].includes(o.status);
|
||||||
const cancellationPending = orderCancellationPending(o),
|
const cancellationPending = orderCancellationPending(o),
|
||||||
changePending = orderChangePending(o),
|
changePending = orderChangePending(o),
|
||||||
ownershipPending = orderOwnershipPending(o),
|
ownershipPending = orderOwnershipPending(o),
|
||||||
approvalPending = !!cancellationPending || !!changePending || !!ownershipPending,
|
approvalPending = !!cancellationPending || !!changePending || !!ownershipPending,
|
||||||
afterSaleDone = !!orderAfterSaleRecord(o),
|
afterSaleDone = !!orderAfterSaleRecord(o),
|
||||||
voided = orderCancellationApproved(o),
|
voided = !!orderCancellationApproved(o),
|
||||||
financialBlocked = approvalPending || !!voided || afterSaleDone,
|
financialBlocked = approvalPending || !!voided || afterSaleDone,
|
||||||
owner = state.user.role === 'owner';
|
owner = state.user.role === 'owner';
|
||||||
let actions = (
|
let actions: ReactNode = (
|
||||||
<>
|
<>
|
||||||
{button('客户预览/打印', 'print', 'primary', {
|
{button('客户预览/打印', 'print', 'primary', {
|
||||||
'data-id': o.id,
|
'data-id': o.id,
|
||||||
@@ -1176,7 +1186,7 @@ export function orderDetail(
|
|||||||
);
|
);
|
||||||
if (o.status === 'draft' && owner && !financialBlocked)
|
if (o.status === 'draft' && owner && !financialBlocked)
|
||||||
actions = Children.toArray([actions, button('继续填写并开单', 'edit')]);
|
actions = Children.toArray([actions, button('继续填写并开单', 'edit')]);
|
||||||
const needsApproval = kind => orderActionRequiresApproval(kind);
|
const needsApproval = (kind: string) => orderActionRequiresApproval(kind);
|
||||||
if (o.status === 'confirmed' && !financialBlocked) {
|
if (o.status === 'confirmed' && !financialBlocked) {
|
||||||
if (o.pendingFees.length)
|
if (o.pendingFees.length)
|
||||||
actions = Children.toArray([
|
actions = Children.toArray([
|
||||||
@@ -1335,7 +1345,7 @@ export function orderDetail(
|
|||||||
<small className="muted">实际已交净额 ¥{yuan(o.profitTransferred)}</small>
|
<small className="muted">实际已交净额 ¥{yuan(o.profitTransferred)}</small>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
{o.settlementDue < 0
|
{Number(o.settlementDue) < 0
|
||||||
? teamMemberName('owner') + '待转回' + teamMemberName('assistant')
|
? teamMemberName('owner') + '待转回' + teamMemberName('assistant')
|
||||||
: teamMemberName('assistant') + '待交' + teamMemberName('owner')}{' '}
|
: teamMemberName('assistant') + '待交' + teamMemberName('owner')}{' '}
|
||||||
<strong>{o.settlementDue == null ? '料费待补' : '¥' + yuan(Math.abs(o.settlementDue))}</strong>
|
<strong>{o.settlementDue == null ? '料费待补' : '¥' + yuan(Math.abs(o.settlementDue))}</strong>
|
||||||
@@ -1386,7 +1396,7 @@ export function orderDetail(
|
|||||||
<summary>操作记录</summary>
|
<summary>操作记录</summary>
|
||||||
<ul className="timeline">
|
<ul className="timeline">
|
||||||
{Children.toArray(
|
{Children.toArray(
|
||||||
o.audit.map(a => (
|
o.audit!.map(a => (
|
||||||
<li>
|
<li>
|
||||||
{actionName[a.action] || a.action} · {a.actor}
|
{actionName[a.action] || a.action} · {a.actor}
|
||||||
<small>{new Date(a.created).toLocaleString('zh-CN')}</small>
|
<small>{new Date(a.created).toLocaleString('zh-CN')}</small>
|
||||||
+49
-42
@@ -1,3 +1,5 @@
|
|||||||
|
import type { CancellationRequest, OwnershipRequest, ChangeRequest, ReviewList, CancelSummary } from '../orderData';
|
||||||
|
import type { OrderContext, SharedViews } from '../viewTypes';
|
||||||
import { Children } from 'react';
|
import { Children } from 'react';
|
||||||
export function orderReviews(
|
export function orderReviews(
|
||||||
{
|
{
|
||||||
@@ -9,7 +11,7 @@ export function orderReviews(
|
|||||||
orderChangeListStatus,
|
orderChangeListStatus,
|
||||||
orderOwnershipListStatus,
|
orderOwnershipListStatus,
|
||||||
orderCancellationListStatus,
|
orderCancellationListStatus,
|
||||||
},
|
}: OrderContext,
|
||||||
{
|
{
|
||||||
orderChangeActionLabel,
|
orderChangeActionLabel,
|
||||||
orderChangeTime,
|
orderChangeTime,
|
||||||
@@ -34,12 +36,12 @@ export function orderReviews(
|
|||||||
orderOwnershipStatus,
|
orderOwnershipStatus,
|
||||||
validateOrderChangeRequest,
|
validateOrderChangeRequest,
|
||||||
validateOrderOwnershipRequest,
|
validateOrderOwnershipRequest,
|
||||||
},
|
}: SharedViews,
|
||||||
) {
|
) {
|
||||||
function orderCancellationRecordStatus(request) {
|
function orderCancellationRecordStatus(request: CancellationRequest) {
|
||||||
return request.direct === true ? '当天直接取消' : orderCancellationStatus[request.status];
|
return request.direct === true ? '当天直接取消' : orderCancellationStatus[request.status];
|
||||||
}
|
}
|
||||||
function orderCancellationListHTML(result) {
|
function orderCancellationListHTML(result: ReviewList<CancellationRequest>) {
|
||||||
const owner = state.user.role === 'owner' && result.canApprove;
|
const owner = state.user.role === 'owner' && result.canApprove;
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -130,7 +132,7 @@ export function orderReviews(
|
|||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function orderOwnershipListHTML(result) {
|
function orderOwnershipListHTML(result: ReviewList<OwnershipRequest>) {
|
||||||
const owner = state.user.role === 'owner' && result.canApprove;
|
const owner = state.user.role === 'owner' && result.canApprove;
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -222,7 +224,7 @@ export function orderReviews(
|
|||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function orderChangeListHTML(result) {
|
function orderChangeListHTML(result: ReviewList<ChangeRequest>) {
|
||||||
const owner = state.user.role === 'owner' && result.canApprove;
|
const owner = state.user.role === 'owner' && result.canApprove;
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -318,7 +320,9 @@ export function orderReviews(
|
|||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function legacyCountConfirmationHTML(value) {
|
function legacyCountConfirmationHTML(
|
||||||
|
value: { requiresLegacyCountVerified?: boolean; legacyCountNotice?: string } | undefined,
|
||||||
|
) {
|
||||||
return value?.requiresLegacyCountVerified ? (
|
return value?.requiresLegacyCountVerified ? (
|
||||||
<>
|
<>
|
||||||
<div className="note">
|
<div className="note">
|
||||||
@@ -334,9 +338,9 @@ export function orderReviews(
|
|||||||
''
|
''
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function validateOrderCancellationRequest(request, orderId) {
|
function validateOrderCancellationRequest(request: CancellationRequest, orderId: string | undefined = undefined) {
|
||||||
const summary = request?.summary,
|
const summary = request?.summary,
|
||||||
nullable = value => value === null || Number.isSafeInteger(value);
|
nullable = (value: unknown) => value === null || Number.isSafeInteger(value);
|
||||||
if (
|
if (
|
||||||
!request ||
|
!request ||
|
||||||
typeof request.id !== 'string' ||
|
typeof request.id !== 'string' ||
|
||||||
@@ -351,8 +355,8 @@ export function orderReviews(
|
|||||||
typeof request.stale !== 'boolean' ||
|
typeof request.stale !== 'boolean' ||
|
||||||
typeof request.canApprove !== 'boolean' ||
|
typeof request.canApprove !== 'boolean' ||
|
||||||
!summary ||
|
!summary ||
|
||||||
!['total', 'netReceived', 'directCost'].every(key => Number.isSafeInteger(summary[key])) ||
|
!(['total', 'netReceived', 'directCost'] as const).every(key => Number.isSafeInteger(summary[key])) ||
|
||||||
!['goodsCost', 'profit', 'settlementDue'].every(key => nullable(summary[key])) ||
|
!(['goodsCost', 'profit', 'settlementDue'] as const).every(key => nullable(summary[key])) ||
|
||||||
!Array.isArray(summary.inventory) ||
|
!Array.isArray(summary.inventory) ||
|
||||||
!summary.inventory.every(
|
!summary.inventory.every(
|
||||||
item => typeof item.date === 'string' && typeof item.pocket === 'string' && Number.isSafeInteger(item.mg),
|
item => typeof item.date === 'string' && typeof item.pocket === 'string' && Number.isSafeInteger(item.mg),
|
||||||
@@ -361,12 +365,12 @@ export function orderReviews(
|
|||||||
throw new Error('取消申请资料未完整返回,请重新读取订单后复核。');
|
throw new Error('取消申请资料未完整返回,请重新读取订单后复核。');
|
||||||
return request;
|
return request;
|
||||||
}
|
}
|
||||||
function orderCancellationSummaryHTML(request) {
|
function orderCancellationSummaryHTML(request: CancellationRequest) {
|
||||||
return orderCancellationSummaryDataHTML(validateOrderCancellationRequest(request).summary);
|
return orderCancellationSummaryDataHTML(validateOrderCancellationRequest(request).summary);
|
||||||
}
|
}
|
||||||
function orderCancellationSummaryDataHTML(value) {
|
function orderCancellationSummaryDataHTML(value: CancelSummary | undefined) {
|
||||||
const summary = validateOrderCancellationSummary(value),
|
const summary = validateOrderCancellationSummary(value),
|
||||||
amount = value => (value === null ? '待补齐' : '¥' + yuan(value));
|
amount = (value: number | null) => (value === null ? '待补齐' : '¥' + yuan(value));
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="note">本次按“录错作废”撤销本单记账,不是实际退货退款。原单和冲回明细保留,不会向客户付款。</div>
|
<div className="note">本次按“录错作废”撤销本单记账,不是实际退货退款。原单和冲回明细保留,不会向客户付款。</div>
|
||||||
@@ -437,12 +441,12 @@ export function orderReviews(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
const requireOrderCancellationDetail = () => ({
|
const requireOrderCancellationDetail = () => ({
|
||||||
order: currentOrder,
|
order: currentOrder!,
|
||||||
data: orderCancellationDetail.data,
|
data: orderCancellationDetail!.data!,
|
||||||
});
|
});
|
||||||
function showOrderCancellationForm(kind) {
|
function showOrderCancellationForm(kind: string) {
|
||||||
const { order, data } = requireOrderCancellationDetail(),
|
const { order, data } = requireOrderCancellationDetail(),
|
||||||
request = data.pending;
|
request = data.pending!;
|
||||||
if (kind === 'request' && orderCancellationCanDirect(order)) kind = 'direct';
|
if (kind === 'request' && orderCancellationCanDirect(order)) kind = 'direct';
|
||||||
if (
|
if (
|
||||||
['request', 'direct'].includes(kind) &&
|
['request', 'direct'].includes(kind) &&
|
||||||
@@ -473,9 +477,9 @@ export function orderReviews(
|
|||||||
取消原因
|
取消原因
|
||||||
<textarea
|
<textarea
|
||||||
name="reason"
|
name="reason"
|
||||||
rows="3"
|
rows={3}
|
||||||
required
|
required
|
||||||
maxLength="200"
|
maxLength={200}
|
||||||
placeholder="写清这张单录错的原因,例如:同一笔销售重复录入。"
|
placeholder="写清这张单录错的原因,例如:同一笔销售重复录入。"
|
||||||
></textarea>
|
></textarea>
|
||||||
</label>
|
</label>
|
||||||
@@ -498,9 +502,9 @@ export function orderReviews(
|
|||||||
取消原因
|
取消原因
|
||||||
<textarea
|
<textarea
|
||||||
name="reason"
|
name="reason"
|
||||||
rows="3"
|
rows={3}
|
||||||
required
|
required
|
||||||
maxLength="200"
|
maxLength={200}
|
||||||
placeholder="写清这张单录错的原因,例如:同一笔销售重复录入。"
|
placeholder="写清这张单录错的原因,例如:同一笔销售重复录入。"
|
||||||
></textarea>
|
></textarea>
|
||||||
</label>
|
</label>
|
||||||
@@ -517,7 +521,7 @@ export function orderReviews(
|
|||||||
<p className="cancellation-reason">取消原因:{request.reason}</p>
|
<p className="cancellation-reason">取消原因:{request.reason}</p>
|
||||||
{orderCancellationSummaryHTML(request)}
|
{orderCancellationSummaryHTML(request)}
|
||||||
<label>
|
<label>
|
||||||
复核备注(选填)<textarea name="note" maxLength="200" rows="2"></textarea>
|
复核备注(选填)<textarea name="note" maxLength={200} rows={2}></textarea>
|
||||||
</label>
|
</label>
|
||||||
<label className="check">
|
<label className="check">
|
||||||
<input type="checkbox" name="verified" required />
|
<input type="checkbox" name="verified" required />
|
||||||
@@ -536,9 +540,9 @@ export function orderReviews(
|
|||||||
驳回意见
|
驳回意见
|
||||||
<textarea
|
<textarea
|
||||||
name="note"
|
name="note"
|
||||||
rows="3"
|
rows={3}
|
||||||
required
|
required
|
||||||
maxLength="200"
|
maxLength={200}
|
||||||
placeholder="写清需要补充或重新核对的地方。"
|
placeholder="写清需要补充或重新核对的地方。"
|
||||||
></textarea>
|
></textarea>
|
||||||
</label>
|
</label>
|
||||||
@@ -573,12 +577,12 @@ export function orderReviews(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
const requireOrderOwnershipDetail = () => ({
|
const requireOrderOwnershipDetail = () => ({
|
||||||
order: currentOrder,
|
order: currentOrder!,
|
||||||
data: orderOwnershipDetail.data,
|
data: orderOwnershipDetail!.data!,
|
||||||
});
|
});
|
||||||
function showOrderOwnershipForm(kind = 'request') {
|
function showOrderOwnershipForm(kind = 'request') {
|
||||||
const { order, data } = requireOrderOwnershipDetail(),
|
const { order, data } = requireOrderOwnershipDetail(),
|
||||||
request = data.pending;
|
request = data.pending!;
|
||||||
if (!['request', 'approve', 'reject'].includes(kind)) throw new Error('归属修改操作无效,请重新读取。');
|
if (!['request', 'approve', 'reject'].includes(kind)) throw new Error('归属修改操作无效,请重新读取。');
|
||||||
if (kind === 'request' && (!data.eligible || request)) throw new Error(data.reason || '本单当前不能重复修改归属。');
|
if (kind === 'request' && (!data.eligible || request)) throw new Error(data.reason || '本单当前不能重复修改归属。');
|
||||||
if (kind !== 'request' && (state.user.role !== 'owner' || !data.canApprove || request?.status !== 'pending'))
|
if (kind !== 'request' && (state.user.role !== 'owner' || !data.canApprove || request?.status !== 'pending'))
|
||||||
@@ -592,7 +596,7 @@ export function orderReviews(
|
|||||||
if (kind === 'request') {
|
if (kind === 'request') {
|
||||||
title = direct ? '修改订单归属' : '申请修改订单归属';
|
title = direct ? '修改订单归属' : '申请修改订单归属';
|
||||||
submit = direct ? '确认修改归属' : '提交归属申请';
|
submit = direct ? '确认修改归属' : '提交归属申请';
|
||||||
const before = data.members.find(member => member.member === data.member),
|
const before = data.members.find(member => member.member === data.member)!,
|
||||||
members = data.members.filter(
|
members = data.members.filter(
|
||||||
member => member.member !== data.member && member.enabled !== false && teamMemberEnabled(member.member),
|
member => member.member !== data.member && member.enabled !== false && teamMemberEnabled(member.member),
|
||||||
);
|
);
|
||||||
@@ -609,7 +613,10 @@ export function orderReviews(
|
|||||||
<label>
|
<label>
|
||||||
修改为
|
修改为
|
||||||
<select name="member" required defaultValue="">
|
<select name="member" required defaultValue="">
|
||||||
{opts([['', '请选择新归属'], ...members.map(member => [member.member, member.label])])}
|
{opts([
|
||||||
|
['', '请选择新归属'],
|
||||||
|
...members.map((member): [string, string] => [member.member, member.label]),
|
||||||
|
])}
|
||||||
</select>
|
</select>
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
@@ -622,8 +629,8 @@ export function orderReviews(
|
|||||||
<textarea
|
<textarea
|
||||||
name="reason"
|
name="reason"
|
||||||
required
|
required
|
||||||
maxLength="200"
|
maxLength={200}
|
||||||
rows="3"
|
rows={3}
|
||||||
placeholder="写清原归属录错的原因及正确归属。"
|
placeholder="写清原归属录错的原因及正确归属。"
|
||||||
></textarea>
|
></textarea>
|
||||||
</label>
|
</label>
|
||||||
@@ -647,7 +654,7 @@ export function orderReviews(
|
|||||||
<>
|
<>
|
||||||
{orderOwnershipEffectHTML(request.before.member)}
|
{orderOwnershipEffectHTML(request.before.member)}
|
||||||
<label>
|
<label>
|
||||||
复核备注(选填)<textarea name="note" maxLength="200" rows="2"></textarea>
|
复核备注(选填)<textarea name="note" maxLength={200} rows={2}></textarea>
|
||||||
</label>
|
</label>
|
||||||
<label className="check">
|
<label className="check">
|
||||||
<input type="checkbox" name="verified" required />
|
<input type="checkbox" name="verified" required />
|
||||||
@@ -662,8 +669,8 @@ export function orderReviews(
|
|||||||
<textarea
|
<textarea
|
||||||
name="note"
|
name="note"
|
||||||
required
|
required
|
||||||
maxLength="200"
|
maxLength={200}
|
||||||
rows="3"
|
rows={3}
|
||||||
placeholder="写清需要重新核对的地方。"
|
placeholder="写清需要重新核对的地方。"
|
||||||
></textarea>
|
></textarea>
|
||||||
</label>
|
</label>
|
||||||
@@ -687,12 +694,12 @@ export function orderReviews(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
const requireOrderChangeDetail = () => ({
|
const requireOrderChangeDetail = () => ({
|
||||||
order: currentOrder,
|
order: currentOrder!,
|
||||||
data: orderChangeDetail.data,
|
data: orderChangeDetail!.data!,
|
||||||
});
|
});
|
||||||
function showOrderChangeForm(kind) {
|
function showOrderChangeForm(kind: string) {
|
||||||
const { order, data } = requireOrderChangeDetail(),
|
const { order, data } = requireOrderChangeDetail(),
|
||||||
request = data.pending;
|
request = data.pending!;
|
||||||
if (!['approve', 'reject'].includes(kind)) throw new Error('修改复核操作无效,请重新读取订单。');
|
if (!['approve', 'reject'].includes(kind)) throw new Error('修改复核操作无效,请重新读取订单。');
|
||||||
if (state.user.role !== 'owner' || !data.canApprove || request?.status !== 'pending')
|
if (state.user.role !== 'owner' || !data.canApprove || request?.status !== 'pending')
|
||||||
throw new Error('修改申请由店主账号复核。');
|
throw new Error('修改申请由店主账号复核。');
|
||||||
@@ -716,7 +723,7 @@ export function orderReviews(
|
|||||||
{orderChangeActionSummaryHTML(request)}
|
{orderChangeActionSummaryHTML(request)}
|
||||||
{orderChangeComparisonHTML(request)}
|
{orderChangeComparisonHTML(request)}
|
||||||
<label>
|
<label>
|
||||||
复核备注(选填)<textarea name="note" maxLength="200" rows="2"></textarea>
|
复核备注(选填)<textarea name="note" maxLength={200} rows={2}></textarea>
|
||||||
</label>
|
</label>
|
||||||
<label className="check">
|
<label className="check">
|
||||||
<input type="checkbox" name="verified" required />
|
<input type="checkbox" name="verified" required />
|
||||||
@@ -732,8 +739,8 @@ export function orderReviews(
|
|||||||
<textarea
|
<textarea
|
||||||
name="note"
|
name="note"
|
||||||
required
|
required
|
||||||
maxLength="200"
|
maxLength={200}
|
||||||
rows="3"
|
rows={3}
|
||||||
placeholder="写清需要重新核对或补充的地方。"
|
placeholder="写清需要重新核对或补充的地方。"
|
||||||
></textarea>
|
></textarea>
|
||||||
</label>
|
</label>
|
||||||
+182
-136
@@ -1,3 +1,21 @@
|
|||||||
|
import type { ReactNode, ButtonHTMLAttributes, InputHTMLAttributes } from 'react';
|
||||||
|
import type { OrderContext, Options } from '../viewTypes';
|
||||||
|
import type {
|
||||||
|
OrderRecord,
|
||||||
|
OrderLine,
|
||||||
|
OwnershipRequest,
|
||||||
|
ChangeRequest,
|
||||||
|
CancelSummary,
|
||||||
|
Member,
|
||||||
|
RelatedLock,
|
||||||
|
LockImpact,
|
||||||
|
InventoryRow,
|
||||||
|
InventoryChange,
|
||||||
|
LockCosts,
|
||||||
|
OrderAfterSale,
|
||||||
|
BookRow,
|
||||||
|
PrintStatus,
|
||||||
|
} from '../orderData';
|
||||||
import { Children, Fragment } from 'react';
|
import { Children, Fragment } from 'react';
|
||||||
import { Calc as LedgerCalc, Cards as CreditCardFees, Values } from '../../../shared';
|
import { Calc as LedgerCalc, Cards as CreditCardFees, Values } from '../../../shared';
|
||||||
export function sharedViews({
|
export function sharedViews({
|
||||||
@@ -8,8 +26,11 @@ export function sharedViews({
|
|||||||
orderOwnershipDetail,
|
orderOwnershipDetail,
|
||||||
orderCancellationDetail,
|
orderCancellationDetail,
|
||||||
ui = {},
|
ui = {},
|
||||||
}) {
|
}: OrderContext) {
|
||||||
function stockCountValue(value, { zero = false, optional = false, signed = false, title = '库存数量(对)' } = {}) {
|
function stockCountValue(
|
||||||
|
value: unknown,
|
||||||
|
{ zero = false, optional = false, signed = false, title = '库存数量(对)' } = {},
|
||||||
|
) {
|
||||||
const text = String(value ?? '').trim();
|
const text = String(value ?? '').trim();
|
||||||
if (!text && optional) return null;
|
if (!text && optional) return null;
|
||||||
if (signed) {
|
if (signed) {
|
||||||
@@ -44,8 +65,8 @@ export function sharedViews({
|
|||||||
return Array.isArray(state?.pockets) ? state.pockets : defaultPocketKeys;
|
return Array.isArray(state?.pockets) ? state.pockets : defaultPocketKeys;
|
||||||
}
|
}
|
||||||
function stockCountField(
|
function stockCountField(
|
||||||
pocket,
|
pocket: string,
|
||||||
value = '',
|
value: string | number | null | undefined = '',
|
||||||
{
|
{
|
||||||
name = 'stockCount',
|
name = 'stockCount',
|
||||||
title = '出库数量(对)',
|
title = '出库数量(对)',
|
||||||
@@ -53,7 +74,7 @@ export function sharedViews({
|
|||||||
readOnly = false,
|
readOnly = false,
|
||||||
visible = pocketCountsEnabled(pocket),
|
visible = pocketCountsEnabled(pocket),
|
||||||
help,
|
help,
|
||||||
} = {},
|
}: { name?: string; title?: string; optional?: boolean; readOnly?: boolean; visible?: boolean; help?: string } = {},
|
||||||
) {
|
) {
|
||||||
const hint = help ?? (optional ? '历史未记录对数,可保留空白;与计工费件数分别填写。' : '与计工费件数分别填写。');
|
const hint = help ?? (optional ? '历史未记录对数,可保留空白;与计工费件数分别填写。' : '与计工费件数分别填写。');
|
||||||
return (
|
return (
|
||||||
@@ -79,7 +100,7 @@ export function sharedViews({
|
|||||||
function currentMember() {
|
function currentMember() {
|
||||||
return state?.user?.member || session?.user?.member || (state?.user?.role === 'owner' ? 'owner' : 'assistant');
|
return state?.user?.member || session?.user?.member || (state?.user?.role === 'owner' ? 'owner' : 'assistant');
|
||||||
}
|
}
|
||||||
function normalizePaymentAccount(account) {
|
function normalizePaymentAccount(account: string) {
|
||||||
return typeof CreditCardFees === 'object' && typeof CreditCardFees.normalizeAccount === 'function'
|
return typeof CreditCardFees === 'object' && typeof CreditCardFees.normalizeAccount === 'function'
|
||||||
? CreditCardFees.normalizeAccount(account)
|
? CreditCardFees.normalizeAccount(account)
|
||||||
: ['助理信用卡', '助理1信用卡', '助理2信用卡', '麦麦信用卡'].includes(account)
|
: ['助理信用卡', '助理1信用卡', '助理2信用卡', '麦麦信用卡'].includes(account)
|
||||||
@@ -95,7 +116,7 @@ export function sharedViews({
|
|||||||
);
|
);
|
||||||
if (assistantFirst)
|
if (assistantFirst)
|
||||||
keys = [...keys.filter(member => member !== 'owner'), ...keys.filter(member => member === 'owner')];
|
keys = [...keys.filter(member => member !== 'owner'), ...keys.filter(member => member === 'owner')];
|
||||||
const options = keys.map(member => [
|
const options = keys.map((member): [string, string] => [
|
||||||
member,
|
member,
|
||||||
teamMemberName(member) + (historical && !teamMemberEnabled(member) ? '(已停用)' : ''),
|
teamMemberName(member) + (historical && !teamMemberEnabled(member) ? '(已停用)' : ''),
|
||||||
]);
|
]);
|
||||||
@@ -103,7 +124,7 @@ export function sharedViews({
|
|||||||
options.push([selected, teamMemberName(selected) + '(已停用 · 原记录)']);
|
options.push([selected, teamMemberName(selected) + '(已停用 · 原记录)']);
|
||||||
return options;
|
return options;
|
||||||
}
|
}
|
||||||
const choice = (title, name, values, selected) => {
|
const choice = (title: string, name: string, values: Options, selected?: string) => {
|
||||||
if (
|
if (
|
||||||
selected &&
|
selected &&
|
||||||
teamMemberKeys().includes(selected) &&
|
teamMemberKeys().includes(selected) &&
|
||||||
@@ -121,19 +142,25 @@ export function sharedViews({
|
|||||||
</label>
|
</label>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
const moneyField = (title, name, value = '') =>
|
const moneyField = (title: string, name: string, value: string | number = '') =>
|
||||||
field(title, name, value, 'number', {
|
field(title, name, value, 'number', {
|
||||||
min: '0',
|
min: '0',
|
||||||
step: '0.01',
|
step: '0.01',
|
||||||
required: true,
|
required: true,
|
||||||
});
|
});
|
||||||
const field = (title, name, value = '', type = 'text', props = {}) => (
|
const field = (
|
||||||
|
title: string,
|
||||||
|
name: string,
|
||||||
|
value: string | number = '',
|
||||||
|
type = 'text',
|
||||||
|
props: InputHTMLAttributes<HTMLInputElement> = {},
|
||||||
|
) => (
|
||||||
<label>
|
<label>
|
||||||
{title}
|
{title}
|
||||||
<input type={type} name={name} defaultValue={value} {...props} />
|
<input type={type} name={name} defaultValue={value} {...props} />
|
||||||
</label>
|
</label>
|
||||||
);
|
);
|
||||||
const opts = values =>
|
const opts = (values: Options) =>
|
||||||
values.map(v => {
|
values.map(v => {
|
||||||
const [value, name, disabled] = Array.isArray(v) ? v : [v, v];
|
const [value, name, disabled] = Array.isArray(v) ? v : [v, v];
|
||||||
return (
|
return (
|
||||||
@@ -142,10 +169,7 @@ export function sharedViews({
|
|||||||
</option>
|
</option>
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
function teamMemberEnabled(member) {
|
const actionName: Record<string, string> = {
|
||||||
return Values.memberEnabled(state, member);
|
|
||||||
}
|
|
||||||
const actionName = {
|
|
||||||
confirm: '确认订单',
|
confirm: '确认订单',
|
||||||
receipt: '登记收款',
|
receipt: '登记收款',
|
||||||
refund: '登记退款',
|
refund: '登记退款',
|
||||||
@@ -161,7 +185,7 @@ export function sharedViews({
|
|||||||
correct: '更正流水',
|
correct: '更正流水',
|
||||||
ownership: '修改订单归属',
|
ownership: '修改订单归属',
|
||||||
};
|
};
|
||||||
function orderOwnershipEffectHTML(before) {
|
function orderOwnershipEffectHTML(before: string) {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<p className="small muted">
|
<p className="small muted">
|
||||||
@@ -177,11 +201,11 @@ export function sharedViews({
|
|||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function orderOwnershipTime(value) {
|
function orderOwnershipTime(value: string | null) {
|
||||||
const date = new Date(value);
|
const date = new Date(value!);
|
||||||
return Number.isNaN(date.getTime()) ? '时间未提供' : date.toLocaleString('zh-CN');
|
return Number.isNaN(date.getTime()) ? '时间未提供' : date.toLocaleString('zh-CN');
|
||||||
}
|
}
|
||||||
function validOrderOwnershipMember(value) {
|
function validOrderOwnershipMember(value: Member) {
|
||||||
return value && teamMemberKeys().includes(value.member) && typeof value.label === 'string' && !!value.label;
|
return value && teamMemberKeys().includes(value.member) && typeof value.label === 'string' && !!value.label;
|
||||||
}
|
}
|
||||||
const orderOwnershipStatus = {
|
const orderOwnershipStatus = {
|
||||||
@@ -189,7 +213,7 @@ export function sharedViews({
|
|||||||
approved: '已修改归属',
|
approved: '已修改归属',
|
||||||
rejected: '已驳回',
|
rejected: '已驳回',
|
||||||
};
|
};
|
||||||
function validateOrderOwnershipRequest(request, orderId) {
|
function validateOrderOwnershipRequest(request: OwnershipRequest, orderId: string | undefined = undefined) {
|
||||||
if (
|
if (
|
||||||
!request ||
|
!request ||
|
||||||
typeof request.id !== 'string' ||
|
typeof request.id !== 'string' ||
|
||||||
@@ -211,7 +235,7 @@ export function sharedViews({
|
|||||||
throw new Error('归属修改资料未完整返回,请重新读取订单后复核。');
|
throw new Error('归属修改资料未完整返回,请重新读取订单后复核。');
|
||||||
return request;
|
return request;
|
||||||
}
|
}
|
||||||
function orderOwnershipPairHTML(request) {
|
function orderOwnershipPairHTML(request: OwnershipRequest) {
|
||||||
validateOrderOwnershipRequest(request);
|
validateOrderOwnershipRequest(request);
|
||||||
return (
|
return (
|
||||||
<div className="order-ownership-pair" aria-label="订单归属原值与新值">
|
<div className="order-ownership-pair" aria-label="订单归属原值与新值">
|
||||||
@@ -227,17 +251,17 @@ export function sharedViews({
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function relatedPriceLocksHTML(items) {
|
function relatedPriceLocksHTML(items: RelatedLock[] | undefined) {
|
||||||
const locks = validateRelatedPriceLocks(items);
|
const locks = validateRelatedPriceLocks(items);
|
||||||
if (!locks.length) return '';
|
if (!locks.length) return '';
|
||||||
const money = value => (value === null ? '待补齐' : '¥' + yuan(value)),
|
const money = (value?: number | null) => (value === null ? '待补齐' : '¥' + yuan(value)),
|
||||||
sources = value =>
|
sources = (value: LockImpact) =>
|
||||||
value.allocations.length
|
value.allocations.length
|
||||||
? value.allocations.map(part => teamMemberName(part.payer) + ' ' + money(part.amount)).join(';')
|
? value.allocations.map(part => teamMemberName(part.payer) + ' ' + money(part.amount)).join(';')
|
||||||
: value.materialAmount === null
|
: value.materialAmount === null
|
||||||
? '待补齐后分摊'
|
? '待补齐后分摊'
|
||||||
: '无分摊金额';
|
: '无分摊金额';
|
||||||
const pair = (name, before, after) => (
|
const pair = (name: string, before: ReactNode, after: ReactNode) => (
|
||||||
<tr>
|
<tr>
|
||||||
<th scope="row">{name}</th>
|
<th scope="row">{name}</th>
|
||||||
<td>{before}</td>
|
<td>{before}</td>
|
||||||
@@ -266,7 +290,7 @@ export function sharedViews({
|
|||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{pair('原锁预留料费', money(lock.before.materialAmount), money(lock.after.materialAmount))}
|
{pair('原锁预留料费', money(lock.before.materialAmount), money(lock.after.materialAmount))}
|
||||||
{['before', 'after'].some(side => Object.hasOwn(lock[side], 'usedMaterialAmount'))
|
{(['before', 'after'] as const).some(side => Object.hasOwn(lock[side], 'usedMaterialAmount'))
|
||||||
? pair(
|
? pair(
|
||||||
'交付耗用原锁料费',
|
'交付耗用原锁料费',
|
||||||
Object.hasOwn(lock.before, 'usedMaterialAmount')
|
Object.hasOwn(lock.before, 'usedMaterialAmount')
|
||||||
@@ -277,7 +301,7 @@ export function sharedViews({
|
|||||||
: '未交付',
|
: '未交付',
|
||||||
)
|
)
|
||||||
: ''}
|
: ''}
|
||||||
{['before', 'after'].some(side => Object.hasOwn(lock[side], 'leftoverCost'))
|
{(['before', 'after'] as const).some(side => Object.hasOwn(lock[side], 'leftoverCost'))
|
||||||
? pair(
|
? pair(
|
||||||
'少重回池成本',
|
'少重回池成本',
|
||||||
Object.hasOwn(lock.before, 'leftoverCost') ? money(lock.before.leftoverCost) : '未交付',
|
Object.hasOwn(lock.before, 'leftoverCost') ? money(lock.before.leftoverCost) : '未交付',
|
||||||
@@ -294,7 +318,7 @@ export function sharedViews({
|
|||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function inventoryCountHTML(item, { signed = false } = {}) {
|
function inventoryCountHTML(item: InventoryRow, { signed = false } = {}) {
|
||||||
return Number.isSafeInteger(item?.stockCount) ? (
|
return Number.isSafeInteger(item?.stockCount) ? (
|
||||||
<div className="small stock-count-number">
|
<div className="small stock-count-number">
|
||||||
{stockCountText(item.stockCount, {
|
{stockCountText(item.stockCount, {
|
||||||
@@ -307,9 +331,9 @@ export function sharedViews({
|
|||||||
''
|
''
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function orderChangeInventoryHTML(inventory) {
|
function orderChangeInventoryHTML(inventory: InventoryChange | undefined) {
|
||||||
if (!inventory) return '';
|
if (!inventory) return '';
|
||||||
const table = (title, rows, changes = false) => (
|
const table = (title: string, rows: InventoryRow[], changes = false) => (
|
||||||
<>
|
<>
|
||||||
<h3>{title}</h3>
|
<h3>{title}</h3>
|
||||||
{rows.length ? (
|
{rows.length ? (
|
||||||
@@ -361,11 +385,11 @@ export function sharedViews({
|
|||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function orderChangeEffectiveExpenses(order) {
|
function orderChangeEffectiveExpenses(order: OrderRecord) {
|
||||||
const corrected = new Set((order.corrections || []).filter(row => row.type === 'expense').map(row => row.target));
|
const corrected = new Set((order.corrections || []).filter(row => row.type === 'expense').map(row => row.target));
|
||||||
return order.expenses.filter(row => row.amount > 0 && !corrected.has(row.id));
|
return order.expenses.filter(row => row.amount > 0 && !corrected.has(row.id));
|
||||||
}
|
}
|
||||||
function orderChangeExpensesValue(order) {
|
function orderChangeExpensesValue(order: OrderRecord) {
|
||||||
return (
|
return (
|
||||||
orderChangeEffectiveExpenses(order)
|
orderChangeEffectiveExpenses(order)
|
||||||
.map(
|
.map(
|
||||||
@@ -375,7 +399,7 @@ export function sharedViews({
|
|||||||
.join('\n\n') || '无已记费用'
|
.join('\n\n') || '无已记费用'
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function orderChangePaymentsValue(order) {
|
function orderChangePaymentsValue(order: OrderRecord) {
|
||||||
const corrected = new Set((order.corrections || []).filter(row => row.type === 'payment').map(row => row.target));
|
const corrected = new Set((order.corrections || []).filter(row => row.type === 'payment').map(row => row.target));
|
||||||
return (
|
return (
|
||||||
order.payments
|
order.payments
|
||||||
@@ -387,12 +411,16 @@ export function sharedViews({
|
|||||||
.join('\n\n') || '无有效收退款'
|
.join('\n\n') || '无有效收退款'
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function orderChangePriceLockCostsHTML(before, after, title = '锁价购料成本') {
|
function orderChangePriceLockCostsHTML(
|
||||||
|
before: { priceLockCosts?: LockCosts },
|
||||||
|
after: { priceLockCosts?: LockCosts },
|
||||||
|
title = '锁价购料成本',
|
||||||
|
): ReactNode {
|
||||||
if (!before.priceLockCosts && !after.priceLockCosts) return '';
|
if (!before.priceLockCosts && !after.priceLockCosts) return '';
|
||||||
if (before.priceLockCosts?.lines || after.priceLockCosts?.lines) {
|
if (before.priceLockCosts?.lines || after.priceLockCosts?.lines) {
|
||||||
const a = before.priceLockCosts || {},
|
const a = before.priceLockCosts || {},
|
||||||
b = after.priceLockCosts || {},
|
b = after.priceLockCosts || {},
|
||||||
rows = a.lines || b.lines;
|
rows = a.lines || b.lines!;
|
||||||
return Children.toArray(
|
return Children.toArray(
|
||||||
rows.map((row, index) => {
|
rows.map((row, index) => {
|
||||||
const left = a.lines?.find(item => item.lineId === row.lineId) || {},
|
const left = a.lines?.find(item => item.lineId === row.lineId) || {},
|
||||||
@@ -417,11 +445,11 @@ export function sharedViews({
|
|||||||
}
|
}
|
||||||
const a = before.priceLockCosts || {},
|
const a = before.priceLockCosts || {},
|
||||||
b = after.priceLockCosts || {},
|
b = after.priceLockCosts || {},
|
||||||
source = value => (value === 'pool' ? '原锁料池' : value === 'manual' ? '手填原锁料价' : '未提供');
|
source = (value?: string) => (value === 'pool' ? '原锁料池' : value === 'manual' ? '手填原锁料价' : '未提供');
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<tr className="change-section-row">
|
<tr className="change-section-row">
|
||||||
<th colSpan="3" scope="colgroup">
|
<th colSpan={3} scope="colgroup">
|
||||||
{title}
|
{title}
|
||||||
</th>
|
</th>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -443,7 +471,7 @@ export function sharedViews({
|
|||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function orderChangeLineValue(line, kind) {
|
function orderChangeLineValue(line: OrderLine | undefined, kind: string) {
|
||||||
if (!line) return '无此商品';
|
if (!line) return '无此商品';
|
||||||
const money = orderChangeMoney;
|
const money = orderChangeMoney;
|
||||||
if (kind === 'name') return `${line.name || '未填写'}${line.priceNote ? '\n' + line.priceNote : ''}`;
|
if (kind === 'name') return `${line.name || '未填写'}${line.priceNote ? '\n' + line.priceNote : ''}`;
|
||||||
@@ -480,7 +508,7 @@ export function sharedViews({
|
|||||||
return `料费:${line.costMaterial?.mode === 'pool' ? line.materialPool?.allocations?.map(item => orderChangePayer(item.payer) + ' ' + money(item.amount)).join(';') || '按真实采购分摊' : orderChangePayer(line.costPayers?.material ?? line.payer)}\n进货工费:${orderChangePayer(line.costPayers?.labor ?? line.payer)}\n配件及其他:${orderChangePayer(line.payer)}`;
|
return `料费:${line.costMaterial?.mode === 'pool' ? line.materialPool?.allocations?.map(item => orderChangePayer(item.payer) + ' ' + money(item.amount)).join(';') || '按真实采购分摊' : orderChangePayer(line.costPayers?.material ?? line.payer)}\n进货工费:${orderChangePayer(line.costPayers?.labor ?? line.payer)}\n配件及其他:${orderChangePayer(line.payer)}`;
|
||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
function orderChangePair(title, before, after) {
|
function orderChangePair(title: string, before: ReactNode, after: ReactNode) {
|
||||||
const changed = String(before ?? '') !== String(after ?? '');
|
const changed = String(before ?? '') !== String(after ?? '');
|
||||||
return (
|
return (
|
||||||
<tr
|
<tr
|
||||||
@@ -499,13 +527,15 @@ export function sharedViews({
|
|||||||
</tr>
|
</tr>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function validateRelatedPriceLocks(items) {
|
function validateRelatedPriceLocks(items: RelatedLock[] | undefined) {
|
||||||
if (items === undefined) return [];
|
if (items === undefined) return [];
|
||||||
const amount = value => value === null || (Number.isSafeInteger(value) && value >= 0);
|
const amount = (value?: number | null) => value === null || (Number.isSafeInteger(value) && value! >= 0);
|
||||||
const snapshot = value =>
|
const snapshot = (value: LockImpact) =>
|
||||||
value &&
|
value &&
|
||||||
amount(value.materialAmount) &&
|
amount(value.materialAmount) &&
|
||||||
['usedMaterialAmount', 'leftoverCost'].every(key => !Object.hasOwn(value, key) || amount(value[key])) &&
|
(['usedMaterialAmount', 'leftoverCost'] as const).every(
|
||||||
|
key => !Object.hasOwn(value, key) || amount(value[key]),
|
||||||
|
) &&
|
||||||
Array.isArray(value.allocations) &&
|
Array.isArray(value.allocations) &&
|
||||||
value.allocations.every(
|
value.allocations.every(
|
||||||
part => teamMemberKeys().includes(part.payer) && Number.isSafeInteger(part.amount) && part.amount >= 0,
|
part => teamMemberKeys().includes(part.payer) && Number.isSafeInteger(part.amount) && part.amount >= 0,
|
||||||
@@ -527,15 +557,15 @@ export function sharedViews({
|
|||||||
throw new Error('关联锁价单的成本影响未完整返回,请重新读取后复核。');
|
throw new Error('关联锁价单的成本影响未完整返回,请重新读取后复核。');
|
||||||
return items;
|
return items;
|
||||||
}
|
}
|
||||||
function validateOrderChangeRequest(request, orderId) {
|
function validateOrderChangeRequest(request: ChangeRequest, orderId: string | undefined = undefined) {
|
||||||
const validSnapshot = order =>
|
const validSnapshot = (order: OrderRecord) =>
|
||||||
order &&
|
order &&
|
||||||
order.id === request.order_id &&
|
order.id === request.order_id &&
|
||||||
Number.isSafeInteger(order.total) &&
|
Number.isSafeInteger(order.total) &&
|
||||||
Array.isArray(order.lines) &&
|
Array.isArray(order.lines) &&
|
||||||
Array.isArray(order.expenses) &&
|
Array.isArray(order.expenses) &&
|
||||||
Array.isArray(order.payments);
|
Array.isArray(order.payments);
|
||||||
const nullable = value => value === null || Number.isSafeInteger(value);
|
const nullable = (value?: number | null) => value === null || Number.isSafeInteger(value);
|
||||||
if (
|
if (
|
||||||
!request ||
|
!request ||
|
||||||
typeof request.id !== 'string' ||
|
typeof request.id !== 'string' ||
|
||||||
@@ -551,11 +581,13 @@ export function sharedViews({
|
|||||||
typeof request.canApprove !== 'boolean' ||
|
typeof request.canApprove !== 'boolean' ||
|
||||||
!validSnapshot(request.before) ||
|
!validSnapshot(request.before) ||
|
||||||
!validSnapshot(request.after) ||
|
!validSnapshot(request.after) ||
|
||||||
!['before', 'after'].every(
|
!(['before', 'after'] as const).every(
|
||||||
side =>
|
side =>
|
||||||
request.summary?.[side] &&
|
request.summary?.[side] &&
|
||||||
['total', 'netReceived', 'directCost'].every(key => Number.isSafeInteger(request.summary[side][key])) &&
|
(['total', 'netReceived', 'directCost'] as const).every(key =>
|
||||||
['goodsCost', 'profit', 'settlementDue'].every(key => nullable(request.summary[side][key])),
|
Number.isSafeInteger(request.summary[side][key]),
|
||||||
|
) &&
|
||||||
|
(['goodsCost', 'profit', 'settlementDue'] as const).every(key => nullable(request.summary[side][key])),
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
throw new Error('修改申请资料未完整返回,请重新读取订单后复核。');
|
throw new Error('修改申请资料未完整返回,请重新读取订单后复核。');
|
||||||
@@ -579,7 +611,7 @@ export function sharedViews({
|
|||||||
if (
|
if (
|
||||||
inventory !== undefined &&
|
inventory !== undefined &&
|
||||||
(!inventory ||
|
(!inventory ||
|
||||||
!['before', 'after', 'changes'].every(
|
!(['before', 'after', 'changes'] as const).every(
|
||||||
key =>
|
key =>
|
||||||
Array.isArray(inventory[key]) &&
|
Array.isArray(inventory[key]) &&
|
||||||
inventory[key].every(
|
inventory[key].every(
|
||||||
@@ -590,7 +622,7 @@ export function sharedViews({
|
|||||||
throw new Error('变更申请库存摘要未完整返回,请重新读取后复核。');
|
throw new Error('变更申请库存摘要未完整返回,请重新读取后复核。');
|
||||||
return request;
|
return request;
|
||||||
}
|
}
|
||||||
function orderChangeComparisonHTML(raw) {
|
function orderChangeComparisonHTML(raw: ChangeRequest) {
|
||||||
const request = validateOrderChangeRequest(raw),
|
const request = validateOrderChangeRequest(raw),
|
||||||
before = request.before,
|
before = request.before,
|
||||||
after = request.after;
|
after = request.after;
|
||||||
@@ -601,14 +633,16 @@ export function sharedViews({
|
|||||||
{
|
{
|
||||||
<>
|
<>
|
||||||
{Children.toArray(
|
{Children.toArray(
|
||||||
[
|
(
|
||||||
['业务日期', 'date'],
|
[
|
||||||
['客户称呼/代号', 'customer'],
|
['业务日期', 'date'],
|
||||||
['开单人', 'salesperson'],
|
['客户称呼/代号', 'customer'],
|
||||||
['收款方式与收款人', 'payment_account'],
|
['开单人', 'salesperson'],
|
||||||
['客户单备注', 'note'],
|
['收款方式与收款人', 'payment_account'],
|
||||||
['内部备注(客户不可见)', 'internal_note'],
|
['客户单备注', 'note'],
|
||||||
].map(([title, key]) =>
|
['内部备注(客户不可见)', 'internal_note'],
|
||||||
|
] as const
|
||||||
|
).map(([title, key]) =>
|
||||||
orderChangePair(
|
orderChangePair(
|
||||||
title,
|
title,
|
||||||
key === 'payment_account' ? accountDisplayName(before[key]) : before[key],
|
key === 'payment_account' ? accountDisplayName(before[key]) : before[key],
|
||||||
@@ -630,14 +664,16 @@ export function sharedViews({
|
|||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
const summary = Children.toArray(
|
const summary = Children.toArray(
|
||||||
[
|
(
|
||||||
['成交金额', 'total'],
|
[
|
||||||
['收款净额', 'netReceived'],
|
['成交金额', 'total'],
|
||||||
['货品成本', 'goodsCost'],
|
['收款净额', 'netReceived'],
|
||||||
['实际费用合计', 'directCost'],
|
['货品成本', 'goodsCost'],
|
||||||
['利润', 'profit'],
|
['实际费用合计', 'directCost'],
|
||||||
['双方待结净额', 'settlementDue'],
|
['利润', 'profit'],
|
||||||
].map(([title, key]) =>
|
['双方待结净额', 'settlementDue'],
|
||||||
|
] as const
|
||||||
|
).map(([title, key]) =>
|
||||||
orderChangePair(
|
orderChangePair(
|
||||||
title,
|
title,
|
||||||
orderChangeMoney(request.summary.before[key]),
|
orderChangeMoney(request.summary.before[key]),
|
||||||
@@ -653,7 +689,7 @@ export function sharedViews({
|
|||||||
(_, index) => (
|
(_, index) => (
|
||||||
<>
|
<>
|
||||||
<tr className="change-section-row">
|
<tr className="change-section-row">
|
||||||
<th colSpan="3" scope="colgroup">
|
<th colSpan={3} scope="colgroup">
|
||||||
商品 {index + 1}
|
商品 {index + 1}
|
||||||
</th>
|
</th>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -726,7 +762,7 @@ export function sharedViews({
|
|||||||
{summary}
|
{summary}
|
||||||
{lines}
|
{lines}
|
||||||
<tr className="change-section-row">
|
<tr className="change-section-row">
|
||||||
<th colSpan="3" scope="colgroup">
|
<th colSpan={3} scope="colgroup">
|
||||||
逐笔收退款与实际费用
|
逐笔收退款与实际费用
|
||||||
</th>
|
</th>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -752,7 +788,7 @@ export function sharedViews({
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function orderChangeCell(value) {
|
function orderChangeCell(value: ReactNode) {
|
||||||
return String(value == null || value === '' ? '未填写' : value)
|
return String(value == null || value === '' ? '未填写' : value)
|
||||||
.split('\n')
|
.split('\n')
|
||||||
.map((line, index) => (
|
.map((line, index) => (
|
||||||
@@ -762,58 +798,60 @@ export function sharedViews({
|
|||||||
</Fragment>
|
</Fragment>
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
function orderChangePayer(value) {
|
function orderChangePayer(value: string | undefined) {
|
||||||
return value ? teamMemberName(value) : '待补齐';
|
return value ? teamMemberName(value) : '待补齐';
|
||||||
}
|
}
|
||||||
function orderChangeMoney(value) {
|
function orderChangeMoney(value: number | null | undefined) {
|
||||||
return value == null ? '待补齐' : '¥' + yuan(value);
|
return value == null ? '待补齐' : '¥' + yuan(value);
|
||||||
}
|
}
|
||||||
function orderChangeInputMoney(value) {
|
function orderChangeInputMoney(value: unknown) {
|
||||||
try {
|
try {
|
||||||
return orderChangeMoney(LedgerCalc.cents(value));
|
return orderChangeMoney(LedgerCalc.cents(value));
|
||||||
} catch {
|
} catch {
|
||||||
return '金额未提供';
|
return '金额未提供';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
function stockCountText(value, { signed = false, unknown = '未记录对数' } = {}) {
|
function stockCountText(value: unknown, { signed = false, unknown = '未记录对数' } = {}) {
|
||||||
return Number.isSafeInteger(value) ? (signed && value > 0 ? '+' : '') + value + '对' : unknown;
|
return Number.isSafeInteger(value) ? (signed && Number(value) > 0 ? '+' : '') + value + '对' : unknown;
|
||||||
}
|
}
|
||||||
function pocketCountsEnabled(key) {
|
function pocketCountsEnabled(key: string) {
|
||||||
return !!key && state?.pocketCatalog?.some(row => row.key === key && row.countUnit === 'pair') === true;
|
return !!key && state?.pocketCatalog?.some(row => row.key === key && row.countUnit === 'pair') === true;
|
||||||
}
|
}
|
||||||
function pocketLabel(key) {
|
function pocketLabel(key: string) {
|
||||||
return state?.pocketCatalog?.find(row => row.key === key)?.name || String(key ?? '');
|
return state?.pocketCatalog?.find(row => row.key === key)?.name || String(key ?? '');
|
||||||
}
|
}
|
||||||
function validateOrderAfterSaleRecord(record) {
|
function validateOrderAfterSaleRecord(record: OrderAfterSale | null) {
|
||||||
if (
|
if (
|
||||||
!record ||
|
!record ||
|
||||||
!Array.isArray(record.lines) ||
|
!Array.isArray(record.lines) ||
|
||||||
!record.lines.length ||
|
!record.lines.length ||
|
||||||
!record.lines.every(line =>
|
!record.lines.every(line =>
|
||||||
['quantity', 'materialReturnedCost', 'laborRestockedCost', 'costLoss'].every(key =>
|
(['quantity', 'materialReturnedCost', 'laborRestockedCost', 'costLoss'] as const).every(key =>
|
||||||
Number.isSafeInteger(line[key]),
|
Number.isSafeInteger(line[key]),
|
||||||
),
|
),
|
||||||
) ||
|
) ||
|
||||||
!record.summary ||
|
!record.summary ||
|
||||||
![
|
!(
|
||||||
'refundAmount',
|
[
|
||||||
'retainedAmount',
|
'refundAmount',
|
||||||
'materialReturnedCost',
|
'retainedAmount',
|
||||||
'laborRestockedCost',
|
'materialReturnedCost',
|
||||||
'costLoss',
|
'laborRestockedCost',
|
||||||
'directCost',
|
'costLoss',
|
||||||
'profit',
|
'directCost',
|
||||||
'profitAdjustment',
|
'profit',
|
||||||
].every(key => Number.isSafeInteger(record.summary[key]))
|
'profitAdjustment',
|
||||||
|
] as const
|
||||||
|
).every(key => Number.isSafeInteger(record.summary[key]))
|
||||||
)
|
)
|
||||||
throw new Error('售后核算资料未完整返回,请重新读取订单。');
|
throw new Error('售后核算资料未完整返回,请重新读取订单。');
|
||||||
return record;
|
return record;
|
||||||
}
|
}
|
||||||
function orderAfterSaleSummaryHTML(raw, { preview = false } = {}) {
|
function orderAfterSaleSummaryHTML(raw: OrderAfterSale | null, { preview = false } = {}) {
|
||||||
const record = validateOrderAfterSaleRecord(raw),
|
const record = validateOrderAfterSaleRecord(raw),
|
||||||
summary = record.summary,
|
summary = record.summary,
|
||||||
money = value => '¥' + yuan(value),
|
money = (value: number) => '¥' + yuan(value),
|
||||||
facts = [
|
facts: [string, number][] = [
|
||||||
['实际退款', summary.refundAmount],
|
['实际退款', summary.refundAmount],
|
||||||
['扣留客户款', summary.retainedAmount],
|
['扣留客户款', summary.retainedAmount],
|
||||||
['回料池原料成本', summary.materialReturnedCost],
|
['回料池原料成本', summary.materialReturnedCost],
|
||||||
@@ -893,7 +931,7 @@ export function sharedViews({
|
|||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function orderChangeActionSummaryHTML(request) {
|
function orderChangeActionSummaryHTML(request: ChangeRequest) {
|
||||||
const action = request.action || 'edit',
|
const action = request.action || 'edit',
|
||||||
input = request.action_input || request.action_details || {};
|
input = request.action_input || request.action_details || {};
|
||||||
if (action === 'edit') return '';
|
if (action === 'edit') return '';
|
||||||
@@ -964,8 +1002,8 @@ export function sharedViews({
|
|||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function orderChangeTime(value) {
|
function orderChangeTime(value: string | null) {
|
||||||
const date = new Date(value);
|
const date = new Date(value!);
|
||||||
return Number.isNaN(date.getTime()) ? '时间未提供' : date.toLocaleString('zh-CN');
|
return Number.isNaN(date.getTime()) ? '时间未提供' : date.toLocaleString('zh-CN');
|
||||||
}
|
}
|
||||||
const orderChangeStatus = {
|
const orderChangeStatus = {
|
||||||
@@ -973,7 +1011,7 @@ export function sharedViews({
|
|||||||
approved: '已同意变更',
|
approved: '已同意变更',
|
||||||
rejected: '已驳回',
|
rejected: '已驳回',
|
||||||
};
|
};
|
||||||
const orderChangeActionLabels = {
|
const orderChangeActionLabels: Record<string, string> = {
|
||||||
edit: '修改订单',
|
edit: '修改订单',
|
||||||
expense: '费用补记',
|
expense: '费用补记',
|
||||||
fees: '旧费用核实',
|
fees: '旧费用核实',
|
||||||
@@ -981,7 +1019,7 @@ export function sharedViews({
|
|||||||
return: '退货',
|
return: '退货',
|
||||||
cost: '成本补录',
|
cost: '成本补录',
|
||||||
};
|
};
|
||||||
function orderChangeActionLabel(request) {
|
function orderChangeActionLabel(request: ChangeRequest) {
|
||||||
if ((request.action_input || request.action_details)?.afterSale) return '处理订单售后';
|
if ((request.action_input || request.action_details)?.afterSale) return '处理订单售后';
|
||||||
return request.action_label || orderChangeActionLabels[request.action || 'edit'] || '订单变更';
|
return request.action_label || orderChangeActionLabels[request.action || 'edit'] || '订单变更';
|
||||||
}
|
}
|
||||||
@@ -990,20 +1028,20 @@ export function sharedViews({
|
|||||||
approved: '已同意取消',
|
approved: '已同意取消',
|
||||||
rejected: '已驳回',
|
rejected: '已驳回',
|
||||||
};
|
};
|
||||||
function orderCancellationTime(value) {
|
function orderCancellationTime(value: string | null) {
|
||||||
const date = new Date(value);
|
const date = new Date(value!);
|
||||||
return Number.isNaN(date.getTime()) ? '时间未提供' : date.toLocaleString('zh-CN');
|
return Number.isNaN(date.getTime()) ? '时间未提供' : date.toLocaleString('zh-CN');
|
||||||
}
|
}
|
||||||
const accountIdentity = value => Values.accountIdentity(teamMemberKeys(), value);
|
const accountIdentity = (value: string) => Values.accountIdentity(teamMemberKeys(), value);
|
||||||
function accountDisplayName(value) {
|
function accountDisplayName(value: string) {
|
||||||
const account = accountIdentity(value);
|
const account = accountIdentity(value);
|
||||||
return account ? teamMemberName(account.member) + account.channel : value;
|
return account ? teamMemberName(account.member) + account.channel : value;
|
||||||
}
|
}
|
||||||
function validateOrderCancellationSummary(summary) {
|
function validateOrderCancellationSummary(summary: CancelSummary | undefined) {
|
||||||
if (
|
if (
|
||||||
!summary ||
|
!summary ||
|
||||||
!['total', 'netReceived', 'directCost'].every(key => Number.isSafeInteger(summary[key])) ||
|
!(['total', 'netReceived', 'directCost'] as const).every(key => Number.isSafeInteger(summary[key])) ||
|
||||||
!['goodsCost', 'profit', 'settlementDue'].every(
|
!(['goodsCost', 'profit', 'settlementDue'] as const).every(
|
||||||
key => summary[key] === null || Number.isSafeInteger(summary[key]),
|
key => summary[key] === null || Number.isSafeInteger(summary[key]),
|
||||||
) ||
|
) ||
|
||||||
!Array.isArray(summary.inventory) ||
|
!Array.isArray(summary.inventory) ||
|
||||||
@@ -1021,9 +1059,9 @@ export function sharedViews({
|
|||||||
data.pending ||
|
data.pending ||
|
||||||
data.directToday !== true ||
|
data.directToday !== true ||
|
||||||
!/^\d{4}-\d{2}-\d{2}$/.test(data.directActionDate || '') ||
|
!/^\d{4}-\d{2}-\d{2}$/.test(data.directActionDate || '') ||
|
||||||
order.date !== data.directActionDate ||
|
order?.date !== data.directActionDate ||
|
||||||
order.price_lock_id ||
|
order?.price_lock_id ||
|
||||||
!['draft', 'confirmed', 'delivered'].includes(order.status)
|
!['draft', 'confirmed', 'delivered'].includes(order?.status || '')
|
||||||
)
|
)
|
||||||
return false;
|
return false;
|
||||||
try {
|
try {
|
||||||
@@ -1033,7 +1071,7 @@ export function sharedViews({
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
function orderActionCanDirect(kind, date = state.today, order = currentOrder) {
|
function orderActionCanDirect(kind: string, date = state.today, order = currentOrder) {
|
||||||
const data = currentOrderChange(order)?.data;
|
const data = currentOrderChange(order)?.data;
|
||||||
return (
|
return (
|
||||||
['expense', 'fees', 'refund', 'return'].includes(kind) &&
|
['expense', 'fees', 'refund', 'return'].includes(kind) &&
|
||||||
@@ -1041,18 +1079,18 @@ export function sharedViews({
|
|||||||
!data.pending &&
|
!data.pending &&
|
||||||
/^\d{4}-\d{2}-\d{2}$/.test(data.directActionDate || '') &&
|
/^\d{4}-\d{2}-\d{2}$/.test(data.directActionDate || '') &&
|
||||||
data.actions?.[kind]?.directToday === true &&
|
data.actions?.[kind]?.directToday === true &&
|
||||||
order.date === data.directActionDate &&
|
order?.date === data.directActionDate &&
|
||||||
date === data.directActionDate &&
|
date === data.directActionDate &&
|
||||||
!(ui.action === kind && ui.forceApproval)
|
!(ui.action === kind && ui.forceApproval)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function orderActionUsesChangeForm(kind) {
|
function orderActionUsesChangeForm(kind: string) {
|
||||||
return state.user.role === 'assistant' && ['expense', 'fees', 'refund', 'return', 'cost'].includes(kind);
|
return state.user.role === 'assistant' && ['expense', 'fees', 'refund', 'return', 'cost'].includes(kind);
|
||||||
}
|
}
|
||||||
function orderActionRequiresApproval(kind, date = state.today) {
|
function orderActionRequiresApproval(kind: string, date = state.today) {
|
||||||
return orderActionUsesChangeForm(kind) && !orderActionCanDirect(kind, date);
|
return orderActionUsesChangeForm(kind) && !orderActionCanDirect(kind, date);
|
||||||
}
|
}
|
||||||
function orderAfterSaleRecord(order) {
|
function orderAfterSaleRecord(order: OrderRecord | undefined) {
|
||||||
return order?.orderAfterSale || null;
|
return order?.orderAfterSale || null;
|
||||||
}
|
}
|
||||||
function orderOwnershipUser() {
|
function orderOwnershipUser() {
|
||||||
@@ -1080,7 +1118,7 @@ export function sharedViews({
|
|||||||
? orderChangeDetail
|
? orderChangeDetail
|
||||||
: null;
|
: null;
|
||||||
}
|
}
|
||||||
function orderChangePending(order) {
|
function orderChangePending(order: OrderRecord) {
|
||||||
return currentOrderChange(order)?.data?.pending || order?.changePending || null;
|
return currentOrderChange(order)?.data?.pending || order?.changePending || null;
|
||||||
}
|
}
|
||||||
function orderCancellationUser() {
|
function orderCancellationUser() {
|
||||||
@@ -1094,11 +1132,11 @@ export function sharedViews({
|
|||||||
? orderCancellationDetail
|
? orderCancellationDetail
|
||||||
: null;
|
: null;
|
||||||
}
|
}
|
||||||
function orderCancellationPending(order) {
|
function orderCancellationPending(order: OrderRecord) {
|
||||||
return currentOrderCancellation(order)?.data?.pending || order.cancellationPending || null;
|
return currentOrderCancellation(order)?.data?.pending || order.cancellationPending || null;
|
||||||
}
|
}
|
||||||
function printStatusBadge(value) {
|
function printStatusBadge(value: { id: string; kind?: string; printStatus?: PrintStatus }) {
|
||||||
if (['afterSale', 'orderAfterSale'].includes(value.kind)) return '';
|
if (['afterSale', 'orderAfterSale'].includes(value.kind ?? '')) return '';
|
||||||
const printed = value.printStatus?.printed;
|
const printed = value.printStatus?.printed;
|
||||||
return (
|
return (
|
||||||
<span
|
<span
|
||||||
@@ -1112,7 +1150,7 @@ export function sharedViews({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
const grams = Values.grams;
|
const grams = Values.grams;
|
||||||
const e = value => String(value ?? '');
|
const e = (value: unknown) => String(value ?? '');
|
||||||
const showOrderCopyEntry = false;
|
const showOrderCopyEntry = false;
|
||||||
const orderEntryTimeFormatter = new Intl.DateTimeFormat('zh-CN', {
|
const orderEntryTimeFormatter = new Intl.DateTimeFormat('zh-CN', {
|
||||||
timeZone: 'Asia/Shanghai',
|
timeZone: 'Asia/Shanghai',
|
||||||
@@ -1124,7 +1162,7 @@ export function sharedViews({
|
|||||||
hourCycle: 'h23',
|
hourCycle: 'h23',
|
||||||
});
|
});
|
||||||
const validOrderDate = Values.validDate;
|
const validOrderDate = Values.validDate;
|
||||||
function orderEntryTime(value) {
|
function orderEntryTime(value: unknown) {
|
||||||
if (
|
if (
|
||||||
typeof value !== 'string' ||
|
typeof value !== 'string' ||
|
||||||
!/^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d{1,3})?)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/.test(
|
!/^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d{1,3})?)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/.test(
|
||||||
@@ -1133,23 +1171,23 @@ export function sharedViews({
|
|||||||
!validOrderDate(value.slice(0, 10))
|
!validOrderDate(value.slice(0, 10))
|
||||||
)
|
)
|
||||||
return '未记录';
|
return '未记录';
|
||||||
const date = new Date(value);
|
const date = new Date(value!);
|
||||||
if (Number.isNaN(date.getTime())) return '未记录';
|
if (Number.isNaN(date.getTime())) return '未记录';
|
||||||
const parts = Object.fromEntries(orderEntryTimeFormatter.formatToParts(date).map(part => [part.type, part.value]));
|
const parts = Object.fromEntries(orderEntryTimeFormatter.formatToParts(date).map(part => [part.type, part.value]));
|
||||||
return `${parts.year}-${parts.month}-${parts.day} ${parts.hour}:${parts.minute}`;
|
return `${parts.year}-${parts.month}-${parts.day} ${parts.hour}:${parts.minute}`;
|
||||||
}
|
}
|
||||||
function orderEntryTimeHTML(order) {
|
function orderEntryTimeHTML(order: { created: string }) {
|
||||||
return <div className="small muted order-entry-time">录入时间(北京时间):{orderEntryTime(order.created)}</div>;
|
return <div className="small muted order-entry-time">录入时间(北京时间):{orderEntryTime(order.created)}</div>;
|
||||||
}
|
}
|
||||||
function orderIsReviewed(row) {
|
function orderIsReviewed(row: Pick<BookRow, 'kind' | 'revision' | 'reviewed_revision'>) {
|
||||||
return (
|
return (
|
||||||
!['afterSale', 'orderAfterSale', 'recovery'].includes(row.kind) &&
|
!['afterSale', 'orderAfterSale', 'recovery'].includes(row.kind ?? '') &&
|
||||||
Number.isSafeInteger(row.revision) &&
|
Number.isSafeInteger(row.revision) &&
|
||||||
row.revision > 0 &&
|
row.revision! > 0 &&
|
||||||
row.reviewed_revision === row.revision
|
row.reviewed_revision === row.revision
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
const label = {
|
const label: Record<string, string> = {
|
||||||
draft: '旧草稿',
|
draft: '旧草稿',
|
||||||
confirmed: '旧单待补齐',
|
confirmed: '旧单待补齐',
|
||||||
delivered: '已完成',
|
delivered: '已完成',
|
||||||
@@ -1158,36 +1196,44 @@ export function sharedViews({
|
|||||||
after_sale: '售后',
|
after_sale: '售后',
|
||||||
recovery: '回收',
|
recovery: '回收',
|
||||||
};
|
};
|
||||||
const badge = o => (
|
const badge = (o: { status: string }) => (
|
||||||
<span className={'order-status ' + (['draft', 'confirmed'].includes(o.status) ? 'danger-text' : 'muted')}>
|
<span className={'order-status ' + (['draft', 'confirmed'].includes(o.status) ? 'danger-text' : 'muted')}>
|
||||||
{label[o.status] || o.status}
|
{label[o.status] || o.status}
|
||||||
</span>
|
</span>
|
||||||
);
|
);
|
||||||
const button = (text, action, cls = '', props = {}) => (
|
const button = (
|
||||||
|
text: ReactNode,
|
||||||
|
action: string,
|
||||||
|
cls = '',
|
||||||
|
props: ButtonHTMLAttributes<HTMLButtonElement> & {
|
||||||
|
[key: `data-${string}`]: string | number | boolean | undefined;
|
||||||
|
} = {},
|
||||||
|
) => (
|
||||||
<button type="button" data-action={action} className={cls} {...props}>
|
<button type="button" data-action={action} className={cls} {...props}>
|
||||||
{text}
|
{text}
|
||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
function teamMemberName(member) {
|
function teamMemberName(member: string | undefined) {
|
||||||
return (
|
return (
|
||||||
state?.shopSettings?.members?.find(row => row.member === member)?.label ||
|
state?.shopSettings?.members?.find(row => row.member === member)?.label ||
|
||||||
state?.members?.find(row => row.member === member)?.label ||
|
state?.members?.find(row => row.member === member)?.label ||
|
||||||
session?.loginOptions?.find(row => row.member === member)?.label ||
|
session?.loginOptions?.find(row => row.member === member)?.label ||
|
||||||
{
|
(
|
||||||
owner: '麦麦',
|
{
|
||||||
assistant: '娜娜',
|
owner: '麦麦',
|
||||||
assistant2: '小昊',
|
assistant: '娜娜',
|
||||||
}[member] ||
|
assistant2: '小昊',
|
||||||
|
} as Record<string, string>
|
||||||
|
)[member ?? ''] ||
|
||||||
'待确认'
|
'待确认'
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function teamMemberKeys() {
|
const teamMemberKeys = () => Values.memberKeys(state);
|
||||||
return Values.memberKeys(state);
|
const teamMemberEnabled = (member: string) => Values.memberEnabled(state, member);
|
||||||
}
|
|
||||||
function teamMode() {
|
function teamMode() {
|
||||||
return !!(state?.user?.member || state?.members?.some(member => member.member === 'assistant2'));
|
return !!(state?.user?.member || state?.members?.some(member => member.member === 'assistant2'));
|
||||||
}
|
}
|
||||||
const yuan = n => (n == null ? '待补' : Values.yuan(n));
|
const yuan = (n?: number | null) => (n == null ? '待补' : Values.yuan(n));
|
||||||
return {
|
return {
|
||||||
yuan,
|
yuan,
|
||||||
teamMode,
|
teamMode,
|
||||||
+45
-9
@@ -1,9 +1,35 @@
|
|||||||
|
import type { LedgerState, LineState, OrderForm } from '../../shared';
|
||||||
|
import type { LockViews, LockRecord, DeliveryCost } from './types';
|
||||||
|
import type { StockSelection, EditLine } from './deliveryTypes';
|
||||||
|
import type { useLockPool } from './useLockPool';
|
||||||
import { Model } from '../../shared';
|
import { Model } from '../../shared';
|
||||||
import { Act, Field, Money, Choice, Check, Charges } from './formParts';
|
import { Act, Field, Money, Choice, Check, Charges } from './formParts';
|
||||||
export function DeliveryFields({ views, state, item, line, index, stock, cost, quote, update, changeStock }) {
|
export function DeliveryFields({
|
||||||
const field = (k, v) => update(Model.setLineField(line, k, v)),
|
views,
|
||||||
buy = (k, v) => update(Model.setPurchaseField(line, k, v));
|
state,
|
||||||
const p = line.purchase,
|
item,
|
||||||
|
line,
|
||||||
|
index,
|
||||||
|
stock,
|
||||||
|
cost,
|
||||||
|
quote,
|
||||||
|
update,
|
||||||
|
changeStock,
|
||||||
|
}: {
|
||||||
|
views: LockViews;
|
||||||
|
state: LedgerState;
|
||||||
|
item: LockRecord;
|
||||||
|
line: LineState;
|
||||||
|
index: number;
|
||||||
|
stock: StockSelection;
|
||||||
|
cost?: DeliveryCost;
|
||||||
|
quote: ReturnType<typeof useLockPool>;
|
||||||
|
update: EditLine;
|
||||||
|
changeStock<K extends keyof StockSelection>(key: K, value: StockSelection[K]): void;
|
||||||
|
}) {
|
||||||
|
const field = (k: keyof LineState, v: string) => update(Model.setLineField(line, k, v)),
|
||||||
|
buy = (k: keyof NonNullable<LineState['purchase']>, v: string) => update(Model.setPurchaseField(line, k, v));
|
||||||
|
const p = line.purchase!,
|
||||||
piece = line.laborMode === 'piece',
|
piece = line.laborMode === 'piece',
|
||||||
gram = p.laborMode === 'gram',
|
gram = p.laborMode === 'gram',
|
||||||
custom = line.nameType === '其他',
|
custom = line.nameType === '其他',
|
||||||
@@ -11,14 +37,14 @@ export function DeliveryFields({ views, state, item, line, index, stock, cost, q
|
|||||||
pool = item.material_source === 'pool',
|
pool = item.material_source === 'pool',
|
||||||
extra = !!(Number(line.quantity) * 1000 > item.locked_mg),
|
extra = !!(Number(line.quantity) * 1000 > item.locked_mg),
|
||||||
extraPool = extra && stock.extra_source === 'pool',
|
extraPool = extra && stock.extra_source === 'pool',
|
||||||
members = k => Model.memberOptions(state, false, { selected: k });
|
members = (k: string) => Model.memberOptions(state, false, { selected: k });
|
||||||
const materialFormula = cost?.extraPool
|
const materialFormula = cost?.extraPool
|
||||||
? '原锁耗用 ' +
|
? '原锁耗用 ' +
|
||||||
Model.grams(cost.originalUsedMg) +
|
Model.grams(cost.originalUsedMg) +
|
||||||
'g,料费 ¥' +
|
'g,料费 ¥' +
|
||||||
Model.yuan(cost.originalUsedCost) +
|
Model.yuan(cost.originalUsedCost) +
|
||||||
';补重 ' +
|
';补重 ' +
|
||||||
views.materialSourceSegmentsText(cost.extraPool.materialSources) +
|
views.materialSourceSegmentsText(cost.extraPool.materialSources ?? []) +
|
||||||
';合计 ¥' +
|
';合计 ¥' +
|
||||||
Model.yuan(cost.materialCost)
|
Model.yuan(cost.materialCost)
|
||||||
: cost
|
: cost
|
||||||
@@ -37,7 +63,7 @@ export function DeliveryFields({ views, state, item, line, index, stock, cost, q
|
|||||||
cost && stock.original_stock && line.pocket
|
cost && stock.original_stock && line.pocket
|
||||||
? `${pool ? '原锁金料已在料池预留,不重复入库;' : stock.original_stock === 'receive' ? '原锁 ' + Model.grams(item.locked_mg) + 'g 先入库;' : '原锁金料此前已入库;'}${cost.extraMg ? (extraPool ? '补重从交付当日料池耗用,不重复入库;' : stock.extra_stock === 'receive' ? '补重 ' + Model.grams(cost.extraMg) + 'g 先入库;' : stock.extra_stock === 'stocked' ? '补重金料此前已入库;' : '请选择补重金料是否已入库;') : ''}从「${Model.pocketLabel(state, line.pocket)}」出库 ${Model.grams(cost.finalMg)}g${count ? ' / ' + (Number(line.stockCount) ? line.stockCount + '对' : '未记录对数') : ''}。${cost.leftoverMg ? (pool ? '少重 ' + Model.grams(cost.leftoverMg) + 'g 解除预留回到料池,实物留在货盘,不重复入库或扣料。' : '余料 ' + Model.grams(cost.leftoverMg) + 'g 留在该货盘,按原进货价计成本,不重复入库。') : ''}`
|
? `${pool ? '原锁金料已在料池预留,不重复入库;' : stock.original_stock === 'receive' ? '原锁 ' + Model.grams(item.locked_mg) + 'g 先入库;' : '原锁金料此前已入库;'}${cost.extraMg ? (extraPool ? '补重从交付当日料池耗用,不重复入库;' : stock.extra_stock === 'receive' ? '补重 ' + Model.grams(cost.extraMg) + 'g 先入库;' : stock.extra_stock === 'stocked' ? '补重金料此前已入库;' : '请选择补重金料是否已入库;') : ''}从「${Model.pocketLabel(state, line.pocket)}」出库 ${Model.grams(cost.finalMg)}g${count ? ' / ' + (Number(line.stockCount) ? line.stockCount + '对' : '未记录对数') : ''}。${cost.leftoverMg ? (pool ? '少重 ' + Model.grams(cost.leftoverMg) + 'g 解除预留回到料池,实物留在货盘,不重复入库或扣料。' : '余料 ' + Model.grams(cost.leftoverMg) + 'g 留在该货盘,按原进货价计成本,不重复入库。') : ''}`
|
||||||
: '选择本件实际货盘和金料入库情况后,显示库存动作。';
|
: '选择本件实际货盘和金料入库情况后,显示库存动作。';
|
||||||
const sources = [
|
const sources: [string, string][] = [
|
||||||
['', '请选择'],
|
['', '请选择'],
|
||||||
['receive', '尚未记入,交付时先入库'],
|
['receive', '尚未记入,交付时先入库'],
|
||||||
['stocked', '此前已记入,只出库'],
|
['stocked', '此前已记入,只出库'],
|
||||||
@@ -376,8 +402,18 @@ export function DeliveryFields({ views, state, item, line, index, stock, cost, q
|
|||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
export function FeeFields({ state, form, update, cardFee }) {
|
export function FeeFields({
|
||||||
const edit = (i, key, v) => update(Model.editFeeRow(form, i, key, v));
|
state,
|
||||||
|
form,
|
||||||
|
update,
|
||||||
|
cardFee,
|
||||||
|
}: {
|
||||||
|
state: LedgerState;
|
||||||
|
form: OrderForm;
|
||||||
|
update(form: OrderForm): void;
|
||||||
|
cardFee: number;
|
||||||
|
}) {
|
||||||
|
const edit = (i: number, key: 'amount' | 'payer' | 'note', v: string) => update(Model.editFeeRow(form, i, key, v));
|
||||||
return (
|
return (
|
||||||
<section className="panel internal">
|
<section className="panel internal">
|
||||||
<div className="panel-title">
|
<div className="panel-title">
|
||||||
+54
-26
@@ -1,3 +1,8 @@
|
|||||||
|
import { savedCreate } from './draftInput';
|
||||||
|
import type { FormEvent } from 'react';
|
||||||
|
import type { LedgerState, SessionInfo } from '../../shared';
|
||||||
|
import type { LockPayment } from './formParts';
|
||||||
|
import type { InputLine, LockEdit, LockProps, LockViews, PreviewRow, SaveLock, InputMaterial } from './types';
|
||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
import { Model, Calc } from '../../shared';
|
import { Model, Calc } from '../../shared';
|
||||||
import { navigate } from '../../lib/router';
|
import { navigate } from '../../lib/router';
|
||||||
@@ -20,7 +25,19 @@ import {
|
|||||||
} from './formParts';
|
} from './formParts';
|
||||||
import { useLockPool } from './useLockPool';
|
import { useLockPool } from './useLockPool';
|
||||||
|
|
||||||
function PoolQuote({ q, error, date, member, state }) {
|
function PoolQuote({
|
||||||
|
q,
|
||||||
|
error,
|
||||||
|
date,
|
||||||
|
member,
|
||||||
|
state,
|
||||||
|
}: {
|
||||||
|
q?: PreviewRow;
|
||||||
|
error: string;
|
||||||
|
date: string;
|
||||||
|
member: string;
|
||||||
|
state: LedgerState;
|
||||||
|
}) {
|
||||||
const grams = Model.grams,
|
const grams = Model.grams,
|
||||||
name = Model.memberName(state, member),
|
name = Model.memberName(state, member),
|
||||||
balance = q?.balance;
|
balance = q?.balance;
|
||||||
@@ -47,9 +64,9 @@ function PoolQuote({ q, error, date, member, state }) {
|
|||||||
'g。'
|
'g。'
|
||||||
: date +
|
: date +
|
||||||
' 料池 ' +
|
' 料池 ' +
|
||||||
grams(q.totalMg) +
|
grams(Number(q.totalMg)) +
|
||||||
'g,已用/预留 ' +
|
'g,已用/预留 ' +
|
||||||
grams(q.usedMg) +
|
grams(Number(q.usedMg)) +
|
||||||
'g,可用 ' +
|
'g,可用 ' +
|
||||||
grams(q.remainingMg) +
|
grams(q.remainingMg) +
|
||||||
'g;本行预留 ' +
|
'g;本行预留 ' +
|
||||||
@@ -77,7 +94,9 @@ function PoolQuote({ q, error, date, member, state }) {
|
|||||||
{q.materialSources.map((s, i) => (
|
{q.materialSources.map((s, i) => (
|
||||||
<div key={i}>
|
<div key={i}>
|
||||||
<strong>
|
<strong>
|
||||||
{s.kind === 'personal_recovery' ? Model.memberName(state, s.member) + '个人回收料' : '公共料'}
|
{s.kind === 'personal_recovery'
|
||||||
|
? Model.memberName(state, s.member ?? '') + '个人回收料'
|
||||||
|
: '公共料'}
|
||||||
</strong>
|
</strong>
|
||||||
<span>{grams(s.quantity)}g</span>
|
<span>{grams(s.quantity)}g</span>
|
||||||
<b>{s.amount == null ? '料费待补' : '¥' + Model.yuan(s.amount)}</b>
|
<b>{s.amount == null ? '料费待补' : '¥' + Model.yuan(s.amount)}</b>
|
||||||
@@ -94,7 +113,7 @@ function PoolQuote({ q, error, date, member, state }) {
|
|||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function lineInput(src = {}) {
|
function lineInput(src: InputLine = {}) {
|
||||||
const material = src.material || {},
|
const material = src.material || {},
|
||||||
manual = material.manual || material;
|
manual = material.manual || material;
|
||||||
return {
|
return {
|
||||||
@@ -114,7 +133,7 @@ function lineInput(src = {}) {
|
|||||||
verified: !!manual.verified,
|
verified: !!manual.verified,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
function packLine(r, date, quote, draft) {
|
function packLine(r: ReturnType<typeof lineInput>, date: string, quote: PreviewRow | undefined, draft: boolean) {
|
||||||
const manual = { rate: r.rate, payer: r.payer, verified: r.verified };
|
const manual = { rate: r.rate, payer: r.payer, verified: r.verified };
|
||||||
return {
|
return {
|
||||||
...(r.lineId ? { lineId: r.lineId } : {}),
|
...(r.lineId ? { lineId: r.lineId } : {}),
|
||||||
@@ -128,31 +147,39 @@ function packLine(r, date, quote, draft) {
|
|||||||
laborMode: r.laborMode,
|
laborMode: r.laborMode,
|
||||||
pieces: r.pieces,
|
pieces: r.pieces,
|
||||||
charges: saleCharges(r.charges),
|
charges: saleCharges(r.charges),
|
||||||
material:
|
material: (r.source === 'pool'
|
||||||
r.source === 'pool'
|
? { source: 'pool', poolId: date, revision: quote?.revision || '', ...(draft ? { manual } : {}) }
|
||||||
? { source: 'pool', poolId: date, revision: quote?.revision || '', ...(draft ? { manual } : {}) }
|
: manual) satisfies InputMaterial,
|
||||||
: manual,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
function initial(state, session, edit, key) {
|
function initial(state: LedgerState, session: SessionInfo, edit: LockEdit | null, key: string) {
|
||||||
const saved = readDraft(key),
|
const saved = readDraft(key, savedCreate),
|
||||||
d = edit ? saved?.inputs || edit.inputs : saved || {};
|
d = edit ? saved?.inputs || edit.inputs : saved || {};
|
||||||
const member = d.member || Model.currentMember(state);
|
const member = d.member || Model.currentMember(state);
|
||||||
return {
|
return {
|
||||||
date: d.date || state.today,
|
date: d.date || state.today,
|
||||||
member,
|
member,
|
||||||
customer: d.customer || '',
|
customer: d.customer || '',
|
||||||
salesperson: d.salesperson || (edit ? session.user.name : Model.defaultSalesperson(state, session)),
|
salesperson: d.salesperson || (edit ? state.user.name : Model.defaultSalesperson(state, session)),
|
||||||
note: d.note || '',
|
note: d.note || '',
|
||||||
discount: d.discount ?? '0',
|
discount: d.discount ?? '0',
|
||||||
payment: initialPayment(state, d.payment, member),
|
payment: initialPayment(state, d.payment, member),
|
||||||
lines: (d.lines?.length ? d.lines : [{ ...d.line, material: d.material }]).map(lineInput),
|
lines: (d.lines?.length ? d.lines : [{ ...d.line, material: d.material }]).map(lineInput),
|
||||||
reason: edit ? saved?.reason || '' : '',
|
reason: edit ? saved?.reason || '' : '',
|
||||||
revision: edit ? (saved?.revision ?? edit.revision) : undefined,
|
revision: edit ? (saved?.revision ?? edit.revision) : undefined,
|
||||||
conflicted: edit && saved && saved.revision !== edit.revision,
|
conflicted: !!(edit && saved && saved.revision !== edit.revision),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
export function LockCreate({ client, state, session, views, edit, save, blocked, reset }) {
|
export function LockCreate({
|
||||||
|
client,
|
||||||
|
state,
|
||||||
|
session,
|
||||||
|
views,
|
||||||
|
edit,
|
||||||
|
save,
|
||||||
|
blocked,
|
||||||
|
reset,
|
||||||
|
}: LockProps & { views: LockViews; edit: LockEdit | null; save: SaveLock; blocked: boolean; reset: () => void }) {
|
||||||
const key = edit
|
const key = edit
|
||||||
? 'mm-price-lock-edit-' + state.user.id + '-' + edit.lock.id
|
? 'mm-price-lock-edit-' + state.user.id + '-' + edit.lock.id
|
||||||
: 'mm-price-lock-draft-' + state.user.id;
|
: 'mm-price-lock-draft-' + state.user.id;
|
||||||
@@ -166,7 +193,7 @@ export function LockCreate({ client, state, session, views, edit, save, blocked,
|
|||||||
: [];
|
: [];
|
||||||
});
|
});
|
||||||
const quote = useLockPool({ client, state, views, date: d.date, member: d.member, entries, editId: edit?.lock.id });
|
const quote = useLockPool({ client, state, views, date: d.date, member: d.member, entries, editId: edit?.lock.id });
|
||||||
function pack(draft) {
|
function pack(draft: boolean) {
|
||||||
return {
|
return {
|
||||||
...(Model.teamMode(state) ? { member: d.member } : {}),
|
...(Model.teamMode(state) ? { member: d.member } : {}),
|
||||||
date: d.date,
|
date: d.date,
|
||||||
@@ -191,11 +218,12 @@ export function LockCreate({ client, state, session, views, edit, save, blocked,
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
localStorage.setItem(key, stored);
|
localStorage.setItem(key, stored);
|
||||||
}, [key, stored]);
|
}, [key, stored]);
|
||||||
const update = changes => {
|
const update = (changes: Partial<typeof d>) => {
|
||||||
set(prev => ({ ...prev, ...changes }));
|
set(prev => ({ ...prev, ...changes }));
|
||||||
setVerified(false);
|
setVerified(false);
|
||||||
};
|
};
|
||||||
const line = (index, changes) => update({ lines: d.lines.map((r, i) => (index === i ? { ...r, ...changes } : r)) });
|
const line = (index: number, changes: Partial<ReturnType<typeof lineInput>>) =>
|
||||||
|
update({ lines: d.lines.map((r, i) => (index === i ? { ...r, ...changes } : r)) });
|
||||||
const approval =
|
const approval =
|
||||||
edit && state.user.role === 'assistant' && (edit.requiresApproval !== false || d.date !== state.today);
|
edit && state.user.role === 'assistant' && (edit.requiresApproval !== false || d.date !== state.today);
|
||||||
function add() {
|
function add() {
|
||||||
@@ -205,7 +233,7 @@ export function LockCreate({ client, state, session, views, edit, save, blocked,
|
|||||||
}
|
}
|
||||||
update({ lines: [...d.lines, lineInput()] });
|
update({ lines: [...d.lines, lineInput()] });
|
||||||
}
|
}
|
||||||
function remove(i) {
|
function remove(i: number) {
|
||||||
if (d.lines.length <= 1) {
|
if (d.lines.length <= 1) {
|
||||||
setError('请至少保留一件锁价商品。');
|
setError('请至少保留一件锁价商品。');
|
||||||
return;
|
return;
|
||||||
@@ -219,7 +247,7 @@ export function LockCreate({ client, state, session, views, edit, save, blocked,
|
|||||||
'yuan',
|
'yuan',
|
||||||
),
|
),
|
||||||
).result;
|
).result;
|
||||||
async function submit(event) {
|
async function submit(event: FormEvent) {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
setError('');
|
setError('');
|
||||||
try {
|
try {
|
||||||
@@ -229,7 +257,7 @@ export function LockCreate({ client, state, session, views, edit, save, blocked,
|
|||||||
if (Calc.isSilver(r.name)) throw new Error('锁价仅支持按克黄金,银饰请直接开单。');
|
if (Calc.isSilver(r.name)) throw new Error('锁价仅支持按克黄金,银饰请直接开单。');
|
||||||
views.lockQuantityMg(r.quantity);
|
views.lockQuantityMg(r.quantity);
|
||||||
if (Calc.cents(r.goldPrice) <= 0) throw new Error('销售金价须大于0。');
|
if (Calc.cents(r.goldPrice) <= 0) throw new Error('销售金价须大于0。');
|
||||||
if (r.material.source === 'pool') {
|
if ('source' in r.material) {
|
||||||
if (d.date !== state.today && (!edit || d.date !== edit.lock.date))
|
if (d.date !== state.today && (!edit || d.date !== edit.lock.date))
|
||||||
throw new Error('当日加权料池只支持今天锁价;补录其他日期请使用手动填写料价。');
|
throw new Error('当日加权料池只支持今天锁价;补录其他日期请使用手动填写料价。');
|
||||||
const q = quote.rows.find(q => q.lineIndex === i);
|
const q = quote.rows.find(q => q.lineIndex === i);
|
||||||
@@ -267,14 +295,14 @@ export function LockCreate({ client, state, session, views, edit, save, blocked,
|
|||||||
}
|
}
|
||||||
await save(url, input);
|
await save(url, input);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (edit && err.status === 409) {
|
if (edit && err instanceof Error && 'status' in err && err.status === 409) {
|
||||||
set(prev => ({ ...prev, conflicted: true }));
|
set(prev => ({ ...prev, conflicted: true }));
|
||||||
setVerified(false);
|
setVerified(false);
|
||||||
}
|
}
|
||||||
setError(err.message);
|
setError(err instanceof Error ? err.message : String(err));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const pay = payment => update({ payment }),
|
const pay = (payment: LockPayment) => update({ payment }),
|
||||||
leave = () => navigate('price-locks');
|
leave = () => navigate('price-locks');
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -351,7 +379,7 @@ export function LockCreate({ client, state, session, views, edit, save, blocked,
|
|||||||
</section>
|
</section>
|
||||||
<div id="lock-create-lines">
|
<div id="lock-create-lines">
|
||||||
{d.lines.map((r, i) => {
|
{d.lines.map((r, i) => {
|
||||||
const set = (key, v) => line(i, { [key]: v }),
|
const set = <K extends keyof typeof r>(key: K, v: (typeof r)[K]) => line(i, { [key]: v }),
|
||||||
pooled = r.source === 'pool',
|
pooled = r.source === 'pool',
|
||||||
q = quote.rows.find(v => v.lineIndex === i),
|
q = quote.rows.find(v => v.lineIndex === i),
|
||||||
sale = safeEstimate(() => Calc.sale(packLine(r, d.date, q, false)).sale).result,
|
sale = safeEstimate(() => Calc.sale(packLine(r, d.date, q, false)).sale).result,
|
||||||
@@ -499,7 +527,7 @@ export function LockCreate({ client, state, session, views, edit, save, blocked,
|
|||||||
.map(
|
.map(
|
||||||
s =>
|
s =>
|
||||||
(s.kind === 'personal_recovery'
|
(s.kind === 'personal_recovery'
|
||||||
? Model.memberName(state, s.member) + '个人回收料'
|
? Model.memberName(state, s.member ?? '') + '个人回收料'
|
||||||
: '公共料') +
|
: '公共料') +
|
||||||
' ' +
|
' ' +
|
||||||
(s.averageRate == null ? '待补' : (s.averageRate / 100).toFixed(2)),
|
(s.averageRate == null ? '待补' : (s.averageRate / 100).toFixed(2)),
|
||||||
+40
-19
@@ -1,3 +1,9 @@
|
|||||||
|
import { savedDelivery } from './draftInput';
|
||||||
|
import type { FormEvent } from 'react';
|
||||||
|
import type { OrderForm, SyncContext } from '../../shared';
|
||||||
|
import type { LockRecord, LockProps, LockViews, SaveLock, DeliveryCost } from './types';
|
||||||
|
import type { LockPayment } from './formParts';
|
||||||
|
import type { DeliveryForm, DeliveryLine, SavedLine } from './deliveryTypes';
|
||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
import { Model, Calc, Cards } from '../../shared';
|
import { Model, Calc, Cards } from '../../shared';
|
||||||
import { navigate } from '../../lib/router';
|
import { navigate } from '../../lib/router';
|
||||||
@@ -18,11 +24,13 @@ import { DeliveryFields, FeeFields } from './DeliveryFields';
|
|||||||
import { useLockPool } from './useLockPool';
|
import { useLockPool } from './useLockPool';
|
||||||
|
|
||||||
const uuid = () => crypto.randomUUID();
|
const uuid = () => crypto.randomUUID();
|
||||||
function initialize(lock, views, ctx, key) {
|
function initialize(lock: LockRecord, views: LockViews, ctx: SyncContext, key: string): DeliveryForm {
|
||||||
const stored = readDraft(key),
|
const stored = readDraft(key, savedDelivery),
|
||||||
d = stored?.revision === lock.revision ? stored : {},
|
d = stored?.revision === lock.revision ? stored : {},
|
||||||
items = views.priceLockLines(lock),
|
items = views.priceLockLines(lock),
|
||||||
rows = items.map(item => d.lines?.find(r => r.lineId === item.id) || (items.length === 1 && d.line ? d : {}));
|
rows: SavedLine[] = items.map(
|
||||||
|
item => d.lines?.find(r => r.lineId === item.id) || (items.length === 1 && d.line ? d : {}),
|
||||||
|
);
|
||||||
const owner = Model.teamMode(ctx.st) ? Model.currentMember(ctx.st) : 'assistant',
|
const owner = Model.teamMode(ctx.st) ? Model.currentMember(ctx.st) : 'assistant',
|
||||||
member = lock.member || owner;
|
member = lock.member || owner;
|
||||||
const lines = rows.map(
|
const lines = rows.map(
|
||||||
@@ -71,7 +79,15 @@ function initialize(lock, views, ctx, key) {
|
|||||||
verified: false,
|
verified: false,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
export function LockDelivery({ client, state, session, views, lock, save, blocked }) {
|
export function LockDelivery({
|
||||||
|
client,
|
||||||
|
state,
|
||||||
|
session,
|
||||||
|
views,
|
||||||
|
lock,
|
||||||
|
save,
|
||||||
|
blocked,
|
||||||
|
}: LockProps & { views: LockViews; lock: LockRecord; save: SaveLock; blocked: boolean }) {
|
||||||
const key = 'mm-price-lock-delivery-' + state.user.id + '-' + lock.id,
|
const key = 'mm-price-lock-delivery-' + state.user.id + '-' + lock.id,
|
||||||
ctx = { st: state, session, uuid };
|
ctx = { st: state, session, uuid };
|
||||||
const [d, set] = useState(() => initialize(lock, views, ctx, key)),
|
const [d, set] = useState(() => initialize(lock, views, ctx, key)),
|
||||||
@@ -91,7 +107,7 @@ export function LockDelivery({ client, state, session, views, lock, save, blocke
|
|||||||
delivery: true,
|
delivery: true,
|
||||||
});
|
});
|
||||||
const costs = d.form.lines.map((r, i) =>
|
const costs = d.form.lines.map((r, i) =>
|
||||||
safeEstimate(() => {
|
safeEstimate<DeliveryCost>(() => {
|
||||||
const stock = d.stock[i],
|
const stock = d.stock[i],
|
||||||
pooled = stock.extra_source === 'pool' && views.lockQuantityMg(r.quantity) > items[i].locked_mg;
|
pooled = stock.extra_source === 'pool' && views.lockQuantityMg(r.quantity) > items[i].locked_mg;
|
||||||
const c = views.priceLockDeliveryCost(items[i], r.quantity, pooled ? '1' : stock.extra_rate);
|
const c = views.priceLockDeliveryCost(items[i], r.quantity, pooled ? '1' : stock.extra_rate);
|
||||||
@@ -108,17 +124,18 @@ export function LockDelivery({ client, state, session, views, lock, save, blocke
|
|||||||
...d.form,
|
...d.form,
|
||||||
fees_date: d.form.date,
|
fees_date: d.form.date,
|
||||||
lines: d.form.lines.map((r, i) => {
|
lines: d.form.lines.map((r, i) => {
|
||||||
const amount = costs[i].result ? (costs[i].result.materialCost / 100).toFixed(2) : '';
|
const amount = costs[i].result ? (costs[i].result!.materialCost / 100).toFixed(2) : '';
|
||||||
return {
|
return {
|
||||||
...r,
|
...r,
|
||||||
purchase: { ...r.purchase, materialMode: 'total', material: amount, total: amount, originalTotal: amount },
|
purchase: { ...r.purchase!, materialMode: 'total', material: amount, total: amount, originalTotal: amount },
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
ctx,
|
ctx,
|
||||||
);
|
);
|
||||||
const form = calculated.form,
|
const form = calculated.form,
|
||||||
lines = calculated.draft.lines,
|
// 交付商品已通过普通开单模型同步,沿用其收集出的分项进货成本。
|
||||||
|
lines = calculated.draft.lines as (DeliveryLine & Record<string, unknown>)[],
|
||||||
order = safeEstimate(() =>
|
order = safeEstimate(() =>
|
||||||
Calc.orderTotal(
|
Calc.orderTotal(
|
||||||
lines.map(r => Calc.sale(r).sale),
|
lines.map(r => Calc.sale(r).sale),
|
||||||
@@ -131,7 +148,10 @@ export function LockDelivery({ client, state, session, views, lock, save, blocke
|
|||||||
amount: difference == null ? '' : (Math.abs(difference) / 100).toFixed(2),
|
amount: difference == null ? '' : (Math.abs(difference) / 100).toFixed(2),
|
||||||
...paymentPayload(d.payment),
|
...paymentPayload(d.payment),
|
||||||
},
|
},
|
||||||
card = d.payment.method === '信用卡' && difference > 0 ? Cards.amount(difference, Model.creditCardRate(state)) : 0;
|
card =
|
||||||
|
d.payment.method === '信用卡' && difference !== null && difference > 0
|
||||||
|
? Cards.amount(difference, Model.creditCardRate(state))
|
||||||
|
: 0;
|
||||||
const deliveryLines = lines.map((r, i) => {
|
const deliveryLines = lines.map((r, i) => {
|
||||||
const s = d.stock[i],
|
const s = d.stock[i],
|
||||||
pool = items[i].material_source === 'pool',
|
pool = items[i].material_source === 'pool',
|
||||||
@@ -170,9 +190,9 @@ export function LockDelivery({ client, state, session, views, lock, save, blocke
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
localStorage.setItem(key, snapshot);
|
localStorage.setItem(key, snapshot);
|
||||||
}, [key, snapshot]);
|
}, [key, snapshot]);
|
||||||
const setForm = next => set({ ...d, form: next }),
|
const setForm = (next: OrderForm) => set({ ...d, form: next }),
|
||||||
payChanged = payment => set({ ...d, payment });
|
payChanged = (payment: LockPayment) => set({ ...d, payment });
|
||||||
async function submit(e) {
|
async function submit(e: FormEvent<HTMLFormElement>) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
setError('');
|
setError('');
|
||||||
try {
|
try {
|
||||||
@@ -184,10 +204,10 @@ export function LockDelivery({ client, state, session, views, lock, save, blocke
|
|||||||
);
|
);
|
||||||
const actual = deliveryLines.map((r, i) => {
|
const actual = deliveryLines.map((r, i) => {
|
||||||
const counts = Model.pocketCountsEnabled(state, r.inventory.pocket),
|
const counts = Model.pocketCountsEnabled(state, r.inventory.pocket),
|
||||||
extra = costs[i].result.extraMg;
|
extra = costs[i].result!.extraMg;
|
||||||
if (!Model.activePocketKeys(state).includes(r.pocket) || !['receive', 'stocked'].includes(r.inventory.original))
|
if (!Model.activePocketKeys(state).includes(r.pocket) || !['receive', 'stocked'].includes(r.inventory.original))
|
||||||
throw new Error('请选择商品 ' + (i + 1) + ' 的实际出库货盘,并确认原锁金料是否已入库。');
|
throw new Error('请选择商品 ' + (i + 1) + ' 的实际出库货盘,并确认原锁金料是否已入库。');
|
||||||
if (counts && !['receive', 'stocked'].includes(r.inventory.countSource))
|
if (counts && !['receive', 'stocked'].includes(r.inventory.countSource ?? ''))
|
||||||
throw new Error('请选择商品 ' + (i + 1) + ' 的成品来源。');
|
throw new Error('请选择商品 ' + (i + 1) + ' 的成品来源。');
|
||||||
if (
|
if (
|
||||||
extra &&
|
extra &&
|
||||||
@@ -199,7 +219,7 @@ export function LockDelivery({ client, state, session, views, lock, save, blocke
|
|||||||
throw new Error('请填写商品 ' + (i + 1) + ' 的补重料价、付款人、是否已入库,并确认实际付款。');
|
throw new Error('请填写商品 ' + (i + 1) + ' 的补重料价、付款人、是否已入库,并确认实际付款。');
|
||||||
return {
|
return {
|
||||||
quantity: r.quantity,
|
quantity: r.quantity,
|
||||||
...(counts ? { stockCount: Model.stockCountValue(r.stockCount) } : {}),
|
...(counts ? { stockCount: Model.stockCountValue(String(r.stockCount ?? '')) } : {}),
|
||||||
laborRate: r.laborRate,
|
laborRate: r.laborRate,
|
||||||
laborMode: r.laborMode,
|
laborMode: r.laborMode,
|
||||||
pieces: r.pieces,
|
pieces: r.pieces,
|
||||||
@@ -234,10 +254,11 @@ export function LockDelivery({ client, state, session, views, lock, save, blocke
|
|||||||
};
|
};
|
||||||
await save('/api/price-locks/' + encodeURIComponent(lock.id) + '/deliver', input);
|
await save('/api/price-locks/' + encodeURIComponent(lock.id) + '/deliver', input);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err.message);
|
setError((err as Error).message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const sum = k => costs.reduce((n, c) => n + (c.result?.[k] || 0), 0);
|
const sum = (k: 'originalUsedMg' | 'originalUsedCost' | 'extraMg' | 'extraCost' | 'leftoverMg' | 'leftoverCost') =>
|
||||||
|
costs.reduce((n, c) => n + (c.result?.[k] || 0), 0);
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Heading
|
<Heading
|
||||||
@@ -390,8 +411,8 @@ export function LockDelivery({ client, state, session, views, lock, save, blocke
|
|||||||
change={payChanged}
|
change={payChanged}
|
||||||
required={!!difference}
|
required={!!difference}
|
||||||
disabled={difference === 0}
|
disabled={difference === 0}
|
||||||
methodLabel={difference < 0 ? '退款方式' : '补收款方式'}
|
methodLabel={difference !== null && difference < 0 ? '退款方式' : '补收款方式'}
|
||||||
recipientLabel={difference < 0 ? '退款账户归属' : '收款人'}
|
recipientLabel={difference !== null && difference < 0 ? '退款账户归属' : '收款人'}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<Check
|
<Check
|
||||||
-11
@@ -1,11 +0,0 @@
|
|||||||
import { type ComponentType } from 'react';
|
|
||||||
import type { LedgerClient } from '../../lib/api';
|
|
||||||
import type { LedgerState, SessionInfo } from '../../shared';
|
|
||||||
export const LockPage: ComponentType<{
|
|
||||||
client: LedgerClient;
|
|
||||||
state: LedgerState;
|
|
||||||
session: SessionInfo;
|
|
||||||
route: 'price-locks' | 'price-lock-create';
|
|
||||||
onState?: (state: LedgerState) => void;
|
|
||||||
onRecoverOther?: () => Promise<void>;
|
|
||||||
}>;
|
|
||||||
+211
-95
@@ -1,4 +1,9 @@
|
|||||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
import { useEffect, useMemo, useRef, useState, type FormEvent, type MouseEvent, type ReactNode } from 'react';
|
||||||
|
import type { LedgerClient } from '../../lib/api';
|
||||||
|
import type { LedgerState } from '../../shared';
|
||||||
|
import { loadState } from '../../lib/session';
|
||||||
|
import { errorText } from '../Settings/settingsModel';
|
||||||
|
import type { LockRecord, LockEdit, LockChange, LockProps, ChangeListRow } from './types';
|
||||||
import { navigate, searchParam, useLocation } from '../../lib/router';
|
import { navigate, searchParam, useLocation } from '../../lib/router';
|
||||||
import { useClientSnapshot } from '../../lib/useClient';
|
import { useClientSnapshot } from '../../lib/useClient';
|
||||||
import { lockViews } from './lockViews';
|
import { lockViews } from './lockViews';
|
||||||
@@ -6,16 +11,38 @@ import { Act, Heading } from './formParts';
|
|||||||
import { LockCreate } from './LockCreate';
|
import { LockCreate } from './LockCreate';
|
||||||
import { LockDelivery } from './LockDelivery';
|
import { LockDelivery } from './LockDelivery';
|
||||||
|
|
||||||
function readDraftFilters(key) {
|
type DialogKind = 'changes' | 'review' | 'cancel' | 'detail';
|
||||||
|
type LocalDialog = { kind: DialogKind; id?: string };
|
||||||
|
type Resource =
|
||||||
|
| { kind: 'lock'; value: LockRecord }
|
||||||
|
| { kind: 'changes'; value: { rows: ChangeListRow[] } }
|
||||||
|
| { kind: 'review'; value: LockChange }
|
||||||
|
| { kind: 'edit'; value: LockEdit }
|
||||||
|
| { kind: 'cancel'; value: LockEdit & { lock: LockRecord } };
|
||||||
|
type PageProps = LockProps & {
|
||||||
|
route: 'price-locks' | 'price-lock-create';
|
||||||
|
onState?: (state: LedgerState) => void;
|
||||||
|
onRecoverOther?: () => Promise<void>;
|
||||||
|
};
|
||||||
|
function object(value: unknown): value is Record<string, unknown> {
|
||||||
|
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||||
|
}
|
||||||
|
function readDraftFilters(key: string): Record<string, unknown> {
|
||||||
try {
|
try {
|
||||||
return JSON.parse(sessionStorage.getItem(key) || '{}') || {};
|
const saved: unknown = JSON.parse(sessionStorage.getItem(key) || '{}');
|
||||||
|
return object(saved) ? saved : {};
|
||||||
} catch {
|
} catch {
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
function useRead(client, url, seq, validate) {
|
function useRead<T>(
|
||||||
|
client: LedgerClient,
|
||||||
|
url: string,
|
||||||
|
seq: number,
|
||||||
|
validate: (value: unknown) => T,
|
||||||
|
): { result?: T; error?: string } {
|
||||||
const key = [client.user, url, seq].join('|'),
|
const key = [client.user, url, seq].join('|'),
|
||||||
[s, set] = useState(null);
|
[s, set] = useState<{ key: string; result?: T; error?: string } | null>(null);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!url) return;
|
if (!url) return;
|
||||||
let active = true;
|
let active = true;
|
||||||
@@ -26,7 +53,7 @@ function useRead(client, url, seq, validate) {
|
|||||||
if (active) set({ key, result });
|
if (active) set({ key, result });
|
||||||
})
|
})
|
||||||
.catch(e => {
|
.catch(e => {
|
||||||
if (active) set({ key, error: e.message });
|
if (active) set({ key, error: errorText(e) });
|
||||||
});
|
});
|
||||||
return () => {
|
return () => {
|
||||||
active = false;
|
active = false;
|
||||||
@@ -34,15 +61,89 @@ function useRead(client, url, seq, validate) {
|
|||||||
}, [client, url, key, validate]);
|
}, [client, url, key, validate]);
|
||||||
return s?.key === key ? s : {};
|
return s?.key === key ? s : {};
|
||||||
}
|
}
|
||||||
const rows = r => {
|
function lockLine(value: unknown) {
|
||||||
if (!Array.isArray(r?.rows)) throw new Error('记录未完整返回,请重试。');
|
if (!object(value) || !object(value.line)) return false;
|
||||||
return r;
|
const line = value.line;
|
||||||
};
|
return (
|
||||||
const modalId = k => (['changes', 'review'].includes(k) ? 'price-lock-changes-dialog' : 'price-lock-dialog');
|
typeof line.name === 'string' &&
|
||||||
function Modal({ children, kind, close }) {
|
Number.isSafeInteger(line.sale) &&
|
||||||
const ref = useRef(null);
|
Number.isSafeInteger(line.laborRate) &&
|
||||||
|
(line.charges == null ||
|
||||||
|
(Array.isArray(line.charges) && line.charges.every(c => object(c) && Number.isSafeInteger(c.amount)))) &&
|
||||||
|
Number.isSafeInteger(value.locked_mg) &&
|
||||||
|
Number.isSafeInteger(value.sell_rate) &&
|
||||||
|
(value.buy_rate === null || Number.isSafeInteger(value.buy_rate)) &&
|
||||||
|
(value.material_amount === null || Number.isSafeInteger(value.material_amount))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
function lockRecord(r: unknown): r is LockRecord {
|
||||||
|
return (
|
||||||
|
object(r) &&
|
||||||
|
typeof r.id === 'string' &&
|
||||||
|
typeof r.date === 'string' &&
|
||||||
|
typeof r.customer === 'string' &&
|
||||||
|
typeof r.number === 'string' &&
|
||||||
|
typeof r.salesperson === 'string' &&
|
||||||
|
(r.status === 'pending' || r.status === 'cancelled' || r.status === 'delivered') &&
|
||||||
|
Number.isSafeInteger(r.revision) &&
|
||||||
|
Number.isSafeInteger(r.netReceived) &&
|
||||||
|
Number.isSafeInteger(r.discount) &&
|
||||||
|
lockLine(r) &&
|
||||||
|
(r.lines == null || (Array.isArray(r.lines) && r.lines.every(lockLine)))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
function changeRow(r: unknown): r is ChangeListRow {
|
||||||
|
return (
|
||||||
|
object(r) &&
|
||||||
|
typeof (r.requestId || r.id) === 'string' &&
|
||||||
|
(r.action === 'edit' || r.action === 'cancel') &&
|
||||||
|
(r.status === 'pending' || r.status === 'approved' || r.status === 'rejected') &&
|
||||||
|
typeof r.created === 'string'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
function editContext(r: unknown, target: string | undefined, editing: boolean): r is LockEdit {
|
||||||
|
return (
|
||||||
|
object(r) &&
|
||||||
|
r.eligible === true &&
|
||||||
|
object(r.lock) &&
|
||||||
|
typeof r.lock.id === 'string' &&
|
||||||
|
typeof r.lock.date === 'string' &&
|
||||||
|
typeof r.lock.number === 'string' &&
|
||||||
|
(r.lock.customer === undefined || typeof r.lock.customer === 'string') &&
|
||||||
|
r.lock.id === target &&
|
||||||
|
r.lock.status === 'pending' &&
|
||||||
|
Number.isSafeInteger(r.revision) &&
|
||||||
|
typeof r.requiresApproval === 'boolean' &&
|
||||||
|
object(r.inputs) &&
|
||||||
|
(!editing || (Array.isArray(r.inputs.lines) && r.inputs.lines.length > 0))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
function changeDetail(r: unknown, id: string | undefined): r is LockChange {
|
||||||
|
return (
|
||||||
|
object(r) &&
|
||||||
|
(r.requestId || r.id) === id &&
|
||||||
|
(r.action === 'edit' || r.action === 'cancel') &&
|
||||||
|
Array.isArray(r.changes) &&
|
||||||
|
lockRecord(r.before) &&
|
||||||
|
changeRow(r) &&
|
||||||
|
Number.isSafeInteger(r.revision)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
function readLocks(r: unknown) {
|
||||||
|
if (!object(r) || !Array.isArray(r.rows) || !r.rows.every(lockRecord)) throw new Error('记录未完整返回,请重试。');
|
||||||
|
return { rows: r.rows };
|
||||||
|
}
|
||||||
|
function readChanges(r: unknown) {
|
||||||
|
if (!object(r) || !Array.isArray(r.rows) || !r.rows.every(changeRow)) throw new Error('记录未完整返回,请重试。');
|
||||||
|
return { rows: r.rows };
|
||||||
|
}
|
||||||
|
const modalId = (k: DialogKind) =>
|
||||||
|
['changes', 'review'].includes(k) ? 'price-lock-changes-dialog' : 'price-lock-dialog';
|
||||||
|
function Modal({ children, kind, close }: { children: ReactNode; kind: DialogKind; close: () => void }) {
|
||||||
|
const ref = useRef<HTMLDialogElement>(null);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const root = ref.current;
|
const root = ref.current;
|
||||||
|
if (!root) return;
|
||||||
root.showModal();
|
root.showModal();
|
||||||
return () => root.close();
|
return () => root.close();
|
||||||
}, []);
|
}, []);
|
||||||
@@ -59,8 +160,8 @@ function Modal({ children, kind, close }) {
|
|||||||
</dialog>
|
</dialog>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
const previousFilters = new WeakMap();
|
const previousFilters = new WeakMap<LedgerClient, { user: string; list: string; changes: string }>();
|
||||||
export function LockPage({ client, state, session, route, onState, onRecoverOther }) {
|
export function LockPage({ client, state, session, route, onState, onRecoverOther }: PageProps) {
|
||||||
useClientSnapshot(client);
|
useClientSnapshot(client);
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
const create = route === 'price-lock-create',
|
const create = route === 'price-lock-create',
|
||||||
@@ -71,7 +172,7 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
|
|||||||
const [previousLocation, setPreviousLocation] = useState(location);
|
const [previousLocation, setPreviousLocation] = useState(location);
|
||||||
const [seq, setSeq] = useState(0),
|
const [seq, setSeq] = useState(0),
|
||||||
[listFilter, setFilter] = useState(() => (remembered?.user === state.user.id ? remembered.list : 'pending')),
|
[listFilter, setFilter] = useState(() => (remembered?.user === state.user.id ? remembered.list : 'pending')),
|
||||||
[local, setLocal] = useState(null),
|
[local, setLocal] = useState<LocalDialog | null>(null),
|
||||||
[changeFilter, setChangeFilter] = useState(() =>
|
[changeFilter, setChangeFilter] = useState(() =>
|
||||||
remembered?.user === state.user.id ? remembered.changes : 'pending',
|
remembered?.user === state.user.id ? remembered.changes : 'pending',
|
||||||
),
|
),
|
||||||
@@ -88,42 +189,33 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
|
|||||||
const formPending = !!client.pending(),
|
const formPending = !!client.pending(),
|
||||||
blocked = client.busy || formPending,
|
blocked = client.busy || formPending,
|
||||||
views = useMemo(() => lockViews(state, session), [state, session]);
|
views = useMemo(() => lockViews(state, session), [state, session]);
|
||||||
const dialog = local || (!deliver && detail ? { kind: 'detail', id: detail } : null),
|
const dialog: LocalDialog | null = local || (!deliver && detail ? { kind: 'detail', id: detail } : null),
|
||||||
kind = dialog?.kind,
|
kind = dialog?.kind,
|
||||||
id = dialog?.id;
|
id = dialog?.id;
|
||||||
const target = editId || deliver || id,
|
const target = editId || deliver || id;
|
||||||
readLock = r => {
|
|
||||||
if (r?.id !== target) throw new Error('锁价单资料未完整返回,请重新读取。');
|
|
||||||
return r;
|
|
||||||
};
|
|
||||||
const validator = useMemo(
|
const validator = useMemo(
|
||||||
() => r => {
|
() =>
|
||||||
if (editId || kind === 'cancel') {
|
(r: unknown): Resource => {
|
||||||
if (
|
if (editId || kind === 'cancel') {
|
||||||
r?.eligible !== true ||
|
if (!editContext(r, target, !!editId))
|
||||||
r.lock?.id !== target ||
|
throw new Error(
|
||||||
r.lock?.status !== 'pending' ||
|
(object(r) && typeof r.reason === 'string' && r.reason) || '锁价修改资料未完整返回,请重新读取。',
|
||||||
!Number.isSafeInteger(r.revision) ||
|
);
|
||||||
typeof r.requiresApproval !== 'boolean' ||
|
if (kind === 'cancel' && !editId) {
|
||||||
(editId && (!Array.isArray(r.inputs?.lines) || !r.inputs.lines.length))
|
if (!lockRecord(r.lock)) throw new Error('锁价单资料未完整返回,请重新读取。');
|
||||||
)
|
return { kind: 'cancel', value: { ...r, lock: r.lock } };
|
||||||
throw new Error(r.reason || '锁价修改资料未完整返回,请重新读取。');
|
}
|
||||||
return r;
|
return { kind: 'edit', value: r };
|
||||||
}
|
}
|
||||||
if (kind === 'review') {
|
if (kind === 'review') {
|
||||||
if (
|
if (!changeDetail(r, id)) throw new Error('锁价申请详情未完整返回,请重新读取。');
|
||||||
(r.requestId || r.id) !== id ||
|
return { kind: 'review', value: r };
|
||||||
!['edit', 'cancel'].includes(r.action) ||
|
}
|
||||||
!Array.isArray(r.changes) ||
|
if (kind === 'changes') return { kind: 'changes', value: readChanges(r) };
|
||||||
!r.before
|
if (!lockRecord(r) || r.id !== target) throw new Error('锁价单资料未完整返回,请重新读取。');
|
||||||
)
|
return { kind: 'lock', value: r };
|
||||||
throw new Error('锁价申请详情未完整返回,请重新读取。');
|
},
|
||||||
return r;
|
[id, target, kind, editId],
|
||||||
}
|
|
||||||
if (kind === 'changes') return rows(r);
|
|
||||||
return readLock(r);
|
|
||||||
},
|
|
||||||
[target, editId, kind, id],
|
|
||||||
);
|
);
|
||||||
const lockUrl = '/api/price-locks/' + encodeURIComponent(target || ''),
|
const lockUrl = '/api/price-locks/' + encodeURIComponent(target || ''),
|
||||||
detailUrl =
|
detailUrl =
|
||||||
@@ -132,12 +224,18 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
|
|||||||
: kind === 'changes'
|
: kind === 'changes'
|
||||||
? '/api/price-lock-changes?status=' + changeFilter
|
? '/api/price-lock-changes?status=' + changeFilter
|
||||||
: kind === 'review'
|
: kind === 'review'
|
||||||
? '/api/price-lock-changes/' + encodeURIComponent(id)
|
? '/api/price-lock-changes/' + encodeURIComponent(id || '')
|
||||||
: deliver || detail || kind === 'detail'
|
: deliver || detail || kind === 'detail'
|
||||||
? lockUrl
|
? lockUrl
|
||||||
: '';
|
: '';
|
||||||
const resource = useRead(client, detailUrl, seq, validator),
|
const resource = useRead(client, detailUrl, seq, validator),
|
||||||
list = useRead(client, !create && !deliver ? '/api/price-locks?status=' + listFilter : '', seq, rows);
|
list = useRead(client, !create && !deliver ? '/api/price-locks?status=' + listFilter : '', seq, readLocks);
|
||||||
|
const result = resource.result,
|
||||||
|
edit = result?.kind === 'edit' ? result.value : null,
|
||||||
|
cancel = result?.kind === 'cancel' ? result.value : null,
|
||||||
|
lock = result?.kind === 'lock' ? result.value : null,
|
||||||
|
review = result?.kind === 'review' ? result.value : null,
|
||||||
|
changes = result?.kind === 'changes' ? result.value : null;
|
||||||
const reload = () => {
|
const reload = () => {
|
||||||
setError('');
|
setError('');
|
||||||
setStale(false);
|
setStale(false);
|
||||||
@@ -159,11 +257,12 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
|
|||||||
reset();
|
reset();
|
||||||
if (detail) navigate('price-locks');
|
if (detail) navigate('price-locks');
|
||||||
};
|
};
|
||||||
function action(e) {
|
function action(e: MouseEvent<HTMLDivElement>) {
|
||||||
const b = e.target.closest('button[data-action]');
|
if (!(e.target instanceof Element)) return;
|
||||||
|
const b = e.target.closest<HTMLButtonElement>('button[data-action]');
|
||||||
if (!b || !e.currentTarget.contains(b)) return;
|
if (!b || !e.currentTarget.contains(b)) return;
|
||||||
const k = b.dataset.action,
|
const k = b.dataset.action || '',
|
||||||
id = b.dataset.id;
|
id = b.dataset.id || '';
|
||||||
if (['edit-price-lock', 'cancel-price-lock'].includes(k) && blocked) {
|
if (['edit-price-lock', 'cancel-price-lock'].includes(k) && blocked) {
|
||||||
setError('请先恢复上次未确认的操作,再修改或作废锁价单。');
|
setError('请先恢复上次未确认的操作,再修改或作废锁价单。');
|
||||||
return;
|
return;
|
||||||
@@ -206,16 +305,24 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
|
|||||||
close();
|
close();
|
||||||
break;
|
break;
|
||||||
case 'price-lock-changes-filter':
|
case 'price-lock-changes-filter':
|
||||||
previousFilters.set(client, { user: state.user.id, list: listFilter, changes: b.dataset.status });
|
previousFilters.set(client, {
|
||||||
setChangeFilter(b.dataset.status);
|
user: state.user.id,
|
||||||
|
list: listFilter,
|
||||||
|
changes: b.dataset.status || changeFilter,
|
||||||
|
});
|
||||||
|
setChangeFilter(b.dataset.status || changeFilter);
|
||||||
reload();
|
reload();
|
||||||
break;
|
break;
|
||||||
case 'price-lock-changes-reload':
|
case 'price-lock-changes-reload':
|
||||||
reload();
|
reload();
|
||||||
break;
|
break;
|
||||||
case 'price-lock-list-status':
|
case 'price-lock-list-status':
|
||||||
previousFilters.set(client, { user: state.user.id, list: b.dataset.status, changes: changeFilter });
|
previousFilters.set(client, {
|
||||||
setFilter(b.dataset.status);
|
user: state.user.id,
|
||||||
|
list: b.dataset.status || listFilter,
|
||||||
|
changes: changeFilter,
|
||||||
|
});
|
||||||
|
setFilter(b.dataset.status || listFilter);
|
||||||
reload();
|
reload();
|
||||||
break;
|
break;
|
||||||
case 'refresh-price-locks':
|
case 'refresh-price-locks':
|
||||||
@@ -227,19 +334,26 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
async function confirmed(url, data, result) {
|
async function confirmed(url: string, data: unknown, result: unknown) {
|
||||||
|
if (!object(result) || !object(data)) throw new Error('锁价操作回执未完整返回,请重新读取后核对。');
|
||||||
|
const request = object(result.request) ? result.request : {},
|
||||||
|
saved = object(result.lock) ? result.lock : {};
|
||||||
const suffix = url.split('/').at(-1),
|
const suffix = url.split('/').at(-1),
|
||||||
lockId =
|
lockId =
|
||||||
result.price_lock_id ||
|
result.price_lock_id ||
|
||||||
result.request?.price_lock_id ||
|
request.price_lock_id ||
|
||||||
result.lock?.id ||
|
saved.id ||
|
||||||
(url === '/api/price-locks' ? result.id : url.split('/')[3]);
|
(url === '/api/price-locks' ? result.id : url.split('/')[3]);
|
||||||
|
if (typeof lockId !== 'string' || !lockId) throw new Error('锁价操作回执未完整返回,请重新读取后核对。');
|
||||||
if (url === '/api/price-locks') {
|
if (url === '/api/price-locks') {
|
||||||
localStorage.removeItem('mm-price-lock-draft-' + state.user.id);
|
localStorage.removeItem('mm-price-lock-draft-' + state.user.id);
|
||||||
reset();
|
reset();
|
||||||
navigate('price-locks', { search: '?lock=' + encodeURIComponent(lockId) });
|
navigate('price-locks', { search: '?lock=' + encodeURIComponent(lockId) });
|
||||||
setMessage('锁价已保存到待交付,尚未出入库、不计利润');
|
setMessage('锁价已保存到待交付,尚未出入库、不计利润');
|
||||||
} else if (suffix === 'deliver') {
|
} else if (suffix === 'deliver') {
|
||||||
|
const orderId = result.order_id || result.id;
|
||||||
|
if (typeof orderId !== 'string' || !orderId || typeof data.date !== 'string')
|
||||||
|
throw new Error('交付回执未完整返回,请重新读取后核对。');
|
||||||
localStorage.removeItem('mm-price-lock-delivery-' + state.user.id + '-' + url.split('/')[3]);
|
localStorage.removeItem('mm-price-lock-delivery-' + state.user.id + '-' + url.split('/')[3]);
|
||||||
const filterKey = 'mm-order-book-' + state.user.id;
|
const filterKey = 'mm-order-book-' + state.user.id;
|
||||||
const filters = readDraftFilters(filterKey);
|
const filters = readDraftFilters(filterKey);
|
||||||
@@ -247,7 +361,6 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
|
|||||||
filterKey,
|
filterKey,
|
||||||
JSON.stringify({ ...filters, mode: 'date', date: data.date, q: '', status: '' }),
|
JSON.stringify({ ...filters, mode: 'date', date: data.date, q: '', status: '' }),
|
||||||
);
|
);
|
||||||
const orderId = result.order_id || result.id;
|
|
||||||
navigate('orders', { search: '?order=' + encodeURIComponent(orderId) });
|
navigate('orders', { search: '?order=' + encodeURIComponent(orderId) });
|
||||||
} else {
|
} else {
|
||||||
setSavedLockId(lockId);
|
setSavedLockId(lockId);
|
||||||
@@ -269,13 +382,13 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
|
|||||||
}
|
}
|
||||||
reload();
|
reload();
|
||||||
try {
|
try {
|
||||||
const fresh = await client.api('/api/state');
|
const fresh = await loadState(client);
|
||||||
if (client.user === fresh.user.id) onState?.(fresh);
|
if (client.user === fresh.user.id) onState?.(fresh);
|
||||||
} catch {
|
} catch {
|
||||||
setMessage('操作已保存,最新记录暂未读到。请重新读取,不要重复提交。');
|
setMessage('操作已保存,最新记录暂未读到。请重新读取,不要重复提交。');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
async function save(url, data) {
|
async function save(url: string, data: Record<string, unknown>) {
|
||||||
const result = await client.mutate(url, data);
|
const result = await client.mutate(url, data);
|
||||||
await confirmed(url, data, result);
|
await confirmed(url, data, result);
|
||||||
}
|
}
|
||||||
@@ -287,21 +400,23 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
|
|||||||
const r = await client.retryPending();
|
const r = await client.retryPending();
|
||||||
if (r) await confirmed(r.job.url, r.job.data, r.result);
|
if (r) await confirmed(r.job.url, r.job.data, r.result);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err.message);
|
setError(errorText(err));
|
||||||
if (err.status === 409) setStale(true);
|
if (err instanceof Error && 'status' in err && err.status === 409) setStale(true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
async function modalSubmit(e) {
|
async function modalSubmit(e: FormEvent<HTMLDivElement>) {
|
||||||
const form = e.target;
|
const form = e.target;
|
||||||
if (!['price-lock-cancel-form', 'price-lock-review-form'].includes(form.id)) return;
|
if (!(form instanceof HTMLFormElement) || !['price-lock-cancel-form', 'price-lock-review-form'].includes(form.id))
|
||||||
|
return;
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
if (blocked || stale) return;
|
if (blocked || stale) return;
|
||||||
setError('');
|
setError('');
|
||||||
try {
|
try {
|
||||||
const r = resource.result,
|
const values = new FormData(form),
|
||||||
values = new FormData(form),
|
|
||||||
verified = values.get('verified') === 'on';
|
verified = values.get('verified') === 'on';
|
||||||
if (kind === 'cancel') {
|
if (kind === 'cancel') {
|
||||||
|
const r = cancel;
|
||||||
|
if (!r) throw new Error('锁价修改资料未完整返回,请重新读取。');
|
||||||
const reason = String(values.get('reason') || '').trim();
|
const reason = String(values.get('reason') || '').trim();
|
||||||
if (!reason) throw new Error('请填写作废原因。');
|
if (!reason) throw new Error('请填写作废原因。');
|
||||||
if (!verified) throw new Error('请核实录错单据并勾选整单作废。');
|
if (!verified) throw new Error('请核实录错单据并勾选整单作废。');
|
||||||
@@ -314,9 +429,11 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
|
|||||||
...(approval ? { action: 'cancel' } : {}),
|
...(approval ? { action: 'cancel' } : {}),
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
const decision = e.nativeEvent.submitter?.value,
|
const r = review;
|
||||||
|
const submitter = e.nativeEvent instanceof SubmitEvent ? e.nativeEvent.submitter : null;
|
||||||
|
const decision = submitter instanceof HTMLButtonElement ? submitter.value : '',
|
||||||
note = String(values.get('review_note') || '').trim();
|
note = String(values.get('review_note') || '').trim();
|
||||||
if (state.user.role !== 'owner' || r.status !== 'pending' || !['approve', 'reject'].includes(decision))
|
if (!r || state.user.role !== 'owner' || r.status !== 'pending' || !['approve', 'reject'].includes(decision))
|
||||||
throw new Error('请重新读取待复核申请。');
|
throw new Error('请重新读取待复核申请。');
|
||||||
if (decision === 'approve' && (r.stale || !verified))
|
if (decision === 'approve' && (r.stale || !verified))
|
||||||
throw new Error(
|
throw new Error(
|
||||||
@@ -331,8 +448,8 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err.message);
|
setError(errorText(err));
|
||||||
if (err.status === 409) setStale(true);
|
if (err instanceof Error && 'status' in err && err.status === 409) setStale(true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const waiting = resource.error ? (
|
const waiting = resource.error ? (
|
||||||
@@ -376,7 +493,7 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
|
|||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
{create ? (
|
{create ? (
|
||||||
editId && !resource.result ? (
|
editId && !edit ? (
|
||||||
waiting
|
waiting
|
||||||
) : (
|
) : (
|
||||||
<LockCreate
|
<LockCreate
|
||||||
@@ -385,22 +502,22 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
|
|||||||
state={state}
|
state={state}
|
||||||
session={session}
|
session={session}
|
||||||
views={views}
|
views={views}
|
||||||
edit={editId ? resource.result : null}
|
edit={editId ? edit : null}
|
||||||
save={save}
|
save={save}
|
||||||
blocked={blocked}
|
blocked={blocked}
|
||||||
reset={reload}
|
reset={reload}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
) : deliver ? (
|
) : deliver ? (
|
||||||
resource.result ? (
|
lock ? (
|
||||||
resource.result.status === 'pending' ? (
|
lock.status === 'pending' ? (
|
||||||
<LockDelivery
|
<LockDelivery
|
||||||
key={deliver}
|
key={deliver}
|
||||||
client={client}
|
client={client}
|
||||||
state={state}
|
state={state}
|
||||||
session={session}
|
session={session}
|
||||||
views={views}
|
views={views}
|
||||||
lock={resource.result}
|
lock={lock}
|
||||||
save={save}
|
save={save}
|
||||||
blocked={blocked}
|
blocked={blocked}
|
||||||
/>
|
/>
|
||||||
@@ -409,9 +526,9 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
|
|||||||
<Heading kicker="LOCK DELIVERED" title="这张锁价单已交付" desc="请查看已生成的销售单,不要重复交付。">
|
<Heading kicker="LOCK DELIVERED" title="这张锁价单已交付" desc="请查看已生成的销售单,不要重复交付。">
|
||||||
<Act name="refresh-price-locks">返回待交付</Act>
|
<Act name="refresh-price-locks">返回待交付</Act>
|
||||||
</Heading>
|
</Heading>
|
||||||
{views.priceLockFacts(resource.result)}
|
{views.priceLockFacts(lock)}
|
||||||
{resource.result.final_order_id && (
|
{lock.final_order_id && (
|
||||||
<Act name="open-lock-order" data-id={resource.result.final_order_id}>
|
<Act name="open-lock-order" data-id={lock.final_order_id}>
|
||||||
查看销售单
|
查看销售单
|
||||||
</Act>
|
</Act>
|
||||||
)}
|
)}
|
||||||
@@ -465,7 +582,7 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
{dialog && !deliver && !create && (
|
{dialog && !deliver && !create && (
|
||||||
<Modal key={kind + '-' + id} kind={kind} close={close}>
|
<Modal key={kind + '-' + id} kind={dialog.kind} close={close}>
|
||||||
{kind === 'changes' ? (
|
{kind === 'changes' ? (
|
||||||
<>
|
<>
|
||||||
<button type="button" className="dialog-close" data-action="price-lock-changes-close" aria-label="关闭">
|
<button type="button" className="dialog-close" data-action="price-lock-changes-close" aria-label="关闭">
|
||||||
@@ -484,28 +601,27 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
|
|||||||
</Act>
|
</Act>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
<div id="price-lock-changes-content">
|
<div id="price-lock-changes-content">{changes ? views.changeRows(changes) : waiting}</div>
|
||||||
{resource.result ? views.changeRows(resource.result) : waiting}
|
|
||||||
</div>
|
|
||||||
</>
|
</>
|
||||||
) : kind === 'detail' ? (
|
) : kind === 'detail' ? (
|
||||||
<>
|
<>
|
||||||
<button type="button" className="dialog-close" data-action="close-price-lock" aria-label="关闭锁价记录">
|
<button type="button" className="dialog-close" data-action="close-price-lock" aria-label="关闭锁价记录">
|
||||||
×
|
×
|
||||||
</button>
|
</button>
|
||||||
<div id="price-lock-detail">{resource.result ? views.detailView(resource.result) : waiting}</div>
|
<div id="price-lock-detail">{lock ? views.detailView(lock) : waiting}</div>
|
||||||
</>
|
</>
|
||||||
) : resource.result ? (
|
) : (kind === 'cancel' ? cancel : review) ? (
|
||||||
<fieldset style={{ display: 'contents' }} disabled={blocked || stale}>
|
<fieldset style={{ display: 'contents' }} disabled={blocked || stale}>
|
||||||
{kind === 'cancel'
|
{kind === 'cancel' && cancel
|
||||||
? views.cancelView(
|
? views.cancelView(
|
||||||
resource.result,
|
cancel,
|
||||||
state.user.role === 'assistant' &&
|
state.user.role === 'assistant' &&
|
||||||
(resource.result.requiresApproval !== false || resource.result.inputs.date !== state.today),
|
(cancel.requiresApproval !== false || cancel.inputs.date !== state.today),
|
||||||
)
|
)
|
||||||
: views.changeDetail(
|
: review &&
|
||||||
resource.result,
|
views.changeDetail(
|
||||||
state.user.role === 'owner' && resource.result.status === 'pending' && !resource.result.stale,
|
review,
|
||||||
|
state.user.role === 'owner' && review.status === 'pending' && !review.stale,
|
||||||
)}
|
)}
|
||||||
</fieldset>
|
</fieldset>
|
||||||
) : (
|
) : (
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import type { LineState, OrderForm } from '../../shared';
|
||||||
|
import type { LockPayment, SavedPayment } from './formParts';
|
||||||
|
|
||||||
|
// 锁价交付在本地保存可提交的商品行。早期单件草稿将商品放在顶层的 line。
|
||||||
|
export interface DeliveryLine {
|
||||||
|
quantity: string;
|
||||||
|
pocket: string;
|
||||||
|
laborRate: string;
|
||||||
|
laborMode: string;
|
||||||
|
pieces: string;
|
||||||
|
stockCount?: string | null;
|
||||||
|
charges: { name: string; amount: string }[];
|
||||||
|
payer: string;
|
||||||
|
costParts: { labor: string; accessories: string; other: string };
|
||||||
|
costLabor: { mode: string; rate?: string; amount?: string };
|
||||||
|
costPayers: Record<string, string>;
|
||||||
|
}
|
||||||
|
export interface SavedLine extends Partial<DeliveryLine> {
|
||||||
|
lineId?: string;
|
||||||
|
line?: Partial<DeliveryLine>;
|
||||||
|
inventory?: { original?: string; countSource?: string; extra?: string };
|
||||||
|
extraMaterial?: { source?: string; rate?: string; payer?: string; verified?: boolean };
|
||||||
|
}
|
||||||
|
export interface DeliveryDraft extends SavedLine {
|
||||||
|
revision?: number;
|
||||||
|
lines?: SavedLine[];
|
||||||
|
date?: string;
|
||||||
|
customer_type?: string;
|
||||||
|
note?: string;
|
||||||
|
discount?: string;
|
||||||
|
fee_items?: Record<string, unknown>[];
|
||||||
|
settlement?: SavedPayment;
|
||||||
|
}
|
||||||
|
export interface StockSelection {
|
||||||
|
original_stock: string;
|
||||||
|
count_source: string;
|
||||||
|
extra_source: string;
|
||||||
|
extra_rate: string;
|
||||||
|
extra_payer: string;
|
||||||
|
extra_stock: string;
|
||||||
|
extra_verified: boolean;
|
||||||
|
}
|
||||||
|
export interface DeliveryForm {
|
||||||
|
form: OrderForm;
|
||||||
|
stock: StockSelection[];
|
||||||
|
customer_type: string;
|
||||||
|
note: string;
|
||||||
|
payment: LockPayment;
|
||||||
|
verified: boolean;
|
||||||
|
}
|
||||||
|
export type EditLine = (line: LineState) => void;
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
import type { LockCreateDraft, InputLine } from './types';
|
||||||
|
import type { SavedPayment } from './formParts';
|
||||||
|
import type { DeliveryDraft, SavedLine } from './deliveryTypes';
|
||||||
|
|
||||||
|
const record = (value: unknown): value is Record<string, unknown> =>
|
||||||
|
value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||||
|
const optional = (value: unknown, predicate: (v: unknown) => boolean) => value == null || predicate(value);
|
||||||
|
const text = (v: unknown) => typeof v === 'string';
|
||||||
|
const scalar = (v: unknown) => text(v) || typeof v === 'number';
|
||||||
|
function payment(v: unknown): v is SavedPayment {
|
||||||
|
return (
|
||||||
|
record(v) &&
|
||||||
|
optional(v.account, text) &&
|
||||||
|
optional(v.credit_card_fee_payer, text) &&
|
||||||
|
optional(v.amount, scalar) &&
|
||||||
|
optional(v.verified, x => typeof x === 'boolean')
|
||||||
|
);
|
||||||
|
}
|
||||||
|
function charges(v: unknown) {
|
||||||
|
return Array.isArray(v) && v.every(row => record(row) && optional(row.name, text) && optional(row.amount, scalar));
|
||||||
|
}
|
||||||
|
function createLine(v: unknown): v is InputLine {
|
||||||
|
return (
|
||||||
|
record(v) &&
|
||||||
|
['name', 'code', 'lineId', 'laborMode'].every(k => optional(v[k], text)) &&
|
||||||
|
['quantity', 'goldPrice', 'laborRate', 'pieces'].every(k => optional(v[k], scalar)) &&
|
||||||
|
optional(v.charges, charges) &&
|
||||||
|
optional(v.material, record)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
function createDraft(v: unknown): v is LockCreateDraft {
|
||||||
|
return (
|
||||||
|
record(v) &&
|
||||||
|
['member', 'date', 'customer', 'salesperson', 'note'].every(k => optional(v[k], text)) &&
|
||||||
|
optional(v.discount, scalar) &&
|
||||||
|
optional(v.payment, payment) &&
|
||||||
|
optional(v.line, createLine) &&
|
||||||
|
optional(v.material, record) &&
|
||||||
|
optional(v.lines, x => Array.isArray(x) && x.every(createLine))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
export type SavedCreate = LockCreateDraft & { inputs?: LockCreateDraft; reason?: string; revision?: number };
|
||||||
|
export function savedCreate(v: unknown): v is SavedCreate {
|
||||||
|
return (
|
||||||
|
record(v) &&
|
||||||
|
optional(v.inputs, createDraft) &&
|
||||||
|
optional(v.revision, Number.isSafeInteger) &&
|
||||||
|
optional(v.reason, text) &&
|
||||||
|
createDraft(v)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
function deliveryLine(v: unknown): v is SavedLine {
|
||||||
|
return (
|
||||||
|
record(v) &&
|
||||||
|
optional(v.lineId, text) &&
|
||||||
|
optional(v.quantity, scalar) &&
|
||||||
|
optional(v.pocket, text) &&
|
||||||
|
optional(v.line, record) &&
|
||||||
|
optional(v.charges, charges) &&
|
||||||
|
optional(v.inventory, record) &&
|
||||||
|
optional(v.extraMaterial, record)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
export function savedDelivery(v: unknown): v is DeliveryDraft {
|
||||||
|
return (
|
||||||
|
record(v) &&
|
||||||
|
optional(v.revision, Number.isSafeInteger) &&
|
||||||
|
optional(v.lines, x => Array.isArray(x) && x.every(deliveryLine)) &&
|
||||||
|
optional(v.fee_items, x => Array.isArray(x) && x.every(record)) &&
|
||||||
|
optional(v.settlement, payment) &&
|
||||||
|
deliveryLine(v)
|
||||||
|
);
|
||||||
|
}
|
||||||
+94
-20
@@ -1,6 +1,52 @@
|
|||||||
|
import type { ButtonHTMLAttributes, InputHTMLAttributes, ReactNode, SelectHTMLAttributes } from 'react';
|
||||||
|
import type { ChargeState, LedgerState } from '../../shared';
|
||||||
|
interface TextField extends Omit<InputHTMLAttributes<HTMLInputElement>, 'name' | 'value'> {
|
||||||
|
label: ReactNode;
|
||||||
|
name: string;
|
||||||
|
value?: string | number | null;
|
||||||
|
update?: (value: string) => void;
|
||||||
|
}
|
||||||
|
type Option = string | readonly [string, string, boolean?];
|
||||||
|
interface ChoiceProps extends Omit<SelectHTMLAttributes<HTMLSelectElement>, 'value'> {
|
||||||
|
label: ReactNode;
|
||||||
|
value?: string | null;
|
||||||
|
options: readonly Option[];
|
||||||
|
update?: (value: string) => void;
|
||||||
|
}
|
||||||
|
interface CheckProps extends Omit<InputHTMLAttributes<HTMLInputElement>, 'value'> {
|
||||||
|
value?: boolean;
|
||||||
|
update: (v: boolean) => void;
|
||||||
|
}
|
||||||
|
export interface LockPayment {
|
||||||
|
method: string;
|
||||||
|
recipient: string;
|
||||||
|
payer: string;
|
||||||
|
verified: boolean;
|
||||||
|
amount: string;
|
||||||
|
}
|
||||||
|
export interface SavedPayment {
|
||||||
|
account?: string;
|
||||||
|
credit_card_fee_payer?: string;
|
||||||
|
verified?: boolean;
|
||||||
|
amount?: string;
|
||||||
|
}
|
||||||
|
interface PaymentProps {
|
||||||
|
state: LedgerState;
|
||||||
|
payment: LockPayment;
|
||||||
|
change: (p: LockPayment) => void;
|
||||||
|
}
|
||||||
import { Model, Cards, Calc } from '../../shared';
|
import { Model, Cards, Calc } from '../../shared';
|
||||||
|
|
||||||
export function Field({ label, name, value = '', type = 'text', update, hidden = false, children, ...props }) {
|
export function Field({
|
||||||
|
label,
|
||||||
|
name,
|
||||||
|
value = '',
|
||||||
|
type = 'text',
|
||||||
|
update,
|
||||||
|
hidden = false,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: TextField) {
|
||||||
return (
|
return (
|
||||||
<label hidden={hidden}>
|
<label hidden={hidden}>
|
||||||
{label}
|
{label}
|
||||||
@@ -15,16 +61,16 @@ export function Field({ label, name, value = '', type = 'text', update, hidden =
|
|||||||
</label>
|
</label>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
export function Money(props) {
|
export function Money(props: TextField) {
|
||||||
return <Field type="number" min="0" step="0.01" required {...props} />;
|
return <Field type="number" min="0" step="0.01" required {...props} />;
|
||||||
}
|
}
|
||||||
export function Choice({ label, name, value, options, update, children, hidden, ...props }) {
|
export function Choice({ label, name, value, options, update, children, hidden, ...props }: ChoiceProps) {
|
||||||
return (
|
return (
|
||||||
<label hidden={hidden}>
|
<label hidden={hidden}>
|
||||||
{label}
|
{label}
|
||||||
<select name={name} value={value ?? ''} {...props} onChange={update ? e => update(e.target.value) : undefined}>
|
<select name={name} value={value ?? ''} {...props} onChange={update ? e => update(e.target.value) : undefined}>
|
||||||
{options.map(v => {
|
{options.map(v => {
|
||||||
const [k, title, disabled] = Array.isArray(v) ? v : [v, v];
|
const [k, title, disabled] = typeof v === 'string' ? [v, v] : v;
|
||||||
return (
|
return (
|
||||||
<option key={k} value={k} disabled={!!disabled}>
|
<option key={k} value={k} disabled={!!disabled}>
|
||||||
{title}
|
{title}
|
||||||
@@ -36,7 +82,7 @@ export function Choice({ label, name, value, options, update, children, hidden,
|
|||||||
</label>
|
</label>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
export function Check({ name, value, update, children, hidden, ...props }) {
|
export function Check({ name, value, update, children, hidden, ...props }: CheckProps) {
|
||||||
return (
|
return (
|
||||||
<label className="check" hidden={hidden}>
|
<label className="check" hidden={hidden}>
|
||||||
<input type="checkbox" name={name} checked={!!value} onChange={e => update(e.target.checked)} {...props} />
|
<input type="checkbox" name={name} checked={!!value} onChange={e => update(e.target.checked)} {...props} />
|
||||||
@@ -44,14 +90,24 @@ export function Check({ name, value, update, children, hidden, ...props }) {
|
|||||||
</label>
|
</label>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
export function Act({ name, onClick, children, className = '', ...props }) {
|
export function Act({ name, onClick, children, className = '', ...props }: ButtonHTMLAttributes<HTMLButtonElement>) {
|
||||||
return (
|
return (
|
||||||
<button type="button" className={className} data-action={name} onClick={onClick} {...props}>
|
<button type="button" className={className} data-action={name} onClick={onClick} {...props}>
|
||||||
{children}
|
{children}
|
||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
export function Heading({ title, kicker, desc, children }) {
|
export function Heading({
|
||||||
|
title,
|
||||||
|
kicker,
|
||||||
|
desc,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
title: string;
|
||||||
|
kicker: string;
|
||||||
|
desc: string;
|
||||||
|
children?: ReactNode;
|
||||||
|
}) {
|
||||||
return (
|
return (
|
||||||
<div className="page-heading">
|
<div className="page-heading">
|
||||||
<div>
|
<div>
|
||||||
@@ -63,8 +119,18 @@ export function Heading({ title, kicker, desc, children }) {
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
export function Charges({ rows, change, title = '客户附加项目(选填)', restore }) {
|
export function Charges({
|
||||||
const set = (i, charge) => change(rows.map((r, n) => (n === i ? charge : r)));
|
rows,
|
||||||
|
change,
|
||||||
|
title = '客户附加项目(选填)',
|
||||||
|
restore,
|
||||||
|
}: {
|
||||||
|
rows: ChargeState[];
|
||||||
|
change: (rows: ChargeState[]) => void;
|
||||||
|
title?: string;
|
||||||
|
restore?: (i: number) => void;
|
||||||
|
}) {
|
||||||
|
const set = (i: number, charge: ChargeState) => change(rows.map((r, n) => (n === i ? charge : r)));
|
||||||
return (
|
return (
|
||||||
<div className="sale-charges">
|
<div className="sale-charges">
|
||||||
<div className="panel-title">
|
<div className="panel-title">
|
||||||
@@ -128,7 +194,7 @@ export function AccountFields({
|
|||||||
recipientLabel = '收款人',
|
recipientLabel = '收款人',
|
||||||
disabled = false,
|
disabled = false,
|
||||||
required = false,
|
required = false,
|
||||||
}) {
|
}: PaymentProps & { methodLabel?: string; recipientLabel?: string; disabled?: boolean; required?: boolean }) {
|
||||||
const card = payment.method === '信用卡';
|
const card = payment.method === '信用卡';
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -159,11 +225,18 @@ export function AccountFields({
|
|||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
export function CardPreview({ id, state, payment, cents, change, enabled = true }) {
|
export function CardPreview({
|
||||||
|
id,
|
||||||
|
state,
|
||||||
|
payment,
|
||||||
|
cents,
|
||||||
|
change,
|
||||||
|
enabled = true,
|
||||||
|
}: PaymentProps & { id: string; cents: number | null; enabled?: boolean }) {
|
||||||
const visible = enabled && payment.method === '信用卡',
|
const visible = enabled && payment.method === '信用卡',
|
||||||
rate = Model.creditCardRate(state);
|
rate = Model.creditCardRate(state);
|
||||||
let amount = null;
|
let amount = null;
|
||||||
if (visible && Number.isSafeInteger(cents) && cents >= 0) amount = Cards.amount(cents, rate);
|
if (visible && cents !== null && Number.isSafeInteger(cents) && cents >= 0) amount = Cards.amount(cents, rate);
|
||||||
return (
|
return (
|
||||||
<div className="credit-card-preview" id={id} hidden={!visible}>
|
<div className="credit-card-preview" id={id} hidden={!visible}>
|
||||||
<div className="credit-card-heading">
|
<div className="credit-card-heading">
|
||||||
@@ -211,28 +284,29 @@ export function CardPreview({ id, state, payment, cents, change, enabled = true
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
export function amountPreview(raw) {
|
export function amountPreview(raw: string) {
|
||||||
try {
|
try {
|
||||||
return Calc.cents(raw);
|
return Calc.cents(raw);
|
||||||
} catch {
|
} catch {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
export function safeEstimate(fn) {
|
export function safeEstimate<T>(fn: () => T): { result: T; error?: undefined } | { result?: undefined; error: string } {
|
||||||
try {
|
try {
|
||||||
return { result: fn() };
|
return { result: fn() };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return { error: error.message };
|
return { error: error instanceof Error ? error.message : String(error) };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
export function readDraft(key) {
|
export function readDraft<T>(key: string, valid: (v: unknown) => v is T): T | null {
|
||||||
try {
|
try {
|
||||||
return JSON.parse(localStorage.getItem(key) || 'null');
|
const value: unknown = JSON.parse(localStorage.getItem(key) || 'null');
|
||||||
|
return valid(value) ? value : null;
|
||||||
} catch {
|
} catch {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
export function saleCharges(charges) {
|
export function saleCharges(charges: ChargeState[]) {
|
||||||
return charges.map(r => ({
|
return charges.map(r => ({
|
||||||
id: r.id,
|
id: r.id,
|
||||||
nameType: r.type,
|
nameType: r.type,
|
||||||
@@ -243,7 +317,7 @@ export function saleCharges(charges) {
|
|||||||
...(r.costRemoved ? { costRemoved: true } : {}),
|
...(r.costRemoved ? { costRemoved: true } : {}),
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
export function initialPayment(state, p, member) {
|
export function initialPayment(state: LedgerState, p: SavedPayment | undefined, member: string): LockPayment {
|
||||||
const id = Model.accountIdentity(state, p?.account || '');
|
const id = Model.accountIdentity(state, p?.account || '');
|
||||||
return {
|
return {
|
||||||
method: id?.channel || '微信',
|
method: id?.channel || '微信',
|
||||||
@@ -253,7 +327,7 @@ export function initialPayment(state, p, member) {
|
|||||||
amount: p?.amount ?? '',
|
amount: p?.amount ?? '',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
export function paymentPayload(payment) {
|
export function paymentPayload(payment: LockPayment) {
|
||||||
return {
|
return {
|
||||||
account: Cards.normalizeAccount((payment.method === '信用卡' ? '麦麦' : payment.recipient) + payment.method),
|
account: Cards.normalizeAccount((payment.method === '信用卡' ? '麦麦' : payment.recipient) + payment.method),
|
||||||
credit_card_fee_payer: payment.payer,
|
credit_card_fee_payer: payment.payer,
|
||||||
+87
-63
@@ -1,12 +1,32 @@
|
|||||||
|
import type { ReactNode } from 'react';
|
||||||
|
import type { LedgerState, SessionInfo } from '../../shared';
|
||||||
|
import type { QuoteRequest, SourceDescription } from '../../lib/materialQuote';
|
||||||
|
import type { Impact, LockCost, Allocation } from '../MaterialPools/model';
|
||||||
|
import type {
|
||||||
|
LockRecord,
|
||||||
|
LockEdit,
|
||||||
|
LockChange,
|
||||||
|
ChangeListRow,
|
||||||
|
LockCreateDraft,
|
||||||
|
LockedSource,
|
||||||
|
ReservedMaterial,
|
||||||
|
DeliveryCost,
|
||||||
|
ChangeSnapshot,
|
||||||
|
} from './types';
|
||||||
import { Children, Fragment } from 'react';
|
import { Children, Fragment } from 'react';
|
||||||
import { describeMaterialSources, validateMaterialQuote as checkMaterialQuote } from '../../lib/materialQuote';
|
import { describeMaterialSources, validateMaterialQuote as checkMaterialQuote } from '../../lib/materialQuote';
|
||||||
import { Model, Calc as LedgerCalc, Values } from '../../shared';
|
import { Model, Calc as LedgerCalc, Values } from '../../shared';
|
||||||
export function lockViews(state, session) {
|
function isInputSnapshot(value: LockRecord | LockCreateDraft): value is LockCreateDraft {
|
||||||
const validateMaterialQuote = (result, input) => checkMaterialQuote(result, input, Model.memberKeys(state));
|
const first = value.lines?.[0];
|
||||||
function priceLockSplitMaterialSources(pool, mg) {
|
return !!first && !('line' in first);
|
||||||
|
}
|
||||||
|
export function lockViews(state: LedgerState, session: SessionInfo) {
|
||||||
|
const validateMaterialQuote = (result: unknown, input: QuoteRequest) =>
|
||||||
|
checkMaterialQuote(result, input, Model.memberKeys(state));
|
||||||
|
function priceLockSplitMaterialSources(pool: ReservedMaterial, mg: number) {
|
||||||
let left = mg;
|
let left = mg;
|
||||||
const taken = [],
|
const taken: LockedSource[] = [],
|
||||||
rest = [];
|
rest: LockedSource[] = [];
|
||||||
if (
|
if (
|
||||||
!Array.isArray(pool.materialSources) ||
|
!Array.isArray(pool.materialSources) ||
|
||||||
pool.materialSources.reduce((sum, source) => sum + source.quantity, 0) !== pool.quantity ||
|
pool.materialSources.reduce((sum, source) => sum + source.quantity, 0) !== pool.quantity ||
|
||||||
@@ -15,7 +35,7 @@ export function lockViews(state, session) {
|
|||||||
throw new Error('原锁分来源克重或成本未完整读到,请重新读取。');
|
throw new Error('原锁分来源克重或成本未完整读到,请重新读取。');
|
||||||
for (const source of pool.materialSources) {
|
for (const source of pool.materialSources) {
|
||||||
if (
|
if (
|
||||||
!['quantity', 'amount', 'basisAmount', 'basisMg', 'prefixMg', 'prefixAmount'].every(
|
!(['quantity', 'amount', 'basisAmount', 'basisMg', 'prefixMg', 'prefixAmount'] as const).every(
|
||||||
key => Number.isSafeInteger(source[key]) && source[key] >= 0,
|
key => Number.isSafeInteger(source[key]) && source[key] >= 0,
|
||||||
) ||
|
) ||
|
||||||
!source.basisMg ||
|
!source.basisMg ||
|
||||||
@@ -102,7 +122,7 @@ export function lockViews(state, session) {
|
|||||||
rest,
|
rest,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
function lockQuantityMg(value) {
|
function lockQuantityMg(value: string) {
|
||||||
const text = String(value ?? '').trim();
|
const text = String(value ?? '').trim();
|
||||||
if (!/^\d+(?:\.\d{1,3})?$/.test(text)) throw new Error('克重请填写正数,最多3位小数。');
|
if (!/^\d+(?:\.\d{1,3})?$/.test(text)) throw new Error('克重请填写正数,最多3位小数。');
|
||||||
const [whole, part = ''] = text.split('.'),
|
const [whole, part = ''] = text.split('.'),
|
||||||
@@ -110,12 +130,12 @@ export function lockViews(state, session) {
|
|||||||
if (!Number.isSafeInteger(mg) || mg <= 0) throw new Error('克重请填写大于0的有效数字。');
|
if (!Number.isSafeInteger(mg) || mg <= 0) throw new Error('克重请填写大于0的有效数字。');
|
||||||
return mg;
|
return mg;
|
||||||
}
|
}
|
||||||
function priceLockDeliveryCost(lock, quantity, extraBuyRate) {
|
function priceLockDeliveryCost(lock: LockRecord, quantity: string, extraBuyRate: string): DeliveryCost {
|
||||||
if (!priceLockUsesPool(lock))
|
if (!priceLockUsesPool(lock))
|
||||||
return LedgerCalc.priceLockCost({
|
return LedgerCalc.priceLockCost({
|
||||||
lockedQuantity: grams(lock.locked_mg),
|
lockedQuantity: grams(lock.locked_mg),
|
||||||
quantity,
|
quantity,
|
||||||
buyRate: (lock.buy_rate / 100).toFixed(2),
|
buyRate: (Number(lock.buy_rate) / 100).toFixed(2),
|
||||||
extraBuyRate,
|
extraBuyRate,
|
||||||
});
|
});
|
||||||
const pool = lock.materialPool,
|
const pool = lock.materialPool,
|
||||||
@@ -125,8 +145,9 @@ export function lockViews(state, session) {
|
|||||||
leftoverMg = lock.locked_mg - originalUsedMg;
|
leftoverMg = lock.locked_mg - originalUsedMg;
|
||||||
if (
|
if (
|
||||||
!pool ||
|
!pool ||
|
||||||
!['basisAmount', 'basisMg', 'prefixMg', 'prefixAmount', 'amount'].every(
|
typeof pool.amount !== 'number' ||
|
||||||
key => Number.isSafeInteger(pool[key]) && pool[key] >= 0,
|
!(['basisAmount', 'basisMg', 'prefixMg', 'prefixAmount', 'amount'] as const).every(
|
||||||
|
key => typeof pool[key] === 'number' && Number.isSafeInteger(pool[key]) && pool[key] >= 0,
|
||||||
) ||
|
) ||
|
||||||
!pool.basisMg
|
!pool.basisMg
|
||||||
)
|
)
|
||||||
@@ -172,7 +193,7 @@ export function lockViews(state, session) {
|
|||||||
: {}),
|
: {}),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
function priceLockLineInputs(lock) {
|
function priceLockLineInputs(lock: LockRecord) {
|
||||||
const line = lock.line,
|
const line = lock.line,
|
||||||
payer = priceLockMaterialAllocations(lock)[0]?.payer || lock.buy_payer || 'owner';
|
payer = priceLockMaterialAllocations(lock)[0]?.payer || lock.buy_payer || 'owner';
|
||||||
return {
|
return {
|
||||||
@@ -188,7 +209,7 @@ export function lockViews(state, session) {
|
|||||||
})),
|
})),
|
||||||
payer,
|
payer,
|
||||||
costParts: {
|
costParts: {
|
||||||
material: (lock.material_amount / 100).toFixed(2),
|
material: (Number(lock.material_amount) / 100).toFixed(2),
|
||||||
labor: '',
|
labor: '',
|
||||||
accessories: '0',
|
accessories: '0',
|
||||||
other: '0',
|
other: '0',
|
||||||
@@ -205,7 +226,7 @@ export function lockViews(state, session) {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
function detailView(lock) {
|
function detailView(lock: LockRecord) {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className={'order-header'}>
|
<div className={'order-header'}>
|
||||||
@@ -256,12 +277,12 @@ export function lockViews(state, session) {
|
|||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function priceLockCardFeeTotal(lock) {
|
function priceLockCardFeeTotal(lock: LockRecord) {
|
||||||
return Number.isSafeInteger(lock.credit_card_fee_total)
|
return lock.credit_card_fee_total !== undefined && Number.isSafeInteger(lock.credit_card_fee_total)
|
||||||
? lock.credit_card_fee_total
|
? lock.credit_card_fee_total
|
||||||
: (lock.credit_card_fees || []).reduce((sum, item) => sum + item.amount, 0);
|
: (lock.credit_card_fees || []).reduce((sum, item) => sum + item.amount, 0);
|
||||||
}
|
}
|
||||||
function renderPriceLockCardFees(lock) {
|
function renderPriceLockCardFees(lock: LockRecord) {
|
||||||
const fees = lock.credit_card_fees || [];
|
const fees = lock.credit_card_fees || [];
|
||||||
if (!fees.length && !priceLockCardFeeTotal(lock)) return '';
|
if (!fees.length && !priceLockCardFeeTotal(lock)) return '';
|
||||||
return (
|
return (
|
||||||
@@ -289,7 +310,7 @@ export function lockViews(state, session) {
|
|||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function priceLockFacts(lock) {
|
function priceLockFacts(lock: LockRecord) {
|
||||||
const voided =
|
const voided =
|
||||||
lock.status === 'cancelled' ? (
|
lock.status === 'cancelled' ? (
|
||||||
<>
|
<>
|
||||||
@@ -417,7 +438,7 @@ export function lockViews(state, session) {
|
|||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function cancelView(result, approval) {
|
function cancelView(result: LockEdit & { lock: LockRecord }, approval: boolean) {
|
||||||
const id = result.lock.id;
|
const id = result.lock.id;
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -440,7 +461,7 @@ export function lockViews(state, session) {
|
|||||||
</div>
|
</div>
|
||||||
<form id={'price-lock-cancel-form'}>
|
<form id={'price-lock-cancel-form'}>
|
||||||
<label>
|
<label>
|
||||||
作废原因<textarea name={'reason'} required={true} maxLength={'200'} rows={'2'}></textarea>
|
作废原因<textarea name={'reason'} required={true} maxLength={200} rows={2}></textarea>
|
||||||
</label>
|
</label>
|
||||||
<label className={'check'}>
|
<label className={'check'}>
|
||||||
<input name={'verified'} type={'checkbox'} required={true} />
|
<input name={'verified'} type={'checkbox'} required={true} />
|
||||||
@@ -466,8 +487,9 @@ export function lockViews(state, session) {
|
|||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function renderPriceLockRelatedOrders(rows) {
|
function renderPriceLockRelatedOrders(rows: Impact['relatedOrders']) {
|
||||||
const money = value => (value === null ? '待核算' : Number.isSafeInteger(value) ? '¥' + yuan(value) : '未提供');
|
const money = (value: number | null | undefined) =>
|
||||||
|
value === null ? '待核算' : Number.isSafeInteger(value) ? '¥' + yuan(value) : '未提供';
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<section className={'lock-related-orders'}>
|
<section className={'lock-related-orders'}>
|
||||||
@@ -508,13 +530,16 @@ export function lockViews(state, session) {
|
|||||||
}
|
}
|
||||||
const validOrderDate = Values.validDate;
|
const validOrderDate = Values.validDate;
|
||||||
const teamMemberKeys = () => Model.memberKeys(state);
|
const teamMemberKeys = () => Model.memberKeys(state);
|
||||||
function validateRelatedPriceLocks(items) {
|
function validateRelatedPriceLocks(items: Impact['relatedPriceLocks']) {
|
||||||
if (items === undefined) return [];
|
if (items === undefined) return [];
|
||||||
const amount = value => value === null || (Number.isSafeInteger(value) && value >= 0);
|
const amount = (value: number | null | undefined) =>
|
||||||
const snapshot = value =>
|
value === null || (typeof value === 'number' && Number.isSafeInteger(value) && value >= 0);
|
||||||
|
const snapshot = (value: LockCost) =>
|
||||||
value &&
|
value &&
|
||||||
amount(value.materialAmount) &&
|
amount(value.materialAmount) &&
|
||||||
['usedMaterialAmount', 'leftoverCost'].every(key => !Object.hasOwn(value, key) || amount(value[key])) &&
|
(['usedMaterialAmount', 'leftoverCost'] as const).every(
|
||||||
|
key => !Object.hasOwn(value, key) || amount(value[key]),
|
||||||
|
) &&
|
||||||
Array.isArray(value.allocations) &&
|
Array.isArray(value.allocations) &&
|
||||||
value.allocations.every(
|
value.allocations.every(
|
||||||
part => teamMemberKeys().includes(part.payer) && Number.isSafeInteger(part.amount) && part.amount >= 0,
|
part => teamMemberKeys().includes(part.payer) && Number.isSafeInteger(part.amount) && part.amount >= 0,
|
||||||
@@ -536,17 +561,17 @@ export function lockViews(state, session) {
|
|||||||
throw new Error('关联锁价单的成本影响未完整返回,请重新读取后复核。');
|
throw new Error('关联锁价单的成本影响未完整返回,请重新读取后复核。');
|
||||||
return items;
|
return items;
|
||||||
}
|
}
|
||||||
function renderRelatedPriceLocks(items) {
|
function renderRelatedPriceLocks(items: Impact['relatedPriceLocks']) {
|
||||||
const locks = validateRelatedPriceLocks(items);
|
const locks = validateRelatedPriceLocks(items);
|
||||||
if (!locks.length) return '';
|
if (!locks.length) return '';
|
||||||
const money = value => (value === null ? '待补齐' : '¥' + yuan(value)),
|
const money = (value: number | null | undefined) => (value === null ? '待补齐' : '¥' + yuan(value)),
|
||||||
sources = value =>
|
sources = (value: LockCost) =>
|
||||||
value.allocations.length
|
value.allocations.length
|
||||||
? value.allocations.map(part => teamMemberName(part.payer) + ' ' + money(part.amount)).join(';')
|
? value.allocations.map(part => teamMemberName(part.payer) + ' ' + money(part.amount)).join(';')
|
||||||
: value.materialAmount === null
|
: value.materialAmount === null
|
||||||
? '待补齐后分摊'
|
? '待补齐后分摊'
|
||||||
: '无分摊金额';
|
: '无分摊金额';
|
||||||
const pair = (name, before, after) => (
|
const pair = (name: string, before: ReactNode, after: ReactNode) => (
|
||||||
<>
|
<>
|
||||||
<tr>
|
<tr>
|
||||||
<th scope={'row'}>{name}</th>
|
<th scope={'row'}>{name}</th>
|
||||||
@@ -581,7 +606,7 @@ export function lockViews(state, session) {
|
|||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{pair('原锁预留料费', money(lock.before.materialAmount), money(lock.after.materialAmount))}
|
{pair('原锁预留料费', money(lock.before.materialAmount), money(lock.after.materialAmount))}
|
||||||
{['before', 'after'].some(side => Object.hasOwn(lock[side], 'usedMaterialAmount'))
|
{(['before', 'after'] as const).some(side => Object.hasOwn(lock[side], 'usedMaterialAmount'))
|
||||||
? pair(
|
? pair(
|
||||||
'交付耗用原锁料费',
|
'交付耗用原锁料费',
|
||||||
Object.hasOwn(lock.before, 'usedMaterialAmount')
|
Object.hasOwn(lock.before, 'usedMaterialAmount')
|
||||||
@@ -592,7 +617,7 @@ export function lockViews(state, session) {
|
|||||||
: '未交付',
|
: '未交付',
|
||||||
)
|
)
|
||||||
: ''}
|
: ''}
|
||||||
{['before', 'after'].some(side => Object.hasOwn(lock[side], 'leftoverCost'))
|
{(['before', 'after'] as const).some(side => Object.hasOwn(lock[side], 'leftoverCost'))
|
||||||
? pair(
|
? pair(
|
||||||
'少重回池成本',
|
'少重回池成本',
|
||||||
Object.hasOwn(lock.before, 'leftoverCost') ? money(lock.before.leftoverCost) : '未交付',
|
Object.hasOwn(lock.before, 'leftoverCost') ? money(lock.before.leftoverCost) : '未交付',
|
||||||
@@ -610,14 +635,14 @@ export function lockViews(state, session) {
|
|||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
const accountDisplayName = value => {
|
const accountDisplayName = (value: string) => {
|
||||||
const id = Model.accountIdentity(state, value);
|
const id = Model.accountIdentity(state, value);
|
||||||
return id ? Model.memberName(state, id.member) + id.channel : value;
|
return id ? Model.memberName(state, id.member) + id.channel : value;
|
||||||
};
|
};
|
||||||
function pocketLabel(key) {
|
function pocketLabel(key: string) {
|
||||||
return state?.pocketCatalog?.find(row => row.key === key)?.name || String(key ?? '');
|
return state?.pocketCatalog?.find(row => row.key === key)?.name || String(key ?? '');
|
||||||
}
|
}
|
||||||
function renderPriceLockItems(lock) {
|
function renderPriceLockItems(lock: LockRecord) {
|
||||||
const rows = priceLockLines(lock);
|
const rows = priceLockLines(lock);
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -679,7 +704,7 @@ export function lockViews(state, session) {
|
|||||||
(delivery.extraMg ?? delivery.extra_mg) ? (
|
(delivery.extraMg ?? delivery.extra_mg) ? (
|
||||||
<>
|
<>
|
||||||
<br />
|
<br />
|
||||||
补重 {grams(delivery.extraMg ?? delivery.extra_mg)}g
|
补重 {grams(delivery.extraMg ?? delivery.extra_mg ?? 0)}g
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
''
|
''
|
||||||
@@ -689,7 +714,7 @@ export function lockViews(state, session) {
|
|||||||
<>
|
<>
|
||||||
<br />
|
<br />
|
||||||
{priceLockUsesPool(row) ? '解除预留回池 ' : '剩料留盘 '}
|
{priceLockUsesPool(row) ? '解除预留回池 ' : '剩料留盘 '}
|
||||||
{grams(delivery.leftoverMg ?? delivery.leftover_mg)}g
|
{grams(delivery.leftoverMg ?? delivery.leftover_mg ?? 0)}g
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
''
|
''
|
||||||
@@ -726,7 +751,7 @@ export function lockViews(state, session) {
|
|||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function renderPriceLockChangeSnapshot(snapshot, title) {
|
function renderPriceLockChangeSnapshot(snapshot: ChangeSnapshot | undefined, title: string) {
|
||||||
if (!snapshot)
|
if (!snapshot)
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -736,10 +761,8 @@ export function lockViews(state, session) {
|
|||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
const value = snapshot.lock || snapshot,
|
const value = 'lock' in snapshot ? snapshot.lock : snapshot;
|
||||||
rows = value.lines || [],
|
if (!isInputSnapshot(value))
|
||||||
inputRows = rows[0] && !rows[0].line;
|
|
||||||
if (!inputRows)
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className={'lock-change-snapshot'}>
|
<div className={'lock-change-snapshot'}>
|
||||||
@@ -763,6 +786,7 @@ export function lockViews(state, session) {
|
|||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
|
const rows = value.lines || [];
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className={'lock-change-snapshot'}>
|
<div className={'lock-change-snapshot'}>
|
||||||
@@ -834,7 +858,7 @@ export function lockViews(state, session) {
|
|||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function changeDetail(result, canReview) {
|
function changeDetail(result: LockChange, canReview: boolean) {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<button className={'dialog-close'} data-action={'price-lock-changes-close'} aria-label={'关闭'}>
|
<button className={'dialog-close'} data-action={'price-lock-changes-close'} aria-label={'关闭'}>
|
||||||
@@ -883,12 +907,12 @@ export function lockViews(state, session) {
|
|||||||
'data-id': result.price_lock_id,
|
'data-id': result.price_lock_id,
|
||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
{session.user.role === 'owner' && result.status === 'pending' ? (
|
{state.user.role === 'owner' && result.status === 'pending' ? (
|
||||||
<>
|
<>
|
||||||
<form id={'price-lock-review-form'}>
|
<form id={'price-lock-review-form'}>
|
||||||
<label>
|
<label>
|
||||||
复核备注
|
复核备注
|
||||||
<textarea name={'review_note'} maxLength={'240'} rows={'2'} placeholder={'驳回时必填'}></textarea>
|
<textarea name={'review_note'} maxLength={240} rows={2} placeholder={'驳回时必填'}></textarea>
|
||||||
</label>
|
</label>
|
||||||
{canReview ? (
|
{canReview ? (
|
||||||
<>
|
<>
|
||||||
@@ -923,7 +947,7 @@ export function lockViews(state, session) {
|
|||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function changeRows(result) {
|
function changeRows(result: { rows: ChangeListRow[] }) {
|
||||||
return result.rows.length ? (
|
return result.rows.length ? (
|
||||||
<>
|
<>
|
||||||
<div className={'table-wrap'}>
|
<div className={'table-wrap'}>
|
||||||
@@ -980,8 +1004,8 @@ export function lockViews(state, session) {
|
|||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function renderPriceLockPendingButtons(lock) {
|
function renderPriceLockPendingButtons(lock: LockRecord) {
|
||||||
return ['owner', 'assistant'].includes(session.user.role) ? (
|
return ['owner', 'assistant'].includes(state.user.role) ? (
|
||||||
<>
|
<>
|
||||||
{button('修改', 'edit-price-lock', 'quiet', {
|
{button('修改', 'edit-price-lock', 'quiet', {
|
||||||
'data-id': lock.id,
|
'data-id': lock.id,
|
||||||
@@ -994,13 +1018,13 @@ export function lockViews(state, session) {
|
|||||||
''
|
''
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
const button = (text, action, cls = '', props = {}) => (
|
const button = (text: string, action: string, cls = '', props: Record<string, string | boolean | null> = {}) => (
|
||||||
<button type="button" data-action={action} className={cls} {...props}>
|
<button type="button" data-action={action} className={cls} {...props}>
|
||||||
{text}
|
{text}
|
||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
const materialSourceSegmentsText = sources => describeMaterialSources(sources, teamMemberName);
|
const materialSourceSegmentsText = (sources: SourceDescription[]) => describeMaterialSources(sources, teamMemberName);
|
||||||
function priceLockMaterialAllocations(lock) {
|
function priceLockMaterialAllocations(lock: LockRecord) {
|
||||||
return priceLockMaterialPending(lock)
|
return priceLockMaterialPending(lock)
|
||||||
? []
|
? []
|
||||||
: priceLockUsesPool(lock)
|
: priceLockUsesPool(lock)
|
||||||
@@ -1008,27 +1032,27 @@ export function lockViews(state, session) {
|
|||||||
: [
|
: [
|
||||||
{
|
{
|
||||||
payer: lock.buy_payer,
|
payer: lock.buy_payer,
|
||||||
amount: lock.material_amount,
|
amount: Number(lock.material_amount),
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
const teamMemberName = key => Model.memberName(state, key, session);
|
const teamMemberName = (key: string) => Model.memberName(state, key, session);
|
||||||
const priceLockPayerName = payer => (payer ? teamMemberName(payer) : '待补');
|
const priceLockPayerName = (payer?: string) => (payer ? teamMemberName(payer) : '待补');
|
||||||
function priceLockAllocationText(allocations) {
|
function priceLockAllocationText(allocations: Allocation[]) {
|
||||||
return allocations.map(part => priceLockPayerName(part.payer) + ' ¥' + yuan(part.amount)).join(';');
|
return allocations.map(part => priceLockPayerName(part.payer) + ' ¥' + yuan(part.amount)).join(';');
|
||||||
}
|
}
|
||||||
function priceLockMaterialAmountText(lock) {
|
function priceLockMaterialAmountText(lock: LockRecord) {
|
||||||
const amount =
|
const amount =
|
||||||
priceLockUsesPool(lock) && Number.isSafeInteger(lock.materialPool?.amount)
|
priceLockUsesPool(lock) && Number.isSafeInteger(lock.materialPool?.amount)
|
||||||
? lock.materialPool.amount
|
? lock.materialPool?.amount
|
||||||
: lock.material_amount;
|
: lock.material_amount;
|
||||||
return priceLockMaterialPending(lock) || !Number.isSafeInteger(amount) ? '料费待补' : '¥' + yuan(amount);
|
return priceLockMaterialPending(lock) || !Number.isSafeInteger(amount) ? '料费待补' : '¥' + yuan(amount);
|
||||||
}
|
}
|
||||||
const priceLockMaterialPending = lock =>
|
const priceLockMaterialPending = (lock: LockRecord) =>
|
||||||
lock?.material_amount === null ||
|
lock?.material_amount === null ||
|
||||||
(priceLockUsesPool(lock) && (lock.materialPool?.status === 'pending' || lock.materialPool?.amount === null));
|
(priceLockUsesPool(lock) && (lock.materialPool?.status === 'pending' || lock.materialPool?.amount === null));
|
||||||
const priceLockUsesPool = lock => lock?.material_source === 'pool';
|
const priceLockUsesPool = (lock: LockRecord) => lock?.material_source === 'pool';
|
||||||
function renderPriceLockItemFacts(lock) {
|
function renderPriceLockItemFacts(lock: LockRecord) {
|
||||||
const pool = priceLockUsesPool(lock),
|
const pool = priceLockUsesPool(lock),
|
||||||
material = lock.materialPool,
|
material = lock.materialPool,
|
||||||
pendingMaterial = priceLockMaterialPending(lock);
|
pendingMaterial = priceLockMaterialPending(lock);
|
||||||
@@ -1077,13 +1101,13 @@ export function lockViews(state, session) {
|
|||||||
}
|
}
|
||||||
const yuan = Model.yuan;
|
const yuan = Model.yuan;
|
||||||
const grams = Model.grams;
|
const grams = Model.grams;
|
||||||
function priceLockLines(lock) {
|
function priceLockLines(lock: LockRecord): LockRecord[] {
|
||||||
if (!Array.isArray(lock?.lines) || !lock.lines.length) return lock ? [lock] : [];
|
if (!Array.isArray(lock?.lines) || !lock.lines.length) return lock ? [lock] : [];
|
||||||
return lock.lines.map((item, index) => {
|
return lock.lines.map((item, index) => {
|
||||||
const row = {
|
const row = {
|
||||||
...lock,
|
...lock,
|
||||||
...item,
|
...item,
|
||||||
id: item.id || item.lineId || item.price_lock_line_id,
|
id: item.id || item.lineId || item.price_lock_line_id || item.id,
|
||||||
line: item.line || item,
|
line: item.line || item,
|
||||||
line_index: index,
|
line_index: index,
|
||||||
parent_id: lock.id,
|
parent_id: lock.id,
|
||||||
@@ -1092,7 +1116,7 @@ export function lockViews(state, session) {
|
|||||||
return row;
|
return row;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
function listRecords(result, status) {
|
function listRecords(result: { rows: LockRecord[] }, status: string) {
|
||||||
return result.rows.length ? (
|
return result.rows.length ? (
|
||||||
<>
|
<>
|
||||||
<div className={'table-wrap'}>
|
<div className={'table-wrap'}>
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
import type { LedgerClient } from '../../lib/api';
|
||||||
|
import type { LedgerState, SessionInfo, LockCostEstimate } from '../../shared';
|
||||||
|
import type { Allocation, Impact } from '../MaterialPools/model';
|
||||||
|
import type { QuoteBalance, QuoteEntry, QuoteSource } from '../../lib/materialQuote';
|
||||||
|
import type { SavedPayment } from './formParts';
|
||||||
|
import type { lockViews } from './lockViews';
|
||||||
|
|
||||||
|
export interface LockProps {
|
||||||
|
client: LedgerClient;
|
||||||
|
state: LedgerState;
|
||||||
|
session: SessionInfo;
|
||||||
|
}
|
||||||
|
export type LockViews = ReturnType<typeof lockViews>;
|
||||||
|
export type SaveLock = (url: string, input: Record<string, unknown>) => Promise<void>;
|
||||||
|
export interface PreviewRow extends QuoteEntry {
|
||||||
|
amount: number | null;
|
||||||
|
allocations: Allocation[];
|
||||||
|
materialSources?: QuoteSource[];
|
||||||
|
balance?: QuoteBalance;
|
||||||
|
averageRate?: number | null;
|
||||||
|
revision?: number | string;
|
||||||
|
remainingMg: number;
|
||||||
|
covered: boolean;
|
||||||
|
shortageMg: number;
|
||||||
|
totalMg?: number;
|
||||||
|
usedMg?: number;
|
||||||
|
wantedMg?: number;
|
||||||
|
}
|
||||||
|
export interface LockedSource extends QuoteSource {
|
||||||
|
amount: number;
|
||||||
|
basisAmount: number;
|
||||||
|
basisMg: number;
|
||||||
|
prefixMg: number;
|
||||||
|
prefixAmount: number;
|
||||||
|
batches?: { mg: number; purchaseId?: string; recoveryId?: string }[];
|
||||||
|
}
|
||||||
|
export interface ReservedMaterial {
|
||||||
|
date: string;
|
||||||
|
status: string;
|
||||||
|
quantity: number;
|
||||||
|
amount: number | null;
|
||||||
|
averageRate: number | null;
|
||||||
|
frozen?: boolean;
|
||||||
|
basisAmount: number;
|
||||||
|
basisMg: number;
|
||||||
|
prefixMg: number;
|
||||||
|
prefixAmount: number;
|
||||||
|
allocations: Allocation[];
|
||||||
|
materialSources?: LockedSource[];
|
||||||
|
}
|
||||||
|
export interface DeliveryCost extends LockCostEstimate {
|
||||||
|
allocations?: Allocation[];
|
||||||
|
materialSources?: LockedSource[];
|
||||||
|
leftoverMaterialSources?: LockedSource[];
|
||||||
|
extraPool?: PreviewRow;
|
||||||
|
}
|
||||||
|
interface DeliveryRecord {
|
||||||
|
finalMg?: number;
|
||||||
|
quantity?: number;
|
||||||
|
extraMg?: number;
|
||||||
|
extra_mg?: number;
|
||||||
|
leftoverMg?: number;
|
||||||
|
leftover_mg?: number;
|
||||||
|
inventory?: { pocket: string };
|
||||||
|
pocket?: string;
|
||||||
|
}
|
||||||
|
interface StoredLine {
|
||||||
|
name: string;
|
||||||
|
code: string;
|
||||||
|
unit: string;
|
||||||
|
pocket: string;
|
||||||
|
laborMode: string;
|
||||||
|
pieces: number;
|
||||||
|
laborRate: number;
|
||||||
|
sale: number;
|
||||||
|
baseSale?: number;
|
||||||
|
charges: { name: string; amount: number }[];
|
||||||
|
}
|
||||||
|
export interface LockItem {
|
||||||
|
id: string;
|
||||||
|
lineId?: string;
|
||||||
|
price_lock_line_id?: string;
|
||||||
|
line: StoredLine;
|
||||||
|
locked_mg: number;
|
||||||
|
sell_rate: number;
|
||||||
|
buy_rate: number | null;
|
||||||
|
buy_payer: string;
|
||||||
|
material_amount: number | null;
|
||||||
|
material_source: string;
|
||||||
|
material_pool_id?: string;
|
||||||
|
materialPool?: ReservedMaterial;
|
||||||
|
delivery?: DeliveryRecord | null;
|
||||||
|
}
|
||||||
|
export interface LockRecord extends LockItem {
|
||||||
|
date: string;
|
||||||
|
status: string;
|
||||||
|
number: string;
|
||||||
|
customer: string;
|
||||||
|
salesperson: string;
|
||||||
|
note: string;
|
||||||
|
discount: number;
|
||||||
|
member?: string;
|
||||||
|
revision: number;
|
||||||
|
netReceived: number;
|
||||||
|
estimated_total: number;
|
||||||
|
final_order_id: string | null;
|
||||||
|
cancelled_reason?: string;
|
||||||
|
cancelled_at?: string;
|
||||||
|
credit_card_fee_total?: number;
|
||||||
|
cash_events?: { kind: string; account: string }[];
|
||||||
|
credit_card_fees?: { amount: number; payer: string; date: string; note?: string }[];
|
||||||
|
cancellationReturns?: { line_index: number; date: string; mg: number; amount: number; origin_pool_id: string }[];
|
||||||
|
lines?: LockItem[];
|
||||||
|
}
|
||||||
|
export interface ManualMaterial {
|
||||||
|
rate?: string;
|
||||||
|
payer?: string;
|
||||||
|
verified?: boolean;
|
||||||
|
}
|
||||||
|
export interface InputMaterial extends ManualMaterial {
|
||||||
|
poolId?: string;
|
||||||
|
source?: string;
|
||||||
|
manual?: ManualMaterial;
|
||||||
|
revision?: string | number;
|
||||||
|
}
|
||||||
|
export interface InputLine {
|
||||||
|
name?: string;
|
||||||
|
code?: string;
|
||||||
|
lineId?: string;
|
||||||
|
quantity?: string;
|
||||||
|
goldPrice?: string;
|
||||||
|
laborRate?: string;
|
||||||
|
laborMode?: string;
|
||||||
|
pieces?: number | string;
|
||||||
|
charges?: { name?: string; amount?: string }[];
|
||||||
|
material?: InputMaterial;
|
||||||
|
}
|
||||||
|
export interface LockCreateDraft {
|
||||||
|
member?: string;
|
||||||
|
date?: string;
|
||||||
|
customer?: string;
|
||||||
|
salesperson?: string;
|
||||||
|
note?: string;
|
||||||
|
discount?: string;
|
||||||
|
payment?: SavedPayment;
|
||||||
|
lines?: InputLine[];
|
||||||
|
line?: InputLine;
|
||||||
|
material?: InputMaterial;
|
||||||
|
}
|
||||||
|
export interface LockEdit {
|
||||||
|
lock: Pick<LockRecord, 'id' | 'date' | 'number' | 'status'> & { customer?: string };
|
||||||
|
revision: number;
|
||||||
|
eligible: boolean;
|
||||||
|
requiresApproval: boolean;
|
||||||
|
reason?: string;
|
||||||
|
inputs: LockCreateDraft & { date: string };
|
||||||
|
}
|
||||||
|
export interface ChangeListRow {
|
||||||
|
id: string;
|
||||||
|
requestId?: string;
|
||||||
|
requester_name: string;
|
||||||
|
requester?: string;
|
||||||
|
created: string;
|
||||||
|
action: 'edit' | 'cancel';
|
||||||
|
status: 'pending' | 'approved' | 'rejected';
|
||||||
|
reason: string;
|
||||||
|
number?: string;
|
||||||
|
customer?: string;
|
||||||
|
before?: { number?: string; customer?: string };
|
||||||
|
}
|
||||||
|
export type ChangeSnapshot = LockRecord | LockCreateDraft | { lock: LockRecord };
|
||||||
|
export interface LockChange extends ChangeListRow {
|
||||||
|
before: LockRecord;
|
||||||
|
after?: ChangeSnapshot;
|
||||||
|
price_lock_id: string;
|
||||||
|
price_lock_revision: number;
|
||||||
|
revision: number;
|
||||||
|
stale: boolean;
|
||||||
|
note?: string;
|
||||||
|
changes: { field: string; before: unknown; after: unknown }[];
|
||||||
|
relatedOrders?: Impact['relatedOrders'];
|
||||||
|
relatedPriceLocks?: Impact['relatedPriceLocks'];
|
||||||
|
}
|
||||||
+48
-14
@@ -1,12 +1,18 @@
|
|||||||
|
import type { LedgerState } from '../../shared';
|
||||||
|
import type { LedgerClient } from '../../lib/api';
|
||||||
|
import type { QuoteEntry, QuoteRequest, validateMaterialQuote } from '../../lib/materialQuote';
|
||||||
|
import type { Allocation, Pool, PoolResult } from '../MaterialPools/model';
|
||||||
|
import type { LockViews, PreviewRow } from './types';
|
||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
import { Calc, Model } from '../../shared';
|
import { Calc, Model } from '../../shared';
|
||||||
import { validatePools, poolRows } from '../MaterialPools/model';
|
import { validatePools, poolRows } from '../MaterialPools/model';
|
||||||
import { safeEstimate } from './formParts';
|
import { safeEstimate } from './formParts';
|
||||||
|
|
||||||
// 公共料池以采购付款顺序分摊。先扣已用与本单前序行,余款才归本行。
|
// 公共料池以采购付款顺序分摊。先扣已用与本单前序行,余款才归本行。
|
||||||
function publicQuote(pool, entries, all, state) {
|
function publicQuote(pool: Pool | undefined, entries: QuoteEntry[], all: Pool[], state: LedgerState): PreviewRow[] {
|
||||||
if (!pool || !pool.totalMg) throw new Error('当日尚无可用材料。请先登记购料,再保存锁价。');
|
if (!pool || !pool.totalMg) throw new Error('当日尚无可用材料。请先登记购料,再保存锁价。');
|
||||||
if (pool.totalAmount == null) throw new Error('料池成本尚未补齐,请先核对材料记录,再保存锁价。');
|
if (pool.totalAmount == null) throw new Error('料池成本尚未补齐,请先核对材料记录,再保存锁价。');
|
||||||
|
const totalAmount = pool.totalAmount;
|
||||||
const preview = Calc.poolMaterialPreview(pool, entries, { allUsages: all.flatMap(r => r.usages || []) });
|
const preview = Calc.poolMaterialPreview(pool, entries, { allUsages: all.flatMap(r => r.usages || []) });
|
||||||
let used = preview.usedMg;
|
let used = preview.usedMg;
|
||||||
const available = Math.max(0, pool.totalMg - used),
|
const available = Math.max(0, pool.totalMg - used),
|
||||||
@@ -14,15 +20,20 @@ function publicQuote(pool, entries, all, state) {
|
|||||||
const funds = pool.purchases.flatMap(p => p.allocations || [{ payer: p.payer, amount: p.amount }]);
|
const funds = pool.purchases.flatMap(p => p.allocations || [{ payer: p.payer, amount: p.amount }]);
|
||||||
return entries.map(r => {
|
return entries.map(r => {
|
||||||
const amount = preview.amounts[r.lineIndex],
|
const amount = preview.amounts[r.lineIndex],
|
||||||
allocations = [],
|
allocations: Allocation[] = [],
|
||||||
covered = preview.covered && !shortageMg && amount != null;
|
covered = preview.covered && !shortageMg && amount != null;
|
||||||
let skip = Calc.poolMaterialAmount(pool.totalAmount, pool.totalMg, used),
|
let skip = Calc.poolMaterialAmount(totalAmount, pool.totalMg, used),
|
||||||
left = amount,
|
left = amount ?? 0,
|
||||||
zero = '';
|
zero = '';
|
||||||
used += r.mg;
|
used += r.mg;
|
||||||
if (covered) {
|
if (covered) {
|
||||||
for (const part of funds) {
|
for (const part of funds) {
|
||||||
if (!Model.memberKeys(state).includes(part.payer) || !Number.isSafeInteger(part.amount) || part.amount <= 0)
|
if (
|
||||||
|
!part.payer ||
|
||||||
|
!Model.memberKeys(state).includes(part.payer) ||
|
||||||
|
!Number.isSafeInteger(part.amount) ||
|
||||||
|
part.amount <= 0
|
||||||
|
)
|
||||||
throw new Error('料池付款来源未完整读到,请刷新料池。');
|
throw new Error('料池付款来源未完整读到,请刷新料池。');
|
||||||
if (skip >= part.amount) {
|
if (skip >= part.amount) {
|
||||||
skip -= part.amount;
|
skip -= part.amount;
|
||||||
@@ -47,7 +58,7 @@ function publicQuote(pool, entries, all, state) {
|
|||||||
amount: covered ? amount : null,
|
amount: covered ? amount : null,
|
||||||
allocations,
|
allocations,
|
||||||
revision: pool.revision,
|
revision: pool.revision,
|
||||||
covered,
|
covered: !!covered,
|
||||||
shortageMg,
|
shortageMg,
|
||||||
averageRate: pool.averageRate,
|
averageRate: pool.averageRate,
|
||||||
remainingMg: available,
|
remainingMg: available,
|
||||||
@@ -57,15 +68,38 @@ function publicQuote(pool, entries, all, state) {
|
|||||||
};
|
};
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
export function useLockPool({ client, state, views, date, member, entries, editId = '', delivery = false }) {
|
interface PoolParams {
|
||||||
|
client: LedgerClient;
|
||||||
|
state: LedgerState;
|
||||||
|
views: LockViews;
|
||||||
|
date: string;
|
||||||
|
member: string;
|
||||||
|
entries: QuoteEntry[];
|
||||||
|
editId?: string;
|
||||||
|
delivery?: boolean;
|
||||||
|
}
|
||||||
|
type PoolResponse = { seq: number } & ({ data: PoolResult; error?: undefined } | { data?: undefined; error: string });
|
||||||
|
type RemoteQuote = { seq: number; key: string } & (
|
||||||
|
{ value: ReturnType<typeof validateMaterialQuote>; error?: undefined } | { value?: undefined; error: string }
|
||||||
|
);
|
||||||
|
export function useLockPool({
|
||||||
|
client,
|
||||||
|
state,
|
||||||
|
views,
|
||||||
|
date,
|
||||||
|
member,
|
||||||
|
entries,
|
||||||
|
editId = '',
|
||||||
|
delivery = false,
|
||||||
|
}: PoolParams) {
|
||||||
const [seq, setSeq] = useState(0),
|
const [seq, setSeq] = useState(0),
|
||||||
[loaded, setLoaded] = useState(null),
|
[loaded, setLoaded] = useState<PoolResponse | null>(null),
|
||||||
[remote, setRemote] = useState(null);
|
[remote, setRemote] = useState<RemoteQuote | null>(null);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (delivery) return;
|
if (delivery) return;
|
||||||
let active = true;
|
let active = true;
|
||||||
client
|
client
|
||||||
.api('/api/material-pools')
|
.api<PoolResult>('/api/material-pools')
|
||||||
.then(validatePools)
|
.then(validatePools)
|
||||||
.then(data => {
|
.then(data => {
|
||||||
if (active) setLoaded({ seq, data });
|
if (active) setLoaded({ seq, data });
|
||||||
@@ -86,7 +120,7 @@ export function useLockPool({ client, state, views, date, member, entries, editI
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!shouldQuote) return;
|
if (!shouldQuote) return;
|
||||||
let active = true;
|
let active = true;
|
||||||
const request = JSON.parse(key);
|
const request: QuoteRequest = JSON.parse(key);
|
||||||
client
|
client
|
||||||
.api('/api/material-pools/quote', request)
|
.api('/api/material-pools/quote', request)
|
||||||
.then(r => views.validateMaterialQuote(r, request))
|
.then(r => views.validateMaterialQuote(r, request))
|
||||||
@@ -100,14 +134,14 @@ export function useLockPool({ client, state, views, date, member, entries, editI
|
|||||||
active = false;
|
active = false;
|
||||||
};
|
};
|
||||||
}, [client, key, seq, shouldQuote, views]);
|
}, [client, key, seq, shouldQuote, views]);
|
||||||
let rows = [],
|
let rows: PreviewRow[] = [],
|
||||||
error = (!delivery && loaded?.seq === seq && loaded.error) || '';
|
error = (!delivery && loaded?.seq === seq && loaded.error) || '';
|
||||||
if (entries.length && !error) {
|
if (entries.length && !error) {
|
||||||
if (!delivery && !data) error = '正在读取每日料池,请稍候。';
|
if (!delivery && !data) error = '正在读取每日料池,请稍候。';
|
||||||
else if (!delivery && !data.rolling?.enabled) error = '请先启用统一料池,再选择当日加权料价。';
|
else if (!delivery && !data?.rolling?.enabled) error = '请先启用统一料池,再选择当日加权料价。';
|
||||||
else if (shouldQuote) {
|
else if (shouldQuote) {
|
||||||
if (remote?.key !== key || remote?.seq !== seq) error = '正在按订单归属核对个人回收料与公共补足,请稍候。';
|
if (remote?.key !== key || remote?.seq !== seq) error = '正在按订单归属核对个人回收料与公共补足,请稍候。';
|
||||||
else if (remote.error) error = remote.error;
|
else if (remote.value === undefined) error = remote.error;
|
||||||
else {
|
else {
|
||||||
const balance = remote.value.pools.find(p => p.poolId === date),
|
const balance = remote.value.pools.find(p => p.poolId === date),
|
||||||
available = balance?.before?.eligibleRemainingMg ?? 0,
|
available = balance?.before?.eligibleRemainingMg ?? 0,
|
||||||
+31
-25
@@ -1,33 +1,37 @@
|
|||||||
|
import type { LedgerState } from '../../shared';
|
||||||
|
import type { ChangeRequest, Input, Exchange, Labor, Material, MoneySummary } from './types';
|
||||||
|
type Cell = string | number | null | undefined;
|
||||||
import { Model } from '../../shared';
|
import { Model } from '../../shared';
|
||||||
import { yuan } from '../../lib/format';
|
import { yuan } from '../../lib/format';
|
||||||
import { count as stockCountText } from '../Inventory/data';
|
import { count as stockCountText } from '../Inventory/data';
|
||||||
import { rowLabel } from './controls';
|
import { rowLabel } from './controls';
|
||||||
export function Comparison({ request, state }) {
|
export function Comparison({ request, state }: { request: ChangeRequest; state: LedgerState }) {
|
||||||
const before = request.before,
|
const before = request.before,
|
||||||
after = request.after,
|
after = request.after,
|
||||||
rows = [],
|
rows: [string, Cell, Cell][] = [],
|
||||||
pair = (title, a, b) => [title, a, b];
|
pair = (title: string, a: Cell, b: Cell): [string, Cell, Cell] => [title, a, b];
|
||||||
const teamMemberName = k => Model.memberName(state, k),
|
const teamMemberName = (k?: string) => Model.memberName(state, k ?? ''),
|
||||||
pocketLabel = k => rowLabel(state, k),
|
pocketLabel = (k?: string) => rowLabel(state, k),
|
||||||
accountDisplayName = v =>
|
accountDisplayName = (v: string) =>
|
||||||
String(v || '')
|
String(v || '')
|
||||||
.replace(/^助理2/, Model.memberName(state, 'assistant2'))
|
.replace(/^助理2/, Model.memberName(state, 'assistant2'))
|
||||||
.replace(/^助理1?/, Model.memberName(state, 'assistant'))
|
.replace(/^助理1?/, Model.memberName(state, 'assistant'))
|
||||||
.replace(/^麦麦/, Model.memberName(state, 'owner'));
|
.replace(/^麦麦/, Model.memberName(state, 'owner'));
|
||||||
const old = input =>
|
const old = (input: Input) =>
|
||||||
input?.old_lines
|
input?.old_lines
|
||||||
.map(row => `${row.name}:来料 ${row.incoming_weight}g,熔后 ${row.melted_weight}g,成色 ${row.purity}%`)
|
.map(row => `${row.name}:来料 ${row.incoming_weight}g,熔后 ${row.melted_weight}g,成色 ${row.purity}%`)
|
||||||
.join('\n'),
|
.join('\n'),
|
||||||
fees = input =>
|
fees = (input: Input) =>
|
||||||
input?.exchange?.fee_items
|
input?.exchange?.fee_items
|
||||||
.map(row => `${row.note}:${row.amount}元 · ${teamMemberName(row.payer)}付款`)
|
.map(row => `${row.note}:${row.amount}元 · ${teamMemberName(row.payer)}付款`)
|
||||||
.join('\n') || '无',
|
.join('\n') || '无',
|
||||||
charges = input => input?.exchange?.charges.map(row => `${row.name}:${row.amount}元`).join('\n') || '无';
|
charges = (input: Input) => input?.exchange?.charges.map(row => `${row.name}:${row.amount}元`).join('\n') || '无';
|
||||||
const x = before.exchange || {},
|
const x: Partial<Exchange> = before.exchange || {},
|
||||||
y = after?.exchange || {},
|
y: Partial<Exchange> = after?.exchange || {},
|
||||||
material = value =>
|
material = (value?: Material) =>
|
||||||
value?.mode === 'pool' ? '料池 ' + value.poolId : value ? '手填 ' + value.rate + '元/克' : '无补金差重',
|
value?.mode === 'pool' ? '料池 ' + value.poolId : value ? '手填 ' + value.rate + '元/克' : '无补金差重',
|
||||||
labor = value => (value ? (value.mode === 'gram' ? value.rate + '元/克' : value.amount + '元总工费') : '未提供');
|
labor = (value?: Labor) =>
|
||||||
|
value ? (value.mode === 'gram' ? value.rate + '元/克' : value.amount + '元总工费') : '未提供';
|
||||||
rows.push(
|
rows.push(
|
||||||
pair('业务日期', before.date, after?.date || '取消原记录'),
|
pair('业务日期', before.date, after?.date || '取消原记录'),
|
||||||
pair('客户', before.customer, after?.customer),
|
pair('客户', before.customer, after?.customer),
|
||||||
@@ -75,7 +79,7 @@ export function Comparison({ request, state }) {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
if (before.exchange?.items || after?.exchange?.items) {
|
if (before.exchange?.items || after?.exchange?.items) {
|
||||||
const items = v =>
|
const items = (v: Input) =>
|
||||||
(v?.exchange?.items || [])
|
(v?.exchange?.items || [])
|
||||||
.map(
|
.map(
|
||||||
(p, i) =>
|
(p, i) =>
|
||||||
@@ -116,7 +120,7 @@ export function Comparison({ request, state }) {
|
|||||||
rows.push(pair('逐件置换完整资料', items(before), after ? items(after) : '全部冲回'));
|
rows.push(pair('逐件置换完整资料', items(before), after ? items(after) : '全部冲回'));
|
||||||
}
|
}
|
||||||
if (before.exchange?.products || after?.exchange?.products) {
|
if (before.exchange?.products || after?.exchange?.products) {
|
||||||
const items = x =>
|
const items = (x?: Exchange) =>
|
||||||
(x?.products ?? (x ? [x] : []))
|
(x?.products ?? (x ? [x] : []))
|
||||||
.map(
|
.map(
|
||||||
(p, i) =>
|
(p, i) =>
|
||||||
@@ -178,17 +182,19 @@ export function Comparison({ request, state }) {
|
|||||||
pair('工费付款人', teamMemberName(x.cost_labor_payer), after ? teamMemberName(y.cost_labor_payer) : '原来源留档'),
|
pair('工费付款人', teamMemberName(x.cost_labor_payer), after ? teamMemberName(y.cost_labor_payer) : '原来源留档'),
|
||||||
pair('实际费用', fees(before), after ? fees(after) : '冲正原费用'),
|
pair('实际费用', fees(before), after ? fees(after) : '冲正原费用'),
|
||||||
);
|
);
|
||||||
const a = request.summary.before || {},
|
const a: MoneySummary = request.summary.before || {},
|
||||||
b = request.summary.after || {};
|
b: MoneySummary = request.summary.after || {};
|
||||||
rows.push(
|
rows.push(
|
||||||
...[
|
...(
|
||||||
['实际收客户', 'cashReceipt'],
|
[
|
||||||
['实际付客户', 'cashPayment'],
|
['实际收客户', 'cashReceipt'],
|
||||||
['购料成本', 'purchaseAmount'],
|
['实际付客户', 'cashPayment'],
|
||||||
['订单货品成本', 'goodsCost'],
|
['购料成本', 'purchaseAmount'],
|
||||||
['实际费用', 'directCost'],
|
['订单货品成本', 'goodsCost'],
|
||||||
['原账利润', 'profit'],
|
['实际费用', 'directCost'],
|
||||||
].map(([title, key]) =>
|
['原账利润', 'profit'],
|
||||||
|
] as const
|
||||||
|
).map(([title, key]) =>
|
||||||
pair(
|
pair(
|
||||||
title,
|
title,
|
||||||
a[key] == null ? '待核实' : '¥' + yuan(a[key]),
|
a[key] == null ? '待核实' : '¥' + yuan(a[key]),
|
||||||
+29
-10
@@ -1,7 +1,9 @@
|
|||||||
|
import type { FormEvent } from 'react';
|
||||||
|
import type { PageProps, RecoveryModel, DepositListData } from './types';
|
||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { grams } from '../../lib/format';
|
import { grams } from '../../lib/format';
|
||||||
import { loadDraft } from './controls';
|
import { loadDraft } from './controls';
|
||||||
export function validateDeposits(r) {
|
export function validateDeposits(r: DepositListData) {
|
||||||
if (
|
if (
|
||||||
!Array.isArray(r.rows) ||
|
!Array.isArray(r.rows) ||
|
||||||
!Number.isSafeInteger(r.remainingMg) ||
|
!Number.isSafeInteger(r.remainingMg) ||
|
||||||
@@ -9,7 +11,17 @@ export function validateDeposits(r) {
|
|||||||
)
|
)
|
||||||
throw new Error('寄存资料未完整返回');
|
throw new Error('寄存资料未完整返回');
|
||||||
}
|
}
|
||||||
export function DepositList({ data, error, start, refresh }) {
|
export function DepositList({
|
||||||
|
data,
|
||||||
|
error,
|
||||||
|
start,
|
||||||
|
refresh,
|
||||||
|
}: {
|
||||||
|
data?: DepositListData;
|
||||||
|
error?: string;
|
||||||
|
start(): void;
|
||||||
|
refresh(): void;
|
||||||
|
}) {
|
||||||
return (
|
return (
|
||||||
<section className="panel" id="customer-material-panel">
|
<section className="panel" id="customer-material-panel">
|
||||||
<div className="panel-title">
|
<div className="panel-title">
|
||||||
@@ -91,29 +103,36 @@ export function DepositList({ data, error, start, refresh }) {
|
|||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
export function DepositForm({ client, state, model, saved }) {
|
export function DepositForm({ client, state, model, saved }: PageProps & { model: RecoveryModel; saved(): void }) {
|
||||||
const key = 'mm-customer-material-' + state.user.id,
|
const key = 'mm-customer-material-' + state.user.id,
|
||||||
[draft, setDraft] = useState(() => loadDraft(key) || {}),
|
[draft, setDraft] = useState(
|
||||||
|
() => loadDraft<Partial<Record<'date' | 'grams' | 'memo' | 'verified', string>>>(key) || {},
|
||||||
|
),
|
||||||
[error, setError] = useState('');
|
[error, setError] = useState('');
|
||||||
const change = e => {
|
const change = (e: FormEvent<HTMLFormElement>) => {
|
||||||
const form = e.currentTarget,
|
const form = e.currentTarget,
|
||||||
next = Object.fromEntries(new FormData(form));
|
next = Object.fromEntries(Array.from(new FormData(form), ([key, value]) => [key, String(value)]));
|
||||||
setDraft(next);
|
setDraft(next);
|
||||||
localStorage.setItem(key, JSON.stringify(next));
|
localStorage.setItem(key, JSON.stringify(next));
|
||||||
};
|
};
|
||||||
async function submit(e) {
|
async function submit(e: FormEvent<HTMLFormElement>) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
const f = new FormData(e.currentTarget),
|
const f = new FormData(e.currentTarget),
|
||||||
input = { date: f.get('date'), grams: f.get('grams'), memo: f.get('memo').trim(), verified: f.has('verified') };
|
input = {
|
||||||
|
date: f.get('date'),
|
||||||
|
grams: f.get('grams'),
|
||||||
|
memo: String(f.get('memo') ?? '').trim(),
|
||||||
|
verified: f.has('verified'),
|
||||||
|
};
|
||||||
try {
|
try {
|
||||||
model.units(input.grams, 3, '寄存克重', { zero: false });
|
model.units(input.grams, 3, '寄存克重', { zero: false });
|
||||||
if (!input.memo) throw new Error('请填写备忘');
|
if (!input.memo) throw new Error('请填写备忘');
|
||||||
const result = await client.mutate('/api/customer-materials', input);
|
const result = await client.mutate<{ id: string }>('/api/customer-materials', input);
|
||||||
if (!result.id) throw new Error('寄存保存结果未完整返回,请核对后再操作');
|
if (!result.id) throw new Error('寄存保存结果未完整返回,请核对后再操作');
|
||||||
localStorage.removeItem(key);
|
localStorage.removeItem(key);
|
||||||
saved();
|
saved();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err.message);
|
setError((err as Error).message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return (
|
return (
|
||||||
+46
-6
@@ -1,3 +1,30 @@
|
|||||||
|
import type { InputHTMLAttributes, ReactNode, SelectHTMLAttributes } from 'react';
|
||||||
|
import type {
|
||||||
|
EditDetail,
|
||||||
|
Draft,
|
||||||
|
Derived,
|
||||||
|
TextField,
|
||||||
|
PageProps,
|
||||||
|
Deposit,
|
||||||
|
QuoteItem,
|
||||||
|
MaterialPool,
|
||||||
|
ExtraFields,
|
||||||
|
ExtraKinds,
|
||||||
|
PoolChoice,
|
||||||
|
} from './types';
|
||||||
|
import type { Choice } from './controls';
|
||||||
|
interface Fields {
|
||||||
|
text(title: string, key: TextField, limit: number, props?: InputHTMLAttributes<HTMLInputElement>): ReactNode;
|
||||||
|
num(title: string, key: TextField, places?: number, props?: InputHTMLAttributes<HTMLInputElement>): ReactNode;
|
||||||
|
select(
|
||||||
|
title: string,
|
||||||
|
key: TextField,
|
||||||
|
choices: readonly Choice[],
|
||||||
|
props?: SelectHTMLAttributes<HTMLSelectElement>,
|
||||||
|
): ReactNode;
|
||||||
|
rateField(title: string, key: TextField, use?: boolean, props?: InputHTMLAttributes<HTMLInputElement>): ReactNode;
|
||||||
|
pairs(title: string, key: TextField, pocket: string, visible?: boolean, optional?: boolean): ReactNode;
|
||||||
|
}
|
||||||
import { Model } from '../../shared';
|
import { Model } from '../../shared';
|
||||||
import { grams } from '../../lib/format';
|
import { grams } from '../../lib/format';
|
||||||
import { pocketOptions, Settlement, money } from './controls';
|
import { pocketOptions, Settlement, money } from './controls';
|
||||||
@@ -17,6 +44,19 @@ export function IndependentItems({
|
|||||||
remove,
|
remove,
|
||||||
setField,
|
setField,
|
||||||
extras,
|
extras,
|
||||||
|
}: {
|
||||||
|
parts: Derived[];
|
||||||
|
quotedItems?: QuoteItem[];
|
||||||
|
draft: Draft;
|
||||||
|
edit: EditDetail;
|
||||||
|
state: PageProps['state'];
|
||||||
|
materials: Deposit[];
|
||||||
|
pools: MaterialPool[];
|
||||||
|
fields(row?: Draft, index?: number): Fields;
|
||||||
|
add(): void;
|
||||||
|
remove(index: number): void;
|
||||||
|
setField<K extends keyof Draft>(key: K, value: Draft[K], index?: number): void;
|
||||||
|
extras<K extends keyof ExtraKinds>(kind: K, rows: ExtraKinds[K][], keys: ExtraFields<K>, caption: string): ReactNode;
|
||||||
}) {
|
}) {
|
||||||
const common = fields(),
|
const common = fields(),
|
||||||
members = Model.memberOptions(state);
|
members = Model.memberOptions(state);
|
||||||
@@ -28,12 +68,12 @@ export function IndependentItems({
|
|||||||
{parts.map(({ draft: row, old, hasBuy, diff, q, input, error }, i) => {
|
{parts.map(({ draft: row, old, hasBuy, diff, q, input, error }, i) => {
|
||||||
const index = i - 1,
|
const index = i - 1,
|
||||||
f = fields(row, index),
|
f = fields(row, index),
|
||||||
original = edit.inputs.exchange.items[i],
|
original = edit.inputs.exchange!.items![i],
|
||||||
item = quotedItems?.[i],
|
item = quotedItems?.[i],
|
||||||
deposit = row.old_source === 'deposit',
|
deposit = row.old_source === 'deposit',
|
||||||
saveSurplus = row.surplus_mode === 'deposit',
|
saveSurplus = row.surplus_mode === 'deposit',
|
||||||
today = draft.date;
|
today = draft.date;
|
||||||
const poolList = pools.filter(
|
const poolList: (Pick<PoolChoice, 'id' | 'date'> & Partial<PoolChoice>)[] = pools.filter(
|
||||||
p =>
|
p =>
|
||||||
p.date <= today &&
|
p.date <= today &&
|
||||||
(p.id === row.material_pool_id ||
|
(p.id === row.material_pool_id ||
|
||||||
@@ -196,10 +236,10 @@ export function IndependentItems({
|
|||||||
? '个人余 ' +
|
? '个人余 ' +
|
||||||
grams(p.personalPools[draft.member]?.remainingMg || 0) +
|
grams(p.personalPools[draft.member]?.remainingMg || 0) +
|
||||||
'g/公共余 ' +
|
'g/公共余 ' +
|
||||||
grams(p.remainingMg) +
|
grams(p.remainingMg ?? 0) +
|
||||||
'g'
|
'g'
|
||||||
: p.totalMg
|
: p.totalMg
|
||||||
? '余 ' + grams(p.remainingMg) + 'g'
|
? '余 ' + grams(p.remainingMg ?? 0) + 'g'
|
||||||
: '待补采购'),
|
: '待补采购'),
|
||||||
]),
|
]),
|
||||||
{ disabled: !diff || row.material_source !== 'pool' },
|
{ disabled: !diff || row.material_source !== 'pool' },
|
||||||
@@ -231,9 +271,9 @@ export function IndependentItems({
|
|||||||
money(item.materialCost) +
|
money(item.materialCost) +
|
||||||
';进货工费 ' +
|
';进货工费 ' +
|
||||||
money(item.laborCost) +
|
money(item.laborCost) +
|
||||||
(item.exchange.costMaterial.materialSources
|
(item.exchange!.costMaterial!.materialSources
|
||||||
? ';' +
|
? ';' +
|
||||||
describeMaterialSources(item.exchange.costMaterial.materialSources, key =>
|
describeMaterialSources(item.exchange!.costMaterial!.materialSources, (key: string) =>
|
||||||
Model.memberName(state, key),
|
Model.memberName(state, key),
|
||||||
)
|
)
|
||||||
: '')}
|
: '')}
|
||||||
+138
-57
@@ -1,23 +1,38 @@
|
|||||||
import { useCallback, useEffect, useState } from 'react';
|
import type { FormEvent } from 'react';
|
||||||
|
import type { usePrintStatuses } from '../../lib/printStatus';
|
||||||
|
import type { ApiError } from '../../lib/api';
|
||||||
|
import type {
|
||||||
|
PageProps,
|
||||||
|
Filters,
|
||||||
|
SummaryRow,
|
||||||
|
EditDetail,
|
||||||
|
RecoveryModel,
|
||||||
|
ChangeRequest,
|
||||||
|
Selection,
|
||||||
|
ChangeList,
|
||||||
|
Saved,
|
||||||
|
} from './types';
|
||||||
|
type PrintStatuses = ReturnType<typeof usePrintStatuses>;
|
||||||
|
import { useCallback, useState } from 'react';
|
||||||
import { Model } from '../../shared';
|
import { Model } from '../../shared';
|
||||||
import { grams } from '../../lib/format';
|
import { grams } from '../../lib/format';
|
||||||
import { useRead, dateValid, count } from '../Inventory/data';
|
import { useRead, dateValid, count } from '../Inventory/data';
|
||||||
import { LegacyCount, Modal, Settlement, money, options, rowLabel } from './controls';
|
import { LegacyCount, Modal, Settlement, money, options, rowLabel } from './controls';
|
||||||
import { Comparison } from './Comparison';
|
import { Comparison } from './Comparison';
|
||||||
const modes = { direct: '直接回收', exchange: '置换' };
|
const modes = { direct: '直接回收', exchange: '置换' };
|
||||||
const status = r =>
|
const status = (r: ChangeRequest) =>
|
||||||
({ pending: '待店主复核', approved: r.action === 'cancel' ? '已同意取消' : '已同意修改', rejected: '已驳回' })[
|
({ pending: '待店主复核', approved: r.action === 'cancel' ? '已同意取消' : '已同意修改', rejected: '已驳回' })[
|
||||||
r.status
|
r.status
|
||||||
] || '状态待核对';
|
] || '状态待核对';
|
||||||
const print = id => window.open('/print/recoveries/' + encodeURIComponent(id), '_blank', 'noopener');
|
const print = (id: string) => window.open('/print/recoveries/' + encodeURIComponent(id), '_blank', 'noopener');
|
||||||
export function PrintButton({ id, title = '客户预览/打印' }) {
|
export function PrintButton({ id, title = '客户预览/打印' }: { id: string; title?: string }) {
|
||||||
return (
|
return (
|
||||||
<button data-action="recovery-print" data-id={id} onClick={() => print(id)}>
|
<button data-action="recovery-print" data-id={id} onClick={() => print(id)}>
|
||||||
{title}
|
{title}
|
||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function PrintBadge({ row, statuses }) {
|
function PrintBadge({ row, statuses }: { row: SummaryRow; statuses: PrintStatuses }) {
|
||||||
const id = row.printStatus?.id || row.id;
|
const id = row.printStatus?.id || row.id;
|
||||||
const printed = (statuses[id] || row.printStatus)?.printed;
|
const printed = (statuses[id] || row.printStatus)?.printed;
|
||||||
return (
|
return (
|
||||||
@@ -31,22 +46,37 @@ function PrintBadge({ row, statuses }) {
|
|||||||
</span>
|
</span>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
export function Records({ client, state, version, filters, query, detail, printStatuses }) {
|
function checkRecordRows(result: { rows: SummaryRow[] }) {
|
||||||
const [draft, setDraft] = useState(filters),
|
if (!result || !Array.isArray(result.rows) || result.rows.some(row => !row.id || !Object.hasOwn(modes, row.mode)))
|
||||||
|
throw new Error('记录与查询范围不一致,请重新读取。');
|
||||||
|
}
|
||||||
|
export function Records({
|
||||||
|
client,
|
||||||
|
state,
|
||||||
|
version,
|
||||||
|
filters,
|
||||||
|
query,
|
||||||
|
detail,
|
||||||
|
printStatuses,
|
||||||
|
}: PageProps & {
|
||||||
|
version: number;
|
||||||
|
filters: Filters;
|
||||||
|
query(filters: Filters): void;
|
||||||
|
detail(id: string): void;
|
||||||
|
printStatuses: PrintStatuses;
|
||||||
|
}) {
|
||||||
|
const [editing, setEditing] = useState({ applied: filters, value: filters }),
|
||||||
[attempt, retry] = useState(0);
|
[attempt, retry] = useState(0);
|
||||||
useEffect(() => {
|
const draft = editing.applied === filters ? editing.value : filters;
|
||||||
setDraft(filters);
|
const setDraft = (value: Filters) => setEditing({ applied: filters, value });
|
||||||
}, [filters]);
|
|
||||||
const check = useCallback(
|
|
||||||
r => {
|
|
||||||
if (!r || !Array.isArray(r.rows) || r.rows.some(v => !v.id || !Object.hasOwn(modes, v.mode)))
|
|
||||||
throw new Error('记录与查询范围不一致,请重新读取。');
|
|
||||||
},
|
|
||||||
[filters],
|
|
||||||
);
|
|
||||||
const valid =
|
const valid =
|
||||||
dateValid(filters.from) && dateValid(filters.date) && filters.from <= filters.date && filters.date <= state.today,
|
dateValid(filters.from) && dateValid(filters.date) && filters.from <= filters.date && filters.date <= state.today,
|
||||||
r = useRead(client, valid ? '/api/recoveries?' + new URLSearchParams(filters) : null, version + attempt, check);
|
r = useRead(
|
||||||
|
client,
|
||||||
|
valid ? '/api/recoveries?' + new URLSearchParams(filters) : null,
|
||||||
|
version + attempt,
|
||||||
|
checkRecordRows,
|
||||||
|
);
|
||||||
return (
|
return (
|
||||||
<section className="panel" id="recovery-history">
|
<section className="panel" id="recovery-history">
|
||||||
<div className="panel-title">
|
<div className="panel-title">
|
||||||
@@ -63,10 +93,12 @@ export function Records({ client, state, version, filters, query, detail, printS
|
|||||||
query({ ...draft });
|
query({ ...draft });
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{[
|
{(
|
||||||
['from', '开始日期'],
|
[
|
||||||
['date', '结束日期'],
|
['from', '开始日期'],
|
||||||
].map(([k, t]) => (
|
['date', '结束日期'],
|
||||||
|
] as const
|
||||||
|
).map(([k, t]) => (
|
||||||
<label key={k}>
|
<label key={k}>
|
||||||
{t}
|
{t}
|
||||||
<input
|
<input
|
||||||
@@ -103,7 +135,7 @@ export function Records({ client, state, version, filters, query, detail, printS
|
|||||||
</div>
|
</div>
|
||||||
) : !r ? (
|
) : !r ? (
|
||||||
'正在读取回收/置换记录…'
|
'正在读取回收/置换记录…'
|
||||||
) : !r.value.rows.length ? (
|
) : !r.value!.rows.length ? (
|
||||||
<p>
|
<p>
|
||||||
<strong>这个日期范围还没有回收/置换单</strong>保存后可在这里查看和打印。
|
<strong>这个日期范围还没有回收/置换单</strong>保存后可在这里查看和打印。
|
||||||
</p>
|
</p>
|
||||||
@@ -118,7 +150,7 @@ export function Records({ client, state, version, filters, query, detail, printS
|
|||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{r.value.rows.map(v => (
|
{r.value!.rows.map(v => (
|
||||||
<tr key={v.id}>
|
<tr key={v.id}>
|
||||||
<td>
|
<td>
|
||||||
{v.date}
|
{v.date}
|
||||||
@@ -155,7 +187,15 @@ export function Records({ client, state, version, filters, query, detail, printS
|
|||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function MaterialFacts({ data, state, cancel = false }) {
|
function MaterialFacts({
|
||||||
|
data,
|
||||||
|
state,
|
||||||
|
cancel = false,
|
||||||
|
}: {
|
||||||
|
data: EditDetail;
|
||||||
|
state: PageProps['state'];
|
||||||
|
cancel?: boolean;
|
||||||
|
}) {
|
||||||
const b = data.record.materialBatch;
|
const b = data.record.materialBatch;
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -193,9 +233,29 @@ function MaterialFacts({ data, state, cancel = false }) {
|
|||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
export function Detail({ client, state, model, id, version, close, edit, review, cancel, printStatuses }) {
|
export function Detail({
|
||||||
|
client,
|
||||||
|
state,
|
||||||
|
model,
|
||||||
|
id,
|
||||||
|
version,
|
||||||
|
close,
|
||||||
|
edit,
|
||||||
|
review,
|
||||||
|
cancel,
|
||||||
|
printStatuses,
|
||||||
|
}: PageProps & {
|
||||||
|
model: RecoveryModel;
|
||||||
|
id: string;
|
||||||
|
version: number;
|
||||||
|
close(): void;
|
||||||
|
edit(id: string): void;
|
||||||
|
review(id: string): void;
|
||||||
|
cancel(id: string): void;
|
||||||
|
printStatuses: PrintStatuses;
|
||||||
|
}) {
|
||||||
const [attempt, retry] = useState(0),
|
const [attempt, retry] = useState(0),
|
||||||
check = useCallback(r => model.checkEdit(r, id), [model, id]),
|
check = useCallback((r: EditDetail) => model.checkEdit(r, id), [model, id]),
|
||||||
response = useRead(client, '/api/recoveries/' + encodeURIComponent(id) + '/edit', version + attempt, check),
|
response = useRead(client, '/api/recoveries/' + encodeURIComponent(id) + '/edit', version + attempt, check),
|
||||||
v = response?.value?.record,
|
v = response?.value?.record,
|
||||||
data = response?.value;
|
data = response?.value;
|
||||||
@@ -205,7 +265,7 @@ export function Detail({ client, state, model, id, version, close, edit, review,
|
|||||||
<div>
|
<div>
|
||||||
{response.error} <button onClick={() => retry(n => n + 1)}>重新读取</button>
|
{response.error} <button onClick={() => retry(n => n + 1)}>重新读取</button>
|
||||||
</div>
|
</div>
|
||||||
) : !v ? (
|
) : !v || !data ? (
|
||||||
<p>正在读取单据…</p>
|
<p>正在读取单据…</p>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
@@ -238,7 +298,7 @@ export function Detail({ client, state, model, id, version, close, edit, review,
|
|||||||
.filter(r => r.customerDeposit)
|
.filter(r => r.customerDeposit)
|
||||||
.map((r, i) => (
|
.map((r, i) => (
|
||||||
<p key={i}>
|
<p key={i}>
|
||||||
使用寄存记录 {r.customerDeposit.number} · {grams(r.customerDeposit.mg)}g
|
使用寄存记录 {r.customerDeposit!.number} · {grams(r.customerDeposit!.mg)}g
|
||||||
</p>
|
</p>
|
||||||
))}
|
))}
|
||||||
<div className="table-wrap">
|
<div className="table-wrap">
|
||||||
@@ -266,7 +326,7 @@ export function Detail({ client, state, model, id, version, close, edit, review,
|
|||||||
</section>
|
</section>
|
||||||
<section className="panel">
|
<section className="panel">
|
||||||
{v.mode === 'exchange' &&
|
{v.mode === 'exchange' &&
|
||||||
(v.newProducts || [v.newProduct]).map((r, i) => (
|
(v.newProducts || [v.newProduct!]).map((r, i) => (
|
||||||
<div key={i}>
|
<div key={i}>
|
||||||
<h3>
|
<h3>
|
||||||
新货 {i + 1}:{r.name} · {grams(r.quantity)}g
|
新货 {i + 1}:{r.name} · {grams(r.quantity)}g
|
||||||
@@ -314,7 +374,7 @@ export function Detail({ client, state, model, id, version, close, edit, review,
|
|||||||
补金差重料费:{money(i.materialCost)} ·{' '}
|
补金差重料费:{money(i.materialCost)} ·{' '}
|
||||||
{i.exchange?.costMaterial?.mode === 'pool'
|
{i.exchange?.costMaterial?.mode === 'pool'
|
||||||
? '按每日料池购料顺序核算付款人'
|
? '按每日料池购料顺序核算付款人'
|
||||||
: Model.memberName(state, i.exchange?.costPayers?.material) + '支付'}
|
: Model.memberName(state, i.exchange?.costPayers?.material ?? '') + '支付'}
|
||||||
</p>
|
</p>
|
||||||
))}
|
))}
|
||||||
{(
|
{(
|
||||||
@@ -323,7 +383,7 @@ export function Detail({ client, state, model, id, version, close, edit, review,
|
|||||||
.filter(i => i.laborCost !== 0)
|
.filter(i => i.laborCost !== 0)
|
||||||
.map((i, n) => (
|
.map((i, n) => (
|
||||||
<p key={n}>
|
<p key={n}>
|
||||||
{i.name}进货工费:{money(i.laborCost)} · {Model.memberName(state, i.laborPayer)}支付
|
{i.name}进货工费:{money(i.laborCost)} · {Model.memberName(state, i.laborPayer ?? '')}支付
|
||||||
</p>
|
</p>
|
||||||
))}
|
))}
|
||||||
{v.exchange?.fee_items
|
{v.exchange?.fee_items
|
||||||
@@ -353,7 +413,7 @@ export function Detail({ client, state, model, id, version, close, edit, review,
|
|||||||
<h3>待店主复核</h3>
|
<h3>待店主复核</h3>
|
||||||
<p>原记录仍生效,申请尚未记账。</p>
|
<p>原记录仍生效,申请尚未记账。</p>
|
||||||
<Comparison request={data.pending} state={state} />
|
<Comparison request={data.pending} state={state} />
|
||||||
<button data-action="recovery-change-open" onClick={() => review(data.pending.id)}>
|
<button data-action="recovery-change-open" onClick={() => review(data.pending!.id)}>
|
||||||
{state.user.role === 'owner' ? '查看并复核' : '查看申请'}
|
{state.user.role === 'owner' ? '查看并复核' : '查看申请'}
|
||||||
</button>
|
</button>
|
||||||
</section>
|
</section>
|
||||||
@@ -376,7 +436,21 @@ export function Detail({ client, state, model, id, version, close, edit, review,
|
|||||||
</Modal>
|
</Modal>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
export function ChangeDialog({ client, state, model, selection, select, close, saved }) {
|
export function ChangeDialog({
|
||||||
|
client,
|
||||||
|
state,
|
||||||
|
model,
|
||||||
|
selection,
|
||||||
|
select,
|
||||||
|
close,
|
||||||
|
saved,
|
||||||
|
}: PageProps & {
|
||||||
|
model: RecoveryModel;
|
||||||
|
selection: Selection;
|
||||||
|
select(value: Selection): void;
|
||||||
|
close(): void;
|
||||||
|
saved(result: Saved, id: string): void;
|
||||||
|
}) {
|
||||||
const owner = state.user.role === 'owner',
|
const owner = state.user.role === 'owner',
|
||||||
[filter, setFilter] = useState('pending'),
|
[filter, setFilter] = useState('pending'),
|
||||||
[attempt, retry] = useState(0),
|
[attempt, retry] = useState(0),
|
||||||
@@ -392,21 +466,23 @@ export function ChangeDialog({ client, state, model, selection, select, close, s
|
|||||||
? '/api/recoveries/' + encodeURIComponent(id) + '/edit'
|
? '/api/recoveries/' + encodeURIComponent(id) + '/edit'
|
||||||
: '/api/recovery-changes/' + encodeURIComponent(id);
|
: '/api/recovery-changes/' + encodeURIComponent(id);
|
||||||
const check = useCallback(
|
const check = useCallback(
|
||||||
r => {
|
(r: ChangeList | EditDetail | ChangeRequest) => {
|
||||||
if (list) {
|
if (list) {
|
||||||
if (
|
if (
|
||||||
|
!('requests' in r) ||
|
||||||
!Array.isArray(r.requests) ||
|
!Array.isArray(r.requests) ||
|
||||||
!['pending', 'approved', 'rejected'].every(k => Number.isSafeInteger(r.counts?.[k]) && r.counts[k] >= 0)
|
!(['pending', 'approved', 'rejected'] as const).every(
|
||||||
|
k => Number.isSafeInteger(r.counts?.[k]) && r.counts[k] >= 0,
|
||||||
|
)
|
||||||
)
|
)
|
||||||
throw new Error('申请列表未完整返回');
|
throw new Error('申请列表未完整返回');
|
||||||
r.requests.forEach(model.checkRequest);
|
r.requests.forEach(model.checkRequest);
|
||||||
} else if (cancel) {
|
} else if (cancel) {
|
||||||
model.checkEdit(r, id);
|
const data = model.checkEdit(r, id);
|
||||||
if (!r.permissions.canCancel || r.pending)
|
if (!data.permissions.canCancel || data.pending)
|
||||||
throw new Error(r.permissions.reason || '记录已取消或有待审批申请,当前不能取消。');
|
throw new Error(data.permissions.reason || '记录已取消或有待审批申请,当前不能取消。');
|
||||||
} else {
|
} else {
|
||||||
model.checkRequest(r);
|
if (model.checkRequest(r).id !== id) throw new Error('申请身份不一致,请重新读取。');
|
||||||
if (r.id !== id) throw new Error('申请身份不一致,请重新读取。');
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[model, list, cancel, id],
|
[model, list, cancel, id],
|
||||||
@@ -419,9 +495,10 @@ export function ChangeDialog({ client, state, model, selection, select, close, s
|
|||||||
setStale(false);
|
setStale(false);
|
||||||
retry(n => n + 1);
|
retry(n => n + 1);
|
||||||
}
|
}
|
||||||
async function submit(e) {
|
async function submit(e: FormEvent<HTMLFormElement>) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
const f = new FormData(e.currentTarget);
|
const f = new FormData(e.currentTarget);
|
||||||
|
if (!r || !('revision' in r) || !id) return;
|
||||||
try {
|
try {
|
||||||
const verified = f.has('verified'),
|
const verified = f.has('verified'),
|
||||||
reason = String(f.get('reason') || '').trim(),
|
reason = String(f.get('reason') || '').trim(),
|
||||||
@@ -434,19 +511,21 @@ export function ChangeDialog({ client, state, model, selection, select, close, s
|
|||||||
revision: r.revision,
|
revision: r.revision,
|
||||||
reason,
|
reason,
|
||||||
verified: true,
|
verified: true,
|
||||||
...(r.permissions.requiresLegacyCountVerified ? { legacyCountVerified: f.has('legacyCountVerified') } : {}),
|
...('permissions' in r && r.permissions.requiresLegacyCountVerified
|
||||||
|
? { legacyCountVerified: f.has('legacyCountVerified') }
|
||||||
|
: {}),
|
||||||
}
|
}
|
||||||
: { revision: r.revision, note, ...(decision === 'approve' ? { verified: true } : {}) };
|
: { revision: r.revision, note, ...(decision === 'approve' ? { verified: true } : {}) };
|
||||||
const res = await client.mutate(
|
const res = await client.mutate<Saved>(
|
||||||
cancel
|
cancel
|
||||||
? '/api/recoveries/' + encodeURIComponent(id) + '/cancel'
|
? '/api/recoveries/' + encodeURIComponent(id) + '/cancel'
|
||||||
: '/api/recovery-changes/' + encodeURIComponent(id) + '/' + decision,
|
: '/api/recovery-changes/' + encodeURIComponent(id) + '/' + decision,
|
||||||
payload,
|
payload,
|
||||||
);
|
);
|
||||||
saved(res, cancel ? id : r.recoveryId);
|
saved(res, 'recoveryId' in r ? r.recoveryId : id);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setMessage(e.message);
|
setMessage((e as Error).message);
|
||||||
if ([403, 404, 409].includes(e.status)) setStale(true);
|
if ([403, 404, 409].includes((e as ApiError).status ?? 0)) setStale(true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return (
|
return (
|
||||||
@@ -456,8 +535,8 @@ export function ChangeDialog({ client, state, model, selection, select, close, s
|
|||||||
list
|
list
|
||||||
? '回收更正' + (owner ? '复核' : '申请')
|
? '回收更正' + (owner ? '复核' : '申请')
|
||||||
: cancel
|
: cancel
|
||||||
? '取消这笔' + (r ? modes[r.inputs.mode] : '回收/置换') + '记录'
|
? '取消这笔' + (r && 'inputs' in r ? modes[r.inputs.mode] : '回收/置换') + '记录'
|
||||||
: (r?.action === 'cancel' ? '取消' : '修改') + '回收/置换记录'
|
: (r && 'action' in r && r.action === 'cancel' ? '取消' : '修改') + '回收/置换记录'
|
||||||
}
|
}
|
||||||
action="recovery-changes-close"
|
action="recovery-changes-close"
|
||||||
close={close}
|
close={close}
|
||||||
@@ -468,15 +547,17 @@ export function ChangeDialog({ client, state, model, selection, select, close, s
|
|||||||
</div>
|
</div>
|
||||||
) : !r ? (
|
) : !r ? (
|
||||||
'正在读取…'
|
'正在读取…'
|
||||||
) : list ? (
|
) : 'requests' in r ? (
|
||||||
<div id="recovery-change-list">
|
<div id="recovery-change-list">
|
||||||
<div>
|
<div>
|
||||||
{[
|
{(
|
||||||
['pending', '待复核'],
|
[
|
||||||
['approved', '已同意'],
|
['pending', '待复核'],
|
||||||
['rejected', '已驳回'],
|
['approved', '已同意'],
|
||||||
['all', '全部'],
|
['rejected', '已驳回'],
|
||||||
].map(([k, t]) => (
|
['all', '全部'],
|
||||||
|
] as const
|
||||||
|
).map(([k, t]) => (
|
||||||
<button
|
<button
|
||||||
key={k}
|
key={k}
|
||||||
data-action="recovery-changes-filter"
|
data-action="recovery-changes-filter"
|
||||||
@@ -521,7 +602,7 @@ export function ChangeDialog({ client, state, model, selection, select, close, s
|
|||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
) : cancel ? (
|
) : 'permissions' in r ? (
|
||||||
<>
|
<>
|
||||||
<p>
|
<p>
|
||||||
{r.record.number} · {r.inputs.date} · {r.inputs.customer}
|
{r.record.number} · {r.inputs.date} · {r.inputs.customer}
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
import type { ReactElement } from 'react';
|
|
||||||
import type { LedgerClient } from '../../lib/api';
|
|
||||||
import type { LedgerState } from '../../shared';
|
|
||||||
export function RecoveriesPage(props: { client: LedgerClient; state: LedgerState; search?: string }): ReactElement;
|
|
||||||
+21
-17
@@ -1,3 +1,5 @@
|
|||||||
|
import type { LedgerClient } from '../../lib/api';
|
||||||
|
import type { ChangeList, EditDetail, Filters, Input, PageProps, Saved, Selection } from './types';
|
||||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||||
import { useRead } from '../Inventory/data';
|
import { useRead } from '../Inventory/data';
|
||||||
import { useClientSnapshot } from '../../lib/useClient';
|
import { useClientSnapshot } from '../../lib/useClient';
|
||||||
@@ -9,40 +11,42 @@ import { DepositForm, DepositList, validateDeposits } from './Deposit';
|
|||||||
import { Records, Detail, ChangeDialog, PrintButton } from './Records';
|
import { Records, Detail, ChangeDialog, PrintButton } from './Records';
|
||||||
import './recoveries.css';
|
import './recoveries.css';
|
||||||
|
|
||||||
const lastQuery = new WeakMap();
|
const lastQuery = new WeakMap<LedgerClient, { user: string; value: Filters }>();
|
||||||
export function RecoveriesPage({ client, state, search = window.location.search }) {
|
export function RecoveriesPage({ client, state, search = window.location.search }: PageProps & { search?: string }) {
|
||||||
useClientSnapshot(client);
|
useClientSnapshot(client);
|
||||||
const model = useMemo(() => recoveryModel(state), [state]),
|
const model = useMemo(() => recoveryModel(state), [state]),
|
||||||
deep = new URLSearchParams(search).get('recovery'),
|
deep = new URLSearchParams(search).get('recovery'),
|
||||||
[detail, setDetail] = useState(deep || ''),
|
[detail, setDetail] = useState(deep || ''),
|
||||||
[selection, select] = useState(null),
|
[previousDeep, setPreviousDeep] = useState(deep),
|
||||||
[edit, setEdit] = useState(null),
|
[selection, select] = useState<Selection | null>(null),
|
||||||
|
[edit, setEdit] = useState<EditDetail | null>(null),
|
||||||
[page, setPage] = useState('new'),
|
[page, setPage] = useState('new'),
|
||||||
[version, reload] = useState(0),
|
[version, reload] = useState(0),
|
||||||
[result, setResult] = useState(null),
|
[result, setResult] = useState<{ payload: Input; r: Saved } | null>(null),
|
||||||
[notice, setNotice] = useState(''),
|
[notice, setNotice] = useState(''),
|
||||||
[formKey, resetForm] = useState(0);
|
[formKey, resetForm] = useState(0);
|
||||||
const [filters, setFilters] = useState(() => {
|
const [filters, setFilters] = useState(() => {
|
||||||
const old = lastQuery.get(client);
|
const old = lastQuery.get(client);
|
||||||
return old?.user === state.user.id ? old.value : { from: state.today, date: state.today, mode: '', member: '' };
|
return old?.user === state.user.id ? old.value : { from: state.today, date: state.today, mode: '', member: '' };
|
||||||
});
|
});
|
||||||
const historyRef = useRef(null),
|
const historyRef = useRef<HTMLDivElement>(null),
|
||||||
editingRequest = useRef(0);
|
editingRequest = useRef(0);
|
||||||
useEffect(() => {
|
if (previousDeep !== deep) {
|
||||||
|
setPreviousDeep(deep);
|
||||||
setDetail(deep || '');
|
setDetail(deep || '');
|
||||||
}, [deep]);
|
}
|
||||||
useEffect(
|
useEffect(
|
||||||
() => () => {
|
() => () => {
|
||||||
editingRequest.current++;
|
editingRequest.current++;
|
||||||
},
|
},
|
||||||
[],
|
[],
|
||||||
);
|
);
|
||||||
const query = f => {
|
const query = (f: Filters) => {
|
||||||
lastQuery.set(client, { user: state.user.id, value: f });
|
lastQuery.set(client, { user: state.user.id, value: f });
|
||||||
setFilters(f);
|
setFilters(f);
|
||||||
};
|
};
|
||||||
const deposits = useRead(client, page === 'saved' ? null : '/api/customer-materials', version, validateDeposits);
|
const deposits = useRead(client, page === 'saved' ? null : '/api/customer-materials', version, validateDeposits);
|
||||||
const checkCount = useCallback(r => {
|
const checkCount = useCallback((r: ChangeList) => {
|
||||||
if (!Number.isSafeInteger(r.counts?.pending) || r.counts.pending < 0) throw new Error('数量未完整返回');
|
if (!Number.isSafeInteger(r.counts?.pending) || r.counts.pending < 0) throw new Error('数量未完整返回');
|
||||||
}, []);
|
}, []);
|
||||||
const count = useRead(
|
const count = useRead(
|
||||||
@@ -62,12 +66,12 @@ export function RecoveriesPage({ client, state, search = window.location.search
|
|||||||
window.dispatchEvent(new Event('next-route'));
|
window.dispatchEvent(new Event('next-route'));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
async function getEdit(id) {
|
async function getEdit(id: string) {
|
||||||
const r = model.checkEdit(await client.api('/api/recoveries/' + encodeURIComponent(id) + '/edit'), id);
|
const r = model.checkEdit(await client.api('/api/recoveries/' + encodeURIComponent(id) + '/edit'), id);
|
||||||
if (!r.permissions.canEdit || r.pending) throw new Error(r.permissions.reason || '这笔记录当前不能修改。');
|
if (!r.permissions.canEdit || r.pending) throw new Error(r.permissions.reason || '这笔记录当前不能修改。');
|
||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
async function begin(id) {
|
async function begin(id: string) {
|
||||||
const request = ++editingRequest.current;
|
const request = ++editingRequest.current;
|
||||||
try {
|
try {
|
||||||
const r = await getEdit(id);
|
const r = await getEdit(id);
|
||||||
@@ -77,10 +81,10 @@ export function RecoveriesPage({ client, state, search = window.location.search
|
|||||||
setPage('new');
|
setPage('new');
|
||||||
setNotice('');
|
setNotice('');
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setNotice(e.message);
|
setNotice((e as Error).message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
function changeSaved(res, id) {
|
function changeSaved(res: Saved, id: string) {
|
||||||
select(null);
|
select(null);
|
||||||
setEdit(null);
|
setEdit(null);
|
||||||
setPage('new');
|
setPage('new');
|
||||||
@@ -88,7 +92,7 @@ export function RecoveriesPage({ client, state, search = window.location.search
|
|||||||
setNotice(res.pending && !res.applied ? '回收更正申请已提交,待店主复核' : '回收更正已保存');
|
setNotice(res.pending && !res.applied ? '回收更正申请已提交,待店主复核' : '回收更正已保存');
|
||||||
reload(n => n + 1);
|
reload(n => n + 1);
|
||||||
}
|
}
|
||||||
function saved(payload, r) {
|
function saved(payload: Input, r: Saved) {
|
||||||
if (edit) {
|
if (edit) {
|
||||||
changeSaved(r, edit.id);
|
changeSaved(r, edit.id);
|
||||||
return;
|
return;
|
||||||
@@ -211,10 +215,10 @@ export function RecoveriesPage({ client, state, search = window.location.search
|
|||||||
deposit={depositPage}
|
deposit={depositPage}
|
||||||
saved={saved}
|
saved={saved}
|
||||||
exitEdit={() => {
|
exitEdit={() => {
|
||||||
setDetail(edit.id);
|
setDetail(edit!.id);
|
||||||
setEdit(null);
|
setEdit(null);
|
||||||
}}
|
}}
|
||||||
refreshEdit={() => getEdit(edit.id)}
|
refreshEdit={() => getEdit(edit!.id)}
|
||||||
/>
|
/>
|
||||||
{!edit && list}
|
{!edit && list}
|
||||||
</>
|
</>
|
||||||
+127
-78
@@ -1,3 +1,23 @@
|
|||||||
|
import type { ChangeEvent, FormEvent, InputHTMLAttributes, SelectHTMLAttributes } from 'react';
|
||||||
|
import type { ApiError } from '../../lib/api';
|
||||||
|
import type { Choice } from './controls';
|
||||||
|
import type {
|
||||||
|
EditDetail,
|
||||||
|
Draft,
|
||||||
|
RecoveryModel,
|
||||||
|
Derived,
|
||||||
|
TextField,
|
||||||
|
PageProps,
|
||||||
|
Deposit,
|
||||||
|
Input,
|
||||||
|
Saved,
|
||||||
|
QuoteItem,
|
||||||
|
MaterialPool,
|
||||||
|
ExtraKinds,
|
||||||
|
ExtraFields,
|
||||||
|
ProductDraft,
|
||||||
|
PoolChoice,
|
||||||
|
} from './types';
|
||||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||||
import { Model, Cards } from '../../shared';
|
import { Model, Cards } from '../../shared';
|
||||||
import { grams } from '../../lib/format';
|
import { grams } from '../../lib/format';
|
||||||
@@ -7,9 +27,10 @@ import { IndependentItems } from './IndependentItems';
|
|||||||
import { localMaterialNote, quotedMaterialNote } from './materialPreview';
|
import { localMaterialNote, quotedMaterialNote } from './materialPreview';
|
||||||
import { useRead } from '../Inventory/data';
|
import { useRead } from '../Inventory/data';
|
||||||
|
|
||||||
function normalize(draft) {
|
function normalize(draft: Draft) {
|
||||||
const result = { ...draft, customer_type: draft.mode === 'direct' ? '' : draft.customer_type };
|
const result = { ...draft, customer_type: draft.mode === 'direct' ? '' : draft.customer_type };
|
||||||
for (const k in result) if (typeof result[k] === 'string') result[k] = result[k].trim();
|
for (const [key, value] of Object.entries(result))
|
||||||
|
if (typeof value === 'string') Object.assign(result, { [key]: value.trim() });
|
||||||
if (draft.old_lines?.length)
|
if (draft.old_lines?.length)
|
||||||
result.old_lines = [
|
result.old_lines = [
|
||||||
{
|
{
|
||||||
@@ -45,7 +66,7 @@ function normalize(draft) {
|
|||||||
];
|
];
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
function derive(model, raw) {
|
function derive(model: RecoveryModel, raw: Draft): Derived {
|
||||||
if (raw.independent_products && raw.mode === 'exchange') {
|
if (raw.independent_products && raw.mode === 'exchange') {
|
||||||
const parts = [raw, ...(raw.extra_products || [])].map((item, index) =>
|
const parts = [raw, ...(raw.extra_products || [])].map((item, index) =>
|
||||||
derive(model, {
|
derive(model, {
|
||||||
@@ -78,7 +99,7 @@ function derive(model, raw) {
|
|||||||
const input = model.input(draft, { quote: true });
|
const input = model.input(draft, { quote: true });
|
||||||
return { draft, parts, input, q: model.calculate(input), error: '' };
|
return { draft, parts, input, q: model.calculate(input), error: '' };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return { draft, parts, input: null, q: null, error: error.message };
|
return { draft, parts, input: null, q: null, error: (error as Error).message };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,11 +155,11 @@ function derive(model, raw) {
|
|||||||
error = '';
|
error = '';
|
||||||
if (!draft.buy_total_manual) draft = { ...draft, buy_total: (q.defaultPurchaseAmount / 100).toFixed(2) };
|
if (!draft.buy_total_manual) draft = { ...draft, buy_total: (q.defaultPurchaseAmount / 100).toFixed(2) };
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
error = e.message;
|
error = (e as Error).message;
|
||||||
}
|
}
|
||||||
return { draft, old, newMg, q, input, error, hasBuy, diff };
|
return { draft, old, newMg, q, input, error, hasBuy, diff };
|
||||||
}
|
}
|
||||||
function RecoveryCardFee({ state, edit, net }) {
|
function RecoveryCardFee({ state, edit, net }: { state: PageProps['state']; edit: EditDetail | null; net: number }) {
|
||||||
const rate = edit ? edit.record.credit_card_rate_permille : state.shopSettings?.creditCardRatePermille;
|
const rate = edit ? edit.record.credit_card_rate_permille : state.shopSettings?.creditCardRatePermille;
|
||||||
const unavailable = <p role="status">信用卡手续费率未能确认,请重新读取后核对。</p>;
|
const unavailable = <p role="status">信用卡手续费率未能确认,请重新读取后核对。</p>;
|
||||||
if (rate == null) return unavailable;
|
if (rate == null) return unavailable;
|
||||||
@@ -157,17 +178,33 @@ function RecoveryCardFee({ state, edit, net }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const basicMethods = ['微信', '支付宝', '现金'];
|
const basicMethods = ['微信', '支付宝', '现金'];
|
||||||
export function RecoveryForm({ client, state, edit, materials = [], deposit, saved, exitEdit, refreshEdit }) {
|
export function RecoveryForm({
|
||||||
|
client,
|
||||||
|
state,
|
||||||
|
edit,
|
||||||
|
materials = [],
|
||||||
|
deposit,
|
||||||
|
saved,
|
||||||
|
exitEdit,
|
||||||
|
refreshEdit,
|
||||||
|
}: PageProps & {
|
||||||
|
edit: EditDetail | null;
|
||||||
|
materials?: Deposit[];
|
||||||
|
deposit(): void;
|
||||||
|
saved(input: Input, result: Saved): void;
|
||||||
|
exitEdit(): void;
|
||||||
|
refreshEdit(): Promise<EditDetail>;
|
||||||
|
}) {
|
||||||
const model = useMemo(() => recoveryModel(state, edit), [state, edit]),
|
const model = useMemo(() => recoveryModel(state, edit), [state, edit]),
|
||||||
key = 'mm-recovery-draft-' + state.user.id;
|
key = 'mm-recovery-draft-' + state.user.id;
|
||||||
const editKey = edit ? 'mm-recovery-edit-' + state.user.id + '-' + edit.id : null;
|
const editKey = edit ? 'mm-recovery-edit-' + state.user.id + '-' + edit.id : null;
|
||||||
const existing = useMemo(() => {
|
const existing = useMemo(() => {
|
||||||
const v = editKey && loadDraft(editKey);
|
const v = editKey ? loadDraft<{ id: string; draft: Draft; revision: number; reason?: string }>(editKey) : null;
|
||||||
return v?.id === edit?.id && v?.draft?.mode === edit?.inputs?.mode && v?.draft?.member === edit?.inputs?.member
|
return v?.id === edit?.id && v?.draft?.mode === edit?.inputs?.mode && v?.draft?.member === edit?.inputs?.member
|
||||||
? v
|
? v
|
||||||
: null;
|
: null;
|
||||||
}, [edit, editKey]);
|
}, [edit, editKey]);
|
||||||
const [raw, setRaw] = useState(() => {
|
const [raw, setRaw] = useState<Draft>(() => {
|
||||||
if (edit)
|
if (edit)
|
||||||
return {
|
return {
|
||||||
...(existing?.draft || model.forEdit(edit.inputs)),
|
...(existing?.draft || model.forEdit(edit.inputs)),
|
||||||
@@ -175,7 +212,7 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
|
|||||||
change_reason: existing?.reason || '',
|
change_reason: existing?.reason || '',
|
||||||
verified: false,
|
verified: false,
|
||||||
};
|
};
|
||||||
const stored = loadDraft(key);
|
const stored = loadDraft<Partial<Draft>>(key);
|
||||||
if (stored?.independent_products && !localStorage.getItem(key + '-before-shared-old'))
|
if (stored?.independent_products && !localStorage.getItem(key + '-before-shared-old'))
|
||||||
localStorage.setItem(key + '-before-shared-old', JSON.stringify(stored));
|
localStorage.setItem(key + '-before-shared-old', JSON.stringify(stored));
|
||||||
const d = model.sharedDraft({
|
const d = model.sharedDraft({
|
||||||
@@ -189,9 +226,11 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
|
|||||||
return d;
|
return d;
|
||||||
});
|
});
|
||||||
const [error, setError] = useState(''),
|
const [error, setError] = useState(''),
|
||||||
[quote, setQuote] = useState({}),
|
[quote, setQuote] = useState<{ signature?: string; text?: string; materialText?: string; value?: QuoteItem }>({}),
|
||||||
[rate, setRate] = useState({}),
|
[rate, setRate] = useState<{ name?: TextField; index?: number; text?: string }>({}),
|
||||||
[conflict, setConflict] = useState(existing && existing.revision !== edit?.revision ? {} : null),
|
[conflict, setConflict] = useState<{ latest?: EditDetail } | null>(
|
||||||
|
existing && existing.revision !== edit?.revision ? {} : null,
|
||||||
|
),
|
||||||
[revision, setRevision] = useState(existing?.revision ?? edit?.revision);
|
[revision, setRevision] = useState(existing?.revision ?? edit?.revision);
|
||||||
const { draft: d, old, newMg, q, input, error: calcError, hasBuy, diff, parts } = derive(model, raw),
|
const { draft: d, old, newMg, q, input, error: calcError, hasBuy, diff, parts } = derive(model, raw),
|
||||||
exchange = d.mode === 'exchange',
|
exchange = d.mode === 'exchange',
|
||||||
@@ -199,12 +238,12 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
|
|||||||
net = q?.netSettlement ?? (exchange ? 0 : -1),
|
net = q?.netSettlement ?? (exchange ? 0 : -1),
|
||||||
card = net > 0 && d.payment_method === '信用卡';
|
card = net > 0 && d.payment_method === '信用卡';
|
||||||
const signature = input && q ? JSON.stringify(edit ? { ...input, revision } : input) : '',
|
const signature = input && q ? JSON.stringify(edit ? { ...input, revision } : input) : '',
|
||||||
live = useRef(raw);
|
live = useRef<Draft | null>(raw);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
live.current = raw;
|
live.current = raw;
|
||||||
if (edit)
|
if (edit)
|
||||||
localStorage.setItem(
|
localStorage.setItem(
|
||||||
editKey,
|
editKey!,
|
||||||
JSON.stringify({ id: edit.id, revision, draft: raw, reason: raw.change_reason || '' }),
|
JSON.stringify({ id: edit.id, revision, draft: raw, reason: raw.change_reason || '' }),
|
||||||
);
|
);
|
||||||
else localStorage.setItem(key, JSON.stringify(raw));
|
else localStorage.setItem(key, JSON.stringify(raw));
|
||||||
@@ -220,18 +259,21 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
|
|||||||
let valid = true;
|
let valid = true;
|
||||||
const timer = setTimeout(async () => {
|
const timer = setTimeout(async () => {
|
||||||
try {
|
try {
|
||||||
const payload = JSON.parse(signature),
|
const payload: Input = JSON.parse(signature),
|
||||||
value = await client.api(quoteUrl, payload);
|
value = await client.api<QuoteItem>(quoteUrl, payload);
|
||||||
if (!Number.isSafeInteger(value.netSettlement) || value.netSettlement !== expected)
|
if (!Number.isSafeInteger(value.netSettlement) || value.netSettlement !== expected)
|
||||||
throw new Error('结算规则已更新,请重新读取页面再核对。');
|
throw new Error('结算规则已更新,请重新读取页面再核对。');
|
||||||
if (!valid) return;
|
if (!valid) return;
|
||||||
const materialText = await quotedMaterialNote(client, state, payload, value, differenceMg, edit);
|
const materialText = await quotedMaterialNote(client, state, payload, value, differenceMg!, edit);
|
||||||
if (valid) setQuote({ signature, text: '结算已核对;保存时按最新账务记录确认。', materialText, value });
|
if (valid) setQuote({ signature, text: '结算已核对;保存时按最新账务记录确认。', materialText, value });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (valid)
|
if (valid)
|
||||||
setQuote({
|
setQuote({
|
||||||
signature,
|
signature,
|
||||||
text: e.name === 'AbortError' ? '结算核对超时,保存时将再次核验。' : '结算核对:' + e.message,
|
text:
|
||||||
|
(e as Error).name === 'AbortError'
|
||||||
|
? '结算核对超时,保存时将再次核验。'
|
||||||
|
: '结算核对:' + (e as Error).message,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}, 350);
|
}, 350);
|
||||||
@@ -240,16 +282,17 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
|
|||||||
clearTimeout(timer);
|
clearTimeout(timer);
|
||||||
};
|
};
|
||||||
}, [client, state, signature, expected, differenceMg, quoteUrl, edit, conflict]);
|
}, [client, state, signature, expected, differenceMg, quoteUrl, edit, conflict]);
|
||||||
const pools = useRead(client, exchange ? '/api/material-pools' : null, 0)?.value?.rows || [],
|
const pools =
|
||||||
|
useRead<{ rows: MaterialPool[] }>(client, exchange ? '/api/material-pools' : null, 0)?.value?.rows || [],
|
||||||
members = Model.memberOptions(state),
|
members = Model.memberOptions(state),
|
||||||
recipients = members.map(([k, t]) => [memberAccountPrefix(k), t]);
|
recipients = members.map(([k, t]) => [memberAccountPrefix(k), t]);
|
||||||
function setField(k, v, index = -1) {
|
function setField<K extends keyof Draft>(k: K, v: Draft[K], index = -1) {
|
||||||
setError('');
|
setError('');
|
||||||
setRaw(previous => {
|
setRaw(previous => {
|
||||||
const next = { ...previous },
|
const next = { ...previous },
|
||||||
row = index < 0 ? next : { ...previous.extra_products[index] };
|
row = index < 0 ? next : { ...previous.extra_products![index] };
|
||||||
row[k] = v;
|
row[k] = v;
|
||||||
if (k === 'incoming_weight' && !row.melted_manual) row.melted_weight = v;
|
if (k === 'incoming_weight' && !row.melted_manual) row.melted_weight = String(v);
|
||||||
if (k === 'melted_weight') row.melted_manual = true;
|
if (k === 'melted_weight') row.melted_manual = true;
|
||||||
if (k === 'buy_total') row.buy_total_manual = true;
|
if (k === 'buy_total') row.buy_total_manual = true;
|
||||||
if (k === 'depreciation_weight') row.depreciation_manual = true;
|
if (k === 'depreciation_weight') row.depreciation_manual = true;
|
||||||
@@ -259,10 +302,10 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
|
|||||||
material_payer: v,
|
material_payer: v,
|
||||||
labor_payer: v,
|
labor_payer: v,
|
||||||
fee_payer: v,
|
fee_payer: v,
|
||||||
payment_recipient: memberAccountPrefix(v),
|
payment_recipient: memberAccountPrefix(String(v)),
|
||||||
});
|
});
|
||||||
if (k === 'date' && (!row.material_pool_id || row.material_pool_id > v)) row.material_pool_id = v;
|
if (k === 'date' && (!row.material_pool_id || row.material_pool_id > String(v))) row.material_pool_id = String(v);
|
||||||
if (index >= 0) next.extra_products = next.extra_products.map((item, i) => (i === index ? row : item));
|
if (index >= 0) next.extra_products = next.extra_products!.map((item, i) => (i === index ? row : item));
|
||||||
return next;
|
return next;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -279,14 +322,14 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
|
|||||||
],
|
],
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
function remove(i) {
|
function remove(i: number) {
|
||||||
setRaw({ ...d, extra_products: d.extra_products.filter((_, index) => index !== i) });
|
setRaw({ ...d, extra_products: d.extra_products!.filter((_, index) => index !== i) });
|
||||||
}
|
}
|
||||||
async function daily(name, index = -1) {
|
async function daily(name: TextField, index = -1) {
|
||||||
const target = live.current;
|
const target = live.current;
|
||||||
setRate({ name, index, text: '正在读取当日加权料价…' });
|
setRate({ name, index, text: '正在读取当日加权料价…' });
|
||||||
try {
|
try {
|
||||||
const v = await client.api(
|
const v = await client.api<MaterialPool & { averageRate: number; totalAmount: number }>(
|
||||||
'/api/material-pools/' + encodeURIComponent(d.date) + '?member=' + encodeURIComponent(d.member),
|
'/api/material-pools/' + encodeURIComponent(d.date) + '?member=' + encodeURIComponent(d.member),
|
||||||
);
|
);
|
||||||
if (!live.current) return;
|
if (!live.current) return;
|
||||||
@@ -307,32 +350,36 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
|
|||||||
if (name === 'buy_rate') setField('buy_total_manual', false, index);
|
if (name === 'buy_rate') setField('buy_total_manual', false, index);
|
||||||
setRate({ name, index, text: '已带入 ' + d.date + ' 公共加权 ¥' + value + '/克,可继续手改。' });
|
setRate({ name, index, text: '已带入 ' + d.date + ' 公共加权 ¥' + value + '/克,可继续手改。' });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setRate({ name, index, text: e.message });
|
setRate({ name, index, text: (e as Error).message });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const signed = (prefix, k) => prefix + k;
|
function fields(row: ProductDraft = d, index = -1, off = false) {
|
||||||
function fields(row = d, index = -1, off = false) {
|
|
||||||
const prefix = index < 0 ? '' : 'extra_',
|
const prefix = index < 0 ? '' : 'extra_',
|
||||||
attrs = (name, props = {}) => ({
|
attrs = (name: TextField) => ({
|
||||||
name: signed(prefix, name),
|
name: prefix + name,
|
||||||
value: row[name] ?? '',
|
value: row[name] ?? '',
|
||||||
onChange: e => setField(name, e.target.value, index),
|
onChange: (e: ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) =>
|
||||||
|
setField(name, e.target.value, index),
|
||||||
disabled: off,
|
disabled: off,
|
||||||
...props,
|
|
||||||
});
|
});
|
||||||
const text = (title, k, limit, attrsMore = {}) => (
|
const text = (
|
||||||
|
title: string,
|
||||||
|
k: TextField,
|
||||||
|
limit: number,
|
||||||
|
attrsMore: InputHTMLAttributes<HTMLInputElement> = {},
|
||||||
|
) => (
|
||||||
<label>
|
<label>
|
||||||
{title}
|
{title}
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
{...attrs(k)}
|
{...attrs(k)}
|
||||||
value={(index < 0 ? raw : raw.extra_products[index])[k] ?? ''}
|
value={(index < 0 ? raw : raw.extra_products![index])[k] ?? ''}
|
||||||
maxLength={limit}
|
maxLength={limit}
|
||||||
{...attrsMore}
|
{...attrsMore}
|
||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
);
|
);
|
||||||
const num = (title, k, places = 2, props = {}) => (
|
const num = (title: string, k: TextField, places = 2, props: InputHTMLAttributes<HTMLInputElement> = {}) => (
|
||||||
<label>
|
<label>
|
||||||
{title}
|
{title}
|
||||||
<input
|
<input
|
||||||
@@ -345,7 +392,12 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
|
|||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
);
|
);
|
||||||
const select = (title, k, choices, props = {}) => (
|
const select = (
|
||||||
|
title: string,
|
||||||
|
k: TextField,
|
||||||
|
choices: readonly Choice[],
|
||||||
|
props: SelectHTMLAttributes<HTMLSelectElement> = {},
|
||||||
|
) => (
|
||||||
<label>
|
<label>
|
||||||
{title}
|
{title}
|
||||||
<select {...attrs(k)} {...props}>
|
<select {...attrs(k)} {...props}>
|
||||||
@@ -353,7 +405,7 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
|
|||||||
</select>
|
</select>
|
||||||
</label>
|
</label>
|
||||||
);
|
);
|
||||||
const pairs = (title, k, pocket, visible = true, optional = false) => (
|
const pairs = (title: string, k: TextField, pocket: string, visible = true, optional = false) => (
|
||||||
<label hidden={!visible || !Model.pocketCountsEnabled(state, pocket)}>
|
<label hidden={!visible || !Model.pocketCountsEnabled(state, pocket)}>
|
||||||
{title}
|
{title}
|
||||||
<input
|
<input
|
||||||
@@ -369,7 +421,7 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
|
|||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
);
|
);
|
||||||
const rateField = (title, k, use = true, props = {}) => (
|
const rateField = (title: string, k: TextField, use = true, props: InputHTMLAttributes<HTMLInputElement> = {}) => (
|
||||||
<div className="recovery-customer-rate">
|
<div className="recovery-customer-rate">
|
||||||
{num(title, k, 2, { required: true, ...props })}
|
{num(title, k, 2, { required: true, ...props })}
|
||||||
{use && (
|
{use && (
|
||||||
@@ -391,7 +443,7 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
|
|||||||
return { attrs, text, num, select, pairs, rateField };
|
return { attrs, text, num, select, pairs, rateField };
|
||||||
}
|
}
|
||||||
const { attrs, text, num, select, pairs } = fields();
|
const { attrs, text, num, select, pairs } = fields();
|
||||||
function product(row, index) {
|
function product(row: ProductDraft, index: number) {
|
||||||
const f = fields(row, index, !exchange),
|
const f = fields(row, index, !exchange),
|
||||||
original =
|
original =
|
||||||
edit?.inputs.exchange?.products?.[index + 1] ||
|
edit?.inputs.exchange?.products?.[index + 1] ||
|
||||||
@@ -443,7 +495,7 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
|
|||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
const available = pools.filter(
|
const available: PoolChoice[] = pools.filter(
|
||||||
p =>
|
p =>
|
||||||
p.date <= d.date &&
|
p.date <= d.date &&
|
||||||
(p.id === d.date ||
|
(p.id === d.date ||
|
||||||
@@ -459,7 +511,7 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
|
|||||||
(!edit.permissions.canDirect ||
|
(!edit.permissions.canDirect ||
|
||||||
edit.permissions.requiresApproval ||
|
edit.permissions.requiresApproval ||
|
||||||
(state.user.role !== 'owner' && (edit.inputs.date !== state.today || d.date !== state.today)));
|
(state.user.role !== 'owner' && (edit.inputs.date !== state.today || d.date !== state.today)));
|
||||||
async function submit(e) {
|
async function submit(e: FormEvent<HTMLFormElement>) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
try {
|
try {
|
||||||
const payload = model.validate(model.input(d));
|
const payload = model.validate(model.input(d));
|
||||||
@@ -476,31 +528,31 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
|
|||||||
: {}),
|
: {}),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
const result = await client.mutate(
|
const result = await client.mutate<Saved>(
|
||||||
edit ? '/api/recoveries/' + encodeURIComponent(edit.id) + '/update' : '/api/recoveries',
|
edit ? '/api/recoveries/' + encodeURIComponent(edit.id) + '/update' : '/api/recoveries',
|
||||||
payload,
|
payload,
|
||||||
);
|
);
|
||||||
localStorage.removeItem(editKey || key);
|
localStorage.removeItem(editKey || key);
|
||||||
saved(payload, result);
|
saved(payload, result);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err.message);
|
setError((err as Error).message);
|
||||||
if (edit && [403, 404, 409].includes(err.status)) setConflict({});
|
if (edit && [403, 404, 409].includes((err as ApiError).status ?? 0)) setConflict({});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
function extras(kind, rows, keys, caption) {
|
function extras<K extends keyof ExtraKinds>(kind: K, rows: ExtraKinds[K][], keys: ExtraFields<K>, caption: string) {
|
||||||
if (!edit) return null;
|
if (!edit) return null;
|
||||||
const prop = kind === 'old' ? 'old_lines' : kind === 'fee' ? 'fee_items' : 'charges',
|
const prop = kind === 'old' ? 'old_lines' : kind === 'fee' ? 'fee_items' : 'charges',
|
||||||
defaults =
|
defaults: ExtraKinds[K] = {
|
||||||
kind === 'old'
|
old: { name: 'Au旧料', incoming_weight: '', melted_weight: '', purity: '100' },
|
||||||
? { name: 'Au旧料', incoming_weight: '', melted_weight: '', purity: '100' }
|
fee: { key: 'other', note: '其他费用', amount: '0', payer: d.member },
|
||||||
: kind === 'fee'
|
charge: { name: '其他收费', amount: '0' },
|
||||||
? { key: 'other', note: '其他费用', amount: '0', payer: d.member }
|
}[kind];
|
||||||
: { name: '其他收费', amount: '0' };
|
function updateRows(value: ExtraKinds[K][]) {
|
||||||
const change = (i, key, v) =>
|
setError('');
|
||||||
setField(
|
setRaw(previous => ({ ...previous, [prop]: value }));
|
||||||
prop,
|
}
|
||||||
rows.map((r, num) => (num === i ? { ...r, [key]: v } : r)),
|
const change = (i: number, key: keyof ExtraKinds[K], value: string) =>
|
||||||
);
|
updateRows(rows.map((r, num) => (num === i ? { ...r, [key]: value } : r)));
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{rows.slice(1).map((r, i) => (
|
{rows.slice(1).map((r, i) => (
|
||||||
@@ -523,7 +575,7 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
|
|||||||
: '费用名称'
|
: '费用名称'
|
||||||
: t}
|
: t}
|
||||||
{k === 'payer' ? (
|
{k === 'payer' ? (
|
||||||
<select name={name} value={r[k] || ''} onChange={e => change(i + 1, k, e.target.value)}>
|
<select name={name} value={String(r[k] || '')} onChange={e => change(i + 1, k, e.target.value)}>
|
||||||
{options(members)}
|
{options(members)}
|
||||||
</select>
|
</select>
|
||||||
) : (
|
) : (
|
||||||
@@ -536,7 +588,7 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
|
|||||||
step={number ? (kind === 'old' ? '0.001' : '0.01') : undefined}
|
step={number ? (kind === 'old' ? '0.001' : '0.01') : undefined}
|
||||||
inputMode={number ? 'decimal' : undefined}
|
inputMode={number ? 'decimal' : undefined}
|
||||||
maxLength={number ? undefined : k === 'note' ? 100 : 60}
|
maxLength={number ? undefined : k === 'note' ? 100 : 60}
|
||||||
value={r[k] || ''}
|
value={String(r[k] || '')}
|
||||||
onChange={e => change(i + 1, k, e.target.value)}
|
onChange={e => change(i + 1, k, e.target.value)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
@@ -548,12 +600,7 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
|
|||||||
data-action="recovery-edit-remove-row"
|
data-action="recovery-edit-remove-row"
|
||||||
data-kind={kind}
|
data-kind={kind}
|
||||||
data-index={i + 1}
|
data-index={i + 1}
|
||||||
onClick={() =>
|
onClick={() => updateRows(rows.filter((_, j) => j !== i + 1))}
|
||||||
setField(
|
|
||||||
prop,
|
|
||||||
rows.filter((_, j) => j !== i + 1),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
>
|
>
|
||||||
移除这项
|
移除这项
|
||||||
</button>
|
</button>
|
||||||
@@ -563,7 +610,7 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
|
|||||||
type="button"
|
type="button"
|
||||||
data-action="recovery-edit-add-row"
|
data-action="recovery-edit-add-row"
|
||||||
data-kind={kind}
|
data-kind={kind}
|
||||||
onClick={() => setField(prop, [...(rows.length ? rows : [defaults]), { ...defaults }])}
|
onClick={() => updateRows([...(rows.length ? rows : [defaults]), { ...defaults }])}
|
||||||
>
|
>
|
||||||
+ 添加{caption}
|
+ 添加{caption}
|
||||||
</button>
|
</button>
|
||||||
@@ -576,10 +623,12 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
|
|||||||
<input type="hidden" name="shared_old_notice" value={d.shared_old_notice || ''} />
|
<input type="hidden" name="shared_old_notice" value={d.shared_old_notice || ''} />
|
||||||
{!edit && (
|
{!edit && (
|
||||||
<div className="actions">
|
<div className="actions">
|
||||||
{[
|
{(
|
||||||
['direct', '直接回收'],
|
[
|
||||||
['exchange', '置换'],
|
['direct', '直接回收'],
|
||||||
].map(([mode, name]) => (
|
['exchange', '置换'],
|
||||||
|
] as const
|
||||||
|
).map(([mode, name]) => (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
key={mode}
|
key={mode}
|
||||||
@@ -643,7 +692,7 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
|
|||||||
parts={parts}
|
parts={parts}
|
||||||
quotedItems={quote.signature === signature ? quote.value?.exchangeItems : undefined}
|
quotedItems={quote.signature === signature ? quote.value?.exchangeItems : undefined}
|
||||||
draft={d}
|
draft={d}
|
||||||
edit={edit}
|
edit={edit!}
|
||||||
state={state}
|
state={state}
|
||||||
fields={fields}
|
fields={fields}
|
||||||
materials={materials}
|
materials={materials}
|
||||||
@@ -738,7 +787,7 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
|
|||||||
<p>每件新货分别填写工费、成本和货盘</p>
|
<p>每件新货分别填写工费、成本和货盘</p>
|
||||||
<p>上方旧料只录一次,供下面所有新货共同抵扣。补金、折旧和余料按整单统一结算。</p>
|
<p>上方旧料只录一次,供下面所有新货共同抵扣。补金、折旧和余料按整单统一结算。</p>
|
||||||
<p id="recovery-new-total">
|
<p id="recovery-new-total">
|
||||||
新货共 {1 + (d.extra_products?.length || 0)} 件 · 合计 {newMg === null ? '待填写' : grams(newMg) + 'g'}
|
新货共 {1 + (d.extra_products?.length || 0)} 件 · 合计 {newMg == null ? '待填写' : grams(newMg) + 'g'}
|
||||||
{old && ' · 共用折后旧料 ' + grams(old.oldMg) + 'g'}
|
{old && ' · 共用折后旧料 ' + grams(old.oldMg) + 'g'}
|
||||||
</p>
|
</p>
|
||||||
<datalist id="recovery-product-names">
|
<datalist id="recovery-product-names">
|
||||||
@@ -959,7 +1008,7 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
|
|||||||
try {
|
try {
|
||||||
setConflict({ latest: await refreshEdit() });
|
setConflict({ latest: await refreshEdit() });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setError(e.message);
|
setError((e as Error).message);
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
@@ -970,7 +1019,7 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
|
|||||||
type="button"
|
type="button"
|
||||||
data-action="recovery-edit-keep"
|
data-action="recovery-edit-keep"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setRevision(conflict.latest.revision);
|
setRevision(conflict.latest!.revision);
|
||||||
setConflict(null);
|
setConflict(null);
|
||||||
setField('verified', false);
|
setField('verified', false);
|
||||||
}}
|
}}
|
||||||
+30
-14
@@ -1,19 +1,23 @@
|
|||||||
|
import type { ReactNode } from 'react';
|
||||||
|
import type { LedgerState } from '../../shared';
|
||||||
|
import type { Draft, Input, Totals, Permission } from './types';
|
||||||
|
export type Choice = string | readonly (string | boolean)[];
|
||||||
import { useEffect, useRef } from 'react';
|
import { useEffect, useRef } from 'react';
|
||||||
import { Model } from '../../shared';
|
import { Model } from '../../shared';
|
||||||
import { grams, yuan } from '../../lib/format';
|
import { grams, yuan } from '../../lib/format';
|
||||||
export const money = value => (value == null ? '待填写' : '¥' + yuan(value));
|
export const money = (value?: number | null) => (value == null ? '待填写' : '¥' + yuan(value));
|
||||||
export const rowLabel = (s, key) => s.pocketCatalog?.find(p => p.key === key)?.name || key;
|
export const rowLabel = (s: LedgerState, key?: string) => s.pocketCatalog?.find(p => p.key === key)?.name || key;
|
||||||
export function options(pairs) {
|
export function options(pairs: readonly Choice[]) {
|
||||||
return pairs.map(opt => {
|
return pairs.map(opt => {
|
||||||
const [value, text, disabled] = Array.isArray(opt) ? opt : [opt, opt];
|
const [value, text, disabled] = typeof opt === 'string' ? [opt, opt] : opt;
|
||||||
return (
|
return (
|
||||||
<option key={value} value={value} disabled={!!disabled}>
|
<option key={String(value)} value={String(value)} disabled={!!disabled}>
|
||||||
{text}
|
{text}
|
||||||
</option>
|
</option>
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
export function Head({ eye, title, sub, children }) {
|
export function Head({ eye, title, sub, children }: { eye: string; title: string; sub: string; children?: ReactNode }) {
|
||||||
return (
|
return (
|
||||||
<header className="page-heading">
|
<header className="page-heading">
|
||||||
<div>
|
<div>
|
||||||
@@ -25,10 +29,22 @@ export function Head({ eye, title, sub, children }) {
|
|||||||
</header>
|
</header>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
export function Modal({ id, title, close, action, children }) {
|
export function Modal({
|
||||||
const ref = useRef(null);
|
id,
|
||||||
|
title,
|
||||||
|
close,
|
||||||
|
action,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
id: string;
|
||||||
|
title: string;
|
||||||
|
close(): void;
|
||||||
|
action: string;
|
||||||
|
children: ReactNode;
|
||||||
|
}) {
|
||||||
|
const ref = useRef<HTMLDialogElement>(null);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const d = ref.current;
|
const d = ref.current!;
|
||||||
d.showModal();
|
d.showModal();
|
||||||
return () => d.close();
|
return () => d.close();
|
||||||
}, []);
|
}, []);
|
||||||
@@ -49,7 +65,7 @@ export function Modal({ id, title, close, action, children }) {
|
|||||||
</dialog>
|
</dialog>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
export function Settlement({ q, draft, input }) {
|
export function Settlement({ q, draft, input }: { q?: Totals | null; draft?: Draft; input?: Partial<Input> | null }) {
|
||||||
if (!q) return null;
|
if (!q) return null;
|
||||||
const direct = input?.mode === 'direct' || draft?.mode === 'direct' || q.mode === 'direct',
|
const direct = input?.mode === 'direct' || draft?.mode === 'direct' || q.mode === 'direct',
|
||||||
def = q.defaultPurchaseAmount ?? q.calculatedPurchaseAmount ?? q.purchaseAmount;
|
def = q.defaultPurchaseAmount ?? q.calculatedPurchaseAmount ?? q.purchaseAmount;
|
||||||
@@ -141,9 +157,9 @@ export function Settlement({ q, draft, input }) {
|
|||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
export function pocketOptions(state, key, historical, blank) {
|
export function pocketOptions(state: LedgerState, key: string, historical: boolean, blank?: string) {
|
||||||
const active = Model.activePocketKeys(state),
|
const active = Model.activePocketKeys(state),
|
||||||
result = active.map(p => [p, rowLabel(state, p)]);
|
result: (string | boolean)[][] = active.map(p => [p, rowLabel(state, p) || p]);
|
||||||
if (key && !active.includes(key))
|
if (key && !active.includes(key))
|
||||||
result.push([
|
result.push([
|
||||||
key,
|
key,
|
||||||
@@ -152,14 +168,14 @@ export function pocketOptions(state, key, historical, blank) {
|
|||||||
]);
|
]);
|
||||||
return blank ? [['', blank], ...result] : result;
|
return blank ? [['', blank], ...result] : result;
|
||||||
}
|
}
|
||||||
export function loadDraft(key) {
|
export function loadDraft<T>(key: string): T | null {
|
||||||
try {
|
try {
|
||||||
return JSON.parse(localStorage.getItem(key) || 'null');
|
return JSON.parse(localStorage.getItem(key) || 'null');
|
||||||
} catch {
|
} catch {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
export function LegacyCount({ value }) {
|
export function LegacyCount({ value }: { value?: Permission }) {
|
||||||
return value?.requiresLegacyCountVerified ? (
|
return value?.requiresLegacyCountVerified ? (
|
||||||
<>
|
<>
|
||||||
<p>{value.legacyCountNotice || '这笔历史记录未记录对数,当前对数按实际盘点基准保留。'}</p>
|
<p>{value.legacyCountNotice || '这笔历史记录未记录对数,当前对数按实际盘点基准保留。'}</p>
|
||||||
+21
-4
@@ -1,10 +1,20 @@
|
|||||||
|
import type { LedgerClient } from '../../lib/api';
|
||||||
|
import type { LedgerState } from '../../shared';
|
||||||
|
import type { Input, Draft, EditDetail, Calculation, QuoteItem, MaterialPool, RecoveryModel } from './types';
|
||||||
import { Calc, Model } from '../../shared';
|
import { Calc, Model } from '../../shared';
|
||||||
import { grams } from '../../lib/format';
|
import { grams } from '../../lib/format';
|
||||||
import { describeMaterialBalance, describeMaterialSources, validateMaterialQuote } from '../../lib/materialQuote';
|
import { describeMaterialBalance, describeMaterialSources, validateMaterialQuote } from '../../lib/materialQuote';
|
||||||
import { money } from './controls';
|
import { money } from './controls';
|
||||||
|
|
||||||
// 与结算报价分开读取料池余额。余额暂不可用时仍可核对已算出的来源、成本和结算。
|
// 与结算报价分开读取料池余额。余额暂不可用时仍可核对已算出的来源、成本和结算。
|
||||||
export async function quotedMaterialNote(client, state, input, result, differenceMg, edit) {
|
export async function quotedMaterialNote(
|
||||||
|
client: LedgerClient,
|
||||||
|
state: LedgerState,
|
||||||
|
input: Input,
|
||||||
|
result: QuoteItem,
|
||||||
|
differenceMg: number,
|
||||||
|
edit: EditDetail | null,
|
||||||
|
) {
|
||||||
const material = input.exchange?.cost_material;
|
const material = input.exchange?.cost_material;
|
||||||
if (material?.mode !== 'pool') return '';
|
if (material?.mode !== 'pool') return '';
|
||||||
const sources = result.exchange?.costMaterial?.materialSources;
|
const sources = result.exchange?.costMaterial?.materialSources;
|
||||||
@@ -25,7 +35,7 @@ export async function quotedMaterialNote(client, state, input, result, differenc
|
|||||||
result.member !== input.member ||
|
result.member !== input.member ||
|
||||||
sources.some(s => s.kind === 'personal_recovery' && s.member !== input.member) ||
|
sources.some(s => s.kind === 'personal_recovery' && s.member !== input.member) ||
|
||||||
sources.reduce((sum, s) => sum + s.quantity, 0) !== differenceMg ||
|
sources.reduce((sum, s) => sum + s.quantity, 0) !== differenceMg ||
|
||||||
(result.materialCost !== null && sources.reduce((sum, s) => sum + s.amount, 0) !== result.materialCost)
|
(result.materialCost !== null && sources.reduce((sum, s) => sum + (s.amount ?? 0), 0) !== result.materialCost)
|
||||||
)
|
)
|
||||||
throw new Error('置换用料来源与当前归属不一致,请重新核对。');
|
throw new Error('置换用料来源与当前归属不一致,请重新核对。');
|
||||||
const request = {
|
const request = {
|
||||||
@@ -43,14 +53,21 @@ export async function quotedMaterialNote(client, state, input, result, differenc
|
|||||||
balance = '个人与公共余量暂未读到,请刷新核对。';
|
balance = '个人与公共余量暂未读到,请刷新核对。';
|
||||||
}
|
}
|
||||||
return (
|
return (
|
||||||
describeMaterialSources(sources, key => Model.memberName(state, key)) +
|
describeMaterialSources(sources, (key: string) => Model.memberName(state, key)) +
|
||||||
';' +
|
';' +
|
||||||
balance +
|
balance +
|
||||||
(edit ? '原单耗用已排除。' : '')
|
(edit ? '原单耗用已排除。' : '')
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function localMaterialNote(draft, calculation, pools, state, model, edit) {
|
export function localMaterialNote(
|
||||||
|
draft: Draft,
|
||||||
|
calculation: Calculation | null,
|
||||||
|
pools: MaterialPool[],
|
||||||
|
state: LedgerState,
|
||||||
|
model: RecoveryModel,
|
||||||
|
edit: EditDetail | null,
|
||||||
|
) {
|
||||||
if (!calculation || draft.mode !== 'exchange') return '填写新旧克重后显示差重料费。';
|
if (!calculation || draft.mode !== 'exchange') return '填写新旧克重后显示差重料费。';
|
||||||
const { differenceMg, matchedMg } = calculation;
|
const { differenceMg, matchedMg } = calculation;
|
||||||
if (!differenceMg) return '等重交换 ' + grams(matchedMg) + 'g,只记实物;无补金差重,不耗用每日料池。';
|
if (!differenceMg) return '等重交换 ' + grams(matchedMg) + 'g,只记实物;无补金差重,不耗用每日料池。';
|
||||||
@@ -1,10 +1,12 @@
|
|||||||
|
import type { LedgerState } from '../../shared';
|
||||||
|
import type { EditDetail } from './types';
|
||||||
import RecoveryRules from '@public/recovery-rules.js';
|
import RecoveryRules from '@public/recovery-rules.js';
|
||||||
import { Model, Calc, Values } from '../../shared';
|
import { Model, Calc, Values } from '../../shared';
|
||||||
import { countValue, dateValid as validOrderDate } from '../Inventory/data';
|
import { countValue, dateValid as validOrderDate } from '../Inventory/data';
|
||||||
|
|
||||||
export const memberAccountPrefix = Values.memberAccountPrefix;
|
export const memberAccountPrefix = Values.memberAccountPrefix;
|
||||||
|
|
||||||
export function recoveryModel(state, editData = null) {
|
export function recoveryModel(state: LedgerState, editData: EditDetail | null = null) {
|
||||||
return RecoveryRules.createModel({
|
return RecoveryRules.createModel({
|
||||||
state,
|
state,
|
||||||
originalInput: editData?.inputs,
|
originalInput: editData?.inputs,
|
||||||
@@ -0,0 +1,366 @@
|
|||||||
|
import type { LedgerClient } from '../../lib/api';
|
||||||
|
import type { LedgerState } from '../../shared';
|
||||||
|
|
||||||
|
export interface PageProps {
|
||||||
|
client: LedgerClient;
|
||||||
|
state: LedgerState;
|
||||||
|
}
|
||||||
|
export type Mode = 'direct' | 'exchange';
|
||||||
|
export type Filters = { from: string; date: string; mode: string; member: string };
|
||||||
|
export interface OldLine {
|
||||||
|
name: string;
|
||||||
|
incoming_weight: string;
|
||||||
|
melted_weight: string;
|
||||||
|
purity: string;
|
||||||
|
}
|
||||||
|
export interface Charge {
|
||||||
|
name: string;
|
||||||
|
amount: string;
|
||||||
|
}
|
||||||
|
export interface Fee {
|
||||||
|
key: string;
|
||||||
|
note: string;
|
||||||
|
amount: string;
|
||||||
|
payer: string;
|
||||||
|
}
|
||||||
|
export type ExtraRow = OldLine | Charge | Fee;
|
||||||
|
export type ProductDraft = Pick<
|
||||||
|
Draft,
|
||||||
|
| 'new_name'
|
||||||
|
| 'new_quantity'
|
||||||
|
| 'pocket'
|
||||||
|
| 'stockCount'
|
||||||
|
| 'labor_mode'
|
||||||
|
| 'labor_rate'
|
||||||
|
| 'cost_labor_mode'
|
||||||
|
| 'cost_labor_value'
|
||||||
|
| 'labor_payer'
|
||||||
|
> &
|
||||||
|
Partial<Draft>;
|
||||||
|
export interface Draft {
|
||||||
|
mode: Mode;
|
||||||
|
date: string;
|
||||||
|
customer: string;
|
||||||
|
customer_type?: string;
|
||||||
|
salesperson: string;
|
||||||
|
member: string;
|
||||||
|
note: string;
|
||||||
|
old_name: string;
|
||||||
|
incoming_weight: string;
|
||||||
|
melted_weight: string;
|
||||||
|
purity: string;
|
||||||
|
old_pocket: string;
|
||||||
|
old_stock_count: string | number;
|
||||||
|
old_source: string;
|
||||||
|
deposit_id: string;
|
||||||
|
deposit_weight: string;
|
||||||
|
surplus_mode: string;
|
||||||
|
surplus_memo: string;
|
||||||
|
buy_rate: string;
|
||||||
|
buy_total: string;
|
||||||
|
new_name: string;
|
||||||
|
new_quantity: string;
|
||||||
|
pocket: string;
|
||||||
|
stockCount: string | number;
|
||||||
|
gold_price: string;
|
||||||
|
labor_mode: string;
|
||||||
|
labor_rate: string;
|
||||||
|
depreciation_weight: string;
|
||||||
|
depreciation_rate: string;
|
||||||
|
discount: string;
|
||||||
|
rounding_mode: string;
|
||||||
|
material_source: string;
|
||||||
|
material_pool_id: string;
|
||||||
|
material_rate: string;
|
||||||
|
material_payer: string;
|
||||||
|
labor_payer: string;
|
||||||
|
cost_payer?: string;
|
||||||
|
cost_labor_mode: string;
|
||||||
|
cost_labor_value: string;
|
||||||
|
fee_note: string;
|
||||||
|
fee_amount: string;
|
||||||
|
fee_payer: string;
|
||||||
|
charge_name: string;
|
||||||
|
charge_amount: string;
|
||||||
|
payment_method: string;
|
||||||
|
payment_recipient: string;
|
||||||
|
payout_method: string;
|
||||||
|
payer: string;
|
||||||
|
buy_total_manual: boolean;
|
||||||
|
depreciation_manual: boolean;
|
||||||
|
melted_manual: boolean;
|
||||||
|
independent_products: boolean;
|
||||||
|
verified?: boolean;
|
||||||
|
change_reason?: string;
|
||||||
|
shared_old_notice?: string;
|
||||||
|
folded_weight?: string;
|
||||||
|
extra_products?: ProductDraft[];
|
||||||
|
old_lines?: OldLine[];
|
||||||
|
charges?: Charge[];
|
||||||
|
fee_items?: Fee[];
|
||||||
|
}
|
||||||
|
export type TextField = {
|
||||||
|
[K in keyof Draft]-?: NonNullable<Draft[K]> extends string | number ? K : never;
|
||||||
|
}[keyof Draft];
|
||||||
|
export type Labor = { mode: 'gram'; rate: string; amount?: never } | { mode: 'total'; amount: string; rate?: never };
|
||||||
|
export type Material = { mode: 'pool'; poolId: string; rate?: never } | { mode: 'gram'; rate: string; poolId?: never };
|
||||||
|
export interface Product {
|
||||||
|
name: string;
|
||||||
|
pocket: string;
|
||||||
|
quantity: string;
|
||||||
|
labor_rate: string;
|
||||||
|
labor_mode: string;
|
||||||
|
stockCount?: number | string | null;
|
||||||
|
cost_labor?: Labor;
|
||||||
|
cost_labor_payer: string;
|
||||||
|
}
|
||||||
|
export interface Exchange extends Partial<Product> {
|
||||||
|
gold_price?: string;
|
||||||
|
depreciation_rate?: string;
|
||||||
|
depreciation_weight?: string;
|
||||||
|
discount: string;
|
||||||
|
rounding_mode: string;
|
||||||
|
cost_payer?: string;
|
||||||
|
cost_material?: Material;
|
||||||
|
cost_material_payer?: string;
|
||||||
|
charges: Charge[];
|
||||||
|
fee_items: Fee[];
|
||||||
|
items?: ItemInput[];
|
||||||
|
products?: Product[];
|
||||||
|
}
|
||||||
|
export interface ItemInput {
|
||||||
|
old_source?: string;
|
||||||
|
deposit_id?: string;
|
||||||
|
deposit_weight?: string;
|
||||||
|
old_lines: OldLine[];
|
||||||
|
old_pocket: string;
|
||||||
|
old_stock_count?: string | number | null;
|
||||||
|
surplus_mode?: string;
|
||||||
|
surplus_memo?: string;
|
||||||
|
buy_rate: string;
|
||||||
|
buy_total?: string;
|
||||||
|
exchange: Exchange;
|
||||||
|
}
|
||||||
|
export interface Input extends Omit<ItemInput, 'exchange'> {
|
||||||
|
mode: Mode;
|
||||||
|
date: string;
|
||||||
|
customer: string;
|
||||||
|
customer_type?: string;
|
||||||
|
salesperson: string;
|
||||||
|
member: string;
|
||||||
|
note: string;
|
||||||
|
payer: string;
|
||||||
|
payment_account: string;
|
||||||
|
verified: boolean;
|
||||||
|
exchange?: Exchange;
|
||||||
|
}
|
||||||
|
export interface Totals {
|
||||||
|
mode: Mode;
|
||||||
|
oldMg: number;
|
||||||
|
newMg: number;
|
||||||
|
matchedMg: number;
|
||||||
|
surplusMg: number;
|
||||||
|
depositMg: number;
|
||||||
|
differenceMg: number;
|
||||||
|
depreciationMg: number;
|
||||||
|
depreciationAmount: number;
|
||||||
|
chargesAmount: number;
|
||||||
|
discount: number;
|
||||||
|
receivable: number;
|
||||||
|
purchaseAmount: number;
|
||||||
|
goldAmount: number;
|
||||||
|
laborAmount: number;
|
||||||
|
roundingAdjustment: number;
|
||||||
|
netSettlement: number;
|
||||||
|
cashReceipt: number;
|
||||||
|
cashPayment: number;
|
||||||
|
defaultPurchaseAmount?: number;
|
||||||
|
calculatedPurchaseAmount?: number;
|
||||||
|
old_lines: { name: string; incomingMg: number; meltedMg: number; foldedMg: number; purity: number }[];
|
||||||
|
newProduct?: { name: string };
|
||||||
|
exchangeItems?: Totals[];
|
||||||
|
}
|
||||||
|
export interface Calculation extends Totals {
|
||||||
|
defaultPurchaseAmount: number;
|
||||||
|
purchaseMg: number;
|
||||||
|
}
|
||||||
|
export interface Source {
|
||||||
|
kind: 'personal_recovery' | 'public';
|
||||||
|
member?: string;
|
||||||
|
quantity: number;
|
||||||
|
amount: number | null;
|
||||||
|
averageRate?: number | null;
|
||||||
|
allocations: { payer: string; amount: number }[];
|
||||||
|
}
|
||||||
|
export interface QuoteItem extends Totals {
|
||||||
|
member: string;
|
||||||
|
materialCost: number | null;
|
||||||
|
laborCost: number | null;
|
||||||
|
exchange?: {
|
||||||
|
costMaterial?: { mode: string; materialSources?: Source[] };
|
||||||
|
costPayers?: { labor: string; material: string };
|
||||||
|
fee_items?: { note: string; amount: number; payer: string }[];
|
||||||
|
};
|
||||||
|
customerDeposit?: { number: string; mg: number };
|
||||||
|
exchangeItems?: QuoteItem[];
|
||||||
|
}
|
||||||
|
export interface SummaryRow {
|
||||||
|
id: string;
|
||||||
|
mode: Mode;
|
||||||
|
number: string;
|
||||||
|
date: string;
|
||||||
|
customer: string;
|
||||||
|
salesperson: string;
|
||||||
|
member: string;
|
||||||
|
oldMg: number;
|
||||||
|
newMg: number;
|
||||||
|
netSettlement: number;
|
||||||
|
printStatus?: { id: string; printed: boolean };
|
||||||
|
}
|
||||||
|
interface SavedProduct {
|
||||||
|
name: string;
|
||||||
|
quantity: number;
|
||||||
|
pocket: string;
|
||||||
|
stockCount?: number | null;
|
||||||
|
laborAmount?: number;
|
||||||
|
laborCost: number | null;
|
||||||
|
laborPayer: string;
|
||||||
|
}
|
||||||
|
export interface RecoveryRecord extends SummaryRow, QuoteItem {
|
||||||
|
status: string;
|
||||||
|
order_id?: string;
|
||||||
|
purchase_id?: string;
|
||||||
|
credit_card_rate_permille?: number | null;
|
||||||
|
payment_account: string;
|
||||||
|
payer: string;
|
||||||
|
note: string;
|
||||||
|
oldPocket: string;
|
||||||
|
newProduct?: SavedProduct;
|
||||||
|
newProducts?: SavedProduct[];
|
||||||
|
profit: number | null;
|
||||||
|
materialCostPending?: boolean;
|
||||||
|
cardFee?: number;
|
||||||
|
materialBatch?: { member: string; mg: number; usedMg: number; remainingMg: number };
|
||||||
|
}
|
||||||
|
export interface Permission {
|
||||||
|
canCancel: boolean;
|
||||||
|
canEdit: boolean;
|
||||||
|
canDirect: boolean;
|
||||||
|
requiresApproval: boolean;
|
||||||
|
reason?: string;
|
||||||
|
requiresLegacyCountVerified?: boolean;
|
||||||
|
legacyCountNotice?: string;
|
||||||
|
}
|
||||||
|
export interface EditDetail {
|
||||||
|
id: string;
|
||||||
|
revision: number;
|
||||||
|
status: string;
|
||||||
|
record: RecoveryRecord;
|
||||||
|
inputs: Input;
|
||||||
|
permissions: Permission;
|
||||||
|
pending: ChangeRequest | null;
|
||||||
|
history: ChangeRequest[];
|
||||||
|
blockedUsages: { anonymous?: boolean; number?: string; mg: number; priceLockId?: string; orderId?: string }[];
|
||||||
|
}
|
||||||
|
export type ChangeStatus = 'pending' | 'approved' | 'rejected';
|
||||||
|
export type MoneySummary = Partial<
|
||||||
|
Record<'cashReceipt' | 'cashPayment' | 'purchaseAmount' | 'goodsCost' | 'directCost' | 'profit', number | null>
|
||||||
|
>;
|
||||||
|
export interface ChangeRequest {
|
||||||
|
id: string;
|
||||||
|
recoveryId: string;
|
||||||
|
member: string;
|
||||||
|
recoveryRevision: number;
|
||||||
|
revision: number;
|
||||||
|
status: ChangeStatus;
|
||||||
|
action: 'cancel' | 'update';
|
||||||
|
before: Input;
|
||||||
|
after: Input | null;
|
||||||
|
requesterName: string;
|
||||||
|
reviewerName?: string;
|
||||||
|
reason: string;
|
||||||
|
note?: string;
|
||||||
|
canApprove: boolean;
|
||||||
|
stale: boolean;
|
||||||
|
summary: { before?: MoneySummary; after?: MoneySummary; legacyCountNotice?: string; legacyCountVerified?: boolean };
|
||||||
|
}
|
||||||
|
export interface ChangeList {
|
||||||
|
requests: ChangeRequest[];
|
||||||
|
counts: Record<ChangeStatus, number>;
|
||||||
|
}
|
||||||
|
export type Selection = { kind: 'list'; id?: undefined } | { kind: 'request' | 'cancel'; id: string };
|
||||||
|
export interface Saved {
|
||||||
|
id: string;
|
||||||
|
number?: string;
|
||||||
|
pending?: boolean;
|
||||||
|
applied?: boolean;
|
||||||
|
}
|
||||||
|
export interface Deposit {
|
||||||
|
id: string;
|
||||||
|
date: string;
|
||||||
|
number: string;
|
||||||
|
memo: string;
|
||||||
|
mg: number;
|
||||||
|
usedMg: number;
|
||||||
|
remainingMg: number;
|
||||||
|
voided?: boolean;
|
||||||
|
actor: string;
|
||||||
|
events: { date: string; memo: string; deltaMg: number; actor: string }[];
|
||||||
|
}
|
||||||
|
export interface DepositListData {
|
||||||
|
rows: Deposit[];
|
||||||
|
remainingMg: number;
|
||||||
|
totalMg: number;
|
||||||
|
usedMg: number;
|
||||||
|
}
|
||||||
|
export interface MaterialPool {
|
||||||
|
id: string;
|
||||||
|
date: string;
|
||||||
|
remainingMg: number;
|
||||||
|
totalMg: number;
|
||||||
|
totalAmount: number | null;
|
||||||
|
usages: { active: boolean; mg: number; order_id?: string; line_index: number }[];
|
||||||
|
personalPools?: Record<string, { remainingMg: number }>;
|
||||||
|
}
|
||||||
|
export type PoolChoice = Pick<MaterialPool, 'id' | 'date' | 'totalMg' | 'remainingMg' | 'personalPools'>;
|
||||||
|
export interface RecoveryContext {
|
||||||
|
state: LedgerState;
|
||||||
|
originalInput?: Input | null;
|
||||||
|
currentMember(): string;
|
||||||
|
defaultSalesperson(): string;
|
||||||
|
teamMemberKeys(): string[];
|
||||||
|
activePocketKeys(): string[];
|
||||||
|
pocketCountsEnabled(pocket: string): boolean;
|
||||||
|
stockCountValue(value: unknown, options?: { optional?: boolean; title?: string }): number | null;
|
||||||
|
validOrderDate(value: string): boolean;
|
||||||
|
isCreditCardAccount(account: string): boolean;
|
||||||
|
memberAccountPrefix(member: string): string;
|
||||||
|
accountIdentity(account: string): { member: string; channel: string } | null;
|
||||||
|
isSilver(name: string): boolean;
|
||||||
|
}
|
||||||
|
export interface RecoveryModel {
|
||||||
|
defaults(mode?: Mode): Draft;
|
||||||
|
sharedDraft(draft: Draft): Draft;
|
||||||
|
forEdit(input: Input): Draft;
|
||||||
|
input(draft: Draft, options?: { quote?: boolean }): Input;
|
||||||
|
calculate(input: Input): Calculation;
|
||||||
|
validate(input: Input): Input;
|
||||||
|
newWeight(draft: Draft): number;
|
||||||
|
units(value: unknown, places: number, title: string, options?: { zero?: boolean }): number;
|
||||||
|
multiply(weight: number, rate: number): number;
|
||||||
|
checkEdit(data: unknown, id: string): EditDetail;
|
||||||
|
checkRequest(data: unknown): ChangeRequest;
|
||||||
|
}
|
||||||
|
export interface Derived {
|
||||||
|
draft: Draft;
|
||||||
|
parts?: Derived[];
|
||||||
|
input: Input | null;
|
||||||
|
q: Calculation | null;
|
||||||
|
error: string;
|
||||||
|
old?: Calculation | null;
|
||||||
|
newMg?: number | null;
|
||||||
|
hasBuy?: boolean;
|
||||||
|
diff?: boolean;
|
||||||
|
}
|
||||||
|
export type ExtraKinds = { old: OldLine; charge: Charge; fee: Fee };
|
||||||
|
export type ExtraFields<K extends keyof ExtraKinds> = [Extract<keyof ExtraKinds[K], string>, string][];
|
||||||
+122
-31
@@ -1,28 +1,96 @@
|
|||||||
import { useEffect, useRef, useState } from 'react';
|
import type { FormEvent, RefObject } from 'react';
|
||||||
|
import type { LedgerClient } from '../../lib/api';
|
||||||
|
import type { LedgerState } from '../../shared';
|
||||||
|
import type {
|
||||||
|
DailyFunds,
|
||||||
|
ReportQuery,
|
||||||
|
Range,
|
||||||
|
ReportAction,
|
||||||
|
ReimbursementList,
|
||||||
|
Reimbursement,
|
||||||
|
ReimbursementItem,
|
||||||
|
Confirmation,
|
||||||
|
} from './contracts';
|
||||||
|
import type { reportPresentation } from './presentation';
|
||||||
|
import { useEffect, useEffectEvent, useLayoutEffect, useRef, useState } from 'react';
|
||||||
import { Calc, Model } from '../../shared';
|
import { Calc, Model } from '../../shared';
|
||||||
import { Button, Choice, Dialog, Field } from '../Settings/controls';
|
import { Button, Choice, Dialog, Field } from '../Settings/controls';
|
||||||
import { errorText } from '../Settings/settingsModel';
|
import { errorText } from '../Settings/settingsModel';
|
||||||
|
|
||||||
const draftsByClient = new WeakMap();
|
type View = ReturnType<typeof reportPresentation>;
|
||||||
function draftsFor(client, user) {
|
type DraftItem = Omit<ReimbursementItem, 'amount'> & { amount: string };
|
||||||
|
interface Draft {
|
||||||
|
id: string;
|
||||||
|
revision?: number;
|
||||||
|
date: string;
|
||||||
|
items: DraftItem[];
|
||||||
|
payer?: string;
|
||||||
|
note: string;
|
||||||
|
}
|
||||||
|
interface Review {
|
||||||
|
id: string;
|
||||||
|
revision: number;
|
||||||
|
kind: 'approve' | 'reject';
|
||||||
|
note: string;
|
||||||
|
verified: boolean;
|
||||||
|
}
|
||||||
|
interface Outlay {
|
||||||
|
amount: string;
|
||||||
|
note: string;
|
||||||
|
verified: boolean;
|
||||||
|
editing: boolean;
|
||||||
|
revision: number;
|
||||||
|
sourceRevision: string;
|
||||||
|
}
|
||||||
|
interface Drafts {
|
||||||
|
user: string;
|
||||||
|
forms: Map<string, Draft>;
|
||||||
|
editors: Map<string, string>;
|
||||||
|
reviews: Map<string, Review>;
|
||||||
|
outlays: Map<string, Outlay>;
|
||||||
|
}
|
||||||
|
interface Props {
|
||||||
|
client: LedgerClient;
|
||||||
|
state: LedgerState;
|
||||||
|
view: View;
|
||||||
|
data: DailyFunds;
|
||||||
|
query: ReportQuery & Range;
|
||||||
|
changeDate: (date: string, reviewId?: string) => void;
|
||||||
|
reload: () => void;
|
||||||
|
notify: (text: string, error?: boolean) => void;
|
||||||
|
actionRef: RefObject<((data: ReportAction) => void) | null>;
|
||||||
|
}
|
||||||
|
interface PageReply {
|
||||||
|
query: { offset: number };
|
||||||
|
list?: ReimbursementList;
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
type FormKind = 'outlay' | 'draft' | 'review';
|
||||||
|
type FormError = { kind: FormKind; text: string; conflict?: boolean };
|
||||||
|
const draftsByClient = new WeakMap<LedgerClient, Drafts>();
|
||||||
|
function draftsFor(client: LedgerClient, user: string) {
|
||||||
const current = draftsByClient.get(client);
|
const current = draftsByClient.get(client);
|
||||||
if (current?.user === user) return current;
|
if (current?.user === user) return current;
|
||||||
const drafts = { user, forms: new Map(), editors: new Map(), reviews: new Map(), outlays: new Map() };
|
const drafts: Drafts = { user, forms: new Map(), editors: new Map(), reviews: new Map(), outlays: new Map() };
|
||||||
draftsByClient.set(client, drafts);
|
draftsByClient.set(client, drafts);
|
||||||
return drafts;
|
return drafts;
|
||||||
}
|
}
|
||||||
function newItem(team) {
|
function newItem(team: boolean): DraftItem {
|
||||||
return {
|
return {
|
||||||
name: '',
|
name: '',
|
||||||
amount: '',
|
amount: '',
|
||||||
...(team ? { member: 'owner', sourceType: 'independent', sourceKey: crypto.randomUUID() } : {}),
|
...(team ? { member: 'owner', sourceType: 'independent', sourceKey: crypto.randomUUID() } : {}),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
function PendingList({ client, view, close, openDate }) {
|
function PendingList({
|
||||||
|
client,
|
||||||
|
view,
|
||||||
|
close,
|
||||||
|
openDate,
|
||||||
|
}: Pick<Props, 'client' | 'view'> & { close: () => void; openDate: (row: Reimbursement) => void }) {
|
||||||
const [query, setQuery] = useState({ offset: 0 }),
|
const [query, setQuery] = useState({ offset: 0 }),
|
||||||
[result, setResult] = useState(null);
|
[result, setResult] = useState<PageReply | null>(null);
|
||||||
const validate = useRef(view.validateDailyReimbursements);
|
const validate = useEffectEvent((data: unknown) => view.validateDailyReimbursements(data));
|
||||||
validate.current = view.validateDailyReimbursements;
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let current = true;
|
let current = true;
|
||||||
client
|
client
|
||||||
@@ -30,7 +98,7 @@ function PendingList({ client, view, close, openDate }) {
|
|||||||
'/api/reimbursements?' + new URLSearchParams({ status: 'pending', limit: '50', offset: String(query.offset) }),
|
'/api/reimbursements?' + new URLSearchParams({ status: 'pending', limit: '50', offset: String(query.offset) }),
|
||||||
)
|
)
|
||||||
.then(data => {
|
.then(data => {
|
||||||
const list = validate.current(data);
|
const list = validate(data);
|
||||||
if (current) setResult({ query, list });
|
if (current) setResult({ query, list });
|
||||||
})
|
})
|
||||||
.catch(error => {
|
.catch(error => {
|
||||||
@@ -134,27 +202,29 @@ function PendingList({ client, view, close, openDate }) {
|
|||||||
</Dialog>
|
</Dialog>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
export function Reimbursements({ client, state, view, data, query, changeDate, reload, notify, actionRef }) {
|
export function Reimbursements({ client, state, view, data, query, changeDate, reload, notify, actionRef }: Props) {
|
||||||
const cache = draftsFor(client, state.user.id),
|
const cache = draftsFor(client, state.user.id),
|
||||||
key = [state.user.id, query.from, query.date, query.month].join('|');
|
key = [state.user.id, query.from, query.date, query.month].join('|');
|
||||||
const [, setTick] = useState(0),
|
const [, setTick] = useState(0),
|
||||||
[list, setList] = useState(false),
|
[list, setList] = useState(false),
|
||||||
[error, setError] = useState(null);
|
[error, setError] = useState<FormError | null>(null);
|
||||||
const redraw = () => setTick(v => v + 1);
|
const redraw = () => setTick(v => v + 1);
|
||||||
const team = view.teamMode(),
|
const team = view.teamMode(),
|
||||||
owner = state.user.role === 'owner',
|
owner = state.user.role === 'owner',
|
||||||
month = query.month || data?.readOnly;
|
month = query.month || data?.readOnly;
|
||||||
const blocked = client.busy || !!client.pending() || !data;
|
const blocked = client.busy || !!client.pending() || !data;
|
||||||
const formKey = cache.editors.get(key),
|
const formKey = cache.editors.get(key),
|
||||||
draft = cache.forms.get(formKey),
|
draft = formKey ? cache.forms.get(formKey) : undefined,
|
||||||
review = cache.reviews.get(key);
|
review = cache.reviews.get(key);
|
||||||
const row = data?.reimbursements.find(r => r.id === review?.id),
|
const row = data?.reimbursements.find(r => r.id === review?.id),
|
||||||
active = state.user.member || view.currentMember();
|
active = state.user.member || view.currentMember();
|
||||||
const memberOptions = view.teamMemberOptions(),
|
const memberOptions = view.teamMemberOptions(),
|
||||||
memberName = id => (state.members || []).find(m => m.member === id)?.label || id;
|
memberName = (id?: string) => (state.members || []).find(m => m.member === id)?.label || id;
|
||||||
const period = query.month ? query.from + ' 至 ' + query.date : query.date;
|
const period = query.month ? query.from + ' 至 ' + query.date : query.date;
|
||||||
const currentView = useRef(key);
|
const currentView = useRef(key);
|
||||||
currentView.current = key;
|
useLayoutEffect(() => {
|
||||||
|
currentView.current = key;
|
||||||
|
}, [key]);
|
||||||
const out = cache.outlays.get(key);
|
const out = cache.outlays.get(key);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!data) return;
|
if (!data) return;
|
||||||
@@ -187,9 +257,9 @@ export function Reimbursements({ client, state, view, data, query, changeDate, r
|
|||||||
}
|
}
|
||||||
redraw();
|
redraw();
|
||||||
}, [data, key, cache, owner, query.month, query.reviewId]);
|
}, [data, key, cache, owner, query.month, query.reviewId]);
|
||||||
function action({ action, id, date }) {
|
function action({ action, id, date }: ReportAction) {
|
||||||
if (action === 'daily-funds-open-date') {
|
if (action === 'daily-funds-open-date') {
|
||||||
changeDate(date);
|
if (date) changeDate(date);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (action === 'reimbursement-open-list') {
|
if (action === 'reimbursement-open-list') {
|
||||||
@@ -223,7 +293,7 @@ export function Reimbursements({ client, state, view, data, query, changeDate, r
|
|||||||
if (action === 'reimbursement-approve' || action === 'reimbursement-reject') {
|
if (action === 'reimbursement-approve' || action === 'reimbursement-reject') {
|
||||||
if (!owner || !record?.canApprove || record.status !== 'pending') return;
|
if (!owner || !record?.canApprove || record.status !== 'pending') return;
|
||||||
cache.reviews.set(key, {
|
cache.reviews.set(key, {
|
||||||
id,
|
id: record.id,
|
||||||
revision: record.revision,
|
revision: record.revision,
|
||||||
kind: action === 'reimbursement-approve' ? 'approve' : 'reject',
|
kind: action === 'reimbursement-approve' ? 'approve' : 'reject',
|
||||||
note: '',
|
note: '',
|
||||||
@@ -243,14 +313,24 @@ export function Reimbursements({ client, state, view, data, query, changeDate, r
|
|||||||
actionRef.current = null;
|
actionRef.current = null;
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
function set(obj, field, value) {
|
function set<O, K extends keyof O>(obj: O, field: K, value: O[K]) {
|
||||||
obj[field] = value;
|
obj[field] = value;
|
||||||
redraw();
|
redraw();
|
||||||
}
|
}
|
||||||
async function submit(event, kind) {
|
async function submit(event: FormEvent, kind: FormKind) {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
if (blocked || month) return;
|
if (blocked || month) return;
|
||||||
let url, input, notice;
|
let url: string, notice: string;
|
||||||
|
let input: {
|
||||||
|
date?: string;
|
||||||
|
revision?: number;
|
||||||
|
note: string;
|
||||||
|
verified?: boolean;
|
||||||
|
amount?: string;
|
||||||
|
sourceRevision?: string;
|
||||||
|
payer?: string;
|
||||||
|
items?: DraftItem[];
|
||||||
|
};
|
||||||
try {
|
try {
|
||||||
if (kind === 'outlay') {
|
if (kind === 'outlay') {
|
||||||
if (!owner || !out) throw new Error('完整支出由店主确认。');
|
if (!owner || !out) throw new Error('完整支出由店主确认。');
|
||||||
@@ -305,7 +385,7 @@ export function Reimbursements({ client, state, view, data, query, changeDate, r
|
|||||||
};
|
};
|
||||||
notice = '报销单已提交,等待店主复核';
|
notice = '报销单已提交,等待店主复核';
|
||||||
} else {
|
} else {
|
||||||
if (!owner || !row?.canApprove || row.status !== 'pending' || row.revision !== review.revision)
|
if (!review || !owner || !row?.canApprove || row.status !== 'pending' || row.revision !== review.revision)
|
||||||
throw new Error('报销单已变化,请重新读取后复核。');
|
throw new Error('报销单已变化,请重新读取后复核。');
|
||||||
const note = review.note.trim();
|
const note = review.note.trim();
|
||||||
if (note.length > 300 || (review.kind === 'reject' && !note))
|
if (note.length > 300 || (review.kind === 'reject' && !note))
|
||||||
@@ -321,13 +401,23 @@ export function Reimbursements({ client, state, view, data, query, changeDate, r
|
|||||||
: '报销已批准,已计入报销日期的应转合计';
|
: '报销已批准,已计入报销日期的应转合计';
|
||||||
}
|
}
|
||||||
setError(null);
|
setError(null);
|
||||||
const result = await client.mutate(url, input);
|
const result = await client.mutate<{
|
||||||
if (kind === 'draft') {
|
confirmation?: Pick<Confirmation, 'revision' | 'sourceRevision'>;
|
||||||
|
reimbursement?: { date: string };
|
||||||
|
date?: string;
|
||||||
|
}>(url, input);
|
||||||
|
if (kind === 'draft' && formKey) {
|
||||||
cache.forms.delete(formKey);
|
cache.forms.delete(formKey);
|
||||||
cache.editors.delete(key);
|
cache.editors.delete(key);
|
||||||
}
|
}
|
||||||
if (kind === 'review') cache.reviews.delete(key);
|
if (kind === 'review') cache.reviews.delete(key);
|
||||||
if (kind === 'outlay') {
|
if (kind === 'outlay' && out) {
|
||||||
|
if (
|
||||||
|
!result.confirmation ||
|
||||||
|
!Number.isSafeInteger(result.confirmation.revision) ||
|
||||||
|
typeof result.confirmation.sourceRevision !== 'string'
|
||||||
|
)
|
||||||
|
throw new Error('实际支出已提交,确认回执未完整返回,请重新读取后核对。');
|
||||||
out.editing = false;
|
out.editing = false;
|
||||||
out.verified = false;
|
out.verified = false;
|
||||||
out.revision = result.confirmation.revision;
|
out.revision = result.confirmation.revision;
|
||||||
@@ -338,15 +428,16 @@ export function Reimbursements({ client, state, view, data, query, changeDate, r
|
|||||||
notify(notice + (date && date !== query.date ? '(' + date + ')' : ''));
|
notify(notice + (date && date !== query.date ? '(' + date + ')' : ''));
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (currentView.current !== key) return;
|
if (currentView.current !== key) return;
|
||||||
setError({ kind, text: errorText(err), conflict: err.status === 409 });
|
const conflict = err instanceof Error && 'status' in err && err.status === 409;
|
||||||
|
setError({ kind, text: errorText(err), conflict });
|
||||||
notify(errorText(err), true);
|
notify(errorText(err), true);
|
||||||
if (err.status === 409) {
|
if (conflict) {
|
||||||
if (review) review.verified = false;
|
if (review) review.verified = false;
|
||||||
reload();
|
reload();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const errBox = (id, kind) => (
|
const errBox = (id: string, kind: FormKind) => (
|
||||||
<div id={id} aria-live="polite">
|
<div id={id} aria-live="polite">
|
||||||
{error?.kind === kind && (
|
{error?.kind === kind && (
|
||||||
<div className="error">
|
<div className="error">
|
||||||
@@ -357,7 +448,7 @@ export function Reimbursements({ client, state, view, data, query, changeDate, r
|
|||||||
onClick={async () => {
|
onClick={async () => {
|
||||||
try {
|
try {
|
||||||
await client.retryPending();
|
await client.retryPending();
|
||||||
if (kind === 'draft') {
|
if (kind === 'draft' && formKey) {
|
||||||
cache.forms.delete(formKey);
|
cache.forms.delete(formKey);
|
||||||
cache.editors.delete(key);
|
cache.editors.delete(key);
|
||||||
}
|
}
|
||||||
@@ -382,7 +473,7 @@ export function Reimbursements({ client, state, view, data, query, changeDate, r
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
const btn = (text, name, primary = false) => (
|
const btn = (text: string, name: string, primary = false) => (
|
||||||
<Button
|
<Button
|
||||||
className={primary ? 'primary' : 'quiet'}
|
className={primary ? 'primary' : 'quiet'}
|
||||||
action={name}
|
action={name}
|
||||||
@@ -392,7 +483,7 @@ export function Reimbursements({ client, state, view, data, query, changeDate, r
|
|||||||
{text}
|
{text}
|
||||||
</Button>
|
</Button>
|
||||||
);
|
);
|
||||||
const total = draft ? view.reimbursementDraftTotal(draft.items) : null;
|
const total = view.reimbursementDraftTotal(draft?.items ?? []);
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{!team && (
|
{!team && (
|
||||||
-5
@@ -1,5 +0,0 @@
|
|||||||
import type { JSX } from 'react';
|
|
||||||
import type { LedgerClient } from '../../lib/api';
|
|
||||||
import type { LedgerState, SessionInfo } from '../../shared';
|
|
||||||
export function ReportPage(props: { client: LedgerClient; state: LedgerState; session: SessionInfo }): JSX.Element;
|
|
||||||
export default ReportPage;
|
|
||||||
+42
-26
@@ -1,4 +1,6 @@
|
|||||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
import type { LedgerClient } from '../../lib/api';
|
||||||
|
import type { ReportContext, ReportQuery, ReportAction, Report, Range } from './contracts';
|
||||||
|
import { useCallback, useEffect, useEffectEvent, useLayoutEffect, useRef, useState } from 'react';
|
||||||
import { navigate } from '../../lib/router';
|
import { navigate } from '../../lib/router';
|
||||||
import { useClientSnapshot } from '../../lib/useClient';
|
import { useClientSnapshot } from '../../lib/useClient';
|
||||||
import { Button, Choice } from '../Settings/controls';
|
import { Button, Choice } from '../Settings/controls';
|
||||||
@@ -7,20 +9,24 @@ import { reportPresentation } from './presentation';
|
|||||||
import { Reimbursements } from './Reimbursements';
|
import { Reimbursements } from './Reimbursements';
|
||||||
import './report.css';
|
import './report.css';
|
||||||
|
|
||||||
const savedQueries = new WeakMap();
|
type ReportProps = Pick<ReportContext, 'state' | 'session'> & { client: LedgerClient };
|
||||||
export function ReportPage({ client, state, session }) {
|
type Reply = { query: ReportQuery; version: number } & (
|
||||||
|
{ error: string; data?: never; fundsError?: never } | { data: Report; fundsError: string; error?: never }
|
||||||
|
);
|
||||||
|
const savedQueries = new WeakMap<LedgerClient, Map<string, ReportQuery>>();
|
||||||
|
export function ReportPage({ client, state, session }: ReportProps) {
|
||||||
useClientSnapshot(client);
|
useClientSnapshot(client);
|
||||||
const user = state.user.id;
|
const user = state.user.id;
|
||||||
const [query, setQuery] = useState(
|
const [query, setQuery] = useState<ReportQuery>(
|
||||||
() => savedQueries.get(client)?.get(user) || { date: state.today, month: false, member: '' },
|
() => savedQueries.get(client)?.get(user) || { date: state.today, month: false, member: '' },
|
||||||
);
|
);
|
||||||
const [version, setVersion] = useState(0),
|
const [version, setVersion] = useState(0),
|
||||||
[reply, setReply] = useState(null),
|
[reply, setReply] = useState<Reply | null>(null),
|
||||||
[notice, setNotice] = useState(null);
|
[notice, setNotice] = useState<{ text: string; error: boolean } | null>(null);
|
||||||
const daily = useRef(null),
|
const daily = useRef<((value: ReportAction) => void) | null>(null),
|
||||||
actions = useRef(null);
|
actions = useRef<((value: ReportAction) => void) | null>(null);
|
||||||
const reload = useCallback(() => setVersion(v => v + 1), []);
|
const reload = useCallback(() => setVersion(v => v + 1), []);
|
||||||
const dispatch = useCallback(data => actions.current(data), []);
|
const dispatch = useCallback((data: ReportAction) => actions.current?.(data), []);
|
||||||
const view = reportPresentation({
|
const view = reportPresentation({
|
||||||
state,
|
state,
|
||||||
session,
|
session,
|
||||||
@@ -28,16 +34,16 @@ export function ReportPage({ client, state, session }) {
|
|||||||
reportMember: query.member,
|
reportMember: query.member,
|
||||||
onAction: dispatch,
|
onAction: dispatch,
|
||||||
});
|
});
|
||||||
const viewRef = useRef(view);
|
const currentModel = useEffectEvent(() => view);
|
||||||
viewRef.current = view;
|
|
||||||
const from = query.month ? query.date.slice(0, 7) + '-01' : query.date;
|
const from = query.month ? query.date.slice(0, 7) + '-01' : query.date;
|
||||||
const range = { ...query, from };
|
const range = { ...query, from };
|
||||||
const ready = reply?.query === query && reply.version === version ? reply : null;
|
const ready = reply?.query === query && reply.version === version ? reply : null;
|
||||||
const notify = (text, error = false) => setNotice({ text, error });
|
const notify = (text: string, error = false) => setNotice({ text, error });
|
||||||
const change = d => {
|
const change = (d: Partial<ReportQuery>) => {
|
||||||
const n = { ...query, reviewId: undefined, ...d };
|
const n = { ...query, reviewId: undefined, ...d };
|
||||||
if (!savedQueries.has(client)) savedQueries.set(client, new Map());
|
const queries = savedQueries.get(client) ?? new Map<string, ReportQuery>();
|
||||||
savedQueries.get(client).set(user, n);
|
queries.set(user, n);
|
||||||
|
savedQueries.set(client, queries);
|
||||||
setQuery(n);
|
setQuery(n);
|
||||||
setNotice(null);
|
setNotice(null);
|
||||||
};
|
};
|
||||||
@@ -45,7 +51,7 @@ export function ReportPage({ client, state, session }) {
|
|||||||
let active = true;
|
let active = true;
|
||||||
async function load() {
|
async function load() {
|
||||||
try {
|
try {
|
||||||
const model = viewRef.current;
|
const model: ReturnType<typeof reportPresentation> = currentModel();
|
||||||
if (!model.validOrderDate(query.date)) throw new Error('请选择有效的对账日期。');
|
if (!model.validOrderDate(query.date)) throw new Error('请选择有效的对账日期。');
|
||||||
if (query.date > state.today) throw new Error('请选择今天或之前的日期。');
|
if (query.date > state.today) throw new Error('请选择今天或之前的日期。');
|
||||||
const data = await client.api(
|
const data = await client.api(
|
||||||
@@ -58,7 +64,8 @@ export function ReportPage({ client, state, session }) {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
if (!active) return;
|
if (!active) return;
|
||||||
model.validateReport(data, { from, date: query.date });
|
const validate: (input: unknown, range: Range) => asserts input is Report = model.validateReport;
|
||||||
|
validate(data, { from, date: query.date });
|
||||||
let fundsError = '';
|
let fundsError = '';
|
||||||
try {
|
try {
|
||||||
model.validateDailyFunds(data.dailyFunds, { ...query, from });
|
model.validateDailyFunds(data.dailyFunds, { ...query, from });
|
||||||
@@ -68,7 +75,11 @@ export function ReportPage({ client, state, session }) {
|
|||||||
setReply({ data, fundsError, query, version });
|
setReply({ data, fundsError, query, version });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (active)
|
if (active)
|
||||||
setReply({ error: err.name === 'AbortError' ? '读取超时,请重新读取。' : errorText(err), query, version });
|
setReply({
|
||||||
|
error: err instanceof Error && err.name === 'AbortError' ? '读取超时,请重新读取。' : errorText(err),
|
||||||
|
query,
|
||||||
|
version,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
void load();
|
void load();
|
||||||
@@ -76,20 +87,23 @@ export function ReportPage({ client, state, session }) {
|
|||||||
active = false;
|
active = false;
|
||||||
};
|
};
|
||||||
}, [client, state.today, state.user.role, user, from, query, version]);
|
}, [client, state.today, state.user.role, user, from, query, version]);
|
||||||
async function action({ action, id, date }) {
|
async function action({ action, id, date }: ReportAction) {
|
||||||
try {
|
try {
|
||||||
if (action === 'report-retry' || action === 'daily-funds-retry') {
|
if (action === 'report-retry' || action === 'daily-funds-retry') {
|
||||||
reload();
|
reload();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (action === 'open-order') return navigate('orders', { search: '?order=' + encodeURIComponent(id) });
|
if (action === 'open-order') return navigate('orders', { search: '?order=' + encodeURIComponent(String(id)) });
|
||||||
if (action === 'after-sale-edit') return navigate('orders', { search: '?afterSale=' + encodeURIComponent(id) });
|
if (action === 'after-sale-edit')
|
||||||
if (action === 'open-price-lock') return navigate('price-locks', { search: '?lock=' + encodeURIComponent(id) });
|
return navigate('orders', { search: '?afterSale=' + encodeURIComponent(String(id)) });
|
||||||
if (action === 'recovery-open') return navigate('recoveries', { search: '?recovery=' + encodeURIComponent(id) });
|
if (action === 'open-price-lock')
|
||||||
|
return navigate('price-locks', { search: '?lock=' + encodeURIComponent(String(id)) });
|
||||||
|
if (action === 'recovery-open')
|
||||||
|
return navigate('recoveries', { search: '?recovery=' + encodeURIComponent(String(id)) });
|
||||||
if (action === 'goto-material-pools')
|
if (action === 'goto-material-pools')
|
||||||
return navigate('material-pools', { search: id ? '?pool=' + encodeURIComponent(id) : '' });
|
return navigate('material-pools', { search: id ? '?pool=' + encodeURIComponent(String(id)) : '' });
|
||||||
if (action === 'recovery-print') {
|
if (action === 'recovery-print') {
|
||||||
window.open('/print/recoveries/' + encodeURIComponent(id), '_blank', 'noopener');
|
window.open('/print/recoveries/' + encodeURIComponent(String(id)), '_blank', 'noopener');
|
||||||
notify('客户打印页已打开;若未出现,请允许此网站打开新窗口');
|
notify('客户打印页已打开;若未出现,请允许此网站打开新窗口');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -116,7 +130,9 @@ export function ReportPage({ client, state, session }) {
|
|||||||
notify(errorText(err), true);
|
notify(errorText(err), true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
actions.current = action;
|
useLayoutEffect(() => {
|
||||||
|
actions.current = action;
|
||||||
|
});
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className="report-page"
|
className="report-page"
|
||||||
@@ -0,0 +1,604 @@
|
|||||||
|
import type { LedgerState, SessionInfo } from '../../shared';
|
||||||
|
|
||||||
|
export interface Range {
|
||||||
|
date: string;
|
||||||
|
from: string;
|
||||||
|
month?: boolean;
|
||||||
|
}
|
||||||
|
export interface ReportQuery {
|
||||||
|
date: string;
|
||||||
|
month: boolean;
|
||||||
|
member: string;
|
||||||
|
reviewId?: string;
|
||||||
|
}
|
||||||
|
export interface ReportContext {
|
||||||
|
state: LedgerState;
|
||||||
|
session: SessionInfo;
|
||||||
|
reportMonth: boolean;
|
||||||
|
reportMember: string;
|
||||||
|
}
|
||||||
|
export interface RuleContext {
|
||||||
|
state: Pick<LedgerState, 'user'>;
|
||||||
|
reportMember: string;
|
||||||
|
teamDataKeys: (data: object) => string[];
|
||||||
|
teamMode: () => boolean;
|
||||||
|
currentMember: () => string;
|
||||||
|
teamMemberKeys: () => string[];
|
||||||
|
isReimbursementStatus: (status: string) => boolean;
|
||||||
|
validOrderDate: (value: unknown) => boolean;
|
||||||
|
}
|
||||||
|
export interface ReportAction {
|
||||||
|
action?: string;
|
||||||
|
id?: string;
|
||||||
|
date?: string;
|
||||||
|
}
|
||||||
|
export type Amount = number | null;
|
||||||
|
export interface Receipts {
|
||||||
|
receipt: number;
|
||||||
|
refund: number;
|
||||||
|
net: number;
|
||||||
|
}
|
||||||
|
export interface Account extends Receipts {
|
||||||
|
account: string;
|
||||||
|
recipient: string;
|
||||||
|
channel: string;
|
||||||
|
entryCount: number;
|
||||||
|
}
|
||||||
|
export interface ReceiptItem {
|
||||||
|
id: string;
|
||||||
|
kind: string;
|
||||||
|
amount: number;
|
||||||
|
account: string;
|
||||||
|
date: string;
|
||||||
|
order_id: string | null;
|
||||||
|
order_date: string | null;
|
||||||
|
price_lock_id: string | null;
|
||||||
|
order_after_sale?: boolean;
|
||||||
|
note?: string;
|
||||||
|
paper_number?: string | null;
|
||||||
|
number: string;
|
||||||
|
reference?: string;
|
||||||
|
customer: string;
|
||||||
|
product?: string;
|
||||||
|
}
|
||||||
|
export interface MemberReceipts extends Receipts {
|
||||||
|
name: string;
|
||||||
|
items: ReceiptItem[];
|
||||||
|
}
|
||||||
|
export interface RecipientReceipts extends MemberReceipts {
|
||||||
|
recipient: string;
|
||||||
|
}
|
||||||
|
export interface OwnershipReceipts extends MemberReceipts {
|
||||||
|
member: string;
|
||||||
|
accounts: Account[];
|
||||||
|
}
|
||||||
|
export interface CostItem {
|
||||||
|
id: string;
|
||||||
|
kind: string;
|
||||||
|
name: string;
|
||||||
|
source: string;
|
||||||
|
amount: Amount;
|
||||||
|
payer: string;
|
||||||
|
date: string;
|
||||||
|
number: string;
|
||||||
|
paper_number?: string;
|
||||||
|
customer: string;
|
||||||
|
order_id?: string;
|
||||||
|
price_lock_id?: string;
|
||||||
|
component: string;
|
||||||
|
materialPoolId?: string | null;
|
||||||
|
nonCash?: boolean;
|
||||||
|
afterSaleExpense?: boolean;
|
||||||
|
paidDate?: string;
|
||||||
|
after_sale_id?: string;
|
||||||
|
pool_id?: string;
|
||||||
|
product?: string;
|
||||||
|
quantity?: number;
|
||||||
|
calculation?: { rate: number; quantity: number; weighted?: boolean } | null;
|
||||||
|
}
|
||||||
|
export interface PayerCosts {
|
||||||
|
name: string;
|
||||||
|
goods: number;
|
||||||
|
paidFees: number;
|
||||||
|
total: number;
|
||||||
|
missingCount: number;
|
||||||
|
pendingCount: number;
|
||||||
|
items: CostItem[];
|
||||||
|
}
|
||||||
|
export interface Allocation {
|
||||||
|
payer: string;
|
||||||
|
amount: number;
|
||||||
|
}
|
||||||
|
export interface ReturnedLine {
|
||||||
|
lineIndex: number;
|
||||||
|
name: string;
|
||||||
|
materialAllocations: Allocation[];
|
||||||
|
restockedLaborAllocations: Allocation[];
|
||||||
|
materialReturnedCost: number;
|
||||||
|
laborRestockedCost: number;
|
||||||
|
}
|
||||||
|
export interface OrderAfterSale {
|
||||||
|
date: string;
|
||||||
|
order_id?: string;
|
||||||
|
orderId?: string;
|
||||||
|
original: { total: number };
|
||||||
|
originalOrder?: { total: number };
|
||||||
|
summary: {
|
||||||
|
lines: ReturnedLine[];
|
||||||
|
materialReturnedCost: number;
|
||||||
|
laborRestockedCost: number;
|
||||||
|
retainedAmount: number;
|
||||||
|
profitAdjustment: number;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
export interface Row {
|
||||||
|
id: string;
|
||||||
|
kind: string;
|
||||||
|
member: string;
|
||||||
|
date: string;
|
||||||
|
status: string;
|
||||||
|
order_date?: string;
|
||||||
|
orderAfterSale: OrderAfterSale;
|
||||||
|
sale: Amount;
|
||||||
|
totalCost: Amount;
|
||||||
|
profit: Amount;
|
||||||
|
known: Record<string, number>;
|
||||||
|
costItems: CostItem[];
|
||||||
|
material: Amount;
|
||||||
|
laborAndFees: Amount;
|
||||||
|
number: string;
|
||||||
|
paper_number?: string;
|
||||||
|
customer: string;
|
||||||
|
costHint?: string;
|
||||||
|
note?: string;
|
||||||
|
project?: string;
|
||||||
|
order_id?: string;
|
||||||
|
recovery_id?: string;
|
||||||
|
recovery_mode?: string;
|
||||||
|
cashPayment: number;
|
||||||
|
payer?: string;
|
||||||
|
after_sale_id?: string;
|
||||||
|
price_lock_id?: string;
|
||||||
|
}
|
||||||
|
export interface Summary {
|
||||||
|
orderCount: number;
|
||||||
|
completedCount: number;
|
||||||
|
returnedCount: number;
|
||||||
|
cancelledCount: number;
|
||||||
|
draftCount: number;
|
||||||
|
afterSaleCount: number;
|
||||||
|
sale: number;
|
||||||
|
totalCost: number;
|
||||||
|
profit: number;
|
||||||
|
missingCosts: number;
|
||||||
|
pendingCosts: number;
|
||||||
|
unknownProfitCount: number;
|
||||||
|
unknownCostCount: number;
|
||||||
|
knownCounts: Record<string, number>;
|
||||||
|
unknownCounts: Record<string, number>;
|
||||||
|
}
|
||||||
|
export interface Profit {
|
||||||
|
recordCount: number;
|
||||||
|
orderCount: number;
|
||||||
|
afterSaleCount: number;
|
||||||
|
draftCount: number;
|
||||||
|
unknownCostCount: number;
|
||||||
|
unknownProfitCount: number;
|
||||||
|
sales: number;
|
||||||
|
knownTotalCost: number;
|
||||||
|
knownProfit: number;
|
||||||
|
incomplete: boolean;
|
||||||
|
totalCost: Amount;
|
||||||
|
profit: Amount;
|
||||||
|
}
|
||||||
|
export interface ProfitRow extends Profit {
|
||||||
|
name: string;
|
||||||
|
member: string;
|
||||||
|
date: string;
|
||||||
|
}
|
||||||
|
export interface ProfitTable extends Range {
|
||||||
|
basis: string;
|
||||||
|
rows: ProfitRow[];
|
||||||
|
summary: Profit;
|
||||||
|
}
|
||||||
|
export interface BusinessCost {
|
||||||
|
member: string;
|
||||||
|
name: string;
|
||||||
|
totalCost: Amount;
|
||||||
|
knownTotalCost: number;
|
||||||
|
missingCount: number;
|
||||||
|
pendingCount: number;
|
||||||
|
}
|
||||||
|
export interface MaterialValue {
|
||||||
|
amount: Amount;
|
||||||
|
knownAmount: number;
|
||||||
|
}
|
||||||
|
export interface MaterialSource extends MaterialValue {
|
||||||
|
kind: string;
|
||||||
|
member: string;
|
||||||
|
priceLocked: boolean;
|
||||||
|
mg: number;
|
||||||
|
averageRate: Amount;
|
||||||
|
missingCount: number;
|
||||||
|
}
|
||||||
|
export interface PoolDay extends MaterialValue {
|
||||||
|
date: string;
|
||||||
|
poolId: string;
|
||||||
|
mg: number;
|
||||||
|
averageRate: Amount;
|
||||||
|
missingCount: number;
|
||||||
|
byPayer: Record<string, MaterialValue>;
|
||||||
|
sources?: MaterialSource[];
|
||||||
|
}
|
||||||
|
export interface PoolMaterial extends MaterialValue {
|
||||||
|
mg: number;
|
||||||
|
missingCount: number;
|
||||||
|
byPayer: Record<string, MaterialValue>;
|
||||||
|
hasPriceLocks: boolean;
|
||||||
|
days: PoolDay[];
|
||||||
|
otherCosts: MaterialValue;
|
||||||
|
}
|
||||||
|
export interface AdvanceItem {
|
||||||
|
id: string;
|
||||||
|
date: string;
|
||||||
|
kind: string;
|
||||||
|
number: string;
|
||||||
|
paperNumber: string;
|
||||||
|
customer: string;
|
||||||
|
name: string;
|
||||||
|
source: string;
|
||||||
|
component: string;
|
||||||
|
poolMaterial: boolean;
|
||||||
|
poolId: string | null;
|
||||||
|
allocationPending: boolean;
|
||||||
|
nonCash?: boolean;
|
||||||
|
status: 'recorded' | 'missing' | 'pending';
|
||||||
|
amount: Amount;
|
||||||
|
estimatedAmount: Amount;
|
||||||
|
}
|
||||||
|
export interface AdvanceDay {
|
||||||
|
date: string;
|
||||||
|
items: AdvanceItem[];
|
||||||
|
amount: Amount;
|
||||||
|
knownAmount: number;
|
||||||
|
missingCount: number;
|
||||||
|
pendingCount: number;
|
||||||
|
poolAmount: Amount;
|
||||||
|
knownPoolAmount: number;
|
||||||
|
otherAmount: Amount;
|
||||||
|
knownOtherAmount: number;
|
||||||
|
}
|
||||||
|
export interface CurrentDay {
|
||||||
|
date: string;
|
||||||
|
recordCount: number;
|
||||||
|
knownMaterialCost: number;
|
||||||
|
knownOtherCost: number;
|
||||||
|
knownProfit: number;
|
||||||
|
ownerNetReceipts: number;
|
||||||
|
missingCostCount: number;
|
||||||
|
pendingCostCount: number;
|
||||||
|
unknownProfitCount: number;
|
||||||
|
incomplete: boolean;
|
||||||
|
materialCost: Amount;
|
||||||
|
otherCost: Amount;
|
||||||
|
profit: Amount;
|
||||||
|
knownAmount: number;
|
||||||
|
amount: Amount;
|
||||||
|
}
|
||||||
|
export interface Counterpart {
|
||||||
|
member: string;
|
||||||
|
name: string;
|
||||||
|
dueOut: number;
|
||||||
|
dueIn: number;
|
||||||
|
offset: number;
|
||||||
|
openingDue: number;
|
||||||
|
periodNew: number;
|
||||||
|
periodTransferred: number;
|
||||||
|
closingDue: number;
|
||||||
|
period: { obligationNet: number; transferred: number; receivedForNet: number; advancedNet: number };
|
||||||
|
}
|
||||||
|
export interface Business extends Range {
|
||||||
|
member: string;
|
||||||
|
name: string;
|
||||||
|
basis: string;
|
||||||
|
recordCount: number;
|
||||||
|
orderCount: number;
|
||||||
|
afterSaleCount: number;
|
||||||
|
draftCount: number;
|
||||||
|
sales: number;
|
||||||
|
netReceipts: number;
|
||||||
|
totalCost: Amount;
|
||||||
|
knownTotalCost: number;
|
||||||
|
selfCost: Amount;
|
||||||
|
knownSelfCost: number;
|
||||||
|
otherCost: Amount;
|
||||||
|
knownOtherCost: number;
|
||||||
|
profit: Amount;
|
||||||
|
knownProfit: number;
|
||||||
|
missingCostCount: number;
|
||||||
|
pendingCostCount: number;
|
||||||
|
unknownProfitCount: number;
|
||||||
|
incomplete: boolean;
|
||||||
|
hasActivity: boolean;
|
||||||
|
costByPayer: Record<string, BusinessCost>;
|
||||||
|
poolMaterial: PoolMaterial;
|
||||||
|
ownerAdvances: Range & { basis: string; days: AdvanceDay[] };
|
||||||
|
currentAccount: Range & { basis: string; days: CurrentDay[] };
|
||||||
|
difference: { amount: number; reconciled: boolean; reasons: { code: string; text: string }[] };
|
||||||
|
equation: { basis: string; revenue: number; totalCost: Amount; profit: Amount; complete: boolean };
|
||||||
|
settlement: Range & {
|
||||||
|
available: boolean;
|
||||||
|
basis: string;
|
||||||
|
partial: boolean;
|
||||||
|
pendingCount: number;
|
||||||
|
legacyCount: number;
|
||||||
|
notice: string;
|
||||||
|
counterparts: Counterpart[];
|
||||||
|
dueIn: Amount;
|
||||||
|
dueOut: Amount;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
export interface DailySource {
|
||||||
|
id: string;
|
||||||
|
date: string;
|
||||||
|
sourceType: string;
|
||||||
|
sourceId: string;
|
||||||
|
payer: string;
|
||||||
|
name: string;
|
||||||
|
note: string;
|
||||||
|
amount: number;
|
||||||
|
}
|
||||||
|
export interface Sources {
|
||||||
|
revision: string;
|
||||||
|
total: number;
|
||||||
|
items: DailySource[];
|
||||||
|
}
|
||||||
|
export interface Confirmation {
|
||||||
|
date: string;
|
||||||
|
amount: number;
|
||||||
|
revision: number;
|
||||||
|
sourceRevision: string;
|
||||||
|
note: string;
|
||||||
|
actor: string;
|
||||||
|
stale: boolean;
|
||||||
|
}
|
||||||
|
export interface FundsDay {
|
||||||
|
date: string;
|
||||||
|
ownerReceipts: Receipts;
|
||||||
|
approvedReimbursements: number;
|
||||||
|
actualOutlay: Amount;
|
||||||
|
confirmation: Confirmation | null;
|
||||||
|
sources: Sources;
|
||||||
|
ready: boolean;
|
||||||
|
transferAmount: Amount;
|
||||||
|
direction: string | null;
|
||||||
|
hasActivity: boolean;
|
||||||
|
}
|
||||||
|
export interface ReimbursementItem {
|
||||||
|
id?: string;
|
||||||
|
availableAmount?: number;
|
||||||
|
name: string;
|
||||||
|
amount: number;
|
||||||
|
member?: string;
|
||||||
|
sourceType?: string;
|
||||||
|
sourceKey?: string;
|
||||||
|
usedAmount?: number;
|
||||||
|
remainingAmount?: number;
|
||||||
|
}
|
||||||
|
export type ReimbursementStatus = 'pending' | 'approved' | 'rejected';
|
||||||
|
export interface Reimbursement {
|
||||||
|
id: string;
|
||||||
|
date: string;
|
||||||
|
status: ReimbursementStatus;
|
||||||
|
revision: number;
|
||||||
|
canEdit: boolean;
|
||||||
|
canApprove: boolean;
|
||||||
|
items: ReimbursementItem[];
|
||||||
|
total: number;
|
||||||
|
note: string;
|
||||||
|
requester_name: string;
|
||||||
|
reviewer_name: string;
|
||||||
|
review_note: string;
|
||||||
|
payer?: string;
|
||||||
|
member?: string;
|
||||||
|
}
|
||||||
|
export interface ReimbursementList {
|
||||||
|
requests: Reimbursement[];
|
||||||
|
total: number;
|
||||||
|
offset: number;
|
||||||
|
limit: number;
|
||||||
|
hasMore: boolean;
|
||||||
|
counts: Record<ReimbursementStatus, number>;
|
||||||
|
}
|
||||||
|
export interface TeamPair {
|
||||||
|
members: string[];
|
||||||
|
net: number;
|
||||||
|
obligationNet: number;
|
||||||
|
transferred: number;
|
||||||
|
due: number;
|
||||||
|
entries: unknown[];
|
||||||
|
}
|
||||||
|
export interface Team {
|
||||||
|
from: string;
|
||||||
|
to: string;
|
||||||
|
revision: string | number;
|
||||||
|
pairs: TeamPair[];
|
||||||
|
balances: unknown[];
|
||||||
|
transfers: unknown[];
|
||||||
|
}
|
||||||
|
export interface DailyFunds extends Range, FundsDay {
|
||||||
|
team?: Team;
|
||||||
|
readOnly: boolean;
|
||||||
|
hasRecords: boolean;
|
||||||
|
pendingCount: number;
|
||||||
|
reimbursements: Reimbursement[];
|
||||||
|
missingDates: string[];
|
||||||
|
staleDates: string[];
|
||||||
|
days: FundsDay[];
|
||||||
|
transfersNotDeducted: boolean;
|
||||||
|
rangeUnsupported?: boolean;
|
||||||
|
}
|
||||||
|
export interface PriceActivityItem {
|
||||||
|
id: string;
|
||||||
|
date: string;
|
||||||
|
kind: string;
|
||||||
|
amount: number;
|
||||||
|
account: string;
|
||||||
|
payer: string;
|
||||||
|
quantity: number;
|
||||||
|
rate: number;
|
||||||
|
product: string;
|
||||||
|
customer: string;
|
||||||
|
note: string;
|
||||||
|
name: string;
|
||||||
|
source: string;
|
||||||
|
price_lock_id: string;
|
||||||
|
order_id: string;
|
||||||
|
number: string;
|
||||||
|
paper_number: string;
|
||||||
|
component: string;
|
||||||
|
actor: string;
|
||||||
|
line_index: number;
|
||||||
|
}
|
||||||
|
export interface PriceActivity extends Range {
|
||||||
|
customerCash: PriceActivityItem[];
|
||||||
|
orderPayments: PriceActivityItem[];
|
||||||
|
materialOutlays: PriceActivityItem[];
|
||||||
|
deliveryGoodsOutlays: PriceActivityItem[];
|
||||||
|
directOutlays: PriceActivityItem[];
|
||||||
|
summary: {
|
||||||
|
eventCount: number;
|
||||||
|
receipt: number;
|
||||||
|
refund: number;
|
||||||
|
net: number;
|
||||||
|
materialOutlay: number;
|
||||||
|
goodsOutlay: number;
|
||||||
|
feeOutlay: number;
|
||||||
|
totalOutlay: number;
|
||||||
|
ownerOutlay: number;
|
||||||
|
assistantOutlay: number;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
export interface MaterialPurchase {
|
||||||
|
id: string;
|
||||||
|
pool_id: string;
|
||||||
|
date: string;
|
||||||
|
mg: number;
|
||||||
|
amount: number;
|
||||||
|
payer?: string;
|
||||||
|
actualpayer?: string;
|
||||||
|
actualPayer?: string;
|
||||||
|
note: string;
|
||||||
|
}
|
||||||
|
export interface PoolActivity extends Range {
|
||||||
|
purchases: MaterialPurchase[];
|
||||||
|
summary: {
|
||||||
|
eventCount: number;
|
||||||
|
purchaseCount: number;
|
||||||
|
poolCount: number;
|
||||||
|
mg: number;
|
||||||
|
materialOutlay: number;
|
||||||
|
purchaseValue: number;
|
||||||
|
ownerOutlay: number;
|
||||||
|
assistantOutlay: number;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
export interface PoolSettlement {
|
||||||
|
legacyReadOnly?: boolean;
|
||||||
|
assistantInventoryCredit: Amount;
|
||||||
|
knownAssistantInventoryCredit: number;
|
||||||
|
transferred: number;
|
||||||
|
settlementDue: Amount;
|
||||||
|
knownSettlementDue: number;
|
||||||
|
pendingCount: number;
|
||||||
|
pools: {
|
||||||
|
id: string;
|
||||||
|
date: string;
|
||||||
|
assistantInventoryCredit: Amount;
|
||||||
|
transferred: number;
|
||||||
|
settlementDue: Amount;
|
||||||
|
pending: boolean;
|
||||||
|
}[];
|
||||||
|
}
|
||||||
|
export interface InventoryBalance {
|
||||||
|
pocket: string;
|
||||||
|
mg: number;
|
||||||
|
reserved: number;
|
||||||
|
available: number;
|
||||||
|
countUnit?: string;
|
||||||
|
count?: number | null;
|
||||||
|
}
|
||||||
|
export interface PeoplePart {
|
||||||
|
total: Amount;
|
||||||
|
endTotal: Amount;
|
||||||
|
baselineTotal: Amount;
|
||||||
|
baselineDate: string;
|
||||||
|
netChange: Amount;
|
||||||
|
netChangeReason: string;
|
||||||
|
recordedDays: number;
|
||||||
|
}
|
||||||
|
export type PeopleCount = Range &
|
||||||
|
PeoplePart & { [key: string]: string | number | boolean | null | PeoplePart | undefined };
|
||||||
|
export interface Report extends Range {
|
||||||
|
basis: string;
|
||||||
|
summary: Summary;
|
||||||
|
orderRows: Row[];
|
||||||
|
accounts: Account[];
|
||||||
|
payerCosts: Record<string, PayerCosts>;
|
||||||
|
recipientReceipts: Record<string, RecipientReceipts>;
|
||||||
|
ownershipReceipts: Record<string, OwnershipReceipts>;
|
||||||
|
ownershipBusiness: Record<string, Business>;
|
||||||
|
receiptsByOrderDate: Receipts & {
|
||||||
|
channels: (Receipts & { name: string; channel: string })[];
|
||||||
|
accounts: Account[];
|
||||||
|
paymentCount: number;
|
||||||
|
orderCount: number;
|
||||||
|
};
|
||||||
|
dailyProfits: ProfitTable;
|
||||||
|
dailyFunds: DailyFunds;
|
||||||
|
peopleCount: PeopleCount;
|
||||||
|
priceLockActivity: PriceActivity | null;
|
||||||
|
materialPoolActivity: PoolActivity | null;
|
||||||
|
materialPoolSettlement: PoolSettlement | null;
|
||||||
|
goods: number;
|
||||||
|
expense: number;
|
||||||
|
outlayGoods: number;
|
||||||
|
outlayExpense: number;
|
||||||
|
outlayTotal: number;
|
||||||
|
customerBalance: number;
|
||||||
|
settlementDue: Amount;
|
||||||
|
knownSettlementDue: number;
|
||||||
|
pendingMaterialCount: number;
|
||||||
|
inventory: InventoryBalance[];
|
||||||
|
warnings: { id: string; number: string; message: string }[];
|
||||||
|
unsettled: {
|
||||||
|
id: string;
|
||||||
|
number: string;
|
||||||
|
customer: string;
|
||||||
|
costDue: Amount;
|
||||||
|
profitDue: Amount;
|
||||||
|
ownerGoods: Amount;
|
||||||
|
ownerDirect: number;
|
||||||
|
total: Amount;
|
||||||
|
}[];
|
||||||
|
close: { date: string; actor: string; created: string; stale: boolean; staleReason: string } | null;
|
||||||
|
}
|
||||||
|
export type Metric = 'sale' | 'totalCost' | 'profit';
|
||||||
|
export type RowMetric = Metric | 'goods' | 'paidFees' | 'material' | 'laborAndFees';
|
||||||
|
export type CurrentDisplayDay = Pick<
|
||||||
|
CurrentDay,
|
||||||
|
| 'date'
|
||||||
|
| 'materialCost'
|
||||||
|
| 'knownMaterialCost'
|
||||||
|
| 'otherCost'
|
||||||
|
| 'knownOtherCost'
|
||||||
|
| 'profit'
|
||||||
|
| 'knownProfit'
|
||||||
|
| 'ownerNetReceipts'
|
||||||
|
| 'amount'
|
||||||
|
| 'incomplete'
|
||||||
|
>;
|
||||||
|
export interface RecoveryCosts {
|
||||||
|
byPayer: Record<string, number>;
|
||||||
|
items: CostItem[];
|
||||||
|
}
|
||||||
+69
-60
@@ -1,9 +1,18 @@
|
|||||||
|
import type { ReactNode } from 'react';
|
||||||
|
import type * as T from './contracts';
|
||||||
import { Children } from 'react';
|
import { Children } from 'react';
|
||||||
import { reportData } from './reportData';
|
import { reportData } from './reportData';
|
||||||
const withKeys = Children.toArray;
|
const withKeys = Children.toArray;
|
||||||
const fallback = (rows, empty) => (rows.length ? rows : empty);
|
const fallback = (rows: ReactNode[], empty: ReactNode) => (rows.length ? rows : empty);
|
||||||
const e = value => (value == null ? '' : String(value));
|
const e = (value: unknown) => (value == null ? '' : String(value));
|
||||||
export function reportPresentation({ state, session, reportMonth, reportMember, onAction, dailyFundsLoading = false }) {
|
export function reportPresentation({
|
||||||
|
state,
|
||||||
|
session,
|
||||||
|
reportMonth,
|
||||||
|
reportMember,
|
||||||
|
onAction,
|
||||||
|
dailyFundsLoading = false,
|
||||||
|
}: T.ReportContext & { onAction: (data: T.ReportAction) => void; dailyFundsLoading?: boolean }) {
|
||||||
const model = reportData({ state, session, reportMonth, reportMember });
|
const model = reportData({ state, session, reportMonth, reportMember });
|
||||||
const {
|
const {
|
||||||
reportSummaryAmount,
|
reportSummaryAmount,
|
||||||
@@ -51,7 +60,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
reportPoolMaterialFormula,
|
reportPoolMaterialFormula,
|
||||||
reportPoolMaterialSourceLabel,
|
reportPoolMaterialSourceLabel,
|
||||||
} = model;
|
} = model;
|
||||||
function renderReportContent(r, range) {
|
function renderReportContent(r: T.Report, range: T.Range) {
|
||||||
const s = r.summary,
|
const s = r.summary,
|
||||||
receipts = r.receiptsByOrderDate,
|
receipts = r.receiptsByOrderDate,
|
||||||
profitMissing = s.unknownProfitCount || 0;
|
profitMissing = s.unknownProfitCount || 0;
|
||||||
@@ -116,7 +125,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
)),
|
)),
|
||||||
),
|
),
|
||||||
<tr>
|
<tr>
|
||||||
<td colSpan="4" className="muted">
|
<td colSpan={4} className="muted">
|
||||||
所选范围没有收退款活动账户。
|
所选范围没有收退款活动账户。
|
||||||
</td>
|
</td>
|
||||||
</tr>,
|
</tr>,
|
||||||
@@ -228,9 +237,9 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderReportDailyProfits(r) {
|
function renderReportDailyProfits(r: T.Report) {
|
||||||
const table = r.dailyProfits,
|
const table = r.dailyProfits,
|
||||||
amounts = row => (
|
amounts = (row: T.Profit) => (
|
||||||
<>
|
<>
|
||||||
<td className="number">¥{yuan(row.sales)}</td>
|
<td className="number">¥{yuan(row.sales)}</td>
|
||||||
<td className="number">{reportDailyProfitAmount(row.totalCost, row.knownTotalCost)}</td>
|
<td className="number">{reportDailyProfitAmount(row.totalCost, row.knownTotalCost)}</td>
|
||||||
@@ -280,7 +289,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
)),
|
)),
|
||||||
),
|
),
|
||||||
<tr>
|
<tr>
|
||||||
<td colSpan="5" className="muted">
|
<td colSpan={5} className="muted">
|
||||||
所选范围暂无订单或售后记录。
|
所选范围暂无订单或售后记录。
|
||||||
</td>
|
</td>
|
||||||
</tr>,
|
</tr>,
|
||||||
@@ -288,7 +297,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
</tbody>
|
</tbody>
|
||||||
<tfoot>
|
<tfoot>
|
||||||
<tr>
|
<tr>
|
||||||
<td colSpan="2">所选范围合计</td>
|
<td colSpan={2}>所选范围合计</td>
|
||||||
{amounts(table.summary)}
|
{amounts(table.summary)}
|
||||||
</tr>
|
</tr>
|
||||||
</tfoot>
|
</tfoot>
|
||||||
@@ -302,7 +311,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderReimbursementRows(data, readOnly) {
|
function renderReimbursementRows(data: T.DailyFunds, readOnly: boolean) {
|
||||||
return (
|
return (
|
||||||
<div className="reimbursement-records">
|
<div className="reimbursement-records">
|
||||||
{fallback(
|
{fallback(
|
||||||
@@ -389,7 +398,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderDailyFundsMonth(data) {
|
function renderDailyFundsMonth(data: T.DailyFunds) {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<p className="small muted">月汇总只读。按每张报销单的报销日期归集,跨日批准仍回到原日期。</p>
|
<p className="small muted">月汇总只读。按每张报销单的报销日期归集,跨日批准仍回到原日期。</p>
|
||||||
@@ -440,7 +449,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
)),
|
)),
|
||||||
),
|
),
|
||||||
<tr>
|
<tr>
|
||||||
<td colSpan="6" className="muted">
|
<td colSpan={6} className="muted">
|
||||||
所选范围暂无需核对的记录。可切换单日确认。
|
所选范围暂无需核对的记录。可切换单日确认。
|
||||||
</td>
|
</td>
|
||||||
</tr>,
|
</tr>,
|
||||||
@@ -452,7 +461,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderDailyFundsSources(data) {
|
function renderDailyFundsSources(data: T.DailyFunds) {
|
||||||
return (
|
return (
|
||||||
<details className="daily-funds-sources">
|
<details className="daily-funds-sources">
|
||||||
<summary>
|
<summary>
|
||||||
@@ -487,7 +496,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
)),
|
)),
|
||||||
),
|
),
|
||||||
<tr>
|
<tr>
|
||||||
<td colSpan="3" className="muted">
|
<td colSpan={3} className="muted">
|
||||||
暂无已记录付款;这不代表当天完整支出一定为 0。
|
暂无已记录付款;这不代表当天完整支出一定为 0。
|
||||||
</td>
|
</td>
|
||||||
</tr>,
|
</tr>,
|
||||||
@@ -499,12 +508,12 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderDailyTransferResult(data, month = false) {
|
function renderDailyTransferResult(data: T.DailyFunds, month = false) {
|
||||||
const ready = data.ready && !dailyFundsLoading;
|
const ready = data.ready && !dailyFundsLoading;
|
||||||
const direction =
|
const direction =
|
||||||
data.transferAmount > 0
|
(data.transferAmount ?? 0) > 0
|
||||||
? teamMemberName('owner') + '转' + teamMemberName('assistant')
|
? teamMemberName('owner') + '转' + teamMemberName('assistant')
|
||||||
: data.transferAmount < 0
|
: (data.transferAmount ?? 0) < 0
|
||||||
? teamMemberName('assistant') + '转' + teamMemberName('owner')
|
? teamMemberName('assistant') + '转' + teamMemberName('owner')
|
||||||
: '无需转款';
|
: '无需转款';
|
||||||
return (
|
return (
|
||||||
@@ -535,7 +544,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
<span>
|
<span>
|
||||||
{month ? '本期' : '本日'}应转合计 · {direction}
|
{month ? '本期' : '本日'}应转合计 · {direction}
|
||||||
</span>
|
</span>
|
||||||
<strong>¥{yuan(Math.abs(data.transferAmount))}</strong>
|
<strong>¥{yuan(Math.abs(data.transferAmount ?? 0))}</strong>
|
||||||
<p>
|
<p>
|
||||||
{teamMemberName('owner')}净收款 ¥{yuan(data.ownerReceipts.net)} − 确认对外支出 ¥{yuan(data.actualOutlay)}{' '}
|
{teamMemberName('owner')}净收款 ¥{yuan(data.ownerReceipts.net)} − 确认对外支出 ¥{yuan(data.actualOutlay)}{' '}
|
||||||
+ 已批准报销 ¥{yuan(data.approvedReimbursements)} = <b>¥{yuan(data.transferAmount)}</b>
|
+ 已批准报销 ¥{yuan(data.approvedReimbursements)} = <b>¥{yuan(data.transferAmount)}</b>
|
||||||
@@ -555,7 +564,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderReimbursementItems(row) {
|
function renderReimbursementItems(row: T.Reimbursement) {
|
||||||
return (
|
return (
|
||||||
<ul className="reimbursement-items-read">
|
<ul className="reimbursement-items-read">
|
||||||
{withKeys(
|
{withKeys(
|
||||||
@@ -581,7 +590,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderReportOwnershipReceipts(r, range) {
|
function renderReportOwnershipReceipts(r: T.Report, range: T.Range) {
|
||||||
const keys = reportOwnershipKeys(r);
|
const keys = reportOwnershipKeys(r);
|
||||||
return (
|
return (
|
||||||
<section className="report-receipts report-ownership-receipts" aria-label="按订单归属汇总净收入">
|
<section className="report-receipts report-ownership-receipts" aria-label="按订单归属汇总净收入">
|
||||||
@@ -638,7 +647,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const card = (title, value, hint = '', emphasis = false) => (
|
const card = (title: ReactNode, value: ReactNode, hint: ReactNode = '', emphasis = false) => (
|
||||||
<div className={'stat ' + (emphasis ? 'emphasis' : '')}>
|
<div className={'stat ' + (emphasis ? 'emphasis' : '')}>
|
||||||
<small>{title}</small>
|
<small>{title}</small>
|
||||||
<strong>{value}</strong>
|
<strong>{value}</strong>
|
||||||
@@ -646,7 +655,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|
||||||
function renderReportPayerCosts(r) {
|
function renderReportPayerCosts(r: T.Report) {
|
||||||
const people = teamDataKeys(r.payerCosts).map(key => r.payerCosts[key]),
|
const people = teamDataKeys(r.payerCosts).map(key => r.payerCosts[key]),
|
||||||
missing = people.reduce((sum, c) => sum + c.missingCount, 0),
|
missing = people.reduce((sum, c) => sum + c.missingCount, 0),
|
||||||
pending = people.reduce((sum, c) => sum + c.pendingCount, 0);
|
pending = people.reduce((sum, c) => sum + c.pendingCount, 0);
|
||||||
@@ -713,7 +722,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderPriceLockActivity(activity) {
|
function renderPriceLockActivity(activity: T.PriceActivity | null) {
|
||||||
if (!activity?.summary?.eventCount) return '';
|
if (!activity?.summary?.eventCount) return '';
|
||||||
const s = activity.summary,
|
const s = activity.summary,
|
||||||
rows = priceLockActivityRows(activity);
|
rows = priceLockActivityRows(activity);
|
||||||
@@ -783,7 +792,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderMaterialPoolActivity(activity) {
|
function renderMaterialPoolActivity(activity: T.PoolActivity | null) {
|
||||||
if (!activity?.purchases?.length) return '';
|
if (!activity?.purchases?.length) return '';
|
||||||
return (
|
return (
|
||||||
<section className="panel material-report-activity">
|
<section className="panel material-report-activity">
|
||||||
@@ -830,7 +839,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderReportOrderNet(r, range) {
|
function renderReportOrderNet(r: T.Report, range: T.Range) {
|
||||||
const s = r.summary;
|
const s = r.summary;
|
||||||
return (
|
return (
|
||||||
<section className="panel report-order-net">
|
<section className="panel report-order-net">
|
||||||
@@ -870,7 +879,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
</td>
|
</td>
|
||||||
<td>{badge(row)}</td>
|
<td>{badge(row)}</td>
|
||||||
{withKeys(
|
{withKeys(
|
||||||
['sale', 'goods', 'paidFees', 'totalCost', 'profit'].map(key => (
|
(['sale', 'goods', 'paidFees', 'totalCost', 'profit'] as const).map(key => (
|
||||||
<td className="number">{reportRowAmount(row, key)}</td>
|
<td className="number">{reportRowAmount(row, key)}</td>
|
||||||
)),
|
)),
|
||||||
)}
|
)}
|
||||||
@@ -878,7 +887,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
)),
|
)),
|
||||||
),
|
),
|
||||||
<tr>
|
<tr>
|
||||||
<td colSpan="7" className="muted">
|
<td colSpan={7} className="muted">
|
||||||
所选日期没有订单或售后记录。
|
所选日期没有订单或售后记录。
|
||||||
</td>
|
</td>
|
||||||
</tr>,
|
</tr>,
|
||||||
@@ -886,7 +895,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
</tbody>
|
</tbody>
|
||||||
<tfoot>
|
<tfoot>
|
||||||
<tr>
|
<tr>
|
||||||
<td colSpan="2">
|
<td colSpan={2}>
|
||||||
销售 {s.orderCount} 单 · 售后 {s.afterSaleCount || 0} 笔
|
销售 {s.orderCount} 单 · 售后 {s.afterSaleCount || 0} 笔
|
||||||
</td>
|
</td>
|
||||||
<td className="number">{reportSummaryAmount(s, 'sale')}</td>
|
<td className="number">{reportSummaryAmount(s, 'sale')}</td>
|
||||||
@@ -902,7 +911,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderReportGlobal(r) {
|
function renderReportGlobal(r: T.Report) {
|
||||||
if (teamMode())
|
if (teamMode())
|
||||||
return (
|
return (
|
||||||
<section className="panel">
|
<section className="panel">
|
||||||
@@ -960,7 +969,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderReportUnsettled(r) {
|
function renderReportUnsettled(r: T.Report) {
|
||||||
return (
|
return (
|
||||||
<section className="panel report-unsettled">
|
<section className="panel report-unsettled">
|
||||||
<h2>逐单交款与返款(截至现在)</h2>
|
<h2>逐单交款与返款(截至现在)</h2>
|
||||||
@@ -1002,7 +1011,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
)),
|
)),
|
||||||
),
|
),
|
||||||
<tr>
|
<tr>
|
||||||
<td colSpan="5">目前没有待结款项。</td>
|
<td colSpan={5}>目前没有待结款项。</td>
|
||||||
</tr>,
|
</tr>,
|
||||||
)}
|
)}
|
||||||
</tbody>
|
</tbody>
|
||||||
@@ -1012,7 +1021,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderMaterialPoolGlobalSettlement(value) {
|
function renderMaterialPoolGlobalSettlement(value: T.PoolSettlement | null) {
|
||||||
if (!value?.pools?.length) return '';
|
if (!value?.pools?.length) return '';
|
||||||
return (
|
return (
|
||||||
<section className="panel material-report-settlement">
|
<section className="panel material-report-settlement">
|
||||||
@@ -1048,7 +1057,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
<td className="number">¥{yuan(item.transferred)}</td>
|
<td className="number">¥{yuan(item.transferred)}</td>
|
||||||
<td className="number">
|
<td className="number">
|
||||||
{materialReportMoney(item.settlementDue)}
|
{materialReportMoney(item.settlementDue)}
|
||||||
{item.settlementDue < 0 ? (
|
{(item.settlementDue ?? 0) < 0 ? (
|
||||||
<>
|
<>
|
||||||
<>
|
<>
|
||||||
<>
|
<>
|
||||||
@@ -1062,7 +1071,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
</>
|
</>
|
||||||
{'</div>'}
|
{'</div>'}
|
||||||
</>
|
</>
|
||||||
) : item.settlementDue > 0 ? (
|
) : (item.settlementDue ?? 0) > 0 ? (
|
||||||
<>
|
<>
|
||||||
<>
|
<>
|
||||||
<>
|
<>
|
||||||
@@ -1099,11 +1108,11 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderReportOwnershipAccounts(person) {
|
function renderReportOwnershipAccounts(person: T.OwnershipReceipts) {
|
||||||
const ownAccounts = person.accounts.filter(account => account.recipient === person.member),
|
const ownAccounts = person.accounts.filter(account => account.recipient === person.member),
|
||||||
otherAccounts = person.accounts.filter(account => account.recipient !== person.member),
|
otherAccounts = person.accounts.filter(account => account.recipient !== person.member),
|
||||||
net = accounts => accounts.reduce((total, account) => total + account.net, 0);
|
net = (accounts: T.Account[]) => accounts.reduce((total, account) => total + account.net, 0);
|
||||||
const group = (title, rows) => (
|
const group = (title: string, rows: T.Account[]) => (
|
||||||
<section className="report-ownership-account-group">
|
<section className="report-ownership-account-group">
|
||||||
<h3>{title}</h3>
|
<h3>{title}</h3>
|
||||||
{rows.length ? (
|
{rows.length ? (
|
||||||
@@ -1149,7 +1158,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderReportOwnershipBusiness(business, range) {
|
function renderReportOwnershipBusiness(business: T.Business, range: T.Range) {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<>
|
<>
|
||||||
@@ -1164,7 +1173,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderReportRecipientDetails(person, kind = 'receipt') {
|
function renderReportRecipientDetails(person: T.MemberReceipts, kind: 'receipt' | 'refund' = 'receipt') {
|
||||||
const items = person.items.filter(item => item.kind === kind),
|
const items = person.items.filter(item => item.kind === kind),
|
||||||
name = kind === 'receipt' ? '收款' : '退款';
|
name = kind === 'receipt' ? '收款' : '退款';
|
||||||
return (
|
return (
|
||||||
@@ -1175,7 +1184,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
{items.length} 笔{items.some(item => item.amount < 0) ? ',含冲回' : ''}
|
{items.length} 笔{items.some(item => item.amount < 0) ? ',含冲回' : ''}
|
||||||
</span>
|
</span>
|
||||||
</summary>
|
</summary>
|
||||||
<div className="table-wrap" tabIndex="0" role="region" aria-label={person.name + name + '明细表'}>
|
<div className="table-wrap" tabIndex={0} role="region" aria-label={person.name + name + '明细表'}>
|
||||||
<table className="report-receipt-table" aria-label={person.name + name + '逐笔明细'}>
|
<table className="report-receipt-table" aria-label={person.name + name + '逐笔明细'}>
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
@@ -1211,7 +1220,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
)),
|
)),
|
||||||
),
|
),
|
||||||
<tr>
|
<tr>
|
||||||
<td colSpan="4" className="muted">
|
<td colSpan={4} className="muted">
|
||||||
所选范围没有{person.name}
|
所选范围没有{person.name}
|
||||||
{name}记录。
|
{name}记录。
|
||||||
</td>
|
</td>
|
||||||
@@ -1220,7 +1229,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
</tbody>
|
</tbody>
|
||||||
<tfoot>
|
<tfoot>
|
||||||
<tr>
|
<tr>
|
||||||
<td colSpan="3">{name}明细合计</td>
|
<td colSpan={3}>{name}明细合计</td>
|
||||||
<td className="number">¥{yuan(person[kind])}</td>
|
<td className="number">¥{yuan(person[kind])}</td>
|
||||||
</tr>
|
</tr>
|
||||||
</tfoot>
|
</tfoot>
|
||||||
@@ -1230,7 +1239,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function reportAfterSaleHint(cost) {
|
function reportAfterSaleHint(cost: T.PayerCosts) {
|
||||||
return cost.items.some(item => item.kind === 'afterSale') ? (
|
return cost.items.some(item => item.kind === 'afterSale') ? (
|
||||||
<div className="small muted">其中售后 ¥{yuan(reportAfterSaleAmount(cost))}</div>
|
<div className="small muted">其中售后 ¥{yuan(reportAfterSaleAmount(cost))}</div>
|
||||||
) : (
|
) : (
|
||||||
@@ -1238,7 +1247,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function reportCostDetails(cost) {
|
function reportCostDetails(cost: T.PayerCosts) {
|
||||||
const items = reportCostItems(cost);
|
const items = reportCostItems(cost);
|
||||||
return (
|
return (
|
||||||
<details className="report-cost-detail">
|
<details className="report-cost-detail">
|
||||||
@@ -1297,7 +1306,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
)),
|
)),
|
||||||
),
|
),
|
||||||
<tr>
|
<tr>
|
||||||
<td colSpan="3" className="muted">
|
<td colSpan={3} className="muted">
|
||||||
没有需逐项核对的成本。货品成本为 0 的分项已省略。
|
没有需逐项核对的成本。货品成本为 0 的分项已省略。
|
||||||
</td>
|
</td>
|
||||||
</tr>,
|
</tr>,
|
||||||
@@ -1309,7 +1318,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function orderBookIdentity(row, version) {
|
function orderBookIdentity(row: T.Row, version?: string) {
|
||||||
if (row.kind === 'orderAfterSale')
|
if (row.kind === 'orderAfterSale')
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
@@ -1405,13 +1414,13 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const badge = o => (
|
const badge = (o: T.Row) => (
|
||||||
<span className={'order-status ' + (['draft', 'confirmed'].includes(o.status) ? 'danger-text' : 'muted')}>
|
<span className={'order-status ' + (['draft', 'confirmed'].includes(o.status) ? 'danger-text' : 'muted')}>
|
||||||
{label[o.status] || o.status}
|
{label[o.status] || o.status}
|
||||||
</span>
|
</span>
|
||||||
);
|
);
|
||||||
|
|
||||||
function renderInventoryBalanceCount(item) {
|
function renderInventoryBalanceCount(item: T.InventoryBalance) {
|
||||||
return item?.countUnit === 'pair' || pocketCountsEnabled(item?.pocket) ? (
|
return item?.countUnit === 'pair' || pocketCountsEnabled(item?.pocket) ? (
|
||||||
<div className="stock-count-number">{stockCountText(item?.count)}</div>
|
<div className="stock-count-number">{stockCountText(item?.count)}</div>
|
||||||
) : (
|
) : (
|
||||||
@@ -1419,7 +1428,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderReportOwnershipCost(business) {
|
function renderReportOwnershipCost(business: T.Business) {
|
||||||
const showPayers = business.knownTotalCost !== 0 || business.totalCost === null,
|
const showPayers = business.knownTotalCost !== 0 || business.totalCost === null,
|
||||||
others = teamMemberKeys()
|
others = teamMemberKeys()
|
||||||
.filter(key => key !== business.member)
|
.filter(key => key !== business.member)
|
||||||
@@ -1461,7 +1470,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderReportOwnerAdvances(business) {
|
function renderReportOwnerAdvances(business: T.Business) {
|
||||||
const advances = business.ownerAdvances,
|
const advances = business.ownerAdvances,
|
||||||
single = advances.from === advances.date,
|
single = advances.from === advances.date,
|
||||||
label = business.member === 'owner' ? teamMemberName('owner') + '付款明细' : teamMemberName('owner') + '垫付明细';
|
label = business.member === 'owner' ? teamMemberName('owner') + '付款明细' : teamMemberName('owner') + '垫付明细';
|
||||||
@@ -1561,7 +1570,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderReportOwnershipProfit(business, range) {
|
function renderReportOwnershipProfit(business: T.Business, range: T.Range) {
|
||||||
const equation = business.equation,
|
const equation = business.equation,
|
||||||
title = reportMonth || range.from !== range.date ? '本期利润' : '当日利润',
|
title = reportMonth || range.from !== range.date ? '本期利润' : '当日利润',
|
||||||
complete = equation.complete && !business.incomplete && business.totalCost !== null && business.profit !== null,
|
complete = equation.complete && !business.incomplete && business.totalCost !== null && business.profit !== null,
|
||||||
@@ -1580,7 +1589,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
订单总成本 <b>¥{yuan(equation.totalCost)}</b>
|
订单总成本 <b>¥{yuan(equation.totalCost)}</b>
|
||||||
</span>
|
</span>
|
||||||
<span aria-hidden="true">=</span>
|
<span aria-hidden="true">=</span>
|
||||||
<strong className={business.profit < 0 ? 'danger-text' : ''}>¥{yuan(business.profit)}</strong>
|
<strong className={(business.profit ?? 0) < 0 ? 'danger-text' : ''}>¥{yuan(business.profit)}</strong>
|
||||||
</p>
|
</p>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
@@ -1607,7 +1616,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderReportOwnershipCurrentAccount(business) {
|
function renderReportOwnershipCurrentAccount(business: T.Business) {
|
||||||
if (business.member === 'owner') return '';
|
if (business.member === 'owner') return '';
|
||||||
const account = business.currentAccount,
|
const account = business.currentAccount,
|
||||||
days = reportCurrentAccountDays(business);
|
days = reportCurrentAccountDays(business);
|
||||||
@@ -1649,7 +1658,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderReportReceiptIdentity(item) {
|
function renderReportReceiptIdentity(item: T.ReceiptItem) {
|
||||||
const number = item.paper_number || item.number || (item.price_lock_id ? '锁价记录' : '订单记录');
|
const number = item.paper_number || item.number || (item.price_lock_id ? '锁价记录' : '订单记录');
|
||||||
const identity = item.order_id ? (
|
const identity = item.order_id ? (
|
||||||
<button
|
<button
|
||||||
@@ -1699,7 +1708,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function materialReportCostLink(item) {
|
function materialReportCostLink(item: T.CostItem) {
|
||||||
return item.materialPoolId ? (
|
return item.materialPoolId ? (
|
||||||
<button
|
<button
|
||||||
className="link-button"
|
className="link-button"
|
||||||
@@ -1714,7 +1723,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function afterSaleEditButton(row) {
|
function afterSaleEditButton(row: T.Row) {
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -1729,7 +1738,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderReportPoolMaterial(business) {
|
function renderReportPoolMaterial(business: T.Business) {
|
||||||
const pool = business.poolMaterial;
|
const pool = business.poolMaterial;
|
||||||
if (!pool?.days.length) return '';
|
if (!pool?.days.length) return '';
|
||||||
const owner = pool.byPayer.owner;
|
const owner = pool.byPayer.owner;
|
||||||
@@ -1764,7 +1773,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function reportOwnerAdvanceIdentity(item) {
|
function reportOwnerAdvanceIdentity(item: T.AdvanceItem) {
|
||||||
return item.kind === 'order' ? (
|
return item.kind === 'order' ? (
|
||||||
<>
|
<>
|
||||||
<button
|
<button
|
||||||
@@ -1785,7 +1794,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function priceLockCostLink(item) {
|
function priceLockCostLink(item: T.CostItem) {
|
||||||
if (item.kind === 'afterSale') return reportCostIdentity(item);
|
if (item.kind === 'afterSale') return reportCostIdentity(item);
|
||||||
if (item.price_lock_id)
|
if (item.price_lock_id)
|
||||||
return (
|
return (
|
||||||
@@ -1813,7 +1822,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderReportPoolMaterialDay(day) {
|
function renderReportPoolMaterialDay(day: T.PoolDay) {
|
||||||
if (!day.sources)
|
if (!day.sources)
|
||||||
return (
|
return (
|
||||||
<li>
|
<li>
|
||||||
@@ -1,8 +1,9 @@
|
|||||||
|
import type * as T from './contracts';
|
||||||
import { Calc as LedgerCalc, Values } from '../../shared';
|
import { Calc as LedgerCalc, Values } from '../../shared';
|
||||||
import ReportRules from '@public/report-rules.js';
|
import ReportRules from '@public/report-rules.js';
|
||||||
const { reportAfterSaleAmount, reportCostItems, reportRowCost, reportCurrentAccountDays } = ReportRules;
|
const { reportAfterSaleAmount, reportCostItems, reportRowCost, reportCurrentAccountDays } = ReportRules;
|
||||||
export function reportData({ state, session, reportMonth, reportMember }) {
|
export function reportData({ state, session, reportMonth, reportMember }: T.ReportContext) {
|
||||||
function reportDownloadText(r) {
|
function reportDownloadText(r: T.Report) {
|
||||||
if (teamMode() && typeof reportTeamDownloadText === 'function') return reportTeamDownloadText(r);
|
if (teamMode() && typeof reportTeamDownloadText === 'function') return reportTeamDownloadText(r);
|
||||||
const s = r.summary,
|
const s = r.summary,
|
||||||
receipts = r.receiptsByOrderDate,
|
receipts = r.receiptsByOrderDate,
|
||||||
@@ -113,7 +114,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
|||||||
);
|
);
|
||||||
if (assistantFirst)
|
if (assistantFirst)
|
||||||
keys = [...keys.filter(member => member !== 'owner'), ...keys.filter(member => member === 'owner')];
|
keys = [...keys.filter(member => member !== 'owner'), ...keys.filter(member => member === 'owner')];
|
||||||
const options = keys.map(member => [
|
const options = keys.map((member): [string, string] => [
|
||||||
member,
|
member,
|
||||||
teamMemberName(member) + (historical && !teamMemberEnabled(member) ? '(已停用)' : ''),
|
teamMemberName(member) + (historical && !teamMemberEnabled(member) ? '(已停用)' : ''),
|
||||||
]);
|
]);
|
||||||
@@ -132,42 +133,42 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
|||||||
|
|
||||||
const validOrderDate = Values.validDate;
|
const validOrderDate = Values.validDate;
|
||||||
|
|
||||||
function dailyFundsMoney(value) {
|
function dailyFundsMoney(value: T.Amount | undefined) {
|
||||||
return value == null ? '待确认' : '¥' + yuan(value);
|
return value == null ? '待确认' : '¥' + yuan(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
function reimbursementDraftTotal(items) {
|
function reimbursementDraftTotal(items: { amount: string }[]) {
|
||||||
const { total, complete, amounts } = ReportRules.reimbursementAmounts(items, LedgerCalc.cents);
|
const { total, complete, amounts } = ReportRules.reimbursementAmounts(items, LedgerCalc.cents);
|
||||||
return { total, complete, formula: amounts.map(amount => '¥' + yuan(amount)).join(' + ') };
|
return { total, complete, formula: amounts.map(amount => '¥' + yuan(amount)).join(' + ') };
|
||||||
}
|
}
|
||||||
|
|
||||||
function teamDataKeys(data) {
|
function teamDataKeys(data: object) {
|
||||||
return [...assistantMemberKeys(), 'owner'].filter(member => data && Object.hasOwn(data, member));
|
return [...assistantMemberKeys(), 'owner'].filter(member => data && Object.hasOwn(data, member));
|
||||||
}
|
}
|
||||||
|
|
||||||
function reportSummaryAmount(summary, key) {
|
function reportSummaryAmount(summary: T.Summary, key: T.Metric) {
|
||||||
const missing = summary.unknownCounts?.[key] || 0;
|
const missing = summary.unknownCounts?.[key] || 0;
|
||||||
return missing && summary.knownCounts?.[key] === 0 && !summary[key] && !summary.afterSaleCount
|
return missing && summary.knownCounts?.[key] === 0 && !summary[key] && !summary.afterSaleCount
|
||||||
? '待补齐'
|
? '待补齐'
|
||||||
: (missing ? '已知 ' : '') + '¥' + yuan(summary[key]);
|
: (missing ? '已知 ' : '') + '¥' + yuan(summary[key]);
|
||||||
}
|
}
|
||||||
|
|
||||||
const yuan = n => (n == null ? '待补' : Values.yuan(n));
|
const yuan = (n: T.Amount | undefined) => (n == null ? '待补' : Values.yuan(n));
|
||||||
|
|
||||||
function reportPeriod(range) {
|
function reportPeriod(range: T.Range) {
|
||||||
return range.from === range.date ? range.date : range.from + ' 至 ' + range.date;
|
return range.from === range.date ? range.date : range.from + ' 至 ' + range.date;
|
||||||
}
|
}
|
||||||
|
|
||||||
function accountDisplayName(value) {
|
function accountDisplayName(value: string) {
|
||||||
const account = accountIdentity(value);
|
const account = accountIdentity(value);
|
||||||
return account ? teamMemberName(account.member) + account.channel : value;
|
return account ? teamMemberName(account.member) + account.channel : value;
|
||||||
}
|
}
|
||||||
|
|
||||||
function reportDailyProfitAmount(value, known, profit = false) {
|
function reportDailyProfitAmount(value: T.Amount, known: number, profit = false) {
|
||||||
return value === null ? (profit ? '待核算(已核算 ¥' : '待补齐(已知 ¥') + yuan(known) + ')' : '¥' + yuan(value);
|
return value === null ? (profit ? '待核算(已核算 ¥' : '待补齐(已知 ¥') + yuan(known) + ')' : '¥' + yuan(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
function reportTeamDownloadText(report) {
|
function reportTeamDownloadText(report: T.Report) {
|
||||||
const summary = report.summary,
|
const summary = report.summary,
|
||||||
receipts = report.receiptsByOrderDate;
|
receipts = report.receiptsByOrderDate;
|
||||||
return [
|
return [
|
||||||
@@ -215,11 +216,11 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
|||||||
].join('\n');
|
].join('\n');
|
||||||
}
|
}
|
||||||
|
|
||||||
function reportCostAmount(value, partial = 0) {
|
function reportCostAmount(value: T.Amount | undefined, partial = 0) {
|
||||||
return partial && value === 0 ? '待补齐' : (partial ? '已知 ' : '') + '¥' + yuan(value);
|
return partial && value === 0 ? '待补齐' : (partial ? '已知 ' : '') + '¥' + yuan(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
function reportPayerHints(cost) {
|
function reportPayerHints(cost: T.PayerCosts) {
|
||||||
return [
|
return [
|
||||||
cost.missingCount ? cost.missingCount + ' 项成本待补齐' : '',
|
cost.missingCount ? cost.missingCount + ' 项成本待补齐' : '',
|
||||||
cost.pendingCount ? cost.pendingCount + ' 项费用未入账,不计合计' : '',
|
cost.pendingCount ? cost.pendingCount + ' 项费用未入账,不计合计' : '',
|
||||||
@@ -228,7 +229,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
|||||||
.join(';');
|
.join(';');
|
||||||
}
|
}
|
||||||
|
|
||||||
function reportCostIdentity(item) {
|
function reportCostIdentity(item: T.CostItem) {
|
||||||
if (item.materialPoolId) return item.materialPoolId + ' 购料';
|
if (item.materialPoolId) return item.materialPoolId + ' 购料';
|
||||||
return item.kind === 'afterSale'
|
return item.kind === 'afterSale'
|
||||||
? '售后 · ' + (item.customer || '未填客户')
|
? '售后 · ' + (item.customer || '未填客户')
|
||||||
@@ -237,7 +238,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
|||||||
(item.customer ? ' · ' + item.customer : '');
|
(item.customer ? ' · ' + item.customer : '');
|
||||||
}
|
}
|
||||||
|
|
||||||
function reportCostFormula(item) {
|
function reportCostFormula(item: T.CostItem) {
|
||||||
const c = item.calculation;
|
const c = item.calculation;
|
||||||
if (!c) return '';
|
if (!c) return '';
|
||||||
return (
|
return (
|
||||||
@@ -252,17 +253,17 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function reportCostItemAmount(item) {
|
function reportCostItemAmount(item: T.CostItem) {
|
||||||
if (item.kind === 'pending')
|
if (item.kind === 'pending')
|
||||||
return '未入账' + (item.amount == null ? '(金额待补)' : '(登记 ¥' + yuan(item.amount) + ')');
|
return '未入账' + (item.amount == null ? '(金额待补)' : '(登记 ¥' + yuan(item.amount) + ')');
|
||||||
return item.amount == null ? '待补齐' : '¥' + yuan(item.amount);
|
return item.amount == null ? '待补齐' : '¥' + yuan(item.amount);
|
||||||
}
|
}
|
||||||
|
|
||||||
function afterSalePayerName(row) {
|
function afterSalePayerName(row: T.Row) {
|
||||||
return row.costItems?.[0]?.payer ? teamMemberName(row.costItems[0].payer) : '付款人待补';
|
return row.costItems?.[0]?.payer ? teamMemberName(row.costItems[0].payer) : '付款人待补';
|
||||||
}
|
}
|
||||||
|
|
||||||
const label = {
|
const label: Record<string, string> = {
|
||||||
draft: '旧草稿',
|
draft: '旧草稿',
|
||||||
confirmed: '旧单待补齐',
|
confirmed: '旧单待补齐',
|
||||||
delivered: '已完成',
|
delivered: '已完成',
|
||||||
@@ -272,7 +273,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
|||||||
recovery: '回收',
|
recovery: '回收',
|
||||||
};
|
};
|
||||||
|
|
||||||
function reportRowAmount(row, key) {
|
function reportRowAmount(row: T.Row, key: T.RowMetric) {
|
||||||
if (row.status === 'draft') return '未开单';
|
if (row.status === 'draft') return '未开单';
|
||||||
if (key === 'goods') {
|
if (key === 'goods') {
|
||||||
const c = reportRowCost(row);
|
const c = reportRowCost(row);
|
||||||
@@ -283,9 +284,9 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
|||||||
return row.known?.[key] ? '已知 ¥' + yuan(row.known[key]) + '(待补齐)' : '待补齐';
|
return row.known?.[key] ? '已知 ¥' + yuan(row.known[key]) + '(待补齐)' : '待补齐';
|
||||||
}
|
}
|
||||||
|
|
||||||
function reportDailyProfitsText(r) {
|
function reportDailyProfitsText(r: T.Report) {
|
||||||
const table = r.dailyProfits,
|
const table = r.dailyProfits,
|
||||||
rowText = row =>
|
rowText = (row: T.Profit) =>
|
||||||
`销售净额 ¥${yuan(row.sales)} / 成本 ${reportDailyProfitAmount(row.totalCost, row.knownTotalCost)} / 利润 ${reportDailyProfitAmount(row.profit, row.knownProfit, true)}`;
|
`销售净额 ¥${yuan(row.sales)} / 成本 ${reportDailyProfitAmount(row.totalCost, row.knownTotalCost)} / 利润 ${reportDailyProfitAmount(row.profit, row.knownProfit, true)}`;
|
||||||
return [
|
return [
|
||||||
'每日利润表(按日期与订单归属人;普通订单按开单日、锁价成单按交付日、售后按记录日)',
|
'每日利润表(按日期与订单归属人;普通订单按开单日、锁价成单按交付日、售后按记录日)',
|
||||||
@@ -297,7 +298,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
function reportOwnershipReceiptsText(r) {
|
function reportOwnershipReceiptsText(r: T.Report) {
|
||||||
return [
|
return [
|
||||||
'按订单归属核对净收入(收款减退款,已含他人代收,尚未扣成本与费用)',
|
'按订单归属核对净收入(收款减退款,已含他人代收,尚未扣成本与费用)',
|
||||||
...reportOwnershipKeys(r).flatMap(key => {
|
...reportOwnershipKeys(r).flatMap(key => {
|
||||||
@@ -315,7 +316,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
function dailyFundsDownloadText(report) {
|
function dailyFundsDownloadText(report: T.Report) {
|
||||||
const range = {
|
const range = {
|
||||||
date: report.date,
|
date: report.date,
|
||||||
from: report.from,
|
from: report.from,
|
||||||
@@ -344,9 +345,9 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
|||||||
if (data.ready)
|
if (data.ready)
|
||||||
result.push(
|
result.push(
|
||||||
`${teamMemberName('owner')}净收款 ¥${yuan(data.ownerReceipts.net)} − 确认完整对外支出 ¥${yuan(data.actualOutlay)} + 已批准报销 ¥${yuan(data.approvedReimbursements)} = 应转合计 ¥${yuan(data.transferAmount)}`,
|
`${teamMemberName('owner')}净收款 ¥${yuan(data.ownerReceipts.net)} − 确认完整对外支出 ¥${yuan(data.actualOutlay)} + 已批准报销 ¥${yuan(data.approvedReimbursements)} = 应转合计 ¥${yuan(data.transferAmount)}`,
|
||||||
data.transferAmount > 0
|
(data.transferAmount ?? 0) > 0
|
||||||
? '方向:' + teamMemberName('owner') + '转' + teamMemberName('assistant')
|
? '方向:' + teamMemberName('owner') + '转' + teamMemberName('assistant')
|
||||||
: data.transferAmount < 0
|
: (data.transferAmount ?? 0) < 0
|
||||||
? '方向:' + teamMemberName('assistant') + '转' + teamMemberName('owner')
|
? '方向:' + teamMemberName('assistant') + '转' + teamMemberName('owner')
|
||||||
: '方向:无需转款',
|
: '方向:无需转款',
|
||||||
);
|
);
|
||||||
@@ -370,14 +371,14 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
function reportRecipientReceiptsText(r) {
|
function reportRecipientReceiptsText(r: T.Report) {
|
||||||
return [
|
return [
|
||||||
'按收款人汇总(普通订单按开单日归集当前收付,锁价按实际收付日归集;负数为冲回)',
|
'按收款人汇总(普通订单按开单日归集当前收付,锁价按实际收付日归集;负数为冲回)',
|
||||||
...teamDataKeys(r.recipientReceipts).flatMap(key => {
|
...teamDataKeys(r.recipientReceipts).flatMap(key => {
|
||||||
const person = r.recipientReceipts[key];
|
const person = r.recipientReceipts[key];
|
||||||
return [
|
return [
|
||||||
`${person.name}总收款:¥${yuan(person.receipt)};退款 ¥${yuan(person.refund)};净收款 ¥${yuan(person.net)}`,
|
`${person.name}总收款:¥${yuan(person.receipt)};退款 ¥${yuan(person.refund)};净收款 ¥${yuan(person.net)}`,
|
||||||
...['receipt', 'refund'].flatMap(kind => {
|
...(['receipt', 'refund'] as const).flatMap(kind => {
|
||||||
const items = person.items.filter(item => item.kind === kind),
|
const items = person.items.filter(item => item.kind === kind),
|
||||||
name = kind === 'receipt' ? '收款' : '退款';
|
name = kind === 'receipt' ? '收款' : '退款';
|
||||||
return [
|
return [
|
||||||
@@ -397,7 +398,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
function priceLockActivityText(activity) {
|
function priceLockActivityText(activity: T.PriceActivity | null) {
|
||||||
if (!activity?.summary?.eventCount) return [];
|
if (!activity?.summary?.eventCount) return [];
|
||||||
const s = activity.summary;
|
const s = activity.summary;
|
||||||
return [
|
return [
|
||||||
@@ -413,25 +414,27 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
|||||||
|
|
||||||
const grams = Values.grams;
|
const grams = Values.grams;
|
||||||
|
|
||||||
const materialPayerName = payer => (payer ? teamMemberName(payer) : '待补');
|
const materialPayerName = (payer?: string) => (payer ? teamMemberName(payer) : '待补');
|
||||||
|
|
||||||
function pocketLabel(key) {
|
function pocketLabel(key: string) {
|
||||||
return state?.pocketCatalog?.find(row => row.key === key)?.name || String(key ?? '');
|
return state?.pocketCatalog?.find(row => row.key === key)?.name || String(key ?? '');
|
||||||
}
|
}
|
||||||
|
|
||||||
function pocketCountsEnabled(key) {
|
function pocketCountsEnabled(key: string) {
|
||||||
return !!key && state?.pocketCatalog?.some(row => row.key === key && row.countUnit === 'pair') === true;
|
return !!key && state?.pocketCatalog?.some(row => row.key === key && row.countUnit === 'pair') === true;
|
||||||
}
|
}
|
||||||
|
|
||||||
function stockCountText(value, { signed = false, unknown = '未记录对数' } = {}) {
|
function stockCountText(value: number | null | undefined, { signed = false, unknown = '未记录对数' } = {}) {
|
||||||
return Number.isSafeInteger(value) ? (signed && value > 0 ? '+' : '') + value + '对' : unknown;
|
return typeof value === 'number' && Number.isSafeInteger(value)
|
||||||
|
? (signed && value > 0 ? '+' : '') + value + '对'
|
||||||
|
: unknown;
|
||||||
}
|
}
|
||||||
|
|
||||||
function materialReportMoney(value) {
|
function materialReportMoney(value: T.Amount | undefined) {
|
||||||
return value == null ? '料费待补' : '¥' + yuan(value);
|
return value == null ? '料费待补' : '¥' + yuan(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
function teamMemberName(member) {
|
function teamMemberName(member: string) {
|
||||||
return (
|
return (
|
||||||
state?.shopSettings?.members?.find(row => row.member === member)?.label ||
|
state?.shopSettings?.members?.find(row => row.member === member)?.label ||
|
||||||
state?.members?.find(row => row.member === member)?.label ||
|
state?.members?.find(row => row.member === member)?.label ||
|
||||||
@@ -463,7 +466,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
|||||||
return teamMemberKeys().filter(teamMemberEnabled);
|
return teamMemberKeys().filter(teamMemberEnabled);
|
||||||
}
|
}
|
||||||
|
|
||||||
function teamMemberEnabled(member) {
|
function teamMemberEnabled(member: string) {
|
||||||
return Values.memberEnabled(state, member);
|
return Values.memberEnabled(state, member);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -471,9 +474,9 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
|||||||
return teamMemberKeys().filter(member => member !== 'owner');
|
return teamMemberKeys().filter(member => member !== 'owner');
|
||||||
}
|
}
|
||||||
|
|
||||||
const accountIdentity = value => Values.accountIdentity(teamMemberKeys(), value);
|
const accountIdentity = (value: string) => Values.accountIdentity(teamMemberKeys(), value);
|
||||||
|
|
||||||
function priceLockActivityRows(activity) {
|
function priceLockActivityRows(activity: T.PriceActivity | null) {
|
||||||
if (!activity) return [];
|
if (!activity) return [];
|
||||||
return [...(activity.customerCash || []), ...(activity.orderPayments || [])]
|
return [...(activity.customerCash || []), ...(activity.orderPayments || [])]
|
||||||
.map(item => ({
|
.map(item => ({
|
||||||
@@ -505,17 +508,18 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
|||||||
.sort((a, b) => a.date.localeCompare(b.date));
|
.sort((a, b) => a.date.localeCompare(b.date));
|
||||||
}
|
}
|
||||||
|
|
||||||
const materialPurchasePayer = purchase => purchase.payer ?? purchase.actualpayer ?? purchase.actualPayer;
|
const materialPurchasePayer = (purchase: T.MaterialPurchase) =>
|
||||||
|
purchase.payer ?? purchase.actualpayer ?? purchase.actualPayer;
|
||||||
|
|
||||||
function peopleCountReportLines(count) {
|
function peopleCountReportLines(count: T.PeopleCount) {
|
||||||
const period = count?.from !== count?.date;
|
const period = count?.from !== count?.date;
|
||||||
return peopleParts(true).map(
|
return peopleParts(true).map(
|
||||||
([part, name]) =>
|
([part, name]) =>
|
||||||
`${peopleCountDisplayName(name, period)}:${peopleCountText(count, part)}${period ? '(期末 ' + (count?.date || '未知') + ';开始日前最近记录 ' + (count?.[part]?.baselineDate || '暂无') + ')' : ''}`,
|
`${peopleCountDisplayName(name, period)}:${peopleCountText(count, part)}${period ? '(期末 ' + (count?.date || '未知') + ';开始日前最近记录 ' + (countForPart(count, part)?.baselineDate || '暂无') + ')' : ''}`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function reportOwnershipBusinessText(business) {
|
function reportOwnershipBusinessText(business: T.Business) {
|
||||||
return [
|
return [
|
||||||
`所属订单总成本:${reportBusinessAmount(business.totalCost, business.knownTotalCost)};本人付款 ${reportBusinessAmount(business.selfCost, business.knownSelfCost)};他人付款 ${reportBusinessAmount(business.otherCost, business.knownOtherCost)}`,
|
`所属订单总成本:${reportBusinessAmount(business.totalCost, business.knownTotalCost)};本人付款 ${reportBusinessAmount(business.selfCost, business.knownSelfCost)};他人付款 ${reportBusinessAmount(business.otherCost, business.knownOtherCost)}`,
|
||||||
...reportPoolMaterialText(business),
|
...reportPoolMaterialText(business),
|
||||||
@@ -531,7 +535,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
function reportReceiptBasis(item) {
|
function reportReceiptBasis(item: T.ReceiptItem) {
|
||||||
return item.order_after_sale
|
return item.order_after_sale
|
||||||
? '订单售后 · 按实际收付日'
|
? '订单售后 · 按实际收付日'
|
||||||
: item.price_lock_id
|
: item.price_lock_id
|
||||||
@@ -539,13 +543,11 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
|||||||
: '普通订单 · 开单 ' + (item.order_date || '日期未提供');
|
: '普通订单 · 开单 ' + (item.order_date || '日期未提供');
|
||||||
}
|
}
|
||||||
|
|
||||||
function reportReceiptLabel(item) {
|
function reportReceiptLabel(item: T.ReceiptItem) {
|
||||||
return (item.kind === 'receipt' ? '收款' : '退款') + (item.amount < 0 ? '冲回' : '');
|
return (item.kind === 'receipt' ? '收款' : '退款') + (item.amount < 0 ? '冲回' : '');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const priceLockPayerName = (payer: string) => (payer ? teamMemberName(payer) : '待补');
|
||||||
|
|
||||||
const priceLockPayerName = payer => (payer ? teamMemberName(payer) : '待补');
|
|
||||||
|
|
||||||
function peopleParts(historical = false) {
|
function peopleParts(historical = false) {
|
||||||
const keys = assistantMemberKeys().filter(member => historical || teamMemberEnabled(member)),
|
const keys = assistantMemberKeys().filter(member => historical || teamMemberEnabled(member)),
|
||||||
@@ -555,12 +557,16 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
|||||||
: parts;
|
: parts;
|
||||||
}
|
}
|
||||||
|
|
||||||
function peopleCountDisplayName(name, period = false) {
|
function peopleCountDisplayName(name: string, period = false) {
|
||||||
return name.replace('人数', period ? '结束日总人数' : '当日总人数');
|
return name.replace('人数', period ? '结束日总人数' : '当日总人数');
|
||||||
}
|
}
|
||||||
|
|
||||||
function peopleCountText(count, part = null) {
|
function countForPart(count: T.PeopleCount, part: string) {
|
||||||
const value = part ? count?.[part] : count;
|
const value = count?.[part];
|
||||||
|
return value && typeof value === 'object' ? value : undefined;
|
||||||
|
}
|
||||||
|
function peopleCountText(count: T.PeopleCount, part: string | null = null) {
|
||||||
|
const value = part ? countForPart(count, part) : count;
|
||||||
if (!value || !Object.hasOwn(value, 'endTotal') || !Object.hasOwn(value, 'netChange')) return '尚未取得总人数';
|
if (!value || !Object.hasOwn(value, 'endTotal') || !Object.hasOwn(value, 'netChange')) return '尚未取得总人数';
|
||||||
const period = count.from !== count.date,
|
const period = count.from !== count.date,
|
||||||
total = value.endTotal === null ? (period ? '结束日未记录' : '当日未记录') : value.endTotal + ' 人(已记录)';
|
total = value.endTotal === null ? (period ? '结束日未记录' : '当日未记录') : value.endTotal + ' 人(已记录)';
|
||||||
@@ -583,11 +589,11 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function reportBusinessAmount(value, known) {
|
function reportBusinessAmount(value: T.Amount, known: number) {
|
||||||
return (value === null ? '已知 ' : '') + '¥' + yuan(value === null ? known : value);
|
return (value === null ? '已知 ' : '') + '¥' + yuan(value === null ? known : value);
|
||||||
}
|
}
|
||||||
|
|
||||||
function reportPoolMaterialText(business) {
|
function reportPoolMaterialText(business: T.Business) {
|
||||||
const pool = business.poolMaterial;
|
const pool = business.poolMaterial;
|
||||||
if (!pool?.days.length) return [];
|
if (!pool?.days.length) return [];
|
||||||
const owner = pool.byPayer.owner;
|
const owner = pool.byPayer.owner;
|
||||||
@@ -603,7 +609,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
function reportOwnerAdvancesText(business) {
|
function reportOwnerAdvancesText(business: T.Business) {
|
||||||
const advances = business.ownerAdvances,
|
const advances = business.ownerAdvances,
|
||||||
label = business.member === 'owner' ? teamMemberName('owner') + '付款明细' : teamMemberName('owner') + '垫付明细';
|
label = business.member === 'owner' ? teamMemberName('owner') + '付款明细' : teamMemberName('owner') + '垫付明细';
|
||||||
return [
|
return [
|
||||||
@@ -625,7 +631,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
function reportCurrentAccountText(business) {
|
function reportCurrentAccountText(business: T.Business) {
|
||||||
if (business.member === 'owner') return [];
|
if (business.member === 'owner') return [];
|
||||||
return [
|
return [
|
||||||
'当日往来账(逐日核对,不含历史余额,未扣实际转账)',
|
'当日往来账(逐日核对,不含历史余额,未扣实际转账)',
|
||||||
@@ -637,16 +643,15 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function reportOwnerAdvanceAmount(value: T.Amount | undefined, known?: number) {
|
||||||
function reportOwnerAdvanceAmount(value, known) {
|
|
||||||
return value === null ? '待补(已知 ¥' + yuan(known) + ')' : '¥' + yuan(value);
|
return value === null ? '待补(已知 ¥' + yuan(known) + ')' : '¥' + yuan(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
function reportOwnerAdvanceFormula(business, day) {
|
function reportOwnerAdvanceFormula(business: T.Business, day: Partial<T.AdvanceDay>) {
|
||||||
return `${business.member === 'owner' ? teamMemberName('owner') + '付款合计' : teamMemberName('owner') + '垫付合计'}:料池料费 ${reportOwnerAdvanceAmount(day.poolAmount, day.knownPoolAmount)} + 其他成本 ${reportOwnerAdvanceAmount(day.otherAmount, day.knownOtherAmount)} = ${reportOwnerAdvanceAmount(day.amount, day.knownAmount)}`;
|
return `${business.member === 'owner' ? teamMemberName('owner') + '付款合计' : teamMemberName('owner') + '垫付合计'}:料池料费 ${reportOwnerAdvanceAmount(day.poolAmount, day.knownPoolAmount)} + 其他成本 ${reportOwnerAdvanceAmount(day.otherAmount, day.knownOtherAmount)} = ${reportOwnerAdvanceAmount(day.amount, day.knownAmount)}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function reportOwnerAdvanceItemAmount(item) {
|
function reportOwnerAdvanceItemAmount(item: T.AdvanceItem) {
|
||||||
if (item.status === 'pending')
|
if (item.status === 'pending')
|
||||||
return (
|
return (
|
||||||
'待核对' +
|
'待核对' +
|
||||||
@@ -656,7 +661,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
|||||||
return item.amount === null ? '待补齐' : '¥' + yuan(item.amount);
|
return item.amount === null ? '待补齐' : '¥' + yuan(item.amount);
|
||||||
}
|
}
|
||||||
|
|
||||||
function reportCurrentAccountDirection(business, day) {
|
function reportCurrentAccountDirection(business: T.Business, day: T.CurrentDisplayDay) {
|
||||||
return day.amount === null
|
return day.amount === null
|
||||||
? '应转金额待核算'
|
? '应转金额待核算'
|
||||||
: day.amount > 0
|
: day.amount > 0
|
||||||
@@ -666,15 +671,15 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
|||||||
: '当日无需转款';
|
: '当日无需转款';
|
||||||
}
|
}
|
||||||
|
|
||||||
function reportCurrentAccountFormula(day) {
|
function reportCurrentAccountFormula(day: T.CurrentDisplayDay) {
|
||||||
return `${teamMemberName('owner')}垫付已用料费 ${reportOwnerAdvanceAmount(day.materialCost, day.knownMaterialCost)} + ${teamMemberName('owner')}垫付其他订单成本 ${reportOwnerAdvanceAmount(day.otherCost, day.knownOtherCost)} + 本人当日订单净利润 ${reportDailyProfitAmount(day.profit, day.knownProfit, true)} − ${teamMemberName('owner')}代收净额 ¥${yuan(day.ownerNetReceipts)} = ${day.amount === null ? '待核算' : '¥' + yuan(day.amount)}`;
|
return `${teamMemberName('owner')}垫付已用料费 ${reportOwnerAdvanceAmount(day.materialCost, day.knownMaterialCost)} + ${teamMemberName('owner')}垫付其他订单成本 ${reportOwnerAdvanceAmount(day.otherCost, day.knownOtherCost)} + 本人当日订单净利润 ${reportDailyProfitAmount(day.profit, day.knownProfit, true)} − ${teamMemberName('owner')}代收净额 ¥${yuan(day.ownerNetReceipts)} = ${day.amount === null ? '待核算' : '¥' + yuan(day.amount)}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function peoplePartMember(part) {
|
function peoplePartMember(part: string) {
|
||||||
return part === 'assistant1' ? 'assistant' : part;
|
return part === 'assistant1' ? 'assistant' : part;
|
||||||
}
|
}
|
||||||
|
|
||||||
function peopleCountUnknownReason(reason, period = false) {
|
function peopleCountUnknownReason(reason: string, period = false) {
|
||||||
return (
|
return (
|
||||||
{
|
{
|
||||||
'missing-current': period ? '结束日未记录' : '当日未记录',
|
'missing-current': period ? '结束日未记录' : '当日未记录',
|
||||||
@@ -684,15 +689,17 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function peopleCountSignedText(value) {
|
function peopleCountSignedText(value: number) {
|
||||||
return (value > 0 ? '+' : '') + value + ' 人';
|
return (value > 0 ? '+' : '') + value + ' 人';
|
||||||
}
|
}
|
||||||
|
|
||||||
function peopleCountDeltaText(value) {
|
function peopleCountDeltaText(value: number) {
|
||||||
return value > 0 ? '新增 ' + value + ' 人' : value < 0 ? '减少 ' + Math.abs(value) + ' 人' : '无变化(0 人)';
|
return value > 0 ? '新增 ' + value + ' 人' : value < 0 ? '减少 ' + Math.abs(value) + ' 人' : '无变化(0 人)';
|
||||||
}
|
}
|
||||||
|
|
||||||
function reportPoolMaterialFormula(day) {
|
function reportPoolMaterialFormula(
|
||||||
|
day: Pick<T.PoolDay, 'mg' | 'averageRate' | 'amount' | 'knownAmount' | 'sources'>,
|
||||||
|
) {
|
||||||
if (day.sources)
|
if (day.sources)
|
||||||
return (
|
return (
|
||||||
day.sources
|
day.sources
|
||||||
@@ -706,7 +713,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
|||||||
return `${grams(day.mg)}g × ${day.averageRate === null ? '待补料价' : '¥' + yuan(day.averageRate) + '/g'} = ${day.amount === null ? '料费待补(已知 ¥' + yuan(day.knownAmount) + ')' : '¥' + yuan(day.amount)}`;
|
return `${grams(day.mg)}g × ${day.averageRate === null ? '待补料价' : '¥' + yuan(day.averageRate) + '/g'} = ${day.amount === null ? '料费待补(已知 ¥' + yuan(day.knownAmount) + ')' : '¥' + yuan(day.amount)}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function reportPoolMaterialPendingNote(pool) {
|
function reportPoolMaterialPendingNote(pool: T.PoolMaterial) {
|
||||||
return pool.days.some(
|
return pool.days.some(
|
||||||
day => day.sources && day.sources.reduce((total, source) => total + source.knownAmount, 0) > day.knownAmount,
|
day => day.sources && day.sources.reduce((total, source) => total + source.knownAmount, 0) > day.knownAmount,
|
||||||
)
|
)
|
||||||
@@ -714,22 +721,23 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
|||||||
: '';
|
: '';
|
||||||
}
|
}
|
||||||
|
|
||||||
function reportPoolMaterialSourceLabel(source) {
|
function reportPoolMaterialSourceLabel(source: T.MaterialSource) {
|
||||||
return (
|
return (
|
||||||
(source.kind === 'personal_recovery' ? teamMemberName(source.member) + '个人回收料' : '公共料') +
|
(source.kind === 'personal_recovery' ? teamMemberName(source.member) + '个人回收料' : '公共料') +
|
||||||
(source.priceLocked ? '(含锁价原料)' : '')
|
(source.priceLocked ? '(含锁价原料)' : '')
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
const { validateDailyFunds, validateReport, validateDailyReimbursements, reportActiveAccounts, reportOwnershipKeys } = ReportRules.forContext({
|
const { validateDailyFunds, validateReport, validateDailyReimbursements, reportActiveAccounts, reportOwnershipKeys } =
|
||||||
teamDataKeys,
|
ReportRules.forContext({
|
||||||
validOrderDate,
|
teamDataKeys,
|
||||||
teamMode,
|
validOrderDate,
|
||||||
currentMember,
|
teamMode,
|
||||||
teamMemberKeys,
|
currentMember,
|
||||||
isReimbursementStatus: value => Object.hasOwn(reimbursementStatusNames, value),
|
teamMemberKeys,
|
||||||
state,
|
isReimbursementStatus: value => Object.hasOwn(reimbursementStatusNames, value),
|
||||||
reportMember,
|
state,
|
||||||
});
|
reportMember,
|
||||||
|
});
|
||||||
return {
|
return {
|
||||||
validateReport,
|
validateReport,
|
||||||
validateDailyFunds,
|
validateDailyFunds,
|
||||||
+9
@@ -0,0 +1,9 @@
|
|||||||
|
// Classic scripts install these names in the browser. Node tests and Vite use the same CommonJS exports.
|
||||||
|
declare var LedgerCalc: typeof import('../../../public/calculations.js');
|
||||||
|
declare var CreditCardFees: typeof import('../../../public/credit-card-fees.js');
|
||||||
|
declare var FeeEstimates: typeof import('../../../public/fee-estimates.js');
|
||||||
|
declare var OrderFormula: typeof import('../../../public/order-formula.js');
|
||||||
|
declare var OrderTemplates: typeof import('../../../public/order-templates.js');
|
||||||
|
declare var OrderCopy: typeof import('../../../public/order-copy.js');
|
||||||
|
declare var OrderEntryModel: typeof import('../../../public/order-entry-model.js');
|
||||||
|
declare var LedgerValues: typeof import('../../../public/ledger-values.js');
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
import type { SyncContext, LineState, OrderForm } from './types';
|
||||||
|
import type { Pool, Allocation } from '../pages/MaterialPools/model';
|
||||||
|
import type { QuoteBalance, QuoteSource } from '../lib/materialQuote';
|
||||||
|
|
||||||
|
export type Uuid = () => string;
|
||||||
|
export type LineContext = Pick<SyncContext, 'st' | 'uuid'> & { member?: string; historicalPocket?: boolean };
|
||||||
|
export type MoneyMode = 'gram' | 'total';
|
||||||
|
export interface ManualMaterial {
|
||||||
|
mode: MoneyMode;
|
||||||
|
rate: string;
|
||||||
|
total: string;
|
||||||
|
originalTotal: string;
|
||||||
|
payer: string;
|
||||||
|
}
|
||||||
|
export interface PoolChoice {
|
||||||
|
id: string;
|
||||||
|
date: string;
|
||||||
|
totalMg: number;
|
||||||
|
usedMg: number;
|
||||||
|
remainingMg: number;
|
||||||
|
availableMg: number;
|
||||||
|
status: string;
|
||||||
|
personalPools?: Pool['personalPools'];
|
||||||
|
usages?: Pool['usages'];
|
||||||
|
}
|
||||||
|
export interface PoolPreview {
|
||||||
|
amount: number | null;
|
||||||
|
covered: boolean;
|
||||||
|
wantedMg: number;
|
||||||
|
usedMg?: number;
|
||||||
|
allocations?: Allocation[];
|
||||||
|
materialSources?: QuoteSource[];
|
||||||
|
balance?: QuoteBalance;
|
||||||
|
quoteError?: string;
|
||||||
|
quoteReady?: boolean;
|
||||||
|
}
|
||||||
|
export interface LinePoolPreview {
|
||||||
|
amount: number | null;
|
||||||
|
poolId?: string;
|
||||||
|
date?: string;
|
||||||
|
status?: string;
|
||||||
|
revision?: string | number;
|
||||||
|
quantity?: number | null;
|
||||||
|
averageRate?: number | null;
|
||||||
|
allocations?: Allocation[];
|
||||||
|
materialSources?: QuoteSource[];
|
||||||
|
}
|
||||||
|
export interface ChargeInput<T = string> {
|
||||||
|
id?: string;
|
||||||
|
nameType?: string;
|
||||||
|
customName?: string;
|
||||||
|
name?: string;
|
||||||
|
amount?: T | null;
|
||||||
|
chargePrices?: Record<string, string>;
|
||||||
|
costRemoved?: boolean;
|
||||||
|
}
|
||||||
|
export interface FeeInput<T = string> {
|
||||||
|
key: string;
|
||||||
|
note: string;
|
||||||
|
amount: T | null;
|
||||||
|
payer: string;
|
||||||
|
sourceName?: string;
|
||||||
|
status?: string;
|
||||||
|
edited?: boolean;
|
||||||
|
expense_id?: string;
|
||||||
|
date?: string;
|
||||||
|
lineNumber?: number;
|
||||||
|
funding?: Record<string, unknown>;
|
||||||
|
system?: string;
|
||||||
|
}
|
||||||
|
export type CostParts<T = string> = Partial<Record<'material' | 'labor' | 'accessories' | 'other', T | null>>;
|
||||||
|
export interface LineInput<T = string> {
|
||||||
|
id?: string;
|
||||||
|
name?: string;
|
||||||
|
nameType?: string;
|
||||||
|
customName?: string;
|
||||||
|
code?: string;
|
||||||
|
unit?: LineState['unit'];
|
||||||
|
pricingMode?: LineState['pricingMode'];
|
||||||
|
quantity?: T;
|
||||||
|
goldPrice?: T;
|
||||||
|
laborMode?: LineState['laborMode'];
|
||||||
|
laborRate?: T;
|
||||||
|
pieces?: string | number;
|
||||||
|
priceNote?: string;
|
||||||
|
baseSale?: T;
|
||||||
|
sale?: T;
|
||||||
|
cost?: T | null;
|
||||||
|
pocket?: string;
|
||||||
|
stockCount?: string | number | null;
|
||||||
|
historicalUnknown?: boolean;
|
||||||
|
returnedStockId?: string;
|
||||||
|
payer?: string;
|
||||||
|
charges?: ChargeInput<T>[];
|
||||||
|
costParts?: CostParts<T>;
|
||||||
|
costPayers?: { labor?: string; material?: string };
|
||||||
|
costLabor?: { mode?: MoneyMode; rate?: T | null };
|
||||||
|
costMaterial?: { mode?: MoneyMode | 'pool'; rate?: T | null; poolId?: string };
|
||||||
|
costMaterialDraft?: Partial<ManualMaterial>;
|
||||||
|
materialPoolDraft?: { poolId?: string; defaultDate?: boolean; manual?: Partial<ManualMaterial> };
|
||||||
|
costFundings?: { labor?: Record<string, unknown> };
|
||||||
|
materialPool?: LinePoolPreview;
|
||||||
|
}
|
||||||
|
export interface EntryDraft<T = string> {
|
||||||
|
id?: string;
|
||||||
|
revision?: number;
|
||||||
|
copy_kind?: string;
|
||||||
|
paper_date?: string;
|
||||||
|
paper_number?: string;
|
||||||
|
rounding_mode?: OrderForm['rounding_mode'];
|
||||||
|
member?: string;
|
||||||
|
date?: string;
|
||||||
|
customer?: string;
|
||||||
|
customer_type?: string;
|
||||||
|
salesperson?: string;
|
||||||
|
internal_note?: string;
|
||||||
|
note?: string;
|
||||||
|
payment_account?: string;
|
||||||
|
credit_card_fee_payer?: string;
|
||||||
|
fees_date?: string;
|
||||||
|
discount?: T;
|
||||||
|
fee_cost_mode?: string;
|
||||||
|
fee_items?: FeeInput<T>[];
|
||||||
|
lines?: LineInput<T>[];
|
||||||
|
}
|
||||||
|
export interface IssuedOrder extends EntryDraft<number> {
|
||||||
|
discount: number;
|
||||||
|
fee_items: FeeInput<number>[];
|
||||||
|
lines: (Omit<LineInput<number>, 'charges'> & {
|
||||||
|
charges?: (ChargeInput<number> & { amount: number | null })[];
|
||||||
|
sale: number;
|
||||||
|
quantity: number;
|
||||||
|
cost: number | null;
|
||||||
|
goldPrice: number;
|
||||||
|
laborRate: number;
|
||||||
|
})[];
|
||||||
|
}
|
||||||
|
export type FormLine = LineInput & {
|
||||||
|
name: string;
|
||||||
|
pocket: string;
|
||||||
|
quantity: string;
|
||||||
|
stockCount?: string | number | null;
|
||||||
|
sale: string;
|
||||||
|
charges: ChargeInput[];
|
||||||
|
};
|
||||||
|
export type OrderInput = Required<Pick<EntryDraft, 'date' | 'discount' | 'rounding_mode'>> &
|
||||||
|
Omit<EntryDraft, 'lines' | 'fee_items'> & { lines: FormLine[]; fee_items: FeeInput[] };
|
||||||
|
export type FormulaLine = Pick<
|
||||||
|
LineState,
|
||||||
|
'unit' | 'pricingMode' | 'quantity' | 'goldPrice' | 'laborMode' | 'laborRate' | 'pieces'
|
||||||
|
> & {
|
||||||
|
charges: { name: string; amount: string }[];
|
||||||
|
};
|
||||||
|
export type CostCatalog = Record<
|
||||||
|
string,
|
||||||
|
{ amount: string; payer: string; name?: string; enabled?: boolean; byQuantity?: boolean }
|
||||||
|
>;
|
||||||
|
export type EditableLine = LineState & { purchase: NonNullable<LineState['purchase']> };
|
||||||
|
export type EditablePresetForm = OrderForm & { presets: NonNullable<OrderForm['presets']> };
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
// 持久化订单按分、毫克保存;复制与模板表单保留字符串。
|
||||||
|
export interface CostMode<T> {
|
||||||
|
mode?: string;
|
||||||
|
rate?: T;
|
||||||
|
poolId?: string;
|
||||||
|
}
|
||||||
|
export interface ProductAmounts<T> {
|
||||||
|
unit: string;
|
||||||
|
quantity: T;
|
||||||
|
name: string;
|
||||||
|
nameType?: string;
|
||||||
|
customName?: string;
|
||||||
|
stockCount?: number | string;
|
||||||
|
pocket?: string;
|
||||||
|
payer?: string;
|
||||||
|
pricingMode?: string;
|
||||||
|
goldPrice?: T;
|
||||||
|
laborRate?: T;
|
||||||
|
laborMode?: string;
|
||||||
|
pieces?: string | number;
|
||||||
|
priceNote?: string;
|
||||||
|
sale: T;
|
||||||
|
baseSale?: T;
|
||||||
|
cost?: T | null;
|
||||||
|
costMaterial?: CostMode<T>;
|
||||||
|
costLabor?: CostMode<T>;
|
||||||
|
costParts?: Record<string, T | null>;
|
||||||
|
costPayers?: Record<string, string>;
|
||||||
|
charges: { id?: string; name: string; amount: T; costRemoved?: boolean }[];
|
||||||
|
}
|
||||||
|
export interface SavedFee {
|
||||||
|
key: string;
|
||||||
|
amount: number;
|
||||||
|
payer: string;
|
||||||
|
note: string;
|
||||||
|
status: string;
|
||||||
|
sourceName?: string;
|
||||||
|
expense_id?: string;
|
||||||
|
system?: string;
|
||||||
|
}
|
||||||
|
export interface Expense {
|
||||||
|
id: string;
|
||||||
|
amount: number;
|
||||||
|
payer: string;
|
||||||
|
note: string;
|
||||||
|
system?: string;
|
||||||
|
key?: string;
|
||||||
|
}
|
||||||
|
export interface CopySource {
|
||||||
|
date: string;
|
||||||
|
status: string;
|
||||||
|
salesperson: string;
|
||||||
|
payment_account: string;
|
||||||
|
discount: number;
|
||||||
|
note?: string;
|
||||||
|
rounding_mode?: string;
|
||||||
|
fee_items: SavedFee[];
|
||||||
|
expenses: Expense[];
|
||||||
|
corrections?: { type: string; target: string }[];
|
||||||
|
pendingFees?: { key: string }[];
|
||||||
|
lines: (ProductAmounts<number> & { materialAllocations?: unknown[] })[];
|
||||||
|
price_lock_id?: string;
|
||||||
|
}
|
||||||
|
export interface ManualCost {
|
||||||
|
mode?: string;
|
||||||
|
rate?: string;
|
||||||
|
total?: string;
|
||||||
|
originalTotal?: string;
|
||||||
|
payer?: string;
|
||||||
|
}
|
||||||
|
export interface DraftProduct extends Partial<Omit<ProductAmounts<string>, 'quantity' | 'costMaterial' | 'costParts'>> {
|
||||||
|
costMaterial?: CostMode<string | number>;
|
||||||
|
costParts?: Record<string, number | string | null>;
|
||||||
|
quantity?: number | string;
|
||||||
|
materialPoolDraft?: { defaultDate: boolean; poolId?: string; manual?: ManualCost };
|
||||||
|
costMaterialDraft?: ManualCost;
|
||||||
|
}
|
||||||
|
export interface TemplateProduct extends DraftProduct {
|
||||||
|
nameType: string;
|
||||||
|
customName: string;
|
||||||
|
unit: string;
|
||||||
|
payer: string;
|
||||||
|
charges: NonNullable<DraftProduct['charges']>;
|
||||||
|
}
|
||||||
|
export interface TemplateFee {
|
||||||
|
key: string;
|
||||||
|
note: string;
|
||||||
|
payer: string;
|
||||||
|
amount: string;
|
||||||
|
edited?: boolean;
|
||||||
|
status?: string;
|
||||||
|
sourceName?: string;
|
||||||
|
lineNumber?: number;
|
||||||
|
}
|
||||||
|
export interface CopyDraft {
|
||||||
|
lines: DraftProduct[];
|
||||||
|
date?: string;
|
||||||
|
id?: string;
|
||||||
|
copy_kind?: string;
|
||||||
|
customer?: string;
|
||||||
|
note?: string;
|
||||||
|
internal_note?: string;
|
||||||
|
discount?: string;
|
||||||
|
salesperson?: string;
|
||||||
|
payment_account?: string;
|
||||||
|
fee_items?: TemplateFee[];
|
||||||
|
}
|
||||||
|
export interface TemplateOptions {
|
||||||
|
newId?: () => string;
|
||||||
|
pocketKeys?: string[];
|
||||||
|
today?: string;
|
||||||
|
salesperson?: string;
|
||||||
|
}
|
||||||
+100
-21
@@ -1,3 +1,6 @@
|
|||||||
|
import type { ManualMaterial, FeeInput, LinePoolPreview, CostCatalog, FormulaLine } from './orderEntryTypes';
|
||||||
|
import type { Pool } from '../pages/MaterialPools/model';
|
||||||
|
import type { QuoteRequest, QuoteRow, QuoteBalance } from '../lib/materialQuote';
|
||||||
// 共用 UMD 模块(../public/*.js)与服务端接口的类型描述。只描述新版界面用到的部分。
|
// 共用 UMD 模块(../public/*.js)与服务端接口的类型描述。只描述新版界面用到的部分。
|
||||||
|
|
||||||
export interface MemberRow {
|
export interface MemberRow {
|
||||||
@@ -24,11 +27,14 @@ export interface SessionInfo {
|
|||||||
}
|
}
|
||||||
export interface PocketRow {
|
export interface PocketRow {
|
||||||
key: string;
|
key: string;
|
||||||
|
self?: boolean;
|
||||||
name?: string;
|
name?: string;
|
||||||
countUnit?: 'pair' | null;
|
countUnit?: 'pair' | null;
|
||||||
|
countSince?: string | null;
|
||||||
active?: boolean;
|
active?: boolean;
|
||||||
}
|
}
|
||||||
export interface LedgerState {
|
export interface LedgerState {
|
||||||
|
orders?: { id?: string; lines?: { pocket: string }[] }[];
|
||||||
today: string;
|
today: string;
|
||||||
mode: string;
|
mode: string;
|
||||||
user: SessionUser;
|
user: SessionUser;
|
||||||
@@ -37,7 +43,7 @@ export interface LedgerState {
|
|||||||
storeName?: string;
|
storeName?: string;
|
||||||
members?: MemberRow[];
|
members?: MemberRow[];
|
||||||
feeDefaults?: Record<string, string>;
|
feeDefaults?: Record<string, string>;
|
||||||
costPresets?: Record<string, unknown>;
|
costPresets?: CostCatalog;
|
||||||
creditCardRatePermille?: number;
|
creditCardRatePermille?: number;
|
||||||
};
|
};
|
||||||
pockets?: string[];
|
pockets?: string[];
|
||||||
@@ -49,7 +55,7 @@ export interface LedgerState {
|
|||||||
export interface ChargeState {
|
export interface ChargeState {
|
||||||
id: string;
|
id: string;
|
||||||
type: string;
|
type: string;
|
||||||
customName: string;
|
customName?: string;
|
||||||
amount: string;
|
amount: string;
|
||||||
prices: Record<string, string>;
|
prices: Record<string, string>;
|
||||||
costRemoved?: boolean;
|
costRemoved?: boolean;
|
||||||
@@ -66,10 +72,11 @@ export interface PurchaseState {
|
|||||||
accessories: string;
|
accessories: string;
|
||||||
other: string;
|
other: string;
|
||||||
dataMode: string;
|
dataMode: string;
|
||||||
preferredMode: string;
|
preferredMode: 'gram' | 'total';
|
||||||
dataUnit: string;
|
dataUnit: string;
|
||||||
total: string;
|
total: string;
|
||||||
originalTotal: string;
|
originalTotal: string;
|
||||||
|
costFundings?: { labor?: Record<string, unknown> };
|
||||||
}
|
}
|
||||||
export interface PoolState {
|
export interface PoolState {
|
||||||
source: 'manual' | 'pool';
|
source: 'manual' | 'pool';
|
||||||
@@ -83,7 +90,9 @@ export interface PoolState {
|
|||||||
help?: string;
|
help?: string;
|
||||||
payerText?: string;
|
payerText?: string;
|
||||||
personal?: boolean;
|
personal?: boolean;
|
||||||
preview: { amount: number | null } | null;
|
preview: LinePoolPreview | null;
|
||||||
|
manual: ManualMaterial;
|
||||||
|
unified?: boolean;
|
||||||
}
|
}
|
||||||
export interface LineView {
|
export interface LineView {
|
||||||
calculation: string;
|
calculation: string;
|
||||||
@@ -110,6 +119,9 @@ export interface ReturnedStockLot {
|
|||||||
materialPoolNotice?: string;
|
materialPoolNotice?: string;
|
||||||
}
|
}
|
||||||
export interface LineState {
|
export interface LineState {
|
||||||
|
countHistoricalUnknown?: boolean;
|
||||||
|
countOriginalPocket?: string;
|
||||||
|
countOriginalQuantity?: string;
|
||||||
returnedStockId?: string;
|
returnedStockId?: string;
|
||||||
returnedStockCode?: string;
|
returnedStockCode?: string;
|
||||||
returnedStockLot?: ReturnedStockLot;
|
returnedStockLot?: ReturnedStockLot;
|
||||||
@@ -148,10 +160,14 @@ export interface FeeRowState {
|
|||||||
sourceName: string;
|
sourceName: string;
|
||||||
edited: boolean;
|
edited: boolean;
|
||||||
status: string;
|
status: string;
|
||||||
|
funding?: Record<string, unknown>;
|
||||||
|
date?: string;
|
||||||
lineNumber?: number;
|
lineNumber?: number;
|
||||||
automatic?: unknown;
|
automatic?: FeeInput;
|
||||||
|
expense_id?: string;
|
||||||
}
|
}
|
||||||
export interface PresetState {
|
export interface PresetState {
|
||||||
|
originals?: Record<string, FeeInput>;
|
||||||
configured: boolean;
|
configured: boolean;
|
||||||
checked: Record<string, boolean>;
|
checked: Record<string, boolean>;
|
||||||
quantity: Record<string, string>;
|
quantity: Record<string, string>;
|
||||||
@@ -163,6 +179,8 @@ export interface PaymentState {
|
|||||||
cardLocked: boolean;
|
cardLocked: boolean;
|
||||||
}
|
}
|
||||||
export interface OrderForm {
|
export interface OrderForm {
|
||||||
|
editing?: boolean;
|
||||||
|
original_customer_type?: string;
|
||||||
returnedLots?: { date: string; member: string; lots: ReturnedStockLot[] };
|
returnedLots?: { date: string; member: string; lots: ReturnedStockLot[] };
|
||||||
copy_kind: string;
|
copy_kind: string;
|
||||||
id: string;
|
id: string;
|
||||||
@@ -212,13 +230,13 @@ export interface FormSummary {
|
|||||||
presetNotes: Record<string, string>;
|
presetNotes: Record<string, string>;
|
||||||
}
|
}
|
||||||
export interface MaterialPools {
|
export interface MaterialPools {
|
||||||
rows: unknown[];
|
rows: Pool[];
|
||||||
rolling?: { enabled?: boolean; cutover?: string };
|
rolling?: { enabled?: boolean; cutover: string };
|
||||||
current?: unknown;
|
current?: Pool;
|
||||||
}
|
}
|
||||||
export interface QuoteState {
|
export interface QuoteState {
|
||||||
input: unknown;
|
input: QuoteRequest;
|
||||||
result: unknown;
|
result: { entries: QuoteRow[]; pools: QuoteBalance[] } | null;
|
||||||
error: string;
|
error: string;
|
||||||
}
|
}
|
||||||
export interface SyncContext {
|
export interface SyncContext {
|
||||||
@@ -257,7 +275,38 @@ export interface PresetCatalogItem {
|
|||||||
shipping?: boolean;
|
shipping?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface MaterialUsage {
|
||||||
|
active: boolean;
|
||||||
|
mg: number;
|
||||||
|
order_id?: string;
|
||||||
|
line_index: number;
|
||||||
|
}
|
||||||
|
export interface LockCostEstimate {
|
||||||
|
lockedMg: number;
|
||||||
|
finalMg: number;
|
||||||
|
originalUsedMg: number;
|
||||||
|
extraMg: number;
|
||||||
|
leftoverMg: number;
|
||||||
|
originalPurchase: number;
|
||||||
|
originalUsedCost: number;
|
||||||
|
extraCost: number;
|
||||||
|
materialCost: number;
|
||||||
|
leftoverCost: number;
|
||||||
|
}
|
||||||
export interface LedgerCalcApi {
|
export interface LedgerCalcApi {
|
||||||
|
orderCosts: (typeof import('../../../public/calculations.js'))['orderCosts'];
|
||||||
|
poolMaterialAmount(amount: number, mg: number, quantity: number): number;
|
||||||
|
poolMaterialPreview(
|
||||||
|
pool: { totalAmount: number | null; totalMg: number; usages: MaterialUsage[] },
|
||||||
|
entries: { lineIndex: number; mg: number }[],
|
||||||
|
options?: { orderId?: string | null; allUsages?: MaterialUsage[] },
|
||||||
|
): { usedMg: number; wantedMg: number; covered: boolean; amounts: Record<number, number | null> };
|
||||||
|
priceLockCost(input: {
|
||||||
|
lockedQuantity: string;
|
||||||
|
quantity: string;
|
||||||
|
buyRate: string;
|
||||||
|
extraBuyRate: string;
|
||||||
|
}): LockCostEstimate;
|
||||||
cents(value: unknown, name?: string): number;
|
cents(value: unknown, name?: string): number;
|
||||||
isSilver(name: string): boolean;
|
isSilver(name: string): boolean;
|
||||||
sale(line: unknown): { sale: number; baseSale: number; chargesTotal: number; charges: unknown[] };
|
sale(line: unknown): { sale: number; baseSale: number; chargesTotal: number; charges: unknown[] };
|
||||||
@@ -270,12 +319,18 @@ export interface LedgerCalcApi {
|
|||||||
costLabels: Record<string, string>;
|
costLabels: Record<string, string>;
|
||||||
}
|
}
|
||||||
export interface CreditCardFeesApi {
|
export interface CreditCardFeesApi {
|
||||||
|
isFee(item: { key?: string; system?: string }): boolean;
|
||||||
isAccount(account: string): boolean;
|
isAccount(account: string): boolean;
|
||||||
amount(cents: number, rate?: number): number;
|
amount(cents: number, rate?: number): number;
|
||||||
normalizeAccount(account: string): string;
|
normalizeAccount(account: string): string;
|
||||||
ratePermille: number;
|
ratePermille: number;
|
||||||
}
|
}
|
||||||
export interface FeeEstimatesApi {
|
export interface FeeEstimatesApi {
|
||||||
|
presetCatalog(
|
||||||
|
values?: unknown,
|
||||||
|
): Record<string, { enabled: boolean; name: string; amount: string; payer: string; byQuantity: boolean }>;
|
||||||
|
presetKind(item: unknown, options?: { presets?: unknown; recorded?: boolean }): string;
|
||||||
|
presetKey(kind: string): string;
|
||||||
presets(values?: unknown): Record<string, { amount: string; payer: string }>;
|
presets(values?: unknown): Record<string, { amount: string; payer: string }>;
|
||||||
checkboxCategory(name: string): string;
|
checkboxCategory(name: string): string;
|
||||||
normalize(name: string): string;
|
normalize(name: string): string;
|
||||||
@@ -285,8 +340,8 @@ export interface OrderFormulaApi {
|
|||||||
input: string,
|
input: string,
|
||||||
options: { roundingMode: string },
|
options: { roundingMode: string },
|
||||||
): {
|
): {
|
||||||
items: { line: Record<string, string> & { charges: { amount: string }[] }; subtotal: number }[];
|
items: { line: FormulaLine; subtotal: number }[];
|
||||||
lines: (Record<string, string> & { charges: { name: string; amount: string }[] })[];
|
lines: FormulaLine[];
|
||||||
subtotal: number;
|
subtotal: number;
|
||||||
total: number;
|
total: number;
|
||||||
roundingMode: string;
|
roundingMode: string;
|
||||||
@@ -302,6 +357,29 @@ export interface OrderTemplatesApi {
|
|||||||
): Record<string, unknown> & { member?: string; salesperson?: string };
|
): Record<string, unknown> & { member?: string; salesperson?: string };
|
||||||
}
|
}
|
||||||
export interface OrderEntryModelApi {
|
export interface OrderEntryModelApi {
|
||||||
|
validateOrderIdentity<T extends { customer: string; salesperson: string; internal_note?: string }>(
|
||||||
|
input: T,
|
||||||
|
options?: { requireInternalNote?: boolean },
|
||||||
|
): T;
|
||||||
|
accountIdentity(st: LedgerState, account: string): { member: string; channel: string } | null;
|
||||||
|
memberAccountPrefix(member: string): string;
|
||||||
|
pocketLabel(st: LedgerState, key: string): string;
|
||||||
|
stockCountValue(value: string, options?: { optional?: boolean; title?: string }): number | null;
|
||||||
|
creditCardRate(st: LedgerState): number;
|
||||||
|
shopFeeDefaults(st: LedgerState): Record<string, string>;
|
||||||
|
orderRoundingHint(total: ReturnType<LedgerCalcApi['orderTotal']>): string;
|
||||||
|
costConfig(st: LedgerState): ReturnType<FeeEstimatesApi['presets']>;
|
||||||
|
newPresets(st: LedgerState, items?: readonly unknown[], recorded?: boolean): PresetState;
|
||||||
|
readPresets(
|
||||||
|
form: { presets: PresetState | null; member?: string },
|
||||||
|
st: LedgerState,
|
||||||
|
): {
|
||||||
|
items: { key: string; note: string; amount: string; payer: string; status: string; edited: boolean }[];
|
||||||
|
notes: Record<string, string>;
|
||||||
|
};
|
||||||
|
feeLabels: Record<string, string>;
|
||||||
|
formMember(form: { member?: string }, st: LedgerState): string;
|
||||||
|
noteTagQuery(text: string): string;
|
||||||
productNames: string[];
|
productNames: string[];
|
||||||
chargeNames: string[];
|
chargeNames: string[];
|
||||||
yuan(cents: number | null | undefined): string;
|
yuan(cents: number | null | undefined): string;
|
||||||
@@ -310,7 +388,7 @@ export interface OrderEntryModelApi {
|
|||||||
teamMode(st: LedgerState): boolean;
|
teamMode(st: LedgerState): boolean;
|
||||||
currentMember(st: LedgerState, session?: SessionInfo | null): string;
|
currentMember(st: LedgerState, session?: SessionInfo | null): string;
|
||||||
memberKeys(st: LedgerState): string[];
|
memberKeys(st: LedgerState): string[];
|
||||||
memberName(st: LedgerState, member: string): string;
|
memberName(st: LedgerState, member: string, session?: SessionInfo | null): string;
|
||||||
memberOptions(st: LedgerState, assistantFirst?: boolean, options?: { selected?: string }): [string, string][];
|
memberOptions(st: LedgerState, assistantFirst?: boolean, options?: { selected?: string }): [string, string][];
|
||||||
defaultSalesperson(st: LedgerState, session?: SessionInfo | null): string;
|
defaultSalesperson(st: LedgerState, session?: SessionInfo | null): string;
|
||||||
activePocketKeys(st: LedgerState): string[];
|
activePocketKeys(st: LedgerState): string[];
|
||||||
@@ -325,9 +403,9 @@ export interface OrderEntryModelApi {
|
|||||||
setPurchaseField(line: LineState, field: string, value: string): LineState;
|
setPurchaseField(line: LineState, field: string, value: string): LineState;
|
||||||
setPoolSource(line: LineState, source: 'manual' | 'pool'): LineState;
|
setPoolSource(line: LineState, source: 'manual' | 'pool'): LineState;
|
||||||
lineVisibility(line: LineState, st: LedgerState): LineVisibility;
|
lineVisibility(line: LineState, st: LedgerState): LineVisibility;
|
||||||
poolQuoteInput(form: OrderForm, ctx: SyncContext): { date: string; member: string; entries: unknown[] };
|
poolQuoteInput(form: OrderForm, ctx: SyncContext): QuoteRequest;
|
||||||
feeSourceText(row: FeeRowState): string;
|
feeSourceText(row: FeeRowState): string;
|
||||||
editFeeRow(form: OrderForm, index: number, field: 'amount' | 'payer' | 'note', value: string): OrderForm;
|
editFeeRow(form: OrderForm, index: number, field: 'amount' | 'payer' | 'note' | 'date', value: string): OrderForm;
|
||||||
addManualFee(form: OrderForm, st: LedgerState, uuid: () => string): OrderForm;
|
addManualFee(form: OrderForm, st: LedgerState, uuid: () => string): OrderForm;
|
||||||
removeFeeRow(form: OrderForm, index: number): OrderForm;
|
removeFeeRow(form: OrderForm, index: number): OrderForm;
|
||||||
restoreChargeCost(form: OrderForm, lineIndex: number, chargeIndex: number): OrderForm;
|
restoreChargeCost(form: OrderForm, lineIndex: number, chargeIndex: number): OrderForm;
|
||||||
@@ -335,7 +413,7 @@ export interface OrderEntryModelApi {
|
|||||||
setPresetQuantity(form: OrderForm, kind: string, value: string): OrderForm;
|
setPresetQuantity(form: OrderForm, kind: string, value: string): OrderForm;
|
||||||
presetCatalogView(form: OrderForm, st: LedgerState): PresetCatalogItem[];
|
presetCatalogView(form: OrderForm, st: LedgerState): PresetCatalogItem[];
|
||||||
paymentMethods(st: LedgerState): string[];
|
paymentMethods(st: LedgerState): string[];
|
||||||
recipientOptions(st: LedgerState, payment: PaymentState): [string, string][];
|
recipientOptions(st: LedgerState, payment: Pick<PaymentState, 'recipient' | 'method'>): [string, string][];
|
||||||
readPaymentAccount(form: OrderForm): string;
|
readPaymentAccount(form: OrderForm): string;
|
||||||
changeMember(form: OrderForm, member: string, st: LedgerState): OrderForm;
|
changeMember(form: OrderForm, member: string, st: LedgerState): OrderForm;
|
||||||
isBlankDraft(draft: unknown): boolean;
|
isBlankDraft(draft: unknown): boolean;
|
||||||
@@ -348,6 +426,11 @@ export interface OrderEntryModelApi {
|
|||||||
syncForm(form: OrderForm, ctx: SyncContext): { form: OrderForm; draft: OrderDraft; summary: FormSummary };
|
syncForm(form: OrderForm, ctx: SyncContext): { form: OrderForm; draft: OrderDraft; summary: FormSummary };
|
||||||
canUseReturnedLot(lot: ReturnedStockLot, st: LedgerState, date: string): boolean;
|
canUseReturnedLot(lot: ReturnedStockLot, st: LedgerState, date: string): boolean;
|
||||||
validateFormFields(form: OrderForm, st: LedgerState): void;
|
validateFormFields(form: OrderForm, st: LedgerState): void;
|
||||||
|
validateIssueDraft<T extends Pick<OrderDraft, 'lines' | 'fee_items' | 'discount' | 'rounding_mode'>>(
|
||||||
|
draft: T,
|
||||||
|
st: LedgerState,
|
||||||
|
options: { requireIdentity: false },
|
||||||
|
): T;
|
||||||
validateIssueDraft(draft: OrderDraft, st: LedgerState): OrderDraft;
|
validateIssueDraft(draft: OrderDraft, st: LedgerState): OrderDraft;
|
||||||
draftInputs(order: unknown): Record<string, unknown>;
|
draftInputs(order: unknown): Record<string, unknown>;
|
||||||
filterNoteTags(tags: string[], text: string): string[];
|
filterNoteTags(tags: string[], text: string): string[];
|
||||||
@@ -355,11 +438,7 @@ export interface OrderEntryModelApi {
|
|||||||
}
|
}
|
||||||
export interface OrderEntryModelApi {
|
export interface OrderEntryModelApi {
|
||||||
isFormulaBlank(line: LineState): boolean;
|
isFormulaBlank(line: LineState): boolean;
|
||||||
applyFormulaLines(
|
applyFormulaLines(form: OrderForm, lines: FormulaLine[], ctx: SyncContext): { form: OrderForm; filled: number[] };
|
||||||
form: OrderForm,
|
|
||||||
lines: Record<string, unknown>[],
|
|
||||||
ctx: SyncContext,
|
|
||||||
): { form: OrderForm; filled: number[] };
|
|
||||||
}
|
}
|
||||||
export interface OrderCopyApi {
|
export interface OrderCopyApi {
|
||||||
hasDraftContent(draft: unknown, options: { today: string; salesperson: string }): boolean;
|
hasDraftContent(draft: unknown, options: { today: string; salesperson: string }): boolean;
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import transcriptJson from '../../e2e/baseline/golden/transcript.json?raw';
|
||||||
|
import { readOrderRecord } from '../src/pages/Orders/readOrder';
|
||||||
import { render, screen } from '@testing-library/react';
|
import { render, screen } from '@testing-library/react';
|
||||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||||
import { orderViews } from '../src/pages/Orders/orderViews';
|
import { orderViews } from '../src/pages/Orders/orderViews';
|
||||||
@@ -5,6 +7,11 @@ import { Cards, type LedgerState } from '../src/shared';
|
|||||||
|
|
||||||
const date = '2026-11-20';
|
const date = '2026-11-20';
|
||||||
const account = '麦麦信用卡';
|
const account = '麦麦信用卡';
|
||||||
|
const transcript: { method?: string; path?: string; status?: number; body?: unknown }[] = JSON.parse(transcriptJson);
|
||||||
|
const saved = transcript.find(
|
||||||
|
step => step.method === 'GET' && step.path === '/api/orders/<id26>' && step.status === 200,
|
||||||
|
);
|
||||||
|
const order = readOrderRecord(saved?.body, '<id26>');
|
||||||
|
|
||||||
function renderPayment(action: 'receipt' | 'correct', orderRate?: number, shopRate?: number) {
|
function renderPayment(action: 'receipt' | 'correct', orderRate?: number, shopRate?: number) {
|
||||||
const state: LedgerState = {
|
const state: LedgerState = {
|
||||||
@@ -16,14 +23,27 @@ function renderPayment(action: 'receipt' | 'correct', orderRate?: number, shopRa
|
|||||||
};
|
};
|
||||||
const views = orderViews({
|
const views = orderViews({
|
||||||
state,
|
state,
|
||||||
session: { user: state.user },
|
session: { user: state.user, setup: true, mode: 'trial', today: date },
|
||||||
currentOrder: {
|
currentOrder: {
|
||||||
|
...order,
|
||||||
id: 'order-1',
|
id: 'order-1',
|
||||||
date,
|
date,
|
||||||
balance: 25000,
|
balance: 25000,
|
||||||
payment_account: account,
|
payment_account: account,
|
||||||
credit_card_rate_permille: orderRate,
|
credit_card_rate_permille: orderRate,
|
||||||
payments: [{ id: 'receipt-1', kind: 'receipt', date, account, amount: 25000 }],
|
payments: [
|
||||||
|
{
|
||||||
|
id: 'receipt-1',
|
||||||
|
kind: 'receipt',
|
||||||
|
date,
|
||||||
|
account,
|
||||||
|
amount: 25000,
|
||||||
|
reference: '',
|
||||||
|
order_id: 'order-1',
|
||||||
|
actor: '店主',
|
||||||
|
created: date,
|
||||||
|
},
|
||||||
|
],
|
||||||
corrections: [],
|
corrections: [],
|
||||||
expenses: [],
|
expenses: [],
|
||||||
settlements: [],
|
settlements: [],
|
||||||
|
|||||||
+20
-2
@@ -6,6 +6,7 @@
|
|||||||
"moduleResolution": "Bundler",
|
"moduleResolution": "Bundler",
|
||||||
"jsx": "react-jsx",
|
"jsx": "react-jsx",
|
||||||
"strict": true,
|
"strict": true,
|
||||||
|
"noImplicitAny": true,
|
||||||
"noUnusedLocals": true,
|
"noUnusedLocals": true,
|
||||||
"noUnusedParameters": false,
|
"noUnusedParameters": false,
|
||||||
"noFallthroughCasesInSwitch": true,
|
"noFallthroughCasesInSwitch": true,
|
||||||
@@ -15,7 +16,24 @@
|
|||||||
"allowJs": true,
|
"allowJs": true,
|
||||||
"noEmit": true,
|
"noEmit": true,
|
||||||
"types": ["vitest/globals", "@testing-library/jest-dom", "node"],
|
"types": ["vitest/globals", "@testing-library/jest-dom", "node"],
|
||||||
"paths": { "@public/*": ["../public/*"] }
|
"paths": {
|
||||||
|
"@public/*": ["../public/*"]
|
||||||
|
},
|
||||||
|
"checkJs": true
|
||||||
},
|
},
|
||||||
"include": ["src", "test", "vite.config.ts"]
|
"include": [
|
||||||
|
"src",
|
||||||
|
"test",
|
||||||
|
"vite.config.ts",
|
||||||
|
"../public/calculations.js",
|
||||||
|
"../public/credit-card-fees.js",
|
||||||
|
"../public/fee-estimates.js",
|
||||||
|
"../public/order-copy.js",
|
||||||
|
"../public/order-templates.js",
|
||||||
|
"../public/order-entry-model.js",
|
||||||
|
"../public/order-formula.js",
|
||||||
|
"../public/ledger-values.js",
|
||||||
|
"../public/report-rules.js",
|
||||||
|
"../public/recovery-rules.js"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user