refactor(sites): read optional site fields through one helper

This commit is contained in:
Alexandre Brandizzi 2026-09-25 11:45:31 -03:00
parent a75b9c8be6
commit 551f6af208

View file

@ -18,6 +18,14 @@ function readString(record: Record<string, unknown>, ...keys: string[]): string
return "";
}
/** Like readString, but an empty value becomes undefined. */
function readOptionalString(
record: Record<string, unknown>,
...keys: string[]
): string | undefined {
return readString(record, ...keys) || undefined;
}
function readId(record: Record<string, unknown>): string | number {
const value = record.id ?? record.Id;
if (typeof value === "string" || typeof value === "number") {
@ -156,26 +164,30 @@ export function mapLocation(raw: unknown): Location {
const contacts = mapLocationContacts(item.contacts ?? item.Contacts);
const mainContact = contacts[0];
const legacyPhone = readString(item, "phone", "Phone") || undefined;
const legacyContact =
readString(item, "contact", "Contact", "contactPerson", "ContactPerson") || undefined;
const legacyPhone = readOptionalString(item, "phone", "Phone");
const legacyContact = readOptionalString(
item,
"contact",
"Contact",
"contactPerson",
"ContactPerson",
);
return {
id: readId(item) || undefined,
name: readString(item, "name", "Name") || undefined,
title: readString(item, "title", "Title") || undefined,
clientName:
readString(item, "clientName", "ClientName", "accountName", "AccountName") || undefined,
name: readOptionalString(item, "name", "Name"),
title: readOptionalString(item, "title", "Title"),
clientName: readOptionalString(item, "clientName", "ClientName", "accountName", "AccountName"),
sitePhone: legacyPhone,
notes: readString(item, "notes", "Notes") || undefined,
address: address || undefined,
city: readString(item, "city", "City") || undefined,
state: readString(item, "state", "State") || undefined,
zipCode: readString(item, "zipCode", "ZipCode", "Zip") || undefined,
notes: readOptionalString(item, "notes", "Notes"),
address,
city: readOptionalString(item, "city", "City"),
state: readOptionalString(item, "state", "State"),
zipCode: readOptionalString(item, "zipCode", "ZipCode", "Zip"),
phone: mainContact ? mainContact.phone : legacyPhone,
contact: mainContact ? mainContact.name : legacyContact,
contactEmail: readString(item, "contactEmail", "ContactEmail") || undefined,
status: readString(item, "status", "Status") || undefined,
contactEmail: readOptionalString(item, "contactEmail", "ContactEmail"),
status: readOptionalString(item, "status", "Status"),
accountId: readOptionalId(item) || undefined,
contacts: contacts.length > 0 ? contacts : undefined,
};