This commit is contained in:
@@ -1,259 +1,293 @@
|
|||||||
"use client"
|
"use client"
|
||||||
import { useMemo, useState, useRef, useEffect } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import { api, DeviceDto } from '@/lib/api'
|
import { useRouter } from 'next/navigation'
|
||||||
import { Settings, CheckCircle2, ArrowRight, Calendar, BarChart3, Activity, RotateCcw } from 'lucide-react'
|
import { api, DeviceDto, PagedResult } from '@/lib/api'
|
||||||
|
import { Settings, Calendar, LogOut, ArrowRight, Search, ChevronRight, ChevronLeft } from 'lucide-react'
|
||||||
import Link from 'next/link'
|
import Link from 'next/link'
|
||||||
import Loading from '@/components/Loading'
|
import Loading from '@/components/Loading'
|
||||||
|
|
||||||
export default function DevicesPage() {
|
export default function DevicesPage() {
|
||||||
const [loading, setLoading] = useState(false)
|
const router = useRouter()
|
||||||
const [deviceName, setDeviceName] = useState('')
|
const [pagedResult, setPagedResult] = useState<PagedResult<DeviceDto> | null>(null)
|
||||||
const [password, setPassword] = useState('')
|
const [loading, setLoading] = useState(true)
|
||||||
const [selected, setSelected] = useState<DeviceDto | null>(null)
|
|
||||||
const [error, setError] = useState<string | null>(null)
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
const [user, setUser] = useState<{ id: number; mobile: string; name: string; family: string; role: number } | null>(null)
|
||||||
|
const [searchTerm, setSearchTerm] = useState('')
|
||||||
|
const [currentPage, setCurrentPage] = useState(1)
|
||||||
|
const [searchInput, setSearchInput] = useState('')
|
||||||
|
|
||||||
const deviceNameRef = useRef<HTMLInputElement>(null)
|
const pageSize = 10
|
||||||
const passwordRef = useRef<HTMLInputElement>(null)
|
|
||||||
|
|
||||||
const canSubmit = useMemo(() => deviceName.trim().length > 0 && password.trim().length > 0, [deviceName, password])
|
const fetchDevices = async (page: number, search?: string) => {
|
||||||
|
if (!user) return
|
||||||
// بررسی auto-fill پس از لود صفحه
|
|
||||||
useEffect(() => {
|
|
||||||
const checkAutoFill = () => {
|
|
||||||
setTimeout(() => {
|
|
||||||
if (deviceNameRef.current) {
|
|
||||||
const filledDeviceName = deviceNameRef.current.value
|
|
||||||
if (filledDeviceName && filledDeviceName !== deviceName) {
|
|
||||||
setDeviceName(filledDeviceName)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (passwordRef.current) {
|
|
||||||
const filledPassword = passwordRef.current.value
|
|
||||||
if (filledPassword && filledPassword !== password) {
|
|
||||||
setPassword(filledPassword)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, 100)
|
|
||||||
}
|
|
||||||
|
|
||||||
checkAutoFill()
|
|
||||||
window.addEventListener('load', checkAutoFill)
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
window.removeEventListener('load', checkAutoFill)
|
|
||||||
}
|
|
||||||
}, [deviceName, password])
|
|
||||||
|
|
||||||
// بررسی تغییرات در فیلدها (برای مرورگرهایی که بعد از تعامل auto-fill میکنند)
|
|
||||||
const handleInputChange = (e: React.FormEvent<HTMLInputElement>) => {
|
|
||||||
const target = e.target as HTMLInputElement
|
|
||||||
if (target.name === 'deviceName') {
|
|
||||||
setDeviceName(target.value)
|
|
||||||
} else if (target.name === 'password') {
|
|
||||||
setPassword(target.value)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function handleSubmit(e: React.FormEvent) {
|
|
||||||
e.preventDefault()
|
|
||||||
setError(null)
|
|
||||||
|
|
||||||
// گرفتن آخرین مقادیر از refها در صورت لزوم
|
|
||||||
const currentDeviceName = deviceNameRef.current?.value || deviceName
|
|
||||||
const currentPassword = passwordRef.current?.value || password
|
|
||||||
|
|
||||||
if (!currentDeviceName.trim() || !currentPassword.trim()) {
|
|
||||||
setError('لطفاً نام دستگاه و رمز عبور را وارد کنید')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
setLoading(true)
|
setLoading(true)
|
||||||
|
setError(null)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// فراخوانی API برای بررسی دستگاه
|
const result = await api.getDevicesFiltered({
|
||||||
const device = await api.CheckDevice(currentDeviceName.trim(), currentPassword.trim())
|
userId: user.id,
|
||||||
|
search: search || undefined,
|
||||||
|
page,
|
||||||
|
pageSize
|
||||||
|
})
|
||||||
|
|
||||||
if (device !=undefined) {
|
if (result.items.length === 0 && page === 1) {
|
||||||
setSelected(device)
|
setError('شما هیچ دستگاهی ندارید. لطفاً با پشتیبانی تماس بگیرید.')
|
||||||
|
} else if (result.items.length === 1 && result.totalCount === 1 && !search) {
|
||||||
|
// Single device - redirect to calendar
|
||||||
|
router.push(`/calendar?deviceId=${result.items[0].id}`)
|
||||||
|
return
|
||||||
} else {
|
} else {
|
||||||
setError('دستگاه یافت نشد یا رمز عبور نادرست است')
|
setPagedResult(result)
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (err) {
|
||||||
console.error('Error checking device:', error)
|
console.error('Error fetching devices:', err)
|
||||||
setError('خطا در ارتباط با سرور')
|
setError('خطا در دریافت لیست دستگاهها')
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleReset() {
|
useEffect(() => {
|
||||||
setSelected(null)
|
// Check authentication
|
||||||
setDeviceName('')
|
const token = localStorage.getItem('authToken')
|
||||||
setPassword('')
|
const userStr = localStorage.getItem('user')
|
||||||
setError(null)
|
|
||||||
|
|
||||||
// پاک کردن refها
|
if (!token || !userStr) {
|
||||||
if (deviceNameRef.current) deviceNameRef.current.value = ''
|
router.push('/')
|
||||||
if (passwordRef.current) passwordRef.current.value = ''
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const userData = JSON.parse(userStr)
|
||||||
|
setUser(userData)
|
||||||
|
} catch {
|
||||||
|
router.push('/')
|
||||||
|
}
|
||||||
|
}, [router])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (user) {
|
||||||
|
fetchDevices(currentPage, searchTerm || undefined)
|
||||||
|
}
|
||||||
|
}, [user, currentPage, searchTerm])
|
||||||
|
|
||||||
|
const handleSearch = (e: React.FormEvent) => {
|
||||||
|
e.preventDefault()
|
||||||
|
setSearchTerm(searchInput)
|
||||||
|
setCurrentPage(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (loading) {
|
const handleLogout = () => {
|
||||||
return <Loading message="در حال بررسی دستگاه..." />
|
localStorage.removeItem('authToken')
|
||||||
|
localStorage.removeItem('user')
|
||||||
|
router.push('/')
|
||||||
|
}
|
||||||
|
|
||||||
|
const totalPages = pagedResult ? Math.ceil(pagedResult.totalCount / pageSize) : 0
|
||||||
|
const showPagination = pagedResult && pagedResult.totalCount > pageSize
|
||||||
|
|
||||||
|
if (loading && !pagedResult) {
|
||||||
|
return <Loading message="در حال بارگذاری..." />
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error && (!pagedResult || pagedResult.items.length === 0)) {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center p-4">
|
||||||
|
<div className="w-full max-w-md">
|
||||||
|
<div className="bg-white rounded-2xl shadow-xl p-8 border border-gray-100 text-center">
|
||||||
|
<div className="text-red-600 mb-4">
|
||||||
|
<Settings className="w-16 h-16 mx-auto" />
|
||||||
|
</div>
|
||||||
|
<h2 className="text-xl font-bold text-gray-900 mb-2">خطا</h2>
|
||||||
|
<p className="text-gray-600 mb-6">{error}</p>
|
||||||
|
<button
|
||||||
|
onClick={handleLogout}
|
||||||
|
className="w-full py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-700 font-medium transition-all duration-200 flex items-center justify-center gap-2"
|
||||||
|
>
|
||||||
|
<LogOut className="w-5 h-5" />
|
||||||
|
خروج
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen flex items-center justify-center p-4">
|
<div className="min-h-screen p-4 md:p-8">
|
||||||
<div className="w-full max-w-md">
|
<div className="max-w-6xl mx-auto">
|
||||||
{/* Main Card */}
|
{/* Header */}
|
||||||
<div className="bg-white rounded-2xl shadow-xl p-8 border border-gray-100">
|
<div className="mb-6 flex items-center justify-between flex-wrap gap-4">
|
||||||
{/* Title Section */}
|
<div>
|
||||||
<div className="text-center mb-8">
|
<h1 className="text-2xl md:text-3xl font-bold text-gray-900 mb-2">
|
||||||
<div className="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-br from-green-500 to-green-600 rounded-2xl shadow-lg mb-4">
|
انتخاب دستگاه
|
||||||
{selected ? (
|
|
||||||
<CheckCircle2 className="w-8 h-8 text-white" />
|
|
||||||
) : (
|
|
||||||
<Settings className="w-8 h-8 text-white" />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<h1 className="text-2xl font-bold text-gray-900 mb-2">
|
|
||||||
{selected ? 'دستگاه فعال' : 'انتخاب دستگاه'}
|
|
||||||
</h1>
|
</h1>
|
||||||
<p className="text-sm text-gray-600">
|
{user && (
|
||||||
{selected
|
<p className="text-sm text-gray-600">
|
||||||
? `دستگاه "${selected.deviceName}" با موفقیت تأیید شد`
|
{user.name} {user.family} ({user.mobile})
|
||||||
: 'نام دستگاه و رمز عبور را وارد کنید'
|
</p>
|
||||||
}
|
)}
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={handleLogout}
|
||||||
|
className="flex items-center gap-2 px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-xl transition-all duration-200 text-sm"
|
||||||
|
>
|
||||||
|
<LogOut className="w-4 h-4" />
|
||||||
|
خروج
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* نمایش فرم فقط وقتی دستگاه انتخاب نشده */}
|
{/* Search */}
|
||||||
{!selected ? (
|
<div className="mb-6">
|
||||||
<form onSubmit={handleSubmit} className="space-y-5">
|
<form onSubmit={handleSearch} className="flex gap-2">
|
||||||
{/* Input Fields */}
|
<div className="flex-1 relative">
|
||||||
<div className="space-y-4">
|
<Search className="absolute right-4 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
|
||||||
<div>
|
<input
|
||||||
<label className="block text-sm font-medium text-gray-700 mb-2">
|
type="text"
|
||||||
نام دستگاه
|
value={searchInput}
|
||||||
</label>
|
onChange={(e) => setSearchInput(e.target.value)}
|
||||||
<input
|
placeholder="جستجو در نام دستگاه، نام صاحب، نام خانوادگی صاحب، موقعیت..."
|
||||||
ref={deviceNameRef}
|
className="w-full pr-12 pl-4 py-3 rounded-xl border-2 border-gray-200 bg-gray-50 focus:border-green-500 focus:bg-white focus:outline-none focus:ring-2 focus:ring-green-500/20 transition-all duration-200"
|
||||||
name="deviceName"
|
/>
|
||||||
className="w-full px-4 py-3 rounded-xl border-2 border-gray-200 bg-gray-50 focus:border-green-500 focus:bg-white focus:outline-none focus:ring-2 focus:ring-green-500/20 transition-all duration-200"
|
</div>
|
||||||
placeholder="نام دستگاه را وارد کنید"
|
<button
|
||||||
defaultValue={deviceName}
|
type="submit"
|
||||||
onInput={handleInputChange}
|
className="px-6 py-3 bg-gradient-to-r from-green-500 to-green-600 hover:from-green-600 hover:to-green-700 text-white font-medium rounded-xl transition-all duration-200 shadow-md hover:shadow-lg flex items-center gap-2"
|
||||||
disabled={loading}
|
>
|
||||||
/>
|
<Search className="w-5 h-5" />
|
||||||
</div>
|
جستجو
|
||||||
<div>
|
</button>
|
||||||
<label className="block text-sm font-medium text-gray-700 mb-2">
|
</form>
|
||||||
رمز عبور
|
{searchTerm && (
|
||||||
</label>
|
<div className="mt-2 flex items-center gap-2">
|
||||||
<input
|
<span className="text-sm text-gray-600">
|
||||||
ref={passwordRef}
|
نتایج جستجو برای: <span className="font-semibold">{searchTerm}</span>
|
||||||
name="password"
|
</span>
|
||||||
className="w-full px-4 py-3 rounded-xl border-2 border-gray-200 bg-gray-50 focus:border-green-500 focus:bg-white focus:outline-none focus:ring-2 focus:ring-green-500/20 transition-all duration-200"
|
|
||||||
placeholder="رمز عبور را وارد کنید"
|
|
||||||
type="password"
|
|
||||||
defaultValue={password}
|
|
||||||
onInput={handleInputChange}
|
|
||||||
disabled={loading}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Error Message */}
|
|
||||||
{error && (
|
|
||||||
<div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-xl text-sm text-center">
|
|
||||||
{error}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Confirm Button */}
|
|
||||||
<button
|
<button
|
||||||
type="submit"
|
onClick={() => {
|
||||||
disabled={loading || !canSubmit}
|
setSearchInput('')
|
||||||
className={`w-full py-3 rounded-xl text-white font-medium transition-all duration-200 flex items-center justify-center gap-2 shadow-md ${
|
setSearchTerm('')
|
||||||
!loading && canSubmit
|
setCurrentPage(1)
|
||||||
? 'bg-gradient-to-r from-green-500 to-green-600 hover:from-green-600 hover:to-green-700 hover:shadow-lg transform hover:-translate-y-0.5'
|
}}
|
||||||
: 'bg-gray-300 cursor-not-allowed'
|
className="text-sm text-green-600 hover:text-green-700"
|
||||||
}`}
|
|
||||||
>
|
>
|
||||||
{loading ? (
|
پاک کردن
|
||||||
<>
|
|
||||||
<div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin" />
|
|
||||||
در حال بررسی...
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<CheckCircle2 className="w-5 h-5" />
|
|
||||||
تایید و ادامه
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</button>
|
</button>
|
||||||
</form>
|
|
||||||
) : (
|
|
||||||
/* نمایش دکمههای عملیات وقتی دستگاه انتخاب شده */
|
|
||||||
<div className="space-y-5">
|
|
||||||
{/* اطلاعات دستگاه فعال */}
|
|
||||||
<div className="bg-gradient-to-r from-green-50 to-emerald-50 border border-green-200 rounded-xl p-4 text-center">
|
|
||||||
<div className="flex items-center justify-center gap-2 mb-1">
|
|
||||||
<CheckCircle2 className="w-5 h-5 text-green-600" />
|
|
||||||
<p className="text-green-800 font-semibold">{selected.deviceName}</p>
|
|
||||||
</div>
|
|
||||||
<p className="text-green-600 text-sm">دستگاه فعال و آماده استفاده</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Main Action Button */}
|
|
||||||
<Link
|
|
||||||
href={`/telemetry?deviceId=${selected.id}`}
|
|
||||||
className="block w-full bg-gradient-to-r from-purple-500 to-purple-600 hover:from-purple-600 hover:to-purple-700 text-white font-medium py-4 px-6 rounded-xl shadow-md hover:shadow-lg transition-all duration-200 flex items-center justify-center gap-2 transform hover:-translate-y-0.5"
|
|
||||||
>
|
|
||||||
<Activity className="w-5 h-5" />
|
|
||||||
دادههای امروز
|
|
||||||
</Link>
|
|
||||||
|
|
||||||
{/* Secondary Action Buttons */}
|
|
||||||
<div className="grid grid-cols-1 gap-3">
|
|
||||||
<Link
|
|
||||||
href={`/device-settings?deviceId=${selected.id}&deviceName=${encodeURIComponent(selected.deviceName)}`}
|
|
||||||
className="flex items-center justify-center gap-2 bg-blue-500 hover:bg-blue-600 text-white font-medium py-3 px-4 rounded-xl transition-all duration-200 shadow-md hover:shadow-lg"
|
|
||||||
>
|
|
||||||
<Settings className="w-5 h-5" />
|
|
||||||
تنظیمات دستگاه
|
|
||||||
</Link>
|
|
||||||
<div className="grid grid-cols-2 gap-3">
|
|
||||||
<Link
|
|
||||||
href={`/calendar/month?deviceId=${selected.id}&year=1403&month=1`}
|
|
||||||
className="flex items-center justify-center gap-2 bg-green-500 hover:bg-green-600 text-white font-medium py-3 px-4 rounded-xl transition-all duration-200 shadow-md hover:shadow-lg text-sm"
|
|
||||||
>
|
|
||||||
<Calendar className="w-4 h-4" />
|
|
||||||
تقویم ماه
|
|
||||||
</Link>
|
|
||||||
<Link
|
|
||||||
href={`/calendar?deviceId=${selected.id}`}
|
|
||||||
className="flex items-center justify-center gap-2 bg-orange-500 hover:bg-orange-600 text-white font-medium py-3 px-4 rounded-xl transition-all duration-200 shadow-md hover:shadow-lg text-sm"
|
|
||||||
>
|
|
||||||
<BarChart3 className="w-4 h-4" />
|
|
||||||
انتخاب ماه
|
|
||||||
</Link>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* دکمه تغییر دستگاه */}
|
|
||||||
<div className="pt-4 border-t border-gray-200">
|
|
||||||
<button
|
|
||||||
onClick={handleReset}
|
|
||||||
className="w-full flex items-center justify-center gap-2 px-6 py-2.5 bg-gray-100 hover:bg-gray-200 text-gray-700 font-medium rounded-xl transition-all duration-200"
|
|
||||||
>
|
|
||||||
<RotateCcw className="w-4 h-4" />
|
|
||||||
تغییر دستگاه
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Results Count */}
|
||||||
|
{pagedResult && (
|
||||||
|
<div className="mb-4 text-sm text-gray-600">
|
||||||
|
نمایش {pagedResult.items.length} از {pagedResult.totalCount} دستگاه
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Devices Grid */}
|
||||||
|
{pagedResult && pagedResult.items.length > 0 ? (
|
||||||
|
<>
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
|
||||||
|
{pagedResult.items.map((device) => (
|
||||||
|
<Link
|
||||||
|
key={device.id}
|
||||||
|
href={`/calendar?deviceId=${device.id}`}
|
||||||
|
className="group bg-white rounded-2xl shadow-md hover:shadow-xl transition-all duration-300 overflow-hidden border border-gray-100 p-6 relative"
|
||||||
|
>
|
||||||
|
<div className="flex items-start gap-4">
|
||||||
|
<div className="flex-shrink-0 w-14 h-14 rounded-xl bg-gradient-to-br from-green-500 to-green-600 flex items-center justify-center shadow-md group-hover:scale-110 transition-transform duration-300">
|
||||||
|
<Settings className="w-7 h-7 text-white" />
|
||||||
|
</div>
|
||||||
|
<div className="flex-1">
|
||||||
|
<h3 className="text-xl font-semibold text-gray-900 mb-1 group-hover:text-green-600 transition-colors">
|
||||||
|
{device.deviceName}
|
||||||
|
</h3>
|
||||||
|
<p className="text-sm text-gray-500 mb-2">
|
||||||
|
{device.location || 'بدون موقعیت'}
|
||||||
|
</p>
|
||||||
|
<div className="flex items-center gap-2 text-xs text-gray-400">
|
||||||
|
<span>{device.userName} {device.userFamily}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex-shrink-0">
|
||||||
|
<Calendar className="w-5 h-5 text-gray-400 group-hover:text-green-600 transition-colors" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="absolute bottom-0 left-0 right-0 h-1 bg-gradient-to-r from-green-500 to-green-600 transform scale-x-0 group-hover:scale-x-100 transition-transform duration-300" />
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Pagination */}
|
||||||
|
{showPagination && (
|
||||||
|
<div className="flex items-center justify-center gap-2 mt-6">
|
||||||
|
<button
|
||||||
|
onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
|
||||||
|
disabled={currentPage === 1}
|
||||||
|
className={`px-4 py-2 rounded-xl transition-all duration-200 flex items-center gap-2 ${
|
||||||
|
currentPage === 1
|
||||||
|
? 'bg-gray-100 text-gray-400 cursor-not-allowed'
|
||||||
|
: 'bg-white border-2 border-gray-200 hover:border-green-500 hover:text-green-600 text-gray-700'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<ChevronRight className="w-4 h-4" />
|
||||||
|
قبلی
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
{Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
|
||||||
|
let pageNum: number
|
||||||
|
if (totalPages <= 5) {
|
||||||
|
pageNum = i + 1
|
||||||
|
} else if (currentPage <= 3) {
|
||||||
|
pageNum = i + 1
|
||||||
|
} else if (currentPage >= totalPages - 2) {
|
||||||
|
pageNum = totalPages - 4 + i
|
||||||
|
} else {
|
||||||
|
pageNum = currentPage - 2 + i
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={pageNum}
|
||||||
|
onClick={() => setCurrentPage(pageNum)}
|
||||||
|
className={`w-10 h-10 rounded-xl transition-all duration-200 ${
|
||||||
|
currentPage === pageNum
|
||||||
|
? 'bg-gradient-to-r from-green-500 to-green-600 text-white shadow-md'
|
||||||
|
: 'bg-white border-2 border-gray-200 hover:border-green-500 hover:text-green-600 text-gray-700'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{pageNum}
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button
|
||||||
|
onClick={() => setCurrentPage(prev => Math.min(totalPages, prev + 1))}
|
||||||
|
disabled={currentPage === totalPages}
|
||||||
|
className={`px-4 py-2 rounded-xl transition-all duration-200 flex items-center gap-2 ${
|
||||||
|
currentPage === totalPages
|
||||||
|
? 'bg-gray-100 text-gray-400 cursor-not-allowed'
|
||||||
|
: 'bg-white border-2 border-gray-200 hover:border-green-500 hover:text-green-600 text-gray-700'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
بعدی
|
||||||
|
<ChevronLeft className="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
!loading && (
|
||||||
|
<div className="bg-white rounded-2xl shadow-md border border-gray-100 p-8 text-center">
|
||||||
|
<p className="text-gray-600">هیچ دستگاهی یافت نشد</p>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Back to Home */}
|
{/* Back to Home */}
|
||||||
<div className="mt-6 text-center">
|
<div className="mt-6 text-center">
|
||||||
<Link
|
<Link
|
||||||
|
|||||||
162
src/app/login/page.tsx
Normal file
162
src/app/login/page.tsx
Normal file
@@ -0,0 +1,162 @@
|
|||||||
|
"use client"
|
||||||
|
import { useState, useRef, useEffect } from 'react'
|
||||||
|
import { api } from '@/lib/api'
|
||||||
|
import { Smartphone, ArrowLeft, ArrowRight } from 'lucide-react'
|
||||||
|
import Link from 'next/link'
|
||||||
|
import { useRouter } from 'next/navigation'
|
||||||
|
import Loading from '@/components/Loading'
|
||||||
|
|
||||||
|
export default function LoginPage() {
|
||||||
|
const [mobile, setMobile] = useState('')
|
||||||
|
const [loading, setLoading] = useState(false)
|
||||||
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
const router = useRouter()
|
||||||
|
const mobileRef = useRef<HTMLInputElement>(null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const checkAutoFill = () => {
|
||||||
|
setTimeout(() => {
|
||||||
|
if (mobileRef.current) {
|
||||||
|
const filledMobile = mobileRef.current.value
|
||||||
|
if (filledMobile && filledMobile !== mobile) {
|
||||||
|
setMobile(filledMobile)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, 100)
|
||||||
|
}
|
||||||
|
|
||||||
|
checkAutoFill()
|
||||||
|
window.addEventListener('load', checkAutoFill)
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('load', checkAutoFill)
|
||||||
|
}
|
||||||
|
}, [mobile])
|
||||||
|
|
||||||
|
const handleInputChange = (e: React.FormEvent<HTMLInputElement>) => {
|
||||||
|
const value = e.currentTarget.value
|
||||||
|
// Only allow digits
|
||||||
|
const digitsOnly = value.replace(/\D/g, '')
|
||||||
|
setMobile(digitsOnly)
|
||||||
|
setError(null)
|
||||||
|
}
|
||||||
|
|
||||||
|
const normalizeMobile = (mobile: string): string => {
|
||||||
|
const digitsOnly = mobile.replace(/\D/g, '')
|
||||||
|
if (digitsOnly.startsWith('9') && digitsOnly.length === 10) {
|
||||||
|
return '0' + digitsOnly
|
||||||
|
}
|
||||||
|
if (digitsOnly.startsWith('0098') && digitsOnly.length === 13) {
|
||||||
|
return '0' + digitsOnly.substring(3)
|
||||||
|
}
|
||||||
|
if (digitsOnly.startsWith('98') && digitsOnly.length === 12) {
|
||||||
|
return '0' + digitsOnly.substring(2)
|
||||||
|
}
|
||||||
|
return digitsOnly
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault()
|
||||||
|
setError(null)
|
||||||
|
|
||||||
|
const normalizedMobile = normalizeMobile(mobile)
|
||||||
|
|
||||||
|
if (!normalizedMobile || normalizedMobile.length !== 11 || !normalizedMobile.startsWith('09')) {
|
||||||
|
setError('لطفاً شماره موبایل معتبر وارد کنید (مثال: 09123456789)')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
setLoading(true)
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await api.sendCode({ mobile: normalizedMobile })
|
||||||
|
|
||||||
|
if (result.success) {
|
||||||
|
// Redirect to verify page with mobile number
|
||||||
|
router.push(`/verify-code?mobile=${encodeURIComponent(normalizedMobile)}`)
|
||||||
|
} else {
|
||||||
|
setError(result.message || 'خطا در ارسال کد')
|
||||||
|
}
|
||||||
|
} catch (error: any) {
|
||||||
|
console.error('Error sending code:', error)
|
||||||
|
setError(error.message || 'خطا در ارتباط با سرور')
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const canSubmit = mobile.length >= 10
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return <Loading message="در حال ارسال کد..." />
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center p-4">
|
||||||
|
<div className="w-full max-w-md">
|
||||||
|
<div className="bg-white rounded-2xl shadow-xl p-8 border border-gray-100">
|
||||||
|
<div className="text-center mb-8">
|
||||||
|
<div className="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-br from-green-500 to-green-600 rounded-2xl shadow-lg mb-4">
|
||||||
|
<Smartphone className="w-8 h-8 text-white" />
|
||||||
|
</div>
|
||||||
|
<h1 className="text-2xl font-bold text-gray-900 mb-2">
|
||||||
|
ورود با شماره موبایل
|
||||||
|
</h1>
|
||||||
|
<p className="text-sm text-gray-600">
|
||||||
|
شماره موبایل خود را وارد کنید تا کد فعالسازی برای شما ارسال شود
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-5">
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 mb-2">
|
||||||
|
شماره موبایل
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
ref={mobileRef}
|
||||||
|
type="tel"
|
||||||
|
inputMode="numeric"
|
||||||
|
className="w-full px-4 py-3 rounded-xl border-2 border-gray-200 bg-gray-50 focus:border-green-500 focus:bg-white focus:outline-none focus:ring-2 focus:ring-green-500/20 transition-all duration-200 text-left"
|
||||||
|
placeholder="09123456789"
|
||||||
|
value={mobile}
|
||||||
|
onInput={handleInputChange}
|
||||||
|
disabled={loading}
|
||||||
|
maxLength={11}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-xl text-sm text-center">
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={loading || !canSubmit}
|
||||||
|
className={`w-full py-3 rounded-xl text-white font-medium transition-all duration-200 flex items-center justify-center gap-2 shadow-md ${
|
||||||
|
!loading && canSubmit
|
||||||
|
? 'bg-gradient-to-r from-green-500 to-green-600 hover:from-green-600 hover:to-green-700 hover:shadow-lg transform hover:-translate-y-0.5'
|
||||||
|
: 'bg-gray-300 cursor-not-allowed'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{loading ? (
|
||||||
|
<>
|
||||||
|
<div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin" />
|
||||||
|
در حال ارسال...
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
ارسال کد فعالسازی
|
||||||
|
<ArrowLeft className="w-5 h-5" />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
241
src/app/page.tsx
241
src/app/page.tsx
@@ -1,90 +1,175 @@
|
|||||||
import { Home as HomeIcon, Settings, Calendar, BarChart3, Leaf } from 'lucide-react'
|
"use client"
|
||||||
import Link from 'next/link'
|
import { useEffect, useState, useRef } from 'react'
|
||||||
|
import { useRouter } from 'next/navigation'
|
||||||
|
import { api } from '@/lib/api'
|
||||||
|
import { Smartphone, ArrowLeft } from 'lucide-react'
|
||||||
|
import Loading from '@/components/Loading'
|
||||||
|
|
||||||
export default function Home() {
|
export default function Home() {
|
||||||
const menuItems = [
|
const router = useRouter()
|
||||||
{
|
const [mobile, setMobile] = useState('')
|
||||||
title: 'انتخاب دستگاه',
|
const [loading, setLoading] = useState(false)
|
||||||
description: 'اتصال به دستگاه گلخانه',
|
const [error, setError] = useState<string | null>(null)
|
||||||
href: '/devices',
|
const mobileRef = useRef<HTMLInputElement>(null)
|
||||||
icon: Settings,
|
|
||||||
color: 'from-blue-500 to-blue-600',
|
useEffect(() => {
|
||||||
iconColor: 'text-blue-500'
|
// Check if user is logged in
|
||||||
},
|
const token = localStorage.getItem('authToken')
|
||||||
{
|
const userStr = localStorage.getItem('user')
|
||||||
title: 'تقویم',
|
|
||||||
description: 'مشاهده دادههای ماهانه',
|
if (token && userStr) {
|
||||||
href: '/calendar?deviceId=1',
|
try {
|
||||||
icon: Calendar,
|
const user = JSON.parse(userStr)
|
||||||
color: 'from-green-500 to-green-600',
|
// Redirect to devices check
|
||||||
iconColor: 'text-green-500'
|
router.push('/devices')
|
||||||
},
|
} catch {
|
||||||
{
|
// Invalid user data, go to login
|
||||||
title: 'جزئیات روز',
|
}
|
||||||
description: 'دادههای روزانه',
|
|
||||||
href: '/day-details?deviceId=1&year=1403&month=1',
|
|
||||||
icon: BarChart3,
|
|
||||||
color: 'from-purple-500 to-purple-600',
|
|
||||||
iconColor: 'text-purple-500'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: 'دادههای تلهمتری',
|
|
||||||
description: 'مشاهده دادههای لحظهای',
|
|
||||||
href: '/telemetry?deviceId=1',
|
|
||||||
icon: Leaf,
|
|
||||||
color: 'from-orange-500 to-orange-600',
|
|
||||||
iconColor: 'text-orange-500'
|
|
||||||
}
|
}
|
||||||
]
|
}, [router])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const checkAutoFill = () => {
|
||||||
|
setTimeout(() => {
|
||||||
|
if (mobileRef.current) {
|
||||||
|
const filledMobile = mobileRef.current.value
|
||||||
|
if (filledMobile && filledMobile !== mobile) {
|
||||||
|
setMobile(filledMobile)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, 100)
|
||||||
|
}
|
||||||
|
|
||||||
|
checkAutoFill()
|
||||||
|
window.addEventListener('load', checkAutoFill)
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('load', checkAutoFill)
|
||||||
|
}
|
||||||
|
}, [mobile])
|
||||||
|
|
||||||
|
const handleInputChange = (e: React.FormEvent<HTMLInputElement>) => {
|
||||||
|
const value = e.currentTarget.value
|
||||||
|
// Only allow digits
|
||||||
|
const digitsOnly = value.replace(/\D/g, '')
|
||||||
|
setMobile(digitsOnly)
|
||||||
|
setError(null)
|
||||||
|
}
|
||||||
|
|
||||||
|
const normalizeMobile = (mobile: string): string => {
|
||||||
|
const digitsOnly = mobile.replace(/\D/g, '')
|
||||||
|
if (digitsOnly.startsWith('9') && digitsOnly.length === 10) {
|
||||||
|
return '0' + digitsOnly
|
||||||
|
}
|
||||||
|
if (digitsOnly.startsWith('0098') && digitsOnly.length === 13) {
|
||||||
|
return '0' + digitsOnly.substring(3)
|
||||||
|
}
|
||||||
|
if (digitsOnly.startsWith('98') && digitsOnly.length === 12) {
|
||||||
|
return '0' + digitsOnly.substring(2)
|
||||||
|
}
|
||||||
|
return digitsOnly
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault()
|
||||||
|
setError(null)
|
||||||
|
|
||||||
|
const normalizedMobile = normalizeMobile(mobile)
|
||||||
|
|
||||||
|
if (!normalizedMobile || normalizedMobile.length !== 11 || !normalizedMobile.startsWith('09')) {
|
||||||
|
setError('لطفاً شماره موبایل معتبر وارد کنید (مثال: 09123456789)')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
setLoading(true)
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await api.sendCode({ mobile: normalizedMobile })
|
||||||
|
|
||||||
|
if (result.success) {
|
||||||
|
// Redirect to verify page with mobile number
|
||||||
|
router.push(`/verify-code?mobile=${encodeURIComponent(normalizedMobile)}`)
|
||||||
|
} else {
|
||||||
|
setError(result.message || 'خطا در ارسال کد')
|
||||||
|
}
|
||||||
|
} catch (error: any) {
|
||||||
|
console.error('Error sending code:', error)
|
||||||
|
setError(error.message || 'خطا در ارتباط با سرور')
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const canSubmit = mobile.length >= 10
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return <Loading message="در حال ارسال کد..." />
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="min-h-screen p-4 md:p-8">
|
<div className="min-h-screen flex items-center justify-center p-4">
|
||||||
<div className="max-w-6xl mx-auto">
|
<div className="w-full max-w-md">
|
||||||
{/* Header */}
|
<div className="bg-white rounded-2xl shadow-xl p-8 border border-gray-100">
|
||||||
<div className="text-center mb-12 mt-8">
|
<div className="text-center mb-8">
|
||||||
<div className="inline-flex items-center justify-center w-20 h-20 bg-gradient-to-br from-green-500 to-green-600 rounded-2xl shadow-lg mb-4">
|
<div className="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-br from-green-500 to-green-600 rounded-2xl shadow-lg mb-4">
|
||||||
<HomeIcon className="w-10 h-10 text-white" />
|
<Smartphone className="w-8 h-8 text-white" />
|
||||||
|
</div>
|
||||||
|
<h1 className="text-2xl font-bold text-gray-900 mb-2">
|
||||||
|
ورود با شماره موبایل
|
||||||
|
</h1>
|
||||||
|
<p className="text-sm text-gray-600">
|
||||||
|
شماره موبایل خود را وارد کنید تا کد فعالسازی برای شما ارسال شود
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<h1 className="text-4xl md:text-5xl font-bold text-gray-900 mb-3">GreenHome</h1>
|
|
||||||
<p className="text-lg text-gray-600">مدیریت هوشمند گلخانه</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Menu Grid */}
|
<form onSubmit={handleSubmit} className="space-y-5">
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
<div>
|
||||||
{menuItems.map((item) => {
|
<label className="block text-sm font-medium text-gray-700 mb-2">
|
||||||
const Icon = item.icon
|
شماره موبایل
|
||||||
return (
|
</label>
|
||||||
<Link
|
<input
|
||||||
key={item.href}
|
ref={mobileRef}
|
||||||
href={item.href}
|
type="tel"
|
||||||
className="group relative bg-white rounded-2xl shadow-md hover:shadow-xl transition-all duration-300 overflow-hidden border border-gray-100"
|
inputMode="numeric"
|
||||||
>
|
className="w-full px-4 py-3 rounded-xl border-2 border-gray-200 bg-gray-50 focus:border-green-500 focus:bg-white focus:outline-none focus:ring-2 focus:ring-green-500/20 transition-all duration-200 text-left"
|
||||||
<div className="p-6">
|
placeholder="09123456789"
|
||||||
<div className="flex items-start gap-4">
|
value={mobile}
|
||||||
<div className={`flex-shrink-0 w-14 h-14 rounded-xl bg-gradient-to-br ${item.color} flex items-center justify-center shadow-md group-hover:scale-110 transition-transform duration-300`}>
|
onInput={handleInputChange}
|
||||||
<Icon className="w-7 h-7 text-white" />
|
disabled={loading}
|
||||||
</div>
|
maxLength={11}
|
||||||
<div className="flex-1">
|
/>
|
||||||
<h3 className="text-xl font-semibold text-gray-900 mb-1 group-hover:text-green-600 transition-colors">
|
</div>
|
||||||
{item.title}
|
|
||||||
</h3>
|
|
||||||
<p className="text-sm text-gray-500">{item.description}</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className={`absolute bottom-0 left-0 right-0 h-1 bg-gradient-to-r ${item.color} transform scale-x-0 group-hover:scale-x-100 transition-transform duration-300`} />
|
|
||||||
</Link>
|
|
||||||
)
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Footer Info */}
|
{error && (
|
||||||
<div className="mt-12 text-center">
|
<div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-xl text-sm text-center">
|
||||||
<p className="text-sm text-gray-500">
|
{error}
|
||||||
سیستم مدیریت و مانیتورینگ گلخانه هوشمند
|
</div>
|
||||||
</p>
|
)}
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={loading || !canSubmit}
|
||||||
|
className={`w-full py-3 rounded-xl text-white font-medium transition-all duration-200 flex items-center justify-center gap-2 shadow-md ${
|
||||||
|
!loading && canSubmit
|
||||||
|
? 'bg-gradient-to-r from-green-500 to-green-600 hover:from-green-600 hover:to-green-700 hover:shadow-lg transform hover:-translate-y-0.5'
|
||||||
|
: 'bg-gray-300 cursor-not-allowed'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{loading ? (
|
||||||
|
<>
|
||||||
|
<div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin" />
|
||||||
|
در حال ارسال...
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
ارسال کد فعالسازی
|
||||||
|
<ArrowLeft className="w-5 h-5" />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</main>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
307
src/app/verify-code/page.tsx
Normal file
307
src/app/verify-code/page.tsx
Normal file
@@ -0,0 +1,307 @@
|
|||||||
|
"use client"
|
||||||
|
import { useState, useEffect, useRef } from 'react'
|
||||||
|
import { useSearchParams, useRouter } from 'next/navigation'
|
||||||
|
import { api } from '@/lib/api'
|
||||||
|
import { Shield, ArrowRight, ArrowLeft, RotateCcw } from 'lucide-react'
|
||||||
|
import Link from 'next/link'
|
||||||
|
import Loading from '@/components/Loading'
|
||||||
|
|
||||||
|
export default function VerifyCodePage() {
|
||||||
|
const searchParams = useSearchParams()
|
||||||
|
const router = useRouter()
|
||||||
|
const mobile = searchParams.get('mobile') || ''
|
||||||
|
|
||||||
|
const [code, setCode] = useState(['', '', '', ''])
|
||||||
|
const [loading, setLoading] = useState(false)
|
||||||
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
const [resendCooldown, setResendCooldown] = useState(120)
|
||||||
|
const [canResend, setCanResend] = useState(false)
|
||||||
|
const inputRefs = useRef<(HTMLInputElement | null)[]>([])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!mobile || mobile.length !== 11) {
|
||||||
|
router.push('/login')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check resend cooldown
|
||||||
|
checkResendStatus()
|
||||||
|
const interval = setInterval(() => {
|
||||||
|
setResendCooldown(prev => {
|
||||||
|
if (prev <= 1) {
|
||||||
|
setCanResend(true)
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return prev - 1
|
||||||
|
})
|
||||||
|
}, 1000)
|
||||||
|
|
||||||
|
return () => clearInterval(interval)
|
||||||
|
}, [mobile, router])
|
||||||
|
|
||||||
|
const checkResendStatus = async () => {
|
||||||
|
try {
|
||||||
|
const result = await api.canResend(mobile)
|
||||||
|
if (result.canResend) {
|
||||||
|
setCanResend(true)
|
||||||
|
setResendCooldown(0)
|
||||||
|
} else {
|
||||||
|
setCanResend(false)
|
||||||
|
setResendCooldown(120)
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error checking resend status:', error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleCodeChange = (index: number, value: string) => {
|
||||||
|
if (!/^\d*$/.test(value)) return
|
||||||
|
|
||||||
|
const newCode = [...code]
|
||||||
|
newCode[index] = value.slice(-1)
|
||||||
|
setCode(newCode)
|
||||||
|
setError(null)
|
||||||
|
|
||||||
|
// Auto-focus next input
|
||||||
|
if (value && index < 3) {
|
||||||
|
inputRefs.current[index + 1]?.focus()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Auto-submit when all fields are filled
|
||||||
|
if (newCode.every(c => c !== '') && newCode.join('').length === 4) {
|
||||||
|
handleVerify(newCode.join(''))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleKeyDown = (index: number, e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||||
|
if (e.key === 'Backspace' && !code[index] && index > 0) {
|
||||||
|
inputRefs.current[index - 1]?.focus()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handlePaste = (e: React.ClipboardEvent) => {
|
||||||
|
e.preventDefault()
|
||||||
|
const pastedData = e.clipboardData.getData('text').replace(/\D/g, '').slice(0, 4)
|
||||||
|
if (pastedData.length === 4) {
|
||||||
|
const newCode = pastedData.split('')
|
||||||
|
setCode(newCode)
|
||||||
|
inputRefs.current[3]?.focus()
|
||||||
|
handleVerify(pastedData)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleVerify = async (codeToVerify?: string) => {
|
||||||
|
const codeValue = codeToVerify || code.join('')
|
||||||
|
|
||||||
|
if (codeValue.length !== 4) {
|
||||||
|
setError('لطفاً کد ۴ رقمی را کامل وارد کنید')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
setLoading(true)
|
||||||
|
setError(null)
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await api.verifyCode({ mobile, code: codeValue })
|
||||||
|
|
||||||
|
if (result.success && result.token && result.user) {
|
||||||
|
// Store token in localStorage
|
||||||
|
localStorage.setItem('authToken', result.token)
|
||||||
|
localStorage.setItem('user', JSON.stringify(result.user))
|
||||||
|
|
||||||
|
// Check user devices
|
||||||
|
try {
|
||||||
|
const devicesResult = await api.getDevicesFiltered({
|
||||||
|
userId: result.user.id,
|
||||||
|
page: 1,
|
||||||
|
pageSize: 10
|
||||||
|
})
|
||||||
|
|
||||||
|
if (devicesResult.totalCount === 0) {
|
||||||
|
// No devices - show error and logout
|
||||||
|
setError('شما هیچ دستگاهی ندارید. لطفاً با پشتیبانی تماس بگیرید.')
|
||||||
|
localStorage.removeItem('authToken')
|
||||||
|
localStorage.removeItem('user')
|
||||||
|
return
|
||||||
|
} else if (devicesResult.totalCount === 1) {
|
||||||
|
// Single device - redirect to calendar
|
||||||
|
router.push(`/calendar?deviceId=${devicesResult.items[0].id}`)
|
||||||
|
} else {
|
||||||
|
// Multiple devices - redirect to device list
|
||||||
|
router.push('/devices')
|
||||||
|
}
|
||||||
|
} catch (deviceError) {
|
||||||
|
console.error('Error fetching devices:', deviceError)
|
||||||
|
// Still redirect to devices page to handle error there
|
||||||
|
router.push('/devices')
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
setError(result.message || 'کد وارد شده نادرست است')
|
||||||
|
// Clear code inputs
|
||||||
|
setCode(['', '', '', ''])
|
||||||
|
inputRefs.current[0]?.focus()
|
||||||
|
}
|
||||||
|
} catch (error: any) {
|
||||||
|
console.error('Error verifying code:', error)
|
||||||
|
setError(error.message || 'خطا در ارتباط با سرور')
|
||||||
|
setCode(['', '', '', ''])
|
||||||
|
inputRefs.current[0]?.focus()
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleResend = async () => {
|
||||||
|
if (!canResend) return
|
||||||
|
|
||||||
|
setLoading(true)
|
||||||
|
setError(null)
|
||||||
|
setCanResend(false)
|
||||||
|
setResendCooldown(120)
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await api.sendCode({ mobile })
|
||||||
|
|
||||||
|
if (result.success) {
|
||||||
|
setResendCooldown(result.resendAfterSeconds || 120)
|
||||||
|
// Clear code inputs
|
||||||
|
setCode(['', '', '', ''])
|
||||||
|
inputRefs.current[0]?.focus()
|
||||||
|
} else {
|
||||||
|
setError(result.message || 'خطا در ارسال مجدد کد')
|
||||||
|
setCanResend(true)
|
||||||
|
}
|
||||||
|
} catch (error: any) {
|
||||||
|
console.error('Error resending code:', error)
|
||||||
|
setError(error.message || 'خطا در ارتباط با سرور')
|
||||||
|
setCanResend(true)
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const formatMobile = (mobile: string) => {
|
||||||
|
if (mobile.length === 11) {
|
||||||
|
//return `${mobile.slice(0, 4)}${mobile.slice(4, 7)} ${mobile.slice(7)}`
|
||||||
|
return mobile;
|
||||||
|
}
|
||||||
|
return mobile
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loading && code.join('').length !== 4) {
|
||||||
|
return <Loading message="در حال بررسی کد..." />
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center p-4">
|
||||||
|
<div className="w-full max-w-md">
|
||||||
|
<div className="bg-white rounded-2xl shadow-xl p-8 border border-gray-100">
|
||||||
|
<div className="text-center mb-8">
|
||||||
|
<div className="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-br from-green-500 to-green-600 rounded-2xl shadow-lg mb-4">
|
||||||
|
<Shield className="w-8 h-8 text-white" />
|
||||||
|
</div>
|
||||||
|
<h1 className="text-2xl font-bold text-gray-900 mb-2">
|
||||||
|
تایید کد فعالسازی
|
||||||
|
</h1>
|
||||||
|
<p className="text-sm text-gray-600 mb-1">
|
||||||
|
کد ارسال شده به شماره
|
||||||
|
</p>
|
||||||
|
<p className="text-sm font-semibold text-gray-900" style={{ direction: 'ltr' }}>
|
||||||
|
{formatMobile(mobile)}
|
||||||
|
</p>
|
||||||
|
<p className="text-sm text-gray-600 mt-2">
|
||||||
|
را وارد کنید
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form onSubmit={(e) => { e.preventDefault(); handleVerify(); }} className="space-y-5">
|
||||||
|
<div className="flex justify-center gap-3" style={{ direction: 'ltr' }}>
|
||||||
|
{code.map((digit, index) => (
|
||||||
|
<input
|
||||||
|
key={index}
|
||||||
|
ref={(el) => { inputRefs.current[index] = el }}
|
||||||
|
type="text"
|
||||||
|
inputMode="numeric"
|
||||||
|
maxLength={1}
|
||||||
|
value={digit}
|
||||||
|
onChange={(e) => handleCodeChange(index, e.target.value)}
|
||||||
|
onKeyDown={(e) => handleKeyDown(index, e)}
|
||||||
|
onPaste={index === 0 ? handlePaste : undefined}
|
||||||
|
className="w-14 h-14 text-center text-2xl font-bold rounded-xl border-2 border-gray-200 bg-gray-50 focus:border-green-500 focus:bg-white focus:outline-none focus:ring-2 focus:ring-green-500/20 transition-all duration-200"
|
||||||
|
disabled={loading}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-xl text-sm text-center">
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={loading || code.join('').length !== 4}
|
||||||
|
className={`w-full py-3 rounded-xl text-white font-medium transition-all duration-200 flex items-center justify-center gap-2 shadow-md ${
|
||||||
|
!loading && code.join('').length === 4
|
||||||
|
? 'bg-gradient-to-r from-green-500 to-green-600 hover:from-green-600 hover:to-green-700 hover:shadow-lg transform hover:-translate-y-0.5'
|
||||||
|
: 'bg-gray-300 cursor-not-allowed'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{loading ? (
|
||||||
|
<>
|
||||||
|
<div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin" />
|
||||||
|
در حال بررسی...
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
تایید و ورود
|
||||||
|
<ArrowLeft className="w-5 h-5" />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<div className="pt-4 border-t border-gray-200 space-y-3">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={handleResend}
|
||||||
|
disabled={!canResend || loading}
|
||||||
|
className={`w-full flex items-center justify-center gap-2 py-2.5 rounded-xl font-medium transition-all duration-200 ${
|
||||||
|
canResend && !loading
|
||||||
|
? 'bg-blue-500 hover:bg-blue-600 text-white shadow-md hover:shadow-lg'
|
||||||
|
: 'bg-gray-100 text-gray-400 cursor-not-allowed'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<RotateCcw className="w-4 h-4" />
|
||||||
|
{canResend ? (
|
||||||
|
'ارسال مجدد کد'
|
||||||
|
) : (
|
||||||
|
`ارسال مجدد (${Math.floor(resendCooldown / 60)}:${String(resendCooldown % 60).padStart(2, '0')})`
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<Link
|
||||||
|
href="/login"
|
||||||
|
className="block w-full text-center text-sm text-gray-600 hover:text-gray-900 transition-colors py-2"
|
||||||
|
>
|
||||||
|
<ArrowRight className="w-4 h-4 inline ml-1" />
|
||||||
|
تغییر شماره موبایل
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-6 text-center">
|
||||||
|
<Link
|
||||||
|
href="/"
|
||||||
|
className="inline-flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 transition-colors"
|
||||||
|
>
|
||||||
|
<ArrowRight className="w-4 h-4" />
|
||||||
|
بازگشت به صفحه اصلی
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
@@ -1,8 +1,12 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
export type DeviceDto = {
|
export type DeviceDto = {
|
||||||
id: number
|
id: number
|
||||||
deviceName: string
|
deviceName: string
|
||||||
owner: string
|
userId: number
|
||||||
mobile: string
|
userName: string
|
||||||
|
userFamily: string
|
||||||
|
userMobile: string
|
||||||
location: string
|
location: string
|
||||||
neshanLocation: string
|
neshanLocation: string
|
||||||
}
|
}
|
||||||
@@ -40,6 +44,33 @@ export type DeviceSettingsDto = {
|
|||||||
updatedAt: string
|
updatedAt: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type SendCodeRequest = {
|
||||||
|
mobile: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type SendCodeResponse = {
|
||||||
|
success: boolean
|
||||||
|
message?: string
|
||||||
|
resendAfterSeconds: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export type VerifyCodeRequest = {
|
||||||
|
mobile: string
|
||||||
|
code: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type VerifyCodeResponse = {
|
||||||
|
success: boolean
|
||||||
|
message?: string
|
||||||
|
token?: string
|
||||||
|
user?: {
|
||||||
|
id: number
|
||||||
|
mobile: string
|
||||||
|
name: string
|
||||||
|
family: string
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export type PagedResult<T> = {
|
export type PagedResult<T> = {
|
||||||
items: T[]
|
items: T[]
|
||||||
totalCount: number
|
totalCount: number
|
||||||
@@ -48,11 +79,21 @@ export type PagedResult<T> = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const API_BASE = process.env.NEXT_PUBLIC_API_URL ?? 'https://ghback.nabaksoft.ir'
|
const API_BASE = process.env.NEXT_PUBLIC_API_URL ?? 'https://ghback.nabaksoft.ir'
|
||||||
|
|
||||||
async function http<T>(url: string, init?: RequestInit): Promise<T> {
|
async function http<T>(url: string, init?: RequestInit): Promise<T> {
|
||||||
const res = await fetch(url, { ...init, headers: { 'Content-Type': 'application/json', ...(init?.headers || {}) } })
|
const res = await fetch(url, { ...init, headers: { 'Content-Type': 'application/json', ...(init?.headers || {}) } })
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
throw new Error(`HTTP ${res.status}`)
|
let errorMessage = `HTTP ${res.status}`
|
||||||
|
try {
|
||||||
|
const errorData = await res.json()
|
||||||
|
if (errorData.message) {
|
||||||
|
errorMessage = errorData.message
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Ignore JSON parse errors
|
||||||
|
}
|
||||||
|
const error: any = new Error(errorMessage)
|
||||||
|
error.status = res.status
|
||||||
|
throw error
|
||||||
}
|
}
|
||||||
return res.json() as Promise<T>
|
return res.json() as Promise<T>
|
||||||
}
|
}
|
||||||
@@ -83,5 +124,20 @@ export const api = {
|
|||||||
// Device Settings
|
// Device Settings
|
||||||
getDeviceSettings: (deviceId: number) => http<DeviceSettingsDto>(`${API_BASE}/api/devicesettings/${deviceId}`),
|
getDeviceSettings: (deviceId: number) => http<DeviceSettingsDto>(`${API_BASE}/api/devicesettings/${deviceId}`),
|
||||||
createDeviceSettings: (dto: DeviceSettingsDto) => http<number>(`${API_BASE}/api/devicesettings`, { method: 'POST', body: JSON.stringify(dto) }),
|
createDeviceSettings: (dto: DeviceSettingsDto) => http<number>(`${API_BASE}/api/devicesettings`, { method: 'POST', body: JSON.stringify(dto) }),
|
||||||
updateDeviceSettings: (dto: DeviceSettingsDto) => http<void>(`${API_BASE}/api/devicesettings`, { method: 'PUT', body: JSON.stringify(dto) })
|
updateDeviceSettings: (dto: DeviceSettingsDto) => http<void>(`${API_BASE}/api/devicesettings`, { method: 'PUT', body: JSON.stringify(dto) }),
|
||||||
|
|
||||||
|
// Authentication
|
||||||
|
sendCode: (request: SendCodeRequest) => http<SendCodeResponse>(`${API_BASE}/api/auth/send-code`, { method: 'POST', body: JSON.stringify(request) }),
|
||||||
|
verifyCode: (request: VerifyCodeRequest) => http<VerifyCodeResponse>(`${API_BASE}/api/auth/verify-code`, { method: 'POST', body: JSON.stringify(request) }),
|
||||||
|
canResend: (mobile: string) => http<{ canResend: boolean }>(`${API_BASE}/api/auth/can-resend?mobile=${encodeURIComponent(mobile)}`),
|
||||||
|
|
||||||
|
// User Devices
|
||||||
|
getUserDevices: (userId: number) => http<DeviceDto[]>(`${API_BASE}/api/devices/user/${userId}`),
|
||||||
|
getDevicesFiltered: (q: { userId: number; search?: string; page?: number; pageSize?: number }) => {
|
||||||
|
const params = new URLSearchParams({ userId: String(q.userId) })
|
||||||
|
if (q.search) params.set('search', q.search)
|
||||||
|
if (q.page) params.set('page', String(q.page))
|
||||||
|
if (q.pageSize) params.set('pageSize', String(q.pageSize))
|
||||||
|
return http<PagedResult<DeviceDto>>(`${API_BASE}/api/devices/filtered?${params.toString()}`)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user