{"record":{"id":"6f16b0bc14299346","repo":"koala73/worldmonitor","slug":"every-delivery-must-use-unit-mixed-units-are-not-converted","errorCode":null,"errorMessage":"Every delivery must use ${unit}; mixed units are not converted.","messagePattern":"Every delivery must use (.+?); mixed units are not converted\\.","errorType":"validation","errorClass":null,"httpStatus":null,"severity":"error","filePath":"src/utils/operational-balance.ts","lineNumber":43,"sourceCode":"  return value;\n}\n\nexport function parseOperationalInput(value: unknown): OperationalInput {\n  const input = record(value);\n  if (typeof input.operation !== 'string' || !input.operation.trim() || input.operation.length > 100) throw new Error('Enter an operation name of 1-100 characters.');\n  if (typeof input.unit !== 'string' || !/^[\\p{L}\\p{N} %./-]{1,24}$/u.test(input.unit) || !input.unit.trim()) throw new Error('Enter one quantity unit of 1-24 characters.');\n  const unit = input.unit.trim();\n  const startDate = date(input.startDate);\n  if (!Number.isInteger(input.horizonDays) || (input.horizonDays as number) < 1 || (input.horizonDays as number) > MAX_OPERATIONAL_DAYS) throw new Error('Horizon must be 1-90 whole days.');\n  const horizonDays = input.horizonDays as number;\n  if (input.basis !== 'example' && input.basis !== 'user') throw new Error('Input basis must be example or user.');\n  const deliveries = (value: unknown): OperationalDelivery[] => {\n    if (!Array.isArray(value) || value.length > MAX_OPERATIONAL_DELIVERIES) throw new Error('Use at most 30 deliveries per list.');\n    return value.map(value => {\n      const row = record(value);\n      const deliveryDate = date(row.date);\n      if (deliveryDate < startDate || deliveryDate > dateAt(startDate, horizonDays - 1)) throw new Error('Delivery dates must be inside the selected horizon.');\n      if (row.unit !== unit) throw new Error(`Every delivery must use ${unit}; mixed units are not converted.`);\n      return { date: deliveryDate, unit, quantity: quantity(row.quantity, 'Delivery quantity'), costUsd: row.costUsd === null || row.costUsd === undefined ? null : quantity(row.costUsd, 'Delivery cost') };\n    });\n  };\n  return { operation: input.operation.trim(), basis: input.basis, unit, startDate, horizonDays,\n    startingStock: quantity(input.startingStock, 'Starting stock'), dailyDemand: quantity(input.dailyDemand, 'Daily demand'),\n    deliveries: deliveries(input.deliveries), alternativeDeliveries: deliveries(input.alternativeDeliveries),\n    alternativeDailyDemand: input.alternativeDailyDemand === null ? null : quantity(input.alternativeDailyDemand, 'Alternative daily demand') };\n}\n\nexport function calculateOperationalBalance(value: unknown): OperationalSnapshot {\n  const input = parseOperationalInput(value);\n  const balance = (deliveries: OperationalDelivery[], demand: number): OperationalBalance => {\n    let stock = input.startingStock;\n    const days = Array.from({ length: input.horizonDays }, (_, index) => {\n      const date = dateAt(input.startDate, index);\n      const arrivals = round(deliveries.filter(row => row.date === date).reduce((sum, row) => sum + row.quantity, 0));\n      const available = round(stock + arrivals);\n      const unmetDemand = round(Math.max(0, demand - available));","sourceCodeStart":25,"sourceCodeEnd":61,"githubUrl":"https://github.com/koala73/worldmonitor/blob/7d06c8633d256c18e38133030bc3613976a96ec9/src/utils/operational-balance.ts#L25-L61","documentation":"Every delivery row must repeat exactly the same unit string chosen for the worksheet (input.unit). The parser deliberately does no unit conversion, so a row carrying a different unit would silently corrupt totals; instead it throws with the expected unit interpolated into the message.","triggerScenarios":"Calling parseOperationalInput/calculateOperationalBalance where any delivery in deliveries or alternativeDeliveries has row.unit !== input.unit — e.g. worksheet unit 'liters' but a delivery row with unit 'L', 'gallons', or a stale value from an earlier edit.","commonSituations":"Mixing metric and imperial rows in an imported schedule; the top-level unit was renamed but old delivery rows kept the previous string; whitespace/case differences like 'Units' vs 'units'; CSV imports with a per-row unit column.","solutions":["Normalize every delivery row's unit to exactly the top-level input.unit string before parsing.","Convert quantities to one canonical unit yourself and set each row.unit to the worksheet unit.","Trim/case-fold unit strings at the form layer so all rows share one canonical spelling.","In the import path, detect mixed units early and ask the user which unit to keep."],"exampleFix":"// before\ncalculateOperationalBalance({ ...input, unit: 'units', deliveries: [{ date: '2026-09-13', quantity: 40, unit: 'pcs', costUsd: null }] });\n// after\nconst deliveries = rows.map(r => ({ ...r, unit: 'units' }));\ncalculateOperationalBalance({ ...input, unit: 'units', deliveries });","handlingStrategy":"validation","validationCode":"if (input.deliveries.some(d => d.unit !== input.unit)) {\n  throw new Error(`All delivery rows must use unit \"${input.unit}\".`);\n}","typeGuard":"const allRowsUseUnit = (rows: { unit: string }[], unit: string): boolean =>\n  rows.every(r => r.unit === unit);","tryCatchPattern":"try {\n  const snapshot = calculateOperationalBalance(input);\n} catch (err) {\n  if (/^Every delivery must use .+; mixed units are not converted\\.$/.test(err.message)) {\n    input.deliveries = input.deliveries.map(d => ({ ...d, unit: input.unit }));\n  } else throw err;\n}","preventionTips":["Render delivery rows with a read-only unit field mirroring the worksheet unit.","Normalize unit strings (trim + lowercase-compare, keep one canonical spelling) on entry.","When importing CSV with a unit column, convert quantities to the worksheet unit first."],"tags":["validation","unit-mismatch","input-validation"],"backgroundTag":"invalid-argument-value","analyzedSha":"7d06c8633d256c18e38133030bc3613976a96ec9","analyzedAt":"2026-09-15T16:44:39.439Z","contentChangedAt":"2026-09-15T16:44:39.439Z","schemaVersion":2},"datasetVersion":"2026-09-15T18:17:12.389Z"}