import React, { useEffect, useRef, useState } from "react"; import { useToast } from "../ui/toast"; import { Card } from "../ui/card"; import { Button } from "../ui/button"; import { Badge } from "../ui/badge"; import { __, sprintf, brandName } from "../../lib/i18n"; import { apiService } from "../../lib/api-client"; import { AlertCircle, AlertTriangle, CheckCircle, ExternalLink, Info, Pencil, Play, RefreshCw, Search, Shuffle, XCircle, } from "lucide-react"; interface WteDetect { has_data: boolean; wte_active: boolean; wte_version: string; trips: number; terms: Record; bookings: number; customers: number; enquiries: number; imported_trips: number; batch_size: number; last_run: { offset?: number; total?: number; done?: boolean; updated_at?: string; }; } interface WteScanTrip { wte_id: number; title: string; status: string; action: "create" | "update"; trip_id: number; itinerary_days: number; faqs: number; pricing: string; price: number; warnings: string[]; } interface WteScan { trips_total: number; counts: { create: number; update: number; warnings: number }; terms: Record< string, { total: number; mapped: number; matched: number; create: number } >; notes: string[]; not_imported: string[]; trips: WteScanTrip[]; } interface WteTripResult { wte_id: number; title: string; action: "created" | "updated" | "skipped" | "failed"; trip_id: number; edit_url: string; view_url: string; warnings: string[]; error: string; } interface WteBatch { total: number; offset: number; next_offset: number; done: boolean; totals: { created: number; updated: number; skipped: number; failed: number }; results: WteTripResult[]; } const taxonomyLabel = (taxonomy: string): string => { switch (taxonomy) { case "destination": return __("Destinations", "yatra"); case "activities": return __("Activities", "yatra"); case "trip_types": return __("Trip types → Categories", "yatra"); case "difficulty": return __("Difficulty levels", "yatra"); case "trip-packages-categories": return __("Traveller categories", "yatra"); default: return taxonomy; } }; const actionBadge = (action: WteTripResult["action"]) => { switch (action) { case "created": return {__("Created", "yatra")}; case "updated": return {__("Updated", "yatra")}; case "skipped": return {__("Skipped", "yatra")}; default: return {__("Failed", "yatra")}; } }; /** * Tools > Import from WP Travel Engine. * * Detect -> Scan (dry run) -> Import (terms, then trips in batches). WP Travel * Engine data is only read by the server; nothing is changed or deleted. */ const WteImport: React.FC = () => { const { showToast } = useToast(); const brand = brandName(); const [detect, setDetect] = useState(null); const [loading, setLoading] = useState(true); const [scan, setScan] = useState(null); const [isScanning, setIsScanning] = useState(false); const [isImporting, setIsImporting] = useState(false); const [updateExisting, setUpdateExisting] = useState(false); const [progress, setProgress] = useState({ done: 0, total: 0 }); const [results, setResults] = useState([]); const [termErrors, setTermErrors] = useState([]); const [totals, setTotals] = useState(null); const [stage, setStage] = useState<"" | "terms" | "trips" | "done">(""); const cancelRef = useRef(false); const loadDetect = async () => { setLoading(true); try { const data = (await apiService.detectWteData()) as WteDetect; setDetect(data); } catch (error: any) { showToast( error?.message || __("Could not check for WP Travel Engine data.", "yatra"), "error", ); } finally { setLoading(false); } }; useEffect(() => { loadDetect(); return () => { cancelRef.current = true; }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const runScan = async () => { setIsScanning(true); try { const data = (await apiService.scanWteData()) as WteScan; setScan(data); } catch (error: any) { showToast(error?.message || __("Scan failed.", "yatra"), "error"); } finally { setIsScanning(false); } }; const runImport = async (startOffset = 0) => { if (!detect) return; cancelRef.current = false; setIsImporting(true); if (startOffset === 0) { setResults([]); setTotals(null); } setProgress({ done: startOffset, total: detect.trips }); try { setStage("terms"); const termResult: any = await apiService.importWteTerms(); // Destinations / activities / trip types that couldn't be created. const errs: string[] = []; Object.values((termResult?.data ?? termResult) || {}).forEach((t: any) => { if (t && Array.isArray(t.errors)) errs.push(...t.errors.map(String)); }); setTermErrors(errs); setStage("trips"); let offset = startOffset; while (true) { if (cancelRef.current) break; const batch = (await apiService.importWteTrips({ offset, limit: detect.batch_size || 10, update_existing: updateExisting, })) as WteBatch; setResults((prev) => [...prev, ...batch.results]); setTotals(batch.totals); setProgress({ done: batch.next_offset, total: batch.total }); if (batch.done || batch.next_offset <= offset) break; offset = batch.next_offset; } if (!cancelRef.current) { setStage("done"); showToast(__("WP Travel Engine import finished.", "yatra"), "success"); } loadDetect(); } catch (error: any) { setStage(""); showToast( error?.message || __("Import stopped. You can resume where it left off.", "yatra"), "error", ); loadDetect(); } finally { setIsImporting(false); } }; const percent = progress.total > 0 ? Math.min(100, Math.round((progress.done / progress.total) * 100)) : 0; const canResume = !isImporting && stage !== "done" && !!detect?.last_run && detect.last_run.done === false && (detect.last_run.offset || 0) > 0; if (loading && !detect) { return (
{__("Looking for WP Travel Engine data...", "yatra")}
); } if (!detect || !detect.has_data) { return (

{__("Import from WP Travel Engine", "yatra")}

{__( "No WP Travel Engine trips were found on this site. Once WP Travel Engine data is present (the plugin does not need to be active), you can import it here.", "yatra", )}

); } return (

{__("Import from WP Travel Engine", "yatra")}

{sprintf( __( "Copy your WP Travel Engine trips, itineraries, FAQs, prices and destinations into %s.", "yatra", ), brand, )}

{__( "Your WP Travel Engine data is only read - nothing is changed or deleted, so you can keep WP Travel Engine until you are happy with the result. Running the import again never creates duplicates.", "yatra", )}

{detect.trips}
{__("Trips", "yatra")}
{(detect.terms.destination || 0) + (detect.terms.activities || 0) + (detect.terms.trip_types || 0)}
{__("Destinations, activities & trip types", "yatra")}
{detect.imported_trips}
{__("Already imported", "yatra")}
{detect.bookings}
{__("Bookings (not imported)", "yatra")}
{canResume && ( )}
{!scan && (

{__("Run a scan first to see what will be imported.", "yatra")}

)} {updateExisting && (

{__( "Trips imported before will be overwritten with their WP Travel Engine data, including any edits you made since.", "yatra", )}

)} {(isImporting || stage === "done" || results.length > 0) && (
{stage === "terms" ? __("Importing destinations, activities and categories...", "yatra") : stage === "done" ? __("Import complete", "yatra") : __("Importing trips...", "yatra")} {percent}%

{sprintf( __("%1$d / %2$d trips processed", "yatra"), progress.done, progress.total, )} {totals && " · " + sprintf( __("%1$d created, %2$d updated, %3$d skipped, %4$d failed", "yatra"), totals.created, totals.updated, totals.skipped, totals.failed, )}

)} {scan && (

{__("Scan results", "yatra")}

{sprintf(__("%d to create", "yatra"), scan.counts.create)} {sprintf(__("%d already imported", "yatra"), scan.counts.update)} {sprintf(__("%d with notes", "yatra"), scan.counts.warnings)}
{Object.entries(scan.terms).map(([taxonomy, row]) => (
{taxonomyLabel(taxonomy)}
{sprintf( __("%1$d new, %2$d existing", "yatra"), row.create, row.matched + row.mapped, )}
))}
{[...scan.notes, ...scan.not_imported].length > 0 && (
    {[...scan.notes, ...scan.not_imported].map((note, i) => (
  • {note}
  • ))}
)}
{scan.trips.map((trip) => ( ))}
{__("Trip", "yatra")} {__("Will", "yatra")} {__("Days", "yatra")} {__("FAQs", "yatra")} {__("Pricing", "yatra")} {__("Notes", "yatra")}
{trip.title} {trip.status !== "publish" && ( ({trip.status}) )} {trip.action === "create" ? ( {__("Create", "yatra")} ) : ( {updateExisting ? __("Update", "yatra") : __("Skip", "yatra")} )} {trip.itinerary_days} {trip.faqs} {trip.pricing === "traveler_based" ? __("Per traveller category", "yatra") : trip.price > 0 ? __("Regular", "yatra") : __("No price", "yatra")} {trip.warnings.length > 0 ? (
    {trip.warnings.map((w, i) => (
  • {w}
  • ))}
) : ( "-" )}
)} {termErrors.length > 0 && (

{__("Some destinations, activities or trip types could not be imported", "yatra")}

    {termErrors.map((e, i) => (
  • {e}
  • ))}
)} {results.length > 0 && (

{__("Import log", "yatra")}

    {results.map((r, i) => (
  • {r.action === "failed" ? ( ) : ( )} {r.title} {actionBadge(r.action)} {r.edit_url && ( {__("Edit", "yatra")} )} {r.view_url && ( {__("View", "yatra")} )}
    {r.error && (

    {r.error}

    )} {r.warnings.length > 0 && (
      {r.warnings.map((w, j) => (
    • {w}
    • ))}
    )}
  • ))}
)}
); }; export default WteImport;