import { isHTTPError, isNetworkError, isTimeoutError } from "ky"; import { mapHttpStatusToMessage } from "@/api/api-error"; import { DISPATCH_REQUIRED_MESSAGE } from "@/domain/work-orders/errors/board-patch-errors"; export const BOARD_CREATE_FAILED_MESSAGE = "Unable to create the work order. Please try again."; const DUPLICATE_WO_NUMBER_MESSAGE = "This work order number is already assigned to another work order."; /** Statuses whose mapped copy is fixed product text, never the response body. */ const FIXED_COPY_STATUSES = new Set([401, 403, 404, 500]); function readErrorCode(data: unknown): string | undefined { if (typeof data !== "object" || data === null) { return undefined; } const record = data as Record; const code = record.code ?? record.Code; return typeof code === "string" ? code : undefined; } /** * why: board create returns backend validation text ("siteCode is required.", * "vendorId is required when setting appointment fields.") that must never reach the * screen. Unknown failures fall back to generic copy, not to `error.message`. */ export function boardCreateErrorMessage(error: unknown): string { if (isHTTPError(error)) { const code = readErrorCode(error.data); if (code === "DispatchRequired") { return DISPATCH_REQUIRED_MESSAGE; } if (code === "DuplicateWoNumber") { return DUPLICATE_WO_NUMBER_MESSAGE; } const status = error.response.status; return FIXED_COPY_STATUSES.has(status) ? mapHttpStatusToMessage(status) : BOARD_CREATE_FAILED_MESSAGE; } if (isNetworkError(error) || isTimeoutError(error)) { return error.message; } return BOARD_CREATE_FAILED_MESSAGE; }