Files
ERP-core/Frontend/erp-system/lib/warranty.ts
T
2026-09-30 17:06:28 +05:30

52 lines
2.3 KiB
TypeScript

// Warranty period helpers. Periods are always stored in months; custom ones are the active
// rows of the Warranty Periods master and are only offered while
// ProductConfig.customWarrantyPeriodsEnabled is on.
import { ProductConfig, WARRANTY_PERIOD_MONTHS_OPTIONS } from "@/types/master-data"
/** Server limit (WarrantyPeriodService) — mirrored so forms fail fast. */
export const MAX_CUSTOM_WARRANTY_MONTHS = 600
/** "6 months", "1 month", or "24 months (2 years)" when it's a whole number of years. */
export function formatWarrantyPeriod(months: number): string {
const base = `${months} month${months === 1 ? "" : "s"}`
if (months >= 12 && months % 12 === 0) {
const years = months / 12
return `${base} (${years} year${years === 1 ? "" : "s"})`
}
return base
}
export type WarrantyInputUnit = "months" | "years"
/**
* Validates a typed length ("2" + years) against the existing active custom periods and
* converts it to months. Returns the months, or an error message fit to show under the input.
*/
export function parseWarrantyInput(
amount: string,
unit: WarrantyInputUnit,
existingCustom: number[],
): { months: number; error?: undefined } | { months?: undefined; error: string } {
const n = Number(amount)
if (!amount.trim() || !Number.isInteger(n) || n < 1) return { error: "Enter a whole number of 1 or more." }
const months = unit === "years" ? n * 12 : n
if (months > MAX_CUSTOM_WARRANTY_MONTHS)
return { error: `A warranty period can be at most ${MAX_CUSTOM_WARRANTY_MONTHS} months (50 years).` }
if ((WARRANTY_PERIOD_MONTHS_OPTIONS as readonly number[]).includes(months))
return { error: `${formatWarrantyPeriod(months)} is already a default period.` }
if (existingCustom.includes(months)) return { error: `${formatWarrantyPeriod(months)} already exists.` }
return { months }
}
/** The period choices for an item: the defaults, plus the active custom ones when enabled. */
export function warrantyPeriodGroups(
config: ProductConfig | null,
customMonths: number[],
): { defaults: number[]; custom: number[] } {
const defaults: number[] = [...WARRANTY_PERIOD_MONTHS_OPTIONS]
const custom = config?.customWarrantyPeriodsEnabled
? [...new Set(customMonths)].filter((m) => !defaults.includes(m)).sort((a, b) => a - b)
: []
return { defaults, custom }
}