/** * Guides & Resources page (3.3) * * Guides (profiles shown on trip pages), vehicles, rooms and equipment, and * a schedule assigning them to trip dates with double-booking and seat * checks. UI shell in the free plugin; the endpoints come from the Yatra Pro * "Guides & Resources" module and only exist while it is enabled. * * @package Yatra */ import React, { useEffect, useMemo, useState } from "react"; import { useQuery, useQueryClient } from "@tanstack/react-query"; import { Users, Plus, Pencil, Trash2, CalendarDays, AlertTriangle, Sparkles, ImageIcon } from "lucide-react"; import { __, sprintf } from "../lib/i18n"; import { apiClient } from "../lib/api-client"; import { formatDate } from "../lib/dateFormat"; 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"; import { useWordPressMedia } from "../hooks/useWordPressMedia"; type ResourceType = "guide" | "vehicle" | "room" | "equipment" | "other"; interface Resource { id: number; type: ResourceType; name: string; photo_id: number | null; photo_url: string; bio: string; languages: string; experience_years: number | null; quantity: number; capacity: number | null; phone: string; email: string; notes: string; show_on_site: boolean; status: "active" | "inactive"; } interface Assignment { id: number; resource_id: number; resource_name: string; resource_type: ResourceType; capacity: number | null; trip_id: number; trip_title: string; start_date: string; end_date: string; quantity: number; note: string; booked_travellers: number; conflict: boolean; short_of_capacity: boolean; assigned_capacity: number | null; } const TYPE_LABELS: Record = { guide: __("Guide", "yatra"), vehicle: __("Vehicle", "yatra"), room: __("Room", "yatra"), equipment: __("Equipment", "yatra"), other: __("Other", "yatra"), }; const EMPTY: Omit = { type: "guide", name: "", photo_id: null, bio: "", languages: "", experience_years: null, quantity: 1, capacity: null, phone: "", email: "", notes: "", show_on_site: true, status: "active", }; const today = () => new Date().toISOString().slice(0, 10); const plusDays = (d: string, n: number) => { const t = new Date(d + "T12:00:00"); t.setDate(t.getDate() + n); return t.toISOString().slice(0, 10); }; const errorMessage = (e: any, fallback: string): string => (e && typeof e.message === "string" && e.message) || fallback; const GuidesResources: React.FC = () => { const queryClient = useQueryClient(); const { showToast } = useToast(); const toast = (type: "success" | "error", message: string) => showToast(message, type); const [moduleAvailable, setModuleAvailable] = useState(isModuleActive("guides_resources")); useEffect(() => { const sync = () => setModuleAvailable(isModuleActive("guides_resources")); window.addEventListener("yatra-modules-updated", sync); return () => window.removeEventListener("yatra-modules-updated", sync); }, []); const [tab, setTab] = useState<"resources" | "schedule">("resources"); const [typeFilter, setTypeFilter] = useState(""); const [editing, setEditing] = useState(null); const [formOpen, setFormOpen] = useState(false); const [form, setForm] = useState({ ...EMPTY }); const [photoUrl, setPhotoUrl] = useState(""); const [saving, setSaving] = useState(false); const [toDelete, setToDelete] = useState(null); const [from, setFrom] = useState(today()); const [to, setTo] = useState(plusDays(today(), 60)); const [assignOpen, setAssignOpen] = useState(false); const [assign, setAssign] = useState({ resource_id: "", trip_id: "", start_date: today(), end_date: "", quantity: "1", note: "" }); const [conflictAsk, setConflictAsk] = useState(""); const { openMediaLibrary } = useWordPressMedia({ title: __("Choose a photo", "yatra") }); const resourcesQuery = useQuery({ queryKey: ["resources"], queryFn: async () => await apiClient.get("/resources"), enabled: moduleAvailable, }); const resources: Resource[] = (resourcesQuery.data as any)?.data ?? []; const shown = useMemo(() => resources.filter((r) => !typeFilter || r.type === typeFilter), [resources, typeFilter]); const scheduleQuery = useQuery({ queryKey: ["resource-assignments", from, to], queryFn: async () => await apiClient.get("/resource-assignments", { params: { from, to } }), enabled: moduleAvailable && tab === "schedule", }); const schedule: Assignment[] = (scheduleQuery.data as any)?.data ?? []; const tripsQuery = useQuery({ queryKey: ["resources-trips"], queryFn: async () => { const res: any = await apiClient.get("/trips", { params: { per_page: 100, status: "publish" } }); const items: any[] = res?.data?.data || res?.data || res || []; return Array.isArray(items) ? items : []; }, enabled: moduleAvailable && assignOpen, }); if (!moduleAvailable) { return (

{__("Guides & Resources", "yatra")}

{__( "Guide profiles on your trip pages and a schedule for guides, vehicles, rooms and equipment. A Yatra Pro module — switch it on in Yatra → Modules.", "yatra", )}

); } const openCreate = () => { setEditing(null); setForm({ ...EMPTY, type: (typeFilter as ResourceType) || "guide" }); setPhotoUrl(""); setFormOpen(true); }; const openEdit = (r: Resource) => { setEditing(r); setForm({ ...r }); setPhotoUrl(r.photo_url); setFormOpen(true); }; const save = async () => { setSaving(true); try { if (editing) { await apiClient.post(`/resources/${editing.id}`, form); } else { await apiClient.post("/resources", form); } setFormOpen(false); queryClient.invalidateQueries({ queryKey: ["resources"] }); toast("success", __("Saved.", "yatra")); } catch (e) { toast("error", errorMessage(e, __("Could not save.", "yatra"))); } finally { setSaving(false); } }; const remove = async () => { if (!toDelete) return; try { await apiClient.delete(`/resources/${toDelete.id}`); queryClient.invalidateQueries({ queryKey: ["resources"] }); queryClient.invalidateQueries({ queryKey: ["resource-assignments"] }); } catch (e) { toast("error", errorMessage(e, __("Could not delete.", "yatra"))); } setToDelete(null); }; const submitAssign = async (force = false) => { try { await apiClient.post("/resource-assignments", { ...assign, quantity: parseInt(assign.quantity, 10) || 1, force }); setAssignOpen(false); setConflictAsk(""); queryClient.invalidateQueries({ queryKey: ["resource-assignments"] }); toast("success", __("Assigned.", "yatra")); } catch (e) { const msg = errorMessage(e, __("Could not assign.", "yatra")); if (!force && /already booked/i.test(msg)) { setConflictAsk(msg); } else { toast("error", msg); } } }; const unassign = async (a: Assignment) => { try { await apiClient.delete(`/resource-assignments/${a.id}`); queryClient.invalidateQueries({ queryKey: ["resource-assignments"] }); } catch (e) { toast("error", errorMessage(e, __("Could not remove.", "yatra"))); } }; const selectedResource = resources.find((r) => String(r.id) === assign.resource_id); const field = (key: string, value: any) => setForm((f: any) => ({ ...f, [key]: value })); return (
{__("Add", "yatra")} ) : ( ) } />
{([["resources", __("Guides & resources", "yatra"), Users], ["schedule", __("Schedule", "yatra"), CalendarDays]] as const).map(([key, label, Icon]) => ( ))}
{tab === "resources" && (
{resourcesQuery.isLoading ? (

{__("Loading…", "yatra")}

) : shown.length === 0 ? (

{__("Nothing here yet. Add your first guide, vehicle or room.", "yatra")}

) : ( {shown.map((r) => ( ))}
{__("Name", "yatra")} {__("Type", "yatra")} {__("Details", "yatra")} {__("Status", "yatra")}
{r.name} {TYPE_LABELS[r.type]} {r.type === "guide" ? [r.languages, r.experience_years ? sprintf(__("%d years", "yatra"), r.experience_years) : ""].filter(Boolean).join(" · ") : [r.quantity > 1 ? sprintf(__("%d units", "yatra"), r.quantity) : "", r.capacity ? sprintf(__("%d seats/beds each", "yatra"), r.capacity) : ""].filter(Boolean).join(" · ")} {r.status === "active" ? __("Active", "yatra") : __("Inactive", "yatra")}
)}
)} {tab === "schedule" && (
setFrom(e.target.value)} />
setTo(e.target.value)} />
{scheduleQuery.isLoading ? (

{__("Loading…", "yatra")}

) : schedule.length === 0 ? (

{__("Nothing assigned in these dates.", "yatra")}

) : ( {schedule.map((a) => ( ))}
{__("Dates", "yatra")} {__("Trip", "yatra")} {__("Assigned", "yatra")} {__("Travellers", "yatra")}
{formatDate(a.start_date)} {a.end_date !== a.start_date ? ` – ${formatDate(a.end_date)}` : ""} {a.trip_title} {a.resource_name} {a.quantity > 1 ? ` × ${a.quantity}` : ""}{" "} ({TYPE_LABELS[a.resource_type]}) {a.conflict && ( {__("Double-booked", "yatra")} )} {a.booked_travellers} {a.short_of_capacity && a.assigned_capacity !== null && ( {sprintf(__("only %d seats/beds", "yatra"), a.assigned_capacity)} )}
)}
)} setFormOpen(false)} title={editing ? __("Edit", "yatra") : __("Add a guide or resource", "yatra")} size="lg" footer={
} >
field("name", e.target.value)} />
{form.type === "guide" ? ( <>
field("languages", e.target.value)} />
field("experience_years", e.target.value === "" ? null : parseInt(e.target.value, 10))} />