fix(estimate): refresh board quotes and estimate unpriced finishes
This commit is contained in:
parent
16027f8ef3
commit
5d551cef63
@ -433,9 +433,12 @@ export function useStandardEstimator(substrates:SubstrateDTO[],userId?:string, a
|
||||
// A cost retry can retain the current page’s manual quotes. Other unsaved edits stay in the workspace.
|
||||
const source = stage === 'cost' && document.stageResults && saved.stageResults
|
||||
? { ...saved, stageResults: { ...saved.stageResults, cost: document.stageResults.cost } } : saved
|
||||
const hardware = await listAccessoryDrafts()
|
||||
const [hardware, latestSubstrates] = await Promise.all([
|
||||
listAccessoryDrafts(),
|
||||
stage === 'cost' ? request<{ substrates: SubstrateDTO[] }>('/api/asset-center/substrates', { cache: 'no-store' }) : null,
|
||||
])
|
||||
if (savedState.current !== session || session.document !== saved) throw new Error('已保存的测算单发生变化,请重新生成。')
|
||||
const next = regenerateStage(source, stage, substrates, session.record.id, hardware.items)
|
||||
const next = regenerateStage(source, stage, latestSubstrates?.substrates ?? substrates, session.record.id, hardware.items)
|
||||
const results = next.stageResults!
|
||||
if (stage === 'sampling') {
|
||||
const { cabinet, revision } = results.sampling
|
||||
|
||||
@ -5,10 +5,11 @@ import { estimateDocumentSchema } from '../contracts'
|
||||
import { cabinetInputSchema } from '../standard/cabinet-contracts'
|
||||
import { applyCabinetWorkflow } from '../standard/cabinet-workflow'
|
||||
import { calculateStandard } from '../standard/calculate'
|
||||
import { projectFinishBom, snapshotFinishBom } from '../standard/finish-bom'
|
||||
import { costResultDocument, projectFinishBom, snapshotFinishBom } from '../standard/finish-bom'
|
||||
import { updateFinishBomFromTable } from '../standard/finish-bom-edits'
|
||||
import { adjustModelTexture, partAppearanceKey, type ModelFinish } from '../standard/model-appearance'
|
||||
import { boardRowAt } from '../standard/rows'
|
||||
import { initializeStageResults, regenerateStage } from '../standard/stage-results'
|
||||
import { exportStandardWorkbook, importStandardWorkbook, newStandardDocument } from '../standard/workbook'
|
||||
|
||||
const finish: ModelFinish = { name: '测试烟熏橡木', libraryId: 'oak', color: '#785836', bom: true,
|
||||
@ -80,3 +81,60 @@ test('no exact quote leaves the total pending, while a manual price survives tex
|
||||
expect(projectFinishBom(restored)!.standard.cells['S' + newRow]).toBe(75)
|
||||
expect(calculateStandard(projectFinishBom(restored)!.standard).total).toBeCloseTo(calculateStandard(before.standard).total!)
|
||||
})
|
||||
|
||||
test('成本重算补齐旧花色空价,按同规格定额暂估,后续优先使用最新库价', () => {
|
||||
const { original, model } = fixture()
|
||||
const appearance: ModelFinish = { name: '米白色', libraryId: 'cream', color: '#f5f2e6', bom: true }
|
||||
const unpriced = { ...original, modelAppearance: { all: appearance } }
|
||||
const saved = initializeStageResults({ ...unpriced, finishBom: snapshotFinishBom(unpriced, []) })
|
||||
const price = (document: typeof saved) => projectFinishBom(costResultDocument(document))!
|
||||
const side = boardRowAt(model.parts.findIndex(part => part.role === 'side'))
|
||||
const back = boardRowAt(model.parts.findIndex(part => part.role === 'back'))
|
||||
expect(price(saved).missingPrice).toBeGreaterThan(0)
|
||||
const comparable = estimateDocumentSchema.parse(regenerateStage(saved, 'cost', [
|
||||
quote(15, { environmentGradeName: 'E0', suggestedPrice: 1, finishes: [{ id: 'cream', name: '米白色' }] }),
|
||||
]))
|
||||
const projected = price(comparable)
|
||||
expect(projected.standard.cells['F' + side]).toBe('米白色')
|
||||
expect(projected.standard.cells['S' + side]).toBeCloseTo(91 / (2.44 * 1.22))
|
||||
expect(projected.standard.cells['S' + back]).toBeCloseTo(17 / (2.44 * 1.22))
|
||||
expect(projected.standard.costEstimates?.['S' + side]?.reason).toContain('同规格定额')
|
||||
expect(projected.missingPrice).toBe(0)
|
||||
expect(calculateStandard(projected.standard).total).toBeGreaterThan(0)
|
||||
|
||||
const library = quote(15, { name: '米白色生态板', suggestedPrice: 144, finishes: [{ id: 'cream', name: '米白色' }] })
|
||||
const refreshed = regenerateStage(comparable, 'cost', [library])
|
||||
expect(price(refreshed).standard.cells['S' + side]).toBeCloseTo(60)
|
||||
expect(price(refreshed).standard.costEstimates?.['S' + side]).toBeUndefined()
|
||||
const changed = updateFinishBomFromTable(costResultDocument(refreshed), price(refreshed), {
|
||||
...price(refreshed).standard, cells: { ...price(refreshed).standard.cells, ['S' + side]: 0 },
|
||||
})
|
||||
const cost = { ...refreshed.stageResults!.cost, finishBom: changed.finishBom }
|
||||
const again = regenerateStage({ ...refreshed, stageResults: { ...refreshed.stageResults!, cost } }, 'cost', [
|
||||
{ ...library, suggestedPrice: 168 },
|
||||
])
|
||||
expect(price(again).standard.cells['S' + side]).toBe(0)
|
||||
expect(price(again).standard.cells.S40).toBeCloseTo(70)
|
||||
})
|
||||
|
||||
test('未换花色的板件更新库价,保留同一板件的手填价', () => {
|
||||
const { original, model } = fixture()
|
||||
const saved = initializeStageResults(original)
|
||||
const top = boardRowAt(model.parts.findIndex(part => part.role === 'top'))
|
||||
const sides = model.parts.flatMap((part, index) => part.role === 'side' ? [boardRowAt(index)] : [])
|
||||
const library = [
|
||||
quote(15, { id: 'top', suggestedPrice: 120, finishes: [{ id: 'walnut', name: '经典北美黑胡桃色' }] }),
|
||||
quote(15, { id: 'body', suggestedPrice: 144, finishes: [{ id: 'white', name: '荷花白色' }] }),
|
||||
]
|
||||
const first = regenerateStage(saved, 'cost', library)
|
||||
expect(costResultDocument(first).standardTemplate?.cells['S' + top]).toBe(50)
|
||||
const cost = first.stageResults!.cost
|
||||
const edited = { ...cost, standard: { ...cost.standard, cells: { ...cost.standard.cells, ['S' + sides[0]]: 37 } } }
|
||||
const again = regenerateStage({ ...first, stageResults: { ...first.stageResults!, cost: edited } }, 'cost', [
|
||||
{ ...library[0], suggestedPrice: 168 }, library[1],
|
||||
])
|
||||
const cells = costResultDocument(again).standardTemplate!.cells
|
||||
expect(cells['S' + top]).toBe(70)
|
||||
expect(cells['S' + sides[0]]).toBe(37)
|
||||
expect(cells['S' + sides[1]]).toBe(60)
|
||||
})
|
||||
|
||||
@ -4,7 +4,7 @@ const quote = z.object({
|
||||
id: z.string().max(150), name: z.string().max(500),
|
||||
sheetLength: z.number().positive(), sheetWidth: z.number().positive(),
|
||||
sheetPrice: z.number().nonnegative().nullable(), sheetWeight: z.number().nonnegative().nullable(),
|
||||
quotedAt: z.string().max(40),
|
||||
quotedAt: z.string().max(40), estimateReason: z.string().max(1000).optional(),
|
||||
})
|
||||
|
||||
const finishBomCells = z.object({
|
||||
|
||||
@ -3,7 +3,7 @@ import type { EstimateDocument } from '../contracts'
|
||||
import type { CabinetPart } from './cabinet-contracts'
|
||||
import type { StandardTemplate } from './contracts'
|
||||
import type { FinishQuote } from './finish-bom-contract'
|
||||
import { matchCabinetMaterial } from './cabinet-quota'
|
||||
import { CABINET_QUOTA, matchCabinetMaterial } from './cabinet-quota'
|
||||
import { type ModelFinish } from './model-appearance'
|
||||
import { inputValue } from './template'
|
||||
|
||||
@ -26,26 +26,54 @@ export function partFinishSpec(document: Pick<EstimateDocument, 'mainMaterial' |
|
||||
}
|
||||
}
|
||||
type FinishSpec = ReturnType<typeof partFinishSpec>
|
||||
type FinishReference = Pick<ModelFinish, 'name' | 'libraryId'>
|
||||
|
||||
type RatedBoard = { sheetLength: number; sheetWidth: number; sheetPrice: number | null }
|
||||
export const boardPricePerSquareMeter = (board: RatedBoard | null | undefined) => board?.sheetPrice == null
|
||||
? null : board.sheetPrice / (board.sheetLength * board.sheetWidth / 1_000_000)
|
||||
|
||||
export function finishQuoteKey(spec: FinishSpec, finish: ModelFinish) {
|
||||
return JSON.stringify([textKey(spec.substrate), spec.thickness, gradeKey(spec.grade), veneerKey(spec.veneer),
|
||||
finishIdentity(finish), finishNameKey(finish.name)])
|
||||
return JSON.stringify([...boardSpecKey(spec), finishIdentity(finish), finishNameKey(finish.name)])
|
||||
}
|
||||
|
||||
export function readFinishQuote(spec: FinishSpec, finish: ModelFinish, substrates: SubstrateDTO[], now: string): FinishQuote | null {
|
||||
if (!finish.libraryId || !spec.substrate || !spec.grade || !spec.veneer) return null
|
||||
export const boardSpecKey = (spec: FinishSpec) =>
|
||||
[textKey(spec.substrate), spec.thickness, gradeKey(spec.grade), veneerKey(spec.veneer)]
|
||||
|
||||
export function readLibraryFinishQuote(spec: FinishSpec, finish: FinishReference, substrates: SubstrateDTO[], now: string,
|
||||
preferredId?: string): FinishQuote | null {
|
||||
if (!finish.name || !spec.substrate || !spec.grade || !spec.veneer) return null
|
||||
const matches = substrates.filter(row =>
|
||||
row.isActive && row.sheetLengthMm > 0 && row.sheetWidthMm > 0
|
||||
&& row.thicknessMm === spec.thickness && textKey(row.categoryName) === textKey(spec.substrate)
|
||||
&& gradeKey(row.environmentGradeName) === gradeKey(spec.grade)
|
||||
&& veneerKey(row.surfaceOptionName ?? '') === veneerKey(spec.veneer)
|
||||
&& row.finishes.some(item => item.id === finish.libraryId),
|
||||
&& row.suggestedPrice !== null && row.finishes.some(item => finish.libraryId
|
||||
? item.id === finish.libraryId : finishNameKey(item.name) === finishNameKey(finish.name)),
|
||||
).sort((left, right) => left.code.localeCompare(right.code) || left.id.localeCompare(right.id))
|
||||
const row = matches.find(item => item.suggestedPrice !== null)
|
||||
if (row) return { id: row.id, name: row.name, sheetLength: row.sheetLengthMm, sheetWidth: row.sheetWidthMm,
|
||||
sheetPrice: row.suggestedPrice, sheetWeight: row.weightKg, quotedAt: now }
|
||||
const exact = matchCabinetMaterial(spec.substrate, spec.grade, finish.name, spec.veneer, spec.thickness)
|
||||
if (!exact || exact.sheetPrice === null) return null
|
||||
return { id: exact.id, name: exact.name, sheetLength: exact.sheetLengthMm, sheetWidth: exact.sheetWidthMm,
|
||||
sheetPrice: exact.sheetPrice, sheetWeight: exact.sheetWeightKg, quotedAt: now }
|
||||
const row = matches.find(item => item.id === preferredId) ?? matches[0]
|
||||
return row ? { id: row.id, name: row.name, sheetLength: row.sheetLengthMm, sheetWidth: row.sheetWidthMm,
|
||||
sheetPrice: row.suggestedPrice, sheetWeight: row.weightKg, quotedAt: now } : null
|
||||
}
|
||||
|
||||
export function readFinishQuote(spec: FinishSpec, finish: ModelFinish, substrates: SubstrateDTO[], now: string,
|
||||
allowComparable = false): FinishQuote | null {
|
||||
if (!spec.substrate || !spec.grade || !spec.veneer) return null
|
||||
const library = readLibraryFinishQuote(spec, finish, substrates, now)
|
||||
if (library) return library
|
||||
const exact = matchCabinetMaterial(spec.substrate, spec.grade, finish.name, spec.veneer, spec.thickness)
|
||||
if (exact && exact.sheetPrice !== null && exact.sheetLengthMm > 0 && exact.sheetWidthMm > 0)
|
||||
return { id: exact.id, name: exact.name, sheetLength: exact.sheetLengthMm, sheetWidth: exact.sheetWidthMm,
|
||||
sheetPrice: exact.sheetPrice, sheetWeight: exact.sheetWeightKg, quotedAt: now }
|
||||
if (!allowComparable) return null
|
||||
|
||||
const comparable = CABINET_QUOTA.boards.filter(row => row.price !== null && row.sheetLength > 0 && row.sheetWidth > 0
|
||||
&& row.thickness === spec.thickness && textKey(row.material) === textKey(spec.substrate)
|
||||
&& gradeKey(row.grade) === gradeKey(spec.grade) && veneerKey(row.veneer) === veneerKey(spec.veneer))
|
||||
.sort((left, right) => left.price! / (left.sheetLength * left.sheetWidth) - right.price! / (right.sheetLength * right.sheetWidth))
|
||||
const ref = comparable[Math.floor(comparable.length / 2)]
|
||||
if (!ref) return null
|
||||
const name = [spec.grade + spec.thickness + 'mm' + spec.substrate, finish.name, spec.veneer].join(' | ')
|
||||
const estimateReason = `当前花色无报价,按同规格定额 ${ref.source}(${ref.color},¥${ref.price}/张,${ref.sheetLength}×${ref.sheetWidth} mm)暂估。`
|
||||
return { id: ref.id, name, sheetLength: ref.sheetLength, sheetWidth: ref.sheetWidth,
|
||||
sheetPrice: ref.price, sheetWeight: null, quotedAt: now, estimateReason }
|
||||
}
|
||||
|
||||
@ -4,7 +4,7 @@ import type { StandardTemplate } from './contracts'
|
||||
import type { FinishBomData } from './finish-bom-contract'
|
||||
import { calculateStandard } from './calculate'
|
||||
import { quotaConsumableOptions } from './cabinet-quota'
|
||||
import { finishNameKey, finishQuoteKey, partFinishSpec, readFinishQuote } from './finish-bom-quotes'
|
||||
import { boardPricePerSquareMeter, finishNameKey, finishQuoteKey, partFinishSpec, readFinishQuote } from './finish-bom-quotes'
|
||||
import { resolveModelFinish, woodEdge, type ModelFinish } from './model-appearance'
|
||||
import { boardRowAt, MAX_BOARD_ROWS } from './rows'
|
||||
import { boardInputColumns, getBoardRows, inputValue } from './template'
|
||||
@ -36,7 +36,7 @@ function finishGroups(document: FinishInputs) {
|
||||
}).filter(item => item.groups.some(group => group.finish))
|
||||
}
|
||||
|
||||
export function snapshotFinishBom(document: EstimateDocument, substrates: SubstrateDTO[]): FinishBomData | undefined {
|
||||
export function snapshotFinishBom(document: EstimateDocument, substrates: SubstrateDTO[], refreshQuotes = false): FinishBomData | undefined {
|
||||
const changed = finishGroups(document)
|
||||
if (!changed.length) return undefined
|
||||
const prior = document.finishBom
|
||||
@ -46,8 +46,8 @@ export function snapshotFinishBom(document: EstimateDocument, substrates: Substr
|
||||
for (const { spec, groups } of changed) for (const { finish, key } of groups) {
|
||||
if (!finish || !key) continue
|
||||
const quoteKey = finishQuoteKey(spec, finish)
|
||||
if (!Object.hasOwn(quotes, quoteKey)) quotes[quoteKey] = prior && Object.hasOwn(prior.quotes, quoteKey)
|
||||
? prior.quotes[quoteKey] : readFinishQuote(spec, finish, substrates, now)
|
||||
if (!Object.hasOwn(quotes, quoteKey)) quotes[quoteKey] = !refreshQuotes && prior && Object.hasOwn(prior.quotes, quoteKey)
|
||||
? prior.quotes[quoteKey] : readFinishQuote(spec, finish, substrates, now, refreshQuotes)
|
||||
if (prior?.edits[key]) edits[key] = prior.edits[key]
|
||||
}
|
||||
return { quotes, edits }
|
||||
@ -121,9 +121,11 @@ export function projectFinishBom(document: FinishInputs) {
|
||||
d.cells['F' + target] = finish.name
|
||||
d.cells['U' + target] = (finish.edgeStyle ?? (woodEdge(finish.name) ? 'wood' : 'solid')) === 'wood' ? '木色' : '素色'
|
||||
const area = quote ? quote.sheetLength * quote.sheetWidth / 1_000_000 : 0
|
||||
d.cells['S' + target] = area && quote?.sheetPrice != null ? quote.sheetPrice / area : null
|
||||
const unitPrice = boardPricePerSquareMeter(quote)
|
||||
d.cells['S' + target] = unitPrice
|
||||
if (quote) {
|
||||
d.materialQuotes[target] = quote
|
||||
if (unitPrice !== null && quote.estimateReason) d.costEstimates['S' + target] = { value: unitPrice, reason: quote.estimateReason }
|
||||
if (area && quote.sheetWeight != null) {
|
||||
d.cells['AB' + target] = quote.sheetWeight / area
|
||||
delete d.costEstimates['AB' + target]
|
||||
|
||||
@ -0,0 +1,50 @@
|
||||
import type { SubstrateDTO } from '@/server/services/asset-center.service.types'
|
||||
import type { EstimateDocument } from '../contracts'
|
||||
import type { EstimateStageResults } from './stage-results-contract'
|
||||
import type { StandardTemplate } from './contracts'
|
||||
import { cabinetDisplayPartRows } from './cabinet-part-labels'
|
||||
import { boardPricePerSquareMeter, boardSpecKey, finishNameKey, partFinishSpec, readLibraryFinishQuote } from './finish-bom-quotes'
|
||||
import { boardRowAt } from './rows'
|
||||
import { inputValue } from './template'
|
||||
|
||||
function boardRows(document: Pick<EstimateDocument, 'mainMaterial' | 'backMaterial'>, standard: StandardTemplate) {
|
||||
return cabinetDisplayPartRows(standard.cabinet?.parts ?? []).map(({ part, source, indexes }, index) => {
|
||||
const row = boardRowAt(index)
|
||||
const spec = partFinishSpec(document, standard, part, row)
|
||||
const name = String(inputValue(standard, 'F' + row) ?? part.color)
|
||||
const identity = JSON.stringify([source.id, indexes, ...boardSpecKey(spec), finishNameKey(name)])
|
||||
return { row, spec, name, identity }
|
||||
})
|
||||
}
|
||||
|
||||
function manualPrice(standard: StandardTemplate, row: number, generated: number | null) {
|
||||
const address = 'S' + row
|
||||
const value = standard.cells[address]
|
||||
if (typeof value !== 'number' || value === standard.costEstimates?.[address]?.value) return null
|
||||
const before = boardPricePerSquareMeter(standard.materialQuotes[row]) ?? generated
|
||||
return before !== null && Math.abs(value - before) <= Math.abs(before) * 1e-12 ? null : value
|
||||
}
|
||||
|
||||
export function refreshStageBoardQuotes(document: EstimateDocument, standard: StandardTemplate,
|
||||
previous: EstimateStageResults['cost'], substrates: SubstrateDTO[]): StandardTemplate {
|
||||
const originalRows = new Map(boardRows(previous.materials ?? document, previous.standard).map(row => [row.identity, row.row]))
|
||||
const next = { ...standard, cells: { ...standard.cells }, costEstimates: { ...standard.costEstimates }, materialQuotes: { ...standard.materialQuotes } }
|
||||
const now = new Date().toISOString()
|
||||
for (const { row, spec, name, identity } of boardRows(document, standard)) {
|
||||
const address = 'S' + row
|
||||
const oldRow = originalRows.get(identity)
|
||||
const generated = standard.cells[address]
|
||||
const manual = oldRow === undefined ? null : manualPrice(previous.standard, oldRow, typeof generated === 'number' ? generated : null)
|
||||
if (manual !== null) {
|
||||
next.cells[address] = manual
|
||||
delete next.costEstimates[address]
|
||||
continue
|
||||
}
|
||||
const quote = readLibraryFinishQuote(spec, { name }, substrates, now, standard.materialQuotes[row]?.id)
|
||||
if (!quote) continue
|
||||
next.materialQuotes[row] = quote
|
||||
next.cells[address] = boardPricePerSquareMeter(quote)
|
||||
delete next.costEstimates[address]
|
||||
}
|
||||
return next
|
||||
}
|
||||
@ -9,6 +9,7 @@ import { cabinetPartLabel } from './cabinet-part-labels'
|
||||
import type { StandardTemplate } from './contracts'
|
||||
import { projectFinishBom, snapshotFinishBom } from './finish-bom'
|
||||
import { generatePlacements, packingCostInputs, packingScene, refreshModelPacking } from './packaging'
|
||||
import { refreshStageBoardQuotes } from './stage-board-quotes'
|
||||
import { applyStageHardware, resolveStageHardware } from './stage-hardware'
|
||||
import type { ResultStage } from './stage-results-contract'
|
||||
import { resolveModelFinish } from './model-appearance'
|
||||
@ -146,12 +147,12 @@ export function regenerateStage(document: EstimateDocument, stage: ResultStage,
|
||||
}
|
||||
if (results.packing.inventoryKey !== keys.inventory) throw new Error('当前模型的板件或五金已变化,请先到包装页重新生成,再更新成本。')
|
||||
if (shippingChanged) throw new Error('发货方式已变化,请先到包装页重新生成,再更新成本。')
|
||||
const standard = packingCostInputs({ ...applied.standard, packing: results.packing.standard.packing },
|
||||
packingScene(results.packing.standard))
|
||||
const standard = refreshStageBoardQuotes(document,
|
||||
packingCostInputs({ ...applied.standard, packing: results.packing.standard.packing }, packingScene(results.packing.standard)),
|
||||
results.cost, substrates)
|
||||
// Keep same-material manual quotes when regenerating, without copying old quantities or geometry.
|
||||
const finishBom = snapshotFinishBom({ ...document, standardTemplate: standard,
|
||||
finishBom: { quotes: { ...results.cost.finishBom?.quotes, ...document.finishBom?.quotes },
|
||||
edits: { ...results.cost.finishBom?.edits, ...document.finishBom?.edits } } }, substrates)
|
||||
finishBom: { quotes: {}, edits: { ...document.finishBom?.edits, ...results.cost.finishBom?.edits } } }, substrates, true)
|
||||
const projection = projectFinishBom({ ...document, standardTemplate: standard, finishBom })!
|
||||
const check = calculateStandard(projection.standard)
|
||||
if (check.issues.length) throw new Error(check.issues[0])
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user