This commit is contained in:
@@ -1,259 +1,293 @@
|
||||
"use client"
|
||||
import { useMemo, useState, useRef, useEffect } from 'react'
|
||||
import { api, DeviceDto } from '@/lib/api'
|
||||
import { Settings, CheckCircle2, ArrowRight, Calendar, BarChart3, Activity, RotateCcw } from 'lucide-react'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { api, DeviceDto, PagedResult } from '@/lib/api'
|
||||
import { Settings, Calendar, LogOut, ArrowRight, Search, ChevronRight, ChevronLeft } from 'lucide-react'
|
||||
import Link from 'next/link'
|
||||
import Loading from '@/components/Loading'
|
||||
|
||||
export default function DevicesPage() {
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [deviceName, setDeviceName] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [selected, setSelected] = useState<DeviceDto | null>(null)
|
||||
const router = useRouter()
|
||||
const [pagedResult, setPagedResult] = useState<PagedResult<DeviceDto> | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
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 passwordRef = useRef<HTMLInputElement>(null)
|
||||
const pageSize = 10
|
||||
|
||||
const canSubmit = useMemo(() => deviceName.trim().length > 0 && password.trim().length > 0, [deviceName, password])
|
||||
|
||||
// بررسی 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
|
||||
}
|
||||
const fetchDevices = async (page: number, search?: string) => {
|
||||
if (!user) return
|
||||
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
// فراخوانی API برای بررسی دستگاه
|
||||
const device = await api.CheckDevice(currentDeviceName.trim(), currentPassword.trim())
|
||||
const result = await api.getDevicesFiltered({
|
||||
userId: user.id,
|
||||
search: search || undefined,
|
||||
page,
|
||||
pageSize
|
||||
})
|
||||
|
||||
if (device !=undefined) {
|
||||
setSelected(device)
|
||||
if (result.items.length === 0 && page === 1) {
|
||||
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 {
|
||||
setError('دستگاه یافت نشد یا رمز عبور نادرست است')
|
||||
setPagedResult(result)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error checking device:', error)
|
||||
setError('خطا در ارتباط با سرور')
|
||||
} catch (err) {
|
||||
console.error('Error fetching devices:', err)
|
||||
setError('خطا در دریافت لیست دستگاهها')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
function handleReset() {
|
||||
setSelected(null)
|
||||
setDeviceName('')
|
||||
setPassword('')
|
||||
setError(null)
|
||||
useEffect(() => {
|
||||
// Check authentication
|
||||
const token = localStorage.getItem('authToken')
|
||||
const userStr = localStorage.getItem('user')
|
||||
|
||||
// پاک کردن refها
|
||||
if (deviceNameRef.current) deviceNameRef.current.value = ''
|
||||
if (passwordRef.current) passwordRef.current.value = ''
|
||||
if (!token || !userStr) {
|
||||
router.push('/')
|
||||
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) {
|
||||
return <Loading message="در حال بررسی دستگاه..." />
|
||||
const handleLogout = () => {
|
||||
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 (
|
||||
<div className="min-h-screen flex items-center justify-center p-4">
|
||||
<div className="w-full max-w-md">
|
||||
{/* Main Card */}
|
||||
<div className="bg-white rounded-2xl shadow-xl p-8 border border-gray-100">
|
||||
{/* Title Section */}
|
||||
<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">
|
||||
{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 ? 'دستگاه فعال' : 'انتخاب دستگاه'}
|
||||
<div className="min-h-screen p-4 md:p-8">
|
||||
<div className="max-w-6xl mx-auto">
|
||||
{/* Header */}
|
||||
<div className="mb-6 flex items-center justify-between flex-wrap gap-4">
|
||||
<div>
|
||||
<h1 className="text-2xl md:text-3xl font-bold text-gray-900 mb-2">
|
||||
انتخاب دستگاه
|
||||
</h1>
|
||||
<p className="text-sm text-gray-600">
|
||||
{selected
|
||||
? `دستگاه "${selected.deviceName}" با موفقیت تأیید شد`
|
||||
: 'نام دستگاه و رمز عبور را وارد کنید'
|
||||
}
|
||||
</p>
|
||||
{user && (
|
||||
<p className="text-sm text-gray-600">
|
||||
{user.name} {user.family} ({user.mobile})
|
||||
</p>
|
||||
)}
|
||||
</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>
|
||||
|
||||
{/* نمایش فرم فقط وقتی دستگاه انتخاب نشده */}
|
||||
{!selected ? (
|
||||
<form onSubmit={handleSubmit} className="space-y-5">
|
||||
{/* Input Fields */}
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">
|
||||
نام دستگاه
|
||||
</label>
|
||||
<input
|
||||
ref={deviceNameRef}
|
||||
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"
|
||||
placeholder="نام دستگاه را وارد کنید"
|
||||
defaultValue={deviceName}
|
||||
onInput={handleInputChange}
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">
|
||||
رمز عبور
|
||||
</label>
|
||||
<input
|
||||
ref={passwordRef}
|
||||
name="password"
|
||||
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 */}
|
||||
{/* Search */}
|
||||
<div className="mb-6">
|
||||
<form onSubmit={handleSearch} className="flex gap-2">
|
||||
<div className="flex-1 relative">
|
||||
<Search className="absolute right-4 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
|
||||
<input
|
||||
type="text"
|
||||
value={searchInput}
|
||||
onChange={(e) => setSearchInput(e.target.value)}
|
||||
placeholder="جستجو در نام دستگاه، نام صاحب، نام خانوادگی صاحب، موقعیت..."
|
||||
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"
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
type="submit"
|
||||
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"
|
||||
>
|
||||
<Search className="w-5 h-5" />
|
||||
جستجو
|
||||
</button>
|
||||
</form>
|
||||
{searchTerm && (
|
||||
<div className="mt-2 flex items-center gap-2">
|
||||
<span className="text-sm text-gray-600">
|
||||
نتایج جستجو برای: <span className="font-semibold">{searchTerm}</span>
|
||||
</span>
|
||||
<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'
|
||||
}`}
|
||||
onClick={() => {
|
||||
setSearchInput('')
|
||||
setSearchTerm('')
|
||||
setCurrentPage(1)
|
||||
}}
|
||||
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>
|
||||
</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>
|
||||
|
||||
{/* 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 */}
|
||||
<div className="mt-6 text-center">
|
||||
<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'
|
||||
import Link from 'next/link'
|
||||
"use client"
|
||||
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() {
|
||||
const menuItems = [
|
||||
{
|
||||
title: 'انتخاب دستگاه',
|
||||
description: 'اتصال به دستگاه گلخانه',
|
||||
href: '/devices',
|
||||
icon: Settings,
|
||||
color: 'from-blue-500 to-blue-600',
|
||||
iconColor: 'text-blue-500'
|
||||
},
|
||||
{
|
||||
title: 'تقویم',
|
||||
description: 'مشاهده دادههای ماهانه',
|
||||
href: '/calendar?deviceId=1',
|
||||
icon: Calendar,
|
||||
color: 'from-green-500 to-green-600',
|
||||
iconColor: 'text-green-500'
|
||||
},
|
||||
{
|
||||
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'
|
||||
const router = useRouter()
|
||||
const [mobile, setMobile] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const mobileRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
// Check if user is logged in
|
||||
const token = localStorage.getItem('authToken')
|
||||
const userStr = localStorage.getItem('user')
|
||||
|
||||
if (token && userStr) {
|
||||
try {
|
||||
const user = JSON.parse(userStr)
|
||||
// Redirect to devices check
|
||||
router.push('/devices')
|
||||
} catch {
|
||||
// Invalid user data, go to login
|
||||
}
|
||||
}
|
||||
]
|
||||
}, [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 (
|
||||
<main className="min-h-screen p-4 md:p-8">
|
||||
<div className="max-w-6xl mx-auto">
|
||||
{/* Header */}
|
||||
<div className="text-center mb-12 mt-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">
|
||||
<HomeIcon className="w-10 h-10 text-white" />
|
||||
<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>
|
||||
<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 */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
{menuItems.map((item) => {
|
||||
const Icon = item.icon
|
||||
return (
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
className="group relative bg-white rounded-2xl shadow-md hover:shadow-xl transition-all duration-300 overflow-hidden border border-gray-100"
|
||||
>
|
||||
<div className="p-6">
|
||||
<div className="flex items-start gap-4">
|
||||
<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`}>
|
||||
<Icon 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">
|
||||
{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>
|
||||
<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>
|
||||
|
||||
{/* Footer Info */}
|
||||
<div className="mt-12 text-center">
|
||||
<p className="text-sm text-gray-500">
|
||||
سیستم مدیریت و مانیتورینگ گلخانه هوشمند
|
||||
</p>
|
||||
{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>
|
||||
</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 = {
|
||||
id: number
|
||||
deviceName: string
|
||||
owner: string
|
||||
mobile: string
|
||||
userId: number
|
||||
userName: string
|
||||
userFamily: string
|
||||
userMobile: string
|
||||
location: string
|
||||
neshanLocation: string
|
||||
}
|
||||
@@ -40,6 +44,33 @@ export type DeviceSettingsDto = {
|
||||
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> = {
|
||||
items: T[]
|
||||
totalCount: number
|
||||
@@ -48,11 +79,21 @@ export type PagedResult<T> = {
|
||||
}
|
||||
|
||||
const API_BASE = process.env.NEXT_PUBLIC_API_URL ?? 'https://ghback.nabaksoft.ir'
|
||||
|
||||
async function http<T>(url: string, init?: RequestInit): Promise<T> {
|
||||
const res = await fetch(url, { ...init, headers: { 'Content-Type': 'application/json', ...(init?.headers || {}) } })
|
||||
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>
|
||||
}
|
||||
@@ -83,5 +124,20 @@ export const api = {
|
||||
// Device Settings
|
||||
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) }),
|
||||
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