import { aggregateAcrossTeams, formatAggregationResult, loopGet, } from "../lib/loop-api.js"; // ─── Loop API V2: /residential/{dept}/viewings ───────────────── // Fields: id, propertyId, propertyAddress, status, // dateOfAppointment, dateOfAppointmentEnd, // attendingAgentId, creatingAgentId, type, buyerName // ──────────────────────────────────────────────────────────────── interface LoopViewingSummary { id: number; propertyId?: number; propertyAddress?: string; status?: string; dateOfAppointment?: string; dateOfAppointmentEnd?: string; attendingAgentId?: string; creatingAgentId?: string; type?: string; buyerName?: string; [key: string]: unknown; } type Department = "sales" | "lettings" | "both"; export async function viewingSearch(params: { accountId: string; department?: Department; searchTerm?: string; appointmentStartDate?: string; appointmentEndDate?: string; status?: string; teamName?: string; limit?: number; }): Promise { const { accountId, department = "both", searchTerm, appointmentStartDate, appointmentEndDate, status, teamName, limit, } = params; const result = await aggregateAcrossTeams( accountId, "viewings", "loop-viewing-search", async (apiKey, team) => { const depts: string[] = department === "both" ? ["sales", "lettings"] : [department]; const all: LoopViewingSummary[] = []; for (const dept of depts) { const qp: string[] = []; if (searchTerm) qp.push(`SearchTerm=${encodeURIComponent(searchTerm)}`); if (appointmentStartDate) qp.push(`AppointmentStartDate=${encodeURIComponent(appointmentStartDate)}`); if (appointmentEndDate) qp.push(`AppointmentEndDate=${encodeURIComponent(appointmentEndDate)}`); if (status) qp.push(`Status=${encodeURIComponent(status)}`); const query = qp.length > 0 ? `?${qp.join("&")}` : ""; const path = `/residential/${dept}/viewings${query}`; const data = await loopGet(apiKey, path, "loop-viewing-search", team); if (Array.isArray(data)) all.push(...data); } return all; }, { teamName, limitPerTeam: limit ?? 50, limitTotal: limit ?? 200 } ); return formatAggregationResult( result, (v) => { const addr = v.propertyAddress ?? "Unknown property"; const id = v.id != null ? ` [ID: ${v.id}]` : ""; // dateOfAppointment is ISO datetime e.g. "2026-04-10T15:30:00" const when = v.dateOfAppointment ? formatDateTime(v.dateOfAppointment) : "No date"; const viewStatus = v.status ? ` [${v.status}]` : ""; const buyer = v.buyerName ? ` — ${v.buyerName}` : ""; const viewType = v.type ? ` (${v.type})` : ""; return `- ${addr}${id} — ${when}${viewType}${buyer}${viewStatus}`; }, "viewings" ); } function formatDateTime(iso: string): string { const [datePart, timePart] = iso.split("T"); if (!timePart) return datePart; return `${datePart} ${timePart.slice(0, 5)}`; }