'use strict'; let materialPoolsCache = null, materialPoolsCacheUser = '', materialPoolsRead = null, materialPoolsRequest = 0, materialPoolsOpenDate = ''; let materialPurchaseEntry = null, materialPurchaseEntryRequest = 0; let materialRollingEntry = null, materialRollingRequest = 0, materialChangeListStatus = 'pending'; let materialChangeListRead = 0, materialChangeListCache = null; let materialQuoteEntry = null, materialQuoteRequest = 0, materialQuoteTimer = null; const materialChangeStatuses = { pending: '待店主复核', approved: '已批准', rejected: '已驳回' }; const materialPoolStatusNames = { pending: '待补采购', unused: '未使用', using: '使用中', exhausted: '已用完' }; const materialPayerName = payer => (payer ? teamMemberName(payer) : '待补'); const materialPurchasePayer = purchase => purchase.payer ?? purchase.actualpayer ?? purchase.actualPayer; const materialPurchaseDraftKey = () => `mm-material-purchase-${session.user.id}`; function materialFormMember(form) { const self = typeof currentMember === 'function' ? currentMember() : state.user.member || (state.user.role === 'assistant' ? 'assistant' : 'owner'); return state.user.role === 'owner' ? form?.querySelector('[name="member"]')?.value || self : self; } function materialSourceName(source) { return source.kind === 'personal_recovery' ? materialPayerName(source.member) + '个人回收料' : '公共料'; } function materialSourceSegmentsText(sources = []) { return sources .map( source => `${materialSourceName(source)} ${grams(source.quantity)}g · ${source.amount == null ? '料费待补' : '¥' + yuan(source.amount)}${source.averageRate == null ? '' : '(加权约 ¥' + materialPoolRate(source.averageRate) + '/克)'}`, ) .join(';'); } function materialSourceSegmentsHTML(sources = []) { return sources.length ? `
${sources.map(source => `
${e(materialSourceName(source))}${grams(source.quantity)}g${source.amount == null ? '料费待补' : '¥' + yuan(source.amount)}${source.averageRate == null ? '' : `加权约 ¥${materialPoolRate(source.averageRate)}/克`}
`).join('')}
` : ''; } function materialQuoteBalanceText(pool) { return pool ? `${pool.before ? `本次前可用:个人 ${grams(pool.before.personalRemainingMg)}g,公共 ${grams(pool.before.publicRemainingMg)}g;` : ''}本次后余:个人回收料 ${grams(pool.personalRemainingMg)}g,公共料 ${grams(pool.publicRemainingMg)}g。` : ''; } function materialPoolHasPersonal(pool) { return !!pool && Object.hasOwn(pool, 'personalPools'); } function materialOrderQuoteInput(form = $('#order-form')) { const date = form?.querySelector('[name="date"]')?.value, member = materialFormMember(form), orderId = form?.querySelector('[name="orderId"]')?.value, entries = []; for (const [lineIndex, row] of [...(form?.querySelectorAll('.line-item') || [])].entries()) { const controls = row.querySelector('.material-source-controls'); if (!controls) continue; const prefix = controls.dataset.prefix, get = name => row.querySelector('[name="' + name + '"]')?.value; const allowed = get('unit') === 'g' && !LedgerCalc.isSilver(get('nameType')), source = get(prefix + 'materialSource'); if (!allowed || source !== 'pool') continue; let poolId = get(prefix + 'materialPoolId') || controls.dataset.poolId; if ( (currentMaterialRolling() && date >= materialPoolsCache.rolling.cutover) || controls.dataset.defaultDate === 'true' || !poolId || poolId > date ) poolId = date; const mg = materialPoolMg(get('quantity')); if (mg) entries.push({ lineIndex, poolId, mg }); } return { date, member, ...(orderId ? { orderId } : {}), entries }; } function materialLockQuoteInput(form = $('#price-lock-create-form')) { const date = form?.querySelector('[name="date"]')?.value, rows = [...(form?.querySelectorAll('[data-price-lock-sale]') || [])], entries = []; if (rows.length) rows.forEach((row, lineIndex) => { if (row.querySelector('[name="material_source"]')?.value !== 'pool') return; const mg = materialPoolMg(row.querySelector('[name="quantity"]')?.value); if (mg) entries.push({ lineIndex, poolId: date, mg, ...(row.dataset.lineId ? { lineId: row.dataset.lineId } : {}) }); }); else { const mg = materialPoolMg(form?.querySelector('[name="quantity"]')?.value); if (mg) entries.push({ lineIndex: 0, poolId: date, mg }); } return { date, member: materialFormMember(form), ...(form?.dataset.priceLockEditId ? { priceLockId: form.dataset.priceLockEditId } : {}), entries, }; } function materialQuoteCurrent(kind) { if (kind === 'lockExtra') { const form = $('#price-lock-delivery-form'); return { form, input: materialLockExtraQuoteInput(form) }; } const form = $(kind === 'lock' ? '#price-lock-create-form' : '#order-form'); return { form, input: kind === 'lock' ? materialLockQuoteInput(form) : materialOrderQuoteInput(form) }; } function validateMaterialQuote(result, input) { const integer = value => Number.isSafeInteger(value) && value >= 0, amount = value => value === null || integer(value); if ( !result || result.date !== input.date || result.member !== input.member || !Array.isArray(result.entries) || result.entries.length !== input.entries.length || !Array.isArray(result.pools) ) throw new Error('分来源料费未完整返回,请刷新料价。'); for (const original of input.entries) { const row = result.entries.find(row => row.lineIndex === original.lineIndex); if ( !row || row.poolId !== original.poolId || row.mg !== original.mg || !amount(row.amount) || !Array.isArray(row.allocations) || !Array.isArray(row.materialSources) || row.materialSources.reduce((sum, source) => sum + source.quantity, 0) !== row.mg ) throw new Error('分来源料费与当前商品不一致,请重新核对。'); for (const source of row.materialSources) if ( !['personal_recovery', 'public'].includes(source.kind) || (source.kind === 'personal_recovery' && source.member !== input.member) || !integer(source.quantity) || !amount(source.amount) || !Array.isArray(source.allocations) || source.allocations.some(part => !teamMemberKeys().includes(part.payer) || !integer(part.amount)) || (source.amount !== null && source.allocations.reduce((sum, part) => sum + part.amount, 0) !== source.amount) ) throw new Error('个人回收料或付款来源不完整,请重新读取。'); if ( row.amount !== null && (row.materialSources.some(source => source.amount === null) || row.materialSources.reduce((sum, source) => sum + source.amount, 0) !== row.amount || row.allocations.reduce((sum, part) => sum + part.amount, 0) !== row.amount) ) throw new Error('分来源料费合计不一致,请重新读取。'); } if ( result.pools.length !== new Set(input.entries.map(row => row.poolId)).size || result.pools.some( pool => !input.entries.some(row => row.poolId === pool.poolId) || !['personalRemainingMg', 'publicRemainingMg', 'eligibleRemainingMg'].every(key => integer(pool[key])) || !amount(pool.personalRemainingAmount) || !amount(pool.publicRemainingAmount), ) ) throw new Error('个人与公共可用克重未完整返回,请重新读取。'); return result; } function materialQuoteFor(form, input, kind = 'order') { const signature = JSON.stringify(input), user = state.user.id; if ( materialQuoteEntry?.form === form && materialQuoteEntry.user === user && materialQuoteEntry.signature === signature ) return materialQuoteEntry; clearTimeout(materialQuoteTimer); const entry = (materialQuoteEntry = { form, input, kind, signature, user, request: ++materialQuoteRequest, result: null, error: '', promise: null, }); materialQuoteTimer = setTimeout(() => loadMaterialQuote(entry), 180); return entry; } async function loadMaterialQuote(entry = materialQuoteEntry) { if (!entry || entry !== materialQuoteEntry) return; if (entry.promise) return entry.promise; clearTimeout(materialQuoteTimer); const active = () => { if (entry !== materialQuoteEntry || entry.request !== materialQuoteRequest || entry.user !== state.user.id) return false; const current = materialQuoteCurrent(entry.kind); return current.form === entry.form && JSON.stringify(current.input) === entry.signature; }; entry.promise = (async () => { try { const result = await api('/api/material-pools/quote', entry.input); if (!active()) return; entry.result = validateMaterialQuote(result, entry.input); entry.error = ''; } catch (err) { if (!active()) return; entry.result = null; entry.error = err.name === 'AbortError' ? '分来源料费核对超时,请刷新料价。' : err.message; } if (active()) { if (entry.kind === 'lock' || entry.kind === 'lockExtra') syncPriceLockForm(); else updateTotal(); } })(); try { await entry.promise; } finally { entry.promise = null; } } function materialPoolMg(value) { const text = String(value ?? '').trim(); if (!/^\d+(?:\.\d{1,3})?$/.test(text)) return null; const [whole, fraction = ''] = text.split('.'), mg = BigInt(whole) * 1000n + BigInt(fraction.padEnd(3, '0')); return mg > 0n && mg <= 100000000000n ? Number(mg) : null; } function materialPoolRate(value) { return value == null ? '待补采购' : yuan(value); } function materialPoolPayers(pool) { return ( teamMemberKeys() .filter(payer => pool?.byPayer?.[payer]?.purchased > 0) .map(materialPayerName) .join('、') || '待补采购' ); } function materialPurchaseNeedsReview(purchase) { return purchase?.ownerReviewRequired === true || (!!currentMaterialRolling() && purchase?.date < state.today); } function currentMaterialRolling(result = materialPoolsCache) { return materialPoolsCacheUser === state.user.id && result?.rolling?.enabled === true ? result.rolling : null; } function materialPoolRows(result = materialPoolsCache) { const rows = result?.rows || []; return result?.rolling?.enabled && result.current ? [result.current, ...rows.filter(pool => pool.id !== result.current.id)] : rows; } function validateMaterialRollingResult(result) { if (!result.rolling?.enabled) return result; const current = result.current, integer = value => Number.isSafeInteger(value) && value >= 0, amount = value => value === null || integer(value); if ( !validOrderDate(result.rolling.cutover) || !current || !validOrderDate(current.date) || current.id !== current.date || !['totalMg', 'usedMg', 'remainingMg'].every(key => integer(current[key])) || !amount(current.totalAmount) || !amount(current.averageRate) || !amount(current.remainingCost) || !Array.isArray(current.usages) || !Array.isArray(current.purchases) || !integer(current.opening?.mg) || !amount(current.opening?.amount) || !integer(current.todayPurchases?.mg) || !integer(current.todayPurchases?.amount) || !Array.isArray(current.todayPurchases?.items) || !integer(current.todayReturns?.mg) || !amount(current.todayReturns?.amount) || !Array.isArray(current.returns) ) throw new Error('当前统一料价资料未完整返回,请重新读取。'); return result; } function invalidateMaterialPools() { ++materialPoolsRequest; ++materialQuoteRequest; materialQuoteEntry = null; clearTimeout(materialQuoteTimer); materialPoolsCache = null; materialPoolsCacheUser = ''; materialPoolsRead = null; ++materialChangeListRead; materialChangeListCache = null; closeMaterialRollingDialog(); } async function readMaterialPools(force = false) { const user = state.user.id; if (!force && materialPoolsCache && materialPoolsCacheUser === user) return materialPoolsCache; if (!force && materialPoolsRead?.user === user) return materialPoolsRead.promise; if (force) { ++materialQuoteRequest; materialQuoteEntry = null; clearTimeout(materialQuoteTimer); } const request = ++materialPoolsRequest; const promise = (async () => { const result = await api('/api/material-pools'); if (!Array.isArray(result.rows)) throw new Error('每日料价记录未完整返回,请重新读取。'); validateMaterialRollingResult(result); if (request !== materialPoolsRequest || state.user.id !== user) return null; materialPoolsCache = result; materialPoolsCacheUser = user; return result; })(); materialPoolsRead = { user, promise }; try { return await promise; } finally { if (materialPoolsRead?.promise === promise) materialPoolsRead = null; } } function materialPoolManualDraft(line, unit) { const saved = line.materialPoolDraft?.manual; if (line.costMaterial?.mode === 'pool') return { mode: saved?.mode || (unit === 'g' ? 'gram' : 'total'), rate: saved?.rate ?? '', total: saved?.total ?? '', originalTotal: saved?.originalTotal ?? '', payer: saved?.payer || 'owner', }; const mode = ['gram', 'total'].includes(line.costMaterial?.mode) ? line.costMaterial.mode : unit === 'g' && line.costParts?.material == null ? 'gram' : 'total'; return { mode: line.costMaterialDraft?.mode || mode, rate: line.costMaterial?.rate ?? line.costMaterialDraft?.rate ?? '', total: line.costMaterialDraft?.total ?? (mode === 'total' ? (line.costParts?.material ?? '') : ''), originalTotal: line.costMaterialDraft?.originalTotal ?? (mode === 'total' ? (line.costParts?.material ?? '') : ''), payer: line.costPayers?.material ?? line.payer ?? 'owner', }; } function materialSourceFieldsHTML(line, prefix, unit) { const source = line.costMaterial?.mode === 'pool' ? 'pool' : 'manual', saved = line.materialPoolDraft || {}, poolId = line.costMaterial?.poolId || saved.poolId || '', manual = materialPoolManualDraft(line, unit); return `
${choice( '料费成本来源', prefix + 'materialSource', [ ['manual', '手动填写成本'], ['pool', '当日加权料价'], ], source, )}${button('刷新料价', 'reload-material-choices', 'quiet')}料价按当天加权;垫付款按购料录入顺序扣减。进货工费仍按实际填写。
`; } function materialPoolFieldsSetup(line, unit, parts, costMaterial, materialDraft, costPayers) { if (line.costMaterial?.mode !== 'pool') return { parts, costMaterial, materialDraft, costPayers }; const manual = materialPoolManualDraft(line, unit); return { parts: { ...parts, material: manual.total }, costMaterial: { mode: manual.mode, rate: manual.rate }, materialDraft: { mode: manual.mode, rate: manual.rate, total: manual.total, originalTotal: manual.originalTotal }, costPayers: { ...costPayers, material: manual.payer }, }; } function materialPoolAvailableRows(orderDate, selected) { const rows = materialPoolsCacheUser === state.user.id ? materialPoolRows() : [], rolling = currentMaterialRolling(); const form = $('#order-form'), orderId = form?.querySelector('[name="orderId"]')?.value, member = materialFormMember(form); const available = rows.map(pool => { if (!materialPoolHasPersonal(pool)) return { ...pool, availableMg: orderId ? Math.max( 0, pool.totalMg - (pool.usages || []) .filter(usage => usage.active && usage.order_id !== orderId) .reduce((sum, usage) => sum + usage.mg, 0), ) : pool.remainingMg, }; const restored = orderId ? (pool.usages || []) .filter(usage => usage.active && usage.order_id === orderId) .flatMap(usage => usage.materialSources || [{ kind: 'public', quantity: usage.mg }]) .filter(source => source.kind === 'public' || source.member === member) .reduce((sum, source) => sum + source.quantity, 0) : 0; return { ...pool, availableMg: pool.remainingMg + (pool.personalPools[member]?.remainingMg || 0) + restored }; }); if (rolling && orderDate >= rolling.cutover) { const pool = available.find(pool => pool.id === orderDate); return [ pool || { id: orderDate, date: orderDate, totalMg: 0, usedMg: 0, remainingMg: 0, availableMg: 0, status: 'pending', }, ]; } const byDate = new Map( available .filter( pool => pool.date <= orderDate && (pool.availableMg > 0 || pool.id === selected || pool.date === orderDate || (orderId && pool.usages?.some(usage => usage.active && usage.order_id === orderId))), ) .map(pool => [pool.id, pool]), ); if (orderDate && !byDate.has(orderDate)) byDate.set(orderDate, { id: orderDate, date: orderDate, totalMg: 0, usedMg: 0, remainingMg: 0, status: 'pending' }); if (selected && selected <= orderDate && !byDate.has(selected)) byDate.set(selected, { id: selected, date: selected, totalMg: 0, usedMg: 0, remainingMg: 0, status: 'pending' }); return [...byDate.values()].sort((a, b) => b.date.localeCompare(a.date)); } function captureManualMaterial(root) { const controls = root.querySelector('.material-source-controls'), material = root.querySelector('.purchase-material'), prefix = controls.dataset.prefix, get = name => root.querySelector(`[name="${prefix + name}"]`); const mode = get('materialMode').value; const manual = { mode: material.dataset.preferredMode || mode, rate: get('materialRate').value, total: mode === 'total' ? get('material').value : material.dataset.total, originalTotal: material.dataset.originalTotal, payer: get('materialPayer').value, }; controls.dataset.manual = JSON.stringify(manual); return manual; } function restoreManualMaterial(root) { const controls = root.querySelector('.material-source-controls'), material = root.querySelector('.purchase-material'), prefix = controls.dataset.prefix, get = name => root.querySelector(`[name="${prefix + name}"]`), manual = JSON.parse(controls.dataset.manual); get('materialMode').value = manual.mode; get('materialRate').value = manual.rate; get('material').value = manual.total; get('materialPayer').value = manual.payer; Object.assign(material.dataset, { mode: manual.mode, preferredMode: manual.mode, total: manual.total, originalTotal: manual.originalTotal, unit: root.closest('.line-item').querySelector('[name="unit"]').value, }); get('materialMode').disabled = false; get('materialRate').placeholder = '填写每克进货料价'; get('material').placeholder = '开单前必填,没有填0'; get('materialRate').readOnly = false; get('materialPayer').disabled = false; get('materialMode').closest('label').hidden = false; get('materialRate').closest('label').hidden = false; get('materialPayer').closest('label').hidden = false; material.querySelector('.material-pool-payer')?.remove(); material.querySelector('.purchase-total').firstChild.textContent = '料费成本合计(元)'; get('materialRate').closest('label').firstChild.textContent = '进货料价(元/克)'; } function materialPoolFormPreview(pool, currentRow) { const form = $('#order-form'), date = form.querySelector('[name="date"]').value, rows = [...form.querySelectorAll('.line-item')], entries = []; if (materialPoolHasPersonal(pool)) { const input = materialOrderQuoteInput(form), quote = materialQuoteFor(form, input), lineIndex = rows.indexOf(currentRow), entry = quote.result?.entries.find(row => row.lineIndex === lineIndex), balance = quote.result?.pools.find(row => row.poolId === pool.id); return { amount: entry?.amount ?? null, materialSources: entry?.materialSources || [], allocations: entry?.allocations || [], balance, quote, covered: entry?.amount != null, wantedMg: input.entries.filter(row => row.poolId === pool.id).reduce((sum, row) => sum + row.mg, 0), }; } rows.forEach((row, lineIndex) => { const controls = row.querySelector('.material-source-controls'); if (!controls) return; const prefix = controls.dataset.prefix, source = row.querySelector(`[name="${prefix}materialSource"]`).value; let selected = row.querySelector(`[name="${prefix}materialPoolId"]`).value || controls.dataset.poolId; if ( (currentMaterialRolling() && date >= materialPoolsCache.rolling.cutover) || controls.dataset.defaultDate === 'true' || !selected || selected > date ) selected = date; const allowed = row.querySelector('[name="unit"]').value === 'g' && !LedgerCalc.isSilver(row.querySelector('[name="nameType"]').value); const active = source === 'pool' || (allowed && controls.dataset.allowed === 'false' && controls.dataset.preferredSource === 'pool'); if (!allowed || !active || selected !== pool.id) return; const mg = materialPoolMg(row.querySelector('[name="quantity"]').value); if (mg) entries.push({ lineIndex, mg }); }); const allUsages = materialPoolRows().flatMap(value => value.usages || []), orderId = form.querySelector('[name="orderId"]')?.value || null; const preview = LedgerCalc.poolMaterialPreview(pool, entries, { orderId, allUsages }); return { ...preview, amount: preview.amounts[rows.indexOf(currentRow)] ?? null }; } function syncMaterialPoolSelection(root, unit, quantity) { const controls = root.querySelector('.material-source-controls'); if (!controls) return false; const row = root.closest('.line-item'), prefix = controls.dataset.prefix, get = name => root.querySelector(`[name="${prefix + name}"]`), source = get('materialSource'), poolSelect = get('materialPoolId'), material = root.querySelector('.purchase-material'); const orderDate = $('#order-form [name="date"]').value, name = row.querySelector('[name="nameType"]').value, allowed = unit === 'g' && !LedgerCalc.isSilver(name); source.querySelector('[value="pool"]').disabled = !allowed; if (!allowed && source.value === 'pool') { controls.dataset.preferredSource = 'pool'; source.value = 'manual'; } else if (allowed && controls.dataset.allowed === 'false' && controls.dataset.preferredSource === 'pool') source.value = 'pool'; controls.dataset.allowed = String(allowed); let selected = poolSelect.value || controls.dataset.poolId; const rolling = currentMaterialRolling(), unified = !!rolling && orderDate >= rolling.cutover; if (unified || controls.dataset.defaultDate === 'true' || !selected || selected > orderDate) selected = orderDate; const available = materialPoolAvailableRows(orderDate, selected), optionsHTML = available .map( pool => ``, ) .join(''); if (poolSelect.innerHTML !== optionsHTML) poolSelect.innerHTML = optionsHTML; poolSelect.value = selected; controls.dataset.poolId = selected; const active = source.value === 'pool', previous = controls.dataset.source; if (active && previous !== 'pool') captureManualMaterial(root); if (!active && previous === 'pool') restoreManualMaterial(root); controls.dataset.source = source.value; controls.querySelector('.material-pool-date-label').hidden = !active; poolSelect.disabled = !active; controls.querySelector('[data-action="reload-material-choices"]').hidden = !active; const help = controls.querySelector('.material-source-help'); help.textContent = allowed ? unified ? '昨日余料、今日购料及退货回料合并加权;今日加料只更新今日订单。进货工费按实际填写。' : '料价按当天加权;垫付款按购料录入顺序扣减。进货工费仍按实际填写。' : '按件商品和银饰请手动填写料费成本。'; const note = controls.querySelector('.material-pool-note'); note.hidden = !active; if (!active) return false; const pool = materialPoolsCacheUser === state.user.id ? materialPoolRows().find(pool => pool.id === selected) : null, mg = materialPoolMg(quantity), personal = materialPoolHasPersonal(pool), member = materialFormMember($('#order-form')); let preview = null, previewError = ''; if (pool) try { if (!personal && pool.totalAmount === null) previewError = '材料成本尚未补齐,请先由店主核对历史材料记录。'; else preview = materialPoolFormPreview(pool, row); } catch (err) { previewError = err.message; } if (personal) previewError = previewError || preview?.quote?.error || ''; const wanted = preview?.wantedMg ?? 0, used = preview?.usedMg ?? pool?.usedMg ?? 0, covered = preview?.covered === true, amount = mg ? (preview?.amount ?? null) : null; const payerText = personal ? preview?.allocations?.length ? [...new Set(preview.allocations.map(part => materialPayerName(part.payer)))].join('、') : '按本单来源核对' : materialPoolPayers(pool); get('materialMode').value = 'total'; get('materialMode').disabled = true; get('materialMode').closest('label').hidden = true; const rate = get('materialRate'); rate.placeholder = '待核算'; get('material').placeholder = '待核算'; rate.disabled = false; rate.required = false; rate.readOnly = true; rate.value = personal || pool?.averageRate == null ? '' : (pool.averageRate / 100).toFixed(2); rate.closest('label').hidden = personal; rate.closest('label').firstChild.textContent = '加权进货料价(元/克,自动)'; get('material').value = amount == null ? '' : (amount / 100).toFixed(2); get('material').readOnly = true; get('material').required = false; get('material').closest('label').firstChild.textContent = '耗用料费合计(元,自动)'; get('materialPayer').disabled = true; get('materialPayer').closest('label').hidden = true; let payer = material.querySelector('.material-pool-payer'); if (!payer) { material .querySelector('.purchase-cost-grid') .insertAdjacentHTML( 'beforeend', field( unified ? '材料原付款人' : '本批购料付款人', prefix + 'materialPoolPayer', '', 'text', 'readonly', ).replace('