diff --git a/src/app/router.tsx b/src/app/router.tsx index f0b20fd..ca77e65 100644 --- a/src/app/router.tsx +++ b/src/app/router.tsx @@ -10,6 +10,7 @@ const UsersPage = lazy(() => import('@/features/users/UsersPage')) const UserDetailPage = lazy(() => import('@/features/users/UserDetailPage')) const ToursPage = lazy(() => import('@/features/tours/ToursPage')) const OngoingToursPage = lazy(() => import('@/features/tours/OngoingToursPage')) +const TourHotelsPage = lazy(() => import('@/features/tours/TourHotelsPage')) const ServicesPage = lazy(() => import('@/features/services/ServicesPage')) const BillingPage = lazy(() => import('@/features/billing/BillingPage')) const BillingDetailPage = lazy(() => import('@/features/billing/BillingDetailPage')) @@ -34,6 +35,7 @@ export default function AppRouter() { } /> } /> } /> + } /> } /> } /> diff --git a/src/config/navigation.ts b/src/config/navigation.ts index 6f86e4b..adee4cb 100644 --- a/src/config/navigation.ts +++ b/src/config/navigation.ts @@ -53,6 +53,12 @@ export function getNavigationConfig(t: (key: string) => string): NavGroupConfig[ to: '/tours/ongoing', icon: 'calendar', }, + { + title: t('navigation.tourHotels'), + titleKey: 'navigation.tourHotels', + to: '/tours/hotels', + icon: 'bed', + }, ], }, { diff --git a/src/features/custom-trip/CustomTripDestinationDetailPage.tsx b/src/features/custom-trip/CustomTripDestinationDetailPage.tsx index 4740d69..b7606ae 100644 --- a/src/features/custom-trip/CustomTripDestinationDetailPage.tsx +++ b/src/features/custom-trip/CustomTripDestinationDetailPage.tsx @@ -37,6 +37,7 @@ import { type ServiceLanguageCode, } from '@/components/shared/ServiceTranslation' import { OFFICIAL_PRESET_CITIES } from './components/CustomTripDestinationsTab' +import { useHotelsCatalogStore, doesHotelMatchDestination } from '@/stores/hotels-catalog' import { fetchCustomTripDestinations, fetchCustomTripOrigins, @@ -80,8 +81,10 @@ export default function CustomTripDestinationDetailPage() { const [isLoading, setIsLoading] = useState(true) const [destination, setDestination] = useState(null) const [allOrigins, setAllOrigins] = useState([]) - const [allDestinations, setAllDestinations] = useState([]) - const [allHotels, setAllHotels] = useState([]) + const allDestinations = useHotelsCatalogStore((s) => s.destinations) + const setAllDestinations = useHotelsCatalogStore((s) => s.setDestinations) + const allHotels = useHotelsCatalogStore((s) => s.hotels) + const setAllHotels = useHotelsCatalogStore((s) => s.setHotels) const [allRelations, setAllRelations] = useState([]) // --- TAB 1: DESTINATION INFO FORM STATE --- @@ -195,7 +198,7 @@ export default function CustomTripDestinationDetailPage() { // --- TAB 2: HOTELS STATE --- const [hotelSearch, setHotelSearch] = useState('') - const [hotelStarsFilter, setHotelStarsFilter] = useState<'all' | '5' | '4' | '3'>('all') + const [hotelStarsFilter, setHotelStarsFilter] = useState<'all' | '5' | '4' | '3' | '2'>('all') const [hotelViewMode, setHotelViewMode] = useState<'cards' | 'table'>('cards') const [isHotelFormOpen, setIsHotelFormOpen] = useState(false) const [editingHotel, setEditingHotel] = useState(null) @@ -330,12 +333,7 @@ export default function CustomTripDestinationDetailPage() { // Destination-specific hotels const destHotels = useMemo(() => { if (!destination) return [] - return allHotels.filter( - (h) => - h.cityName === destination.name || - destination.name.includes(h.cityName) || - h.cityName.includes(destination.name) - ) + return allHotels.filter((h) => doesHotelMatchDestination(h, destination)) }, [allHotels, destination]) // Filtered hotels @@ -605,17 +603,12 @@ export default function CustomTripDestinationDetailPage() { } await saveCustomTripHotel(item) - setAllHotels((prev) => { - const exists = prev.some((h) => h.id === item.id) - return exists ? prev.map((h) => (h.id === item.id ? item : h)) : [item, ...prev] - }) setIsHotelFormOpen(false) } const handleConfirmDeleteHotel = async () => { if (!hotelToDelete) return await deleteCustomTripHotel(hotelToDelete.id) - setAllHotels((prev) => prev.filter((h) => h.id !== hotelToDelete.id)) setHotelToDelete(null) } @@ -1361,7 +1354,7 @@ export default function CustomTripDestinationDetailPage() { {/* Stars Filter */}
- {(['all', '5', '4', '3'] as const).map((s) => ( + {(['all', '5', '4', '3', '2'] as const).map((s) => (
{/* Add Custom Amenity */} diff --git a/src/features/custom-trip/CustomTripPage.tsx b/src/features/custom-trip/CustomTripPage.tsx index 86e4a97..362f50c 100644 --- a/src/features/custom-trip/CustomTripPage.tsx +++ b/src/features/custom-trip/CustomTripPage.tsx @@ -21,7 +21,10 @@ import { deleteCustomTripDestination, fetchCustomTripTransportRelations, fetchCustomTripHotels, + saveCustomTripHotel, + deleteCustomTripHotel, } from './services/custom-trip-api' +import { useHotelsCatalogStore } from '@/stores/hotels-catalog' import { CustomTripOrdersTab } from './components/CustomTripOrdersTab' import { CustomTripOriginsTab } from './components/CustomTripOriginsTab' import { CustomTripDestinationsTab } from './components/CustomTripDestinationsTab' @@ -60,9 +63,11 @@ export default function CustomTripPage() { const [isDestinationsLoading, setIsDestinationsLoading] = useState(true) const [orders, setOrders] = useState([]) const [origins, setOrigins] = useState([]) - const [destinations, setDestinations] = useState([]) + const destinations = useHotelsCatalogStore((s) => s.destinations) + const setDestinations = useHotelsCatalogStore((s) => s.setDestinations) const [relations, setRelations] = useState([]) - const [hotels, setHotels] = useState([]) + const hotels = useHotelsCatalogStore((s) => s.hotels) + const setHotels = useHotelsCatalogStore((s) => s.setHotels) useEffect(() => { let isMounted = true @@ -195,29 +200,15 @@ export default function CustomTripPage() { // Hotels CRUD const handleAddHotel = (item: CustomTripHotelItem) => { - setHotels((prev) => [item, ...prev]) - // Update destination's hotel count - setDestinations((prev) => - prev.map((d) => - d.name === item.cityName ? { ...d, hotelsCount: d.hotelsCount + 1 } : d - ) - ) + saveCustomTripHotel(item).catch(() => {}) } const handleUpdateHotel = (item: CustomTripHotelItem) => { - setHotels((prev) => prev.map((h) => (h.id === item.id ? item : h))) + saveCustomTripHotel(item).catch(() => {}) } const handleDeleteHotel = (id: string | number) => { - const target = hotels.find((h) => h.id === id) - setHotels((prev) => prev.filter((h) => h.id !== id)) - if (target) { - setDestinations((prev) => - prev.map((d) => - d.name === target.cityName ? { ...d, hotelsCount: Math.max(0, d.hotelsCount - 1) } : d - ) - ) - } + deleteCustomTripHotel(id).catch(() => {}) } // Orders update diff --git a/src/features/custom-trip/components/CustomTripDestinationsTab.tsx b/src/features/custom-trip/components/CustomTripDestinationsTab.tsx index ca5120e..1d2f311 100644 --- a/src/features/custom-trip/components/CustomTripDestinationsTab.tsx +++ b/src/features/custom-trip/components/CustomTripDestinationsTab.tsx @@ -30,6 +30,7 @@ import { SelectValue, } from '@/components/ui/select' import type { CustomTripDestinationItem, CustomTripTransportRelationItem } from '../types' +import { useHotelsCatalogStore, doesHotelMatchDestination } from '@/stores/hotels-catalog' interface CustomTripDestinationsTabProps { destinations: CustomTripDestinationItem[] @@ -276,6 +277,15 @@ export function CustomTripDestinationsTab({ const navigate = useNavigate() const [search, setSearch] = useState('') const [selectedCountry, setSelectedCountry] = useState('all') + const sharedHotels = useHotelsCatalogStore((s) => s.hotels) + const isHotelsLoaded = useHotelsCatalogStore((s) => s.isLoaded) + + const getHotelCount = (item: CustomTripDestinationItem) => { + if (isHotelsLoaded) { + return sharedHotels.filter((h) => doesHotelMatchDestination(h, item)).length + } + return item.hotelsCount || 0 + } const getTransportCount = (item: CustomTripDestinationItem) => { if (item.transportsCount !== undefined) return item.transportsCount @@ -693,9 +703,16 @@ export function CustomTripDestinationsTab({ - + { + e.stopPropagation() + navigate(`/custom-trip/destinations/${item.id}?tab=hotels`) + }} + className="inline-flex items-center gap-1 px-2.5 py-1 rounded-xl bg-card border border-border/70 text-xs font-semibold text-foreground hover:border-primary/50 transition-colors cursor-pointer" + title="مشاهده و مدیریت هتل‌های این مقصد" + > - {toFa(item.hotelsCount)} + {toFa(getHotelCount(item))} هتل diff --git a/src/features/custom-trip/services/custom-trip-api.ts b/src/features/custom-trip/services/custom-trip-api.ts index 8eeeecc..358bf9d 100644 --- a/src/features/custom-trip/services/custom-trip-api.ts +++ b/src/features/custom-trip/services/custom-trip-api.ts @@ -1,4 +1,5 @@ import { apiFetch } from '@/services/http' +import { useHotelsCatalogStore } from '@/stores/hotels-catalog' import type { CustomTripOrderItem, CustomTripOriginItem, @@ -418,7 +419,9 @@ export async function fetchCustomTripDestinations(): Promise( 'trip/custom/v2/catalog/destinations/?include_inactive=true' ) - return Array.isArray(remote) ? remote : [] + const list = Array.isArray(remote) ? remote : [] + useHotelsCatalogStore.getState().setDestinations(list, false) + return list } export async function fetchCustomTripDestinationById( @@ -481,13 +484,22 @@ export async function saveCustomTripDestination( body: JSON.stringify(payload), }) }) - return { ...item, ...res } + const saved = { ...item, ...res } + useHotelsCatalogStore.getState().setDestinations((prev) => { + const exists = prev.some((d) => String(d.id) === String(saved.id)) + return exists ? prev.map((d) => (String(d.id) === String(saved.id) ? saved : d)) : [saved, ...prev] + }, true) + return saved } export async function deleteCustomTripDestination(id: string | number): Promise { await apiFetch(`trip/custom/v2/catalog/destinations/${id}/`, { method: 'DELETE', }) + useHotelsCatalogStore.getState().setDestinations( + (prev) => prev.filter((d) => String(d.id) !== String(id)), + true + ) } export async function fetchCustomTripTransports(): Promise { @@ -600,30 +612,68 @@ export async function deleteCustomTripTransportRelation(id: string | number): Pr }) } -export async function fetchCustomTripHotels(): Promise { - const remote = await apiFetch('trip/custom/v2/catalog/hotels/') - if (!Array.isArray(remote)) return [] - return remote.map((h: any) => ({ - id: h.id, - name: h.name || '', - cityName: h.cityName || h.city_name || '', - stars: Number(h.stars) || 4, - score: Number(h.score) || 4.8, +function mapRawHotelToItem(h: any, fallback?: Partial): CustomTripHotelItem { + const rawTranslations = + h?.translations && typeof h.translations === 'object' + ? h.translations + : fallback?.translations + const meta = + rawTranslations && typeof (rawTranslations as any)._meta === 'object' + ? (rawTranslations as any)._meta + : {} + + return { + id: h?.id ?? fallback?.id ?? `hotel_${Date.now()}`, + name: fallback?.name || h?.name || '', + cityName: fallback?.cityName || meta?.cityName || h?.cityName || h?.city_name || '', + stars: Number(fallback?.stars ?? h?.stars ?? 4), + score: Number(fallback?.score ?? h?.score ?? 4.8), distanceToShrine: - h.distanceToShrine || - (h.distance_to_city_km ? `${h.distance_to_city_km} کیلومتر تا حرم مطهر` : 'نزدیک به حرم مطهر'), - distanceToShrineKm: Number(h.distanceToShrineKm ?? h.distance_to_city_km ?? 0.3), - amenities: Array.isArray(h.amenities) + fallback?.distanceToShrine || + meta?.distanceToShrine || + h?.distanceToShrine || + (h?.distance_to_city_km ? `${h.distance_to_city_km} کیلومتر تا حرم مطهر` : 'نزدیک به حرم مطهر'), + distanceToShrineKm: Number( + fallback?.distanceToShrineKm ?? h?.distanceToShrineKm ?? h?.distance_to_city_km ?? 0.3 + ), + amenities: Array.isArray(fallback?.amenities) + ? fallback.amenities + : Array.isArray(meta?.amenities) + ? meta.amenities + : Array.isArray(h?.amenities) ? h.amenities : ['اینترنت رایگان', 'رستوران و بوفه', 'نزدیک به حرم مطهر'], - description: h.description || 'هتل درجه یک و مجهز جهت اقامت زائرین گرامی.', - guideNote: h.guideNote || undefined, - pricePerDayAdult: Number(h.pricePerDayAdult ?? h.price_per_day ?? 80), - pricePerDayChild: Number(h.pricePerDayChild ?? h.price_per_day_child ?? 40), - image: '', - isActive: h.isActive !== undefined ? Boolean(h.isActive) : true, - translations: h.translations, - })) + description: + fallback?.description || + meta?.description || + h?.description || + 'هتل درجه یک و مجهز جهت اقامت زائرین گرامی.', + guideNote: fallback?.guideNote ?? meta?.guideNote ?? h?.guideNote ?? undefined, + pricePerDayAdult: Number( + fallback?.pricePerDayAdult ?? h?.pricePerDayAdult ?? h?.price_per_day ?? 80 + ), + pricePerDayChild: Number( + fallback?.pricePerDayChild ?? h?.pricePerDayChild ?? h?.price_per_day_child ?? 40 + ), + image: fallback?.image || h?.image || '', + isActive: + fallback?.isActive !== undefined + ? Boolean(fallback.isActive) + : meta?.isActive !== undefined + ? Boolean(meta.isActive) + : h?.isActive !== undefined + ? Boolean(h.isActive) + : true, + translations: rawTranslations, + } +} + +export async function fetchCustomTripHotels(): Promise { + const remote = await apiFetch('trip/custom/v2/catalog/hotels/') + if (!Array.isArray(remote)) return [] + const list = remote.map((h: any) => mapRawHotelToItem(h)) + useHotelsCatalogStore.getState().setHotels(list, false) + return list } export async function saveCustomTripHotel(item: CustomTripHotelItem): Promise { @@ -658,16 +708,17 @@ export async function saveCustomTripHotel(item: CustomTripHotelItem): Promise { - await apiFetch(`trip/custom/v2/catalog/hotels/${id}/`, { - method: 'DELETE', - }) + const isNumericId = typeof id === 'number' || /^\d+$/.test(String(id)) + if (isNumericId) { + await apiFetch(`trip/custom/v2/catalog/hotels/${id}/`, { + method: 'DELETE', + }) + } + useHotelsCatalogStore.getState().removeHotel(id, true) } diff --git a/src/features/tours/TourHotelsPage.tsx b/src/features/tours/TourHotelsPage.tsx new file mode 100644 index 0000000..3d84d7c --- /dev/null +++ b/src/features/tours/TourHotelsPage.tsx @@ -0,0 +1,1441 @@ +import React, { useState, useEffect, useMemo } from 'react' +import { useNavigate } from 'react-router-dom' +import { Ic } from '@/icons' +import { Card, CardContent } from '@/components/ui/card' +import { Button } from '@/components/ui/button' +import { Badge } from '@/components/ui/badge' +import { Input } from '@/components/ui/input' +import { Textarea } from '@/components/ui/textarea' +import { Switch } from '@/components/ui/switch' +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from '@/components/ui/select' +import { + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogDescription, + DialogFooter, +} from '@/components/ui/dialog' +import DeleteConfirmDialog from '@/components/shared/DeleteConfirmDialog' +import { + ServiceTranslation, + SERVICE_LANGUAGES, + type ServiceLanguageCode, +} from '@/components/shared/ServiceTranslation' +import TablePagination from '@/components/shared/TablePagination' +import { Shimmer } from '@/components/shared/shimmer_frontend' +import { toFa, cn } from '@/lib/utils' +import { useTranslation } from '@/i18n' +import { toast } from '@/stores/toast' +import { useHotelsCatalogStore, doesHotelMatchDestination } from '@/stores/hotels-catalog' +import { + fetchCustomTripHotels, + fetchCustomTripDestinations, + saveCustomTripHotel, + deleteCustomTripHotel, +} from '@/features/custom-trip/services/custom-trip-api' +import type { CustomTripHotelItem, CustomTripDestinationItem } from '@/features/custom-trip/types' + +const COMMON_AMENITIES = [ + { id: 'wifi', name: 'اینترنت وای‌فای رایگان' }, + { id: 'restaurant', name: 'رستوران ایرانی و بوفه باز' }, + { id: 'shrine_transfer', name: 'ترانسفر حرم مطهر رایگان' }, + { id: 'airport_transfer', name: 'ترانسفر فرودگاهی اختصاصی' }, + { id: 'laundry', name: 'لاندری و خشکشویی' }, + { id: 'wheelchair', name: 'خدمات ویژه ویلچر و آسانسور' }, + { id: 'doctor', name: 'پزشک و خدمات درمانی مقیم' }, + { id: 'safety_box', name: 'صندوق امانات دیجیتال در اتاق' }, +] + +export default function TourHotelsPage() { + const { t } = useTranslation() + const navigate = useNavigate() + + // داده‌های کاتالوگ یکپارچه از Zustand Store (مشترک با Custom Trip) + const hotels = useHotelsCatalogStore((s) => s.hotels) + const destinations = useHotelsCatalogStore((s) => s.destinations) + const isLoaded = useHotelsCatalogStore((s) => s.isLoaded) + + const [isLoading, setIsLoading] = useState(!isLoaded) + const [isRefreshing, setIsRefreshing] = useState(false) + + // فیلترها و ناوبری + const [searchTerm, setSearchTerm] = useState('') + const [selectedDestination, setSelectedDestination] = useState('all') + const [starsFilter, setStarsFilter] = useState<'all' | '5' | '4' | '3' | '2'>('all') + const [statusFilter, setStatusFilter] = useState<'all' | 'active' | 'inactive'>('all') + const [viewMode, setViewMode] = useState<'cards' | 'table'>('cards') + + // صفحه‌بندی + const [currentPage, setCurrentPage] = useState(1) + const pageSize = viewMode === 'cards' ? 12 : 20 + + // مودال افزودن / ویرایش هتل + const [isFormOpen, setIsFormOpen] = useState(false) + const [editingHotel, setEditingHotel] = useState(null) + const [isSaving, setIsSaving] = useState(false) + + // مودال حذف هتل + const [hotelToDelete, setHotelToDelete] = useState(null) + const [isDeleting, setIsDeleting] = useState(false) + + // استیت‌های فرم چندزبانه (ServiceTranslation) + const [activeLangTab, setActiveLangTab] = useState('ar') + const [formCityName, setFormCityName] = useState('') + const [isCustomCity, setIsCustomCity] = useState(false) + const [hotelNames, setHotelNames] = useState>({ + ar: '', + fa: '', + en: '', + ru: '', + id: '', + }) + const [hotelDistances, setHotelDistances] = useState>({ + ar: '', + fa: '', + en: '', + ru: '', + id: '', + }) + const [hotelDescriptions, setHotelDescriptions] = useState>({ + ar: '', + fa: '', + en: '', + ru: '', + id: '', + }) + const [hotelGuideNotes, setHotelGuideNotes] = useState>({ + ar: '', + fa: '', + en: '', + ru: '', + id: '', + }) + const [hotelStars, setHotelStars] = useState(5) + const [hotelScore, setHotelScore] = useState(4.8) + const [hotelPriceAdult, setHotelPriceAdult] = useState(100) + const [hotelPriceChild, setHotelPriceChild] = useState(50) + const [hotelIsActive, setHotelIsActive] = useState(true) + const [hotelAmenities, setHotelAmenities] = useState([]) + const [customAmenityInput, setCustomAmenityInput] = useState('') + + const currentFormLang = + SERVICE_LANGUAGES.find((l) => l.code === activeLangTab) || SERVICE_LANGUAGES[0] + + // لود اولیه در صورت خالی بودن استور + useEffect(() => { + if (!isLoaded || hotels.length === 0 || destinations.length === 0) { + setIsLoading(true) + Promise.all([fetchCustomTripHotels(), fetchCustomTripDestinations()]) + .catch((err) => { + console.error('Failed to load hotels catalog:', err) + }) + .finally(() => { + setIsLoading(false) + }) + } + }, [isLoaded, hotels.length, destinations.length]) + + // به‌روزرسانی دستی کاتالوگ + const handleRefresh = async () => { + setIsRefreshing(true) + try { + await Promise.all([fetchCustomTripHotels(), fetchCustomTripDestinations()]) + toast.success(t('common.refresh')) + } catch (err) { + console.error('Refresh error:', err) + toast.error(t('common.errorOccurred')) + } finally { + setIsRefreshing(false) + } + } + + // پیدا کردن شهر مقصد متناظر برای پیوند به شناسنامه مقصد + const findDestinationForHotel = (hotel: CustomTripHotelItem): CustomTripDestinationItem | undefined => { + return destinations.find((d) => doesHotelMatchDestination(hotel, d)) + } + + // هدایت به شناسنامه شهر در سفرهای اختصاصی + const handleNavigateToDestinationProfile = (hotel: CustomTripHotelItem) => { + const dest = findDestinationForHotel(hotel) + if (dest) { + navigate(`/custom-trip/destinations/${dest.id}?tab=hotels`) + } else { + navigate('/custom-trip/destinations') + } + } + + // فیلتر هتل‌ها بر اساس جستجو، شهر مقصد، ستاره و وضعیت + const filteredHotels = useMemo(() => { + const term = searchTerm.trim().toLowerCase() + + return hotels.filter((h) => { + // فیلتر مقصد + if (selectedDestination !== 'all') { + const dest = destinations.find((d) => String(d.id) === selectedDestination) + if (dest) { + if (!doesHotelMatchDestination(h, dest)) return false + } else { + if (!doesHotelMatchDestination(h, selectedDestination)) return false + } + } + + // فیلتر ستاره + if (starsFilter !== 'all' && String(h.stars) !== starsFilter) { + return false + } + + // فیلتر وضعیت فعال بودن + if (statusFilter === 'active' && !h.isActive) return false + if (statusFilter === 'inactive' && h.isActive) return false + + // فیلتر متن جستجو + if (term) { + const matchName = (h.name || '').toLowerCase().includes(term) + const matchCity = (h.cityName || '').toLowerCase().includes(term) + const matchDistance = (h.distanceToShrine || '').toLowerCase().includes(term) + const matchDesc = (h.description || '').toLowerCase().includes(term) + const matchGuide = (h.guideNote || '').toLowerCase().includes(term) + const matchAmenities = (h.amenities || []).some((a) => a.toLowerCase().includes(term)) + + let matchTranslations = false + if (h.translations) { + for (const tr of Object.values(h.translations)) { + if ( + (tr?.name && tr.name.toLowerCase().includes(term)) || + (tr?.description && tr.description.toLowerCase().includes(term)) || + (tr?.distanceToShrine && tr.distanceToShrine.toLowerCase().includes(term)) + ) { + matchTranslations = true + break + } + } + } + + if ( + !matchName && + !matchCity && + !matchDistance && + !matchDesc && + !matchGuide && + !matchAmenities && + !matchTranslations + ) { + return false + } + } + + return true + }) + }, [hotels, destinations, selectedDestination, starsFilter, statusFilter, searchTerm]) + + // شمارش هتل‌ها در هر مقصد برای برچسب‌های فیلتر + const destinationHotelCounts = useMemo(() => { + const map = new Map() + destinations.forEach((d) => { + const count = hotels.filter((h) => doesHotelMatchDestination(h, d)).length + map.set(String(d.id), count) + }) + return map + }, [destinations, hotels]) + + // محاسبه شاخص‌های آماری KPI + const stats = useMemo(() => { + const total = hotels.length + const luxury = hotels.filter((h) => h.stars === 5).length + const active = hotels.filter((h) => h.isActive).length + // تعداد مقاصدی که حداقل ۱ هتل دارند + const coveredDestinations = destinations.filter( + (d) => (destinationHotelCounts.get(String(d.id)) || 0) > 0 + ).length + + return { total, luxury, active, coveredDestinations } + }, [hotels, destinations, destinationHotelCounts]) + + // بازنشانی صفحه در تغییر فیلترها + useEffect(() => { + setCurrentPage(1) + }, [searchTerm, selectedDestination, starsFilter, statusFilter, viewMode]) + + // محاسبات صفحه‌بندی + const totalPages = Math.ceil(filteredHotels.length / pageSize) || 1 + const activePage = Math.min(currentPage, totalPages) + + const paginatedHotels = useMemo(() => { + const start = (activePage - 1) * pageSize + return filteredHotels.slice(start, start + pageSize) + }, [filteredHotels, activePage, pageSize]) + + // باز کردن مدال افزودن هتل جدید + const handleOpenAddHotel = () => { + setEditingHotel(null) + setActiveLangTab('ar') + const emptyMap: Record = { ar: '', fa: '', en: '', ru: '', id: '' } + setHotelNames(emptyMap) + setHotelDistances(emptyMap) + setHotelDescriptions(emptyMap) + setHotelGuideNotes(emptyMap) + + // مقصد پیش‌فرض: اولین مقصد موجود یا کربلای معلی + const defaultCity = destinations.length > 0 ? destinations[0].name : 'کربلای معلی' + setFormCityName(defaultCity) + setIsCustomCity(false) + + setHotelStars(5) + setHotelScore(4.8) + setHotelPriceAdult(110) + setHotelPriceChild(55) + setHotelIsActive(true) + setHotelAmenities([ + 'اینترنت وای‌فای رایگان', + 'رستوران ایرانی و بوفه باز', + 'ترانسفر حرم مطهر رایگان', + ]) + setCustomAmenityInput('') + setIsFormOpen(true) + } + + // باز کردن مدال ویرایش هتل + const handleOpenEditHotel = (hotel: CustomTripHotelItem) => { + setEditingHotel(hotel) + setActiveLangTab('ar') + const newNames: Record = { ar: '', fa: '', en: '', ru: '', id: '' } + const newDistances: Record = { + ar: '', + fa: '', + en: '', + ru: '', + id: '', + } + const newDescs: Record = { ar: '', fa: '', en: '', ru: '', id: '' } + const newGuides: Record = { ar: '', fa: '', en: '', ru: '', id: '' } + + if (hotel.translations) { + for (const lang of ['ar', 'fa', 'en', 'ru', 'id'] as ServiceLanguageCode[]) { + if (hotel.translations[lang]?.name) newNames[lang] = hotel.translations[lang].name! + if (hotel.translations[lang]?.distanceToShrine) + newDistances[lang] = hotel.translations[lang].distanceToShrine! + if (hotel.translations[lang]?.description) + newDescs[lang] = hotel.translations[lang].description! + if (hotel.translations[lang]?.guideNote) + newGuides[lang] = hotel.translations[lang].guideNote! + } + } + + // مقادیر جایگزین (Fallback) + if (!newNames.ar) newNames.ar = hotel.name || '' + if (!newNames.fa) newNames.fa = hotel.name || '' + if (!newDistances.ar) newDistances.ar = hotel.distanceToShrine || '' + if (!newDistances.fa) newDistances.fa = hotel.distanceToShrine || '' + if (!newDescs.ar) newDescs.ar = hotel.description || '' + if (!newDescs.fa) newDescs.fa = hotel.description || '' + if (!newGuides.ar && hotel.guideNote) newGuides.ar = hotel.guideNote + if (!newGuides.fa && hotel.guideNote) newGuides.fa = hotel.guideNote + + setHotelNames(newNames) + setHotelDistances(newDistances) + setHotelDescriptions(newDescs) + setHotelGuideNotes(newGuides) + + // بررسی آیا شهر در لیست مقاصد موجود است + const matchDest = destinations.find((d) => doesHotelMatchDestination(hotel, d)) + if (matchDest) { + setFormCityName(matchDest.name) + setIsCustomCity(false) + } else { + setFormCityName(hotel.cityName || '') + setIsCustomCity(true) + } + + setHotelStars(hotel.stars) + setHotelScore(hotel.score || 4.8) + setHotelPriceAdult(hotel.pricePerDayAdult || 100) + setHotelPriceChild(hotel.pricePerDayChild || 50) + setHotelIsActive(hotel.isActive) + setHotelAmenities(hotel.amenities || []) + setCustomAmenityInput('') + setIsFormOpen(true) + } + + // تاگل امکانات هتل + const handleToggleAmenity = (name: string) => { + setHotelAmenities((prev) => + prev.includes(name) ? prev.filter((a) => a !== name) : [...prev, name] + ) + } + + // افزودن امکانات دلخواه + const handleAddCustomAmenity = () => { + const val = customAmenityInput.trim() + if (!val) return + if (!hotelAmenities.includes(val)) { + setHotelAmenities((prev) => [...prev, val]) + } + setCustomAmenityInput('') + } + + // ذخیره اطلاعات هتل (همگام‌سازی دوطرفه با Custom Trip و Backend) + const handleSaveHotel = async (e: React.FormEvent) => { + e.preventDefault() + + const primaryName = + hotelNames[activeLangTab]?.trim() || + hotelNames.ar?.trim() || + hotelNames.fa?.trim() || + hotelNames.en?.trim() || + 'هتل جدید' + + const primaryDistance = + hotelDistances[activeLangTab]?.trim() || + hotelDistances.ar?.trim() || + hotelDistances.fa?.trim() || + 'فاصله استاندارد تا حرم مطهر' + + const primaryDesc = + hotelDescriptions[activeLangTab]?.trim() || + hotelDescriptions.ar?.trim() || + hotelDescriptions.fa?.trim() || + 'هتل درجه یک و مجهز جهت اقامت زائرین گرامی.' + + const primaryGuide = + hotelGuideNotes[activeLangTab]?.trim() || + hotelGuideNotes.ar?.trim() || + hotelGuideNotes.fa?.trim() || + undefined + + const translations: Record< + string, + { name?: string; description?: string; distanceToShrine?: string; guideNote?: string } + > = {} + for (const lang of ['ar', 'fa', 'en', 'ru', 'id'] as ServiceLanguageCode[]) { + translations[lang] = { + name: hotelNames[lang]?.trim() || primaryName, + distanceToShrine: hotelDistances[lang]?.trim() || primaryDistance, + description: hotelDescriptions[lang]?.trim() || primaryDesc, + guideNote: hotelGuideNotes[lang]?.trim() || primaryGuide, + } + } + + const item: CustomTripHotelItem = { + id: editingHotel ? editingHotel.id : `hotel_${Date.now()}`, + name: primaryName, + cityName: formCityName.trim() || 'کربلای معلی', + stars: hotelStars, + score: hotelScore, + distanceToShrine: primaryDistance, + amenities: hotelAmenities, + description: primaryDesc, + guideNote: primaryGuide, + pricePerDayAdult: hotelPriceAdult, + pricePerDayChild: hotelPriceChild, + isActive: hotelIsActive, + translations, + } + + setIsSaving(true) + try { + await saveCustomTripHotel(item) + setIsFormOpen(false) + toast.success(t('tours.hotelSavedSuccess')) + } catch (err) { + console.error('Failed to save hotel:', err) + toast.error(t('common.errorOccurred')) + } finally { + setIsSaving(false) + } + } + + // حذف هتل + const handleConfirmDeleteHotel = async () => { + if (!hotelToDelete) return + setIsDeleting(true) + try { + await deleteCustomTripHotel(hotelToDelete.id) + setHotelToDelete(null) + toast.success(t('tours.hotelDeletedSuccess')) + } catch (err) { + console.error('Failed to delete hotel:', err) + toast.error(t('common.errorOccurred')) + } finally { + setIsDeleting(false) + } + } + + return ( +
+ {/* ========================================================================= */} + {/* 1. سربرگ اصلی صفحه مدیریت هتل‌ها (Header & Synchronization Badge) */} + {/* ========================================================================= */} +
+
+
+
+ +
+

{t('tours.hotelsTitle')}

+ + {t('tours.hotelsRegisteredCount', { count: toFa(hotels.length) })} + + + {/* نشانگر هماهنگی بلادرنگ با سفرهای اختصاصی */} + + + {t('tours.sharedWithCustomTrip')} + +
+

+ {t('tours.hotelsSubtitle')} +

+
+ +
+ + + +
+
+ + {/* ========================================================================= */} + {/* 2. شاخص‌های آماری کلیدی هتل‌ها (KPI Metrics) */} + {/* ========================================================================= */} +
+ {/* کل هتل‌ها */} + + +
+

{t('tours.kpiTotal')}

+

+ {toFa(stats.total)} +

+
+
+ +
+
+
+ + {/* هتل‌های لوکس ۵ ستاره */} + + +
+

{t('tours.kpiLuxury')}

+

+ {toFa(stats.luxury)} +

+
+
+ +
+
+
+ + {/* هتل‌های فعال */} + + +
+

{t('tours.kpiActive')}

+

+ {toFa(stats.active)} +

+
+
+ +
+
+
+ + {/* شهرهای تحت پوشش */} + + +
+

+ {t('tours.kpiDestinations')} +

+

+ {toFa(stats.coveredDestinations)} +

+
+
+ +
+
+
+
+ + {/* ========================================================================= */} + {/* 3. نوار ابزار جستجو و فیلترها (Destination Pills, Stars, Mode Toggle) */} + {/* ========================================================================= */} +
+
+ {/* جستجو و فیلتر ستاره */} +
+
+ + setSearchTerm(e.target.value)} + placeholder={t('tours.searchHotelsPlaceholder')} + className="ps-9 pe-8 h-10 rounded-xl bg-background text-xs sm:text-sm border-border-soft" + /> + {searchTerm && ( + + )} +
+ + {/* فیلتر ستاره‌ها */} +
+ {(['all', '5', '4', '3', '2'] as const).map((s) => ( + + ))} +
+ + {/* فیلتر وضعیت فعال بودن */} +
+ + + +
+
+ + {/* حالت نمایش کارتی یا جدولی */} +
+
+ + +
+
+
+ + {/* فیلتر مقاصد زیارتی (Destination Pills with Hotel Counts) */} + {destinations.length > 0 && ( +
+ + + {destinations.map((dest) => { + const count = destinationHotelCounts.get(String(dest.id)) || 0 + const isSelected = selectedDestination === String(dest.id) + return ( + + ) + })} +
+ )} +
+ + {/* ========================================================================= */} + {/* 4. محتوای فهرست هتل‌ها (Loading, Empty, Cards or Table) */} + {/* ========================================================================= */} + {isLoading ? ( +
+ {Array.from({ length: 6 }).map((_, i) => ( + + + + +
+ + +
+
+ ))} +
+ ) : filteredHotels.length === 0 ? ( +
+
+ +
+

{t('tours.noHotelsFound')}

+

+ می‌توانید فیلترهای جستجو را بازنشانی کرده یا هتل جدیدی به سامانه بیفزایید. +

+ +
+ ) : viewMode === 'cards' ? ( + /* ================= CARDS VIEW ================= */ +
+ {paginatedHotels.map((hotel) => { + const cleanName = (hotel.name || '').replace(/\s*\([A-Za-z0-9\s\-']+\)/g, '').trim() + const matchDest = findDestinationForHotel(hotel) + + return ( +
+
+ {/* Header: Name, Destination Chip, Stars */} +
+
+
+

+ {cleanName || hotel.name} +

+
+ + {/* City / Destination badge */} +
+ + + {/* Stars */} +
+ {Array.from({ length: hotel.stars }).map((_, i) => ( + + ★ + + ))} +
+ + {/* Score */} + {hotel.score && ( + + {toFa(hotel.score)} / ۵ + + )} +
+
+ + {/* Actions: Edit & Delete */} +
+ + +
+
+ + {/* Distance to shrine */} +
+ + {hotel.distanceToShrine} +
+ + {/* Amenities Preview */} + {hotel.amenities && hotel.amenities.length > 0 && ( +
+ {hotel.amenities.slice(0, 3).map((amenity, idx) => ( + + {amenity} + + ))} + {hotel.amenities.length > 3 && ( + + +{toFa(hotel.amenities.length - 3)} + + )} +
+ )} + + {/* Description preview */} + {hotel.description && ( +

+ {hotel.description} +

+ )} +
+ + {/* Footer: Price & Active Status */} +
+ + + {hotel.isActive ? t('customTrip.active') : t('customTrip.inactive')} + + +
+
+ + {t('tours.adultRate')}: + + + ${toFa(hotel.pricePerDayAdult)} + +
+ | +
+ + {t('tours.childRate')}: + + + ${toFa(hotel.pricePerDayChild)} + +
+
+
+
+ ) + })} +
+ ) : ( + /* ================= TABLE VIEW ================= */ +
+
+ + + + + + + + + + + + + + + + {paginatedHotels.map((hotel, idx) => { + const matchDest = findDestinationForHotel(hotel) + const globalIdx = (activePage - 1) * pageSize + idx + 1 + + return ( + + + + + + + + + + + + ) + })} + +
#{t('customTrip.hotelName')}{t('customTrip.originCity')}{t('customTrip.hotelStars')}{t('customTrip.distanceToShrine')}{t('tours.adultRate')}{t('tours.childRate')}{t('customTrip.status')}{t('customTrip.actions')}
+ {toFa(globalIdx)} + +
{hotel.name}
+ {hotel.score && ( + + امتیاز {toFa(hotel.score)} / ۵ + + )} +
+ + + + {toFa(hotel.stars)} ★ + + + {hotel.distanceToShrine} + + ${toFa(hotel.pricePerDayAdult)} + + ${toFa(hotel.pricePerDayChild)} + + + + + {hotel.isActive ? t('customTrip.active') : t('customTrip.inactive')} + + + +
+ + +
+
+
+
+ )} + + {/* صفحه‌بندی فهرست هتل‌ها */} + {totalPages > 1 && ( +
+ setCurrentPage(page)} + /> +
+ )} + + {/* ========================================================================= */} + {/* 5. مدال افزودن / ویرایش هتل (Add / Edit Hotel Modal with Multi-Language) */} + {/* ========================================================================= */} + + + + + + {editingHotel ? t('tours.editHotel') : t('tours.addHotel')} + + + مشخصات، شهر مقصد، درجه ستاره، فاصله تا حرم، امکانات و نرخ‌های هتل را ثبت نمایید. + + + +
+
+ {/* انتخاب شهر مقصد */} +
+ + {destinations.length > 0 && !isCustomCity ? ( +
+ +
+ ) : ( +
+ setFormCityName(e.target.value)} + placeholder="مثال: کربلای معلی، نجف اشرف، مشهد..." + className="h-10 rounded-xl text-xs" + required + /> + {destinations.length > 0 && ( + + )} +
+ )} +
+ + {/* ماژول ترجمه چندزبانه (ServiceTranslation) */} +
+
+ setActiveLangTab(lang)} + completedLangs={{ + ar: Boolean(hotelNames.ar?.trim()), + fa: Boolean(hotelNames.fa?.trim()), + en: Boolean(hotelNames.en?.trim()), + ru: Boolean(hotelNames.ru?.trim()), + id: Boolean(hotelNames.id?.trim()), + }} + primaryLang="ar" + title="اطلاعات متنی و چندزبانه هتل" + required + variant="pills" + /> +
+ + {/* فیلدهای اختصاصی زبان انتخاب‌شده */} +
+ {/* نام هتل */} +
+
+ + + {currentFormLang.dir.toUpperCase()} + +
+ + setHotelNames((prev) => ({ ...prev, [activeLangTab]: e.target.value })) + } + dir={currentFormLang.dir} + placeholder={`نام هتل به زبان ${currentFormLang.name}...`} + className="h-10 rounded-xl text-xs bg-background" + required={activeLangTab === 'fa' || activeLangTab === 'ar'} + /> +
+ + {/* فاصله تا حرم مطهر */} +
+ + + setHotelDistances((prev) => ({ ...prev, [activeLangTab]: e.target.value })) + } + dir={currentFormLang.dir} + placeholder={`مثال: ۴۰۰ متر تا حرم مطهر به زبان ${currentFormLang.name}...`} + className="h-10 rounded-xl text-xs bg-background" + /> +
+ + {/* توضیحات هتل */} +
+ +