81 lines
2.8 KiB
TypeScript
Raw Normal View History

import {
orderConfigurationsSchema,
orderSelectionsSchema,
type OrderConfigurations,
type OrderSelections,
} from "./schema";
import type { SimConfigureFormData } from "../sim";
export interface BuildSimOrderConfigurationsOptions {
/**
* Optional fallback phone number when the SIM form does not include it directly.
* Useful for flows where the phone number is collected separately.
*/
phoneNumber?: string | null | undefined;
}
const normalizeString = (value: unknown): string | undefined => {
if (typeof value !== "string") return undefined;
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : undefined;
};
const normalizeDate = (value: unknown): string | undefined => {
const str = normalizeString(value);
if (!str) return undefined;
return str.replace(/-/g, "");
};
/**
* Build an OrderConfigurations object for SIM orders from the shared SimConfigureFormData.
* Ensures the resulting payload conforms to the domain schema before it is sent to the BFF.
*/
export function buildSimOrderConfigurations(
formData: SimConfigureFormData,
options: BuildSimOrderConfigurationsOptions = {}
): OrderConfigurations {
const base: Record<string, unknown> = {
simType: formData.simType,
activationType: formData.activationType,
};
const eid = normalizeString(formData.eid);
if (formData.simType === "eSIM" && eid) {
base.eid = eid;
}
const scheduledDate = normalizeDate(formData.scheduledActivationDate);
if (formData.activationType === "Scheduled" && scheduledDate) {
base.scheduledAt = scheduledDate;
}
const phoneCandidate =
normalizeString(formData.mnpData?.phoneNumber) ?? normalizeString(options.phoneNumber);
if (phoneCandidate) {
base.mnpPhone = phoneCandidate;
}
if (formData.wantsMnp && formData.mnpData) {
const mnp = formData.mnpData;
base.isMnp = "true";
base.mnpNumber = normalizeString(mnp.reservationNumber);
base.mnpExpiry = normalizeDate(mnp.expiryDate);
base.mvnoAccountNumber = normalizeString(mnp.mvnoAccountNumber);
base.portingLastName = normalizeString(mnp.portingLastName);
base.portingFirstName = normalizeString(mnp.portingFirstName);
base.portingLastNameKatakana = normalizeString(mnp.portingLastNameKatakana);
base.portingFirstNameKatakana = normalizeString(mnp.portingFirstNameKatakana);
base.portingGender = normalizeString(mnp.portingGender);
base.portingDateOfBirth = normalizeDate(mnp.portingDateOfBirth);
} else if (formData.wantsMnp) {
// When wantsMnp is true but data is missing, mark the flag so validation fails clearly downstream.
base.isMnp = "true";
}
return orderConfigurationsSchema.parse(base);
}
export function normalizeOrderSelections(value: unknown): OrderSelections {
return orderSelectionsSchema.parse(value);
}