/** * Travel Agencies page * * Agencies (contact + billing details, agency code, pay-by-invoice terms), * monthly statements (PDF, email, record one payment across the month's * bookings) and who receives which email for an agency booking. * * UI shell in the free plugin; every endpoint is registered by the Yatra Pro * "Travel Agencies" module and only exists while that module is enabled. * * @package Yatra */ import React, { useEffect, useMemo, useState } from "react"; import { useQuery, useQueryClient } from "@tanstack/react-query"; import { Briefcase, Plus, KeyRound, FileText, Mail, Banknote, Download, Archive, Pencil, Copy, Sparkles, ArrowRight, } from "lucide-react"; import { __, sprintf } from "../lib/i18n"; import { apiClient } from "../lib/api-client"; import { formatDate } from "../lib/dateFormat"; import { formatYatraMoney } from "../lib/currency-display"; import { usePermissions } from "../hooks/usePermissions"; import { useToast } from "../components/ui/toast"; import { Badge } from "../components/ui/badge"; import { Button } from "../components/ui/button"; import { Input } from "../components/ui/input"; import { Label } from "../components/ui/label"; import { Select } from "../components/ui/select"; import { Modal } from "../components/ui/modal"; import { ConfirmationDialog } from "../components/ui/confirmation-dialog"; import { Card, CardContent } from "../components/ui/card"; import { PageHeader } from "../components/common/PageHeader"; import { isModuleActive } from "../lib/plugin-utils"; interface AgencyUser { id: number; login: string; email: string; name: string; } interface Agency { id: number; name: string; contact_name: string; email: string; billing_email: string; phone: string; billing_address: string; vat_number: string; payment_terms: "invoice" | "standard"; has_code: boolean; code_hint: string; user_ids: number[]; users?: AgencyUser[]; notes: string; status: string; bookings_count: number; } interface StatementRow { booking_id: number; reference: string; travel_date: string; guest: string; trip: string; travelers: number; status: string; currency: string; total: number; paid: number; due: number; } interface Statement { number: string; month: string; rows: StatementRow[]; totals: Record; } type Tab = "agencies" | "statements" | "emails"; type Routing = Record<"booking" | "payment" | "trip", "agency" | "guest" | "both">; const EMPTY_FORM = { name: "", contact_name: "", email: "", billing_email: "", phone: "", billing_address: "", vat_number: "", payment_terms: "invoice" as "invoice" | "standard", users: "", notes: "", }; const thisMonth = (): string => { const d = new Date(); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`; }; const money = (n: number, c: string) => formatYatraMoney(Number(n) || 0, c || (window as any)?.yatraAdmin?.currency || "USD", { zeroAsUnknown: false, }); const errorMessage = (e: any, fallback: string): string => (e && typeof e.message === "string" && e.message) || fallback; const UpgradeCard: React.FC = () => (

{__("Travel Agencies", "yatra")}

{__( "Take bookings from travel agencies for their clients: agency billing details kept apart from the guest's, tour emails to the guest and booking and payment emails to the agency, pay by invoice, and one monthly statement settled with a single payment. Available on the Growth and Scale plans — switch it on in Yatra → Modules.", "yatra", )}

); const TravelAgencies: React.FC = () => { const { can } = usePermissions(); const { showToast } = useToast(); const queryClient = useQueryClient(); const canEdit = can("yatra_edit_bookings"); const [moduleAvailable, setModuleAvailable] = useState(() => isModuleActive("travel_agency"), ); useEffect(() => { const sync = () => setModuleAvailable(isModuleActive("travel_agency")); window.addEventListener("yatra-modules-updated", sync); window.addEventListener("yatra-force-nav-refresh", sync); return () => { window.removeEventListener("yatra-modules-updated", sync); window.removeEventListener("yatra-force-nav-refresh", sync); }; }, []); const [tab, setTab] = useState("agencies"); const [showArchived, setShowArchived] = useState(false); // Agency form const [editing, setEditing] = useState(null); const [formOpen, setFormOpen] = useState(false); const [form, setForm] = useState({ ...EMPTY_FORM }); const [saving, setSaving] = useState(false); const [newCode, setNewCode] = useState<{ agency: string; code: string } | null>(null); const [toArchive, setToArchive] = useState(null); const [toRotate, setToRotate] = useState(null); // Statements const [stAgency, setStAgency] = useState(0); const [stMonth, setStMonth] = useState(thisMonth()); const [payOpen, setPayOpen] = useState(false); const [pay, setPay] = useState({ amount: "", method: "bank_transfer", reference: "", date: "" }); const [busy, setBusy] = useState(""); // Routing const [routing, setRouting] = useState(null); const agenciesQuery = useQuery({ queryKey: ["travel-agencies", showArchived], queryFn: async () => await apiClient.get("/travel-agencies", { params: showArchived ? { archived: 1 } : {} }), enabled: moduleAvailable, }); const agencies: Agency[] = (agenciesQuery.data as any)?.data ?? []; const activeAgencies = useMemo(() => agencies.filter((a) => a.status === "active"), [agencies]); useEffect(() => { if (!stAgency && activeAgencies.length > 0) { setStAgency(activeAgencies[0].id); } }, [activeAgencies, stAgency]); const statementQuery = useQuery({ queryKey: ["travel-agency-statement", stAgency, stMonth], queryFn: async () => await apiClient.get(`/travel-agencies/${stAgency}/statement`, { params: { month: stMonth } }), enabled: moduleAvailable && tab === "statements" && stAgency > 0, }); const statement: Statement | null = (statementQuery.data as any)?.data ?? null; const settingsQuery = useQuery({ queryKey: ["travel-agency-settings"], queryFn: async () => await apiClient.get("/travel-agencies/settings"), enabled: moduleAvailable && tab === "emails", }); useEffect(() => { const r = (settingsQuery.data as any)?.data?.routing; if (r) setRouting(r); }, [settingsQuery.data]); if (!moduleAvailable) { return ; } const refreshAgencies = () => queryClient.invalidateQueries({ queryKey: ["travel-agencies"] }); const refreshStatement = () => queryClient.invalidateQueries({ queryKey: ["travel-agency-statement"] }); const openCreate = () => { setEditing(null); setForm({ ...EMPTY_FORM }); setFormOpen(true); }; const openEdit = (a: Agency) => { setEditing(a); setForm({ name: a.name, contact_name: a.contact_name, email: a.email, billing_email: a.billing_email, phone: a.phone, billing_address: a.billing_address, vat_number: a.vat_number, payment_terms: a.payment_terms, users: (a.users ?? []).map((u) => u.login).join(", "), notes: a.notes, }); setFormOpen(true); }; const saveAgency = async () => { setSaving(true); try { const res: any = editing ? await apiClient.post(`/travel-agencies/${editing.id}`, form) : await apiClient.post("/travel-agencies", form); setFormOpen(false); if (!editing && res?.code) { setNewCode({ agency: res.data?.name ?? form.name, code: res.code }); } showToast(editing ? __("Agency saved.", "yatra") : __("Agency added.", "yatra"), "success"); refreshAgencies(); } catch (e) { showToast(errorMessage(e, __("The agency could not be saved.", "yatra")), "error"); } finally { setSaving(false); } }; const rotateCode = async (a: Agency) => { try { const res: any = await apiClient.post(`/travel-agencies/${a.id}/code`, {}); setNewCode({ agency: a.name, code: res.code }); refreshAgencies(); } catch (e) { showToast(errorMessage(e, __("A new code could not be created.", "yatra")), "error"); } finally { setToRotate(null); } }; const archiveAgency = async (a: Agency) => { try { const res: any = await apiClient.delete(`/travel-agencies/${a.id}`); showToast(res?.message || __("Agency archived.", "yatra"), "success"); refreshAgencies(); } catch (e) { showToast(errorMessage(e, __("The agency could not be archived.", "yatra")), "error"); } finally { setToArchive(null); } }; const downloadPdf = async () => { setBusy("pdf"); try { const blob = await apiClient.getBlob(`/travel-agencies/${stAgency}/statement/pdf`, { params: { month: stMonth }, }); const url = URL.createObjectURL(blob); const link = document.createElement("a"); link.href = url; const isPdf = blob.type.includes("pdf"); link.download = `${statement?.number || "statement"}.${isPdf ? "pdf" : "html"}`; document.body.appendChild(link); link.click(); link.remove(); setTimeout(() => URL.revokeObjectURL(url), 2000); } catch (e) { showToast(errorMessage(e, __("The statement could not be downloaded.", "yatra")), "error"); } finally { setBusy(""); } }; const emailStatement = async () => { setBusy("email"); try { const res: any = await apiClient.post( `/travel-agencies/${stAgency}/statement/email?month=${encodeURIComponent(stMonth)}`, {}, ); showToast(res?.message || __("Statement emailed to the agency.", "yatra"), "success"); } catch (e) { showToast(errorMessage(e, __("The statement could not be emailed.", "yatra")), "error"); } finally { setBusy(""); } }; const recordPayment = async () => { setBusy("pay"); try { const res: any = await apiClient.post( `/travel-agencies/${stAgency}/statement/payment?month=${encodeURIComponent(stMonth)}`, { ...pay, amount: Number(pay.amount) }, ); showToast( res?.message || __("Payment recorded.", "yatra"), res?.partial ? "warning" : "success", res?.partial ? 10000 : undefined, ); setPayOpen(false); setPay({ amount: "", method: "bank_transfer", reference: "", date: "" }); refreshStatement(); queryClient.invalidateQueries({ queryKey: ["bookings"] }); queryClient.invalidateQueries({ queryKey: ["payments"] }); } catch (e) { showToast(errorMessage(e, __("The payment could not be recorded.", "yatra")), "error"); } finally { setBusy(""); } }; const saveRouting = async () => { if (!routing) return; setBusy("routing"); try { await apiClient.post("/travel-agencies/settings", { routing }); showToast(__("Email settings saved.", "yatra"), "success"); queryClient.invalidateQueries({ queryKey: ["travel-agency-settings"] }); } catch (e) { showToast(errorMessage(e, __("The settings could not be saved.", "yatra")), "error"); } finally { setBusy(""); } }; const field = (key: keyof typeof EMPTY_FORM, label: string, props: any = {}) => (
setForm({ ...form, [key]: e.target.value })} {...props} />
); const tabButton = (key: Tab, label: string, Icon: any) => ( ); const openDue = statement ? Object.entries(statement.totals).filter(([, t]) => t.due > 0.004) : []; const routingRow = (group: keyof Routing, title: string, help: string) => (
{title}
{help}
); return (
{__("Add agency", "yatra")} ) : null } />
{tabButton("agencies", __("Agencies", "yatra"), Briefcase)} {tabButton("statements", __("Statements", "yatra"), FileText)} {tabButton("emails", __("Emails", "yatra"), Mail)}
{tab === "agencies" && (
{agenciesQuery.isLoading ? (
{__("Loading…", "yatra")}
) : agencies.length === 0 ? (

{__("No agencies yet. Add an agency to give it an agency code for checkout.", "yatra")}

) : (
{agencies.map((a) => ( ))}
{__("Agency", "yatra")} {__("Billing", "yatra")} {__("Payment terms", "yatra")} {__("Agency code", "yatra")} {__("Bookings", "yatra")}
{a.name}
{[a.contact_name, a.email, a.phone].filter(Boolean).join(" · ")}
{a.users && a.users.length > 0 ? (
{sprintf( /* translators: %s: list of WordPress users. */ __("Signs in as: %s", "yatra"), a.users.map((u) => u.login).join(", "), )}
) : null}
{a.billing_email || a.email}
{a.vat_number ? (
{__("VAT", "yatra")}: {a.vat_number}
) : null}
{a.payment_terms === "invoice" ? ( {__("Pay by invoice", "yatra")} ) : ( {__("Pays at checkout", "yatra")} )} {a.status !== "active" ? ( {__("Archived", "yatra")} ) : null} {a.has_code ? `AG-····-${a.code_hint}` : "—"} {a.bookings_count} {canEdit && a.status === "active" ? (
) : null}
)}
)} {tab === "statements" && ( {activeAgencies.length === 0 && agencies.length === 0 ? (

{__("Add an agency first.", "yatra")}

) : ( <>
e.target.value && setStMonth(e.target.value)} />
{canEdit ? ( <> ) : null}
{statementQuery.isLoading ? (
{__("Loading…", "yatra")}
) : !statement || statement.rows.length === 0 ? (

{__("No tours travelled in this month.", "yatra")}

) : (
{sprintf( /* translators: %s: statement number. */ __("Statement %s", "yatra"), statement.number, )}
{statement.rows.map((r) => ( ))} {Object.entries(statement.totals).map(([cur, t]) => ( ))}
{__("Date", "yatra")} {__("Booking", "yatra")} {__("Guest", "yatra")} {__("Tour", "yatra")} {__("Total", "yatra")} {__("Paid", "yatra")} {__("Due", "yatra")}
{formatDate(r.travel_date)} {r.reference} {r.guest} {r.travelers > 1 ? ×{r.travelers} : null} {r.trip} {money(r.total, r.currency)} {money(r.paid, r.currency)} {money(r.due, r.currency)}
{__("Total", "yatra")} {Object.keys(statement.totals).length > 1 ? ` (${cur})` : ""} {money(t.total, cur)} {money(t.paid, cur)} {money(t.due, cur)}
)} )}
)} {tab === "emails" && (

{__( "For bookings made by an agency, choose who receives each kind of email. Your own admin copies are not affected.", "yatra", )}

{routingRow( "booking", __("Booking emails", "yatra"), __("Booking confirmation (with prices), cancellations and expiry.", "yatra"), )} {routingRow( "payment", __("Payment emails", "yatra"), __("Payment receipts, balance reminders, payment links. Sent to the agency's billing email.", "yatra"), )} {routingRow( "trip", __("Tour emails", "yatra"), __("Pickup reminder before the tour, consent forms, review request.", "yatra"), )} {canEdit ? (
) : null}
)} setFormOpen(false)} title={editing ? __("Edit agency", "yatra") : __("Add agency", "yatra")} size="lg" footer={
} >
{field("name", __("Agency name", "yatra"), { required: true })} {field("contact_name", __("Contact person", "yatra"))} {field("email", __("Email", "yatra"), { type: "email", required: true })} {field("billing_email", __("Billing email (invoices and receipts)", "yatra"), { type: "email" })} {field("phone", __("Phone", "yatra"))} {field("vat_number", __("VAT / tax number", "yatra"))}