Files
Investidor-V2/resources/js/lib/business-locations.ts
T
nala 1106509116
tests / ci (push) Canceled after 0s
vrsao 2
2026-10-08 14:02:01 +02:00

103 lines
3.1 KiB
TypeScript

export type BusinessLocationPath = {
province_id: string;
district_id: string;
admin_post_id: string;
locality_id: string;
};
export const emptyBusinessLocation = (): BusinessLocationPath => ({
province_id: '',
district_id: '',
admin_post_id: '',
locality_id: '',
});
export function decodeBusinessLocations(
value?: string,
): BusinessLocationPath[] {
if (!value) return [];
try {
const parsed: unknown = JSON.parse(value);
if (!Array.isArray(parsed)) return [];
return parsed.slice(0, 20).map((entry) => {
const row =
entry && typeof entry === 'object'
? (entry as Record<string, unknown>)
: {};
return {
province_id:
typeof row.province_id === 'string' ? row.province_id : '',
district_id:
typeof row.district_id === 'string' ? row.district_id : '',
admin_post_id:
typeof row.admin_post_id === 'string'
? row.admin_post_id
: '',
locality_id:
typeof row.locality_id === 'string' ? row.locality_id : '',
};
});
} catch {
return [];
}
}
export function encodeBusinessLocations(rows: BusinessLocationPath[]): string {
return JSON.stringify(rows.slice(0, 20));
}
export function updateBusinessLocation(
rows: BusinessLocationPath[],
index: number,
key: keyof BusinessLocationPath,
value: string,
): BusinessLocationPath[] {
if (!rows[index]) return rows;
const next = rows.map((row) => ({ ...row }));
next[index][key] = value;
const children: Partial<
Record<keyof BusinessLocationPath, (keyof BusinessLocationPath)[]>
> = {
province_id: ['district_id', 'admin_post_id', 'locality_id'],
district_id: ['admin_post_id', 'locality_id'],
admin_post_id: ['locality_id'],
};
for (const child of children[key] ?? []) next[index][child] = '';
return next;
}
export function hasDuplicateBusinessLocationPath(
rows: BusinessLocationPath[],
): boolean {
const paths = rows.map((row) =>
[
row.province_id,
row.district_id,
row.admin_post_id,
row.locality_id,
].filter(Boolean),
);
return paths.some(
(path, index) =>
path.length > 0 &&
paths.slice(index + 1).some((other) => {
if (other.length === 0) return false;
const common = Math.min(path.length, other.length);
return path
.slice(0, common)
.every((id, part) => id === other[part]);
}),
);
}
export function locationPathFromPayload(
payload: Record<string, string | undefined>,
): BusinessLocationPath {
return {
province_id: payload.province_id ?? '',
district_id: payload.district_id ?? '',
admin_post_id: payload.admin_post_id ?? '',
locality_id: payload.locality_id ?? '',
};
}