/** * Booking workspace (3.2): the actions an operator takes on one booking — * record a payment, record a refund, change the price — and the booking's * history with internal notes. Server: /bookings/{id}/activity, /notes, * /adjustments, /payments, /payments/{id}/refund. */ import React, { useEffect, useMemo, useState } from "react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { ArrowDownLeft, CircleDollarSign, Clock, Edit3, Inbox, Link2, Mail, MessageSquare, Percent, Plus, RefreshCcw, Sparkles, XCircle, } from "lucide-react"; import { apiClient } from "../../lib/api-client"; import { __, sprintf } from "../../lib/i18n"; import { formatYatraMoney } from "../../lib/currency-display"; import { Button } from "../ui/button"; import { Card, CardContent, CardHeader, CardTitle } from "../ui/card"; import { Modal } from "../ui/modal"; import { Input } from "../ui/input"; import { Label } from "../ui/label"; import { useToast } from "../ui/toast"; import { ConditionalRender } from "../ui/conditional-render"; type TimelineEvent = { id: string; type: string; message: string; author: string; at: string; meta: Record; }; const money = (n: number, currency?: string) => formatYatraMoney(Number(n) || 0, currency || "USD", { zeroAsUnknown: false }); const errorMessage = (e: any, fallback: string) => e?.response?.data?.message || e?.message || fallback; /** Refresh everything on the booking screen that money actions change. */ const useRefresh = (bookingId: number) => { const qc = useQueryClient(); return () => { qc.invalidateQueries({ queryKey: ["booking", String(bookingId)] }); qc.invalidateQueries({ queryKey: ["booking", bookingId] }); qc.invalidateQueries({ queryKey: ["booking-activity", bookingId] }); qc.invalidateQueries({ queryKey: ["bookings"] }); }; }; // --------------------------------------------------------------------------- // Record payment // --------------------------------------------------------------------------- const METHODS: { value: string; label: () => string }[] = [ { value: "bank_transfer", label: () => __("Bank transfer", "yatra") }, { value: "cash", label: () => __("Cash", "yatra") }, { value: "card_terminal", label: () => __("Card (terminal)", "yatra") }, { value: "cheque", label: () => __("Cheque", "yatra") }, { value: "other", label: () => __("Other", "yatra") }, ]; export const RecordPaymentButton: React.FC<{ bookingId: number; amountDue: number; currency?: string; }> = ({ bookingId, amountDue, currency }) => { const { showToast } = useToast(); const refresh = useRefresh(bookingId); const [open, setOpen] = useState(false); const [amount, setAmount] = useState(""); const [method, setMethod] = useState("bank_transfer"); const [reference, setReference] = useState(""); const [note, setNote] = useState(""); const start = () => { setAmount(amountDue > 0 ? amountDue.toFixed(2) : ""); setMethod("bank_transfer"); setReference(""); setNote(""); setOpen(true); }; const mutation = useMutation({ mutationFn: async () => apiClient.post(`/bookings/${bookingId}/payments`, { amount: Number(amount), status: "completed", gateway: method, payment_method: method, transaction_id: reference.trim() || undefined, notes: note.trim() || undefined, }), onSuccess: () => { showToast(__("Payment recorded.", "yatra"), "success"); setOpen(false); refresh(); }, onError: (e: any) => showToast(errorMessage(e, __("The payment could not be recorded.", "yatra")), "error"), }); // The server refuses more than the balance due; say so before submitting. const overDue = Number(amount) > Math.max(0, amountDue) + 0.009; const valid = Number(amount) > 0 && !overDue; return ( <> setOpen(false)} size="sm" title={__("Record a payment", "yatra")} description={__( "Money you received outside online checkout — a bank transfer, cash at the office, a card terminal. The booking's balance and payment status update straight away, and the customer gets the payment receipt email if it is switched on.", "yatra", )} footer={
} >
setAmount(e.target.value)} data-testid="record-payment-amount" />

{overDue ? sprintf( __("More than the balance due (%s). Use Adjust price first if the customer owes more.", "yatra"), money(Math.max(0, amountDue), currency), ) : sprintf(__("Balance due: %s", "yatra"), money(amountDue, currency))}

setReference(e.target.value)} placeholder={__("e.g. bank reference or receipt number", "yatra")} />
setNote(e.target.value)} />
); }; // --------------------------------------------------------------------------- // Payment link // --------------------------------------------------------------------------- interface PaymentLinkRow { id: string; amount: number; note: string; status: "open" | "paid" | "cancelled" | "expired"; created_at: string; expires_at: string; paid_at: string; } /** * Ask the customer to pay part (or all) of the balance: a link to Yatra's * balance checkout for that amount, copied or emailed. */ export const PaymentLinkButton: React.FC<{ bookingId: number; amountDue: number; currency?: string; }> = ({ bookingId, amountDue, currency }) => { const { showToast } = useToast(); const queryClient = useQueryClient(); const [open, setOpen] = useState(false); const [amount, setAmount] = useState(""); const [note, setNote] = useState(""); const [sendEmail, setSendEmail] = useState(true); const [created, setCreated] = useState(""); const links = useQuery({ queryKey: ["booking-payment-links", bookingId], queryFn: async () => { const res: any = await apiClient.get(`/bookings/${bookingId}/payment-links`); return { rows: (res?.data || []) as PaymentLinkRow[], // Older Free builds don't send it: assume payable. canPayOnline: res?.can_pay_online !== false, }; }, enabled: open, }); const rows = links.data?.rows || []; const canPayOnline = links.data ? links.data.canPayOnline : true; // Open links already ask for part of the balance; together they may not exceed it. const requested = rows.filter((l) => l.status === "open").reduce((sum, l) => sum + Number(l.amount || 0), 0); const requestable = Math.max(0, Math.max(0, amountDue) - requested); // Suggest what is still unrequested once the open links are known. useEffect(() => { if (open && links.data && !created && requested > 0 && amount === (amountDue > 0 ? amountDue.toFixed(2) : "")) { setAmount(requestable > 0 ? requestable.toFixed(2) : ""); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [open, links.data]); const start = () => { setAmount(amountDue > 0 ? amountDue.toFixed(2) : ""); setNote(""); setSendEmail(true); setCreated(""); setOpen(true); }; const create = useMutation({ mutationFn: async () => apiClient.post(`/bookings/${bookingId}/payment-links`, { amount: Number(amount), note: note.trim(), send_email: sendEmail, }), onSuccess: (res: any) => { setCreated(String(res?.url || "")); showToast(sendEmail ? __("Payment link created and emailed.", "yatra") : __("Payment link created.", "yatra"), "success"); queryClient.invalidateQueries({ queryKey: ["booking-payment-links", bookingId] }); queryClient.invalidateQueries({ queryKey: ["booking-activity", bookingId] }); }, onError: (e: any) => showToast(errorMessage(e, __("The payment link could not be created.", "yatra")), "error"), }); const cancel = useMutation({ mutationFn: async (id: string) => apiClient.delete(`/bookings/${bookingId}/payment-links/${id}`), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ["booking-payment-links", bookingId] }); queryClient.invalidateQueries({ queryKey: ["booking-activity", bookingId] }); }, onError: (e: any) => showToast(errorMessage(e, __("The link could not be cancelled.", "yatra")), "error"), }); const n = Number(amount); const over = n > requestable + 0.009; const valid = n > 0 && !over && canPayOnline; const statusLabel = (s: PaymentLinkRow["status"]) => s === "paid" ? __("Paid", "yatra") : s === "cancelled" ? __("Cancelled", "yatra") : s === "expired" ? __("Expired", "yatra") : __("Waiting for payment", "yatra"); return ( <> setOpen(false)} size="sm" title={__("Request a payment", "yatra")} description={__( "A link the customer opens to pay this amount by card or PayPal — part of the balance or all of it. It works once and expires after 14 days.", "yatra", )} footer={
} >
setAmount(e.target.value)} data-testid="payment-link-amount" />

{over ? requested > 0 ? sprintf( __("Open links already ask for %1$s. You can ask for at most %2$s more.", "yatra"), money(requested, currency), money(requestable, currency), ) : sprintf(__("More than the balance due (%s).", "yatra"), money(Math.max(0, amountDue), currency)) : requested > 0 ? sprintf( __("Balance due: %1$s · already requested by open links: %2$s", "yatra"), money(amountDue, currency), money(requested, currency), ) : sprintf(__("Balance due: %s", "yatra"), money(amountDue, currency))}

{!canPayOnline && (

{__( "No online payment method is turned on, so the customer could not pay a link. Turn on a card or PayPal payment method in Settings → Payments first.", "yatra", )}

)}
setNote(e.target.value)} placeholder={__("e.g. Second instalment", "yatra")} />
{created && (
{__("Link created", "yatra")}
{created}
)} {rows.length > 0 && (
{__("Links for this booking", "yatra")}
    {rows.map((l) => (
  • {money(l.amount, currency)} · {statusLabel(l.status)} {l.status === "open" && ( )}
  • ))}
)}
); }; // --------------------------------------------------------------------------- // Price adjustment // --------------------------------------------------------------------------- export const AdjustPriceButton: React.FC<{ bookingId: number; total: number; currency?: string; }> = ({ bookingId, total, currency }) => { const { showToast } = useToast(); const refresh = useRefresh(bookingId); const [open, setOpen] = useState(false); const [kind, setKind] = useState<"discount" | "surcharge">("discount"); const [amount, setAmount] = useState(""); const [reason, setReason] = useState(""); const mutation = useMutation({ mutationFn: async () => { const res: any = await apiClient.post(`/bookings/${bookingId}/adjustments`, { kind, amount: Number(amount), reason: reason.trim(), }); if (res && res.success === false) throw new Error(res.message); return res; }, onSuccess: (res: any) => { showToast(res?.message || __("Price updated.", "yatra"), "success"); setOpen(false); setAmount(""); setReason(""); refresh(); }, onError: (e: any) => showToast(errorMessage(e, __("The price could not be changed.", "yatra")), "error"), }); const n = Number(amount); const newTotal = kind === "discount" ? total - n : total + n; const valid = n > 0 && reason.trim() !== "" && (kind === "surcharge" || n <= total); return ( <> setOpen(false)} size="sm" title={__("Adjust the price", "yatra")} description={__( "Give a discount or add a surcharge after the booking was made. The total, balance due and payment status update, and the change is kept in the booking history with your reason.", "yatra", )} footer={
} >
{(["discount", "surcharge"] as const).map((k) => ( ))}
setAmount(e.target.value)} data-testid="adjust-price-amount" /> {n > 0 && (

{sprintf(__("New total: %1$s (was %2$s)", "yatra"), money(newTotal, currency), money(total, currency))}

)}
setReason(e.target.value)} placeholder={__("e.g. Repeat customer, single room", "yatra")} data-testid="adjust-price-reason" />
); }; // --------------------------------------------------------------------------- // Refund // --------------------------------------------------------------------------- export const RefundPaymentButton: React.FC<{ bookingId: number; paymentId: number; maxAmount: number; currency?: string; /** The payment's gateway can send the money back (Yatra 3.2+). */ gatewayRefundAvailable?: boolean; gatewayLabel?: string; }> = ({ bookingId, paymentId, maxAmount, currency, gatewayRefundAvailable, gatewayLabel }) => { const { showToast } = useToast(); const refresh = useRefresh(bookingId); const [open, setOpen] = useState(false); const [amount, setAmount] = useState(""); const [reason, setReason] = useState(""); const [throughGateway, setThroughGateway] = useState(false); const mutation = useMutation({ mutationFn: async () => { const res: any = await apiClient.post(`/payments/${paymentId}/refund`, { amount: Number(amount), reason: reason.trim(), through_gateway: Boolean(gatewayRefundAvailable && throughGateway), }); if (res && res.success === false) throw new Error(res.message); return res; }, onSuccess: (res: any) => { showToast( res?.message || (res?.through_gateway ? __("Refund sent to the customer and recorded.", "yatra") : __("Refund recorded.", "yatra")), res?.pending ? "warning" : "success", ); setOpen(false); refresh(); }, onError: (e: any) => showToast(errorMessage(e, __("The refund could not be recorded.", "yatra")), "error"), }); const n = Number(amount); const valid = n > 0 && n <= maxAmount; return ( setOpen(false)} size="sm" title={__("Refund", "yatra")} description={ gatewayRefundAvailable && throughGateway ? sprintf( __( "Sends the money back to the customer through %s, then records the refund in the booking's ledger. The original payment is kept.", "yatra", ), gatewayLabel || __("the payment provider", "yatra"), ) : __( "Records money you sent back to the customer. Send the money itself from your payment provider or bank — Yatra keeps the original payment and adds the refund to the booking's ledger.", "yatra", ) } footer={
} >
setAmount(e.target.value)} data-testid="refund-amount" />

{sprintf(__("Up to %s", "yatra"), money(maxAmount, currency))}

setReason(e.target.value)} data-testid="refund-reason" />
{gatewayRefundAvailable && ( )}
); }; // --------------------------------------------------------------------------- // History + notes // --------------------------------------------------------------------------- const ICONS: Record = { created: , payment: , refund: , status_changed: , email_sent: , note: , price_adjusted: , edited: , expired: , customer_request: , }; const COLORS: Record = { payment: "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300", refund: "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300", note: "bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300", expired: "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300", customer_request: "bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300", }; // --------------------------------------------------------------------------- // Change / cancellation requests sent by the customer from their account // --------------------------------------------------------------------------- export interface CustomerRequest { id: string; type: "cancel" | "change"; message: string; status: "open" | "resolved"; created_at: string; } export const CustomerRequestsCard: React.FC<{ bookingId: number; requests: CustomerRequest[]; }> = ({ bookingId, requests }) => { const { showToast } = useToast(); const refresh = useRefresh(bookingId); const open = (requests || []).filter((r) => r.status === "open"); const resolve = useMutation({ mutationFn: async (requestId: string) => { const res: any = await apiClient.post( `/bookings/${bookingId}/requests/${requestId}/resolve`, {}, ); if (res && res.success === false) throw new Error(res.message); return res; }, onSuccess: (res: any) => { showToast(res?.message || __("Request marked as resolved.", "yatra"), "success"); refresh(); }, onError: (e: any) => showToast(errorMessage(e, __("The request could not be updated.", "yatra")), "error"), }); if (open.length === 0) return null; return ( {__("Customer requests", "yatra")} {open.map((r) => (
{r.type === "cancel" ? __("Cancellation requested", "yatra") : __("Change requested", "yatra")}
{r.created_at}

{r.message}

))}

{__( "Nothing has been changed yet. Cancel, refund or edit the booking as your policy allows, reply to the customer, then mark the request as resolved.", "yatra", )}

); }; export const BookingActivityCard: React.FC<{ bookingId: number }> = ({ bookingId }) => { const { showToast } = useToast(); const qc = useQueryClient(); const [note, setNote] = useState(""); const [showAll, setShowAll] = useState(false); const { data, isLoading } = useQuery({ queryKey: ["booking-activity", bookingId], queryFn: async () => { const res: any = await apiClient.get(`/bookings/${bookingId}/activity`); return (res?.data ?? []) as TimelineEvent[]; }, enabled: bookingId > 0, }); const addNote = useMutation({ mutationFn: async () => { const res: any = await apiClient.post(`/bookings/${bookingId}/notes`, { note: note.trim() }); if (res && res.success === false) throw new Error(res.message); return res; }, onSuccess: () => { setNote(""); qc.invalidateQueries({ queryKey: ["booking-activity", bookingId] }); }, onError: (e: any) => showToast(errorMessage(e, __("The note could not be saved.", "yatra")), "error"), }); const events = useMemo(() => data ?? [], [data]); const shown = useMemo(() => (showAll ? events : events.slice(0, 8)), [events, showAll]); return ( {__("History & notes", "yatra")}