{"record":{"id":"d69d94d376052d0a","repo":"koala73/worldmonitor","slug":"horizon-must-be-1-90-whole-days","errorCode":null,"errorMessage":"Horizon must be 1-90 whole days.","messagePattern":"Horizon must be 1-90 whole days\\.","errorType":"validation","errorClass":null,"httpStatus":null,"severity":"error","filePath":"src/utils/operational-balance.ts","lineNumber":34,"sourceCode":"  if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1e6 || round(value) !== value) {\n    throw new Error(`${label} must be between 0 and 1 million with at most 6 decimal places.`);\n  }\n  return value;\n}\nfunction date(value: unknown): string {\n  if (typeof value !== 'string' || !/^\\d{4}-\\d{2}-\\d{2}$/.test(value) || !Number.isFinite(Date.parse(value)) || new Date(value).toISOString().slice(0, 10) !== value || value < '1900-01-01' || value > '9998-12-31') {\n    throw new Error('Use a valid date from 1900 through 9998.');\n  }\n  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","sourceCodeStart":16,"sourceCodeEnd":52,"githubUrl":"https://github.com/koala73/worldmonitor/blob/7d06c8633d256c18e38133030bc3613976a96ec9/src/utils/operational-balance.ts#L16-L52","documentation":"parseOperationalInput validates the operational-balance worksheet input before any calculation. The horizon (planning window length) must be an integer number of whole days between 1 and MAX_OPERATIONAL_DAYS (90). This throw fires when horizonDays is missing, non-numeric, fractional, or outside that range, because a broken horizon would make every downstream date computation meaningless.","triggerScenarios":"Calling parseOperationalInput (directly or via calculateOperationalBalance/importOperationalWorksheet) with input.horizonDays set to a non-integer (e.g. 10.5), a number < 1 (0, -5), a number > 90 (365), a numeric string like '30' that was never converted, or omitted entirely (undefined).","commonSituations":"A UI form submits the raw input string instead of parseInt() of it; a persisted worksheet JSON was hand-edited to a yearly horizon; a defaults object forgets horizonDays; a slider component emits fractional steps.","solutions":["Ensure input.horizonDays is a JS number coerced with Number() or parseInt(value, 10) before calling parseOperationalInput.","Clamp or re-prompt the user for a horizon in the 1-90 range at the form/UI layer before submission.","If the value comes from imported worksheet JSON, validate/normalize it against the operationalExample() shape first.","Confirm the field is actually named horizonDays on the input object (not horizon or days)."],"exampleFix":"// before\ncalculateOperationalBalance({ operation: 'Ops', basis: 'user', unit: 'units', startDate: '2026-09-10', horizonDays: form.horizon, startingStock: 100, dailyDemand: 20, deliveries: [], alternativeDeliveries: [], alternativeDailyDemand: null });\n// after\nconst horizonDays = Number.parseInt(form.horizon, 10);\nif (!Number.isInteger(horizonDays) || horizonDays < 1 || horizonDays > 90) throw new Error('Pick a horizon of 1-90 whole days.');\ncalculateOperationalBalance({ operation: 'Ops', basis: 'user', unit: 'units', startDate: '2026-09-10', horizonDays, startingStock: 100, dailyDemand: 20, deliveries: [], alternativeDeliveries: [], alternativeDailyDemand: null });","handlingStrategy":"validation","validationCode":"function isValidHorizon(v: unknown): v is number {\n  return Number.isInteger(v) && (v as number) >= 1 && (v as number) <= 90;\n}\nif (!isValidHorizon(input.horizonDays)) throw new Error('Pick a horizon of 1-90 whole days.');","typeGuard":"const isWholeDays1to90 = (v: unknown): v is number =>\n  typeof v === 'number' && Number.isInteger(v) && v >= 1 && v <= 90;","tryCatchPattern":"try {\n  const snapshot = calculateOperationalBalance(rawInput);\n} catch (err) {\n  if (err instanceof Error && err.message === 'Horizon must be 1-90 whole days.') {\n    resetHorizonFieldToDefault();\n  } else throw err;\n}","preventionTips":["Coerce form strings with Number.parseInt(value, 10) before assigning horizonDays.","Use a bounded integer slider/stepper (min 1, max 90, step 1) in the UI.","Validate the whole input object against operationalExample()'s shape before every parse call."],"tags":["validation","input-validation","range-check"],"backgroundTag":"value-out-of-range","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"}