Compare commits

...

3 Commits

  1. 22
      src/features/auth/LoginPage.tsx
  2. 42
      src/features/custom-trip/CustomTripOrderDetailPage.tsx
  3. 55
      src/features/custom-trip/CustomTripPage.tsx
  4. 32
      src/features/custom-trip/components/CustomTripOrderReviewDialog.tsx
  5. 69
      src/features/custom-trip/components/CustomTripOrdersTab.tsx
  6. 39
      src/features/custom-trip/services/__tests__/custom-trip-api.test.ts
  7. 48
      src/features/custom-trip/services/custom-trip-api.ts
  8. 2
      src/features/custom-trip/types.ts
  9. 218
      src/features/services/components/DuasServiceView.tsx
  10. 8
      src/features/services/services/trip-etiquette-api.ts
  11. 12
      src/features/services/types/trip-etiquette.ts
  12. 24
      src/lib/date-utils.ts
  13. 18
      src/locales/ar.json
  14. 18
      src/locales/en.json
  15. 18
      src/locales/fa.json
  16. 2
      vite.config.ts

22
src/features/auth/LoginPage.tsx

@ -43,11 +43,6 @@ export default function LoginPage() {
loginMutation.mutate({ email: email.trim(), password })
}
const fillDemo = () => {
setEmail('admin@gmail.com')
setPassword('admin')
}
const errorMessage =
loginMutation.error instanceof ApiError
? loginMutation.error.message
@ -78,23 +73,6 @@ export default function LoginPage() {
onSubmit={submit}
className="space-y-4 rounded-2xl border border-border-soft bg-card/60 p-6 shadow-2xl backdrop-blur"
>
{/* راهنمای لاگین دمو */}
<div className="flex items-center justify-between rounded-xl border border-primary/20 bg-primary/10 p-3 text-xs">
<div>
<span className="font-bold text-primary block">{t('auth.demoBoxTitle')}</span>
<span dir="ltr" className="text-[11px] text-grey-2 font-mono">admin@gmail.com / admin</span>
</div>
<Button
type="button"
variant="outline"
size="sm"
onClick={fillDemo}
className="h-7 text-[11px]"
>
{t('auth.autoFill')}
</Button>
</div>
<Field label={t('auth.emailLabel')}>
<Input
type="email"

42
src/features/custom-trip/CustomTripOrderDetailPage.tsx

@ -8,7 +8,7 @@ import { Textarea } from '@/components/ui/textarea'
import { Shimmer, ShimmerBox, ShimmerLine } from '@/components/shared/shimmer_frontend'
import { Ic } from '@/icons'
import { toFa, toEn, formatAmount } from '@/lib/utils'
import { formatDualDate } from '@/lib/date-utils'
import { formatDualDate, formatDateTimeByLanguage, formatDateRangeByLanguage, parseTravelDateRange } from '@/lib/date-utils'
import { UniversalDatePicker } from '@/components/shared/UniversalDatePicker'
import { useTranslation } from '@/i18n'
import { useBillingBadgeStore } from '@/stores/billing-badge'
@ -226,7 +226,7 @@ export default function CustomTripOrderDetailPage() {
const normalized = normalizeLegsChain(
baseOrigin,
orderData.legs || [],
orderData.legs?.[0]?.departureDate || orderData.created
orderData.startDate || orderData.legs?.[0]?.departureDate || orderData.created
)
setEditLegs(normalized)
setEditPrice(Number(orderData.finalPrice ?? orderData.priceEstimate ?? 0))
@ -530,6 +530,8 @@ export default function CustomTripOrderDetailPage() {
try {
const updated = await updateCustomTripOrder(order.id, {
originCity: editOriginCity,
startDate: editLegs[0]?.departureDate || order.startDate || null,
travelDateText: order.travelDateText || editLegs[0]?.departureDate || '',
legs: editLegs,
priceEstimate: editPrice,
adminNotes: editNotes,
@ -563,6 +565,8 @@ export default function CustomTripOrderDetailPage() {
try {
const updated = await updateCustomTripOrder(order.id, {
originCity: editOriginCity,
startDate: editLegs[0]?.departureDate || order.startDate || null,
travelDateText: order.travelDateText || editLegs[0]?.departureDate || '',
legs: editLegs,
priceEstimate: editPrice,
adminNotes: editNotes,
@ -1708,10 +1712,42 @@ export default function CustomTripOrderDetailPage() {
</span>
</div>
{(() => {
const parsedRange = parseTravelDateRange(
order.travelDateText,
(editLegs[0]?.departureDate || order.startDate) as string | null
)
return (
<div className="flex items-start justify-between gap-2 pb-2 border-b border-border/50">
<span className="text-muted-foreground text-xs shrink-0">
{parsedRange.endIso
? t('customTrip.approxTravelRange')
: t('customTrip.tripStartDate')}:
</span>
<div className="text-end">
<span className="font-mono font-bold text-primary block leading-relaxed">
{parsedRange.startIso && parsedRange.endIso
? formatDateRangeByLanguage(parsedRange.startIso, parsedRange.endIso, language)
: (editLegs[0]?.departureDate || order.startDate)
? formatDualDate((editLegs[0]?.departureDate || order.startDate) as string, language)
: '—'}
</span>
{!parsedRange.endIso &&
order.travelDateText &&
!/^\d{4}-\d{2}-\d{2}/.test(order.travelDateText) && (
<span className="text-[11px] text-muted-foreground block mt-0.5">
({order.travelDateText})
</span>
)}
</div>
</div>
)
})()}
<div className="flex items-center justify-between">
<span className="text-muted-foreground text-xs">{t('customTrip.createdDate')}:</span>
<span className="font-mono text-foreground">
{formatDualDate(order.created, language)}
{formatDateTimeByLanguage(order.created, language)}
</span>
</div>
</div>

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

@ -1,4 +1,4 @@
import React, { useState, useEffect } from 'react'
import React, { useState, useEffect, useCallback, useRef } from 'react'
import { useParams, useNavigate, useSearchParams, useLocation } from 'react-router-dom'
import { Ic, IconName } from '@/icons'
import { Shimmer } from '@/components/shared/shimmer_frontend'
@ -59,6 +59,7 @@ export default function CustomTripPage() {
const activeTab = activeTabParam && TABS.some((tab) => tab.id === activeTabParam) ? activeTabParam : 'orders'
const [isOrdersLoading, setIsOrdersLoading] = useState(true)
const [isOrdersRefreshing, setIsOrdersRefreshing] = useState(false)
const [isOriginsLoading, setIsOriginsLoading] = useState(true)
const [isDestinationsLoading, setIsDestinationsLoading] = useState(true)
const [orders, setOrders] = useState<CustomTripOrderItem[]>([])
@ -68,6 +69,56 @@ export default function CustomTripPage() {
const [relations, setRelations] = useState<CustomTripTransportRelationItem[]>([])
const hotels = useHotelsCatalogStore((s) => s.hotels)
const setHotels = useHotelsCatalogStore((s) => s.setHotels)
const isMountedRef = useRef(true)
useEffect(() => {
isMountedRef.current = true
return () => {
isMountedRef.current = false
}
}, [])
const handleRefreshOrders = useCallback(async () => {
setIsOrdersRefreshing(true)
try {
const data = await fetchCustomTripOrders()
if (isMountedRef.current) {
setOrders(data)
}
} catch {
} finally {
if (isMountedRef.current) {
setIsOrdersRefreshing(false)
}
}
}, [])
useEffect(() => {
if (activeTab !== 'orders') return
const onFocus = () => {
void handleRefreshOrders()
}
const onVisibilityChange = () => {
if (document.visibilityState === 'visible') {
void handleRefreshOrders()
}
}
window.addEventListener('focus', onFocus)
document.addEventListener('visibilitychange', onVisibilityChange)
const intervalId = window.setInterval(() => {
if (document.visibilityState === 'visible') {
void handleRefreshOrders()
}
}, 15000)
return () => {
window.removeEventListener('focus', onFocus)
document.removeEventListener('visibilitychange', onVisibilityChange)
window.clearInterval(intervalId)
}
}, [activeTab, handleRefreshOrders])
useEffect(() => {
let isMounted = true
@ -303,6 +354,8 @@ export default function CustomTripPage() {
<CustomTripOrdersTab
orders={orders}
onOrderUpdated={handleOrderUpdated}
onRefresh={() => void handleRefreshOrders()}
isRefreshing={isOrdersRefreshing}
origins={origins}
destinations={destinations}
hotels={hotels}

32
src/features/custom-trip/components/CustomTripOrderReviewDialog.tsx

@ -14,7 +14,7 @@ import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Ic } from '@/icons'
import { toFa, toEn, formatAmount } from '@/lib/utils'
import { formatDualDate } from '@/lib/date-utils'
import { formatDualDate, formatDateRangeByLanguage, parseTravelDateRange } from '@/lib/date-utils'
import { UniversalDatePicker } from '@/components/shared/UniversalDatePicker'
import { useTranslation } from '@/i18n'
import { useBillingBadgeStore } from '@/stores/billing-badge'
@ -248,7 +248,7 @@ export function CustomTripOrderReviewDialog({
useEffect(() => {
if (order) {
const orig = order.originCity || ''
const defaultStart = getDefaultBaseDate(order.created)
const defaultStart = order.startDate || order.legs?.[0]?.departureDate || getDefaultBaseDate(order.created)
setEditOriginCity(orig)
const initialLegs: CustomTripLeg[] =
order.legs && order.legs.length > 0
@ -594,6 +594,8 @@ export function CustomTripOrderReviewDialog({
priceEstimate: Number(editPrice),
adminNotes: editNotes,
originCity: editOriginCity,
startDate: editLegs[0]?.departureDate || order.startDate || null,
travelDateText: order.travelDateText || editLegs[0]?.departureDate || '',
legs: editLegs,
transferToBilling: false,
})
@ -625,6 +627,8 @@ export function CustomTripOrderReviewDialog({
priceEstimate: finalAmount,
adminNotes: editNotes,
originCity: editOriginCity,
startDate: editLegs[0]?.departureDate || order.startDate || null,
travelDateText: order.travelDateText || editLegs[0]?.departureDate || '',
legs: editLegs,
transferToBilling: true,
})
@ -751,7 +755,7 @@ export function CustomTripOrderReviewDialog({
</div>
{/* Customer Info Card */}
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3 p-3.5 rounded-xl bg-muted/40 border border-border/60 text-xs sm:text-sm">
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 p-3.5 rounded-xl bg-muted/40 border border-border/60 text-xs sm:text-sm">
<div>
<span className="text-muted-foreground text-xs block">{t('customTrip.passengerName')}:</span>
<span className="font-bold text-foreground">
@ -772,6 +776,28 @@ export function CustomTripOrderReviewDialog({
{order.infantsCount > 0 && `، ${toFa(order.infantsCount)} ${t('customTrip.infants')}`}
</span>
</div>
{(() => {
const parsedRange = parseTravelDateRange(
order.travelDateText,
(editLegs[0]?.departureDate || order.startDate) as string | null
)
return (
<div>
<span className="text-muted-foreground text-xs block">
{parsedRange.endIso
? t('customTrip.approxTravelRange')
: t('customTrip.tripStartDate')}:
</span>
<span className="font-mono font-bold text-primary">
{parsedRange.startIso && parsedRange.endIso
? formatDateRangeByLanguage(parsedRange.startIso, parsedRange.endIso, language)
: (editLegs[0]?.departureDate || order.startDate)
? formatDualDate((editLegs[0]?.departureDate || order.startDate) as string, language)
: '—'}
</span>
</div>
)
})()}
</div>
{/* Origin City Selector */}

69
src/features/custom-trip/components/CustomTripOrdersTab.tsx

@ -15,7 +15,13 @@ import {
import { Ic } from '@/icons'
import { toFa } from '@/lib/utils'
import { useTranslation } from '@/i18n'
import { formatDateByLanguage } from '@/lib/date-utils'
import {
formatDateByLanguage,
formatDateTimeByLanguage,
formatDateRangeByLanguage,
parseTravelDateRange,
} from '@/lib/date-utils'
import { sortOrdersByCreatedDesc } from '../services/custom-trip-api'
import type {
CustomTripOrderItem,
CustomTripOrderStatus,
@ -27,6 +33,8 @@ import type {
interface CustomTripOrdersTabProps {
orders: CustomTripOrderItem[]
onOrderUpdated: (updated: CustomTripOrderItem) => void
onRefresh?: () => void
isRefreshing?: boolean
origins?: CustomTripOriginItem[]
destinations?: CustomTripDestinationItem[]
hotels?: CustomTripHotelItem[]
@ -35,6 +43,8 @@ interface CustomTripOrdersTabProps {
export function CustomTripOrdersTab({
orders,
onOrderUpdated,
onRefresh,
isRefreshing = false,
origins = [],
destinations = [],
hotels = [],
@ -102,17 +112,19 @@ export function CustomTripOrdersTab({
}
}
const filteredOrders = orders.filter((order) => {
const matchesStatus = statusFilter === 'all' || order.status === statusFilter
const term = search.trim().toLowerCase()
const matchesSearch =
!term ||
order.id.toString().includes(term) ||
(order.user.fullName && order.user.fullName.toLowerCase().includes(term)) ||
(order.originCity && order.originCity.toLowerCase().includes(term)) ||
order.destinations.some((d) => d.toLowerCase().includes(term))
return matchesStatus && matchesSearch
})
const filteredOrders = sortOrdersByCreatedDesc(
orders.filter((order) => {
const matchesStatus = statusFilter === 'all' || order.status === statusFilter
const term = search.trim().toLowerCase()
const matchesSearch =
!term ||
order.id.toString().includes(term) ||
(order.user.fullName && order.user.fullName.toLowerCase().includes(term)) ||
(order.originCity && order.originCity.toLowerCase().includes(term)) ||
order.destinations.some((d) => d.toLowerCase().includes(term))
return matchesStatus && matchesSearch
})
)
return (
<div className="space-y-4">
@ -211,6 +223,19 @@ export function CustomTripOrdersTab({
className="ps-9 h-10 rounded-xl bg-background border-border/60 text-xs sm:text-sm"
/>
</div>
{onRefresh && (
<Button
type="button"
variant="outline"
size="sm"
onClick={onRefresh}
disabled={isRefreshing}
className="h-10 px-3.5 rounded-xl gap-2 text-xs font-semibold border-border/60 shrink-0 cursor-pointer"
>
<Ic name="refresh" className={`size-4 ${isRefreshing ? 'animate-spin' : ''}`} />
<span>{t(isRefreshing ? 'dashboard.refreshing' : 'common.refresh')}</span>
</Button>
)}
</div>
{/* Status filter chips */}
@ -392,6 +417,24 @@ export function CustomTripOrdersTab({
.join(' | ')}
</div>
)}
{(order.startDate || order.legs?.[0]?.departureDate || order.travelDateText) && (() => {
const parsedRange = parseTravelDateRange(
order.travelDateText,
(order.startDate || order.legs?.[0]?.departureDate) as string | null
)
const fallbackDate = (order.startDate || order.legs?.[0]?.departureDate) as string | undefined
if (!parsedRange.startIso && !fallbackDate) return null
return (
<div className="text-[11px] text-primary font-mono font-medium mt-1 flex items-center gap-1">
<Ic name="calendar" className="size-3 shrink-0" />
<span>
{parsedRange.endIso
? `${t('customTrip.approxTravelRange')}: ${formatDateRangeByLanguage(parsedRange.startIso, parsedRange.endIso, language)}`
: `${t('customTrip.tripStartDate')}: ${formatDateByLanguage(fallbackDate || parsedRange.startIso, language)}`}
</span>
</div>
)
})()}
</TableCell>
<TableCell className="px-4 py-3.5 text-center">
<span className="inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-xl bg-card border border-border/70 text-foreground">
@ -449,7 +492,7 @@ export function CustomTripOrdersTab({
</div>
</TableCell>
<TableCell className="px-4 py-3.5 text-center font-mono text-xs text-muted-foreground">
{formatDateByLanguage(order.created, language)}
{formatDateTimeByLanguage(order.created, language)}
</TableCell>
<TableCell className="px-4 py-3.5 text-center" onClick={(e) => e.stopPropagation()}>
<Button

39
src/features/custom-trip/services/__tests__/custom-trip-api.test.ts

@ -0,0 +1,39 @@
import { describe, expect, it } from 'vitest'
import { sortOrdersByCreatedDesc } from '../custom-trip-api'
describe('sortOrdersByCreatedDesc', () => {
it('sorts orders by creation date and time from newest to oldest', () => {
const input = [
{ id: 150, created: '2026-10-24T16:08:51.649117' },
{ id: 153, created: '2026-10-26T15:37:35.936085' },
{ id: 156, created: '2026-11-01T15:54:15.359013' },
{ id: 155, created: '2026-10-26T18:45:37.290538' },
{ id: 154, created: '2026-10-26T16:52:11.347603' },
]
const sorted = sortOrdersByCreatedDesc(input)
expect(sorted.map((o) => o.id)).toEqual([156, 155, 154, 153, 150])
})
it('uses id descending as deterministic tie-breaker when timestamps match', () => {
const input = [
{ id: 10, created: '2026-10-26T12:00:00' },
{ id: 12, created: '2026-10-26T12:00:00' },
{ id: 11, created: '2026-10-26T12:00:00' },
]
const sorted = sortOrdersByCreatedDesc(input)
expect(sorted.map((o) => o.id)).toEqual([12, 11, 10])
})
it('handles missing or invalid created values without throwing', () => {
const input = [
{ id: 1, created: '' },
{ id: 2, created: 'invalid-date' },
{ id: 3, created: '2026-11-01T10:00:00' },
]
const sorted = sortOrdersByCreatedDesc(input)
expect(sorted.map((o) => o.id)).toEqual([3, 2, 1])
})
})

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

@ -64,6 +64,8 @@ function mapBackendOrderToPanel(raw: any): CustomTripOrderItem {
const rawServices = Array.isArray(raw.services) ? raw.services : []
const originCity = raw.origin_city || raw.originCity || ''
const destinations: string[] = Array.isArray(raw.destinations) ? raw.destinations : []
const rawStartDate: string | null = raw.start_date || raw.startDate || null
const rawTravelDateText: string = raw.travel_date_text || raw.travelDateText || ''
let legs = rawLegs.map((leg: any, idx: number) => {
const isReturn = Boolean(
@ -145,7 +147,7 @@ function mapBackendOrderToPanel(raw: any): CustomTripOrderItem {
})
}
let curDate = legs[0].departureDate || getDefaultStartDateIso(raw.created)
let curDate = legs[0].departureDate || rawStartDate || getDefaultStartDateIso(raw.created)
legs = legs.map((l, idx) => {
const fromCity = idx === 0 ? originCity || l.fromCity : legs[idx - 1].toCity || l.fromCity
if (l.isReturn) {
@ -224,17 +226,46 @@ function mapBackendOrderToPanel(raw: any): CustomTripOrderItem {
factorId: raw.factor_id ?? null,
factorNumber: raw.factor_number ?? null,
status: (raw.status || 'PENDING') as CustomTripOrderStatus,
startDate: rawStartDate || legs[0]?.departureDate || stays[0]?.check_in || null,
travelDateText: rawTravelDateText || '',
created: raw.created || new Date().toISOString(),
detail: cleanLegacyDetail(raw.detail),
adminNotes: raw.admin_notes || raw.adminNotes || '',
}
}
export function sortOrdersByCreatedDesc<T extends { created?: string | null; id: number }>(
orders: T[]
): T[] {
return [...orders].sort((a, b) => {
const timeA = a.created ? Date.parse(a.created) : 0
const timeB = b.created ? Date.parse(b.created) : 0
const safeA = Number.isNaN(timeA) ? 0 : timeA
const safeB = Number.isNaN(timeB) ? 0 : timeB
if (safeB !== safeA) return safeB - safeA
return Number(b.id) - Number(a.id)
})
}
export async function fetchCustomTripOrders(): Promise<CustomTripOrderItem[]> {
try {
const res = await apiFetch<any>('trip/custom/v2/admin/orders/?page_size=100')
const list = Array.isArray(res) ? res : Array.isArray(res?.results) ? res.results : []
return list.map(mapBackendOrderToPanel)
const allRaw: any[] = []
let page = 1
const maxPages = 20
while (page <= maxPages) {
const res = await apiFetch<any>(`trip/custom/v2/admin/orders/?page=${page}&page_size=200`)
if (Array.isArray(res)) {
allRaw.push(...res)
break
}
const results = Array.isArray(res?.results) ? res.results : []
allRaw.push(...results)
if (!res?.next || results.length === 0) break
page += 1
}
return sortOrdersByCreatedDesc(allRaw.map(mapBackendOrderToPanel))
} catch (err) {
console.warn('[CustomTrip API] Could not fetch admin orders from v2 endpoint:', err)
return []
@ -267,6 +298,8 @@ export async function updateCustomTripOrder(
priceEstimate?: number
adminNotes?: string
originCity?: string
startDate?: string | null
travelDateText?: string
legs?: {
fromCity: string
toCity: string
@ -289,6 +322,13 @@ export async function updateCustomTripOrder(
if (data.originCity) {
itineraryPayload.origin_city = data.originCity
}
const effectiveStartDate = data.startDate || data.legs?.[0]?.departureDate || null
if (effectiveStartDate) {
itineraryPayload.start_date = String(effectiveStartDate).slice(0, 10)
}
if (data.travelDateText !== undefined) {
itineraryPayload.travel_date_text = data.travelDateText
}
if (Array.isArray(data.legs) && data.legs.length > 0) {
itineraryPayload.legs = data.legs.map((leg, idx) => ({
sequence: idx + 1,

2
src/features/custom-trip/types.ts

@ -64,6 +64,8 @@ export interface CustomTripOrderItem {
factorId?: number | null
factorNumber?: number | null
status: CustomTripOrderStatus
startDate?: string | null
travelDateText?: string
created: string
detail?: string
adminNotes?: string

218
src/features/services/components/DuasServiceView.tsx

@ -1,4 +1,5 @@
import React, { useState, useEffect, useMemo } from 'react'
import { useTranslation } from '@/i18n'
import { Ic } from '@/icons'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
@ -60,6 +61,7 @@ function normalizeCityName(rawName: string): string {
}
export function DuasServiceView() {
const { t } = useTranslation()
const [duas, setDuas] = useState<DuaItem[]>([])
const [isLoading, setIsLoading] = useState(true)
const [isRefreshing, setIsRefreshing] = useState(false)
@ -95,6 +97,14 @@ export function DuasServiceView() {
const [formNameEn, setFormNameEn] = useState('')
const [formNameRu, setFormNameRu] = useState('')
const [formNameId, setFormNameId] = useState('')
const [formDescriptions, setFormDescriptions] = useState<Record<'fa' | 'ar' | 'en' | 'ru' | 'id', string>>({
fa: '',
ar: '',
en: '',
ru: '',
id: '',
})
const [activeDescLang, setActiveDescLang] = useState<'fa' | 'ar' | 'en' | 'ru' | 'id'>('fa')
const [formCityIds, setFormCityIds] = useState<number[]>([])
// نگهداری دسته‌بندی‌های انتخاب‌شده به تفکیک هر شهر (cityId -> categoryIds[]) جهت استقلال کامل هر شهر
const [cityCategoryMap, setCityCategoryMap] = useState<Record<number, number[]>>({})
@ -125,8 +135,19 @@ export function DuasServiceView() {
// Tab 2 Verses states
const [verseSearch, setVerseSearch] = useState('')
const [activeTranslationLang, setActiveTranslationLang] = useState<'fa' | 'en' | 'ru' | 'id'>('fa')
const [activeVerseDescLang, setActiveVerseDescLang] = useState<'fa' | 'ar' | 'en' | 'ru' | 'id'>('fa')
const [copiedVerseIndex, setCopiedVerseIndex] = useState<number | null>(null)
const [verseDrafts, setVerseDrafts] = useState<Record<number, { text: string; translations: Record<string, string> }>>({})
const [verseDrafts, setVerseDrafts] = useState<
Record<
number,
{
text: string
translations: Record<string, string>
descriptions: Record<string, string>
repeat_count: number | null
}
>
>({})
const [savingVerseIndex, setSavingVerseIndex] = useState<number | null>(null)
const [savedVerseSuccessIndex, setSavedVerseSuccessIndex] = useState<number | null>(null)
@ -352,6 +373,14 @@ export function DuasServiceView() {
setFormNameEn(enVal)
setFormNameRu(ruVal)
setFormNameId(idVal)
const initDesc = (dua.description && typeof dua.description === 'object') ? dua.description : {}
setFormDescriptions({
fa: initDesc.fa || '',
ar: initDesc.ar || '',
en: initDesc.en || '',
ru: initDesc.ru || '',
id: initDesc.id || '',
})
setHasAttemptedSaveGeneral(false)
// Cities: فقط شهرهای معتبر که در سامانه دسته‌بندی دارند به صورت اولیه انتخاب شوند
@ -405,12 +434,37 @@ export function DuasServiceView() {
const detail = await fetchDuaDetail(dua.index)
setDuaDetail(detail)
const detDesc = (detail.description && typeof detail.description === 'object') ? detail.description : {}
setFormDescriptions({
fa: detDesc.fa || '',
ar: detDesc.ar || '',
en: detDesc.en || '',
ru: detDesc.ru || '',
id: detDesc.id || '',
})
// Initialize verse drafts
const drafts: Record<number, { text: string; translations: Record<string, string> }> = {}
const drafts: Record<
number,
{
text: string
translations: Record<string, string>
descriptions: Record<string, string>
repeat_count: number | null
}
> = {}
detail.verses?.forEach((v) => {
drafts[v.index] = {
text: v.text,
translations: { ...(v.translations || {}) },
descriptions: {
fa: v.descriptions?.fa || '',
ar: v.descriptions?.ar || '',
en: v.descriptions?.en || '',
ru: v.descriptions?.ru || '',
id: v.descriptions?.id || '',
},
repeat_count: v.repeat_count ?? null,
}
})
setVerseDrafts(drafts)
@ -617,8 +671,15 @@ export function DuasServiceView() {
])
)
const descriptionObj: Record<string, string> = {}
;(['fa', 'ar', 'en', 'ru', 'id'] as const).forEach((l) => {
const val = (formDescriptions[l] || '').trim()
if (val) descriptionObj[l] = val
})
const updated = await updateDua(selectedDuaForModal.index, {
name: nameObj,
description: descriptionObj,
city_ids: activeCityIds,
category_ids: allActiveCategoryIds,
city_allocations: cityAllocations,
@ -636,6 +697,7 @@ export function DuasServiceView() {
...d,
name: updated.name,
name_display: updated.name_display || formNameFa || formNameAr,
description: updated.description || descriptionObj,
cities: updated.cities,
city_ids: Array.isArray(updated.city_ids) ? updated.city_ids : activeCityIds,
categories: updated.categories,
@ -647,7 +709,7 @@ export function DuasServiceView() {
)
// بستن مدال پس از ذخیره‌سازی موفقیت‌آمیز
setSelectedDuaForModal(null)
toast.success('اطلاعات عمومی دعا با موفقیت در دیتابیس ذخیره شد.')
toast.success(t('duasAdmin.saveGeneralSuccess'))
// تازه‌سازی خودکار داده‌های صفحه از سرور
await loadDuas(true)
@ -667,9 +729,11 @@ export function DuasServiceView() {
await updateVerse(verseIndex, {
text: draft.text,
translations: draft.translations,
descriptions: draft.descriptions,
repeat_count: draft.repeat_count && draft.repeat_count > 0 ? draft.repeat_count : null,
})
setSavedVerseSuccessIndex(verseIndex)
toast.success(`فراز با موفقیت در دیتابیس ذخیره شد.`)
toast.success(t('duasAdmin.saveVerseSuccess'))
setTimeout(() => setSavedVerseSuccessIndex(null), 2500)
} catch (err: any) {
toast.error(err?.message || 'خطا در ذخیره‌سازی فراز در سرور.')
@ -1455,6 +1519,50 @@ export function DuasServiceView() {
</div>
</div>
{/* ۱.۵. توضیحات و فضیلت مفاتیح‌الجنان (۵ زبانه) */}
<div className="rounded-2xl border border-border-soft bg-card/50 p-4 space-y-3">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
<div>
<span className="text-xs font-bold text-foreground flex items-center gap-1.5">
<Ic name="book" className="size-3.5 text-primary" />
<span>{t('duasAdmin.mafatihIntroTitle')}</span>
</span>
<span className="text-[11px] text-muted-foreground block mt-0.5">
{t('duasAdmin.mafatihIntroHint')}
</span>
</div>
<div className="flex items-center gap-1 flex-wrap shrink-0">
{(['fa', 'ar', 'en', 'ru', 'id'] as const).map((lang) => (
<button
key={lang}
type="button"
onClick={() => setActiveDescLang(lang)}
className={`text-[11px] px-2.5 py-1 rounded-lg font-mono font-bold transition cursor-pointer ${
activeDescLang === lang
? 'bg-primary text-primary-foreground shadow-xs'
: 'bg-card text-muted-foreground hover:text-foreground border border-border-soft'
}`}
>
{lang.toUpperCase()}
</button>
))}
</div>
</div>
<textarea
value={formDescriptions[activeDescLang] || ''}
onChange={(e) =>
setFormDescriptions((prev) => ({
...prev,
[activeDescLang]: e.target.value,
}))
}
dir={activeDescLang === 'fa' || activeDescLang === 'ar' ? 'rtl' : 'ltr'}
rows={4}
placeholder={t('duasAdmin.mafatihIntroPlaceholder')}
className="w-full p-3 rounded-xl bg-card border border-border-soft text-xs text-foreground leading-relaxed focus:outline-hidden focus:ring-1 focus:ring-primary resize-y"
/>
</div>
{/* ۲. انتساب شهر و دسته‌بندی‌ها (انتخاب‌گونه و خاموش/روشن) */}
<div className="space-y-3 pt-2.5 border-t border-border-soft/70">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
@ -1889,8 +1997,17 @@ export function DuasServiceView() {
const draft = verseDrafts[verse.index] || {
text: verse.text,
translations: { ...(verse.translations || {}) },
descriptions: {
fa: verse.descriptions?.fa || '',
ar: verse.descriptions?.ar || '',
en: verse.descriptions?.en || '',
ru: verse.descriptions?.ru || '',
id: verse.descriptions?.id || '',
},
repeat_count: verse.repeat_count ?? null,
}
const activeTranslation = draft.translations?.[activeTranslationLang] || ''
const activeVerseDesc = draft.descriptions?.[activeVerseDescLang] || ''
const isSavingThis = savingVerseIndex === verse.index
const isSavedSuccess = savedVerseSuccessIndex === verse.index
@ -1900,10 +2017,17 @@ export function DuasServiceView() {
className="p-4 rounded-2xl border border-border-soft bg-card/30 space-y-3 hover:border-primary/30 transition shadow-2xs"
>
{/* هدر فراز */}
<div className="flex items-center justify-between">
<span className="text-[11px] font-mono font-bold text-primary">
فراز {toFa(index + 1)} از {toFa(duaDetail?.verses?.length || 0)} (کد: #{verse.index})
</span>
<div className="flex flex-wrap items-center justify-between gap-2">
<div className="flex items-center gap-2">
<span className="text-[11px] font-mono font-bold text-primary">
فراز {toFa(index + 1)} از {toFa(duaDetail?.verses?.length || 0)} (کد: #{verse.index})
</span>
{draft.repeat_count && draft.repeat_count > 1 ? (
<Badge variant="outline" className="text-[10px] font-mono px-2 py-0 border-primary/30 text-primary bg-primary/5">
×{draft.repeat_count} {t('duasAdmin.repeatCountSuffix')}
</Badge>
) : null}
</div>
<div className="flex items-center gap-1.5">
<Button
variant="ghost"
@ -1938,6 +2062,77 @@ export function DuasServiceView() {
</div>
</div>
{/* بخش توضیحات بین‌فرازی مفاتیح (۵ زبانه شامل عربی) و شمارنده تکرار */}
<div className="p-3 rounded-xl border border-border-soft bg-muted/20 space-y-2">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
<label className="text-[11px] font-bold text-foreground">
{t('duasAdmin.verseDescLabel')} ({activeVerseDescLang.toUpperCase()}):
</label>
<div className="flex items-center gap-2 flex-wrap">
<div className="flex items-center gap-1">
{(['fa', 'ar', 'en', 'ru', 'id'] as const).map((lang) => (
<button
key={lang}
type="button"
onClick={() => setActiveVerseDescLang(lang)}
className={`text-[10px] px-2 py-0.5 rounded-md font-mono font-bold transition cursor-pointer ${
activeVerseDescLang === lang
? 'bg-primary text-primary-foreground'
: 'bg-card text-muted-foreground hover:text-foreground border border-border-soft'
}`}
>
{lang.toUpperCase()}
</button>
))}
</div>
<div className="flex items-center gap-1.5">
<span className="text-[10px] text-muted-foreground font-medium">
{t('duasAdmin.repeatCountLabel')}:
</span>
<Input
type="number"
min={0}
value={draft.repeat_count ?? ''}
onChange={(e) => {
const raw = e.target.value.trim()
const parsed = raw === '' ? null : Math.max(0, parseInt(raw, 10) || 0)
setVerseDrafts((prev) => ({
...prev,
[verse.index]: {
...draft,
repeat_count: parsed && parsed > 0 ? parsed : null,
},
}))
}}
placeholder={t('duasAdmin.repeatCountPlaceholder')}
className="w-24 h-7 text-xs font-mono bg-card border-border-soft rounded-lg text-center"
dir="ltr"
/>
</div>
</div>
</div>
<textarea
value={activeVerseDesc}
onChange={(e) => {
const newDesc = e.target.value
setVerseDrafts((prev) => ({
...prev,
[verse.index]: {
...draft,
descriptions: {
...(draft.descriptions || {}),
[activeVerseDescLang]: newDesc,
},
},
}))
}}
dir={activeVerseDescLang === 'fa' || activeVerseDescLang === 'ar' ? 'rtl' : 'ltr'}
rows={2}
placeholder={t('duasAdmin.verseDescPlaceholder')}
className="w-full p-2.5 rounded-xl bg-card border border-border-soft text-xs text-foreground leading-relaxed focus:outline-hidden focus:ring-1 focus:ring-primary resize-y"
/>
</div>
{/* فیلد ادیت متن اصلی عربی */}
<div className="space-y-1">
<label className="block text-[11px] font-bold text-foreground">
@ -1950,9 +2145,8 @@ export function DuasServiceView() {
setVerseDrafts((prev) => ({
...prev,
[verse.index]: {
...prev[verse.index],
...draft,
text: newText,
translations: prev[verse.index]?.translations || {},
},
}))
}}
@ -1974,9 +2168,9 @@ export function DuasServiceView() {
setVerseDrafts((prev) => ({
...prev,
[verse.index]: {
text: prev[verse.index]?.text || verse.text,
...draft,
translations: {
...(prev[verse.index]?.translations || {}),
...(draft.translations || {}),
[activeTranslationLang]: newTr,
},
},

8
src/features/services/services/trip-etiquette-api.ts

@ -246,6 +246,7 @@ export async function createDua(input: CreateDuaInput): Promise<DuaItem> {
method: 'POST',
body: {
name: input.name,
description: input.description,
category_ids: input.category_ids,
shrine_ids: input.shrine_ids,
is_active: input.is_active,
@ -308,7 +309,12 @@ export async function deleteDua(index: number): Promise<void> {
*/
export async function updateVerse(
index: number,
input: { text?: string; translations?: Record<string, string> }
input: {
text?: string
translations?: Record<string, string>
descriptions?: Record<string, string>
repeat_count?: number | null
}
): Promise<VerseItem> {
return apiFetch<VerseItem>(`trip-etiquette/verses/${index}/`, {
method: 'PATCH',

12
src/features/services/types/trip-etiquette.ts

@ -68,6 +68,7 @@ export interface DuaItem {
index: number
name: Record<string, string> | any
name_display: string
description?: Record<string, string>
categories?: Array<{
id: number
name: string
@ -104,6 +105,15 @@ export interface VerseItem {
sub_ritual: number
text: string
juz: number
repeat_count?: number | null
descriptions?: {
fa?: string
ar?: string
en?: string
ru?: string
id?: string
[key: string]: string | undefined
}
translations: {
fa: string
en: string
@ -129,6 +139,7 @@ export interface CreateShrineInput {
export interface CreateDuaInput {
name: Record<string, string> | Array<{ language_code: string; name: string }>
description?: Record<string, string>
category_ids?: number[]
shrine_ids?: number[]
city_ids?: number[]
@ -142,6 +153,7 @@ export interface CityAllocationInput {
export interface UpdateDuaInput {
name?: Record<string, string> | Array<{ language_code: string; name: string }>
description?: Record<string, string>
category_ids?: number[]
shrine_ids?: number[]
city_ids?: number[]

24
src/lib/date-utils.ts

@ -94,6 +94,30 @@ export function formatDateRangeByLanguage(
return `${startFormatted} – ${endFormatted}`
}
/**
* استخراج بازه حرکت و برگشت حدودی از رشته ISO Range (`YYYY-MM-DD..YYYY-MM-DD`)
*/
export function parseTravelDateRange(
rawText?: string | null,
fallbackStartIso?: string | null
): { startIso: string | null; endIso: string | null } {
const text = String(rawText || '').trim()
const rangeMatch = text.match(
/^(\d{4}-\d{2}-\d{2})\s*(?:\.\.|to|->|—|–)\s*(\d{4}-\d{2}-\d{2})$/
)
if (rangeMatch) {
return { startIso: rangeMatch[1], endIso: rangeMatch[2] }
}
if (/^\d{4}-\d{2}-\d{2}$/.test(text)) {
return { startIso: text, endIso: null }
}
const fb = String(fallbackStartIso || '').trim()
if (/^\d{4}-\d{2}-\d{2}$/.test(fb)) {
return { startIso: fb, endIso: null }
}
return { startIso: null, endIso: null }
}
/**
* قالب‌بندی تاریخ (دوگانه میلادی و قمری با نام ماه) و ساعت به صورت همزمان
*/

18
src/locales/ar.json

@ -60,8 +60,6 @@
"auth": {
"loginTitle": "تسجيل الدخول إلى لوحة الإدارة",
"loginDescription": "أدخل بيانات الاعتماد الخاصة بك للوصول إلى بوابة الإدارة",
"demoBoxTitle": "حساب تجريبي جاهز:",
"autoFill": "تعبئة تلقائية",
"emailLabel": "البريد الإلكتروني للحساب",
"emailPlaceholder": "you@example.com",
"passwordLabel": "كلمة المرور",
@ -965,7 +963,21 @@
"originStartAndEnd": "(نقطة انطلاق ونهاية الرحلة)",
"selectReturnDestinationPlaceholder": "يرجى اختيار مدينة الوجهة في مسار العودة.",
"viewInBilling": "عرض في القسم المالي",
"nightsCountLabel": "عدد ليالي الإقامة"
"nightsCountLabel": "عدد ليالي الإقامة",
"tripStartDate": "تاريخ بدء الرحلة",
"approxTravelRange": "الفترة التقريبية للمغادرة والعودة"
},
"duasAdmin": {
"mafatihIntroTitle": "شرح وفضيلة الدعاء من مفاتيح الجنان (متعدد اللغات)",
"mafatihIntroHint": "المقدمة والفضيلة والآداب العامة للدعاء باللغات الخمس المعتمدة (تظهر في أعلى الصفحة في التطبيق)",
"mafatihIntroPlaceholder": "أدخل نص الشرح والفضيلة باللغة المحددة...",
"verseDescLabel": "توضيح وإرشاد الفقرة من المفاتيح",
"verseDescPlaceholder": "مثال: ثم تصلّي ركعتي الزيارة أو تقول عشر مرّات...",
"repeatCountLabel": "عدد التكرار (العداد)",
"repeatCountPlaceholder": "مثال: 10 أو 100",
"repeatCountSuffix": "مرّات",
"saveGeneralSuccess": "تم حفظ المعلومات العامة وشرح الدعاء بنجاح.",
"saveVerseSuccess": "تم حفظ الفقرة والشرح وعدد التكرار بنجاح."
},
"languages": {
"fa": "فارسی",

18
src/locales/en.json

@ -60,8 +60,6 @@
"auth": {
"loginTitle": "Login to Admin Dashboard",
"loginDescription": "Enter your credentials to access the management portal",
"demoBoxTitle": "Demo Ready Account:",
"autoFill": "Auto Fill",
"emailLabel": "Account Email",
"emailPlaceholder": "you@example.com",
"passwordLabel": "Password",
@ -965,7 +963,21 @@
"originStartAndEnd": "(Origin & final endpoint of journey)",
"selectReturnDestinationPlaceholder": "Please select the destination city for the return leg.",
"viewInBilling": "View in Billing",
"nightsCountLabel": "Stay Nights"
"nightsCountLabel": "Stay Nights",
"tripStartDate": "Trip Start Date",
"approxTravelRange": "Approx. Departure & Return Range"
},
"duasAdmin": {
"mafatihIntroTitle": "Mafatih al-Jinan Introduction & Virtues (Multilingual)",
"mafatihIntroHint": "General introduction, virtues, and etiquette in all 5 languages (shown in the collapsible top banner in the app)",
"mafatihIntroPlaceholder": "Enter the introduction and virtues in the selected language...",
"verseDescLabel": "Mid-Dua Mafatih Instruction / Etiquette",
"verseDescPlaceholder": "e.g. Then recite ten times or perform two Rak'ahs of Ziyarat prayer...",
"repeatCountLabel": "Repeat Count (Dhikr Counter)",
"repeatCountPlaceholder": "e.g. 10 or 100",
"repeatCountSuffix": "times",
"saveGeneralSuccess": "Dua general info and descriptions saved successfully.",
"saveVerseSuccess": "Phrase, instructions, and repeat count saved successfully."
},
"languages": {
"fa": "فارسی",

18
src/locales/fa.json

@ -60,8 +60,6 @@
"auth": {
"loginTitle": "ورود به پنل مدیریت و داشبورد",
"loginDescription": "برای دسترسی به پرتال مدیریت، اطلاعات ورود خود را وارد نمایید",
"demoBoxTitle": "حساب آزمایشی آماده:",
"autoFill": "پر کردن خودکار",
"emailLabel": "ایمیل حساب کاربری",
"emailPlaceholder": "you@example.com",
"passwordLabel": "رمز عبور",
@ -965,7 +963,21 @@
"originStartAndEnd": "(مبدأ آغاز و پایان سفر)",
"selectReturnDestinationPlaceholder": "لطفاً شهر مقصد در مسیر بازگشت را انتخاب نمایید.",
"viewInBilling": "مشاهده در بخش مالی",
"nightsCountLabel": "تعداد شب اقامت"
"nightsCountLabel": "تعداد شب اقامت",
"tripStartDate": "تاریخ شروع سفر",
"approxTravelRange": "بازه حدودی حرکت و برگشت"
},
"duasAdmin": {
"mafatihIntroTitle": "توضیحات و فضیلت مفاتیح‌الجنان (چندزبانه)",
"mafatihIntroHint": "مقدمه، فضیلت و آداب کلی دعا در ۵ زبان رسمی (نمایش در کادر بالای صفحه در اپلیکیشن)",
"mafatihIntroPlaceholder": "متن توضیحات و فضیلت دعا را در زبان انتخاب‌شده وارد کنید...",
"verseDescLabel": "توضیح و دستورالعمل بین‌فرازی مفاتیح",
"verseDescPlaceholder": "مثال: سپس دو رکعت نماز زیارت می‌خوانی یا ده مرتبه می‌گویی...",
"repeatCountLabel": "تعداد تکرار (ذکرشمار)",
"repeatCountPlaceholder": "مثلاً ۱۰ یا ۱۰۰",
"repeatCountSuffix": "مرتبه",
"saveGeneralSuccess": "اطلاعات عمومی و توضیحات دعا با موفقیت ذخیره شد.",
"saveVerseSuccess": "فراز، توضیحات و تعداد تکرار با موفقیت ذخیره شد."
},
"languages": {
"fa": "فارسی",

2
vite.config.ts

@ -316,6 +316,8 @@ export default defineConfig(({ mode }) => {
alias: { '@': path.resolve(__dirname, './src') },
},
server: {
/* پورت پیش‌فرض خارج از بازهٔ ephemeral و پورت رزرو ۵۳۵۷ ویندوز تا با تداخل پورت کرش نکند. */
port: Number(env.VITE_DEV_PORT) || 15173,
proxy: {
'/api': {
target: apiTarget,

Loading…
Cancel
Save