Browse Source

refactor: extract hotels catalog store and add tour hotels page

master
parent
commit
87c863dedb
  1. 2
      src/app/router.tsx
  2. 6
      src/config/navigation.ts
  3. 39
      src/features/custom-trip/CustomTripDestinationDetailPage.tsx
  4. 29
      src/features/custom-trip/CustomTripPage.tsx
  5. 21
      src/features/custom-trip/components/CustomTripDestinationsTab.tsx
  6. 115
      src/features/custom-trip/services/custom-trip-api.ts
  7. 1441
      src/features/tours/TourHotelsPage.tsx
  8. 1
      src/features/tours/services/tour-api.ts
  9. 17
      src/features/tours/types.ts
  10. 32
      src/locales/ar.json
  11. 32
      src/locales/en.json
  12. 32
      src/locales/fa.json
  13. 207
      src/stores/hotels-catalog.ts

2
src/app/router.tsx

@ -10,6 +10,7 @@ const UsersPage = lazy(() => import('@/features/users/UsersPage'))
const UserDetailPage = lazy(() => import('@/features/users/UserDetailPage')) const UserDetailPage = lazy(() => import('@/features/users/UserDetailPage'))
const ToursPage = lazy(() => import('@/features/tours/ToursPage')) const ToursPage = lazy(() => import('@/features/tours/ToursPage'))
const OngoingToursPage = lazy(() => import('@/features/tours/OngoingToursPage')) const OngoingToursPage = lazy(() => import('@/features/tours/OngoingToursPage'))
const TourHotelsPage = lazy(() => import('@/features/tours/TourHotelsPage'))
const ServicesPage = lazy(() => import('@/features/services/ServicesPage')) const ServicesPage = lazy(() => import('@/features/services/ServicesPage'))
const BillingPage = lazy(() => import('@/features/billing/BillingPage')) const BillingPage = lazy(() => import('@/features/billing/BillingPage'))
const BillingDetailPage = lazy(() => import('@/features/billing/BillingDetailPage')) const BillingDetailPage = lazy(() => import('@/features/billing/BillingDetailPage'))
@ -34,6 +35,7 @@ export default function AppRouter() {
<Route path="/users/:id" element={<PageReady><UserDetailPage /></PageReady>} /> <Route path="/users/:id" element={<PageReady><UserDetailPage /></PageReady>} />
<Route path="/tours" element={<PageReady><ToursPage /></PageReady>} /> <Route path="/tours" element={<PageReady><ToursPage /></PageReady>} />
<Route path="/tours/ongoing" element={<PageReady><OngoingToursPage /></PageReady>} /> <Route path="/tours/ongoing" element={<PageReady><OngoingToursPage /></PageReady>} />
<Route path="/tours/hotels" element={<PageReady><TourHotelsPage /></PageReady>} />
<Route path="/tours/orders" element={<Navigate to="/billing?service=tour" replace />} /> <Route path="/tours/orders" element={<Navigate to="/billing?service=tour" replace />} />
<Route path="/tours/custom-trip" element={<Navigate to="/custom-trip" replace />} /> <Route path="/tours/custom-trip" element={<Navigate to="/custom-trip" replace />} />

6
src/config/navigation.ts

@ -53,6 +53,12 @@ export function getNavigationConfig(t: (key: string) => string): NavGroupConfig[
to: '/tours/ongoing', to: '/tours/ongoing',
icon: 'calendar', icon: 'calendar',
}, },
{
title: t('navigation.tourHotels'),
titleKey: 'navigation.tourHotels',
to: '/tours/hotels',
icon: 'bed',
},
], ],
}, },
{ {

39
src/features/custom-trip/CustomTripDestinationDetailPage.tsx

@ -37,6 +37,7 @@ import {
type ServiceLanguageCode, type ServiceLanguageCode,
} from '@/components/shared/ServiceTranslation' } from '@/components/shared/ServiceTranslation'
import { OFFICIAL_PRESET_CITIES } from './components/CustomTripDestinationsTab' import { OFFICIAL_PRESET_CITIES } from './components/CustomTripDestinationsTab'
import { useHotelsCatalogStore, doesHotelMatchDestination } from '@/stores/hotels-catalog'
import { import {
fetchCustomTripDestinations, fetchCustomTripDestinations,
fetchCustomTripOrigins, fetchCustomTripOrigins,
@ -80,8 +81,10 @@ export default function CustomTripDestinationDetailPage() {
const [isLoading, setIsLoading] = useState(true) const [isLoading, setIsLoading] = useState(true)
const [destination, setDestination] = useState<CustomTripDestinationItem | null>(null) const [destination, setDestination] = useState<CustomTripDestinationItem | null>(null)
const [allOrigins, setAllOrigins] = useState<CustomTripOriginItem[]>([]) const [allOrigins, setAllOrigins] = useState<CustomTripOriginItem[]>([])
const [allDestinations, setAllDestinations] = useState<CustomTripDestinationItem[]>([])
const [allHotels, setAllHotels] = useState<CustomTripHotelItem[]>([])
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<CustomTripTransportRelationItem[]>([]) const [allRelations, setAllRelations] = useState<CustomTripTransportRelationItem[]>([])
// --- TAB 1: DESTINATION INFO FORM STATE --- // --- TAB 1: DESTINATION INFO FORM STATE ---
@ -195,7 +198,7 @@ export default function CustomTripDestinationDetailPage() {
// --- TAB 2: HOTELS STATE --- // --- TAB 2: HOTELS STATE ---
const [hotelSearch, setHotelSearch] = useState('') 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 [hotelViewMode, setHotelViewMode] = useState<'cards' | 'table'>('cards')
const [isHotelFormOpen, setIsHotelFormOpen] = useState(false) const [isHotelFormOpen, setIsHotelFormOpen] = useState(false)
const [editingHotel, setEditingHotel] = useState<CustomTripHotelItem | null>(null) const [editingHotel, setEditingHotel] = useState<CustomTripHotelItem | null>(null)
@ -330,12 +333,7 @@ export default function CustomTripDestinationDetailPage() {
// Destination-specific hotels // Destination-specific hotels
const destHotels = useMemo(() => { const destHotels = useMemo(() => {
if (!destination) return [] 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]) }, [allHotels, destination])
// Filtered hotels // Filtered hotels
@ -605,17 +603,12 @@ export default function CustomTripDestinationDetailPage() {
} }
await saveCustomTripHotel(item) 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) setIsHotelFormOpen(false)
} }
const handleConfirmDeleteHotel = async () => { const handleConfirmDeleteHotel = async () => {
if (!hotelToDelete) return if (!hotelToDelete) return
await deleteCustomTripHotel(hotelToDelete.id) await deleteCustomTripHotel(hotelToDelete.id)
setAllHotels((prev) => prev.filter((h) => h.id !== hotelToDelete.id))
setHotelToDelete(null) setHotelToDelete(null)
} }
@ -1361,7 +1354,7 @@ export default function CustomTripDestinationDetailPage() {
{/* Stars Filter */} {/* Stars Filter */}
<div className="flex items-center gap-1 p-1 bg-muted/60 rounded-xl border border-border/50 text-xs overflow-x-auto no-scrollbar max-w-full"> <div className="flex items-center gap-1 p-1 bg-muted/60 rounded-xl border border-border/50 text-xs overflow-x-auto no-scrollbar max-w-full">
{(['all', '5', '4', '3'] as const).map((s) => (
{(['all', '5', '4', '3', '2'] as const).map((s) => (
<button <button
key={s} key={s}
type="button" type="button"
@ -2036,6 +2029,22 @@ export default function CustomTripDestinationDetailPage() {
</label> </label>
) )
})} })}
{hotelFormAmenities
.filter((a) => !COMMON_AMENITIES.some((ca) => ca.name === a))
.map((customAm) => (
<label
key={customAm}
className="flex items-center gap-2 cursor-pointer text-xs text-foreground p-1 hover:bg-card rounded-lg"
>
<input
type="checkbox"
checked={true}
onChange={() => handleToggleHotelAmenity(customAm)}
className="rounded border-border text-primary focus:ring-primary"
/>
<span>{customAm}</span>
</label>
))}
</div> </div>
{/* Add Custom Amenity */} {/* Add Custom Amenity */}

29
src/features/custom-trip/CustomTripPage.tsx

@ -21,7 +21,10 @@ import {
deleteCustomTripDestination, deleteCustomTripDestination,
fetchCustomTripTransportRelations, fetchCustomTripTransportRelations,
fetchCustomTripHotels, fetchCustomTripHotels,
saveCustomTripHotel,
deleteCustomTripHotel,
} from './services/custom-trip-api' } from './services/custom-trip-api'
import { useHotelsCatalogStore } from '@/stores/hotels-catalog'
import { CustomTripOrdersTab } from './components/CustomTripOrdersTab' import { CustomTripOrdersTab } from './components/CustomTripOrdersTab'
import { CustomTripOriginsTab } from './components/CustomTripOriginsTab' import { CustomTripOriginsTab } from './components/CustomTripOriginsTab'
import { CustomTripDestinationsTab } from './components/CustomTripDestinationsTab' import { CustomTripDestinationsTab } from './components/CustomTripDestinationsTab'
@ -60,9 +63,11 @@ export default function CustomTripPage() {
const [isDestinationsLoading, setIsDestinationsLoading] = useState(true) const [isDestinationsLoading, setIsDestinationsLoading] = useState(true)
const [orders, setOrders] = useState<CustomTripOrderItem[]>([]) const [orders, setOrders] = useState<CustomTripOrderItem[]>([])
const [origins, setOrigins] = useState<CustomTripOriginItem[]>([]) const [origins, setOrigins] = useState<CustomTripOriginItem[]>([])
const [destinations, setDestinations] = useState<CustomTripDestinationItem[]>([])
const destinations = useHotelsCatalogStore((s) => s.destinations)
const setDestinations = useHotelsCatalogStore((s) => s.setDestinations)
const [relations, setRelations] = useState<CustomTripTransportRelationItem[]>([]) const [relations, setRelations] = useState<CustomTripTransportRelationItem[]>([])
const [hotels, setHotels] = useState<CustomTripHotelItem[]>([])
const hotels = useHotelsCatalogStore((s) => s.hotels)
const setHotels = useHotelsCatalogStore((s) => s.setHotels)
useEffect(() => { useEffect(() => {
let isMounted = true let isMounted = true
@ -195,29 +200,15 @@ export default function CustomTripPage() {
// Hotels CRUD // Hotels CRUD
const handleAddHotel = (item: CustomTripHotelItem) => { 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) => { const handleUpdateHotel = (item: CustomTripHotelItem) => {
setHotels((prev) => prev.map((h) => (h.id === item.id ? item : h)))
saveCustomTripHotel(item).catch(() => {})
} }
const handleDeleteHotel = (id: string | number) => { 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 // Orders update

21
src/features/custom-trip/components/CustomTripDestinationsTab.tsx

@ -30,6 +30,7 @@ import {
SelectValue, SelectValue,
} from '@/components/ui/select' } from '@/components/ui/select'
import type { CustomTripDestinationItem, CustomTripTransportRelationItem } from '../types' import type { CustomTripDestinationItem, CustomTripTransportRelationItem } from '../types'
import { useHotelsCatalogStore, doesHotelMatchDestination } from '@/stores/hotels-catalog'
interface CustomTripDestinationsTabProps { interface CustomTripDestinationsTabProps {
destinations: CustomTripDestinationItem[] destinations: CustomTripDestinationItem[]
@ -276,6 +277,15 @@ export function CustomTripDestinationsTab({
const navigate = useNavigate() const navigate = useNavigate()
const [search, setSearch] = useState('') const [search, setSearch] = useState('')
const [selectedCountry, setSelectedCountry] = useState<string>('all') const [selectedCountry, setSelectedCountry] = useState<string>('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) => { const getTransportCount = (item: CustomTripDestinationItem) => {
if (item.transportsCount !== undefined) return item.transportsCount if (item.transportsCount !== undefined) return item.transportsCount
@ -693,9 +703,16 @@ export function CustomTripDestinationsTab({
</span> </span>
</td> </td>
<td className="px-4 py-3.5 text-center"> <td className="px-4 py-3.5 text-center">
<span 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">
<span
onClick={(e) => {
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="مشاهده و مدیریت هتل‌های این مقصد"
>
<Ic name="bed" className="size-3.5 text-primary" /> <Ic name="bed" className="size-3.5 text-primary" />
<span className="font-mono">{toFa(item.hotelsCount)}</span>
<span className="font-mono">{toFa(getHotelCount(item))}</span>
<span className="text-[11px] text-muted-foreground">هتل</span> <span className="text-[11px] text-muted-foreground">هتل</span>
</span> </span>
</td> </td>

115
src/features/custom-trip/services/custom-trip-api.ts

@ -1,4 +1,5 @@
import { apiFetch } from '@/services/http' import { apiFetch } from '@/services/http'
import { useHotelsCatalogStore } from '@/stores/hotels-catalog'
import type { import type {
CustomTripOrderItem, CustomTripOrderItem,
CustomTripOriginItem, CustomTripOriginItem,
@ -418,7 +419,9 @@ export async function fetchCustomTripDestinations(): Promise<CustomTripDestinati
const remote = await apiFetch<CustomTripDestinationItem[]>( const remote = await apiFetch<CustomTripDestinationItem[]>(
'trip/custom/v2/catalog/destinations/?include_inactive=true' '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( export async function fetchCustomTripDestinationById(
@ -481,13 +484,22 @@ export async function saveCustomTripDestination(
body: JSON.stringify(payload), 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<void> { export async function deleteCustomTripDestination(id: string | number): Promise<void> {
await apiFetch(`trip/custom/v2/catalog/destinations/${id}/`, { await apiFetch(`trip/custom/v2/catalog/destinations/${id}/`, {
method: 'DELETE', method: 'DELETE',
}) })
useHotelsCatalogStore.getState().setDestinations(
(prev) => prev.filter((d) => String(d.id) !== String(id)),
true
)
} }
export async function fetchCustomTripTransports(): Promise<CustomTripTransportItem[]> { export async function fetchCustomTripTransports(): Promise<CustomTripTransportItem[]> {
@ -600,30 +612,68 @@ export async function deleteCustomTripTransportRelation(id: string | number): Pr
}) })
} }
export async function fetchCustomTripHotels(): Promise<CustomTripHotelItem[]> {
const remote = await apiFetch<any[]>('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>): 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: 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 ? 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<CustomTripHotelItem[]> {
const remote = await apiFetch<any[]>('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<CustomTripHotelItem> { export async function saveCustomTripHotel(item: CustomTripHotelItem): Promise<CustomTripHotelItem> {
@ -658,16 +708,17 @@ export async function saveCustomTripHotel(item: CustomTripHotelItem): Promise<Cu
body: JSON.stringify(payload), body: JSON.stringify(payload),
}) })
return {
...item,
id: res.id ?? item.id,
name: res.name || item.name,
cityName: res.cityName || item.cityName,
}
const saved = mapRawHotelToItem(res, item)
useHotelsCatalogStore.getState().upsertHotel(saved, item.id, true)
return saved
} }
export async function deleteCustomTripHotel(id: string | number): Promise<void> { export async function deleteCustomTripHotel(id: string | number): Promise<void> {
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)
} }

1441
src/features/tours/TourHotelsPage.tsx
File diff suppressed because it is too large
View File

1
src/features/tours/services/tour-api.ts

@ -109,6 +109,7 @@ export async function saveTourTranslations(
description?: string description?: string
tour_feature?: { title: string; icon?: string }[] tour_feature?: { title: string; icon?: string }[]
travel_tips?: Record<string, string> travel_tips?: Record<string, string>
tour_meta?: import('../types').TourMeta
translations?: Record<string, import('../types').TourTranslationData> translations?: Record<string, import('../types').TourTranslationData>
} }
): Promise<{ status: string; message: string }> { ): Promise<{ status: string; message: string }> {

17
src/features/tours/types.ts

@ -60,6 +60,21 @@ export interface AccommodationItem {
stars: number stars: number
distance_to_shrine: string distance_to_shrine: string
nights?: number nights?: number
hotel_id?: number | string
city_key?: string
}
export interface TransportStepItem {
id?: string
order?: number
from_city: string
to_city: string
vehicle_type: 'airplane' | 'train' | 'bus' | string
vehicle_label?: string
is_return?: boolean
departure_time?: string
carrier_name?: string
baggage_allowance?: string
} }
export interface TransportInfo { export interface TransportInfo {
@ -69,6 +84,7 @@ export interface TransportInfo {
arrival_city?: string arrival_city?: string
departure_time?: string departure_time?: string
baggage_allowance?: string baggage_allowance?: string
steps?: TransportStepItem[]
} }
export interface CancellationRule { export interface CancellationRule {
@ -80,6 +96,7 @@ export interface CancellationRule {
export interface TourMeta { export interface TourMeta {
accommodations?: AccommodationItem[] accommodations?: AccommodationItem[]
transport_info?: TransportInfo transport_info?: TransportInfo
transport_steps?: TransportStepItem[]
included_services?: string[] included_services?: string[]
excluded_services?: string[] excluded_services?: string[]
cancellation_policy?: CancellationRule[] cancellation_policy?: CancellationRule[]

32
src/locales/ar.json

@ -8,6 +8,7 @@
"tours": "الرحلات", "tours": "الرحلات",
"allTours": "جميع الرحلات", "allTours": "جميع الرحلات",
"ongoingTours": "الرحلات الجارية", "ongoingTours": "الرحلات الجارية",
"tourHotels": "الفنادق",
"customTrip": "رحلة مخصصة", "customTrip": "رحلة مخصصة",
"customTripOrders": "طلبات الرحلات المخصصة", "customTripOrders": "طلبات الرحلات المخصصة",
"customTripOrigins": "مدن الانطلاق", "customTripOrigins": "مدن الانطلاق",
@ -195,7 +196,8 @@
"disabled": "معطل", "disabled": "معطل",
"unknown": "غير محدد", "unknown": "غير محدد",
"days": "{count} أيام", "days": "{count} أيام",
"dayOne": "يوم واحد"
"dayOne": "يوم واحد",
"date": "التاريخ"
}, },
"tours": { "tours": {
"title": "إدارة الرحلات", "title": "إدارة الرحلات",
@ -236,7 +238,33 @@
"countryIran": "إيران", "countryIran": "إيران",
"countrySaudi": "السعودية", "countrySaudi": "السعودية",
"countrySyria": "سوريا", "countrySyria": "سوريا",
"countryOman": "عمان"
"countryOman": "عمان",
"hotelsTitle": "إدارة الفنادق والإقامة",
"hotelsSubtitle": "إدارة موحدة للفنادق ودرجة النجوم والمسافة إلى الحرم المطهر والمرافق والأسعار اليومية (مشتركة ومتزامنة مع الرحلة المخصصة)",
"hotelsRegisteredCount": "{count} فندق مسجل",
"viewDestinationInCustomTrip": "عرض ملف مدينة الوجهة",
"allDestinations": "جميع الوجهات",
"allStars": "جميع النجوم",
"starsCount": "{count} نجوم",
"searchHotelsPlaceholder": "البحث في اسم الفندق أو المدينة أو المسافة أو المرافق...",
"filterByDestination": "تصفية حسب وجهة المدينة",
"addHotel": "إضافة فندق جديد",
"editHotel": "تعديل بيانات الفندق",
"hotelDeletedSuccess": "تم حذف الفندق بنجاح.",
"hotelSavedSuccess": "تم حفظ بيانات الفندق ومزامنتها بنجاح عبر النظام.",
"sharedWithCustomTrip": "متزامن مع الرحلة المخصصة",
"noHotelsFound": "لم يتم العثور على أي فندق بهذه المواصفات.",
"kpiTotal": "إجمالي الفنادق المسجلة",
"kpiLuxury": "فنادق فاخرة (5 نجوم)",
"kpiActive": "الفنادق النشطة",
"kpiDestinations": "مدن الوجهات المغطاة",
"adultRate": "سعر البالغ",
"childRate": "سعر الطفل",
"pricePerDay": "السعر اليومي",
"selectDestinationCity": "اختر مدينة الوجهة",
"cityDestinationLabel": "مدينة الوجهة:",
"enterOrSelectCity": "اختر اسم المدينة أو الوجهة",
"customCityName": "اسم مدينة مخصص (إذا لم يكن في القائمة)"
}, },
"services": { "services": {
"title": "مركز الخدمات", "title": "مركز الخدمات",

32
src/locales/en.json

@ -8,6 +8,7 @@
"tours": "Tours", "tours": "Tours",
"allTours": "All Tours", "allTours": "All Tours",
"ongoingTours": "Ongoing Tours", "ongoingTours": "Ongoing Tours",
"tourHotels": "Hotels",
"customTrip": "Custom Trip", "customTrip": "Custom Trip",
"customTripOrders": "Trip Requests & Orders", "customTripOrders": "Trip Requests & Orders",
"customTripOrigins": "Origin Cities", "customTripOrigins": "Origin Cities",
@ -195,7 +196,8 @@
"disabled": "Disabled", "disabled": "Disabled",
"unknown": "Unknown", "unknown": "Unknown",
"days": "{count} Days", "days": "{count} Days",
"dayOne": "1 Day"
"dayOne": "1 Day",
"date": "Date"
}, },
"tours": { "tours": {
"title": "Tour Management", "title": "Tour Management",
@ -236,7 +238,33 @@
"countryIran": "Iran", "countryIran": "Iran",
"countrySaudi": "Saudi Arabia", "countrySaudi": "Saudi Arabia",
"countrySyria": "Syria", "countrySyria": "Syria",
"countryOman": "Oman"
"countryOman": "Oman",
"hotelsTitle": "Hotels & Stays Management",
"hotelsSubtitle": "Unified management of hotels, star ratings, distance to holy shrines, amenities, and daily rates (shared and synchronized with Custom Trip)",
"hotelsRegisteredCount": "{count} Hotels Registered",
"viewDestinationInCustomTrip": "View Destination Profile",
"allDestinations": "All Destinations",
"allStars": "All Stars",
"starsCount": "{count} Stars",
"searchHotelsPlaceholder": "Search by hotel name, city, distance to shrine, or amenities...",
"filterByDestination": "Filter by Destination City",
"addHotel": "Add New Hotel",
"editHotel": "Edit Hotel Details",
"hotelDeletedSuccess": "Hotel deleted successfully.",
"hotelSavedSuccess": "Hotel saved and synchronized successfully across the system.",
"sharedWithCustomTrip": "Synced with Custom Trip",
"noHotelsFound": "No hotels found matching criteria.",
"kpiTotal": "Total Registered Hotels",
"kpiLuxury": "Luxury Hotels (5 Stars)",
"kpiActive": "Active Hotels",
"kpiDestinations": "Covered Destinations",
"adultRate": "Adult Rate",
"childRate": "Child Rate",
"pricePerDay": "Daily Rate",
"selectDestinationCity": "Select Destination City",
"cityDestinationLabel": "Destination City:",
"enterOrSelectCity": "Select city or destination",
"customCityName": "Custom city name (if not in list)"
}, },
"services": { "services": {
"title": "Services Center", "title": "Services Center",

32
src/locales/fa.json

@ -8,6 +8,7 @@
"tours": "تورها", "tours": "تورها",
"allTours": "فهرست همه تورها", "allTours": "فهرست همه تورها",
"ongoingTours": "تورهای در حال برگزاری", "ongoingTours": "تورهای در حال برگزاری",
"tourHotels": "هتل‌ها",
"customTrip": "سفر اختصاصی", "customTrip": "سفر اختصاصی",
"customTripOrders": "سفارش‌های ثبت‌شده", "customTripOrders": "سفارش‌های ثبت‌شده",
"customTripOrigins": "شهرهای مبدأ", "customTripOrigins": "شهرهای مبدأ",
@ -195,7 +196,8 @@
"disabled": "غیرفعال", "disabled": "غیرفعال",
"unknown": "نامشخص", "unknown": "نامشخص",
"days": "{count} روز", "days": "{count} روز",
"dayOne": "1 روز"
"dayOne": "1 روز",
"date": "تاریخ"
}, },
"tours": { "tours": {
"title": "مدیریت تورها", "title": "مدیریت تورها",
@ -236,7 +238,33 @@
"countryIran": "ایران", "countryIran": "ایران",
"countrySaudi": "عربستان", "countrySaudi": "عربستان",
"countrySyria": "سوریه", "countrySyria": "سوریه",
"countryOman": "عمان"
"countryOman": "عمان",
"hotelsTitle": "مدیریت هتل‌ها و اقامتگاه‌ها",
"hotelsSubtitle": "مدیریت یکپارچه هتل‌ها، درجه ستاره، فاصله تا حرم مطهر، امکانات و نرخ‌های اقامت (مشترک و همگام با سفر اختصاصی)",
"hotelsRegisteredCount": "{count} هتل ثبت‌شده",
"viewDestinationInCustomTrip": "مشاهده شناسنامه مقصد",
"allDestinations": "همه مقاصد",
"allStars": "همه ستاره‌ها",
"starsCount": "{count} ستاره",
"searchHotelsPlaceholder": "جستجوی نام هتل، شهر، فاصله تا حرم یا امکانات...",
"filterByDestination": "فیلتر بر اساس شهر مقصد",
"addHotel": "افزودن هتل جدید",
"editHotel": "ویرایش مشخصات هتل",
"hotelDeletedSuccess": "هتل با موفقیت حذف شد.",
"hotelSavedSuccess": "مشخصات هتل با موفقیت ذخیره و در سراسر سامانه همگام شد.",
"sharedWithCustomTrip": "همگام با سفر اختصاصی",
"noHotelsFound": "هیچ هتلی با این مشخصات یافت نشد.",
"kpiTotal": "کل هتل‌های ثبت‌شده",
"kpiLuxury": "هتل‌های لوکس (۵ ستاره)",
"kpiActive": "هتل‌های فعال",
"kpiDestinations": "شهرهای دارای هتل",
"adultRate": "نرخ بزرگسال",
"childRate": "نرخ کودک",
"pricePerDay": "نرخ روزانه",
"selectDestinationCity": "انتخاب شهر مقصد",
"cityDestinationLabel": "شهر مقصد:",
"enterOrSelectCity": "نام شهر یا مقصد را انتخاب کنید",
"customCityName": "نام شهر دلخواه (در صورت نبود در لیست)"
}, },
"services": { "services": {
"title": "مرکز خدمات", "title": "مرکز خدمات",

207
src/stores/hotels-catalog.ts

@ -0,0 +1,207 @@
import { create } from 'zustand'
import type { CustomTripHotelItem, CustomTripDestinationItem } from '@/features/custom-trip/types'
import { OFFICIAL_PRESET_CITIES } from '@/features/custom-trip/components/CustomTripDestinationsTab'
/**
* بررسی تطابق هتل با شهر مقصد (پشتیبانی از نام فارسی، عربی، انگلیسی و کلید استاندارد مقصد)
*/
export function doesHotelMatchDestination(
hotel: CustomTripHotelItem,
dest: CustomTripDestinationItem | string | null | undefined
): boolean {
if (!dest) return false
const hCity = (hotel.cityName || '').trim().toLowerCase()
if (!hCity) return false
if (typeof dest === 'string') {
const target = dest.trim().toLowerCase()
if (!target || target === 'all') return true
return hCity === target || hCity.includes(target) || target.includes(hCity)
}
const candidates = new Set<string>()
if (dest.name) candidates.add(dest.name.trim().toLowerCase())
if (dest.nameEn) candidates.add(dest.nameEn.trim().toLowerCase())
if (dest.id) candidates.add(String(dest.id).trim().toLowerCase())
if (dest.translations) {
Object.values(dest.translations).forEach((t) => {
if (t?.name) candidates.add(t.name.trim().toLowerCase())
})
}
const preset = OFFICIAL_PRESET_CITIES.find(
(c) =>
c.id.toLowerCase() === String(dest.id).toLowerCase() ||
c.names.fa === dest.name ||
c.names.ar === dest.name ||
c.names.en.toLowerCase() === (dest.nameEn || '').toLowerCase()
)
if (preset) {
candidates.add(preset.id.toLowerCase())
Object.values(preset.names).forEach((n) => {
if (n) candidates.add(n.trim().toLowerCase())
})
}
for (const cand of candidates) {
if (!cand) continue
if (hCity === cand || hCity.includes(cand) || cand.includes(hCity)) {
return true
}
}
return false
}
function recalculateDestinationHotelCounts(
destinations: CustomTripDestinationItem[],
hotels: CustomTripHotelItem[]
): CustomTripDestinationItem[] {
if (!destinations.length) return destinations
return destinations.map((dest) => {
const count = hotels.filter((h) => doesHotelMatchDestination(h, dest)).length
return {
...dest,
hotelsCount: count,
}
})
}
const SYNC_CHANNEL_NAME = 'aqila_hotels_catalog_sync'
let broadcastChannel: BroadcastChannel | null = null
if (typeof window !== 'undefined' && 'BroadcastChannel' in window) {
try {
broadcastChannel = new BroadcastChannel(SYNC_CHANNEL_NAME)
} catch {
broadcastChannel = null
}
}
interface HotelsCatalogState {
hotels: CustomTripHotelItem[]
destinations: CustomTripDestinationItem[]
isLoaded: boolean
lastUpdatedAt: number
setHotels: (
updater: CustomTripHotelItem[] | ((prev: CustomTripHotelItem[]) => CustomTripHotelItem[]),
broadcast?: boolean
) => void
setDestinations: (
updater:
| CustomTripDestinationItem[]
| ((prev: CustomTripDestinationItem[]) => CustomTripDestinationItem[]),
broadcast?: boolean
) => void
upsertHotel: (hotel: CustomTripHotelItem, previousId?: string | number, broadcast?: boolean) => void
removeHotel: (id: string | number, broadcast?: boolean) => void
}
export const useHotelsCatalogStore = create<HotelsCatalogState>((set, get) => ({
hotels: [],
destinations: [],
isLoaded: false,
lastUpdatedAt: 0,
setHotels: (updater, broadcast = false) => {
const nextHotels = typeof updater === 'function' ? updater(get().hotels) : updater
const nextDestinations = recalculateDestinationHotelCounts(get().destinations, nextHotels)
set({
hotels: nextHotels,
destinations: nextDestinations,
isLoaded: true,
lastUpdatedAt: Date.now(),
})
if (broadcast && broadcastChannel) {
try {
broadcastChannel.postMessage({ type: 'SET_HOTELS', hotels: nextHotels })
} catch {}
}
},
setDestinations: (updater, broadcast = false) => {
const rawDestinations =
typeof updater === 'function' ? updater(get().destinations) : updater
const currentHotels = get().hotels
const nextDestinations =
currentHotels.length > 0
? recalculateDestinationHotelCounts(rawDestinations, currentHotels)
: rawDestinations
set({
destinations: nextDestinations,
lastUpdatedAt: Date.now(),
})
if (broadcast && broadcastChannel) {
try {
broadcastChannel.postMessage({ type: 'SET_DESTINATIONS', destinations: nextDestinations })
} catch {}
}
},
upsertHotel: (hotel, previousId, broadcast = true) => {
const current = get().hotels
const matchId = (h: CustomTripHotelItem) =>
String(h.id) === String(hotel.id) ||
(previousId !== undefined && String(h.id) === String(previousId))
const exists = current.some(matchId)
const nextHotels = exists
? current.map((h) => (matchId(h) ? hotel : h))
: [hotel, ...current]
const nextDestinations = recalculateDestinationHotelCounts(get().destinations, nextHotels)
set({
hotels: nextHotels,
destinations: nextDestinations,
isLoaded: true,
lastUpdatedAt: Date.now(),
})
if (broadcast && broadcastChannel) {
try {
broadcastChannel.postMessage({
type: 'UPSERT_HOTEL',
hotel,
previousId,
})
} catch {}
}
},
removeHotel: (id, broadcast = true) => {
const nextHotels = get().hotels.filter((h) => String(h.id) !== String(id))
const nextDestinations = recalculateDestinationHotelCounts(get().destinations, nextHotels)
set({
hotels: nextHotels,
destinations: nextDestinations,
lastUpdatedAt: Date.now(),
})
if (broadcast && broadcastChannel) {
try {
broadcastChannel.postMessage({
type: 'REMOVE_HOTEL',
id,
})
} catch {}
}
},
}))
if (broadcastChannel) {
broadcastChannel.onmessage = (event) => {
const data = event.data
if (!data || typeof data !== 'object') return
if (data.type === 'SET_HOTELS' && Array.isArray(data.hotels)) {
useHotelsCatalogStore.getState().setHotels(data.hotels, false)
} else if (data.type === 'SET_DESTINATIONS' && Array.isArray(data.destinations)) {
useHotelsCatalogStore.getState().setDestinations(data.destinations, false)
} else if (data.type === 'UPSERT_HOTEL' && data.hotel) {
useHotelsCatalogStore.getState().upsertHotel(data.hotel, data.previousId, false)
} else if (data.type === 'REMOVE_HOTEL' && data.id !== undefined) {
useHotelsCatalogStore.getState().removeHotel(data.id, false)
}
}
}
Loading…
Cancel
Save