Compare commits
2
Commits
5e1e4c600c
...
0ce4586f9d
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0ce4586f9d | ||
|
|
641f280012 |
No files matched your search
@@ -0,0 +1,114 @@
|
|||||||
|
# 当天订单对账演示接口契约
|
||||||
|
|
||||||
|
2026-11-02 当前页面新增并只使用 `report.daily` 的当日对账投影:`{date,overview:{orderCount,salesCents,orderCostCents,profitCents},members:[{member,name,date,openingCents,orderCount,salesCents,orderCostCents,profitCents,selfCollectedCents,ownerCollectedCents,otherCollectedCents,ownerAdvancedCents,selfPaidCents,otherAdvancedCents,calculatedToOwnerCents,toOwnerCents,reviewRequired,incomeDetails,channelTotals,costDetails,costsByPayer}]}`。金额仍为整数分;收入明细保留orderId、customer、collector、channel、amountCents和self/owner/other分类,成本明细保留orderId、customer、kind、payer及amountCents,两者合计均严格核对。只取所选日期归属订单,真实净利润包含负数;助理公式为麦麦垫付成本+当天净利润-麦麦代收款。亏损日toOwnerCents为null待复核;正常日负值表示麦麦应返/核对。初期余额只作参考。UI支持收入按钮展开客户和渠道,移除转账及累计现金结清流程。旧transfers及旧报告/API仅兼容保留,daily不依赖、不修改或新增转账。原料池FIFO、日加权及刷卡6‰算法不变;全套38/38通过,仅本地修改,未提交或推送。
|
||||||
|
|
||||||
|
## 以下为早期引擎与兼容字段契约,累计转账字段不用于当前日报页面
|
||||||
|
|
||||||
|
本目录是独立方案演示,不接正式账本。所有金额对外输入为元(数字或十进制字符串),报告金额统一为整数分;重量输入为克,报告为整数毫克。UI 只格式化金额和重量,不计算结算。
|
||||||
|
|
||||||
|
## HTTP
|
||||||
|
|
||||||
|
- `GET /api/demo/state?date=2026-11-01`:返回完整演示数据和该日累计报告。
|
||||||
|
- `GET /api/demo/report?date=2026-11-01`:仅返回该日报告。
|
||||||
|
- `GET /api/demo/purchase-preview?grams=10&total=10000`:返回 `{weightMg:10000,totalCents:1000000,unitPriceCents:100000,unitPriceYuanPerGram:1000}`;单价单位为分/克或元/克,只作展示。
|
||||||
|
- `POST /api/demo/opening`:`{member, amount, date?}`。只修改成员初始周转金金额;日期固定为演示起始日,传入其他日期会拒绝。
|
||||||
|
- `POST /api/demo/purchase`:`{date,payer,grams,total,note?}`。购入共用料池,款项已由付款人付出。
|
||||||
|
- `POST /api/demo/order`:`{date,member,customer,grams,sale,collector,channel,expenseAmount?,expensePayer?,materialSource?,directMaterialCost?,directMaterialPayer?,note?,allowLoss?}`。只登记已交付、货款全部实收的普通销售。`materialSource` 为 `pool`(默认)或 `direct`;direct 为本单自行配货,材料成本当日本人或代付人已付,克重不扣共用池。channel 为 `wechat`、`alipay`、`cash`、`bank` 或 `credit_card`;信用卡自动由 owner 收款,手续费 6‰ 由 owner 支付。`allowLoss:true` 可明确登记亏损待复核单;不自动反向支付利润。
|
||||||
|
- `POST /api/demo/transfer`:`{date,from,to,amount,note?,idempotencyKey?}`。只允许当前日期这对成员的已形成待转方向、且不超过待转额;登记才改变现金。支持部分转账。相同 idempotencyKey 及相同内容返回原结果,不重复记账;已结清后再次全额转账报错。
|
||||||
|
- `POST /api/demo/reset`:`{}`。重置到默认示例,已有模拟记录清空。
|
||||||
|
- `POST /api/demo/scenario`:`{name:"complex"}` 或 `{scenario:"complex"}` 载入第二个虚构场景;`{name:"default"}` 等于重置。
|
||||||
|
|
||||||
|
所有写入默认响应当前操作日期的完整 state。`/reset` 与 `/scenario` 返回场景默认日期。可带 `requestId` 字段作为表单级幂等键(除 reset/scenario/opening 外);相同内容仅执行一次。Host 限定 localhost/127.0.0.1,Origin 限定同源;仅监听 `127.0.0.1:3102`。API 错误不修改任何状态。
|
||||||
|
|
||||||
|
成功:`{ok:true,data:...}`。失败:`{ok:false,error:{code,message,field?}}`,状态码 400(校验)、409(结算冲突)、403(Host/Origin)、404(不存在)、405(方法)、413(超64KB)、415(非JSON)。
|
||||||
|
|
||||||
|
## state.data
|
||||||
|
|
||||||
|
```js
|
||||||
|
{
|
||||||
|
version: 1,
|
||||||
|
demo: {name: "default", title: "周转金+利润上交+按用料还款", fictional: true, startDate: "2026-11-01", defaultDate: "2026-11-01"},
|
||||||
|
members: [{id:"owner",name:"麦麦"},{id:"assistant",name:"助理1"},{id:"assistant2",name:"助理2"}],
|
||||||
|
dates: ["2026-11-01"],
|
||||||
|
currentDate: "2026-11-01",
|
||||||
|
opening: [{member:"owner",amount:1000000,date:"2026-11-01"}, ...],
|
||||||
|
purchases: [{id,date,payer,weightMg,totalCents,note}],
|
||||||
|
orders: [{id,date,member,customer,weightMg,saleCents,collector,channel,expenseCents,expensePayer,materialSource,directMaterialCostCents,directMaterialPayer,note,allowLoss}],
|
||||||
|
transfers: [{id,date,from,to,amountCents,note}],
|
||||||
|
report: { /* 下方 */ }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## report
|
||||||
|
|
||||||
|
```js
|
||||||
|
{
|
||||||
|
date: "2026-11-01",
|
||||||
|
scenarioName: "default",
|
||||||
|
overview: {
|
||||||
|
// 以下收入/成本/利润及三个Count是所选日。
|
||||||
|
salesCents,materialCostCents,expenseCents,cardFeeCents,orderCostCents,profitCents,orderCount,purchaseCount,transferCount,
|
||||||
|
// cumulative 为截至所选日的累计。
|
||||||
|
cumulativeSalesCents,cumulativeMaterialCostCents,cumulativeExpenseCents,cumulativeCardFeeCents,cumulativeOrderCostCents,cumulativeProfitCents,cumulativeOrderCount,
|
||||||
|
cashCents,unusedMaterialCents,pendingTransferCents
|
||||||
|
},
|
||||||
|
members: [{
|
||||||
|
member:"assistant", name:"助理1", openingCents:1000000,
|
||||||
|
// 现金及实收/实付/实转合计截至所选日累计。
|
||||||
|
cashCents, collectedCents, purchasePaidCents, directMaterialPaidCents, expensePaidCents, cardFeePaidCents,
|
||||||
|
transferInCents, transferOutCents,
|
||||||
|
// 本人所选日订单归属数据。
|
||||||
|
salesCents,materialCostCents,expenseCents,cardFeeCents,orderCostCents,profitCents,profitDueCents,
|
||||||
|
cumulativeSalesCents,cumulativeMaterialCostCents,cumulativeExpenseCents,cumulativeCardFeeCents,cumulativeOrderCostCents,cumulativeProfitCents,cumulativeProfitDueCents,
|
||||||
|
unusedMaterialCents, cashPlusUnusedCents,projectedSettledCashCents,
|
||||||
|
pendingPayCents,pendingReceiveCents,
|
||||||
|
// 仅本人所选日订单:本人自收按渠道、他人代收按成员。
|
||||||
|
dailyCollections:[{channel,label,amountCents}],collectedByOthers:[{member,name,amountCents}],
|
||||||
|
// 截至所选日此成员实际收款按渠道累计(可包含为别人代收)。
|
||||||
|
channelReceipts:[{channel,label,amountCents}],
|
||||||
|
cashExplanation:"期初周转金+实际收款-购料-自行配货材料-实付费用-刷卡手续费+已收转账-已付转账",
|
||||||
|
expectedSettledAssetsCents, projectedSettledAssetsCents,
|
||||||
|
cashStatus:{status:"ok"|"shortfall",shortfallCents,note},
|
||||||
|
balanceCheck:{status:"ok"|"review",mathStatus:"ok"|"review",differenceCents,note},
|
||||||
|
settlement:{openingPayCents,openingReceiveCents,newPayCents,newReceiveCents,transferredOutCents,transferredInCents,pendingPayCents,pendingReceiveCents}
|
||||||
|
}],
|
||||||
|
materialPool: {openingWeightMg,openingCostCents,purchaseWeightMg,purchaseCostCents,availableWeightMg,availableCostCents,usedWeightMg,usedCostCents,closingWeightMg,closingCostCents,weightedCostYuanPerGram,weightedUnitPriceCents, funding:[{purchaseId,date,payer,totalCents,consumedCents,remainingCents}]},
|
||||||
|
settlements: [{
|
||||||
|
pairId:"owner:assistant", memberA:"owner",memberB:"assistant", memberAName:"麦麦",memberBName:"助理1",
|
||||||
|
from:"assistant",to:"owner",fromName:"助理1",toName:"麦麦",pendingCents:180000,
|
||||||
|
// Signed 以下字段:正数代表 memberA 应向 memberB 转账,负数代表反向。
|
||||||
|
openingSignedCents,newSignedCents,transferredSignedCents,pendingSignedCents,
|
||||||
|
opening:{from,to,amountCents},newToday:{from,to,amountCents},transferredToday:{from,to,amountCents},
|
||||||
|
components:{materialSignedCents,expenseSignedCents,cardFeeSignedCents,collectionSignedCents,profitSignedCents},
|
||||||
|
events:[{date,orderId?,transferId?,type,from,to,amountCents,description}],refundAfterRecalculation
|
||||||
|
}],
|
||||||
|
// 截至所选日全部订单,UI 按 date 与 member 筛选;当前日金额直接取上述统计。
|
||||||
|
orders: [{ /* 原订单字段 + */ materialCostCents,cardFeeCents,orderCostCents,profitCents,profitDueCents,reviewRequired,funding:[{purchaseId,payer,amountCents}], formula}],
|
||||||
|
transactions:[{id,date,type,member?,from?,to?,amountCents,description}],
|
||||||
|
warnings:[{code,message,orderId?}],
|
||||||
|
reconciliation:{totalCashCents,totalUnusedCents,totalAssetsCents,openingCents,totalProfitCents,expectedAssetsCents,differenceCents,status,mathStatus,cashShortfallCents}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`settlements` 固定包含三对成员;某对已结清时 pendingCents 为 0,from/to 为 null。同日新增会先抵扣这对成员的代收/代付,仅在成员对内抵扣,不在三人之间循环轧差。`pendingTransferCents` 为三对累计待转绝对额之和。
|
||||||
|
|
||||||
|
`openingSignedCents` 是报告日前未结余额;`newSignedCents` 是当日新产生往来;`transferredSignedCents` 是当日已转;恒等式 `openingSignedCents + newSignedCents - transferredSignedCents === pendingSignedCents`。组件是截至报告日累计义务;事件包括独立标记的已登记转账,不会把旧利润重新计入本日新增。
|
||||||
|
|
||||||
|
`projectedSettledCashCents = cashCents + pendingReceiveCents - pendingPayCents`;`projectedSettledAssetsCents` 还加本人付款未用材料。`expectedSettledAssetsCents` 对助理固定为期初,对麦麦为期初+全店累计利润。亏损政策未确认时仍保留此正常预期,并用 `balanceCheck.status = review` 与差额明示异常,不自动重新指定亏损承担方。`refundAfterRecalculation` 兼容字段仅提示有已转情况下当前方向反转,不据此断言改价原因。
|
||||||
|
|
||||||
|
现金可为负以供试算,但不自动补本金或生成贷款。此时 `cashStatus.status=shortfall`,警示明确资金缺口、需核实另行垫入资金;即使数学资产闭环,member.balanceCheck 与总 reconciliation 的 status 也为 review,mathStatus 单独表示数学闭环是否相符。
|
||||||
|
|
||||||
|
## 计算与边界
|
||||||
|
|
||||||
|
1. 共用池按“昨日期末存料成本+当天全部购料”计算当天加权成本;当天订单按录入序号分摊,最后用尽时精确带走剩余分。跨天保留未用材料重量和成本。
|
||||||
|
2. 每笔购料仅在购料时扣一次现金。用料成本从购料付款余额 FIFO 分配到付款人:订单归属人向别人归还已耗用成本;未用料仍是原付款人的资金占用资产,不直接形成别人的欠款。
|
||||||
|
3. 销售利润=实收售价-实际用料成本-其他费用-刷卡手续费。助理正利润应交麦麦;麦麦自己的利润留在麦麦名下。亏损仅待复核,不能自动产生麦麦向助理的利润补款。
|
||||||
|
4. 代收货款形成收款人欠订单归属人;他人代付材料、费用和手续费形成订单归属人欠付款人。
|
||||||
|
5. 已登记转账按独立成员对冲减应转。同日加购或历史日补录会重算该日及后续成本,保留所有已转,可能出现反向待返;不能隐去原已付事实。跨日新购不重算采购日前成本。新登记转账始终按所选日当前待转方向和余额检查。
|
||||||
|
6. 非普通已交付收齐销售、预收锁价、分期欠款、退款、退货、回收、置换本次不支持;字段不能使本模型猜测正式账的处理方式。
|
||||||
|
|
||||||
|
## Node模块
|
||||||
|
|
||||||
|
`require('./engine.js')` 导出 `createSeed(name='default')`、`applyCommand(state,type,payload)`、`buildReport(state,date)`、`publicState(state,date)`、`purchasePreview(payload)` 和 `DemoError`。applyCommand 返回新state,不原地修改;失败抛DemoError(code/status/field),且原状态不变。engine不读写任何文件。
|
||||||
|
|
||||||
|
`require('./server.js').createDemoServer({stateFile,publicDirectory})` 供隔离测试使用;测试必须传系统临时目录文件及随机端口。命令行启动仅使用上述固定`/tmp`状态文件及3102。
|
||||||
@@ -0,0 +1,435 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const { createHash } = require('node:crypto');
|
||||||
|
const { MEMBERS, createSeed } = require('./seed');
|
||||||
|
|
||||||
|
const MEMBER_IDS = MEMBERS.map((item) => item.id);
|
||||||
|
const NAMES = Object.fromEntries(MEMBERS.map((item) => [item.id, item.name]));
|
||||||
|
const CHANNELS = Object.freeze({ wechat: '微信', alipay: '支付宝', cash: '现金', bank: '银行转账', credit_card: '信用卡' });
|
||||||
|
const MAX_CENTS = 10000000000;
|
||||||
|
const MAX_MG = 1000000000;
|
||||||
|
const DAY = /^\d{4}-\d{2}-\d{2}$/;
|
||||||
|
|
||||||
|
class DemoError extends Error {
|
||||||
|
constructor(code, message, field, status = 400) {
|
||||||
|
super(message);
|
||||||
|
this.name = 'DemoError';
|
||||||
|
this.code = code;
|
||||||
|
this.status = status;
|
||||||
|
if (field) this.field = field;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function fail(code, message, field, status) { throw new DemoError(code, message, field, status); }
|
||||||
|
function clone(value) { return JSON.parse(JSON.stringify(value)); }
|
||||||
|
function dateValue(value, field = 'date') {
|
||||||
|
if (typeof value !== 'string' || !DAY.test(value) || value < '2000-01-01' || value > '2099-12-31') {
|
||||||
|
fail('INVALID_DATE', '日期须为2000—2099年内的有效年月日。', field);
|
||||||
|
}
|
||||||
|
const parsed = new Date(`${value}T00:00:00.000Z`);
|
||||||
|
if (!Number.isFinite(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== value) fail('INVALID_DATE', '日期无效。', field);
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
function memberValue(value, field) {
|
||||||
|
if (!MEMBER_IDS.includes(value)) fail('INVALID_MEMBER', '请选择有效成员。', field);
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
function decimal(value, digits, field, positive = false, maximum = MAX_CENTS) {
|
||||||
|
if (!['number', 'string'].includes(typeof value) || (typeof value === 'number' && !Number.isFinite(value))) {
|
||||||
|
fail('INVALID_AMOUNT', `${field}须为有效数字。`, field);
|
||||||
|
}
|
||||||
|
const source = String(value).trim();
|
||||||
|
const match = /^(0|[1-9]\d*)(?:\.(\d+))?$/.exec(source);
|
||||||
|
if (!match || (match[2] || '').length > digits) fail('INVALID_AMOUNT', `${field}最多保留${digits}位小数,且不能为负数。`, field);
|
||||||
|
const units = BigInt(match[1]) * (10n ** BigInt(digits)) + BigInt((match[2] || '').padEnd(digits, '0') || '0');
|
||||||
|
if (units > BigInt(maximum) || (positive && units === 0n)) fail('INVALID_AMOUNT', positive ? `${field}须大于0且在演示范围内。` : `${field}超出演示范围。`, field);
|
||||||
|
return Number(units);
|
||||||
|
}
|
||||||
|
function money(value, field, positive = false) { return decimal(value, 2, field, positive); }
|
||||||
|
function weight(value) { return decimal(value, 3, 'grams', true, MAX_MG); }
|
||||||
|
function roundRatio(numerator, denominator) {
|
||||||
|
if (denominator <= 0) throw new Error('内部计算分母须为正数。');
|
||||||
|
return Number((BigInt(numerator) + BigInt(denominator) / 2n) / BigInt(denominator));
|
||||||
|
}
|
||||||
|
function multiplyRatio(a, b, denominator) { return roundRatio(BigInt(a) * BigInt(b), denominator); }
|
||||||
|
function textValue(value, field, required = false, limit = 500) {
|
||||||
|
if (value === undefined && !required) return '';
|
||||||
|
if (typeof value !== 'string' || value.trim().length > limit || (required && !value.trim())) fail('INVALID_TEXT', `${field}须为${required ? '非空' : ''}文本,最长${limit}字。`, field);
|
||||||
|
return value.trim();
|
||||||
|
}
|
||||||
|
function payloadObject(value) {
|
||||||
|
if (!value || typeof value !== 'object' || Array.isArray(value)) fail('INVALID_BODY', '请求须为JSON对象。');
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
function allowedKeys(payload, keys) {
|
||||||
|
const allowed = new Set([...keys, 'requestId', 'idempotencyKey']);
|
||||||
|
for (const key of Object.keys(payload)) if (!allowed.has(key)) fail('UNSUPPORTED_FIELD', `演示不支持字段:${key}。只支持已交付且已收齐的普通销售。`, key);
|
||||||
|
}
|
||||||
|
function validBusinessDate(state, value) {
|
||||||
|
const date = dateValue(value);
|
||||||
|
if (date < state.demo.startDate) fail('BEFORE_OPENING', '交易日期不能早于演示期初。', 'date');
|
||||||
|
return date;
|
||||||
|
}
|
||||||
|
function latestDate(state) {
|
||||||
|
return [...state.purchases, ...state.orders, ...state.transfers].reduce((latest, item) => item.date > latest ? item.date : latest, state.demo.startDate);
|
||||||
|
}
|
||||||
|
function pairInfo(one, two) {
|
||||||
|
const [memberA, memberB] = [one, two].sort((a, b) => MEMBER_IDS.indexOf(a) - MEMBER_IDS.indexOf(b));
|
||||||
|
return { pairId: `${memberA}:${memberB}`, memberA, memberB };
|
||||||
|
}
|
||||||
|
function direction(memberA, memberB, signed) {
|
||||||
|
return { from: signed === 0 ? null : signed > 0 ? memberA : memberB, to: signed === 0 ? null : signed > 0 ? memberB : memberA, amountCents: Math.abs(signed) };
|
||||||
|
}
|
||||||
|
function canonical(value) {
|
||||||
|
if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
|
||||||
|
if (value && typeof value === 'object') return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(',')}}`;
|
||||||
|
return JSON.stringify(value);
|
||||||
|
}
|
||||||
|
function idempotency(payload, type) {
|
||||||
|
const key = payload.requestId === undefined ? payload.idempotencyKey : payload.requestId;
|
||||||
|
if (key === undefined) return null;
|
||||||
|
if (typeof key !== 'string' || !/^[A-Za-z0-9_.:-]{1,100}$/.test(key)) fail('INVALID_REQUEST_ID', '重复提交标识须为1—100位字母、数字或._:-。', 'requestId');
|
||||||
|
const content = { ...payload };
|
||||||
|
delete content.requestId;
|
||||||
|
delete content.idempotencyKey;
|
||||||
|
return { key, type, fingerprint: createHash('sha256').update(canonical(content)).digest('hex') };
|
||||||
|
}
|
||||||
|
|
||||||
|
function purchasePreview(payload) {
|
||||||
|
const weightMg = weight(payload.grams);
|
||||||
|
const totalCents = money(payload.total, 'total', true);
|
||||||
|
const unitPriceCents = multiplyRatio(totalCents, 1000, weightMg);
|
||||||
|
return { weightMg, totalCents, unitPriceCents, unitPriceYuanPerGram: unitPriceCents / 100 };
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyCommand(state, type, rawPayload) {
|
||||||
|
const payload = payloadObject(rawPayload);
|
||||||
|
if (type === 'reset' || type === 'scenario') {
|
||||||
|
allowedKeys(payload, type === 'reset' ? [] : ['name', 'scenario']);
|
||||||
|
const name = type === 'reset' ? 'default' : (payload.name || payload.scenario);
|
||||||
|
if (!['default', 'complex'].includes(name)) fail('INVALID_SCENARIO', '请选择默认示例或复杂示例。', 'name');
|
||||||
|
return createSeed(name);
|
||||||
|
}
|
||||||
|
const definitions = {
|
||||||
|
opening: ['member', 'amount', 'date'],
|
||||||
|
purchase: ['date', 'payer', 'grams', 'total', 'note'],
|
||||||
|
order: ['date', 'member', 'customer', 'grams', 'sale', 'collector', 'channel', 'expenseAmount', 'expensePayer', 'materialSource', 'directMaterialCost', 'directMaterialPayer', 'note', 'allowLoss'],
|
||||||
|
transfer: ['date', 'from', 'to', 'amount', 'note'],
|
||||||
|
};
|
||||||
|
if (!definitions[type]) fail('UNKNOWN_COMMAND', '未知演示操作。', undefined, 404);
|
||||||
|
allowedKeys(payload, definitions[type]);
|
||||||
|
const request = type === 'opening' ? null : idempotency(payload, type);
|
||||||
|
const oldRequest = request && (state.requests || []).find((item) => item.key === request.key);
|
||||||
|
if (oldRequest) {
|
||||||
|
if (oldRequest.type !== request.type || oldRequest.fingerprint !== request.fingerprint) fail('IDEMPOTENCY_CONFLICT', '该提交标识已用于不同内容,请刷新后重试。', 'requestId', 409);
|
||||||
|
return clone(state);
|
||||||
|
}
|
||||||
|
const next = clone(state);
|
||||||
|
let entry;
|
||||||
|
if (type === 'opening') {
|
||||||
|
const member = memberValue(payload.member, 'member');
|
||||||
|
if (payload.date !== undefined && dateValue(payload.date) !== state.demo.startDate) fail('FIXED_OPENING_DATE', '本演示只修改期初金额,期初日期固定,不能跨过已有交易。', 'date');
|
||||||
|
next.opening.find((item) => item.member === member).amount = money(payload.amount, 'amount');
|
||||||
|
} else {
|
||||||
|
const sequence = next.nextSequence++;
|
||||||
|
const date = validBusinessDate(state, payload.date);
|
||||||
|
const note = textValue(payload.note, 'note');
|
||||||
|
if (type === 'purchase') {
|
||||||
|
entry = { id: `purchase-${sequence}`, sequence, date, payer: memberValue(payload.payer, 'payer'), weightMg: weight(payload.grams), totalCents: money(payload.total, 'total', true), note };
|
||||||
|
next.purchases.push(entry);
|
||||||
|
} else if (type === 'order') {
|
||||||
|
const member = memberValue(payload.member, 'member');
|
||||||
|
const channel = payload.channel || 'wechat';
|
||||||
|
if (typeof channel !== 'string' || !Object.hasOwn(CHANNELS, channel)) fail('INVALID_CHANNEL', '请选择有效收款渠道。', 'channel');
|
||||||
|
const materialSource = payload.materialSource || 'pool';
|
||||||
|
if (!['pool', 'direct'].includes(materialSource)) fail('INVALID_MATERIAL_SOURCE', '材料来源须为共用料池或本单自行配货。', 'materialSource');
|
||||||
|
if (payload.allowLoss !== undefined && typeof payload.allowLoss !== 'boolean') fail('INVALID_ALLOW_LOSS', '亏损复核标记须为布尔值。', 'allowLoss');
|
||||||
|
const expenseCents = money(payload.expenseAmount === undefined ? 0 : payload.expenseAmount, 'expenseAmount');
|
||||||
|
if (materialSource === 'pool' && payload.directMaterialCost !== undefined && money(payload.directMaterialCost, 'directMaterialCost') !== 0) fail('INVALID_DIRECT_COST', '共用料池用料不能同时登记自行配货材料款。', 'directMaterialCost');
|
||||||
|
entry = {
|
||||||
|
id: `order-${sequence}`, sequence, date, member, customer: textValue(payload.customer, 'customer', true, 80),
|
||||||
|
weightMg: weight(payload.grams), saleCents: money(payload.sale, 'sale', true),
|
||||||
|
collector: channel === 'credit_card' ? 'owner' : memberValue(payload.collector || member, 'collector'), channel,
|
||||||
|
expenseCents, expensePayer: memberValue(payload.expensePayer || member, 'expensePayer'), materialSource,
|
||||||
|
directMaterialCostCents: materialSource === 'direct' ? money(payload.directMaterialCost, 'directMaterialCost', true) : 0,
|
||||||
|
directMaterialPayer: memberValue(payload.directMaterialPayer || member, 'directMaterialPayer'),
|
||||||
|
allowLoss: payload.allowLoss === true, note,
|
||||||
|
};
|
||||||
|
next.orders.push(entry);
|
||||||
|
} else {
|
||||||
|
const from = memberValue(payload.from, 'from');
|
||||||
|
const to = memberValue(payload.to, 'to');
|
||||||
|
if (from === to) fail('SAME_MEMBER', '转出人与转入人不能相同。', 'to');
|
||||||
|
const amountCents = money(payload.amount, 'amount', true);
|
||||||
|
const pair = pairInfo(from, to);
|
||||||
|
const relation = buildReport(state, date).settlements.find((item) => item.pairId === pair.pairId);
|
||||||
|
if (relation.from !== from || relation.to !== to || amountCents > relation.pendingCents) fail('TRANSFER_EXCEEDS_PENDING', '这对成员当前没有该方向的足额待转款;请按报告中的方向和金额登记。', 'amount', 409);
|
||||||
|
entry = { id: `transfer-${sequence}`, sequence, date, from, to, amountCents, note };
|
||||||
|
next.transfers.push(entry);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (request) next.requests.push({ ...request, entryId: entry.id });
|
||||||
|
// 每次从全部虚构事实重放;失败时调用者仍持有原state,任何现金和文件均不改变。
|
||||||
|
const complete = buildReport(next, latestDate(next));
|
||||||
|
if (type === 'order') {
|
||||||
|
const calculated = complete.orders.find((item) => item.id === entry.id);
|
||||||
|
if (calculated.profitCents < 0 && !entry.allowLoss) fail('LOSS_REQUIRES_REVIEW', '本单预计亏损。亏损结算政策未确认;只有明确标记“亏损待复核”后才可演示登记,且不会自动反向支付利润。', 'allowLoss', 409);
|
||||||
|
}
|
||||||
|
return next;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 日报只取所选日原始订单的计算结果,不读取历史往来或实转记录。
|
||||||
|
function dailyReport(state, date, calculatedOrders) {
|
||||||
|
const dayOrders = calculatedOrders.filter(order => order.date === date);
|
||||||
|
const sum = (rows, key) => rows.reduce((n, row) => n + row[key], 0);
|
||||||
|
const members = MEMBERS.map(({id, name}) => {
|
||||||
|
const orders = dayOrders.filter(order => order.member === id);
|
||||||
|
const incomeDetails = orders.map(order => ({orderId:order.id, customer:order.customer, collector:order.collector, collectorName:NAMES[order.collector], channel:order.channel, channelName:CHANNELS[order.channel], amountCents:order.saleCents, collectionType:order.collector === id ? 'self' : order.collector === 'owner' ? 'owner' : 'other'}));
|
||||||
|
const costDetails = orders.flatMap(order => [
|
||||||
|
...order.funding.map(part => ({kind:'material',label:order.materialSource === 'direct' ? '单独配货材料' : '已用材料',payer:part.payer,amountCents:part.amountCents})),
|
||||||
|
...(order.expenseCents ? [{kind:'expense',label:'工费等费用',payer:order.expensePayer,amountCents:order.expenseCents}] : []),
|
||||||
|
...(order.cardFeeCents ? [{kind:'cardFee',label:'刷卡手续费6‰',payer:'owner',amountCents:order.cardFeeCents}] : []),
|
||||||
|
].map(part => ({...part,orderId:order.id,customer:order.customer,payerName:NAMES[part.payer]})));
|
||||||
|
const costsByPayer = MEMBERS.map(payer => ({member:payer.id,name:payer.name,amountCents:sum(costDetails.filter(part => part.payer === payer.id),'amountCents')}));
|
||||||
|
const channelTotals = Object.entries(CHANNELS).map(([channel,label]) => ({channel,label,amountCents:sum(incomeDetails.filter(item => item.channel === channel),'amountCents')})).filter(item => item.amountCents);
|
||||||
|
const salesCents = sum(orders,'saleCents'), orderCostCents = sum(orders,'orderCostCents'), profitCents = sum(orders,'profitCents');
|
||||||
|
if (sum(costDetails,'amountCents') !== orderCostCents || sum(incomeDetails,'amountCents') !== salesCents) throw new Error('当日订单收入或成本明细不守恒。');
|
||||||
|
const ownerAdvancedCents = sum(costDetails.filter(item => item.payer === 'owner'),'amountCents');
|
||||||
|
const ownerCollectedCents = sum(incomeDetails.filter(item => item.collectionType === 'owner'),'amountCents');
|
||||||
|
const reviewRequired = orders.some(order => order.reviewRequired), calculatedToOwnerCents = id === 'owner' ? 0 : ownerAdvancedCents + profitCents - ownerCollectedCents;
|
||||||
|
return {member:id,name,date,openingCents:state.opening.find(item => item.member === id)?.amount || 0,orderCount:orders.length,salesCents,orderCostCents,profitCents,
|
||||||
|
selfCollectedCents:sum(incomeDetails.filter(item => item.collectionType === 'self'),'amountCents'),ownerCollectedCents,otherCollectedCents:sum(incomeDetails.filter(item => item.collectionType === 'other'),'amountCents'),
|
||||||
|
ownerAdvancedCents,selfPaidCents:sum(costDetails.filter(item => item.payer === id),'amountCents'),otherAdvancedCents:sum(costDetails.filter(item => item.payer !== id && item.payer !== 'owner'),'amountCents'),
|
||||||
|
calculatedToOwnerCents,toOwnerCents:reviewRequired ? null : calculatedToOwnerCents,reviewRequired,incomeDetails,channelTotals,costDetails,costsByPayer};
|
||||||
|
});
|
||||||
|
return {date,members,overview:{orderCount:dayOrders.length,salesCents:sum(dayOrders,'saleCents'),orderCostCents:sum(dayOrders,'orderCostCents'),profitCents:sum(dayOrders,'profitCents')}};
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildReport(state, requestedDate) {
|
||||||
|
const date = dateValue(requestedDate || state.demo.defaultDate);
|
||||||
|
if (date < state.demo.startDate) fail('BEFORE_OPENING', '查看日期不能早于演示期初。', 'date');
|
||||||
|
const stats = Object.fromEntries(MEMBERS.map(({ id, name }) => {
|
||||||
|
const opening = state.opening.find((item) => item.member === id);
|
||||||
|
const amount = opening && opening.date <= date ? opening.amount : 0;
|
||||||
|
return [id, {
|
||||||
|
member: id, name, openingCents: amount, cashCents: amount,
|
||||||
|
collectedCents: 0, purchasePaidCents: 0, directMaterialPaidCents: 0, expensePaidCents: 0, cardFeePaidCents: 0,
|
||||||
|
transferInCents: 0, transferOutCents: 0,
|
||||||
|
salesCents: 0, materialCostCents: 0, expenseCents: 0, cardFeeCents: 0, profitCents: 0, orderCostCents: 0, profitDueCents: 0,
|
||||||
|
cumulativeSalesCents: 0, cumulativeMaterialCostCents: 0, cumulativeExpenseCents: 0, cumulativeCardFeeCents: 0,
|
||||||
|
cumulativeProfitCents: 0, cumulativeOrderCostCents: 0, cumulativeProfitDueCents: 0,
|
||||||
|
unusedMaterialCents: 0, pendingPayCents: 0, pendingReceiveCents: 0,
|
||||||
|
dailyCollections: [], collectedByOthers: [], channelReceipts: [],
|
||||||
|
settlement: { openingPayCents: 0, openingReceiveCents: 0, newPayCents: 0, newReceiveCents: 0, transferredOutCents: 0, transferredInCents: 0, pendingPayCents: 0, pendingReceiveCents: 0 },
|
||||||
|
}];
|
||||||
|
}));
|
||||||
|
const pairs = [];
|
||||||
|
for (let a = 0; a < MEMBER_IDS.length; a++) for (let b = a + 1; b < MEMBER_IDS.length; b++) {
|
||||||
|
const memberA = MEMBER_IDS[a];
|
||||||
|
const memberB = MEMBER_IDS[b];
|
||||||
|
pairs.push({ pairId: `${memberA}:${memberB}`, memberA, memberB, memberAName: NAMES[memberA], memberBName: NAMES[memberB], openingSignedCents: 0, newSignedCents: 0, transferredSignedCents: 0, pendingSignedCents: 0,
|
||||||
|
components: { materialSignedCents: 0, expenseSignedCents: 0, cardFeeSignedCents: 0, collectionSignedCents: 0, profitSignedCents: 0 }, events: [] });
|
||||||
|
}
|
||||||
|
const pairById = Object.fromEntries(pairs.map((item) => [item.pairId, item]));
|
||||||
|
const funding = [];
|
||||||
|
const calculatedOrders = [];
|
||||||
|
const transactions = [];
|
||||||
|
const warnings = [];
|
||||||
|
const receipts = Object.fromEntries(MEMBER_IDS.map((id) => [id, {}]));
|
||||||
|
const ownCollections = Object.fromEntries(MEMBER_IDS.map((id) => [id, {}]));
|
||||||
|
const otherCollections = Object.fromEntries(MEMBER_IDS.map((id) => [id, {}]));
|
||||||
|
let poolWeight = 0;
|
||||||
|
let poolCost = 0;
|
||||||
|
let selectedPool;
|
||||||
|
const dates = [...new Set([date, ...state.purchases.map((item) => item.date), ...state.orders.map((item) => item.date), ...state.transfers.map((item) => item.date)])].filter((item) => item <= date).sort();
|
||||||
|
const sorted = (items) => [...items].sort((a, b) => a.sequence - b.sequence);
|
||||||
|
function cash(member, amountCents, entry, type, description) {
|
||||||
|
stats[member].cashCents += amountCents;
|
||||||
|
transactions.push({ id: `${entry.id}:${type}`, date: entry.date, sequence: entry.sequence, type, member, amountCents, description, ...(type === 'purchase' ? { purchaseId: entry.id } : { orderId: entry.id }) });
|
||||||
|
}
|
||||||
|
function obligation(from, to, amountCents, type, order, description) {
|
||||||
|
if (!amountCents || from === to) return;
|
||||||
|
const pair = pairById[pairInfo(from, to).pairId];
|
||||||
|
const signed = from === pair.memberA ? amountCents : -amountCents;
|
||||||
|
pair.pendingSignedCents += signed;
|
||||||
|
if (order.date === date) pair.newSignedCents += signed;
|
||||||
|
else pair.openingSignedCents += signed;
|
||||||
|
pair.components[`${type}SignedCents`] += signed;
|
||||||
|
pair.events.push({ date: order.date, sequence: order.sequence, orderId: order.id, type, from, to, amountCents, description });
|
||||||
|
}
|
||||||
|
function consumeFunding(amountCents) {
|
||||||
|
let pending = amountCents;
|
||||||
|
const slices = [];
|
||||||
|
for (const source of funding) {
|
||||||
|
const taken = Math.min(source.remainingCents, pending);
|
||||||
|
if (taken > 0) {
|
||||||
|
source.remainingCents -= taken;
|
||||||
|
source.consumedCents += taken;
|
||||||
|
pending -= taken;
|
||||||
|
slices.push({ purchaseId: source.purchaseId, payer: source.payer, amountCents: taken });
|
||||||
|
}
|
||||||
|
if (pending === 0) break;
|
||||||
|
}
|
||||||
|
if (pending !== 0) throw new Error('材料付款来源余额与料池成本不一致。');
|
||||||
|
return slices;
|
||||||
|
}
|
||||||
|
for (const day of dates) {
|
||||||
|
const purchases = sorted(state.purchases.filter((item) => item.date === day));
|
||||||
|
const orders = sorted(state.orders.filter((item) => item.date === day));
|
||||||
|
const openingWeightMg = poolWeight;
|
||||||
|
const openingCostCents = poolCost;
|
||||||
|
let purchaseWeightMg = 0;
|
||||||
|
let purchaseCostCents = 0;
|
||||||
|
for (const purchase of purchases) {
|
||||||
|
purchaseWeightMg += purchase.weightMg;
|
||||||
|
purchaseCostCents += purchase.totalCents;
|
||||||
|
funding.push({ purchaseId: purchase.id, date: day, payer: purchase.payer, totalCents: purchase.totalCents, consumedCents: 0, remainingCents: purchase.totalCents });
|
||||||
|
stats[purchase.payer].purchasePaidCents += purchase.totalCents;
|
||||||
|
cash(purchase.payer, -purchase.totalCents, purchase, 'purchase', `${NAMES[purchase.payer]}实付购料款`);
|
||||||
|
}
|
||||||
|
const availableWeightMg = poolWeight + purchaseWeightMg;
|
||||||
|
const availableCostCents = poolCost + purchaseCostCents;
|
||||||
|
let usedWeightMg = 0;
|
||||||
|
let usedCostCents = 0;
|
||||||
|
for (const order of orders) {
|
||||||
|
let materialCostCents;
|
||||||
|
let materialFunding;
|
||||||
|
if (order.materialSource === 'direct') {
|
||||||
|
materialCostCents = order.directMaterialCostCents;
|
||||||
|
materialFunding = [{ purchaseId: null, payer: order.directMaterialPayer, amountCents: materialCostCents }];
|
||||||
|
stats[order.directMaterialPayer].directMaterialPaidCents += materialCostCents;
|
||||||
|
cash(order.directMaterialPayer, -materialCostCents, order, 'direct_material', `${NAMES[order.directMaterialPayer]}实付本单自行配货材料款`);
|
||||||
|
} else {
|
||||||
|
if (usedWeightMg + order.weightMg > availableWeightMg) fail('INSUFFICIENT_MATERIAL', `${day}共用料不足,无法登记${order.customer}:可用${((availableWeightMg - usedWeightMg) / 1000).toFixed(3)}克。请先登记同日或之前的真实模拟购料。`, 'grams', 409);
|
||||||
|
usedWeightMg += order.weightMg;
|
||||||
|
const cumulativeCost = multiplyRatio(availableCostCents, usedWeightMg, availableWeightMg);
|
||||||
|
materialCostCents = cumulativeCost - usedCostCents;
|
||||||
|
usedCostCents = cumulativeCost;
|
||||||
|
materialFunding = consumeFunding(materialCostCents);
|
||||||
|
}
|
||||||
|
const cardFeeCents = order.channel === 'credit_card' ? multiplyRatio(order.saleCents, 6, 1000) : 0;
|
||||||
|
const orderCostCents = materialCostCents + order.expenseCents + cardFeeCents;
|
||||||
|
const profitCents = order.saleCents - orderCostCents;
|
||||||
|
const profitDueCents = order.member === 'owner' ? 0 : Math.max(profitCents, 0);
|
||||||
|
stats[order.collector].collectedCents += order.saleCents;
|
||||||
|
cash(order.collector, order.saleCents, order, 'collection', `${NAMES[order.collector]}通过${CHANNELS[order.channel]}实收${order.customer}货款`);
|
||||||
|
receipts[order.collector][order.channel] = (receipts[order.collector][order.channel] || 0) + order.saleCents;
|
||||||
|
stats[order.expensePayer].expensePaidCents += order.expenseCents;
|
||||||
|
if (order.expenseCents) cash(order.expensePayer, -order.expenseCents, order, 'expense', `${NAMES[order.expensePayer]}实付${order.customer}其他费用`);
|
||||||
|
if (cardFeeCents) {
|
||||||
|
stats.owner.cardFeePaidCents += cardFeeCents;
|
||||||
|
cash('owner', -cardFeeCents, order, 'card_fee', '麦麦实付信用卡手续费6‰');
|
||||||
|
}
|
||||||
|
for (const slice of materialFunding) obligation(order.member, slice.payer, slice.amountCents, 'material', order, '已耗用材料归还原付款人');
|
||||||
|
obligation(order.member, order.expensePayer, order.expenseCents, 'expense', order, '归还他人代付的其他费用');
|
||||||
|
obligation(order.member, 'owner', cardFeeCents, 'cardFee', order, '归还麦麦代付的信用卡手续费');
|
||||||
|
obligation(order.collector, order.member, order.saleCents, 'collection', order, '代收货款归还订单归属人');
|
||||||
|
obligation(order.member, 'owner', profitDueCents, 'profit', order, '助理本单正利润上交麦麦');
|
||||||
|
const itemStats = stats[order.member];
|
||||||
|
const fields = { Sales: order.saleCents, MaterialCost: materialCostCents, Expense: order.expenseCents, CardFee: cardFeeCents, Profit: profitCents, OrderCost: orderCostCents, ProfitDue: profitDueCents };
|
||||||
|
for (const [field, value] of Object.entries(fields)) {
|
||||||
|
itemStats[`cumulative${field}Cents`] += value;
|
||||||
|
if (day === date) itemStats[`${field[0].toLowerCase()}${field.slice(1)}Cents`] += value;
|
||||||
|
}
|
||||||
|
if (day === date) {
|
||||||
|
if (order.collector === order.member) ownCollections[order.member][order.channel] = (ownCollections[order.member][order.channel] || 0) + order.saleCents;
|
||||||
|
else otherCollections[order.member][order.collector] = (otherCollections[order.member][order.collector] || 0) + order.saleCents;
|
||||||
|
}
|
||||||
|
const calculated = { ...clone(order), materialCostCents, cardFeeCents, orderCostCents, profitCents, profitDueCents, reviewRequired: profitCents < 0,
|
||||||
|
funding: materialFunding, formula: `${(order.saleCents / 100).toFixed(2)}-${(materialCostCents / 100).toFixed(2)}-${(order.expenseCents / 100).toFixed(2)}-${(cardFeeCents / 100).toFixed(2)}=${(profitCents / 100).toFixed(2)}` };
|
||||||
|
calculatedOrders.push(calculated);
|
||||||
|
if (profitCents < 0) warnings.push({ code: 'LOSS_REQUIRES_REVIEW', orderId: order.id, message: `${order.customer}亏损${(-profitCents / 100).toFixed(2)}元,亏损承担政策待复核;本演示不自动让麦麦反向补利润。` });
|
||||||
|
}
|
||||||
|
poolWeight = availableWeightMg - usedWeightMg;
|
||||||
|
poolCost = availableCostCents - usedCostCents;
|
||||||
|
for (const transfer of sorted(state.transfers.filter((item) => item.date === day))) {
|
||||||
|
stats[transfer.from].cashCents -= transfer.amountCents;
|
||||||
|
stats[transfer.to].cashCents += transfer.amountCents;
|
||||||
|
stats[transfer.from].transferOutCents += transfer.amountCents;
|
||||||
|
stats[transfer.to].transferInCents += transfer.amountCents;
|
||||||
|
const pair = pairById[pairInfo(transfer.from, transfer.to).pairId];
|
||||||
|
const signed = transfer.from === pair.memberA ? transfer.amountCents : -transfer.amountCents;
|
||||||
|
pair.pendingSignedCents -= signed;
|
||||||
|
if (day === date) {
|
||||||
|
pair.transferredSignedCents += signed;
|
||||||
|
stats[transfer.from].settlement.transferredOutCents += transfer.amountCents;
|
||||||
|
stats[transfer.to].settlement.transferredInCents += transfer.amountCents;
|
||||||
|
} else pair.openingSignedCents -= signed;
|
||||||
|
pair.events.push({ date: day, sequence: transfer.sequence, transferId: transfer.id, type: 'transfer', from: transfer.from, to: transfer.to, amountCents: transfer.amountCents, description: '已点击登记的模拟转账' });
|
||||||
|
transactions.push({ ...clone(transfer), type: 'transfer', description: `${NAMES[transfer.from]}已向${NAMES[transfer.to]}登记模拟转账` });
|
||||||
|
}
|
||||||
|
if (day === date) selectedPool = { openingWeightMg, openingCostCents, purchaseWeightMg, purchaseCostCents, availableWeightMg, availableCostCents, usedWeightMg, usedCostCents, closingWeightMg: poolWeight, closingCostCents: poolCost,
|
||||||
|
weightedCostYuanPerGram: availableWeightMg ? Number((availableCostCents * 10 / availableWeightMg).toFixed(6)) : 0,
|
||||||
|
weightedUnitPriceCents: availableWeightMg ? multiplyRatio(availableCostCents, 1000, availableWeightMg) : 0 };
|
||||||
|
}
|
||||||
|
for (const source of funding) stats[source.payer].unusedMaterialCents += source.remainingCents;
|
||||||
|
for (const pair of pairs) {
|
||||||
|
pair.pendingCents = Math.abs(pair.pendingSignedCents);
|
||||||
|
const current = direction(pair.memberA, pair.memberB, pair.pendingSignedCents);
|
||||||
|
pair.from = current.from;
|
||||||
|
pair.to = current.to;
|
||||||
|
pair.fromName = NAMES[current.from] || '';
|
||||||
|
pair.toName = NAMES[current.to] || '';
|
||||||
|
pair.opening = direction(pair.memberA, pair.memberB, pair.openingSignedCents);
|
||||||
|
pair.newToday = direction(pair.memberA, pair.memberB, pair.newSignedCents);
|
||||||
|
pair.transferredToday = direction(pair.memberA, pair.memberB, pair.transferredSignedCents);
|
||||||
|
for (const [prefix, signed] of [['opening', pair.openingSignedCents], ['new', pair.newSignedCents], ['pending', pair.pendingSignedCents]]) {
|
||||||
|
const result = direction(pair.memberA, pair.memberB, signed);
|
||||||
|
if (result.amountCents) {
|
||||||
|
stats[result.from].settlement[`${prefix}PayCents`] += result.amountCents;
|
||||||
|
stats[result.to].settlement[`${prefix}ReceiveCents`] += result.amountCents;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (current.amountCents) {
|
||||||
|
stats[current.from].pendingPayCents += current.amountCents;
|
||||||
|
stats[current.to].pendingReceiveCents += current.amountCents;
|
||||||
|
}
|
||||||
|
const obligationsSigned = Object.values(pair.components).reduce((sum, item) => sum + item, 0);
|
||||||
|
const hasTransfers = pair.events.some((event) => event.type === 'transfer');
|
||||||
|
pair.refundAfterRecalculation = hasTransfers && pair.pendingSignedCents !== 0 && (obligationsSigned === 0 || Math.sign(pair.pendingSignedCents) !== Math.sign(obligationsSigned));
|
||||||
|
if (pair.refundAfterRecalculation) warnings.push({ code: 'SETTLEMENT_DIRECTION_CHANGED', message: `${pair.fromName}当前需向${pair.toName}转${(pair.pendingCents / 100).toFixed(2)}元:当前往来方向已变化,原已登记转账仍保留;请按本日新增与累计待转核对。` });
|
||||||
|
pair.events.sort((a, b) => a.date.localeCompare(b.date) || a.sequence - b.sequence);
|
||||||
|
}
|
||||||
|
const cumulativeProfitCents = Object.values(stats).reduce((sum, item) => sum + item.cumulativeProfitCents, 0);
|
||||||
|
for (const member of Object.values(stats)) {
|
||||||
|
member.dailyCollections = Object.entries(ownCollections[member.member]).map(([channel, amountCents]) => ({ channel, label: CHANNELS[channel], amountCents }));
|
||||||
|
member.collectedByOthers = Object.entries(otherCollections[member.member]).map(([id, amountCents]) => ({ member: id, name: NAMES[id], amountCents }));
|
||||||
|
member.channelReceipts = Object.entries(receipts[member.member]).map(([channel, amountCents]) => ({ channel, label: CHANNELS[channel], amountCents }));
|
||||||
|
member.cashPlusUnusedCents = member.cashCents + member.unusedMaterialCents;
|
||||||
|
member.projectedSettledCashCents = member.cashCents + member.pendingReceiveCents - member.pendingPayCents;
|
||||||
|
member.projectedSettledAssetsCents = member.cashPlusUnusedCents + member.pendingReceiveCents - member.pendingPayCents;
|
||||||
|
member.expectedSettledAssetsCents = member.openingCents + (member.member === 'owner' ? cumulativeProfitCents : 0);
|
||||||
|
const differenceCents = member.projectedSettledAssetsCents - member.expectedSettledAssetsCents;
|
||||||
|
const shortfallCents = Math.max(-member.cashCents, 0);
|
||||||
|
member.cashStatus = { status: shortfallCents ? 'shortfall' : 'ok', shortfallCents, note: shortfallCents ? `资金缺口${(shortfallCents / 100).toFixed(2)}元,需核实另行垫入资金;不是额外利润或已到账款。` : '当前现金未出现资金缺口。' };
|
||||||
|
member.balanceCheck = { status: differenceCents === 0 && !shortfallCents ? 'ok' : 'review', mathStatus: differenceCents === 0 ? 'ok' : 'review', differenceCents,
|
||||||
|
note: shortfallCents ? `${differenceCents === 0 ? '资产数学核对相符,但' : ''}${member.cashStatus.note}` : differenceCents === 0 ? (member.member === 'owner' ? '现金+本人未用料+应收-应付=期初+全店累计利润。' : '现金+本人未用料+应收-应付=期初周转金。') : '亏损政策尚未确认,需人工复核承担方;演示未自动补款。' };
|
||||||
|
if (shortfallCents) warnings.push({ code: 'CASH_SHORTFALL', member: member.member, message: `${member.name}:${member.cashStatus.note}` });
|
||||||
|
member.cashExplanation = '期初周转金+实际收款-购料-自行配货材料-实付费用-刷卡手续费+已收转账-已付转账';
|
||||||
|
}
|
||||||
|
const memberList = MEMBERS.map(({ id }) => stats[id]);
|
||||||
|
const sum = (field) => memberList.reduce((total, item) => total + item[field], 0);
|
||||||
|
const overview = {
|
||||||
|
salesCents: sum('salesCents'), materialCostCents: sum('materialCostCents'), expenseCents: sum('expenseCents'), cardFeeCents: sum('cardFeeCents'), orderCostCents: sum('orderCostCents'), profitCents: sum('profitCents'),
|
||||||
|
cumulativeSalesCents: sum('cumulativeSalesCents'), cumulativeMaterialCostCents: sum('cumulativeMaterialCostCents'), cumulativeExpenseCents: sum('cumulativeExpenseCents'), cumulativeCardFeeCents: sum('cumulativeCardFeeCents'), cumulativeOrderCostCents: sum('cumulativeOrderCostCents'), cumulativeProfitCents,
|
||||||
|
cashCents: sum('cashCents'), unusedMaterialCents: poolCost, pendingTransferCents: pairs.reduce((total, item) => total + item.pendingCents, 0),
|
||||||
|
orderCount: calculatedOrders.filter((item) => item.date === date).length, purchaseCount: state.purchases.filter((item) => item.date === date).length, transferCount: state.transfers.filter((item) => item.date === date).length,
|
||||||
|
cumulativeOrderCount: calculatedOrders.length,
|
||||||
|
};
|
||||||
|
const totalAssetsCents = overview.cashCents + poolCost;
|
||||||
|
const openingCents = sum('openingCents');
|
||||||
|
const expectedAssetsCents = openingCents + cumulativeProfitCents;
|
||||||
|
const cashShortfallCents = memberList.reduce((total, item) => total + item.cashStatus.shortfallCents, 0);
|
||||||
|
return { date, scenarioName: state.demo.name, daily:dailyReport(state,date,calculatedOrders), overview, members: memberList, materialPool: { ...selectedPool, funding: clone(funding) }, settlements: pairs,
|
||||||
|
orders: calculatedOrders, transactions: transactions.sort((a, b) => a.date.localeCompare(b.date) || a.sequence - b.sequence), warnings,
|
||||||
|
reconciliation: { totalCashCents: overview.cashCents, totalUnusedCents: poolCost, totalAssetsCents, openingCents, totalProfitCents: cumulativeProfitCents, expectedAssetsCents, differenceCents: totalAssetsCents - expectedAssetsCents,
|
||||||
|
mathStatus: totalAssetsCents === expectedAssetsCents ? 'ok' : 'review', cashShortfallCents, status: totalAssetsCents === expectedAssetsCents && cashShortfallCents === 0 ? 'ok' : 'review' } };
|
||||||
|
}
|
||||||
|
|
||||||
|
function publicState(state, date) {
|
||||||
|
const currentDate = date || state.demo.defaultDate;
|
||||||
|
const dates = [...new Set([state.demo.startDate, currentDate, ...state.purchases.map((item) => item.date), ...state.orders.map((item) => item.date), ...state.transfers.map((item) => item.date)])].sort();
|
||||||
|
return { version: state.version, demo: clone(state.demo), members: clone(state.members), dates, currentDate, opening: clone(state.opening), purchases: clone(state.purchases), orders: clone(state.orders), transfers: clone(state.transfers), report: buildReport(state, currentDate) };
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { DemoError, CHANNELS, MEMBERS, createSeed, applyCommand, buildReport, publicState, purchasePreview };
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
@charset "UTF-8";
|
||||||
|
:root{--ink:#233d35;--muted:#6d766f;--paper:#f6f5f0;--border:#dedfd6;--gold:#a97b35;--green:#254e40;--deep:#1c3d32;--white:#fffefa;--danger:#a03d31;--soft:#edf2ec;--gold-soft:#f5eedf;--shadow:0 10px 30px #213d3005}
|
||||||
|
*{box-sizing:border-box}html{scroll-behavior:smooth}body{margin:0;background:var(--paper);color:var(--ink);font-family:-apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;font-size:14px;line-height:1.65}body:has(dialog[open]){overflow:hidden}button,input,select,textarea{font:inherit}button,a{touch-action:manipulation}button{border:1px solid var(--border);border-radius:7px;padding:10px 15px;cursor:pointer;background:var(--white);color:var(--ink);font-weight:600;transition:background .15s,border-color .15s}button:hover{border-color:#9cae9b;background:var(--soft)}button:focus-visible,a:focus-visible,summary:focus-visible{outline:3px solid #b4c7af;outline-offset:3px}button:disabled{opacity:.5;cursor:not-allowed}button.primary{background:var(--green);color:white;border-color:var(--green)}button.primary:hover{background:var(--deep)}button.text-button{background:transparent;border:0;padding:8px 4px;font-size:12px;font-weight:500}button.text-button:hover{color:var(--gold);background:transparent}button.compact{font-size:12px;padding:7px 11px}button.light{background:var(--white);color:var(--green);border-color:var(--white)}a{color:var(--green)}input,select,textarea{width:100%;min-width:0;border:1px solid #cfd5cc;border-radius:6px;padding:10px 11px;background:white;color:#26382f;min-height:43px}input:focus,select:focus,textarea:focus{outline:2px solid #b3c8ba;outline-offset:1px}input:disabled,select:disabled{background:#f1f2ec;color:var(--muted)}input[type=number]{font-variant-numeric:tabular-nums}label{display:block;color:#59675e;font-size:12px;min-width:0}label>input,label>select,label>textarea{margin-top:6px;font-size:14px}h1,h2,h3,p{margin-top:0}h1{font-size:clamp(23px,2.5vw,30px);line-height:1.4;font-weight:650;margin-bottom:0;letter-spacing:.5px}h2{font-size:19px;font-weight:650;margin-bottom:12px}h3{font-size:15px;margin-bottom:10px}.muted{color:var(--muted)}.small{font-size:12px}.eyebrow{font-size:11px;letter-spacing:1.4px;color:var(--gold);font-weight:650;margin-bottom:7px}.money{font-variant-numeric:tabular-nums;letter-spacing:-.2px}.nowrap{white-space:nowrap}[hidden]{display:none!important}
|
||||||
|
.app-header{min-height:96px;background:var(--white);border-bottom:1px solid var(--border);padding:20px 4vw;display:flex;justify-content:space-between;align-items:center;gap:20px}.brand{display:flex;align-items:center;gap:15px;min-width:0;text-decoration:none}.brand-mark{display:grid;place-items:center;flex:0 0 44px;background:var(--green);color:#e7dcc2;width:44px;height:44px;font-size:24px;border-radius:11px;font-family:serif}.brand strong{font-size:19px;font-weight:650;letter-spacing:1px}.brand small{display:block;font-size:11px;color:var(--muted);letter-spacing:.5px;margin-top:2px}.brand-dot{color:#ac986b}.badge{display:inline-block;background:#e9efe7;color:#446250;padding:5px 10px;border-radius:5px;font-size:11px;white-space:nowrap}.badge.gold{background:var(--gold-soft);color:#8b692f}.demo-notice{padding:9px 4vw;background:#eeeadf;font-size:12px;color:#796a4d;display:flex;gap:9px;align-items:center}.notice-dot{height:5px;width:5px;border-radius:50%;background:#ae894d;flex-shrink:0}main{width:100%;max-width:1480px;padding:24px 4vw 45px;margin:auto;min-height:70vh}.toolbar{display:flex;align-items:end;gap:24px;flex-wrap:wrap}.date-control{width:164px;flex-shrink:0}.date-control input{padding:8px 10px;min-height:42px}.view-control{min-width:0}.control-label{display:block;font-size:12px;color:#59675e;margin-bottom:6px}.segmented{display:flex;border:1px solid var(--border);padding:3px;background:#eeefe8;border-radius:8px;gap:3px}.segmented button{font-size:12px;font-weight:500;border:0;background:transparent;padding:8px 14px;min-height:34px;white-space:nowrap}.segmented button.active{background:var(--green);color:white;box-shadow:0 2px 3px #254e401a}.toolbar-actions{display:flex;gap:18px;align-items:center;margin-left:auto;padding-bottom:3px}.view-disclaimer{font-size:11px;color:#8d9286;margin:10px 0 26px}.page-heading{display:flex;justify-content:space-between;align-items:center;gap:20px;margin-bottom:23px;flex-wrap:wrap}.actions{display:flex;gap:8px;flex-wrap:wrap}.actions button{font-size:12px}.scenario-note{border:1px solid #ddd1b1;border-radius:8px;background:#f5efdf;color:#7c6233;font-size:12px;padding:12px 16px;margin:0 0 20px}.panel{min-width:0;border:1px solid var(--border);background:var(--white);border-radius:11px;padding:24px;margin-bottom:20px;box-shadow:var(--shadow)}.panel-heading{display:flex;justify-content:space-between;align-items:center;gap:16px;flex-wrap:wrap;margin-bottom:20px}.panel-heading h2{margin:0}.panel-heading p{font-size:12px;color:var(--muted);margin:4px 0 0}.panel-heading>.small{max-width:530px}.panel-section{padding-top:20px;margin-top:20px;border-top:1px solid var(--border)}.panel-section h3{font-size:13px}.empty{padding:22px 15px;background:#f4f5ed;color:var(--muted);border-radius:6px;font-size:12px;text-align:center}.empty p{margin:4px 0}.empty strong{color:var(--ink);font-size:14px}.loading-state{padding:55px 20px;text-align:center;color:var(--muted);font-size:13px}.page-error{display:flex;align-items:center;gap:15px;justify-content:space-between}.error{background:#fae8e2;color:#983f34;padding:12px 14px;border:1px solid #efd0c7;border-radius:7px;font-size:12px;margin:12px 0}.page-error button{font-size:12px;flex-shrink:0}.ok{color:#32694c}.danger-text{color:var(--danger)}
|
||||||
|
.settlement-hero{position:relative;border-radius:12px;background:var(--green);color:#fff;padding:25px 28px;margin-bottom:18px;overflow:hidden}.settlement-hero::after{content:"";position:absolute;width:200px;height:200px;border:1px solid #ffffff0c;border-radius:50%;right:-100px;top:-100px;pointer-events:none}.settlement-hero.is-settled{background:#355d4e}.hero-top{display:flex;align-items:center;justify-content:space-between;gap:24px;flex-wrap:wrap}.hero-heading{font-size:15px;letter-spacing:.3px;margin-bottom:6px;color:#dae5dc}.hero-amount{font-size:clamp(34px,4vw,46px);font-weight:600;line-height:1.25;letter-spacing:-1px;margin:0}.hero-amount .yen{font-size:23px;font-weight:400;margin-right:6px;vertical-align:4px}.hero-action{display:grid;gap:8px;justify-items:end}.hero-action small{font-size:11px;color:#c8d7c9}.hero-action button{padding:12px 20px;font-size:13px}.hero-foot{margin-top:19px;padding-top:15px;border-top:1px solid #ffffff25;color:#d4e0d4;font-size:12px}.hero-foot p{margin:0}.hero-foot details{margin:0}.hero-foot summary{font-weight:500;cursor:pointer;display:list-item;list-style-position:inside;line-height:1.8}.hero-foot .hero-formula{margin-top:9px;color:#f3f4e9;font-size:13px;overflow-wrap:anywhere}.hero-foot .relation-extra{color:#c8d6cb;margin-top:7px;font-size:11px}.hero-settled-label{display:inline-block;margin-bottom:7px;background:#ffffff17;color:#dce7da;padding:3px 8px;border-radius:4px;font-size:11px}.day-stats{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:13px;margin-bottom:20px}.stat{min-width:0;border:1px solid var(--border);border-radius:9px;background:var(--white);padding:17px 19px}.stat small{font-size:12px;color:var(--muted);display:block}.stat strong{font-size:25px;display:block;margin:5px 0 1px;line-height:1.45;font-weight:600;overflow-wrap:anywhere}.stat p{font-size:11px;color:#899082;margin:0}.stat.profit{border-color:#c6d1bf;background:#eef2e9}.stat.profit strong{color:var(--green)}.income-breakdown{display:flex;gap:10px 24px;flex-wrap:wrap;font-size:12px;color:#61715f;margin:-5px 0 18px}.income-breakdown>span{display:flex;align-items:center;gap:7px}.income-breakdown b{font-weight:600;color:var(--ink)}.formula-box{padding:14px 17px;border:1px solid #ded7c3;border-radius:7px;background:#f5f1e6;color:#77613d;line-height:1.9;font-size:13px}.formula-box p{margin:0}.formula-box strong{font-weight:650;color:#5c4c33}.funds-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:0;margin:0 -24px}.fund-item{min-width:0;border-right:1px solid var(--border);padding:0 24px}.fund-item:last-child{border-right:0}.fund-item>span{display:block;color:var(--muted);font-size:12px}.fund-item>strong{font-size:27px;display:block;margin-top:5px;font-weight:600;overflow-wrap:anywhere}.fund-item>small{display:block;color:#899082;font-size:11px;margin-top:4px}.fund-item.final strong{color:var(--green)}.cash-trail{display:flex;gap:10px 21px;align-items:center;flex-wrap:wrap;font-size:12px;color:#71816b;margin:22px 0 0;padding:14px 16px;border-radius:6px;background:#f1f4ed}.cash-trail strong{font-weight:600;color:#31543e}.cash-trail .check-result{margin-left:auto}.fund-clarification{font-size:12px;margin:15px 0 0;color:var(--muted)}.member-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:14px}.member-card{min-width:0;border:1px solid var(--border);padding:20px;border-radius:8px;background:#fafaf5}.member-title{display:flex;justify-content:space-between;align-items:center;gap:8px;margin-bottom:18px}.member-title h3{margin:0;font-size:16px}.member-title button{font-size:11px;padding:5px 8px}.member-main{font-size:26px;font-weight:600;display:block;margin:4px 0 15px}.member-card .small{font-size:11px}.mini-rows{display:grid;gap:8px}.mini-row{display:flex;justify-content:space-between;gap:12px;flex-wrap:wrap;font-size:12px}.mini-row span{color:var(--muted)}.mini-row b{font-weight:500}.mini-row.emphasized{border-top:1px solid var(--border);padding-top:10px;margin-top:3px}.mini-row.emphasized b{font-weight:650;color:var(--green)}
|
||||||
|
.relation-list{display:grid;gap:12px}.relation-card{border:1px solid #d9dfd1;border-radius:8px;padding:18px 20px;background:#fcfcf6}.relation-card.settled{background:#f6f7f1;border-color:#e1e4d9}.relation-top{display:flex;align-items:center;justify-content:space-between;gap:15px;flex-wrap:wrap;margin-bottom:15px}.relation-top h3{font-size:14px;font-weight:600;margin:0}.relation-arrow{color:#a39779;padding:0 9px;font-weight:400}.relation-top .status{font-size:11px;color:#47714e;display:flex;align-items:center;gap:7px}.status-dot{display:inline-block;width:6px;height:6px;border-radius:50%;background:#77967b}.relation-amounts{display:grid;grid-template-columns:repeat(4,minmax(0,1fr)) auto;align-items:center;gap:15px}.relation-amounts>div{min-width:0}.relation-amounts span{display:block;font-size:11px;color:var(--muted)}.relation-amounts strong{display:block;font-size:20px;font-weight:500;overflow-wrap:anywhere}.relation-amounts .due strong{color:#8e632c;font-weight:650}.relation-amounts button{font-size:12px;padding:9px 12px}.relation-amounts button:disabled{cursor:default}.relation-formula{font-size:12px;color:#7e7c68;margin:14px 0 0;border-top:1px solid #e6e6d9;padding-top:11px;overflow-wrap:anywhere}.relation-history{margin:11px 0 0;font-size:12px;color:var(--muted)}.relation-history summary{cursor:pointer;color:#687464}.transfer-entry{display:flex;justify-content:space-between;gap:12px;flex-wrap:wrap;font-size:11px;padding:7px 0;border-bottom:1px solid #e7e9df}.transfer-entry:last-child{border-bottom:0}.transfer-entry strong{font-size:12px;font-weight:500;color:var(--ink)}
|
||||||
|
.pool-totals{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:16px 25px;margin-bottom:20px}.pool-total{min-width:0;padding:0 0 0 18px;border-left:3px solid #bca169}.pool-total span{font-size:12px;color:var(--muted)}.pool-total strong{display:block;font-size:30px;line-height:1.45;margin-top:5px;font-weight:600;overflow-wrap:anywhere}.pool-total strong small{font-size:13px;font-weight:400;margin-left:4px}.pool-rule{margin:0;padding:12px 16px;border-radius:6px;background:var(--gold-soft);font-size:12px;color:#7f6537}.source-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px;margin-top:18px}.source-card{border:1px solid #e0e3d7;padding:14px 16px;border-radius:7px;background:#f7f8f0;min-width:0}.source-card h3{font-size:12px;margin:0 0 10px}.source-card .mini-row{font-size:11px}.source-card .mini-row b{font-size:12px}.source-explanation{font-size:11px;color:#7d846f;margin:10px 0 0}.pool-use-list{display:grid;gap:8px}.pool-use-row{display:flex;flex-wrap:wrap;gap:6px 18px;align-items:center;font-size:12px;padding:10px 12px;background:#f6f7ef;border-radius:5px}.pool-use-row b{font-weight:600}.pool-use-row .use-amount{margin-left:auto;color:#7b5a2e;font-weight:600}.pool-overview-label{font-size:11px;color:#919584;margin:15px 0 0}
|
||||||
|
.activity-tabs{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:17px}.activity-tabs button{font-size:12px;padding:7px 12px;border:1px solid #dce0d2;background:#f6f7f1;font-weight:500}.activity-tabs button.active{background:#e5eddf;border-color:#bdcbb3;color:var(--green);font-weight:600}.table-scroll{overflow-x:auto;width:100%;border:1px solid #e0e3d8;border-radius:7px;overscroll-behavior-x:contain}table{width:100%;border-collapse:collapse;font-size:12px}th{text-align:left;font-size:11px;color:var(--muted);font-weight:500;padding:11px 13px;border-bottom:1px solid var(--border);white-space:nowrap;background:#f5f6ef}td{padding:13px;border-bottom:1px solid #e8e9e1;vertical-align:top}tr:last-child td{border-bottom:0}td.number,th.number{text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap}td strong{font-weight:600}td small{display:block;font-size:11px;color:#858b7d;line-height:1.7}td .profit-number{color:var(--green)}.orders-table{min-width:900px}.purchases-table{min-width:650px}.transfers-table{min-width:500px}.activity-subtitle{font-size:11px;color:#818879;margin:-4px 0 14px}.order-formula{margin:7px 0 0;font-size:11px;color:#7c826f}.section-details{margin:18px 0 0}.section-details summary{font-size:12px;cursor:pointer;color:#65775e}.section-details p{font-size:12px;color:var(--muted);margin:10px 0 0;line-height:1.9}.bottom-note{font-size:11px;line-height:1.9;color:#8b9181;margin:28px 1px 0;max-width:900px}.app-footer{border-top:1px solid var(--border);padding:17px 4vw;color:#8e9588;font-size:11px;display:flex;gap:10px;justify-content:space-between;flex-wrap:wrap}.app-footer span{color:#a0a595}
|
||||||
|
dialog{border:1px solid var(--border);border-radius:14px;width:min(730px,calc(100vw - 32px));max-height:90vh;max-height:90dvh;padding:28px 30px;background:var(--paper);color:var(--ink);box-shadow:0 20px 80px #15291e40;overscroll-behavior:contain}dialog::backdrop{background:#182e2470;backdrop-filter:blur(3px)}.small-dialog{width:min(530px,calc(100vw - 32px))}.dialog-heading{display:flex;justify-content:space-between;align-items:flex-start;gap:18px;margin-bottom:12px}.dialog-heading h2{font-size:24px;margin:0;line-height:1.4}.dialog-heading .eyebrow{margin-bottom:5px}.close-button{font-size:24px;line-height:1;border:0;padding:3px 6px;color:#8a9586;background:transparent;min-height:30px}.close-button:hover{background:#e7ece2}.dialog-description{font-size:12px;line-height:1.9;color:var(--muted);margin:0 0 22px}.form-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px}.full-field{margin-top:17px}.unit-price-preview{display:flex;align-items:center;justify-content:space-between;gap:15px;background:#ebf0e4;border:1px solid #d4dfc9;padding:11px 14px;border-radius:6px;margin-top:16px;font-size:12px;color:#68775a}.unit-price-preview output{font-weight:600;color:#3d5c38;font-variant-numeric:tabular-nums}.form-actions{display:flex;align-items:center;justify-content:space-between;gap:15px;flex-wrap:wrap;margin-top:24px;padding-top:18px;border-top:1px solid var(--border)}.form-actions>span{font-size:11px;color:#8b9281}.form-actions button{font-size:13px}.form-note{font-size:12px;padding:12px 15px;border:1px solid #dfcfa8;background:var(--gold-soft);color:#7e6131;border-radius:6px;margin:18px 0 0}.form-footnote{font-size:11px;color:#8a907f;margin:17px 0 0;line-height:1.8}.inline-fields{padding:16px;border:1px solid var(--border);background:#eef0e6;border-radius:7px;margin-top:17px}.transfer-direction{font-size:17px;margin:20px 0 16px}.transfer-outstanding{display:flex;gap:20px;justify-content:space-between;align-items:center;border:1px solid #d7ddcd;background:#ebf0e4;padding:13px 16px;border-radius:7px;margin-bottom:22px}.transfer-outstanding>span{font-size:12px;color:#768064}.transfer-outstanding>strong{font-size:25px;font-weight:600;font-variant-numeric:tabular-nums}.form-error{margin:18px 0 0}#toast{position:fixed;bottom:22px;left:50%;transform:translateX(-50%);background:#253e34;color:white;padding:12px 22px;border-radius:8px;box-shadow:0 5px 25px #0002;z-index:2000;max-width:min(600px,90vw);font-size:13px;text-align:center}#toast.error-toast{background:#8b392f}
|
||||||
|
@media(min-width:1550px){main{padding-left:45px;padding-right:45px}}
|
||||||
|
@media(max-width:1100px){.toolbar{gap:16px}.toolbar-actions{gap:12px}.segmented button{padding:8px 10px}.day-stats{gap:10px}.stat{padding:15px}.stat strong{font-size:23px}.funds-grid{gap:18px 0;grid-template-columns:repeat(2,minmax(0,1fr))}.fund-item:nth-child(2){border-right:0}.member-card{padding:15px}.member-main{font-size:24px}.relation-amounts{gap:13px}.relation-amounts strong{font-size:19px}.pool-total strong{font-size:27px}}
|
||||||
|
@media(max-width:800px){.toolbar-actions{margin-left:0;flex:1 1 100%;justify-content:flex-end;padding-bottom:0;margin-top:-4px}.view-disclaimer{margin-top:7px;margin-bottom:23px}.page-heading{gap:15px}.settlement-hero{padding:23px}.panel{padding:21px}.funds-grid{margin:0 -21px}.fund-item{padding:0 21px}.member-grid{grid-template-columns:1fr}.member-card{padding:18px}.member-title{margin-bottom:12px}.member-main{display:inline-block;font-size:28px;margin-bottom:12px;margin-top:0}.member-card .mini-rows{grid-template-columns:repeat(2,minmax(0,1fr));gap:9px 25px}.member-card .mini-row.emphasized{grid-column:1/-1}.source-grid{grid-template-columns:1fr}.source-card{padding:15px}.source-card .mini-rows{grid-template-columns:repeat(3,minmax(0,1fr));gap:9px 20px}.source-card .mini-row{display:block}.source-card .mini-row b{display:block;margin-top:2px}.relation-amounts{grid-template-columns:repeat(4,minmax(0,1fr))}.relation-amounts>.relation-button{grid-column:1/-1;margin-top:2px}.relation-button button{width:100%}.pool-total strong{font-size:25px}.pool-total{padding-left:13px}.cash-trail .check-result{margin-left:0;flex:1 1 100%}}
|
||||||
|
@media(max-width:560px){body{font-size:13px}.app-header{padding:19px 16px;min-height:86px;gap:12px}.brand{gap:10px}.brand-mark{flex-basis:36px;width:36px;height:38px;border-radius:9px;font-size:21px}.brand strong{font-size:15px;letter-spacing:.2px}.brand small{font-size:9px;letter-spacing:0;margin-top:3px}.app-header>.badge{display:none}.demo-notice{padding:8px 16px;font-size:11px;gap:7px}main{padding:21px 15px 30px}.toolbar{gap:15px 12px;align-items:end}.date-control{width:146px}.date-control input{min-height:40px;padding:8px}.view-control{flex:1 1 100%;order:2}.toolbar-actions{flex:1 1 100px;order:1;margin:0;justify-content:flex-end;display:grid;gap:0;padding-bottom:1px;text-align:right}.toolbar-actions button{font-size:11px;padding:3px 0;text-align:right}.segmented{width:100%}.segmented button{flex:1;font-size:12px;padding:8px 5px}.view-disclaimer{font-size:10px;margin-top:9px;margin-bottom:22px}.page-heading{margin-bottom:18px}.page-heading .eyebrow{font-size:10px}h1{font-size:24px}.page-heading .actions{width:100%;gap:7px}.page-heading .actions button{font-size:11px;padding:8px 10px;flex:1;white-space:nowrap}.settlement-hero{padding:20px 18px;margin-bottom:13px}.hero-top{gap:17px}.hero-heading{font-size:13px}.hero-amount{font-size:39px}.hero-amount .yen{font-size:21px}.hero-action{width:100%;display:flex;align-items:center;justify-content:space-between;gap:13px}.hero-action button{padding:10px 14px;font-size:12px}.hero-action small{font-size:10px;max-width:132px}.hero-foot{margin-top:17px;padding-top:13px;font-size:11px}.hero-foot .hero-formula{font-size:12px}.day-stats{grid-template-columns:repeat(2,minmax(0,1fr));gap:9px;margin-bottom:17px}.stat{padding:14px 13px}.stat small{font-size:11px}.stat strong{font-size:24px;margin-top:3px}.stat p{font-size:10px}.panel{padding:18px 16px;margin-bottom:17px;border-radius:9px}.panel-heading{margin-bottom:17px;gap:9px}.panel-heading h2{font-size:17px}.panel-heading p,.panel-heading .small{font-size:11px}.income-breakdown{font-size:11px;gap:7px 14px}.formula-box{font-size:12px;padding:12px}.funds-grid{margin:0 -16px;gap:17px 0}.fund-item{padding:0 16px}.fund-item>span{font-size:11px}.fund-item>strong{font-size:24px}.fund-item>small{font-size:10px;line-height:1.7}.cash-trail{font-size:11px;padding:11px 12px;gap:8px}.fund-clarification{font-size:11px}.relation-card{padding:15px 13px}.relation-top{gap:8px;margin-bottom:15px}.relation-top h3{font-size:13px}.relation-top .status{font-size:10px}.relation-arrow{padding:0 5px}.relation-amounts{grid-template-columns:repeat(2,minmax(0,1fr));gap:12px 15px}.relation-amounts span{font-size:10px}.relation-amounts strong{font-size:22px}.relation-formula{font-size:11px;line-height:1.9;margin-top:12px}.relation-button button{font-size:11px}.pool-totals{grid-template-columns:1fr 1fr;gap:17px 12px;margin-bottom:18px}.pool-total:first-child{grid-column:1/-1}.pool-total strong{font-size:26px;margin-top:2px}.pool-total:first-child strong{font-size:31px}.pool-total span{font-size:11px}.pool-rule{font-size:11px;padding:11px 12px}.source-card .mini-rows{gap:9px}.source-card .mini-row{font-size:10px}.source-card .mini-row b{font-size:11px}.pool-use-row{font-size:11px;gap:5px 10px;padding:10px}.pool-use-row .use-amount{margin-left:0;flex-basis:100%}.activity-tabs{gap:6px;margin-bottom:14px}.activity-tabs button{font-size:11px;padding:6px 9px}.activity-subtitle{font-size:10px}.app-footer{padding:15px;font-size:10px;gap:3px}.bottom-note{margin-top:22px;font-size:10px}.page-error{align-items:flex-start;flex-wrap:wrap}dialog{width:calc(100vw - 24px);max-height:92dvh;padding:23px 18px;border-radius:12px}.small-dialog{width:calc(100vw - 24px)}.dialog-heading h2{font-size:22px}.dialog-description{font-size:11px;margin-bottom:18px}.form-grid{gap:14px 12px}label{font-size:11px}label>input,label>select{font-size:13px}.form-grid input,.form-grid select{padding:10px 8px}.unit-price-preview{font-size:11px;padding:10px 12px;flex-wrap:wrap;gap:4px}.form-actions>span{font-size:10px}.form-actions button{font-size:12px;padding:9px 13px}.form-note{font-size:11px;padding:11px 12px}.form-footnote{font-size:10px}.inline-fields{padding:12px}.transfer-outstanding>strong{font-size:24px}#toast{font-size:12px;padding:11px 17px;bottom:15px}}
|
||||||
|
@media(prefers-reduced-motion:reduce){html{scroll-behavior:auto}button{transition:none}}
|
||||||
|
|
||||||
|
/* 金额之外的正文也保持可读,说明只在需要时展开。 */
|
||||||
|
.day-stats{grid-template-columns:repeat(3,minmax(0,1fr))}
|
||||||
|
.check-field{display:flex;align-items:flex-start;gap:10px;font-size:14px;margin:15px 0 0}.check-field input{width:18px;min-height:18px;height:18px;flex-shrink:0;margin:3px 0 0;accent-color:var(--green)}
|
||||||
|
.control-label,.date-control,.segmented button,.toolbar-actions button,.actions button,.panel-heading p,.panel-heading>.small,.stat small,.stat p,.income-breakdown,.hero-heading,.hero-action button,.hero-action small,.hero-foot,.hero-foot .hero-formula,.hero-foot .relation-extra,.fund-item>span,.fund-item>small,.cash-trail,.fund-clarification,.member-title button,.member-card .small,.mini-row,.relation-top h3,.relation-top .status,.relation-amounts span,.relation-amounts button,.relation-formula,.relation-history,.transfer-entry,.pool-total span,.pool-rule,.source-card h3,.source-card .mini-row,.source-explanation,.pool-use-row,.pool-overview-label,.activity-tabs button,.activity-subtitle,.section-details summary,.section-details p,.dialog-description,.form-grid label,.full-field,.unit-price-preview,.form-actions>span,.form-actions button,.form-note,.form-footnote,.form-error,.error{font-size:14px}
|
||||||
|
.stat p{font-size:12px;margin-top:4px}.hero-action small{font-size:12px}.hero-foot .relation-extra{font-size:12px}.fund-item>small{font-size:12px}.view-disclaimer{font-size:12px}.table-scroll table{font-size:14px}.table-scroll th{font-size:13px}.table-scroll td small,.order-formula{font-size:12px}.direction-caption{font-size:12px!important;line-height:1.6;margin-top:2px}.cash-detail-rows{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px 25px;margin-top:16px}.source-card .mini-row b{font-size:14px}.form-grid input,.form-grid select{font-size:14px}.unit-price-preview{font-size:13px}.relation-history .transfer-entry{font-size:12px}.relation-history .transfer-entry strong{font-size:14px}.bottom-note{font-size:12px}.scenario-note{font-size:14px}.badge{font-size:12px}.panel-heading>.badge{flex-shrink:0}.hero-foot details{margin-top:5px}
|
||||||
|
@media(max-width:800px){.day-stats{grid-template-columns:repeat(3,minmax(0,1fr))}.source-card .mini-rows{grid-template-columns:1fr 1fr 1fr}.source-card .mini-row{font-size:12px}.source-card .mini-row b{font-size:14px}}
|
||||||
|
@media(max-width:560px){.day-stats{grid-template-columns:repeat(3,minmax(0,1fr));gap:7px}.stat{padding:13px 10px}.stat small{font-size:12px}.stat strong{font-size:clamp(18px,5.2vw,24px)}.stat p{font-size:10px;line-height:1.7}.date-control{font-size:12px}.toolbar-actions button{font-size:12px}.segmented button{font-size:14px}.actions button{font-size:12px}.view-disclaimer{font-size:11px}.hero-heading{font-size:14px}.hero-action small{font-size:12px;max-width:145px}.hero-foot,.hero-foot .hero-formula{font-size:13px}.hero-foot .relation-extra{font-size:12px}.fund-item>span{font-size:13px}.fund-item>small{font-size:12px}.cash-trail{font-size:13px}.fund-clarification{font-size:13px}.relation-top h3{font-size:14px}.relation-top .status{font-size:12px}.relation-amounts span{font-size:13px}.relation-formula{font-size:13px}.pool-total span,.pool-rule{font-size:13px}.source-card .mini-rows{grid-template-columns:1fr}.source-card .mini-row{display:flex;font-size:13px}.source-card .mini-row b{margin:0}.pool-use-row{font-size:13px}.activity-tabs button{font-size:13px}.panel-heading p{font-size:13px}.form-grid label,.full-field{font-size:13px}.form-actions>span,.form-footnote{font-size:12px}.dialog-description{font-size:13px}.unit-price-preview{font-size:12px}.cash-detail-rows{grid-template-columns:1fr}.bottom-note{font-size:12px}}
|
||||||
|
@media(max-width:560px){.day-stats{grid-template-columns:repeat(2,minmax(0,1fr))}.stat strong{font-size:23px;white-space:nowrap;overflow-wrap:normal}.stat.profit{grid-column:1/-1;display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:center;gap:3px 10px}.stat.profit strong{grid-column:2;grid-row:1/3;margin:0;font-size:28px}.stat.profit p{grid-column:1;margin:0}}
|
||||||
|
@media(max-width:380px){.stat strong{font-size:21px}.stat.profit strong{font-size:26px}}
|
||||||
|
|
||||||
|
.opening-banner{display:flex;align-items:center;gap:14px;flex-wrap:wrap;margin:0 0 18px;padding:14px 18px;border:1px solid #d9dfd7;border-radius:12px;background:#fff}.opening-banner small{color:#69756d}.income-details{padding:16px 18px;background:#fff;border-radius:12px;margin-bottom:18px}.income-details summary{font-weight:600;cursor:pointer}.owner-advance{background:#fff7e6}.mini-row.highlight{padding:12px;background:#fff1d6;border-radius:8px}.member-due{font-weight:700;color:#254e40}.income-details table{width:100%;min-width:550px}.income-details th,.income-details td{padding:12px;text-align:left}.income-details .number{text-align:right}.member-card .income-details{margin:12px 0 0;padding:10px 0}.settlement-hero .badge{white-space:nowrap}.cash-detail-rows .mini-row{display:flex;justify-content:space-between;gap:12px}.stat-income{text-align:left;cursor:pointer;width:100%;background:#fff;border:1px solid #d9dfd7}.stat-income:hover{border-color:#254e40}.stat-income:focus-visible{outline:3px solid #86ab98;outline-offset:3px}.member-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:16px}.member-card{min-width:0}@media(max-width:950px){.member-grid{grid-template-columns:1fr}}
|
||||||
@@ -0,0 +1,320 @@
|
|||||||
|
/* 独立演示页面:业务金额由接口返回,页面只负责录入、筛选与展示。 */
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
const 页面 = {
|
||||||
|
数据: null,
|
||||||
|
视角: 'assistant',
|
||||||
|
明细: 'orders',
|
||||||
|
日期: '2026-11-01',
|
||||||
|
载入序号: 0,
|
||||||
|
写入中: false,
|
||||||
|
重置模式: 'default',
|
||||||
|
单价序号: 0,
|
||||||
|
单价定时器: null,
|
||||||
|
提示定时器: null,
|
||||||
|
};
|
||||||
|
const $ = (选择器, 根 = document) => 根.querySelector(选择器);
|
||||||
|
const $$ = (选择器, 根 = document) => [...根.querySelectorAll(选择器)];
|
||||||
|
const 转义 = 值 => String(值 ?? '').replace(/[&<>"']/g, 字符 => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[字符]));
|
||||||
|
const 数字格式 = new Intl.NumberFormat('zh-CN', {minimumFractionDigits:2, maximumFractionDigits:2});
|
||||||
|
const 克重格式 = new Intl.NumberFormat('zh-CN', {minimumFractionDigits:3, maximumFractionDigits:3});
|
||||||
|
const 金额 = 分 => Number.isFinite(分) ? `¥${数字格式.format(分 / 100)}` : '—';
|
||||||
|
const 元输入 = 分 => Number.isFinite(分) ? (分 / 100).toFixed(2) : '';
|
||||||
|
const 克重 = 毫克 => Number.isFinite(毫克) ? 克重格式.format(毫克 / 1000) : '—';
|
||||||
|
const 单价 = 元 => Number.isFinite(元) ? `¥${数字格式.format(元)} / g` : '—';
|
||||||
|
const 渠道名 = 渠道 => ({wechat:'微信',alipay:'支付宝',bank:'银行卡',cash:'现金',credit_card:'信用卡'}[渠道] || 渠道 || '未注明');
|
||||||
|
const 成员名 = 编号 => 页面.数据?.members?.find(成员 => 成员.id === 编号)?.name || ({owner:'麦麦',assistant:'助理1',assistant2:'助理2'}[编号]) || '未注明';
|
||||||
|
const 本人 = () => 页面.数据?.report?.daily?.members?.find(成员 => 成员.member === 页面.视角);
|
||||||
|
const 是总览 = () => 页面.视角 === 'owner';
|
||||||
|
const 当日订单 = () => (页面.数据?.report?.orders || []).filter(订单 => 订单.date === 页面.日期 && (是总览() || 订单.member === 页面.视角));
|
||||||
|
const 相关订单 = () => (页面.数据?.report?.orders || []).filter(订单 => 是总览() || 订单.member === 页面.视角);
|
||||||
|
|
||||||
|
async function 请求(路径, 选项 = {}) {
|
||||||
|
let 响应;
|
||||||
|
try {
|
||||||
|
响应 = await fetch(路径, {cache:'no-store', ...选项, headers:{'Content-Type':'application/json', ...(选项.headers || {})}});
|
||||||
|
} catch (_) {
|
||||||
|
throw new Error('暂时连不上本机演示服务,请确认演示已启动后重试。');
|
||||||
|
}
|
||||||
|
let 结果;
|
||||||
|
try { 结果 = await 响应.json(); }
|
||||||
|
catch (_) { throw new Error('演示服务没有返回完整结果,请重试。'); }
|
||||||
|
if (!响应.ok || 结果.ok !== true) {
|
||||||
|
const 错误 = new Error(结果.error?.message || '这条记录没有保存,请检查输入后重试。');
|
||||||
|
错误.field = 结果.error?.field;
|
||||||
|
throw 错误;
|
||||||
|
}
|
||||||
|
return 结果.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
function 提示(文字, 错误 = false) {
|
||||||
|
clearTimeout(页面.提示定时器);
|
||||||
|
const 容器 = $('#toast');
|
||||||
|
容器.textContent = 文字;
|
||||||
|
容器.classList.toggle('error-toast', 错误);
|
||||||
|
容器.hidden = false;
|
||||||
|
页面.提示定时器 = setTimeout(() => { 容器.hidden = true; }, 4500);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function 载入(日期 = 页面.日期) {
|
||||||
|
const 序号 = ++页面.载入序号;
|
||||||
|
$('#load-error').hidden = true;
|
||||||
|
if (!页面.数据) $('#loading').hidden = false;
|
||||||
|
$('#report-date').disabled = true;
|
||||||
|
try {
|
||||||
|
const 数据 = await 请求(`/api/demo/state?date=${encodeURIComponent(日期)}`);
|
||||||
|
if (序号 !== 页面.载入序号) return;
|
||||||
|
页面.数据 = 数据;
|
||||||
|
页面.日期 = 数据.currentDate || 数据.report.date || 日期;
|
||||||
|
$('#report-date').value = 页面.日期;
|
||||||
|
渲染();
|
||||||
|
} catch (错误) {
|
||||||
|
if (序号 !== 页面.载入序号) return;
|
||||||
|
$('#load-error span').textContent = 错误.message;
|
||||||
|
$('#load-error').hidden = false;
|
||||||
|
if (页面.数据) $('#report-date').value = 页面.日期;
|
||||||
|
} finally {
|
||||||
|
if (序号 === 页面.载入序号) {
|
||||||
|
$('#loading').hidden = true;
|
||||||
|
$('#report-date').disabled = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function 渲染() {
|
||||||
|
const 数据 = 页面.数据;
|
||||||
|
if (!数据?.report) return;
|
||||||
|
$('#dashboard').hidden = false;
|
||||||
|
$('#view-tabs').innerHTML = 数据.members.map(成员 => `<button type="button" data-view="${转义(成员.id)}" class="${页面.视角 === 成员.id ? 'active' : ''}" aria-pressed="${页面.视角 === 成员.id}">${转义(成员.id === 'owner' ? '麦麦总览' : 成员.name)}</button>`).join('');
|
||||||
|
$('#day-caption').textContent = `${页面.日期} · ${是总览() ? '麦麦总览' : `${成员名(页面.视角)}的日结`}`;
|
||||||
|
$('#page-title').textContent = 是总览() ? '每个人的钱,沿同一张账对清。' : '今天赚多少,该转多少。';
|
||||||
|
const 说明 = $('#scenario-note');
|
||||||
|
说明.hidden = 数据.demo?.name !== 'complex';
|
||||||
|
说明.textContent = '复杂场景:含两人购料、信用卡代收和跨日余料。可切换 11 月 1 日、11 月 2 日,分别核对当天订单、收款与成本。';
|
||||||
|
渲染日结();
|
||||||
|
渲染资金();
|
||||||
|
渲染材料();
|
||||||
|
渲染明细();
|
||||||
|
}
|
||||||
|
|
||||||
|
function 统计卡(标题, 分, 注释, 类名 = '', 收入成员 = '') {
|
||||||
|
const 标签 = 收入成员 ? 'button' : 'div';
|
||||||
|
return `<${标签} class="stat ${类名} ${收入成员 ? 'stat-income' : ''}" ${收入成员 ? `type="button" data-income="${转义(收入成员)}" aria-label="查看收入客户与渠道明细"` : ''}><small>${转义(标题)}</small><strong class="money">${金额(分)}</strong><p>${转义(注释)}${收入成员 ? ' · 点击核对明细' : ''}</p></${标签}>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function 小行(标题, 分, 强调 = false) {
|
||||||
|
return `<div class="mini-row ${强调 ? 'highlight' : ''}"><span>${转义(标题)}</span><strong class="money">${金额(分)}</strong></div>`;
|
||||||
|
}
|
||||||
|
function 收款身份(项) {
|
||||||
|
return 项.collectionType === 'self' ? '本人收款' : 项.collectionType === 'owner' ? '麦麦代收' : `${成员名(项.collector)}代收(其他成员)`;
|
||||||
|
}
|
||||||
|
function 渲染收入明细(成员) {
|
||||||
|
return `<details class="income-details section-details" id="income-details-${成员.member}"><summary>归属订单收入 ${金额(成员.salesCents)} · 点击按客户和渠道核对</summary><p>只含 ${转义(页面.日期)} 归属${转义(成员.name)}的已收齐订单;归属收入包含代收,不等于本人账户到账。</p><div class="income-breakdown">${小行('本人收款',成员.selfCollectedCents)}${小行('麦麦代收',成员.ownerCollectedCents)}${小行('其他成员代收',成员.otherCollectedCents)}</div><div class="table-scroll"><table><thead><tr><th>客户订单</th><th>收款归类</th><th>实际渠道</th><th class="number">实收金额</th></tr></thead><tbody>${成员.incomeDetails.map(项 => `<tr><td>${转义(项.customer)}</td><td>${转义(收款身份(项))}</td><td>${转义(项.channelName)} · ${转义(项.collectorName)}</td><td class="number">${金额(项.amountCents)}</td></tr>`).join('') || '<tr><td colspan="4">当天没有本人订单收入。</td></tr>'}</tbody><tfoot><tr><td colspan="3">归属订单实收合计</td><td class="number">${金额(成员.salesCents)}</td></tr></tfoot></table></div><div class="cash-detail-rows">${成员.channelTotals.map(项 => 小行(`${项.label}合计(含代收)`,项.amountCents)).join('')}</div></details>`;
|
||||||
|
}
|
||||||
|
function 日报公式(成员) {
|
||||||
|
return `麦麦垫付成本 ${金额(成员.ownerAdvancedCents)} + 当天净利润 ${金额(成员.profitCents)} − 麦麦代收 ${金额(成员.ownerCollectedCents)}`;
|
||||||
|
}
|
||||||
|
function 渲染日结() {
|
||||||
|
const 报告 = 页面.数据.report.daily, 成员 = 本人(), 摘要 = 是总览() ? 报告.overview : 成员;
|
||||||
|
const 主标题 = 是总览() ? '当天全店净利润' : 成员.reviewRequired ? '当天应转金额待复核' : 成员.toOwnerCents < 0 ? '当天麦麦应返/核对' : '当天应转麦麦';
|
||||||
|
const 主金额 = 是总览() ? 摘要.profitCents : 成员.toOwnerCents;
|
||||||
|
$('#daily-summary').innerHTML = `${是总览() ? '' : `<div class="opening-banner">${转义(成员.name)} · 初期余额 <strong class="money">${金额(成员.openingCents)}</strong><small>初始周转金设置,仅作对账参考</small></div>`}<div class="day-stats">${统计卡(是总览() ? '当天归属订单收入' : '本人当天订单收入',摘要.salesCents,'已收齐订单实收合计,包含代收','',是总览() ? 'all' : 页面.视角)}${统计卡('当天订单成本',摘要.orderCostCents,'已用材料+工费等+刷卡手续费')}${统计卡('当天全部净利润',摘要.profitCents,'合并当天盈利和亏损订单','profit')}</div>${是总览() ? '' : 渲染收入明细(成员)}<div class="settlement-hero"><div class="hero-top"><div><div class="hero-heading">${转义(主标题)}</div><p class="hero-amount money">${主金额 === null ? '待复核' : 金额(是总览() ? 主金额 : Math.abs(主金额))}</p></div><span class="badge">仅 ${转义(页面.日期)}</span></div><div class="hero-foot"><p>${是总览() ? '当天全店收入减去当天订单成本。' : 日报公式(成员) + (成员.toOwnerCents === null ? ';含亏损订单,核实后再确定应转。' : ` = ${金额(成员.toOwnerCents)}`)}</p><p>只核对所选日,不累计历史待转,不记录或推断付款完成。未用材料不计本日偿还。${!是总览() && 成员.toOwnerCents < 0 ? '代收抵扣后为负,请核对麦麦应返金额;此处没有登记付款。' : ''}</p></div></div>${!是总览() && 成员.reviewRequired ? '<div class="error">当天包含亏损订单,净利润保留真实金额;应转待复核,不自动反向补利润。</div>' : ''}`;
|
||||||
|
}
|
||||||
|
function 渲染成本明细(成员) {
|
||||||
|
return `<section class="panel"><div class="panel-heading"><div><h2>${转义(成员.name)}当天订单成本</h2><p>只含本人当天订单;麦麦垫付按已耗用材料及实际费用归属计算。</p></div><strong class="money">${金额(成员.orderCostCents)}</strong></div><div class="cash-detail-rows">${成员.costsByPayer.map(项 => 小行(`${项.name}${项.member === 'owner' ? '垫付(应转构成)' : '支付'}`,项.amountCents,项.member === 'owner')).join('')}</div><details class="section-details"><summary>查看各订单的成本项目与付款人</summary><div class="table-scroll"><table><thead><tr><th>客户订单</th><th>成本项目</th><th>实际付款人</th><th class="number">金额</th></tr></thead><tbody>${成员.costDetails.map(项 => `<tr class="${项.payer === 'owner' ? 'owner-advance' : ''}"><td>${转义(项.customer)}</td><td>${转义(项.label)}</td><td>${转义(项.payerName)}${项.payer === 'owner' ? '垫付' : ''}</td><td class="number">${金额(项.amountCents)}</td></tr>`).join('') || '<tr><td colspan="4">当天没有订单成本。</td></tr>'}</tbody><tfoot><tr><td colspan="3">本人当天订单成本合计</td><td class="number">${金额(成员.orderCostCents)}</td></tr></tfoot></table></div></details>${成员.otherAdvancedCents ? '<p class="form-note">含其他成员代付成本,请按付款人明细单独核对。</p>' : ''}</section>`;
|
||||||
|
}
|
||||||
|
function 渲染资金() {
|
||||||
|
const 报告 = 页面.数据.report.daily;
|
||||||
|
if (!是总览()) { $('#member-summary').innerHTML = 渲染成本明细(本人()); return; }
|
||||||
|
$('#member-summary').innerHTML = `<div class="panel"><div class="panel-heading"><div><h2>各成员当天对账</h2><p>期初只作参考;收入、成本、净利润和应转均按所选日。</p></div></div><div class="member-grid">${报告.members.map(成员 => `<article class="member-card"><h3>${转义(成员.name)}</h3>${小行('初期余额',成员.openingCents)}${小行('当天归属收入',成员.salesCents)}${小行('本人收款',成员.selfCollectedCents)}${小行('麦麦代收',成员.ownerCollectedCents)}${小行('其他成员代收',成员.otherCollectedCents)}${小行('当天成本',成员.orderCostCents)}${小行('麦麦垫付成本',成员.ownerAdvancedCents,true)}${小行('当天净利润',成员.profitCents)}${成员.member === 'owner' ? '' : `<p class="member-due">${成员.reviewRequired ? '亏损待复核' : 成员.toOwnerCents < 0 ? '麦麦应返/核对 ' + 金额(-成员.toOwnerCents) : '当天应转麦麦 ' + 金额(成员.toOwnerCents)}</p><p class="small">${日报公式(成员)}</p>`}${渲染收入明细(成员)}</article>`).join('')}</div></div>${报告.members.map(成员 => 渲染成本明细(成员)).join('')}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function 渲染材料() {
|
||||||
|
const 池 = 页面.数据.report.materialPool;
|
||||||
|
const 我的订单 = 相关订单();
|
||||||
|
const 相关购料编号 = new Set(我的订单.flatMap(订单 => (订单.funding || []).map(项 => 项.purchaseId)));
|
||||||
|
const 付款来源 = (池.funding || []).filter(项 => 是总览() || 项.payer === 页面.视角 || 相关购料编号.has(项.purchaseId));
|
||||||
|
const 用料 = 我的订单.filter(订单 => 订单.date === 页面.日期 && 订单.materialSource !== 'direct' && (订单.funding || []).length);
|
||||||
|
$('#material-pool').innerHTML = `<div class="panel"><div class="panel-heading"><div><h2>材料还在,就继续留在池里。</h2><p>共享材料池 · 截至 ${转义(页面.日期)} 的余料状态</p></div><button type="button" class="compact" data-open="purchase-dialog">+ 新增购料</button></div><div class="pool-totals"><div class="pool-total"><span>所选日加权料价</span><strong class="money">${单价(池.weightedCostYuanPerGram)}</strong></div><div class="pool-total"><span>剩余克重</span><strong class="money">${克重(池.closingWeightMg)}<small>g</small></strong></div><div class="pool-total"><span>剩余材料价值</span><strong class="money">${金额(池.closingCostCents)}</strong></div></div><p class="pool-rule">未用的料不需要还款。订单用了谁出钱买的料,才向谁归还已用部分;自己买的未用料,仍计入自己的资金占用。</p><details class="section-details"><summary>查看付款来源余额与当日用料去向</summary>${!是总览() ? '<p class="pool-overview-label">材料池余料是共享库存;下方只列本人购料,以及本人订单用到的付款来源。</p>' : ''}${付款来源.length ? `<div class="source-grid">${付款来源.map(来源 => `<article class="source-card"><h3>${转义(成员名(来源.payer))}付款 · ${转义(来源.date)}</h3><div class="mini-rows">${小行('购料实付',来源.totalCents)}${小行('累计已用',来源.consumedCents)}${小行('未用余额',来源.remainingCents)}</div></article>`).join('')}</div>` : '<div class="empty">暂无与你有关的材料付款来源。</div>'}<div class="panel-section"><h3>当日用料的还款来源</h3>${用料.length ? `<div class="pool-use-list">${用料.flatMap(订单 => 订单.funding.map(来源 => `<div class="pool-use-row"><b>${转义(订单.customer || '客户')} · ${转义(成员名(订单.member))}的订单</b><span>使用${转义(成员名(来源.payer))}付款的材料</span><span class="use-amount">${来源.payer === 订单.member ? '自有料款,无需还给别人' : `向${转义(成员名(来源.payer))}归还`} ${金额(来源.amountCents)}</span></div>`)).join('')}</div>` : '<div class="empty">所选日暂无共用材料池用料。</div>'}</div></details></div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function 渲染明细() {
|
||||||
|
const 订单 = 当日订单();
|
||||||
|
const 购料 = (页面.数据.purchases || []).filter(记录 => 记录.date === 页面.日期 && (是总览() || 记录.payer === 页面.视角));
|
||||||
|
const 标签 = [{编号:'orders',标题:'销售订单',数量:订单.length},{编号:'purchases',标题:'购料记录',数量:购料.length}];
|
||||||
|
let 内容;
|
||||||
|
if (页面.明细 === 'purchases') 内容 = 渲染购料表(购料);
|
||||||
|
else { 页面.明细 = 'orders'; 内容 = 渲染订单表(订单); }
|
||||||
|
$('#activity').innerHTML = `<div class="panel"><div class="panel-heading"><div><h2>当日明细</h2><p>${是总览() ? '查看全部成员的当日记录。' : '只显示本人订单、本人购料。'}</p></div><span class="badge">${转义(页面.日期)}</span></div><div class="activity-tabs" role="group" aria-label="选择明细类型">${标签.map(项 => `<button type="button" data-activity="${项.编号}" class="${页面.明细 === 项.编号 ? 'active' : ''}" aria-pressed="${页面.明细 === 项.编号}">${项.标题} <span>${项.数量}</span></button>`).join('')}</div>${内容}</div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function 渲染订单表(列表) {
|
||||||
|
if (!列表.length) return '<div class="empty"><strong>这一天还没有销售记录</strong><p>只有已交付、已收齐的普通销售进入这份日结。</p></div>';
|
||||||
|
return `<p class="activity-subtitle">材料成本来自所选日料池加权成本;单独购料按该笔实付计算。</p><div class="table-scroll" tabindex="0" aria-label="销售订单明细,可横向滚动"><table class="orders-table"><thead><tr><th>客户 / 成员</th><th class="number">克重</th><th class="number">销售实收</th><th>实际收款</th><th class="number">材料成本</th><th class="number">工费等 / 刷卡费</th><th class="number">订单利润</th></tr></thead><tbody>${列表.map(订单 => `<tr><td><strong>${转义(订单.customer)}</strong><small>${转义(成员名(订单.member))}${订单.materialSource === 'direct' ? ' · 单独购料' : ''}</small></td><td class="number">${克重(订单.weightMg)}g</td><td class="number">${金额(订单.saleCents)}</td><td>${转义(渠道名(订单.channel))}<small>${转义(成员名(订单.collector))}${订单.collector === 订单.member ? '自收' : '代收'}</small></td><td class="number">${金额(订单.materialCostCents)}</td><td class="number">${金额(订单.expenseCents)}<small>${转义(成员名(订单.expensePayer))}支付${订单.cardFeeCents ? `;刷卡费 ${金额(订单.cardFeeCents)} 由麦麦支付` : ''}</small></td><td class="number"><strong class="profit-number">${金额(订单.profitCents)}</strong><small>${订单.reviewRequired ? '亏损待复核' : '销售减材料、费用及手续费'}</small></td></tr><tr class="order-formula-row"><td colspan="7"><p class="order-formula">${转义(订单.formula || '')}</p></td></tr>`).join('')}</tbody></table></div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function 渲染购料表(列表) {
|
||||||
|
if (!列表.length) return '<div class="empty">这一天没有本人购料记录。共享材料余额仍保留在上方。</div>';
|
||||||
|
return `<div class="table-scroll" tabindex="0" aria-label="购料明细,可横向滚动"><table class="purchases-table"><thead><tr><th>日期</th><th>付款人</th><th class="number">购料克重</th><th class="number">实付总额</th><th>备注</th></tr></thead><tbody>${列表.map(记录 => `<tr><td>${转义(记录.date)}</td><td>${转义(成员名(记录.payer))}</td><td class="number">${克重(记录.weightMg)}g</td><td class="number">${金额(记录.totalCents)}</td><td>${转义(记录.note || '—')}</td></tr>`).join('')}</tbody></table></div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function 填成员选项(表单) {
|
||||||
|
$$('select', 表单).filter(下拉 => ['payer','member','collector','expensePayer','directMaterialPayer'].includes(下拉.name)).forEach(下拉 => {
|
||||||
|
下拉.innerHTML = 页面.数据.members.map(成员 => `<option value="${转义(成员.id)}">${转义(成员.name)}</option>`).join('');
|
||||||
|
下拉.value = 页面.视角;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function 清空表单错误(表单) {
|
||||||
|
const 错误栏 = $('.form-error', 表单);
|
||||||
|
if (错误栏) { 错误栏.textContent = ''; 错误栏.hidden = true; }
|
||||||
|
$$('[aria-invalid]', 表单).forEach(字段 => 字段.removeAttribute('aria-invalid'));
|
||||||
|
}
|
||||||
|
|
||||||
|
function 打开表单(编号) {
|
||||||
|
if (页面.写入中 || !页面.数据) return;
|
||||||
|
const 弹窗 = $(`#${编号}`);
|
||||||
|
const 表单 = $('form', 弹窗);
|
||||||
|
表单.reset();
|
||||||
|
delete 表单.dataset.requestId;
|
||||||
|
清空表单错误(表单);
|
||||||
|
填成员选项(表单);
|
||||||
|
const 日期字段 = $('[name="date"]', 表单);
|
||||||
|
if (日期字段) 日期字段.value = 页面.日期;
|
||||||
|
if (编号 === 'purchase-dialog') { clearTimeout(页面.单价定时器); 页面.单价序号 += 1; $('#purchase-unit-price').textContent = '填入克重和总额后显示'; }
|
||||||
|
if (编号 === 'order-dialog') 更新销售字段();
|
||||||
|
if (编号 === 'opening-dialog') 更新期初();
|
||||||
|
弹窗.showModal();
|
||||||
|
}
|
||||||
|
|
||||||
|
function 更新销售字段() {
|
||||||
|
const 表单 = $('#order-form');
|
||||||
|
const 信用卡 = 表单.elements.channel.value === 'credit_card';
|
||||||
|
const 收款人 = 表单.elements.collector;
|
||||||
|
if (信用卡) 收款人.value = 'owner';
|
||||||
|
收款人.disabled = 信用卡;
|
||||||
|
$('#credit-card-note').hidden = !信用卡;
|
||||||
|
const 单独购料 = 表单.elements.materialSource.value === 'direct';
|
||||||
|
$('#direct-material-fields').hidden = !单独购料;
|
||||||
|
表单.elements.directMaterialCost.required = 单独购料;
|
||||||
|
}
|
||||||
|
|
||||||
|
function 更新期初() {
|
||||||
|
const 表单 = $('#opening-form');
|
||||||
|
const 期初 = (页面.数据.opening || []).find(项 => 项.member === 表单.elements.member.value);
|
||||||
|
表单.elements.amount.value = 元输入(期初?.amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
function 打开重置(复杂) {
|
||||||
|
if (页面.写入中) return;
|
||||||
|
页面.重置模式 = 复杂 ? 'complex' : 'default';
|
||||||
|
const 表单 = $('#reset-form');
|
||||||
|
清空表单错误(表单);
|
||||||
|
$('#reset-title').textContent = 复杂 ? '换一组复杂场景试算?' : '重新开始这次试算?';
|
||||||
|
$('#reset-description').textContent = 复杂 ? '将清空当前演示里的新增记录和示例记录,载入“两人购料、信用卡代收、次日余料”的虚构示例。' : '将清空当前演示里的新增记录和示例记录,恢复“助理1应转麦麦1800元”的最简示例。当前正式账目不受影响。';
|
||||||
|
$('#reset-confirm').textContent = 复杂 ? '清空并载入复杂场景' : '重置为最简示例';
|
||||||
|
$('#reset-dialog').showModal();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function 提交(表单, 路径, 参数, 成功文字) {
|
||||||
|
if (页面.写入中) return;
|
||||||
|
清空表单错误(表单);
|
||||||
|
页面.写入中 = true;
|
||||||
|
const 提交键 = $('button[type="submit"]', 表单);
|
||||||
|
const 原文字 = 提交键.textContent;
|
||||||
|
const 控件 = $$('button,input,select', 表单);
|
||||||
|
const 原禁用 = 控件.map(字段 => 字段.disabled);
|
||||||
|
控件.forEach(字段 => { 字段.disabled = true; });
|
||||||
|
提交键.textContent = '正在记录…';
|
||||||
|
try {
|
||||||
|
const 数据 = await 请求(路径, {method:'POST', body:JSON.stringify(参数)});
|
||||||
|
页面.数据 = 数据;
|
||||||
|
页面.日期 = 数据.currentDate || 数据.report.date || 页面.日期;
|
||||||
|
$('#report-date').value = 页面.日期;
|
||||||
|
// 使写入前尚未完成的读取失效,避免旧结果盖住新余额。
|
||||||
|
页面.载入序号 += 1;
|
||||||
|
渲染();
|
||||||
|
表单.closest('dialog').close();
|
||||||
|
提示(成功文字);
|
||||||
|
} catch (错误) {
|
||||||
|
const 错误栏 = $('.form-error', 表单);
|
||||||
|
错误栏.textContent = 错误.message;
|
||||||
|
错误栏.hidden = false;
|
||||||
|
const 字段 = 错误.field && 表单.elements.namedItem(错误.field);
|
||||||
|
if (字段?.setAttribute) 字段.setAttribute('aria-invalid', 'true');
|
||||||
|
错误栏.scrollIntoView({block:'nearest'});
|
||||||
|
} finally {
|
||||||
|
控件.forEach((字段, 序号) => { 字段.disabled = 原禁用[序号]; });
|
||||||
|
提交键.textContent = 原文字;
|
||||||
|
页面.写入中 = false;
|
||||||
|
$('#report-date').disabled = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function 表单参数(表单) { return Object.fromEntries(new FormData(表单).entries()); }
|
||||||
|
function 记录编号(表单) {
|
||||||
|
const 输入签名 = JSON.stringify([...new FormData(表单).entries()]);
|
||||||
|
if (!表单.dataset.requestId || 表单.dataset.requestSignature !== 输入签名) {
|
||||||
|
表单.dataset.requestId = typeof crypto.randomUUID === 'function' ? crypto.randomUUID() : `demo-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
||||||
|
表单.dataset.requestSignature = 输入签名;
|
||||||
|
}
|
||||||
|
return 表单.dataset.requestId;
|
||||||
|
}
|
||||||
|
|
||||||
|
function 安排单价预览() {
|
||||||
|
clearTimeout(页面.单价定时器);
|
||||||
|
const 表单 = $('#purchase-form');
|
||||||
|
const 克 = 表单.elements.grams.value;
|
||||||
|
const 元 = 表单.elements.total.value;
|
||||||
|
const 序号 = ++页面.单价序号;
|
||||||
|
const 输出 = $('#purchase-unit-price');
|
||||||
|
if (!克 || !元 || !表单.elements.grams.validity.valid || !表单.elements.total.validity.valid) {
|
||||||
|
输出.textContent = '填入有效克重和总额后显示';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
输出.textContent = '正在计算…';
|
||||||
|
页面.单价定时器 = setTimeout(async () => {
|
||||||
|
try {
|
||||||
|
const 结果 = await 请求(`/api/demo/purchase-preview?grams=${encodeURIComponent(克)}&total=${encodeURIComponent(元)}`);
|
||||||
|
if (序号 === 页面.单价序号) 输出.textContent = `${金额(结果.unitPriceCents)} / g`;
|
||||||
|
} catch (错误) {
|
||||||
|
if (序号 === 页面.单价序号) 输出.textContent = 错误.message;
|
||||||
|
}
|
||||||
|
}, 220);
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener('click', 事件 => {
|
||||||
|
const 按钮 = 事件.target.closest('button');
|
||||||
|
if (!按钮) return;
|
||||||
|
if (按钮.dataset.income) {
|
||||||
|
const 明细 = 按钮.dataset.income === 'all' ? $$('.income-details') : [$('#income-details-' + 按钮.dataset.income)].filter(Boolean);
|
||||||
|
明细.forEach(项 => { 项.open = true; });
|
||||||
|
明细[0]?.scrollIntoView?.({behavior:'smooth',block:'start'});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (按钮.hasAttribute('data-close')) { if (!页面.写入中) 按钮.closest('dialog').close(); return; }
|
||||||
|
if (按钮.dataset.view) { 页面.视角 = 按钮.dataset.view; 渲染(); return; }
|
||||||
|
if (按钮.dataset.open) { 打开表单(按钮.dataset.open); return; }
|
||||||
|
if (按钮.dataset.activity) { 页面.明细 = 按钮.dataset.activity; 渲染明细(); }
|
||||||
|
});
|
||||||
|
$('#report-date').addEventListener('change', 事件 => { if (事件.target.value) 载入(事件.target.value); });
|
||||||
|
$('#retry-load').addEventListener('click', () => 载入());
|
||||||
|
$('#reset-demo').addEventListener('click', () => 打开重置(false));
|
||||||
|
$('#complex-scenario').addEventListener('click', () => 打开重置(true));
|
||||||
|
$('#purchase-form').addEventListener('input', 事件 => { if (['grams','total'].includes(事件.target.name)) 安排单价预览(); });
|
||||||
|
$('#order-form').addEventListener('change', 事件 => {
|
||||||
|
if (事件.target.name === 'member') {
|
||||||
|
$('#order-form').elements.collector.value = 事件.target.value;
|
||||||
|
$('#order-form').elements.expensePayer.value = 事件.target.value;
|
||||||
|
$('#order-form').elements.directMaterialPayer.value = 事件.target.value;
|
||||||
|
}
|
||||||
|
if (['member','channel','materialSource'].includes(事件.target.name)) 更新销售字段();
|
||||||
|
});
|
||||||
|
$('#opening-form [name="member"]').addEventListener('change', 更新期初);
|
||||||
|
$('#purchase-form').addEventListener('submit', 事件 => { 事件.preventDefault(); const 表单 = 事件.currentTarget; 提交(表单,'/api/demo/purchase',{...表单参数(表单),requestId:记录编号(表单)},'购料已记录,材料余额与日结已更新。'); });
|
||||||
|
$('#order-form').addEventListener('submit', 事件 => { 事件.preventDefault(); const 表单 = 事件.currentTarget; const 参数 = 表单参数(表单); 参数.allowLoss = 表单.elements.allowLoss.checked; if (参数.channel === 'credit_card') 参数.collector = 'owner'; if (参数.materialSource !== 'direct') { delete 参数.directMaterialCost; delete 参数.directMaterialPayer; } 提交(表单,'/api/demo/order',{...参数,requestId:记录编号(表单)},'销售已记录,收入、利润与应转金额已更新。'); });
|
||||||
|
$('#opening-form').addEventListener('submit', 事件 => { 事件.preventDefault(); const 表单 = 事件.currentTarget; 提交(表单,'/api/demo/opening',{...表单参数(表单),date:页面.数据.demo.startDate},'期初参考金额已更新。'); });
|
||||||
|
$('#reset-form').addEventListener('submit', 事件 => { 事件.preventDefault(); const 复杂 = 页面.重置模式 === 'complex'; 页面.视角 = 'assistant'; 页面.明细 = 'orders'; 提交(事件.currentTarget,复杂 ? '/api/demo/scenario' : '/api/demo/reset',复杂 ? {name:'complex'} : {},复杂 ? '已载入复杂场景,可切换日期和视角查看。' : '已恢复最简示例,可以重新试算。'); });
|
||||||
|
$$('dialog').forEach(弹窗 => { 弹窗.addEventListener('cancel', 事件 => { if (页面.写入中) 事件.preventDefault(); }); });
|
||||||
|
|
||||||
|
载入();
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<meta name="theme-color" content="#254e40">
|
||||||
|
<title>周转金日结 · 独立演示</title>
|
||||||
|
<link rel="stylesheet" href="/app.css">
|
||||||
|
<script src="/app.js" defer></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="toast" role="status" aria-live="polite" hidden></div>
|
||||||
|
<header class="app-header">
|
||||||
|
<a class="brand" href="/" aria-label="周转金日结演示首页">
|
||||||
|
<span class="brand-mark" aria-hidden="true">麦</span>
|
||||||
|
<span><strong>周转金日结 <span class="brand-dot">·</span> 独立演示</strong><small>把今天赚的、垫的、该转的,一起对清楚。</small></span>
|
||||||
|
</a>
|
||||||
|
<span class="badge">本机试算</span>
|
||||||
|
</header>
|
||||||
|
<div class="demo-notice"><span class="notice-dot" aria-hidden="true"></span>示例数据,仅用于试算;当前账目保持原规则。</div>
|
||||||
|
|
||||||
|
<main>
|
||||||
|
<section class="toolbar" aria-label="演示日期与视角">
|
||||||
|
<label class="date-control">查看日期<input id="report-date" type="date" value="2026-11-01" required></label>
|
||||||
|
<div class="view-control"><span class="control-label">演示视角</span><div id="view-tabs" class="segmented" role="group" aria-label="选择演示视角"></div></div>
|
||||||
|
<div class="toolbar-actions"><button type="button" class="text-button" id="complex-scenario">试试复杂场景<span aria-hidden="true"> ↗</span></button><button type="button" class="text-button muted" id="reset-demo">重置演示</button></div>
|
||||||
|
</section>
|
||||||
|
<p class="view-disclaimer">视角切换只演示页面效果,不代表真实登录或权限验证。</p>
|
||||||
|
|
||||||
|
<div id="load-error" class="error page-error" role="alert" hidden><span></span><button type="button" id="retry-load">重新加载</button></div>
|
||||||
|
<div id="loading" class="loading-state" role="status">正在整理示例账目…</div>
|
||||||
|
<div id="dashboard" hidden>
|
||||||
|
<div class="page-heading"><div><p id="day-caption" class="eyebrow"></p><h1 id="page-title">今天的钱,对清楚了。</h1></div><div class="actions"><button type="button" data-open="opening-dialog">设置期初</button><button type="button" data-open="purchase-dialog">+ 新增购料</button><button type="button" data-open="order-dialog" class="primary">+ 新增销售</button></div></div>
|
||||||
|
<div id="scenario-note" class="scenario-note" hidden></div>
|
||||||
|
<section id="daily-summary" aria-label="当日日结"></section>
|
||||||
|
<section id="member-summary" aria-label="成员资金"></section>
|
||||||
|
<section id="material-pool" aria-label="材料池"></section>
|
||||||
|
<section id="activity" aria-label="账目明细"></section>
|
||||||
|
<p class="bottom-note">这个演示只接收“已交付、已收齐”的普通销售。只核对所选日,不登记转账或推断已经付款。</p>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
<footer class="app-footer">麦麦珠宝 · 周转金日结演示 <span>独立示例空间,与当前正式账目分开。</span></footer>
|
||||||
|
|
||||||
|
<dialog id="purchase-dialog" aria-labelledby="purchase-title">
|
||||||
|
<form id="purchase-form">
|
||||||
|
<div class="dialog-heading"><div><p class="eyebrow">材料池</p><h2 id="purchase-title">新增购料</h2></div><button type="button" class="close-button" data-close aria-label="关闭新增购料">×</button></div>
|
||||||
|
<p class="dialog-description">谁付了钱,就记在谁的资金来源里。没用完的料继续留在材料池。</p>
|
||||||
|
<div class="form-grid"><label>购料日期<input name="date" type="date" required></label><label>付款人<select name="payer" required></select></label><label>购料克重(g)<input name="grams" type="number" inputmode="decimal" min="0.001" step="0.001" required placeholder="例如 10.000"></label><label>实付总额(元)<input name="total" type="number" inputmode="decimal" min="0.01" step="0.01" required placeholder="例如 10000.00"></label></div>
|
||||||
|
<div class="unit-price-preview"><span>自动购料单价</span><output id="purchase-unit-price">填入克重和总额后显示</output></div>
|
||||||
|
<label class="full-field">备注<input name="note" maxlength="200" placeholder="例如:补一批料,继续用于明天订单"></label>
|
||||||
|
<div class="form-error error" role="alert" hidden></div>
|
||||||
|
<div class="form-actions"><span>仅写入当前演示</span><button type="submit" class="primary">保存购料</button></div>
|
||||||
|
</form>
|
||||||
|
</dialog>
|
||||||
|
|
||||||
|
<dialog id="order-dialog" aria-labelledby="order-title">
|
||||||
|
<form id="order-form">
|
||||||
|
<div class="dialog-heading"><div><p class="eyebrow">已交付、已收齐</p><h2 id="order-title">新增销售</h2></div><button type="button" class="close-button" data-close aria-label="关闭新增销售">×</button></div>
|
||||||
|
<p class="dialog-description">只试算普通销售;每笔收入、材料和费用都记清实际收付款人。</p>
|
||||||
|
<div class="form-grid"><label>销售日期<input name="date" type="date" required></label><label>归属成员<select name="member" required></select></label><label>客户代号<input name="customer" maxlength="40" required placeholder="例如:小禾"></label><label>用料克重(g)<input name="grams" type="number" inputmode="decimal" min="0.001" step="0.001" required placeholder="例如 1.500"></label><label>销售实收(元)<input name="sale" type="number" inputmode="decimal" min="0.01" step="0.01" required placeholder="例如 2000.00"></label><label>收款渠道<select name="channel" required><option value="wechat">微信</option><option value="alipay">支付宝</option><option value="bank">银行卡</option><option value="cash">现金</option><option value="credit_card">信用卡</option></select></label><label>实际收款人<select name="collector" required></select></label><label>工费等支出(元)<input name="expenseAmount" type="number" inputmode="decimal" min="0" step="0.01" value="0.00" required></label><label>支出付款人<select name="expensePayer" required></select></label><label>材料来源<select name="materialSource"><option value="pool">共用材料池</option><option value="direct">订单单独购料</option></select></label></div>
|
||||||
|
<div id="direct-material-fields" class="inline-fields form-grid" hidden><label>单独购料金额(元)<input name="directMaterialCost" type="number" inputmode="decimal" min="0.01" step="0.01"></label><label>材料付款人<select name="directMaterialPayer"></select></label></div>
|
||||||
|
<p id="credit-card-note" class="form-note" hidden>信用卡统一由麦麦收款,6‰手续费由麦麦支付;费用计入这张订单。</p>
|
||||||
|
<p class="form-footnote">订单利润=销售实收-材料成本-工费等支出-信用卡手续费。</p>
|
||||||
|
<details class="section-details"><summary>亏损单的演示设置</summary><label class="check-field"><input name="allowLoss" type="checkbox">作为亏损待复核单登记,不自动向助理补利润。</label></details>
|
||||||
|
<div class="form-error error" role="alert" hidden></div>
|
||||||
|
<div class="form-actions"><span>保存后自动重算日结</span><button type="submit" class="primary">保存销售</button></div>
|
||||||
|
</form>
|
||||||
|
</dialog>
|
||||||
|
|
||||||
|
<dialog id="opening-dialog" aria-labelledby="opening-title" class="small-dialog">
|
||||||
|
<form id="opening-form">
|
||||||
|
<div class="dialog-heading"><div><p class="eyebrow">周转金</p><h2 id="opening-title">设置期初</h2></div><button type="button" class="close-button" data-close aria-label="关闭设置期初">×</button></div>
|
||||||
|
<p class="dialog-description">设置每个人的初期余额,作为每日对账参考。</p>
|
||||||
|
<div class="form-grid"><label>成员<select name="member" required></select></label><label>期初周转金(元)<input name="amount" type="number" inputmode="decimal" min="0" step="0.01" required></label></div>
|
||||||
|
<div class="form-error error" role="alert" hidden></div>
|
||||||
|
<div class="form-actions"><span>仅调整示例</span><button type="submit" class="primary">保存期初</button></div>
|
||||||
|
</form>
|
||||||
|
</dialog>
|
||||||
|
|
||||||
|
<dialog id="reset-dialog" aria-labelledby="reset-title" class="small-dialog">
|
||||||
|
<form id="reset-form">
|
||||||
|
<div class="dialog-heading"><div><p class="eyebrow">演示场景</p><h2 id="reset-title">重新开始这次试算?</h2></div><button type="button" class="close-button" data-close aria-label="取消重置">×</button></div>
|
||||||
|
<p id="reset-description" class="dialog-description"></p>
|
||||||
|
<div class="form-error error" role="alert" hidden></div>
|
||||||
|
<div class="form-actions"><button type="button" data-close>保留当前试算</button><button type="submit" class="primary" id="reset-confirm">重置演示</button></div>
|
||||||
|
</form>
|
||||||
|
</dialog>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
// 仅用于本地方案演示的虚构数据,不读取正式账本。
|
||||||
|
const MEMBERS = Object.freeze([
|
||||||
|
Object.freeze({ id: 'owner', name: '麦麦' }),
|
||||||
|
Object.freeze({ id: 'assistant', name: '助理1' }),
|
||||||
|
Object.freeze({ id: 'assistant2', name: '助理2' }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
function createSeed(name = 'default') {
|
||||||
|
if (!['default', 'complex'].includes(name)) throw new Error('未知演示场景。');
|
||||||
|
const state = {
|
||||||
|
version: 1,
|
||||||
|
demo: {
|
||||||
|
name,
|
||||||
|
title: '周转金+利润上交+按用料还款',
|
||||||
|
fictional: true,
|
||||||
|
startDate: '2026-11-01',
|
||||||
|
defaultDate: name === 'complex' ? '2026-11-02' : '2026-11-01',
|
||||||
|
},
|
||||||
|
members: MEMBERS.map((item) => ({ ...item })),
|
||||||
|
opening: MEMBERS.map((item) => ({ member: item.id, amount: 1000000, date: '2026-11-01' })),
|
||||||
|
purchases: [],
|
||||||
|
orders: [],
|
||||||
|
transfers: [],
|
||||||
|
requests: [],
|
||||||
|
nextSequence: 1,
|
||||||
|
};
|
||||||
|
function addPurchase(date, payer, weightMg, totalCents, note) {
|
||||||
|
const sequence = state.nextSequence++;
|
||||||
|
state.purchases.push({ id: `purchase-${sequence}`, sequence, date, payer, weightMg, totalCents, note });
|
||||||
|
}
|
||||||
|
function addOrder(values) {
|
||||||
|
const sequence = state.nextSequence++;
|
||||||
|
state.orders.push({
|
||||||
|
id: `order-${sequence}`, sequence, materialSource: 'pool', directMaterialCostCents: 0,
|
||||||
|
directMaterialPayer: values.member, allowLoss: false, note: '', ...values,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (name === 'default') {
|
||||||
|
addPurchase('2026-11-01', 'owner', 10000, 1000000, '虚构示例:麦麦购入10克共用料。');
|
||||||
|
addOrder({
|
||||||
|
date: '2026-11-01', member: 'assistant', customer: '示例客户小禾', weightMg: 1500,
|
||||||
|
saleCents: 200000, collector: 'assistant', channel: 'wechat', expenseCents: 20000,
|
||||||
|
expensePayer: 'assistant', note: '已交付、已收齐;尚未登记模拟转账。',
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
addPurchase('2026-11-01', 'owner', 2000, 200000, '虚构场景:麦麦先付2克材料款。');
|
||||||
|
addPurchase('2026-11-01', 'assistant', 8000, 880000, '虚构场景:助理1后付8克材料款,按付款金额FIFO还款。');
|
||||||
|
addOrder({
|
||||||
|
date: '2026-11-01', member: 'assistant', customer: '示例客户小圆', weightMg: 1500,
|
||||||
|
saleCents: 210000, collector: 'owner', channel: 'credit_card', expenseCents: 18000,
|
||||||
|
expensePayer: 'assistant2', note: '麦麦代收信用卡,助理2代付工费。',
|
||||||
|
});
|
||||||
|
addOrder({
|
||||||
|
date: '2026-11-01', member: 'assistant2', customer: '示例客户小桥', weightMg: 1000,
|
||||||
|
saleCents: 170000, collector: 'assistant', channel: 'alipay', expenseCents: 10000,
|
||||||
|
expensePayer: 'owner', note: '助理1代收支付宝;用料付款来源跨过麦麦余额后继续助理1。',
|
||||||
|
});
|
||||||
|
addPurchase('2026-11-02', 'assistant2', 2000, 260000, '次日新购2克,不改写昨日用料成本。');
|
||||||
|
addOrder({
|
||||||
|
date: '2026-11-02', member: 'assistant', customer: '示例客户小雨', weightMg: 1500,
|
||||||
|
saleCents: 210000, collector: 'assistant', channel: 'wechat', expenseCents: 12000,
|
||||||
|
expensePayer: 'assistant', note: '昨日余料与今日采购按今日加权,用料按原付款金额FIFO。',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { MEMBERS, createSeed };
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
// 独立本地演示:禁止导入正式应用、数据库或账号配置。
|
||||||
|
const http = require('node:http');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const path = require('node:path');
|
||||||
|
const os = require('node:os');
|
||||||
|
const { DemoError, createSeed, applyCommand, buildReport, publicState, purchasePreview } = require('./engine');
|
||||||
|
|
||||||
|
const DEFAULT_STATE_FILE = '/tmp/weiguang-capital-demo-20261028/state.json';
|
||||||
|
const DEFAULT_PORT = 3102;
|
||||||
|
const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.png': 'image/png' };
|
||||||
|
|
||||||
|
function validateStoredState(state) {
|
||||||
|
if (!state || state.version !== 1 || !state.demo || state.demo.fictional !== true || !['default', 'complex'].includes(state.demo.name)) throw new Error('演示状态格式不符,未读取或修改其他文件。');
|
||||||
|
for (const key of ['members', 'opening', 'purchases', 'orders', 'transfers', 'requests']) if (!Array.isArray(state[key])) throw new Error(`演示状态缺少${key}。`);
|
||||||
|
if (!Number.isSafeInteger(state.nextSequence) || state.nextSequence < 1) throw new Error('演示序号无效。');
|
||||||
|
if (state.opening.length !== 3 || state.opening.some((item) => !['owner', 'assistant', 'assistant2'].includes(item.member) || !Number.isSafeInteger(item.amount) || item.amount < 0 || item.date !== state.demo.startDate)) throw new Error('演示期初格式无效。');
|
||||||
|
for (const [key, amounts] of [['purchases', ['weightMg', 'totalCents']], ['orders', ['weightMg', 'saleCents', 'expenseCents', 'directMaterialCostCents']], ['transfers', ['amountCents']]]) {
|
||||||
|
for (const item of state[key]) {
|
||||||
|
if (typeof item.id !== 'string' || !Number.isSafeInteger(item.sequence) || !/^\d{4}-\d{2}-\d{2}$/.test(item.date)) throw new Error('演示交易格式无效。');
|
||||||
|
for (const amount of amounts) if (!Number.isSafeInteger(item[amount]) || item[amount] < 0) throw new Error('演示金额或重量格式无效。');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const lastDate = [...state.purchases, ...state.orders, ...state.transfers].reduce((latest, item) => item.date > latest ? item.date : latest, state.demo.startDate);
|
||||||
|
buildReport(state, lastDate);
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
function createStore(stateFile) {
|
||||||
|
const resolved = path.resolve(stateFile);
|
||||||
|
const temporaryRoot = path.resolve(os.tmpdir());
|
||||||
|
// 测试可另设临时文件;运行数据不能写进产品目录或正式账本。
|
||||||
|
if (!resolved.startsWith('/tmp/') && !resolved.startsWith(`${temporaryRoot}${path.sep}`)) throw new Error('演示持久文件必须显式位于系统临时目录。');
|
||||||
|
let state = fs.existsSync(resolved) ? validateStoredState(JSON.parse(fs.readFileSync(resolved, 'utf8'))) : createSeed();
|
||||||
|
function persist(next) {
|
||||||
|
fs.mkdirSync(path.dirname(resolved), { recursive: true, mode: 0o700 });
|
||||||
|
const temporaryFile = `${resolved}.${process.pid}.new`;
|
||||||
|
try {
|
||||||
|
fs.writeFileSync(temporaryFile, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
|
||||||
|
fs.renameSync(temporaryFile, resolved);
|
||||||
|
} finally {
|
||||||
|
if (fs.existsSync(temporaryFile)) fs.unlinkSync(temporaryFile);
|
||||||
|
}
|
||||||
|
state = next;
|
||||||
|
}
|
||||||
|
if (!fs.existsSync(resolved)) persist(state);
|
||||||
|
return {
|
||||||
|
get: () => state,
|
||||||
|
mutate(type, payload) {
|
||||||
|
const next = applyCommand(state, type, payload);
|
||||||
|
persist(next);
|
||||||
|
return state;
|
||||||
|
},
|
||||||
|
stateFile: resolved,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createDemoServer(options = {}) {
|
||||||
|
const store = createStore(options.stateFile || DEFAULT_STATE_FILE);
|
||||||
|
const publicDirectory = path.resolve(options.publicDirectory || path.join(__dirname, 'public'));
|
||||||
|
const server = http.createServer(async (req, res) => {
|
||||||
|
function headers(contentType) {
|
||||||
|
return {
|
||||||
|
'Content-Type': contentType,
|
||||||
|
'Cache-Control': 'no-store',
|
||||||
|
'X-Content-Type-Options': 'nosniff',
|
||||||
|
'Referrer-Policy': 'no-referrer',
|
||||||
|
'Content-Security-Policy': "default-src 'self'; connect-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'none'; base-uri 'none'; form-action 'self'",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
function json(status, data) {
|
||||||
|
res.writeHead(status, headers('application/json; charset=utf-8'));
|
||||||
|
res.end(JSON.stringify(data));
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const port = server.address().port;
|
||||||
|
const permittedHosts = new Set([`127.0.0.1:${port}`, `localhost:${port}`]);
|
||||||
|
if (!permittedHosts.has(req.headers.host)) throw new DemoError('INVALID_HOST', '本演示只接受本机地址。', undefined, 403);
|
||||||
|
if (req.headers.origin !== undefined && req.headers.origin !== `http://${req.headers.host}`) throw new DemoError('INVALID_ORIGIN', '本演示只接受本机同源请求。', undefined, 403);
|
||||||
|
const url = new URL(req.url, `http://${req.headers.host}`);
|
||||||
|
if (url.pathname.startsWith('/api/')) {
|
||||||
|
if (req.method === 'GET') {
|
||||||
|
const date = url.searchParams.get('date') || undefined;
|
||||||
|
if (url.pathname === '/api/demo/state') return json(200, { ok: true, data: publicState(store.get(), date) });
|
||||||
|
if (url.pathname === '/api/demo/report') return json(200, { ok: true, data: buildReport(store.get(), date) });
|
||||||
|
if (url.pathname === '/api/demo/purchase-preview') return json(200, { ok: true, data: purchasePreview({ grams: url.searchParams.get('grams'), total: url.searchParams.get('total') }) });
|
||||||
|
throw new DemoError('NOT_FOUND', '演示接口不存在。', undefined, 404);
|
||||||
|
}
|
||||||
|
if (req.method !== 'POST') throw new DemoError('METHOD_NOT_ALLOWED', '该演示接口只接受GET或POST。', undefined, 405);
|
||||||
|
const match = /^\/api\/demo\/(opening|purchase|order|transfer|reset|scenario)$/.exec(url.pathname);
|
||||||
|
if (!match) throw new DemoError('NOT_FOUND', '演示接口不存在。', undefined, 404);
|
||||||
|
if (!(req.headers['content-type'] || '').toLowerCase().startsWith('application/json')) throw new DemoError('JSON_REQUIRED', '请以JSON对象提交演示数据。', undefined, 415);
|
||||||
|
const chunks = [];
|
||||||
|
let bytes = 0;
|
||||||
|
for await (const chunk of req) {
|
||||||
|
bytes += chunk.length;
|
||||||
|
if (bytes > 65536) throw new DemoError('BODY_TOO_LARGE', '单次演示输入不能超过64KB。', undefined, 413);
|
||||||
|
chunks.push(chunk);
|
||||||
|
}
|
||||||
|
let payload;
|
||||||
|
try { payload = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { throw new DemoError('INVALID_JSON', 'JSON内容无效。'); }
|
||||||
|
// 同步原子落盘,保证并发请求不会丢单;验证全部通过后才替换持久状态。
|
||||||
|
const next = store.mutate(match[1], payload);
|
||||||
|
const selectedDate = match[1] === 'reset' || match[1] === 'scenario' ? next.demo.defaultDate : (payload.date || next.demo.defaultDate);
|
||||||
|
return json(200, { ok: true, data: publicState(next, selectedDate) });
|
||||||
|
}
|
||||||
|
if (!['GET', 'HEAD'].includes(req.method)) throw new DemoError('METHOD_NOT_ALLOWED', '静态文件只支持GET。', undefined, 405);
|
||||||
|
let requestedPath;
|
||||||
|
try { requestedPath = decodeURIComponent(url.pathname); } catch { throw new DemoError('INVALID_PATH', '文件路径无效。'); }
|
||||||
|
if (requestedPath.includes('\0') || requestedPath.includes('\\')) throw new DemoError('INVALID_PATH', '文件路径无效。');
|
||||||
|
const relative = requestedPath === '/' ? 'index.html' : requestedPath.replace(/^\/public\//, '').replace(/^\//, '');
|
||||||
|
const file = path.resolve(publicDirectory, relative);
|
||||||
|
if (!file.startsWith(`${publicDirectory}${path.sep}`) || !MIME[path.extname(file)]) throw new DemoError('NOT_FOUND', '演示文件不存在。', undefined, 404);
|
||||||
|
if (!fs.existsSync(file) || !fs.statSync(file).isFile() || !fs.realpathSync(file).startsWith(`${fs.realpathSync(publicDirectory)}${path.sep}`)) throw new DemoError('NOT_FOUND', '演示文件不存在。', undefined, 404);
|
||||||
|
const content = fs.readFileSync(file);
|
||||||
|
res.writeHead(200, { ...headers(MIME[path.extname(file)]), 'Content-Length': content.length });
|
||||||
|
res.end(req.method === 'HEAD' ? undefined : content);
|
||||||
|
} catch (error) {
|
||||||
|
if (res.headersSent) return res.destroy();
|
||||||
|
const known = error instanceof DemoError;
|
||||||
|
json(known ? error.status : 500, { ok: false, error: { code: known ? error.code : 'INTERNAL_ERROR', message: known ? error.message : '演示服务暂时无法完成操作,原状态未修改。', ...(known && error.field ? { field: error.field } : {}) } });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return server;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (require.main === module) {
|
||||||
|
try {
|
||||||
|
const server = createDemoServer();
|
||||||
|
server.on('error', (error) => {
|
||||||
|
process.stderr.write(error.code === 'EADDRINUSE' ? '3102端口已占用。若演示已经打开,请使用原窗口。\n' : `演示启动失败:${error.message}\n`);
|
||||||
|
process.exitCode = 1;
|
||||||
|
});
|
||||||
|
server.listen(DEFAULT_PORT, '127.0.0.1', () => {
|
||||||
|
process.stdout.write(`周转金方案本地演示:http://127.0.0.1:${DEFAULT_PORT}\n仅虚构数据:${DEFAULT_STATE_FILE}\n按Control+C关闭。\n`);
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
process.stderr.write(`演示启动失败:${error.message}\n`);
|
||||||
|
process.exitCode = 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { createDemoServer, DEFAULT_STATE_FILE, DEFAULT_PORT };
|
||||||
@@ -0,0 +1,240 @@
|
|||||||
|
"use strict";
|
||||||
|
|
||||||
|
// 独立审查:测试中的数值来自逐笔现金与资产推导,不复写引擎算法。
|
||||||
|
const test = require("node:test");
|
||||||
|
const assert = require("node:assert/strict");
|
||||||
|
const { createSeed, applyCommand, buildReport } = require("../engine.js");
|
||||||
|
|
||||||
|
const 日期一 = "2026-11-01";
|
||||||
|
const 日期二 = "2026-11-02";
|
||||||
|
const 日期三 = "2026-11-03";
|
||||||
|
|
||||||
|
function 空场景() {
|
||||||
|
const 状态 = createSeed("default");
|
||||||
|
状态.purchases = [];
|
||||||
|
状态.orders = [];
|
||||||
|
状态.transfers = [];
|
||||||
|
return 状态;
|
||||||
|
}
|
||||||
|
|
||||||
|
function 元(分) { return (分 / 100).toFixed(2); }
|
||||||
|
function 成员(报告, 名称) { return 报告.members.find((项) => 项.member === 名称); }
|
||||||
|
function 待转(报告, 付款人, 收款人) {
|
||||||
|
const 项 = 报告.settlements.find((结算) => 结算.from === 付款人 && 结算.to === 收款人);
|
||||||
|
return 项 ? 项.pendingCents : 0;
|
||||||
|
}
|
||||||
|
function 核对闭环(报告, 总资产) {
|
||||||
|
assert.equal(报告.reconciliation.differenceCents, 0, "总现金+未用材料应等于期初+累计利润");
|
||||||
|
assert.equal(报告.reconciliation.status, "ok");
|
||||||
|
if (总资产 !== undefined) assert.equal(报告.reconciliation.totalAssetsCents, 总资产);
|
||||||
|
for (const 项 of 报告.members) {
|
||||||
|
assert.equal(项.balanceCheck.differenceCents, 0, `${项.member} 的待结算资产必须闭环`);
|
||||||
|
assert.equal(
|
||||||
|
项.cashCents + 项.unusedMaterialCents - 项.pendingPayCents + 项.pendingReceiveCents,
|
||||||
|
项.expectedSettledAssetsCents,
|
||||||
|
`${项.member} 的现金、存料与往来必须闭环`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for (const 项 of 报告.settlements) {
|
||||||
|
assert.equal(
|
||||||
|
项.openingSignedCents + 项.newSignedCents - 项.transferredSignedCents,
|
||||||
|
项.pendingSignedCents,
|
||||||
|
`${项.pairId} 的期初+新增-实转必须等于待转`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function 全部结清(状态, 日期) {
|
||||||
|
for (const 项 of buildReport(状态, 日期).settlements) {
|
||||||
|
if (!项.pendingCents) continue;
|
||||||
|
状态 = applyCommand(状态, "transfer", {
|
||||||
|
date: 日期, from: 项.from, to: 项.to, amount: 元(项.pendingCents)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return 状态;
|
||||||
|
}
|
||||||
|
|
||||||
|
test("跨三日加权用料、资金 FIFO 与三人现金资产独立闭环", () => {
|
||||||
|
let 状态 = 空场景();
|
||||||
|
状态 = applyCommand(状态, "purchase", { date: 日期一, payer: "owner", grams: "10", total: "10000" });
|
||||||
|
状态 = applyCommand(状态, "purchase", { date: 日期一, payer: "assistant", grams: "10", total: "8000" });
|
||||||
|
状态 = applyCommand(状态, "order", {
|
||||||
|
date: 日期一, member: "assistant", customer: "虚构甲", grams: "2", sale: "2600",
|
||||||
|
collector: "assistant", channel: "cash", expenseAmount: "200", expensePayer: "assistant"
|
||||||
|
});
|
||||||
|
let 报告 = buildReport(状态, 日期一);
|
||||||
|
assert.equal(报告.orders[0].materialCostCents, 180000);
|
||||||
|
assert.equal(报告.orders[0].profitCents, 60000);
|
||||||
|
assert.equal(待转(报告, "assistant", "owner"), 240000);
|
||||||
|
状态 = 全部结清(状态, 日期一);
|
||||||
|
报告 = buildReport(状态, 日期一);
|
||||||
|
assert.equal(成员(报告, "assistant").cashCents, 200000);
|
||||||
|
assert.equal(成员(报告, "assistant").unusedMaterialCents, 800000);
|
||||||
|
核对闭环(报告, 3060000);
|
||||||
|
|
||||||
|
状态 = applyCommand(状态, "purchase", { date: 日期二, payer: "assistant2", grams: "5", total: "6000" });
|
||||||
|
状态 = applyCommand(状态, "order", {
|
||||||
|
date: 日期二, member: "assistant2", customer: "虚构乙", grams: "4", sale: "5000",
|
||||||
|
collector: "assistant2", channel: "bank", expenseAmount: "200", expensePayer: "assistant2"
|
||||||
|
});
|
||||||
|
报告 = buildReport(状态, 日期二);
|
||||||
|
const 当日单 = 报告.orders.find((项) => 项.date === 日期二);
|
||||||
|
assert.equal(当日单.materialCostCents, 386087);
|
||||||
|
assert.equal(当日单.profitCents, 93913);
|
||||||
|
assert.equal(待转(报告, "assistant2", "owner"), 480000);
|
||||||
|
assert.equal(报告.settlements.find((项) => 项.memberA === "owner" && 项.memberB === "assistant").newSignedCents, 0);
|
||||||
|
状态 = 全部结清(状态, 日期二);
|
||||||
|
核对闭环(buildReport(状态, 日期二), 3153913);
|
||||||
|
|
||||||
|
状态 = applyCommand(状态, "order", {
|
||||||
|
date: 日期三, member: "assistant2", customer: "虚构丙", grams: "6", sale: "7000",
|
||||||
|
collector: "assistant2", channel: "wechat", expenseAmount: "100", expensePayer: "owner"
|
||||||
|
});
|
||||||
|
报告 = buildReport(状态, 日期三);
|
||||||
|
const 第三日单 = 报告.orders.find((项) => 项.date === 日期三);
|
||||||
|
assert.equal(第三日单.materialCostCents, 579130);
|
||||||
|
assert.equal(第三日单.profitCents, 110870);
|
||||||
|
assert.deepEqual(第三日单.funding.map((项) => [项.payer, 项.amountCents]), [
|
||||||
|
["owner", 433913], ["assistant", 145217]
|
||||||
|
]);
|
||||||
|
assert.equal(待转(报告, "assistant2", "owner"), 554783);
|
||||||
|
assert.equal(待转(报告, "assistant2", "assistant"), 145217);
|
||||||
|
核对闭环(报告, 3264783);
|
||||||
|
状态 = 全部结清(状态, 日期三);
|
||||||
|
报告 = buildReport(状态, 日期三);
|
||||||
|
assert.equal(报告.overview.pendingTransferCents, 0);
|
||||||
|
assert.equal(成员(报告, "owner").cashCents, 1264783);
|
||||||
|
assert.equal(成员(报告, "assistant").cashCents, 345217);
|
||||||
|
assert.equal(成员(报告, "assistant").unusedMaterialCents, 654783);
|
||||||
|
assert.equal(成员(报告, "assistant2").cashCents, 400000);
|
||||||
|
assert.equal(成员(报告, "assistant2").unusedMaterialCents, 600000);
|
||||||
|
核对闭环(报告, 3264783);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("已结清后新增同日购料改价,保留实转并形成反向待返", () => {
|
||||||
|
let 状态 = 空场景();
|
||||||
|
状态 = applyCommand(状态, "purchase", { date: 日期一, payer: "owner", grams: "1", total: "1000" });
|
||||||
|
状态 = applyCommand(状态, "purchase", { date: 日期一, payer: "assistant", grams: "1", total: "1000" });
|
||||||
|
状态 = applyCommand(状态, "order", {
|
||||||
|
date: 日期一, member: "assistant", customer: "虚构改价", grams: "1", sale: "2000",
|
||||||
|
collector: "assistant", channel: "cash"
|
||||||
|
});
|
||||||
|
状态 = 全部结清(状态, 日期一);
|
||||||
|
assert.equal(状态.transfers.length, 1);
|
||||||
|
assert.equal(buildReport(状态, 日期一).overview.pendingTransferCents, 0);
|
||||||
|
|
||||||
|
状态 = applyCommand(状态, "purchase", { date: 日期一, payer: "assistant2", grams: "2", total: "4000" });
|
||||||
|
let 报告 = buildReport(状态, 日期一);
|
||||||
|
assert.equal(报告.orders[0].materialCostCents, 150000);
|
||||||
|
assert.equal(报告.orders[0].profitCents, 50000);
|
||||||
|
assert.equal(状态.transfers.length, 1, "改价不能删除历史真实转账");
|
||||||
|
assert.equal(待转(报告, "owner", "assistant"), 50000);
|
||||||
|
核对闭环(报告, 3050000);
|
||||||
|
|
||||||
|
状态 = applyCommand(状态, "transfer", { date: 日期二, from: "owner", to: "assistant", amount: "200" });
|
||||||
|
报告 = buildReport(状态, 日期二);
|
||||||
|
assert.equal(待转(报告, "owner", "assistant"), 30000);
|
||||||
|
const 结算 = 报告.settlements.find((项) => 项.memberA === "owner" && 项.memberB === "assistant");
|
||||||
|
assert.equal(结算.openingSignedCents, 50000);
|
||||||
|
assert.equal(结算.newSignedCents, 0);
|
||||||
|
assert.equal(结算.transferredSignedCents, 20000);
|
||||||
|
核对闭环(报告, 3050000);
|
||||||
|
状态 = 全部结清(状态, 日期三);
|
||||||
|
报告 = buildReport(状态, 日期三);
|
||||||
|
assert.equal(成员(报告, "owner").cashCents, 1050000);
|
||||||
|
assert.equal(成员(报告, "assistant").cashCents, 950000);
|
||||||
|
assert.equal(成员(报告, "assistant").unusedMaterialCents, 50000);
|
||||||
|
核对闭环(报告, 3050000);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("三人代收代付只按成员对抵扣,不静默循环轧差", () => {
|
||||||
|
let 状态 = 空场景();
|
||||||
|
状态 = applyCommand(状态, "order", {
|
||||||
|
date: 日期一, member: "assistant", customer: "虚构甲", grams: "1", sale: "2000",
|
||||||
|
collector: "assistant2", channel: "bank", materialSource: "direct",
|
||||||
|
directMaterialCost: "1000", directMaterialPayer: "owner", expenseAmount: "100", expensePayer: "assistant"
|
||||||
|
});
|
||||||
|
状态 = applyCommand(状态, "order", {
|
||||||
|
date: 日期一, member: "assistant2", customer: "虚构乙", grams: "1", sale: "1000",
|
||||||
|
collector: "owner", channel: "wechat", materialSource: "direct",
|
||||||
|
directMaterialCost: "600", directMaterialPayer: "assistant", expenseAmount: "100", expensePayer: "owner"
|
||||||
|
});
|
||||||
|
let 报告 = buildReport(状态, 日期一);
|
||||||
|
assert.equal(待转(报告, "assistant", "owner"), 190000);
|
||||||
|
assert.equal(待转(报告, "assistant2", "assistant"), 260000);
|
||||||
|
assert.equal(待转(报告, "owner", "assistant2"), 60000);
|
||||||
|
assert.equal(报告.overview.pendingTransferCents, 510000);
|
||||||
|
核对闭环(报告, 3120000);
|
||||||
|
状态 = 全部结清(状态, 日期二);
|
||||||
|
报告 = buildReport(状态, 日期二);
|
||||||
|
assert.equal(成员(报告, "owner").cashCents, 1120000);
|
||||||
|
assert.equal(成员(报告, "assistant").cashCents, 1000000);
|
||||||
|
assert.equal(成员(报告, "assistant2").cashCents, 1000000);
|
||||||
|
核对闭环(报告, 3120000);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("老板刷卡代收并付6‰费用,只向助理返还其已付工费", () => {
|
||||||
|
let 状态 = 空场景();
|
||||||
|
状态 = applyCommand(状态, "purchase", { date: 日期一, payer: "owner", grams: "10", total: "10000" });
|
||||||
|
状态 = applyCommand(状态, "order", {
|
||||||
|
date: 日期一, member: "assistant", customer: "虚构刷卡", grams: "1.5", sale: "2000",
|
||||||
|
collector: "owner", channel: "credit_card", expenseAmount: "200", expensePayer: "assistant"
|
||||||
|
});
|
||||||
|
let 报告 = buildReport(状态, 日期一);
|
||||||
|
assert.equal(报告.orders[0].cardFeeCents, 1200);
|
||||||
|
assert.equal(报告.orders[0].profitCents, 28800);
|
||||||
|
assert.equal(待转(报告, "owner", "assistant"), 20000);
|
||||||
|
核对闭环(报告, 3028800);
|
||||||
|
状态 = 全部结清(状态, 日期二);
|
||||||
|
报告 = buildReport(状态, 日期二);
|
||||||
|
assert.equal(成员(报告, "assistant").cashCents, 1000000);
|
||||||
|
assert.equal(成员(报告, "owner").cashCents, 178800);
|
||||||
|
assert.equal(成员(报告, "owner").unusedMaterialCents, 850000);
|
||||||
|
核对闭环(报告, 3028800);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("明确登记的亏损不自动让老板向助理补利润,承担差额明确待复核", () => {
|
||||||
|
let 状态 = 空场景();
|
||||||
|
const 订单 = {
|
||||||
|
date: 日期一, member: "assistant", customer: "虚构亏损", grams: "1", sale: "1000",
|
||||||
|
collector: "assistant", channel: "cash", materialSource: "direct",
|
||||||
|
directMaterialCost: "1200", directMaterialPayer: "assistant", expenseAmount: "100", expensePayer: "assistant"
|
||||||
|
};
|
||||||
|
const 原状态 = JSON.stringify(状态);
|
||||||
|
assert.throws(() => applyCommand(状态, "order", 订单));
|
||||||
|
assert.equal(JSON.stringify(状态), 原状态, "失败指令不得修改原状态");
|
||||||
|
状态 = applyCommand(状态, "order", { ...订单, allowLoss: true });
|
||||||
|
const 报告 = buildReport(状态, 日期一);
|
||||||
|
assert.equal(报告.orders[0].profitCents, -30000);
|
||||||
|
assert.equal(报告.orders[0].profitDueCents, 0);
|
||||||
|
assert.equal(报告.orders[0].reviewRequired, true);
|
||||||
|
assert.equal(报告.overview.pendingTransferCents, 0);
|
||||||
|
assert.equal(成员(报告, "assistant").cashCents, 970000);
|
||||||
|
assert.equal(成员(报告, "assistant").expectedSettledAssetsCents, 1000000);
|
||||||
|
assert.equal(成员(报告, "assistant").balanceCheck.differenceCents, -30000);
|
||||||
|
assert.equal(成员(报告, "assistant").balanceCheck.status, "review");
|
||||||
|
assert.equal(成员(报告, "owner").balanceCheck.differenceCents, 30000);
|
||||||
|
assert.equal(成员(报告, "owner").balanceCheck.status, "review");
|
||||||
|
assert.equal(报告.reconciliation.totalAssetsCents, 2970000);
|
||||||
|
assert.equal(报告.reconciliation.differenceCents, 0);
|
||||||
|
assert.equal(报告.reconciliation.status, "ok");
|
||||||
|
assert.equal(报告.members.reduce((合计, 项) => 合计 + 项.balanceCheck.differenceCents, 0), 0);
|
||||||
|
assert.ok(报告.warnings.some((项) => 项.code === "LOSS_REQUIRES_REVIEW"));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("旧日结清后次日正常代收反转往来,不捏造同日改价原因", () => {
|
||||||
|
let 状态 = createSeed("default");
|
||||||
|
状态 = applyCommand(状态, "transfer", { date: 日期一, from: "assistant", to: "owner", amount: "1800" });
|
||||||
|
状态 = applyCommand(状态, "order", {
|
||||||
|
date: 日期二, member: "assistant", customer: "虚构次日代收", grams: "1", sale: "1000",
|
||||||
|
collector: "owner", channel: "wechat", materialSource: "direct",
|
||||||
|
directMaterialCost: "500", directMaterialPayer: "assistant"
|
||||||
|
});
|
||||||
|
const 报告 = buildReport(状态, 日期二);
|
||||||
|
assert.equal(待转(报告, "owner", "assistant"), 50000);
|
||||||
|
const 结算 = 报告.settlements.find((项) => 项.pairId === "owner:assistant");
|
||||||
|
assert.equal(结算.openingSignedCents, 0);
|
||||||
|
assert.equal(结算.newSignedCents, 50000);
|
||||||
|
assert.ok(报告.warnings.every((项) => !项.message.includes("同日加权成本重算")), "正常代收不能被解释为同日购料改价");
|
||||||
|
核对闭环(报告, 3080000);
|
||||||
|
});
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
'use strict';
|
||||||
|
const test=require('node:test'),assert=require('node:assert/strict');
|
||||||
|
const {createSeed,applyCommand,buildReport}=require('../engine');
|
||||||
|
const D='2026-11-01',NEXT='2026-11-02';
|
||||||
|
const empty=()=>({...createSeed(),purchases:[],orders:[],transfers:[],requests:[],nextSequence:1});
|
||||||
|
const order=extra=>({date:D,member:'assistant',customer:'虚构日报客户',grams:'1',sale:'700',collector:'assistant',channel:'wechat',materialSource:'direct',directMaterialCost:'400',directMaterialPayer:'owner',expenseAmount:'100',expensePayer:'assistant',...extra});
|
||||||
|
const own=report=>report.daily.members.find(item=>item.member==='assistant');
|
||||||
|
|
||||||
|
test('日报1700收入拆客户渠道,1300成本含麦麦1000,净利润400应转1400且旧转账不改变日报',()=>{
|
||||||
|
let state=applyCommand(empty(),'order',order({customer:'虚构微信客户'}));state=applyCommand(state,'order',order({customer:'虚构支付宝客户',sale:'1000',channel:'alipay',directMaterialCost:'600',expenseAmount:'200'}));
|
||||||
|
const snapshot=JSON.stringify(state),daily=buildReport(state,D).daily,member=own({daily});
|
||||||
|
assert.equal(member.openingCents,1000000);assert.equal(member.salesCents,170000);assert.equal(member.orderCostCents,130000);assert.equal(member.profitCents,40000);assert.equal(member.ownerAdvancedCents,100000);assert.equal(member.selfPaidCents,30000);assert.equal(member.toOwnerCents,140000);assert.equal(member.reviewRequired,false);
|
||||||
|
assert.deepEqual(member.channelTotals.map(item=>[item.channel,item.amountCents]),[['wechat',70000],['alipay',100000]]);assert.deepEqual(member.incomeDetails.map(item=>[item.customer,item.amountCents]),[['虚构微信客户',70000],['虚构支付宝客户',100000]]);assert.equal(member.costDetails.reduce((n,item)=>n+item.amountCents,0),130000);
|
||||||
|
const transferred=applyCommand(state,'transfer',{date:D,from:'assistant',to:'owner',amount:'400'});assert.equal(transferred.transfers.length,1);assert.deepEqual(buildReport(transferred,D).daily,daily);assert.equal(JSON.stringify(state),snapshot);
|
||||||
|
const next=own(buildReport(transferred,NEXT));for(const key of ['salesCents','orderCostCents','profitCents','ownerAdvancedCents','toOwnerCents'])assert.equal(next[key],0,key);assert.equal(next.openingCents,1000000);assert.deepEqual(next.incomeDetails,[]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('信用卡麦麦代收抵扣、6‰成本归属准确,负应转仅表示核对方向,其他成员代收单列',()=>{
|
||||||
|
let state=applyCommand(empty(),'order',order({sale:'1000',channel:'credit_card',collector:'assistant2',directMaterialCost:'800'}));
|
||||||
|
let member=own(buildReport(state,D));assert.equal(member.salesCents,100000);assert.equal(member.ownerCollectedCents,100000);assert.equal(member.selfCollectedCents,0);assert.equal(member.otherCollectedCents,0);assert.equal(member.ownerAdvancedCents,80600);assert.equal(member.profitCents,9400);assert.equal(member.toOwnerCents,-10000);assert.equal(member.reviewRequired,false);assert.equal(state.transfers.length,0);
|
||||||
|
state=applyCommand(state,'order',order({customer:'虚构他人代收',collector:'assistant2',expenseAmount:'0'}));member=own(buildReport(state,D));assert.equal(member.otherCollectedCents,70000);assert.equal(member.incomeDetails[1].collectionType,'other');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('当天正负利润合并为真实净额,亏损单待复核,未用材料不算麦麦垫付偿还',()=>{
|
||||||
|
let state=applyCommand(empty(),'order',order({sale:'200',directMaterialCost:'100',expenseAmount:'0'}));state=applyCommand(state,'order',order({sale:'50',directMaterialCost:'80',expenseAmount:'0',allowLoss:true}));const member=own(buildReport(state,D));
|
||||||
|
assert.equal(member.profitCents,7000);assert.equal(member.reviewRequired,true);assert.equal(member.toOwnerCents,null);assert.equal(member.calculatedToOwnerCents,25000);assert.equal(state.transfers.length,0);
|
||||||
|
const original=buildReport(createSeed(),D),pool=own(original);assert.equal(pool.ownerAdvancedCents,150000);assert.equal(pool.toOwnerCents,180000);assert.equal(original.materialPool.closingCostCents,850000);assert.equal(pool.costDetails.filter(item=>item.kind==='material').reduce((n,item)=>n+item.amountCents,0),150000);
|
||||||
|
});
|
||||||
@@ -0,0 +1,211 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { createSeed, applyCommand, buildReport, publicState, purchasePreview, DemoError } = require('../engine');
|
||||||
|
|
||||||
|
const DATE = '2026-11-01';
|
||||||
|
function member(report, id) { return report.members.find((item) => item.member === id); }
|
||||||
|
function empty() {
|
||||||
|
return { ...createSeed(), purchases: [], orders: [], transfers: [], requests: [], nextSequence: 1 };
|
||||||
|
}
|
||||||
|
function sale(values = {}) {
|
||||||
|
return { date: DATE, member: 'assistant', customer: '虚构客户', grams: '1.5', sale: '2000', collector: 'assistant', channel: 'wechat', expenseAmount: '200', expensePayer: 'assistant', ...values };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('默认示例只形成1800待转,登记后助理现金10000;初始无虚假实转', () => {
|
||||||
|
const initial = createSeed();
|
||||||
|
const report = buildReport(initial, DATE);
|
||||||
|
assert.equal(initial.transfers.length, 0);
|
||||||
|
assert.equal(report.overview.materialCostCents, 150000);
|
||||||
|
assert.equal(report.overview.orderCostCents, 170000);
|
||||||
|
assert.equal(report.overview.profitCents, 30000);
|
||||||
|
assert.equal(member(report, 'assistant').pendingPayCents, 180000);
|
||||||
|
assert.equal(member(report, 'assistant').cashCents, 1180000);
|
||||||
|
assert.equal(member(report, 'assistant2').salesCents, 0);
|
||||||
|
const settled = applyCommand(initial, 'transfer', { date: DATE, from: 'assistant', to: 'owner', amount: '1800' });
|
||||||
|
const final = buildReport(settled, DATE);
|
||||||
|
assert.equal(member(final, 'assistant').cashCents, 1000000);
|
||||||
|
assert.equal(member(final, 'owner').cashCents, 180000);
|
||||||
|
assert.equal(final.materialPool.closingCostCents, 850000);
|
||||||
|
assert.equal(final.overview.pendingTransferCents, 0);
|
||||||
|
assert.equal(final.reconciliation.totalAssetsCents, 3030000);
|
||||||
|
assert.equal(initial.transfers.length, 0, '纯指令不得原地修改旧state');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('自己出资购料:只上交利润,结清后现金加未用料仍为期初', () => {
|
||||||
|
let state = empty();
|
||||||
|
state = applyCommand(state, 'purchase', { date: DATE, payer: 'assistant', grams: '10', total: '10000' });
|
||||||
|
state = applyCommand(state, 'order', sale());
|
||||||
|
const before = buildReport(state, DATE);
|
||||||
|
assert.equal(member(before, 'assistant').unusedMaterialCents, 850000);
|
||||||
|
assert.equal(member(before, 'assistant').pendingPayCents, 30000);
|
||||||
|
state = applyCommand(state, 'transfer', { date: DATE, from: 'assistant', to: 'owner', amount: '300' });
|
||||||
|
const person = member(buildReport(state, DATE), 'assistant');
|
||||||
|
assert.equal(person.cashCents, 150000);
|
||||||
|
assert.equal(person.cashPlusUnusedCents, 1000000);
|
||||||
|
assert.equal(person.balanceCheck.status, 'ok');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('本单自行配货不会重复扣共用池,跨成员材料代付形成成本往来', () => {
|
||||||
|
let state = empty();
|
||||||
|
state = applyCommand(state, 'order', sale({ materialSource: 'direct', directMaterialCost: '1500', directMaterialPayer: 'assistant2', collector: 'owner' }));
|
||||||
|
const report = buildReport(state, DATE);
|
||||||
|
assert.equal(report.materialPool.closingWeightMg, 0);
|
||||||
|
assert.equal(report.materialPool.closingCostCents, 0);
|
||||||
|
assert.equal(member(report, 'assistant2').cashCents, 850000);
|
||||||
|
assert.equal(member(report, 'assistant2').pendingReceiveCents, 150000);
|
||||||
|
assert.equal(member(report, 'assistant').pendingReceiveCents, 170000);
|
||||||
|
assert.equal(member(report, 'assistant').pendingPayCents, 150000);
|
||||||
|
assert.equal(member(report, 'assistant').projectedSettledCashCents, 1000000);
|
||||||
|
assert.deepEqual(member(report, 'assistant').dailyCollections, []);
|
||||||
|
assert.deepEqual(member(report, 'assistant').collectedByOthers, [{ member: 'owner', name: '麦麦', amountCents: 200000 }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('信用卡统一麦麦收款和付6‰:减利润并抵扣代收,不给助理虚增实收', () => {
|
||||||
|
let state = empty();
|
||||||
|
state = applyCommand(state, 'purchase', { date: DATE, payer: 'owner', grams: 10, total: 10000 });
|
||||||
|
state = applyCommand(state, 'order', sale({ channel: 'credit_card', collector: 'assistant2' }));
|
||||||
|
const report = buildReport(state, DATE);
|
||||||
|
assert.equal(report.orders[0].collector, 'owner');
|
||||||
|
assert.equal(report.orders[0].cardFeeCents, 1200);
|
||||||
|
assert.equal(report.orders[0].profitCents, 28800);
|
||||||
|
assert.equal(member(report, 'owner').cashCents, 198800);
|
||||||
|
assert.equal(member(report, 'assistant').collectedCents, 0);
|
||||||
|
assert.equal(member(report, 'assistant').pendingReceiveCents, 20000);
|
||||||
|
state = applyCommand(state, 'transfer', { date: DATE, from: 'owner', to: 'assistant', amount: 200 });
|
||||||
|
assert.equal(member(buildReport(state, DATE), 'assistant').cashCents, 1000000);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('三毫克一分钱:多单舍入精确消耗付款余款,不创造或丢失成本', () => {
|
||||||
|
let state = empty();
|
||||||
|
state = applyCommand(state, 'purchase', { date: DATE, payer: 'owner', grams: '0.003', total: '0.01' });
|
||||||
|
for (let i = 0; i < 3; i++) state = applyCommand(state, 'order', sale({ customer: `虚构微量${i}`, grams: '0.001', sale: '1', expenseAmount: 0 }));
|
||||||
|
const report = buildReport(state, DATE);
|
||||||
|
assert.deepEqual(report.orders.map((item) => item.materialCostCents), [0, 1, 0]);
|
||||||
|
assert.equal(report.materialPool.usedCostCents, 1);
|
||||||
|
assert.equal(report.materialPool.closingCostCents, 0);
|
||||||
|
assert.equal(report.materialPool.funding[0].remainingCents, 0);
|
||||||
|
assert.equal(report.reconciliation.differenceCents, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('每日利润不把旧日重复列入;期初未结结转并仅减本日实际转账', () => {
|
||||||
|
let state = createSeed();
|
||||||
|
state = applyCommand(state, 'transfer', { date: '2026-11-02', from: 'assistant', to: 'owner', amount: 500 });
|
||||||
|
const report = buildReport(state, '2026-11-02');
|
||||||
|
const person = member(report, 'assistant');
|
||||||
|
assert.equal(person.salesCents, 0);
|
||||||
|
assert.equal(person.profitCents, 0);
|
||||||
|
assert.equal(person.cumulativeProfitCents, 30000);
|
||||||
|
assert.equal(report.overview.orderCount, 0);
|
||||||
|
assert.equal(person.settlement.openingPayCents, 180000);
|
||||||
|
assert.equal(person.settlement.newPayCents, 0);
|
||||||
|
assert.equal(person.settlement.transferredOutCents, 50000);
|
||||||
|
assert.equal(person.settlement.pendingPayCents, 130000);
|
||||||
|
for (const pair of report.settlements) assert.equal(pair.openingSignedCents + pair.newSignedCents - pair.transferredSignedCents, pair.pendingSignedCents);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('跨日新购不重算旧日利润;查看旧日不包含未来现金', () => {
|
||||||
|
const initial = createSeed();
|
||||||
|
const earlier = buildReport(initial, DATE);
|
||||||
|
const state = applyCommand(initial, 'purchase', { date: '2026-11-02', payer: 'assistant2', grams: 5, total: 20000 });
|
||||||
|
assert.deepEqual(buildReport(state, DATE), earlier);
|
||||||
|
assert.equal(buildReport(state, '2026-11-02').orders[0].materialCostCents, 150000);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('已结清不得重复付,部分结清不得超付或反向付', () => {
|
||||||
|
let state = createSeed();
|
||||||
|
const prior = JSON.stringify(state);
|
||||||
|
for (const body of [{ from: 'assistant', to: 'owner', amount: 1800.01 }, { from: 'owner', to: 'assistant', amount: 1 }, { from: 'assistant', to: 'assistant', amount: 1 }]) {
|
||||||
|
assert.throws(() => applyCommand(state, 'transfer', { date: DATE, ...body }), DemoError);
|
||||||
|
assert.equal(JSON.stringify(state), prior);
|
||||||
|
}
|
||||||
|
state = applyCommand(state, 'transfer', { date: DATE, from: 'assistant', to: 'owner', amount: 1000 });
|
||||||
|
assert.throws(() => applyCommand(state, 'transfer', { date: DATE, from: 'assistant', to: 'owner', amount: 1000 }), /足额待转/);
|
||||||
|
state = applyCommand(state, 'transfer', { date: DATE, from: 'assistant', to: 'owner', amount: 800 });
|
||||||
|
assert.throws(() => applyCommand(state, 'transfer', { date: DATE, from: 'assistant', to: 'owner', amount: 1800 }), /足额待转/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('同一提交幂等键不会重复扣现金;改内容重用键拒绝', () => {
|
||||||
|
const payload = { date: DATE, from: 'assistant', to: 'owner', amount: 1800, idempotencyKey: 'transfer-check-1' };
|
||||||
|
const settled = applyCommand(createSeed(), 'transfer', payload);
|
||||||
|
assert.deepEqual(applyCommand(settled, 'transfer', payload), settled);
|
||||||
|
assert.throws(() => applyCommand(settled, 'transfer', { ...payload, amount: 10 }), /已用于不同内容/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('同日加购使旧单亏损:保留已转,标复核差额,不自动补利润', () => {
|
||||||
|
let state = createSeed();
|
||||||
|
state = applyCommand(state, 'transfer', { date: DATE, from: 'assistant', to: 'owner', amount: 1800 });
|
||||||
|
state = applyCommand(state, 'purchase', { date: DATE, payer: 'owner', grams: 1, total: 20000 });
|
||||||
|
const report = buildReport(state, DATE);
|
||||||
|
assert.equal(state.transfers.length, 1);
|
||||||
|
assert.ok(report.orders[0].profitCents < 0);
|
||||||
|
assert.equal(report.orders[0].profitDueCents, 0);
|
||||||
|
assert.equal(report.orders[0].reviewRequired, true);
|
||||||
|
assert.equal(member(report, 'assistant').balanceCheck.status, 'review');
|
||||||
|
assert.ok(report.warnings.some((item) => item.code === 'LOSS_REQUIRES_REVIEW'));
|
||||||
|
assert.equal(report.reconciliation.mathStatus, 'ok');
|
||||||
|
assert.equal(report.reconciliation.status, 'review');
|
||||||
|
assert.ok(report.warnings.some((item) => item.code === 'CASH_SHORTFALL'));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('资产数学平衡但现金不足时明确资金缺口,不自动增加本金或利润', () => {
|
||||||
|
const state = applyCommand(empty(), 'purchase', { date: DATE, payer: 'assistant', grams: 20, total: 12000 });
|
||||||
|
const report = buildReport(state, DATE);
|
||||||
|
const person = member(report, 'assistant');
|
||||||
|
assert.equal(person.cashCents, -200000);
|
||||||
|
assert.equal(person.unusedMaterialCents, 1200000);
|
||||||
|
assert.equal(person.expectedSettledAssetsCents, 1000000);
|
||||||
|
assert.equal(person.cashStatus.status, 'shortfall');
|
||||||
|
assert.equal(person.cashStatus.shortfallCents, 200000);
|
||||||
|
assert.equal(person.balanceCheck.mathStatus, 'ok');
|
||||||
|
assert.equal(person.balanceCheck.status, 'review');
|
||||||
|
assert.equal(report.reconciliation.mathStatus, 'ok');
|
||||||
|
assert.equal(report.reconciliation.status, 'review');
|
||||||
|
assert.equal(report.overview.profitCents, 0);
|
||||||
|
assert.equal(state.transfers.length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('普通销售严格验证未收齐/预收字段、精度、有效日期和料池余额', () => {
|
||||||
|
const state = createSeed();
|
||||||
|
const before = JSON.stringify(state);
|
||||||
|
for (const input of [
|
||||||
|
sale({ received: 500 }), sale({ status: 'unpaid' }), sale({ grams: '1.2345' }), sale({ sale: '1.001' }),
|
||||||
|
sale({ grams: '-1' }), sale({ sale: '1e3' }), sale({ date: '2026-02-30' }), sale({ date: '2026-10-31' }),
|
||||||
|
sale({ grams: 11 }), sale({ member: 'stranger' }), sale({ customer: '' }), sale({ expenseAmount: NaN }), sale({ channel: ['credit_card'] }),
|
||||||
|
]) {
|
||||||
|
assert.throws(() => applyCommand(state, 'order', input), DemoError);
|
||||||
|
assert.equal(JSON.stringify(state), before);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('期初只可改金额,不能越过交易日期;修改不混作利润', () => {
|
||||||
|
const state = applyCommand(createSeed(), 'opening', { member: 'assistant', amount: '12000.01' });
|
||||||
|
const report = buildReport(state, DATE);
|
||||||
|
assert.equal(member(report, 'assistant').openingCents, 1200001);
|
||||||
|
assert.equal(member(report, 'assistant').projectedSettledAssetsCents, 1200001);
|
||||||
|
assert.equal(report.overview.profitCents, 30000);
|
||||||
|
assert.throws(() => applyCommand(state, 'opening', { member: 'assistant', amount: 10000, date: '2026-11-02' }), /期初日期固定/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('复杂场景三对往来均有事实,精确闭环;重置无已转', () => {
|
||||||
|
const complex = applyCommand(createSeed(), 'scenario', { scenario: 'complex' });
|
||||||
|
const report = buildReport(complex);
|
||||||
|
assert.equal(complex.transfers.length, 0);
|
||||||
|
assert.equal(report.date, '2026-11-02');
|
||||||
|
assert.equal(report.orders.length, 3);
|
||||||
|
assert.equal(report.settlements.filter((item) => item.pendingCents > 0).length, 3);
|
||||||
|
for (const person of report.members) assert.equal(person.balanceCheck.status, 'ok');
|
||||||
|
assert.equal(report.reconciliation.status, 'ok');
|
||||||
|
const reset = applyCommand(complex, 'reset', {});
|
||||||
|
assert.deepEqual(reset, createSeed());
|
||||||
|
});
|
||||||
|
|
||||||
|
test('采购预览和公开state不暴露内部幂等记录,单位均为分/毫克', () => {
|
||||||
|
assert.deepEqual(purchasePreview({ grams: '10', total: '10000' }), { weightMg: 10000, totalCents: 1000000, unitPriceCents: 100000, unitPriceYuanPerGram: 1000 });
|
||||||
|
const state = publicState(createSeed());
|
||||||
|
assert.equal(state.currentDate, DATE);
|
||||||
|
assert.equal(state.purchases[0].weightMg, 10000);
|
||||||
|
assert.equal(state.purchases[0].totalCents, 1000000);
|
||||||
|
assert.equal(Object.hasOwn(state, 'requests'), false);
|
||||||
|
});
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const os = require('node:os');
|
||||||
|
const path = require('node:path');
|
||||||
|
const http = require('node:http');
|
||||||
|
const { once } = require('node:events');
|
||||||
|
const { createDemoServer } = require('../server');
|
||||||
|
|
||||||
|
async function fixture(t) {
|
||||||
|
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'weiguang-capital-http-'));
|
||||||
|
const stateFile = path.join(directory, 'state.json');
|
||||||
|
const publicDirectory = path.join(directory, 'public');
|
||||||
|
fs.mkdirSync(publicDirectory);
|
||||||
|
fs.writeFileSync(path.join(publicDirectory, 'index.html'), '<!doctype html><html lang="zh"><title>仅虚构演示</title></html>');
|
||||||
|
fs.writeFileSync(path.join(publicDirectory, 'demo.js'), 'window.demoOnly = true;');
|
||||||
|
const server = createDemoServer({ stateFile, publicDirectory });
|
||||||
|
server.listen(0, '127.0.0.1');
|
||||||
|
await once(server, 'listening');
|
||||||
|
const port = server.address().port;
|
||||||
|
t.after(async () => { await new Promise((resolve) => server.close(resolve)); fs.rmSync(directory, { recursive: true, force: true }); });
|
||||||
|
async function request(method, route, payload, headers = {}) {
|
||||||
|
const body = payload === undefined ? undefined : typeof payload === 'string' ? payload : JSON.stringify(payload);
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const req = http.request({ hostname: '127.0.0.1', port, path: route, method, headers: { ...(body !== undefined ? { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) } : {}), ...headers } }, (res) => {
|
||||||
|
const chunks = [];
|
||||||
|
res.on('data', (chunk) => chunks.push(chunk));
|
||||||
|
res.on('end', () => {
|
||||||
|
const text = Buffer.concat(chunks).toString('utf8');
|
||||||
|
resolve({ status: res.statusCode, headers: res.headers, text, body: res.headers['content-type']?.includes('application/json') ? JSON.parse(text) : undefined });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
req.on('error', reject);
|
||||||
|
req.end(body);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return { request, stateFile, publicDirectory, port, server };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('HTTP仅临时state,GET/POST结算和部分已转跨日都返回一致报告', async (t) => {
|
||||||
|
const { request, stateFile, server } = await fixture(t);
|
||||||
|
assert.equal(server.address().address, '127.0.0.1');
|
||||||
|
const first = await request('GET', '/api/demo/state');
|
||||||
|
assert.equal(first.status, 200);
|
||||||
|
assert.equal(first.body.data.report.overview.profitCents, 30000);
|
||||||
|
assert.equal(first.body.data.transfers.length, 0);
|
||||||
|
const changed = await request('POST', '/api/demo/transfer', { date: '2026-11-02', from: 'assistant', to: 'owner', amount: '500', requestId: 'http-transfer-1' });
|
||||||
|
assert.equal(changed.status, 200);
|
||||||
|
assert.equal(changed.body.data.currentDate, '2026-11-02');
|
||||||
|
const person = changed.body.data.report.members.find((item) => item.member === 'assistant');
|
||||||
|
assert.equal(person.profitCents, 0);
|
||||||
|
assert.equal(person.pendingPayCents, 130000);
|
||||||
|
assert.equal(JSON.parse(fs.readFileSync(stateFile, 'utf8')).transfers.length, 1);
|
||||||
|
const report = await request('GET', '/api/demo/report?date=2026-11-02');
|
||||||
|
assert.deepEqual(report.body.data, changed.body.data.report);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('HTTP重复提交可安全重试,已结清重复全额拒绝且磁盘不变', async (t) => {
|
||||||
|
const { request, stateFile } = await fixture(t);
|
||||||
|
const body = { date: '2026-11-01', from: 'assistant', to: 'owner', amount: '1800', requestId: 'same-transfer' };
|
||||||
|
assert.equal((await request('POST', '/api/demo/transfer', body)).status, 200);
|
||||||
|
const bytes = fs.readFileSync(stateFile, 'utf8');
|
||||||
|
const repeated = await request('POST', '/api/demo/transfer', body);
|
||||||
|
assert.equal(repeated.status, 200);
|
||||||
|
assert.equal(repeated.body.data.transfers.length, 1);
|
||||||
|
assert.equal(fs.readFileSync(stateFile, 'utf8'), bytes);
|
||||||
|
const { requestId, ...again } = body;
|
||||||
|
const rejected = await request('POST', '/api/demo/transfer', again);
|
||||||
|
assert.equal(rejected.status, 409);
|
||||||
|
assert.equal(rejected.body.error.code, 'TRANSFER_EXCEEDS_PENDING');
|
||||||
|
assert.equal(fs.readFileSync(stateFile, 'utf8'), bytes);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('HTTP未知/预收/欠款输入或无效JSON失败不落盘', async (t) => {
|
||||||
|
const { request, stateFile } = await fixture(t);
|
||||||
|
const bytes = fs.readFileSync(stateFile, 'utf8');
|
||||||
|
const inputs = [
|
||||||
|
['/api/demo/order', { date: '2026-11-01', member: 'assistant', customer: '虚构未收齐', grams: 1, sale: 2000, paidAmount: 1000 }],
|
||||||
|
['/api/demo/purchase', { date: '2026-02-30', payer: 'owner', grams: 1, total: 1000 }],
|
||||||
|
['/api/demo/opening', { member: 'owner', amount: -1 }],
|
||||||
|
['/api/demo/order', '{bad json'],
|
||||||
|
['/api/demo/purchase', []],
|
||||||
|
];
|
||||||
|
for (const [route, body] of inputs) {
|
||||||
|
const result = await request('POST', route, body);
|
||||||
|
assert.equal(result.status, 400);
|
||||||
|
assert.equal(result.body.ok, false);
|
||||||
|
assert.equal(typeof result.body.error.message, 'string');
|
||||||
|
assert.equal(fs.readFileSync(stateFile, 'utf8'), bytes);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('HTTP严格校验Host和同源,拒绝外站/其他本机Origin', async (t) => {
|
||||||
|
const { request, stateFile, port } = await fixture(t);
|
||||||
|
const bytes = fs.readFileSync(stateFile, 'utf8');
|
||||||
|
const payload = { member: 'assistant', amount: 1 };
|
||||||
|
for (const headers of [{ Host: `evil.example:${port}` }, { Origin: 'https://evil.example' }, { Origin: 'null' }, { Origin: `http://localhost:${port}` }]) {
|
||||||
|
const result = await request('POST', '/api/demo/opening', payload, headers);
|
||||||
|
assert.equal(result.status, 403);
|
||||||
|
assert.equal(fs.readFileSync(stateFile, 'utf8'), bytes);
|
||||||
|
}
|
||||||
|
const own = await request('POST', '/api/demo/opening', { member: 'assistant', amount: 10000 }, { Origin: `http://127.0.0.1:${port}` });
|
||||||
|
assert.equal(own.status, 200);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('HTTP静态文件限制public且不公开engine或state,正确MIME与防缓存', async (t) => {
|
||||||
|
const { request } = await fixture(t);
|
||||||
|
const index = await request('GET', '/');
|
||||||
|
assert.equal(index.status, 200);
|
||||||
|
assert.match(index.text, /仅虚构演示/);
|
||||||
|
assert.match(index.headers['content-type'], /^text\/html/);
|
||||||
|
assert.equal(index.headers['cache-control'], 'no-store');
|
||||||
|
assert.equal((await request('GET', '/public/demo.js')).status, 200);
|
||||||
|
assert.equal((await request('GET', '/demo.js')).status, 200);
|
||||||
|
for (const route of ['/engine.js', '/state.json', '/%2e%2e%2fengine.js', '/server.js', '/contract.md']) assert.equal((await request('GET', route)).status, 404);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('HTTP支持采购预览、两天虚构场景和重置,不预登记任何已转', async (t) => {
|
||||||
|
const { request } = await fixture(t);
|
||||||
|
const preview = await request('GET', '/api/demo/purchase-preview?grams=10&total=10000');
|
||||||
|
assert.equal(preview.body.data.unitPriceCents, 100000);
|
||||||
|
const scenario = await request('POST', '/api/demo/scenario', { name: 'complex' });
|
||||||
|
assert.equal(scenario.body.data.currentDate, '2026-11-02');
|
||||||
|
assert.equal(scenario.body.data.orders.length, 3);
|
||||||
|
assert.equal(scenario.body.data.transfers.length, 0);
|
||||||
|
assert.equal(scenario.body.data.report.reconciliation.status, 'ok');
|
||||||
|
const reset = await request('POST', '/api/demo/reset', {});
|
||||||
|
assert.equal(reset.body.data.currentDate, '2026-11-01');
|
||||||
|
assert.equal(reset.body.data.orders.length, 1);
|
||||||
|
assert.equal(reset.body.data.transfers.length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('HTTP限制方法/内容类型/64KB正文,错误不改变状态', async (t) => {
|
||||||
|
const { request, stateFile } = await fixture(t);
|
||||||
|
const bytes = fs.readFileSync(stateFile, 'utf8');
|
||||||
|
assert.equal((await request('DELETE', '/api/demo/state')).status, 405);
|
||||||
|
assert.equal((await request('POST', '/api/demo/purchase', '{}', { 'Content-Type': 'text/plain' })).status, 415);
|
||||||
|
assert.equal((await request('POST', '/api/demo/purchase', JSON.stringify({ note: '大'.repeat(24000) }))).status, 413);
|
||||||
|
assert.equal((await request('POST', '/api/demo/not-real', {})).status, 404);
|
||||||
|
assert.equal(fs.readFileSync(stateFile, 'utf8'), bytes);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('HTTP持久状态可重开;服务拒绝把数据放到产品文件夹', async (t) => {
|
||||||
|
const { request, stateFile, publicDirectory } = await fixture(t);
|
||||||
|
await request('POST', '/api/demo/opening', { member: 'assistant', amount: 12000 });
|
||||||
|
const second = createDemoServer({ stateFile, publicDirectory });
|
||||||
|
second.listen(0, '127.0.0.1');
|
||||||
|
await once(second, 'listening');
|
||||||
|
t.after(() => new Promise((resolve) => second.close(resolve)));
|
||||||
|
const response = await fetch(`http://127.0.0.1:${second.address().port}/api/demo/state`);
|
||||||
|
const reopened = await response.json();
|
||||||
|
assert.equal(reopened.data.opening.find((item) => item.member === 'assistant').amount, 1200000);
|
||||||
|
assert.throws(() => createDemoServer({ stateFile: path.join(__dirname, 'no-write-state.json') }), /临时目录/);
|
||||||
|
});
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const path = require('node:path');
|
||||||
|
const vm = require('node:vm');
|
||||||
|
const { createSeed, publicState, applyCommand } = require('../engine');
|
||||||
|
|
||||||
|
// 用真实引擎报告验证展示筛选与转义;浏览器布局另由本地预览核验。
|
||||||
|
function 页面输出(state, view = 'assistant', date = '2026-11-01') {
|
||||||
|
const nodes = new Map(),handlers={};
|
||||||
|
function node(selector) {
|
||||||
|
if (!nodes.has(selector)) nodes.set(selector, {
|
||||||
|
innerHTML:'', textContent:'', value:'', hidden:false, disabled:false,
|
||||||
|
addEventListener() {}, scrollIntoView(){this.scrolled=true;}, querySelector: child => node(`${selector} ${child}`),
|
||||||
|
querySelectorAll:() => [], classList:{toggle() {}},
|
||||||
|
});
|
||||||
|
return nodes.get(selector);
|
||||||
|
}
|
||||||
|
const context = vm.createContext({
|
||||||
|
document:{querySelector:node, querySelectorAll:() => [], addEventListener(type,fn){(handlers[type]??=[]).push(fn);}},
|
||||||
|
Intl, Number, String, Math, Date, Set, JSON, Object, encodeURIComponent, setTimeout, clearTimeout,
|
||||||
|
crypto:{randomUUID:() => 'test-request'},
|
||||||
|
});
|
||||||
|
const source = fs.readFileSync(path.join(__dirname, '../public/app.js'), 'utf8').replace(/\n载入\(\);\s*$/, '\n');
|
||||||
|
vm.runInContext(source, context);
|
||||||
|
context.input = publicState(state, date);
|
||||||
|
context.view = view;
|
||||||
|
context.date = date;
|
||||||
|
vm.runInContext('页面.数据=input; 页面.视角=view; 页面.日期=date; 渲染();', context);
|
||||||
|
const output=selector=>node(selector).innerHTML;output.node=node;output.click=button=>{for(const fn of handlers.click||[])fn({target:{closest:()=>button}});};return output;
|
||||||
|
}
|
||||||
|
|
||||||
|
test('默认日报展示初期和当日应转,收入卡可访问展开明细,旧转账不改变页面日报', () => {
|
||||||
|
const seed = createSeed();
|
||||||
|
const report = publicState(seed, '2026-11-01').report;
|
||||||
|
const render = 页面输出(seed);
|
||||||
|
const due = report.settlements.find(item => item.pendingCents > 0);
|
||||||
|
assert.match(render('#daily-summary'), /1,800\.00/);
|
||||||
|
assert.match(render('#daily-summary'), /初期余额[\s\S]*10,000\.00/);assert.match(render('#daily-summary'), /<button[^>]*data-income="assistant"/);assert.match(render('#daily-summary'), /本人收款|微信/);assert.doesNotMatch(render('#daily-summary'), /data-transfer=|本日已转|结清后现金/);
|
||||||
|
render.click({dataset:{income:'assistant'}});assert.equal(render.node('#income-details-assistant').open,true);assert.equal(render.node('#income-details-assistant').scrolled,true);assert.doesNotMatch(render('#daily-summary'), /order-2/);
|
||||||
|
|
||||||
|
const partial = applyCommand(seed, 'transfer', {date:'2026-11-01',from:due.from,to:due.to,amount:'800.00'});
|
||||||
|
const partialView = 页面输出(partial);
|
||||||
|
assert.equal(partialView('#daily-summary'),render('#daily-summary'));
|
||||||
|
|
||||||
|
const settled = applyCommand(seed, 'transfer', {date:'2026-11-01',from:due.from,to:due.to,amount:'1800.00'});
|
||||||
|
const after = 页面输出(settled);
|
||||||
|
assert.equal(after('#daily-summary'),render('#daily-summary'));assert.equal(after('#member-summary'),render('#member-summary'));
|
||||||
|
const html=fs.readFileSync(path.join(__dirname,'../public/index.html'),'utf8'),script=fs.readFileSync(path.join(__dirname,'../public/app.js'),'utf8');assert.doesNotMatch(html,/transfer-form|transfer-dialog|id="settlements"/);assert.doesNotMatch(script,/api\/demo\/transfer|data-transfer=|编号:'transfers'/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('助理视角只展示本人订单和利润,总览才能查看其他成员订单', () => {
|
||||||
|
const seed = createSeed('complex');
|
||||||
|
const ownCustomers = seed.orders.filter(order => order.member === 'assistant2' && order.date === '2026-11-01').map(order => order.customer);
|
||||||
|
const otherCustomers = seed.orders.filter(order => order.member !== 'assistant2' && order.date === '2026-11-01').map(order => order.customer);
|
||||||
|
const personal = 页面输出(seed, 'assistant2');
|
||||||
|
const overview = 页面输出(seed, 'owner');
|
||||||
|
for (const name of ownCustomers) assert.ok(personal('#activity').includes(name));
|
||||||
|
for (const name of otherCustomers) {
|
||||||
|
assert.ok(!personal('#activity').includes(name));
|
||||||
|
assert.ok(overview('#activity').includes(name));
|
||||||
|
}
|
||||||
|
assert.doesNotMatch(personal('#member-summary'), /member-card/);
|
||||||
|
assert.match(overview('#member-summary'), /member-card/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('客户输入以文字展示,不能变成页面元素', () => {
|
||||||
|
const seed = createSeed();
|
||||||
|
seed.orders[0].customer = '<img src=x onerror="alert(1)">';
|
||||||
|
const render = 页面输出(seed);
|
||||||
|
assert.doesNotMatch(render('#activity'), /<img/);
|
||||||
|
assert.match(render('#activity'), /<img src=x onerror="alert\(1\)">/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('单独购料订单不混入共用材料池的用料还款说明', () => {
|
||||||
|
const seed = applyCommand(createSeed(), 'order', {date:'2026-11-01',member:'assistant',customer:'单独配货检查',grams:'1',sale:'1500',collector:'assistant',channel:'wechat',materialSource:'direct',directMaterialCost:'1000',directMaterialPayer:'owner'});
|
||||||
|
const render = 页面输出(seed);
|
||||||
|
assert.match(render('#activity'), /单独配货检查/);
|
||||||
|
assert.doesNotMatch(render('#material-pool'), /单独配货检查/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('日报不展示依赖历史实转的现金结清或累计核对面板', () => {
|
||||||
|
const seed = applyCommand(createSeed(), 'purchase', {date:'2026-11-01',payer:'assistant',grams:'20',total:'20000'});
|
||||||
|
const own = 页面输出(seed);
|
||||||
|
assert.match(own('#member-summary'), /麦麦垫付/);assert.doesNotMatch(own('#member-summary'), /资金缺口|资金待核对|✓ 已对上|结清后现金|当前现金|累计收到转账/);
|
||||||
|
const other = 页面输出(seed, 'assistant2');
|
||||||
|
assert.doesNotMatch(other('#daily-summary'), /资金缺口/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('老板全店亏损保留负号,助理亏损应转待复核',()=>{
|
||||||
|
const base={...createSeed(),orders:[],purchases:[],transfers:[],requests:[],nextSequence:1};
|
||||||
|
const state=applyCommand(base,'order',{date:'2026-11-01',member:'assistant',customer:'亏损虚构客户',grams:'1',sale:'50',collector:'assistant',channel:'wechat',materialSource:'direct',directMaterialCost:'80',directMaterialPayer:'owner',expenseAmount:'0',expensePayer:'assistant',allowLoss:true});
|
||||||
|
assert.match(页面输出(state,'owner')('#daily-summary'),/hero-amount money">¥-30\.00/);assert.match(页面输出(state)('#daily-summary'),/当天应转金额待复核/);assert.match(页面输出(state)('#daily-summary'),/亏损订单/);
|
||||||
|
});
|
||||||
Executable
+15
@@ -0,0 +1,15 @@
|
|||||||
|
#!/bin/zsh
|
||||||
|
cd -- "${0:A:h}" || exit 1
|
||||||
|
if [[ -x /opt/homebrew/bin/node ]]; then
|
||||||
|
demo_node=/opt/homebrew/bin/node
|
||||||
|
elif command -v node >/dev/null 2>&1; then
|
||||||
|
demo_node=$(command -v node)
|
||||||
|
else
|
||||||
|
print "未找到Node.js。请先安装Node.js,再双击打开演示。"
|
||||||
|
read -r "?按回车关闭。"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
"$demo_node" server.js
|
||||||
|
if [[ $? -ne 0 ]]; then
|
||||||
|
read -r "?启动未完成,按回车关闭。"
|
||||||
|
fi
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
# 当天订单对账:独立演示
|
||||||
|
|
||||||
|
2026-11-02 当前版按麦麦确认:当天应转麦麦=麦麦垫付的本人当天订单成本+本人当天净利润-麦麦代收本人订单款。页面显示初期余额和所选日收入、成本、净利润;点击收入金额卡或展开明细,可按客户、实际收款人及微信/支付宝等渠道核对,自收与麦麦/其他成员代收分开。成本明细突出麦麦垫付,未用料不计偿还。仅核对所选日,移除模拟转账按钮、表单、页签、累计待转与现金结清面板;旧transfers兼容保留,不影响新日报、不自动生成付款记录。亏损合并计入真实净利润,应转待复核;正常代收抵扣为负则显示“麦麦应返/核对”。期初、新增示例购料销售、料池原算法和三人模拟视角保留。
|
||||||
|
|
||||||
|
本轮全部38/38测试通过,并经根代理独立复跑和浏览器验收:助理日报、老板总览、点击收入展开、次日无单全0及初期余额保留。日志 `/tmp/maimai-capital-daily-directed-20261102.log`。仅修改独立演示,未提交、推送或操作正式仓库/真实数据库。
|
||||||
|
|
||||||
|
## 以下为2026-10-28早期方案历史记录,当前页面以上述更新为准
|
||||||
|
|
||||||
|
## 保存状态
|
||||||
|
|
||||||
|
2026年10月28日,麦麦确认将此版本单独保存在本机,暂不推送、不合并到正式版本,也不启用到当前账目。独立目录为 `/Users/mai/Documents/Claude/台账系统-周转金演示`,本地分支为 `codex/working-capital-demo`。后续只有麦麦明确要求更新这个演示版本时,才调整这份方案;正式系统的维护与推送不包含本演示。
|
||||||
|
|
||||||
|
这是独立方案模型,只用虚构人员和虚构订单供本地看效果。它不接正式账、不导入正式应用、不读取数据库或凭据,也不修改当前正式财务算法。演示登记的“模拟转账”不向任何银行或支付平台发起真实付款。
|
||||||
|
|
||||||
|
## 打开和关闭
|
||||||
|
|
||||||
|
双击本目录的 `启动演示.command`,再在浏览器打开 <http://127.0.0.1:3102>。关闭运行演示的终端,或在终端按 Control+C 即可停止。下次双击可继续查看尚未重置的虚构数据。
|
||||||
|
|
||||||
|
也可以在本目录运行:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
node server.js
|
||||||
|
```
|
||||||
|
|
||||||
|
只监听 `127.0.0.1:3102`。数据文件固定为 `/tmp/weiguang-capital-demo-20261028/state.json`,不写到产品或知识库内容目录。系统可能清理 `/tmp`;演示数据不是业务档案。页面“重置演示”恢复最初示例,不触碰其他文件。
|
||||||
|
|
||||||
|
## 最先看这个例子
|
||||||
|
|
||||||
|
日期为2026年11月1日,麦麦、助理1、助理2各有10000元初始周转金。麦麦购入10克材料,实付10000元。助理1交付示例客户小禾1.5克,自己微信收2000元、自己付工费200元:
|
||||||
|
|
||||||
|
- 实际用料成本1500元,订单利润300元。
|
||||||
|
- 助理1应归还麦麦已耗用材料款1500元、上交利润300元,合计待转1800元。
|
||||||
|
- 采购时已经扣过麦麦现金;订单用料不会再扣一次购料款。未耗用的8500元材料仍是麦麦资金占用的资产,不成为助理1的欠款。
|
||||||
|
- 页面初始没有任何已转记录。只有点击“登记模拟转账”,才会真的改变本演示现金。转1800元后,助理1现金回到10000元。
|
||||||
|
- 助理2最初没有销售,报告显示无销售活动,不编造订单或已交利润。
|
||||||
|
|
||||||
|
## 本模型的口径
|
||||||
|
|
||||||
|
收入、用料、费用、利润按订单归属统计;实际收款、实付材料、费用、手续费和模拟转账按真实经办成员计算现金。助理正利润形成上交麦麦的应转,别人代付成本形成归还,别人代收货款在该成员对内抵扣。每对成员独立计算,三个人之间不会静默循环轧差。
|
||||||
|
|
||||||
|
共用池每天用“昨日期末剩余重量和成本+当天所有购料”算当日加权成本。订单按当日固定加权成本分摊,整数分舍入通过累计耗用分摊,最后用尽时精确带走余款。成本付款来源按购料的尚未分配付款金额FIFO分摊:先归还最早付款来源,再归还下一笔。FIFO跟踪的是金额,不是声称每克金都属于谁。未用料资产也按这些付款余额归属。
|
||||||
|
|
||||||
|
同日新增购料会重算该日订单;已经登记的转账始终保留,若原来转多,会明确出现反向待返。次日新购只影响次日及以后,不重算前日成本。报告将期初未结、本日新增、本日已转、累计待转分别列出;前日利润不会再次成为本日应交。
|
||||||
|
|
||||||
|
信用卡自动由麦麦收款,6‰手续费由麦麦支付,手续费进入对应订单成本;报告通过代付往来归还麦麦。微信、支付宝、现金和银行转账可指定实际收款成员。本单自行配货可直接登记已付材料款,不扣共用料池,也不假设一笔材料款既发生在采购又发生在订单。
|
||||||
|
|
||||||
|
现金公式是:期初周转金+实际收款-购料-自行配货材料-实付其他费用-刷卡手续费+已收转账-已付转账。
|
||||||
|
|
||||||
|
正常盈利情景下,每位助理的“现金+本人付款未用材料+应收成员往来-应付成员往来”等于初始周转金;全部结清后就是“现金+本人未用材料=初始周转金”。麦麦对应结果为初始周转金加全店累计利润。全店“现金+未用料资产=总期初+累计真实利润”。
|
||||||
|
|
||||||
|
## 操作边界
|
||||||
|
|
||||||
|
只支持已交付、货款全部收齐的普通销售。预收锁价、未收齐订单、退款、退货、回收、置换及正式账迁移不在此次方案内。输入金额最多两位小数、重量最多三位小数,不接受负数、无效日期或不足的共用材料。
|
||||||
|
|
||||||
|
亏损结算政策没有确认。默认拒绝直接登记亏损单;只有明确选择“亏损待复核”才记录事实,不自动让麦麦向助理反向支付利润。若同日加购重算使旧订单变亏损,会保留购料与已转事实,标出订单待复核、资本差额和风险;不能把这个异常解释为已确认的亏损承担政策。
|
||||||
|
|
||||||
|
试算采购或费用超过当前现金时,可以保留负余额看资金缺口,但页面必须显示资金不足和待核实,不能把数学闭环显示为全部正常。缺口不是额外利润或已经到账的钱,演示不会自动补足本金或生成贷款。
|
||||||
|
|
||||||
|
转账只允许当前这对成员的实际待转方向与金额,支持部分结清;已经结清再次全额登记会拒绝。表单提供幂等键,网络重试不会重复记账。同一幂等键不同内容会拒绝。失败操作不会改动演示状态。期初金额可修改,期初日期固定,避免把已有交易放在期初之前。
|
||||||
|
|
||||||
|
“复杂示例”是另一个可重置的虚构场景:信用卡麦麦代收、助理跨成员代收代付、付款金额FIFO跨来源、余料次日再用与次日新购。它同样不预设任何已上交或已转账。
|
||||||
|
|
||||||
|
## 本地验证
|
||||||
|
|
||||||
|
在本目录运行:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
node --test test/*.test.js
|
||||||
|
```
|
||||||
|
|
||||||
|
测试用独立临时数据文件和随机本地端口,不占用3102,也不读取正式数据。接口和字段见 `contract.md`。技术说明只解释本演示,不代表正式账方案已经获准上线。
|
||||||
Reference in new issue
Block a user