shoc-frontend-new/src/domain/work-orders/utils/completion-doc-site.ts

87 lines
2.7 KiB
TypeScript

import type { Location } from "@/domain/locations/types/location";
import type { CompDocSiteInfo } from "@/domain/work-orders/types/completion-doc";
import type { WorkOrderTableRow } from "@/domain/work-orders/types/work-order-table-row";
import {
effectiveCompany,
effectiveSite,
} from "@/domain/work-orders/utils/effective-completion-snapshot";
type CompDocAddress = Pick<
CompDocSiteInfo,
"street" | "city" | "state" | "zip" | "label" | "fullAddress"
>;
type CompDocIdentityRow = Pick<WorkOrderTableRow, "site" | "location" | "status" | "frozenSite"> &
Partial<Pick<WorkOrderTableRow, "company" | "tech" | "techPhone" | "frozenCompany">>;
function buildLabel(city?: string, state?: string): string {
return [city, state].filter(Boolean).join(", ");
}
function toCompDocAddress(
street: string,
city: string,
state: string,
zip: string,
): CompDocAddress {
const label = buildLabel(city, state);
const fullAddress = [street, label, zip].filter(Boolean).join(", ") || "—";
return { street, city, state, zip, label, fullAddress };
}
function withCompDocIdentity(address: CompDocAddress, row: CompDocIdentityRow): CompDocSiteInfo {
const frozen = effectiveSite(row);
const company = effectiveCompany({
status: row.status,
company: row.company ?? "",
tech: row.tech ?? "",
techPhone: row.techPhone ?? "",
frozenCompany: row.frozenCompany,
});
return {
...address,
code: frozen?.code ?? row.site,
tech: company.contactName ?? "",
company: company.name ?? "",
};
}
function resolveLiveLocationSite(location: Location): CompDocAddress {
return toCompDocAddress(
location.address ?? "",
location.city ?? "",
location.state ?? "",
location.zipCode ?? "",
);
}
function resolveRowLocationSite(row: Pick<WorkOrderTableRow, "location">): CompDocAddress {
const locationParts = row.location.split(",").map((part) => part.trim());
const city = locationParts[0] ?? "";
const state = locationParts[1] ?? "";
const label = buildLabel(city, state);
const street = row.location && !label ? row.location : "";
return toCompDocAddress(street, city, state, "");
}
export function resolveCompDocSite(
row: CompDocIdentityRow,
location?: Location | null,
): CompDocSiteInfo {
const frozen = effectiveSite(row);
if (frozen != null) {
return withCompDocIdentity(
toCompDocAddress(
frozen.address ?? "",
frozen.city ?? "",
frozen.state ?? "",
frozen.zip ?? "",
),
row,
);
}
if (location?.address || location?.city) {
return withCompDocIdentity(resolveLiveLocationSite(location), row);
}
return withCompDocIdentity(resolveRowLocationSite(row), row);
}