feat: connect UI texts, address CRUD, OTP autofocus and profile to backend

This commit is contained in:
parsa committed 2026-05-26 21:39:14 +03:30
1 parent 4e2c8d5cfe
commit 467532713c
82 files changed
+14436 -274

No files matched your search

+32 -22
View File
@@ -11,6 +11,8 @@ import { Toaster } from "sonner";
import { Product } from "./data/products";
import { useCartStore } from "./store/cartStore";
import { usePetStore } from "./store/usePetStore";
import { useUserStore } from "./store/userStore";
import { useSettingsStore } from "./store/settingsStore";
import { NetworkBanner } from './components/NetworkBanner';
import { ErrorBoundary } from './components/ErrorBoundary';
import { NotFoundPage } from './components/ErrorPages';
@@ -64,14 +66,29 @@ export default function App() {
const [isLoading, setIsLoading] = useState(true);
const [searchQuery, setSearchQuery] = useState("");
const { fetchProfile, isLoggedIn: storeIsLoggedIn } = useUserStore();
const fetchSettings = useSettingsStore(state => state.fetchSettings);
const getText = useSettingsStore(state => state.getText);
useEffect(() => {
const init = async () => {
// Simulating initial data load
await new Promise(resolve => setTimeout(resolve, 800));
await fetchSettings();
const token = localStorage.getItem('accessToken');
if (token) {
try {
await fetchProfile();
} catch (e) {
console.error("Auth init failed:", e);
}
}
setIsLoading(false);
};
init();
}, []);
}, [fetchProfile, fetchSettings]);
useEffect(() => {
setIsLoggedIn(storeIsLoggedIn);
}, [storeIsLoggedIn]);
useEffect(() => {
const handlePopState = (event: PopStateEvent) => {
const params = new URLSearchParams(window.location.search);
@@ -154,15 +171,8 @@ export default function App() {
window.scrollTo({ top: 0, behavior: 'smooth' });
};
const finalizeOrder = () => {
const activePet = getActivePet();
const orderId = addOrder({
items,
total: getTotal(),
petId: activePet?.id
});
const finalizeOrder = (orderId: string) => {
setLastOrderId(orderId);
clearCart();
setCurrentView("order-success");
window.scrollTo({ top: 0, behavior: 'smooth' });
};
@@ -296,20 +306,20 @@ export default function App() {
className="rounded-[3rem] shadow-2xl relative z-10 grayscale-[10%]"
/>
<div className="absolute -bottom-6 -left-6 bg-canina-blue text-white p-8 rounded-3xl shadow-xl z-20">
<div className="text-4xl font-black mb-1 italic">کیفیت</div>
<div className="text-xs uppercase tracking-widest font-bold opacity-80">استانداردهای فوق‌دارویی</div>
<div className="text-4xl font-black mb-1 italic">{getText('about_teaser_quality_title', 'کیفیت')}</div>
<div className="text-xs uppercase tracking-widest font-bold opacity-80">{getText('about_teaser_quality_desc', 'استانداردهای فوق‌دارویی')}</div>
</div>
</div>
<div>
<div className="text-canina-blue text-xs font-bold uppercase tracking-[0.2em] mb-4">میراث ما از آلمان</div>
<div className="text-canina-blue text-xs font-bold uppercase tracking-[0.2em] mb-4">{getText('about_teaser_badge', 'میراث ما از آلمان')}</div>
<h2 className="text-3xl lg:text-5xl font-black text-medical-gray-900 leading-[1.2] mb-8">
چرا برند آلمانی <span className="text-canina-blue italic">Canina</span> مرجع دامپزشکان است؟
{getText('about_teaser_title', 'چرا برند آلمانی Canina مرجع دامپزشکان است؟')}
</h2>
<div className="space-y-6">
{[
{ title: "مواد اولیه نایاب", desc: "استفاده از پودر صدف لب‌سبز اصل نیوزیلند و مواد ارگانیک با گرید دارویی." },
{ title: "فاقد مواد نگهدارنده", desc: "تمامی محصولات ۱۰۰٪ طبیعی و فاقد رنگ‌های مصنوعی و طعم‌دهنده‌های شیمیایی هستند." },
{ title: "تاییدیه اروپا", desc: "مطابق با سخت‌گیرانه‌ترین استانداردهای ایمنی مواد غذایی و دارویی در اتحادیه اروپا." }
{ title: getText('about_teaser_feat1_title', 'مواد اولیه نایاب'), desc: getText('about_teaser_feat1_desc', 'استفاده از پودر صدف لب‌سبز اصل نیوزیلند و مواد ارگانیک با گرید دارویی.') },
{ title: getText('about_teaser_feat2_title', 'فاقد مواد نگهدارنده'), desc: getText('about_teaser_feat2_desc', 'تمامی محصولات ۱۰۰٪ طبیعی و فاقد رنگ‌های مصنوعی و طعم‌دهنده‌های شیمیایی هستند.') },
{ title: getText('about_teaser_feat3_title', 'تاییدیه اروپا'), desc: getText('about_teaser_feat3_desc', 'مطابق با سخت‌گیرانه‌ترین استانداردهای ایمنی مواد غذایی و دارویی در اتحادیه اروپا.') }
].map((item, idx) => (
<div key={idx} className="flex gap-4">
<div className="w-12 h-12 rounded-2xl bg-medical-gray-50 flex items-center justify-center flex-shrink-0 text-canina-blue font-bold">
@@ -373,20 +383,20 @@ export default function App() {
</div>
<div className="max-w-4xl mx-auto px-4 text-center relative z-10">
<h2 className="text-3xl lg:text-5xl font-black text-white mb-8 leading-tight">
می‌خواهید بدانید کدام محصول برای پت شما مناسب‌تر است؟
{getText('cta_title', 'می‌خواهید بدانید کدام محصول برای پت شما مناسب‌تر است؟')}
</h2>
<p className="text-white/80 text-lg mb-10 leading-relaxed">
تیم متخصص دامپزشکی کانینا ایران آماده پاسخگویی به سوالات شماست.
{getText('cta_subtitle', 'تیم متخصص دامپزشکی کانینا ایران آماده پاسخگویی به سوالات شماست.')}
</p>
<div className="flex flex-wrap justify-center gap-4">
<button className="bg-white text-canina-blue px-12 py-5 rounded-full font-black text-xl hover:scale-105 transition-transform shadow-2xl shadow-black/20">
دریافت رژیم مکمل رایگان
{getText('cta_btn_free', 'دریافت رژیم مکمل رایگان')}
</button>
<button
onClick={() => navigateToShop()}
className="bg-canina-blue/20 backdrop-blur-md border-2 border-white text-white px-12 py-5 rounded-full font-black text-xl hover:bg-white hover:text-canina-blue transition-all"
>
ورود به محصولات تخصصی
{getText('cta_btn_products', 'ورود به محصولات تخصصی')}
</button>
</div>
</div>
+1 -1
View File
@@ -102,7 +102,7 @@ export default function AddressModal({ isOpen, onClose, onSave, editingAddress }
phone: normalizeDigits(formData.phone),
zipCode: normalizeDigits(formData.zipCode),
id: editingAddress?.id || Math.random().toString(36).substr(2, 9),
isDefault: editingAddress?.isDefault || false
isDefault: formData.isDefault
});
toast.success(editingAddress ? "تغییرات آدرس با موفقیت ذخیره شد" : "آدرس جدید با موفقیت اضافه شد");
setIsSubmitting(false);
+335 -46
View File
@@ -1,8 +1,10 @@
import React from "react";
import React, { useState, useEffect, useRef } from "react";
import { motion, AnimatePresence } from "motion/react";
import { X, User, Building2, Heart, ShieldCheck } from "lucide-react";
import { X, User, Building2, Heart, ShieldCheck, Phone, Key, LogIn, ArrowRight, RefreshCw } from "lucide-react";
import { useUserStore, UserRole } from "../store/userStore";
import { authService } from "../services/authService";
import { toast } from "sonner";
import { toPersian } from "../lib/utils";
interface AuthModalProps {
isOpen: boolean;
@@ -10,20 +12,145 @@ interface AuthModalProps {
}
export default function AuthModal({ isOpen, onClose }: AuthModalProps) {
const { setRole, setLoggedIn } = useUserStore();
const { setRole, setLoggedIn, fetchProfile } = useUserStore();
const [view, setView] = useState<"quick" | "phone" | "otp">("quick");
const [phoneNumber, setPhoneNumber] = useState("");
const [otpCode, setOtpCode] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [countdown, setCountdown] = useState(0);
const otpInputRef = useRef<HTMLInputElement>(null);
const handleQuickLogin = (role: UserRole) => {
// TODO: [BACKEND_API] POST /api/auth/login | Payload: { role: UserRole, mobile?: string } | Expected: { token: string, user: UserProfile } | Errors: [401]
setRole(role);
setLoggedIn(role !== "User_Guest");
toast.success(`خوش آمدید! در نقش ${role === "User_Partner" ? 'همکار' : role === 'User_PetOwner' ? 'صاحب پت' : 'مهمان'} وارد شدید.`);
onClose();
useEffect(() => {
if (view === "otp") {
const timer = setTimeout(() => {
otpInputRef.current?.focus();
}, 100);
return () => clearTimeout(timer);
}
}, [view]);
// Reset modal state on open/close
useEffect(() => {
if (!isOpen) {
setView("quick");
setPhoneNumber("");
setOtpCode("");
setIsLoading(false);
setCountdown(0);
}
}, [isOpen]);
// Cooldown countdown timer
useEffect(() => {
if (countdown > 0) {
const timer = setTimeout(() => setCountdown(countdown - 1), 1000);
return () => clearTimeout(timer);
}
}, [countdown]);
const handleQuickLogin = async (targetRole: UserRole) => {
if (targetRole === "User_Guest") {
setRole("User_Guest");
setLoggedIn(false);
toast.success("به عنوان کاربر مهمان وارد شدید.");
onClose();
return;
}
setIsLoading(true);
const testPhone = targetRole === "User_PetOwner" ? "09121111111" : "09122222222";
try {
// Step 1: Send OTP to test phone
const sendRes = await authService.sendOtp(testPhone);
const code = (sendRes as any).code;
if (!code) {
throw new Error("کد تایید تستی تولید نشد");
}
// Step 2: Verify OTP
const verifyRes = await authService.verifyOtp(testPhone, code);
if (verifyRes.success) {
// Force state sync and fetch profile
setRole(targetRole);
await fetchProfile();
toast.success(`ورود سریع موفق! در نقش ${targetRole === "User_Partner" ? 'همکار' : 'صاحب پت'} وارد شدید.`);
onClose();
}
} catch (err: any) {
toast.error(`خطا در ورود سریع: ${err.message}`);
} finally {
setIsLoading(false);
}
};
const handleSendOtp = async (e: React.FormEvent) => {
e.preventDefault();
const cleanPhone = phoneNumber.trim();
if (!/^09\d{9}$/.test(cleanPhone)) {
toast.error("شماره موبایل نامعتبر است");
return;
}
setIsLoading(true);
try {
const res = await authService.sendOtp(cleanPhone);
if ((res as any).code) {
toast.info(`کد تایید (تست): ${(res as any).code}`, { duration: 10000 });
} else {
toast.success("کد تایید پیامک شد");
}
setView("otp");
setCountdown(120);
} catch (err: any) {
toast.error(err.message || "خطا در ارسال کد تایید");
} finally {
setIsLoading(false);
}
};
const handleVerifyOtp = async (e: React.FormEvent) => {
e.preventDefault();
const cleanCode = otpCode.trim();
if (cleanCode.length !== 5) {
toast.error("کد باید ۵ رقم باشد");
return;
}
setIsLoading(true);
try {
const response = await authService.verifyOtp(phoneNumber.trim(), cleanCode);
if (response.success) {
await fetchProfile();
toast.success("ورود موفقیت‌آمیز بود");
onClose();
}
} catch (err: any) {
toast.error(err.message || "کد تایید نامعتبر است");
} finally {
setIsLoading(false);
}
};
const handleResendOtp = async () => {
if (countdown > 0) return;
setIsLoading(true);
try {
await authService.sendOtp(phoneNumber.trim());
toast.success("کد تایید جدید ارسال شد");
setCountdown(120);
} catch (err: any) {
toast.error(err.message || "خطا در ارسال مجدد کد");
} finally {
setIsLoading(false);
}
};
return (
<AnimatePresence>
{isOpen && (
<>
{/* Backdrop */}
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
@@ -31,63 +158,225 @@ export default function AuthModal({ isOpen, onClose }: AuthModalProps) {
className="fixed inset-0 bg-black/60 backdrop-blur-sm z-[60]"
onClick={onClose}
/>
{/* Modal content */}
<motion.div
initial={{ opacity: 0, scale: 0.9, y: 20 }}
animate={{ opacity: 1, scale: 1, y: 0 }}
exit={{ opacity: 0, scale: 0.9, y: 20 }}
className="fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-full max-w-md bg-white rounded-[2.5rem] shadow-2xl z-[70] overflow-hidden border border-medical-gray-100"
className="fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-full max-w-md bg-white rounded-[2.5rem] shadow-2xl z-[70] overflow-hidden border border-medical-gray-100 font-vazir"
dir="rtl"
>
{/* Top highlight bar */}
<div className="absolute top-0 left-0 w-full h-2 bg-gradient-to-r from-canina-blue to-indigo-500" />
<div className="p-8 relative">
{/* Close Button */}
<button
onClick={onClose}
className="absolute top-6 left-6 p-2 rounded-full hover:bg-medical-gray-50 text-medical-gray-400 transition-colors"
className="absolute top-6 left-6 p-2 rounded-full hover:bg-medical-gray-50 text-medical-gray-400 hover:text-medical-gray-600 transition-colors"
>
<X className="w-6 h-6" />
</button>
<div className="flex flex-col items-center text-center mb-10 pt-4">
<div className="w-20 h-20 bg-canina-blue/10 rounded-3xl flex items-center justify-center mb-6">
{/* Title Header */}
<div className="flex flex-col items-center text-center mb-8 pt-4">
<div className="w-20 h-20 bg-canina-blue/10 rounded-3xl flex items-center justify-center mb-4 shadow-inner">
<ShieldCheck className="w-10 h-10 text-canina-blue" />
</div>
<h2 className="text-3xl font-black text-medical-gray-900 font-vazir mb-3">ورود به دنیای کانی‌نا</h2>
<p className="text-medical-gray-500 font-medium font-vazir max-w-[280px]">
برای دسترسی به پرونده سلامت و تخفیفات اختصاصی وارد شوید
<h2 className="text-3xl font-black text-medical-gray-900 mb-2 italic">
ورود به دنیای کانی‌نا
</h2>
<p className="text-medical-gray-500 text-sm font-bold max-w-[280px]">
{view === "otp"
? `کد تایید ارسال شده به شماره ${toPersian(phoneNumber)} را وارد کنید`
: "برای دسترسی به پرونده سلامت و سفارشات وارد شوید"}
</p>
</div>
<div className="space-y-4">
<button className="w-full bg-medical-gray-50 border border-medical-gray-100 rounded-2xl p-4 flex items-center justify-between group hover:border-canina-blue transition-all">
<span className="font-bold text-sm text-medical-gray-600 font-vazir">ورود با شماره موبایل</span>
<div className="w-8 h-8 rounded-full bg-white flex items-center justify-center shadow-sm text-canina-blue">→</div>
</button>
</div>
{/* Content Panel */}
<AnimatePresence mode="wait">
{view === "quick" && (
<motion.div
key="quick-view"
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -10 }}
className="space-y-6"
>
<button
onClick={() => setView("phone")}
className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-2xl p-5 flex items-center justify-between group hover:border-canina-blue transition-all cursor-pointer shadow-sm"
>
<div className="flex items-center gap-3">
<Phone className="w-5 h-5 text-canina-blue" />
<span className="font-black text-sm text-medical-gray-700">ورود با شماره موبایل</span>
</div>
<div className="w-8 h-8 rounded-xl bg-white border border-medical-gray-100 flex items-center justify-center shadow-sm text-canina-blue group-hover:bg-canina-blue group-hover:text-white transition-all">←</div>
</button>
<div className="mt-12 pt-8 border-t border-medical-gray-50">
<p className="text-[10px] font-black text-medical-gray-300 uppercase tracking-widest text-center mb-6 font-vazir">ورود سریع (جهت تست)</p>
<div className="grid grid-cols-3 gap-3">
<button
onClick={() => handleQuickLogin("User_Guest")}
className="flex flex-col items-center gap-2 p-3 rounded-2xl border border-medical-gray-100 hover:bg-medical-gray-50 transition-all group"
<div className="pt-6 border-t border-medical-gray-100">
<p className="text-[10px] font-black text-medical-gray-400 uppercase tracking-widest text-center mb-4">ورود سریع تستی (با دیتابیس واقعی)</p>
<div className="grid grid-cols-3 gap-3">
<button
onClick={() => handleQuickLogin("User_Guest")}
disabled={isLoading}
className="flex flex-col items-center gap-2 p-3 rounded-2xl border border-medical-gray-100 hover:bg-medical-gray-50 transition-all group cursor-pointer disabled:opacity-50"
>
<User className="w-6 h-6 text-medical-gray-400 group-hover:text-canina-blue" />
<span className="text-[10px] font-black text-medical-gray-700">مهمان</span>
</button>
<button
onClick={() => handleQuickLogin("User_PetOwner")}
disabled={isLoading}
className="flex flex-col items-center gap-2 p-3 rounded-2xl border border-medical-gray-100 hover:bg-medical-gray-50 transition-all group cursor-pointer disabled:opacity-50"
>
{isLoading ? (
<RefreshCw className="w-6 h-6 text-canina-blue animate-spin" />
) : (
<Heart className="w-6 h-6 text-medical-gray-400 group-hover:text-canina-blue" />
)}
<span className="text-[10px] font-black text-medical-gray-700">صاحب پت</span>
</button>
<button
onClick={() => handleQuickLogin("User_Partner")}
disabled={isLoading}
className="flex flex-col items-center gap-2 p-3 rounded-2xl border border-medical-gray-100 hover:bg-medical-gray-50 transition-all group cursor-pointer disabled:opacity-50"
>
{isLoading ? (
<RefreshCw className="w-6 h-6 text-canina-blue animate-spin" />
) : (
<Building2 className="w-6 h-6 text-medical-gray-400 group-hover:text-canina-blue" />
)}
<span className="text-[10px] font-black text-medical-gray-700">همکار</span>
</button>
</div>
</div>
</motion.div>
)}
{view === "phone" && (
<motion.form
key="phone-view"
initial={{ opacity: 0, x: 20 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: -20 }}
onSubmit={handleSendOtp}
className="space-y-6"
>
<User className="w-6 h-6 text-medical-gray-400 group-hover:text-canina-blue" />
<span className="text-[10px] font-bold font-vazir">مهمان</span>
</button>
<button
onClick={() => handleQuickLogin("User_PetOwner")}
className="flex flex-col items-center gap-2 p-3 rounded-2xl border border-medical-gray-100 hover:bg-medical-gray-50 transition-all group"
<div className="space-y-2">
<div className="flex justify-between items-center">
<label className="text-[10px] font-black text-medical-gray-400 uppercase tracking-widest">شماره موبایل</label>
<button
type="button"
onClick={() => setView("quick")}
className="text-[10px] font-black text-canina-blue hover:underline"
>
برگشت به ورود سریع
</button>
</div>
<div className="relative">
<Phone className="absolute right-4 top-1/2 -translate-y-1/2 w-5 h-5 text-medical-gray-400" />
<input
type="tel"
maxLength={11}
placeholder="مثال: ۰۹۱۲۳۴۵۶۷۸۹"
value={phoneNumber}
onChange={(e) => setPhoneNumber(e.target.value.replace(/[^0-9]/g, ''))}
disabled={isLoading}
className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-2xl py-4 pr-12 pl-4 focus:ring-2 focus:ring-canina-blue/20 outline-none font-bold text-lg text-left tracking-widest"
/>
</div>
</div>
<button
type="submit"
disabled={isLoading || phoneNumber.length < 11}
className="w-full py-5 bg-canina-blue text-white rounded-2xl font-black text-xl hover:bg-indigo-700 disabled:opacity-50 transition-all shadow-xl shadow-canina-blue/20 flex items-center justify-center gap-3 cursor-pointer"
>
{isLoading ? (
<RefreshCw className="w-6 h-6 animate-spin" />
) : (
<>
<LogIn className="w-6 h-6" />
ارسال کد تایید
</>
)}
</button>
</motion.form>
)}
{view === "otp" && (
<motion.form
key="otp-view"
initial={{ opacity: 0, x: 20 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: -20 }}
onSubmit={handleVerifyOtp}
className="space-y-6"
>
<Heart className="w-6 h-6 text-medical-gray-400 group-hover:text-canina-blue" />
<span className="text-[10px] font-bold font-vazir">صاحب پت</span>
</button>
<button
onClick={() => handleQuickLogin("User_Partner")}
className="flex flex-col items-center gap-2 p-3 rounded-2xl border border-medical-gray-100 hover:bg-medical-gray-50 transition-all group"
>
<Building2 className="w-6 h-6 text-medical-gray-400 group-hover:text-canina-blue" />
<span className="text-[10px] font-bold font-vazir">همکار</span>
</button>
</div>
</div>
<div className="space-y-2">
<div className="flex justify-between items-center">
<label className="text-[10px] font-black text-medical-gray-400 uppercase tracking-widest">کد تایید پیامکی</label>
<button
type="button"
onClick={() => setView("phone")}
className="text-[10px] font-black text-canina-blue flex items-center gap-1 hover:underline"
>
<ArrowRight className="w-3 h-3" />
تغییر شماره
</button>
</div>
<div className="relative">
<Key className="absolute right-4 top-1/2 -translate-y-1/2 w-5 h-5 text-medical-gray-400" />
<input
ref={otpInputRef}
type="text"
maxLength={5}
placeholder="کد ۵ رقمی"
value={otpCode}
onChange={(e) => setOtpCode(e.target.value.replace(/[^0-9]/g, ''))}
disabled={isLoading}
className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-2xl py-4 pr-12 pl-4 focus:ring-2 focus:ring-canina-blue/20 outline-none font-black text-2xl text-center tracking-[0.5em]"
/>
</div>
</div>
<div className="text-center">
{countdown > 0 ? (
<span className="text-xs font-bold text-medical-gray-400">
ارسال مجدد کد پس از {toPersian(countdown)} ثانیه
</span>
) : (
<button
type="button"
onClick={handleResendOtp}
disabled={isLoading}
className="text-xs font-black text-canina-blue hover:underline flex items-center gap-1.5 justify-center mx-auto"
>
<RefreshCw className="w-3.5 h-3.5" />
ارسال مجدد کد تایید
</button>
)}
</div>
<button
type="submit"
disabled={isLoading || otpCode.length < 5}
className="w-full py-5 bg-canina-blue text-white rounded-2xl font-black text-xl hover:bg-indigo-700 disabled:opacity-50 transition-all shadow-xl shadow-canina-blue/20 flex items-center justify-center gap-3 cursor-pointer"
>
{isLoading ? (
<RefreshCw className="w-6 h-6 animate-spin" />
) : (
<>
<LogIn className="w-6 h-6" />
تایید کد و ورود
</>
)}
</button>
</motion.form>
)}
</AnimatePresence>
</div>
</motion.div>
</>
+12 -9
View File
@@ -22,7 +22,7 @@ import { useUserStore } from "../store/userStore";
import { PRODUCTS } from "../data/products";
import { toast } from "sonner";
export default function CheckoutPage({ onBack, onComplete }: { onBack: () => void; onComplete: () => void }) {
export default function CheckoutPage({ onBack, onComplete }: { onBack: () => void; onComplete: (orderId: string) => void }) {
const { items, getTotal, getSubtotal, getDiscount, isSubscribed, charityDonation, setCharityDonation, addOrder, clearCart } = useCartStore();
const { getActivePet, updatePet } = usePetStore();
const { profile, updateProfile } = useUserStore();
@@ -44,13 +44,13 @@ export default function CheckoutPage({ onBack, onComplete }: { onBack: () => voi
}
};
const handleFinalize = () => {
const handleFinalize = async () => {
setLoading(true);
const activePet = getActivePet();
setTimeout(() => {
// 1. Register the order
addOrder({
try {
// 1. Register the order in the backend
const orderId = await addOrder({
items: [...items],
total: getTotal(),
charityDonation: charityDonation,
@@ -64,7 +64,7 @@ export default function CheckoutPage({ onBack, onComplete }: { onBack: () => voi
});
}
// 2. Update pet consumptions for the refill logic
// 3. Update pet consumptions for the refill logic
if (activePet) {
const newConsumptions = [...(activePet.consumptions || [])];
@@ -85,11 +85,14 @@ export default function CheckoutPage({ onBack, onComplete }: { onBack: () => voi
updatePet(activePet.id, { consumptions: newConsumptions });
}
setLoading(false);
clearCart();
onComplete();
onComplete(orderId);
toast.success("سفارش شما با موفقیت ثبت شد و به پرونده سلامت همدمتان اضافه شد!");
}, 2000);
} catch (err: any) {
toast.error(err.message || "خطا در ثبت سفارش. لطفاً مجدداً تلاش کنید.");
} finally {
setLoading(false);
}
};
if (items.length === 0) {
+25 -14
View File
@@ -2,6 +2,7 @@ import { motion, useMotionValue, useTransform, animate } from "motion/react";
import { ChevronLeft } from "lucide-react";
import { useEffect, useState } from "react";
import { toPersian } from "../lib/utils";
import { useSettingsStore } from "../store/settingsStore";
function StatCounter({ target }: { target: number }) {
const [displayValue, setDisplayValue] = useState(0);
@@ -59,6 +60,10 @@ function Typewriter({ text }: { text: string }) {
}
export default function Hero({ onProfileClick, onShopNavigate }: { onProfileClick?: () => void, onShopNavigate?: () => void }) {
const getText = useSettingsStore(state => state.getText);
const title = getText('hero_title', "تخصص آلمانی در خدمت\nسلامت پت‌های خانگی");
const titleParts = title.split('\n');
return (
<section className="relative overflow-hidden bg-white py-20 lg:py-32 border-b border-medical-gray-100">
{/* Background patterns */}
@@ -77,17 +82,23 @@ export default function Hero({ onProfileClick, onShopNavigate }: { onProfileClic
>
<div className="inline-flex items-center gap-2 px-3 py-1 bg-canina-blue/5 border border-canina-blue/10 rounded-full mb-6">
<span className="w-2 h-2 rounded-full bg-canina-blue animate-pulse" />
<span className="text-canina-blue text-xs font-bold uppercase tracking-widest leading-none">تخصص دارویی از آلمان</span>
<span className="text-canina-blue text-xs font-bold uppercase tracking-widest leading-none">{getText('hero_badge', "تخصص دارویی از آلمان")}</span>
</div>
<h1 className="text-4xl lg:text-7xl font-black text-medical-gray-900 leading-[1.1] mb-6">
تخصص آلمانی در خدمت <br />
<span className="text-canina-blue font-vazir">سلامت پت‌های خانگی</span>
{titleParts[0]} <br />
{titleParts[1] && <span className="text-canina-blue font-vazir">{titleParts[1]}</span>}
</h1>
<p className="text-lg lg:text-xl text-medical-gray-600 mb-10 max-w-2xl mx-auto lg:mx-0 leading-relaxed font-vazir">
بیش از <span className="font-bold text-canina-blue">۴۰ سال</span> تجربه نوآورانه در تولید مکمل‌های درمانی با بالاترین استاندارد کیفی «گرید دارویی اختصاصی». راهکار هوشمند برای هر نیاز بالینی.
</p>
<p
className="text-lg lg:text-xl text-medical-gray-600 mb-10 max-w-2xl mx-auto lg:mx-0 leading-relaxed font-vazir animate-fade-in"
dangerouslySetInnerHTML={{
__html: getText(
'hero_desc',
'بیش از <span className="font-bold text-canina-blue">۴۰ سال</span> تجربه نوآورانه در تولید مکمل‌های درمانی با بالاترین استاندارد کیفی «گرید دارویی اختصاصی». راهکار هوشمند برای هر نیاز بالینی.'
)
}}
/>
<div className="flex flex-wrap justify-center lg:justify-start gap-4">
<button
@@ -99,14 +110,14 @@ export default function Hero({ onProfileClick, onShopNavigate }: { onProfileClic
}}
className="bg-medical-gray-900 text-white px-10 py-5 rounded-full font-bold text-lg hover:bg-canina-blue hover:shadow-2xl transition-all flex items-center gap-2 group font-vazir"
>
دستیار سلامت پت
{getText('hero_btn_advisor', "دستیار سلامت پت")}
<ChevronLeft className="w-5 h-5 group-hover:-translate-x-1 transition-transform" />
</button>
<button
onClick={onShopNavigate}
className="bg-white border-2 border-medical-gray-200 text-medical-gray-700 px-10 py-5 rounded-full font-bold text-lg hover:border-canina-blue hover:text-canina-blue transition-all font-vazir"
>
مشاهده محصولات
{getText('hero_btn_products', "مشاهده محصولات")}
</button>
</div>
</motion.div>
@@ -119,11 +130,11 @@ export default function Hero({ onProfileClick, onShopNavigate }: { onProfileClic
className="grid grid-cols-3 gap-8 mt-16 pt-8 border-t border-medical-gray-100"
>
<div className="flex flex-col items-center lg:items-end">
<Typewriter text="۱۹۸۴ سال تأسیس" />
<Typewriter text={getText('hero_stat_founded', "۱۹۸۴ سال تأسیس")} />
</div>
<div className="flex flex-col items-center lg:items-end">
<StatCounter target={40} />
<div className="text-xs text-medical-gray-500 font-bold uppercase tracking-tight mt-3 font-vazir">نمایندگی فعال</div>
<div className="text-xs text-medical-gray-500 font-bold uppercase tracking-tight mt-3 font-vazir">{getText('hero_stat_agencies', "نمایندگی فعال")}</div>
</div>
<div className="flex flex-col items-center lg:items-end">
<div className="relative overflow-hidden group">
@@ -139,7 +150,7 @@ export default function Hero({ onProfileClick, onShopNavigate }: { onProfileClic
className="absolute inset-0 bg-gradient-to-r from-transparent via-white/40 to-transparent skew-x-12 z-20 pointer-events-none"
/>
</div>
<div className="text-xs text-medical-gray-500 font-bold uppercase tracking-tight mt-3 font-vazir">فرمول آلمانی</div>
<div className="text-xs text-medical-gray-500 font-bold uppercase tracking-tight mt-3 font-vazir">{getText('hero_stat_german_formula', "فرمول آلمانی")}</div>
</div>
</motion.div>
</div>
@@ -160,8 +171,8 @@ export default function Hero({ onProfileClick, onShopNavigate }: { onProfileClic
referrerPolicy="no-referrer"
/>
<div className="absolute bottom-0 left-0 right-0 p-8 bg-gradient-to-t from-black/80 to-transparent text-white text-right">
<div className="text-sm font-medium mb-1 opacity-80 uppercase tracking-widest text-[10px]">سرآمد علمی در پزشکی پت‌ها</div>
<div className="text-xl font-bold italic tracking-tighter">مکمل‌های تایید شده دامپزشکی</div>
<div className="text-sm font-medium mb-1 opacity-80 uppercase tracking-widest text-[10px]">{getText('hero_image_badge', "سرآمد علمی در پزشکی پت‌ها")}</div>
<div className="text-xl font-bold italic tracking-tighter">{getText('hero_image_title', "مکمل‌های تایید شده دامپزشکی")}</div>
</div>
</div>
</motion.div>
@@ -174,7 +185,7 @@ export default function Hero({ onProfileClick, onShopNavigate }: { onProfileClic
>
<div className="flex flex-col items-center">
<span className="text-2xl lg:text-3xl font-black text-canina-blue leading-none tracking-tighter">DE</span>
<span className="text-[8px] lg:text-[10px] font-bold text-medical-gray-500 uppercase tracking-widest mt-1">استاندارد کیفی آلمان</span>
<span className="text-[8px] lg:text-[10px] font-bold text-medical-gray-500 uppercase tracking-widest mt-1">{getText('hero_quality_standard', "استاندارد کیفی آلمان")}</span>
</div>
</motion.div>
</div>
+17 -1
View File
@@ -1,8 +1,24 @@
import { useMemo } from "react";
import { INGREDIENTS_WIKI, PRODUCTS, Product } from "../data/products";
import { motion } from "motion/react";
import { FlaskConical, CheckCircle2, ChevronRight, ChevronLeft, Beaker } from "lucide-react";
import { useSettingsStore } from "../store/settingsStore";
export default function IngredientWiki({ onProductClick, onBack }: { onProductClick: (p: Product) => void, onBack?: () => void }) {
const texts = useSettingsStore(state => state.texts);
const ingredientsWiki = useMemo(() => {
const jsonStr = texts['ingredients_wiki'];
if (jsonStr) {
try {
return JSON.parse(jsonStr) as typeof INGREDIENTS_WIKI;
} catch (e) {
console.error("Failed to parse ingredients_wiki from DB setting:", e);
}
}
return INGREDIENTS_WIKI;
}, [texts]);
return (
<div className="bg-white py-12 px-4 overflow-hidden font-vazir" dir="rtl">
<div className="max-w-7xl mx-auto">
@@ -45,7 +61,7 @@ export default function IngredientWiki({ onProductClick, onBack }: { onProductCl
</div>
<div className="space-y-32">
{INGREDIENTS_WIKI.map((ing, idx) => {
{ingredientsWiki.map((ing, idx) => {
const hasIngredient = PRODUCTS.filter(p =>
p.main_ingredients.some(mi => mi.toLowerCase().includes(ing.name.toLowerCase())) ||
p.main_ingredients.some(mi => mi.toLowerCase().includes(ing.id.replace('-', ' ')))
+235 -54
View File
@@ -1,6 +1,10 @@
import React, { useState } from "react";
import React, { useState, useEffect, useRef } from "react";
import { motion, AnimatePresence } from "motion/react";
import { X, ShieldCheck, Mail, Lock, LogIn, UserPlus } from "lucide-react";
import { X, ShieldCheck, Phone, Key, LogIn, ArrowRight, RefreshCw } from "lucide-react";
import { authService } from "../services/authService";
import { useUserStore } from "../store/userStore";
import { toast } from "sonner";
import { toPersian } from "../lib/utils";
interface LoginModalProps {
isOpen: boolean;
@@ -11,12 +15,110 @@ interface LoginModalProps {
}
export default function LoginModal({ isOpen, onClose, onLogin, petName, isAdvisorContext }: LoginModalProps) {
const [view, setView] = useState<"login" | "register">("login");
const [step, setStep] = useState<"phone" | "otp">("phone");
const [phoneNumber, setPhoneNumber] = useState("");
const [otpCode, setOtpCode] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [countdown, setCountdown] = useState(0);
const { fetchProfile } = useUserStore();
const otpInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
if (step === "otp") {
const timer = setTimeout(() => {
otpInputRef.current?.focus();
}, 100);
return () => clearTimeout(timer);
}
}, [step]);
// Reset modal state when closed or opened
useEffect(() => {
if (!isOpen) {
setStep("phone");
setPhoneNumber("");
setOtpCode("");
setIsLoading(false);
setCountdown(0);
}
}, [isOpen]);
// Countdown timer for OTP resend
useEffect(() => {
if (countdown > 0) {
const timer = setTimeout(() => setCountdown(countdown - 1), 1000);
return () => clearTimeout(timer);
}
}, [countdown]);
const handleSendOtp = async (e: React.FormEvent) => {
e.preventDefault();
const cleanPhone = phoneNumber.trim();
if (!/^09\d{9}$/.test(cleanPhone)) {
toast.error("شماره موبایل باید با ۰۹ شروع شده و ۱۱ رقم باشد");
return;
}
setIsLoading(true);
try {
const res = await authService.sendOtp(cleanPhone);
if ((res as any).code) {
toast.info(`کد تایید (تست): ${(res as any).code}`, { duration: 10000 });
} else {
toast.success("کد تایید پیامک شد");
}
setStep("otp");
setCountdown(120); // 2 minutes cooldown
} catch (err: any) {
toast.error(err.message || "خطا در ارسال کد تایید");
} finally {
setIsLoading(false);
}
};
const handleVerifyOtp = async (e: React.FormEvent) => {
e.preventDefault();
const cleanCode = otpCode.trim();
if (cleanCode.length !== 5) {
toast.error("کد تایید باید ۵ رقم باشد");
return;
}
setIsLoading(true);
try {
const response = await authService.verifyOtp(phoneNumber.trim(), cleanCode);
if (response.success) {
await fetchProfile();
toast.success("ورود با موفقیت انجام شد");
onLogin();
onClose();
}
} catch (err: any) {
toast.error(err.message || "کد تایید اشتباه است");
} finally {
setIsLoading(false);
}
};
const handleResendOtp = async () => {
if (countdown > 0) return;
setIsLoading(true);
try {
await authService.sendOtp(phoneNumber.trim());
toast.success("کد تایید جدید ارسال شد");
setCountdown(120);
} catch (err: any) {
toast.error(err.message || "خطا در ارسال مجدد کد تایید");
} finally {
setIsLoading(false);
}
};
return (
<AnimatePresence>
{isOpen && (
<div className="fixed inset-0 z-[200] flex items-center justify-center p-4">
{/* Backdrop */}
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
@@ -24,80 +126,159 @@ export default function LoginModal({ isOpen, onClose, onLogin, petName, isAdviso
onClick={onClose}
className="absolute inset-0 bg-medical-gray-900/60 backdrop-blur-md"
/>
{/* Modal Container */}
<motion.div
initial={{ opacity: 0, scale: 0.9, y: 20 }}
animate={{ opacity: 1, scale: 1, y: 0 }}
exit={{ opacity: 0, scale: 0.9, y: 20 }}
className="bg-white w-full max-w-md rounded-[3.5rem] p-10 relative z-10 shadow-2xl overflow-hidden font-vazir"
className="bg-white w-full max-w-md rounded-[3.5rem] p-10 relative z-10 shadow-2xl overflow-hidden font-vazir border border-medical-gray-100"
dir="rtl"
>
<div className="absolute top-0 left-0 w-full h-2 bg-canina-blue" />
{/* Top color indicator */}
<div className="absolute top-0 left-0 w-full h-2 bg-gradient-to-r from-canina-blue to-indigo-500" />
{/* Close Button */}
<button
onClick={onClose}
className="absolute top-8 left-8 text-medical-gray-400 hover:text-medical-gray-600 transition-colors"
className="absolute top-8 left-8 p-2 rounded-full hover:bg-medical-gray-50 text-medical-gray-400 hover:text-medical-gray-600 transition-colors"
>
<X className="w-6 h-6" />
</button>
<div className="text-center mb-10">
<div className="w-20 h-20 bg-canina-blue/10 rounded-[2rem] flex items-center justify-center mx-auto mb-6">
{/* Header info */}
<div className="text-center mb-8">
<div className="w-20 h-20 bg-canina-blue/10 rounded-[2.5rem] flex items-center justify-center mx-auto mb-6 shadow-inner">
<ShieldCheck className="w-10 h-10 text-canina-blue" />
</div>
<h3 className="text-3xl font-black text-medical-gray-900 mb-2 italic">
{view === "login" ? "ورود به کانی‌نا" : "عضویت در کانی‌نا"}
ورود به کانی‌نا
</h3>
{isAdvisorContext ? (
<p className="text-medical-gray-500 font-bold leading-relaxed px-4">
تحلیل سلامت <span className="text-canina-blue">{petName || "همدم شما"}</span> آماده است! برای مشاهده رژیم مکمل پیشنهادی و ذخیره دائمی شناسنامه، وارد شوید.
<p className="text-medical-gray-500 font-bold leading-relaxed px-2 text-sm">
تحلیل سلامت <span className="text-canina-blue">{petName || "همدم شما"}</span> آماده است! برای مشاهده رژیم مکمل پیشنهادی و ذخیره شناسنامه، وارد شوید.
</p>
) : (
<p className="text-medical-gray-500 font-bold">برای دسترسی به پنل مدیریت سلامت، وارد شوید</p>
<p className="text-medical-gray-500 font-bold text-sm">برای دسترسی به پنل مدیریت سلامت، وارد شوید</p>
)}
</div>
<div className="space-y-4 mb-8">
<div className="relative">
<Mail className="absolute right-4 top-1/2 -translate-y-1/2 w-5 h-5 text-medical-gray-400" />
<input
type="email"
placeholder="ایمیل یا شماره موبایل"
className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-2xl py-4 pr-12 pl-4 focus:ring-2 focus:ring-canina-blue/20 outline-none font-bold"
/>
</div>
<div className="relative">
<Lock className="absolute right-4 top-1/2 -translate-y-1/2 w-5 h-5 text-medical-gray-400" />
<input
type="password"
placeholder="رمز عبور"
className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-2xl py-4 pr-12 pl-4 focus:ring-2 focus:ring-canina-blue/20 outline-none font-bold"
/>
</div>
{view === "login" && (
<div className="text-left">
<button className="text-xs font-black text-canina-blue hover:underline italic">رمز عبور را فراموش کرده‌اید؟</button>
</div>
)}
</div>
<button
onClick={onLogin}
className="w-full py-5 bg-canina-blue text-white rounded-2xl font-black text-xl hover:bg-indigo-700 transition-all shadow-xl shadow-canina-blue/20 flex items-center justify-center gap-3 mb-6"
>
{view === "login" ? <LogIn className="w-6 h-6" /> : <UserPlus className="w-6 h-6" />}
{view === "login" ? "ورود به حساب" : "ایجاد حساب کاربری"}
</button>
<div className="text-center">
<p className="text-xs text-medical-gray-400 font-bold">
{view === "login" ? "هنوز حساب ندارید؟" : "قبلاً ثبت‌نام کرده‌اید؟"}{' '}
<button
onClick={() => setView(view === "login" ? "register" : "login")}
className="text-canina-blue font-black hover:underline"
{/* Step-based Forms */}
<AnimatePresence mode="wait">
{step === "phone" ? (
<motion.form
key="phone-form"
initial={{ opacity: 0, x: 20 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: -20 }}
onSubmit={handleSendOtp}
className="space-y-6"
>
{view === "login" ? "عضویت رایگان" : "ورود"}
</button>
</p>
</div>
<div className="space-y-2">
<label className="text-[10px] font-black text-medical-gray-400 uppercase tracking-widest block">شماره موبایل</label>
<div className="relative">
<Phone className="absolute right-4 top-1/2 -translate-y-1/2 w-5 h-5 text-medical-gray-400" />
<input
type="tel"
maxLength={11}
placeholder="مثال: ۰۹۱۲۳۴۵۶۷۸۹"
value={phoneNumber}
onChange={(e) => setPhoneNumber(e.target.value.replace(/[^0-9]/g, ''))}
disabled={isLoading}
className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-2xl py-4 pr-12 pl-4 focus:ring-2 focus:ring-canina-blue/20 focus:border-canina-blue outline-none font-bold text-lg text-left tracking-widest"
/>
</div>
</div>
<button
type="submit"
disabled={isLoading || phoneNumber.length < 11}
className="w-full py-5 bg-canina-blue text-white rounded-2xl font-black text-xl hover:bg-indigo-700 disabled:opacity-50 disabled:cursor-not-allowed transition-all shadow-xl shadow-canina-blue/20 flex items-center justify-center gap-3 cursor-pointer"
>
{isLoading ? (
<RefreshCw className="w-6 h-6 animate-spin" />
) : (
<>
<LogIn className="w-6 h-6" />
ارسال کد تایید
</>
)}
</button>
</motion.form>
) : (
<motion.form
key="otp-form"
initial={{ opacity: 0, x: 20 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: -20 }}
onSubmit={handleVerifyOtp}
className="space-y-6"
>
<div className="space-y-2">
<div className="flex justify-between items-center">
<label className="text-[10px] font-black text-medical-gray-400 uppercase tracking-widest">کد تایید پیامکی</label>
<button
type="button"
onClick={() => setStep("phone")}
className="text-[10px] font-black text-canina-blue flex items-center gap-1 hover:underline"
>
<ArrowRight className="w-3 h-3" />
ویرایش شماره
</button>
</div>
<div className="relative">
<Key className="absolute right-4 top-1/2 -translate-y-1/2 w-5 h-5 text-medical-gray-400" />
<input
ref={otpInputRef}
type="text"
maxLength={5}
placeholder="کد ۵ رقمی"
value={otpCode}
onChange={(e) => setOtpCode(e.target.value.replace(/[^0-9]/g, ''))}
disabled={isLoading}
className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-2xl py-4 pr-12 pl-4 focus:ring-2 focus:ring-canina-blue/20 focus:border-canina-blue outline-none font-black text-2xl text-center tracking-[0.5em]"
/>
</div>
<p className="text-[10px] text-medical-gray-400 font-bold text-center mt-2">
کد تایید به شماره {toPersian(phoneNumber)} ارسال گردید.
</p>
</div>
<div className="flex justify-center">
{countdown > 0 ? (
<span className="text-xs font-bold text-medical-gray-400 font-vazir">
ارسال مجدد کد پس از {toPersian(countdown)} ثانیه
</span>
) : (
<button
type="button"
onClick={handleResendOtp}
disabled={isLoading}
className="text-xs font-black text-canina-blue hover:underline flex items-center gap-1.5"
>
<RefreshCw className="w-3.5 h-3.5" />
ارسال مجدد کد تایید
</button>
)}
</div>
<button
type="submit"
disabled={isLoading || otpCode.length < 5}
className="w-full py-5 bg-canina-blue text-white rounded-2xl font-black text-xl hover:bg-indigo-700 disabled:opacity-50 disabled:cursor-not-allowed transition-all shadow-xl shadow-canina-blue/20 flex items-center justify-center gap-3 cursor-pointer"
>
{isLoading ? (
<RefreshCw className="w-6 h-6 animate-spin" />
) : (
<>
<LogIn className="w-6 h-6" />
ورود و تایید حساب
</>
)}
</button>
</motion.form>
)}
</AnimatePresence>
</motion.div>
</div>
)}
+9 -1
View File
@@ -42,6 +42,7 @@ const ICON_MAP: Record<string, any> = {
import { toPersian, cn } from "../lib/utils";
import { Product, PRODUCTS } from "../data/products";
import { SCIENTIFIC_TERMS } from "../data/scientificTerms";
import { useSettingsStore } from "../store/settingsStore";
import { create } from "zustand";
import { useCartStore } from "../store/cartStore";
import { usePetStore } from "../store/usePetStore";
@@ -78,6 +79,13 @@ export default function ProductPage({ product, onBack, onProductClick, onWikiNav
const activePet = getActivePet();
const { petType, weight, setPetType, setWeight } = useCalculatorStore();
const { addItem } = useCartStore();
const scientificTerms = useSettingsStore(state => state.scientificTerms);
const termKeys = useMemo(() => {
return Array.from(new Set([
...Object.keys(scientificTerms),
...Object.keys(SCIENTIFIC_TERMS)
]));
}, [scientificTerms]);
// Re-hydrate product to ensure methods like calculateDosage exist
const fullProduct = useMemo(() => {
@@ -237,7 +245,7 @@ export default function ProductPage({ product, onBack, onProductClick, onWikiNav
<h4 className="text-xs font-black text-medical-gray-400 uppercase tracking-widest mb-6 font-vazir">مواد تشکیل‌دهنده برتر</h4>
<div className="flex flex-wrap gap-3">
{product.main_ingredients.map((ing, idx) => {
const termKey = Object.keys(SCIENTIFIC_TERMS).find(key => ing.includes(key));
const termKey = termKeys.find(key => ing.includes(key));
return (
<div key={idx} className="bg-medical-gray-50 border border-medical-gray-100 px-5 py-3 rounded-2xl flex items-center gap-3 group hover:border-canina-blue/30 transition-all">
<span className="text-sm font-bold text-medical-gray-700 font-vazir">
+15 -1
View File
@@ -1,5 +1,6 @@
import React, { useState } from "react";
import { motion, AnimatePresence } from "motion/react";
import { useSettingsStore } from "../store/settingsStore";
import {
Dog,
Cat,
@@ -36,6 +37,19 @@ const MEDICAL_OPTIONS = [
];
export default function SmartAdvisor({ onComplete }: SmartAdvisorProps) {
const texts = useSettingsStore(state => state.texts);
const medicalOptions = React.useMemo(() => {
const jsonStr = texts['medical_options'];
if (jsonStr) {
try {
return JSON.parse(jsonStr) as typeof MEDICAL_OPTIONS;
} catch (e) {
console.error("Failed to parse medical_options JSON:", e);
}
}
return MEDICAL_OPTIONS;
}, [texts]);
const [step, setStep] = useState(1);
// Step 1 Data
@@ -238,7 +252,7 @@ export default function SmartAdvisor({ onComplete }: SmartAdvisorProps) {
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{MEDICAL_OPTIONS.map((opt) => (
{medicalOptions.map((opt) => (
<button
key={opt.id}
onClick={() => {
+3 -1
View File
@@ -2,6 +2,7 @@ import React, { useState } from 'react';
import { motion, AnimatePresence } from 'motion/react';
import { Info, ExternalLink } from 'lucide-react';
import { SCIENTIFIC_TERMS } from '../data/scientificTerms';
import { useSettingsStore } from '../store/settingsStore';
interface TooltipProps {
termKey: string;
@@ -11,7 +12,8 @@ interface TooltipProps {
export default function Tooltip({ termKey, children, onWikiNavigate }: TooltipProps) {
const [isVisible, setIsVisible] = useState(false);
const termData = SCIENTIFIC_TERMS[termKey];
const scientificTerms = useSettingsStore(state => state.scientificTerms);
const termData = scientificTerms[termKey] || SCIENTIFIC_TERMS[termKey];
if (!termData) return <>{children}</>;
+178 -25
View File
@@ -5,6 +5,7 @@ import { OrderRowSkeleton } from "./Skeleton";
import { useUserStore, Address } from "../store/userStore";
import { useCartStore } from "../store/cartStore";
import { toPersian, cn } from "../lib/utils";
import { toast } from "sonner";
import OrderDetailsModal from "./OrderDetailsModal";
import AddressModal from "./AddressModal";
import DeleteConfirmModal from "./DeleteConfirmModal";
@@ -34,16 +35,59 @@ export default function UserDashboard({ onBack, onNavigate }: { onBack: () => vo
// Wallet State
const [isTopUpModalOpen, setIsTopUpModalOpen] = useState(false);
// Profile State
const [isEditing, setIsEditing] = useState(false);
const [isSavingProfile, setIsSavingProfile] = useState(false);
const [profileForm, setProfileForm] = useState({
firstName: profile.firstName || "",
lastName: profile.lastName || "",
email: profile.email || "",
mobile: profile.mobile || ""
});
// Sync profile data on change
React.useEffect(() => {
setProfileForm({
firstName: profile.firstName || "",
lastName: profile.lastName || "",
email: profile.email || "",
mobile: profile.mobile || ""
});
}, [profile]);
const handleSaveProfile = async (e: React.FormEvent) => {
e.preventDefault();
if (!isEditing) return;
setIsSavingProfile(true);
try {
await useUserStore.getState().updateProfile({
firstName: profileForm.firstName,
lastName: profileForm.lastName,
email: profileForm.email
});
setIsEditing(false);
toast.success("اطلاعات کاربری با موفقیت ویرایش شد");
} catch (err: any) {
toast.error(err.message || "خطا در ویرایش اطلاعات");
} finally {
setIsSavingProfile(false);
}
};
const handleLogout = () => {
logout();
onBack();
};
const handleSaveAddress = (addr: Address) => {
if (editingAddress) {
updateAddress(addr.id, addr);
} else {
addAddress(addr);
const handleSaveAddress = async (addr: Address) => {
try {
if (editingAddress) {
await updateAddress(addr.id, addr);
} else {
await addAddress(addr);
}
} catch (err) {
toast.error("خطا در ثبت آدرس");
}
setEditingAddress(null);
};
@@ -53,9 +97,14 @@ export default function UserDashboard({ onBack, onNavigate }: { onBack: () => vo
setIsDeleteModalOpen(true);
};
const handleConfirmDelete = () => {
const handleConfirmDelete = async () => {
if (addressToDelete) {
deleteAddress(addressToDelete.id);
try {
await deleteAddress(addressToDelete.id);
toast.success("آدرس با موفقیت حذف شد");
} catch (err) {
toast.error("خطا در حذف آدرس");
}
setAddressToDelete(null);
}
};
@@ -185,23 +234,120 @@ export default function UserDashboard({ onBack, onNavigate }: { onBack: () => vo
{activeTab === "profile" && (
<div>
<h3 className="text-2xl font-black text-medical-gray-900 mb-8 italic">اطلاعات فردی</h3>
<div className="grid md:grid-cols-2 gap-8">
<div className="space-y-2">
<label className="text-[10px] font-black text-medical-gray-400 uppercase tracking-widest block pr-4">نام</label>
<input type="text" readOnly value={profile.firstName} className="w-full bg-medical-gray-50 border border-medical-gray-100 p-4 rounded-2xl font-bold outline-none" />
</div>
<div className="space-y-2">
<label className="text-[10px] font-black text-medical-gray-400 uppercase tracking-widest block pr-4">نام خانوادگی</label>
<input type="text" readOnly value={profile.lastName} className="w-full bg-medical-gray-50 border border-medical-gray-100 p-4 rounded-2xl font-bold outline-none" />
</div>
<div className="space-y-2 md:col-span-2">
<label className="text-[10px] font-black text-medical-gray-400 uppercase tracking-widest block pr-4">ایمیل</label>
<input type="text" readOnly value={profile.email} className="w-full bg-medical-gray-50 border border-medical-gray-100 p-4 rounded-2xl font-bold outline-none" />
</div>
</div>
<button className="mt-12 bg-medical-gray-900 text-white px-10 py-4 rounded-2xl font-black hover:bg-canina-blue transition-all">
ویرایش اطلاعات
</button>
<form onSubmit={handleSaveProfile} className="space-y-8">
<div className="grid md:grid-cols-2 gap-8">
<div className="space-y-2">
<label htmlFor="firstName" className="text-[10px] font-black text-medical-gray-400 uppercase tracking-widest block pr-4">نام</label>
<input
type="text"
id="firstName"
name="firstName"
autoComplete="given-name"
required
readOnly={!isEditing}
value={isEditing ? profileForm.firstName : profile.firstName}
onChange={e => setProfileForm({ ...profileForm, firstName: e.target.value })}
className={cn(
"w-full border p-4 rounded-2xl font-bold outline-none transition-all",
isEditing
? "bg-white border-canina-blue/30 focus:ring-2 focus:ring-canina-blue/20"
: "bg-medical-gray-50 border-medical-gray-100"
)}
/>
</div>
<div className="space-y-2">
<label htmlFor="lastName" className="text-[10px] font-black text-medical-gray-400 uppercase tracking-widest block pr-4">نام خانوادگی</label>
<input
type="text"
id="lastName"
name="lastName"
autoComplete="family-name"
required
readOnly={!isEditing}
value={isEditing ? profileForm.lastName : profile.lastName}
onChange={e => setProfileForm({ ...profileForm, lastName: e.target.value })}
className={cn(
"w-full border p-4 rounded-2xl font-bold outline-none transition-all",
isEditing
? "bg-white border-canina-blue/30 focus:ring-2 focus:ring-canina-blue/20"
: "bg-medical-gray-50 border-medical-gray-100"
)}
/>
</div>
<div className="space-y-2">
<label htmlFor="email" className="text-[10px] font-black text-medical-gray-400 uppercase tracking-widest block pr-4">ایمیل</label>
<input
type="email"
id="email"
name="email"
autoComplete="email"
required
readOnly={!isEditing}
value={isEditing ? profileForm.email : profile.email}
onChange={e => setProfileForm({ ...profileForm, email: e.target.value })}
className={cn(
"w-full border p-4 rounded-2xl font-bold outline-none transition-all text-left",
isEditing
? "bg-white border-canina-blue/30 focus:ring-2 focus:ring-canina-blue/20"
: "bg-medical-gray-50 border-medical-gray-100"
)}
dir="ltr"
/>
</div>
<div className="space-y-2">
<label htmlFor="mobile" className="text-[10px] font-black text-medical-gray-400 uppercase tracking-widest block pr-4">شماره موبایل</label>
<input
type="tel"
id="mobile"
name="mobile"
autoComplete="tel"
readOnly
disabled
value={toPersian(profile.mobile || "")}
className="w-full bg-medical-gray-50 border border-medical-gray-100 p-4 rounded-2xl font-bold outline-none text-left opacity-75 cursor-not-allowed"
dir="ltr"
/>
</div>
</div>
<div className="flex gap-4 mt-8">
{isEditing ? (
<>
<button
type="submit"
disabled={isSavingProfile}
className="bg-canina-blue text-white px-10 py-4 rounded-2xl font-black hover:bg-indigo-700 transition-all flex items-center gap-2 disabled:opacity-50"
>
{isSavingProfile && <span className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />}
ذخیره تغییرات
</button>
<button
type="button"
onClick={() => {
setProfileForm({
firstName: profile.firstName || "",
lastName: profile.lastName || "",
email: profile.email || "",
mobile: profile.mobile || ""
});
setIsEditing(false);
}}
className="bg-medical-gray-50 text-medical-gray-500 border border-medical-gray-200 px-10 py-4 rounded-2xl font-black hover:bg-medical-gray-100 transition-all"
>
انصراف
</button>
</>
) : (
<button
type="button"
onClick={() => setIsEditing(true)}
className="bg-medical-gray-900 text-white px-10 py-4 rounded-2xl font-black hover:bg-canina-blue transition-all"
>
ویرایش اطلاعات
</button>
)}
</div>
</form>
</div>
)}
@@ -338,7 +484,14 @@ export default function UserDashboard({ onBack, onNavigate }: { onBack: () => vo
</div>
{!addr.isDefault && (
<button
onClick={() => setDefaultAddress(addr.id)}
onClick={async () => {
try {
await setDefaultAddress(addr.id);
toast.success("آدرس پیش‌فرض با موفقیت تغییر کرد");
} catch (err) {
toast.error("خطا در تغییر آدرس پیش‌فرض");
}
}}
className="mr-auto text-[10px] font-black text-canina-blue hover:text-medical-gray-900 uppercase tracking-widest whitespace-nowrap"
>
انتخاب به عنوان پیش‌فرض
+23
View File
@@ -0,0 +1,23 @@
import axios from 'axios';
const api = axios.create({
baseURL: '/api',
timeout: 10000,
headers: {
'Content-Type': 'application/json',
},
});
// Interceptor to add auth token in the future
api.interceptors.request.use(
(config) => {
const token = localStorage.getItem('accessToken');
if (token && config.headers) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => Promise.reject(error)
);
export default api;
+102
View File
@@ -0,0 +1,102 @@
import api from './api';
export interface User {
id: string;
firstName: string;
lastName: string;
email: string;
mobile: string | null;
role: string;
walletBalance: number;
charityDonationTotal: number;
createdAt: string;
updatedAt: string;
pets?: any[];
orders?: any[];
}
export interface AuthResponse {
success: boolean;
data: {
user: User;
accessToken: string;
};
}
export class AuthService {
private static instance: AuthService;
private constructor() {}
public static getInstance(): AuthService {
if (!AuthService.instance) {
AuthService.instance = new AuthService();
}
return AuthService.instance;
}
/**
* Send SMS verification code (OTP)
*/
public async sendOtp(phoneNumber: string): Promise<{ success: boolean; message: string }> {
try {
const response = await api.post('/auth/send-otp', { phoneNumber });
return response.data;
} catch (error: any) {
const message = error.response?.data?.message || 'خطا در ارسال کد تایید';
throw new Error(Array.isArray(message) ? message[0] : message);
}
}
/**
* Verify SMS verification code and login/register
*/
public async verifyOtp(phoneNumber: string, code: string): Promise<AuthResponse> {
try {
const response = await api.post('/auth/verify-otp', { phoneNumber, code });
const { data } = response.data;
if (data?.accessToken) {
localStorage.setItem('accessToken', data.accessToken);
}
return response.data;
} catch (error: any) {
const message = error.response?.data?.message || 'کد تایید نامعتبر است';
throw new Error(Array.isArray(message) ? message[0] : message);
}
}
/**
* Get current user profile
*/
public async getProfile(): Promise<User> {
try {
const response = await api.get('/users/profile');
return response.data;
} catch (error: any) {
const message = error.response?.data?.message || 'خطا در دریافت اطلاعات کاربری';
throw new Error(Array.isArray(message) ? message[0] : message);
}
}
/**
* Update current user profile
*/
public async updateProfile(profileData: Partial<User>): Promise<User> {
try {
const response = await api.patch('/users/profile', profileData);
return response.data;
} catch (error: any) {
const message = error.response?.data?.message || 'خطا در ویرایش اطلاعات کاربری';
throw new Error(Array.isArray(message) ? message[0] : message);
}
}
/**
* Logout user and clear tokens
*/
public logout(): void {
localStorage.removeItem('accessToken');
}
}
export const authService = AuthService.getInstance();
+79
View File
@@ -0,0 +1,79 @@
import api from './api';
import { CartItem } from '../store/cartStore';
export interface OrderItem {
id: string;
orderId: string;
productId: string | null;
quantity: number;
product?: any;
}
export interface Order {
id: string;
userId: string;
couponId: string | null;
totalAmount: number;
charityDonation: number;
status: string;
trackingNumber: string | null;
createdAt: string;
orderItems: OrderItem[];
}
export class OrderService {
private static instance: OrderService;
private constructor() {}
public static getInstance(): OrderService {
if (!OrderService.instance) {
OrderService.instance = new OrderService();
}
return OrderService.instance;
}
/**
* Create a new order on the backend
*/
public async createOrder(orderData: {
petId?: string;
items: { productId: string; quantity: number }[];
}): Promise<Order> {
try {
const response = await api.post('/orders', orderData);
return response.data;
} catch (error: any) {
const message = error.response?.data?.message || 'خطا در ثبت سفارش';
throw new Error(Array.isArray(message) ? message[0] : message);
}
}
/**
* Get all orders for the current user
*/
public async getUserOrders(): Promise<Order[]> {
try {
const response = await api.get('/orders');
return response.data;
} catch (error: any) {
const message = error.response?.data?.message || 'خطا در دریافت لیست سفارش‌ها';
throw new Error(Array.isArray(message) ? message[0] : message);
}
}
/**
* Get order details by ID
*/
public async getOrderById(id: string): Promise<Order> {
try {
const response = await api.get(`/orders/${id}`);
return response.data;
} catch (error: any) {
const message = error.response?.data?.message || 'خطا در دریافت جزئیات سفارش';
throw new Error(Array.isArray(message) ? message[0] : message);
}
}
}
export const orderService = OrderService.getInstance();
+75 -40
View File
@@ -1,3 +1,4 @@
import api from './api';
import { PRODUCTS, Product, PetType } from "../data/products";
export class ProductService {
@@ -12,59 +13,93 @@ export class ProductService {
return ProductService.instance;
}
/**
* Simulates an API call to get all products with optional filters
*/
private mapBackendToFrontend(data: any): Product {
// Find the local static product to inherit functions like calculateDosage
const local = PRODUCTS.find(p => p.artNo === data.artNo);
const safeParse = (val: any, fallback: any) => {
if (!val) return fallback;
if (typeof val === 'string') {
try { return JSON.parse(val); } catch (e) { return fallback; }
}
return val;
};
return {
id: data.id,
artNo: data.artNo,
name: data.name,
scientificTagline: data.scientificTagline,
description: data.description,
shortDescription: data.shortDescription,
price: data.priceDisplay || `${data.priceValue.toLocaleString('fa-IR')} تومان`,
priceValue: Number(data.priceValue),
category: data.category,
categorySlug: data.categorySlug,
unit: data.unit,
packageSize: data.packageSize,
dosage_logic: data.dosageLogic,
benefits: data.benefits,
suitableFor: data.suitableFor as PetType,
storage: data.storage,
specialBadge: data.specialBadge,
onSetOfAction: data.onSetOfAction,
optimisticTemplate: data.optimisticTemplate,
feedingAdvice: data.feedingAdvice,
image: data.image,
main_ingredients: data.ingredients?.map((i: any) => i.ingredient) || [],
symptoms: data.symptoms?.map((s: any) => s.symptom) || [],
keyBenefits: safeParse(data.keyBenefits, []),
expectedResults: safeParse(data.expectedResults, []),
benefitsList: safeParse(data.benefitsList, []),
faqs: safeParse(data.faqs, []),
analysis: safeParse(data.analysis, {}),
specialist: safeParse(data.specialist, null),
relatedProducts: safeParse(data.relatedProducts, []),
contraindications: safeParse(data.contraindications, []),
calculateDosage: local?.calculateDosage || (() => ({ quantity: 0, unit: '', description: '' }))
};
}
public async getProducts(filters?: {
category?: string;
petType?: PetType | "all";
query?: string;
}): Promise<Product[]> {
// TODO: [BACKEND_API] GET /api/products | Payload: { category?: string, petType?: string, query?: string } | Expected: Product[] | Errors: [500]
// Simulate network delay
await new Promise(resolve => setTimeout(resolve, 600));
const params = new URLSearchParams();
if (filters?.category && filters.category !== "all") params.append('category', filters.category);
if (filters?.petType && filters.petType !== "all") params.append('petType', filters.petType);
if (filters?.query) params.append('query', filters.query);
let filtered = [...PRODUCTS];
if (filters?.category && filters.category !== "all") {
const target = filters.category.trim().toLowerCase();
console.log("[ProductService] Filtering by Category (Input):", target);
filtered = filtered.filter(p => {
const catName = p.category.trim().toLowerCase();
const catSlug = (p.categorySlug || "").trim().toLowerCase();
const match = catName === target || catSlug === target;
if (match) {
console.log(`[ProductService] Found Match: ${p.name} (Cat: ${catName}, Slug: ${catSlug})`);
}
return match;
});
try {
const response = await api.get(`/products?${params.toString()}`);
return response.data.map((item: any) => this.mapBackendToFrontend(item));
} catch (error) {
console.error("[ProductService] Failed to fetch products:", error);
return [];
}
if (filters?.petType && filters.petType !== "all") {
filtered = filtered.filter(p => p.suitableFor === filters.petType || p.suitableFor === "هر دو");
}
if (filters?.query) {
const q = filters.query.toLowerCase();
filtered = filtered.filter(p =>
p.name.toLowerCase().includes(q) ||
p.description.toLowerCase().includes(q) ||
p.symptoms.some(s => s.toLowerCase().includes(q))
);
}
return filtered;
}
public async getProductById(id: string): Promise<Product | null> {
await new Promise(resolve => setTimeout(resolve, 300));
return PRODUCTS.find(p => p.id === id) || null;
try {
const response = await api.get(`/products/${id}`);
return this.mapBackendToFrontend(response.data);
} catch (error) {
console.error(`[ProductService] Failed to fetch product ${id}:`, error);
return null;
}
}
public async getFeaturedProducts(): Promise<Product[]> {
await new Promise(resolve => setTimeout(resolve, 400));
return PRODUCTS.slice(0, 4);
try {
const response = await api.get('/products');
return response.data.slice(0, 4).map((item: any) => this.mapBackendToFrontend(item));
} catch (error) {
console.error("[ProductService] Failed to fetch featured products:", error);
return [];
}
}
}
+46 -12
View File
@@ -1,6 +1,8 @@
import { create } from "zustand";
import { persist } from "zustand/middleware";
import { Product } from "../data/products";
import { orderService } from "../services/orderService";
export interface CartItem {
product: Product;
@@ -34,9 +36,10 @@ interface CartStore {
toggleSubscription: () => void;
setCharityDonation: (amount: number) => void;
applyCoupon: (code: string) => boolean;
addOrder: (order: Omit<Order, 'id' | 'date' | 'status' | 'trackingNumber'>) => string;
addOrder: (order: Omit<Order, 'id' | 'date' | 'status' | 'trackingNumber'>) => Promise<string>;
clearCart: () => void;
removeCoupon: () => void;
setOrders: (orders: any[]) => void;
getTotalItems: () => number;
getSubtotal: () => number;
getDiscount: () => number;
@@ -93,21 +96,52 @@ export const useCartStore = create<CartStore>()(
}
return false;
},
addOrder: (orderData) => {
// TODO: [BACKEND_API] POST /api/orders | Payload: Omit<Order, 'id' | 'date' | 'status' | 'trackingNumber'> | Expected: Order | Errors: [400, 401]
const id = `CN-${Math.floor(Math.random() * 90000) + 10000}`;
const newOrder: Order = {
...orderData,
id,
date: new Date().toISOString(),
status: 'processing',
trackingNumber: `IR-${Math.floor(Math.random() * 900000) + 100000}`
addOrder: async (orderData) => {
const payload = {
petId: orderData.petId,
items: orderData.items.map(i => ({
productId: i.product.id,
quantity: i.quantity
}))
};
set({ orders: [newOrder, ...get().orders] });
return id;
try {
const backendOrder = await orderService.createOrder(payload);
const newOrder: Order = {
...orderData,
id: backendOrder.id,
date: backendOrder.createdAt,
total: Number(backendOrder.totalAmount),
charityDonation: Number(backendOrder.charityDonation),
status: backendOrder.status as any,
trackingNumber: backendOrder.trackingNumber || `CN-${Math.floor(Math.random() * 90000) + 10000}`
};
set({ orders: [newOrder, ...get().orders] });
return backendOrder.id;
} catch (error: any) {
console.error("Order creation failed on backend:", error);
throw error;
}
},
clearCart: () => set({ items: [], coupon: null }),
removeCoupon: () => set({ coupon: null }),
setOrders: (backendOrders) => {
const mappedOrders: Order[] = backendOrders.map(bo => ({
id: bo.id,
date: bo.createdAt,
items: bo.orderItems?.map((oi: any) => ({
product: oi.product,
quantity: oi.quantity
})) || [],
total: Number(bo.totalAmount),
charityDonation: Number(bo.charityDonation),
status: bo.status,
trackingNumber: bo.trackingNumber || `CN-${Math.floor(Math.random() * 90000) + 10000}`
}));
set({ orders: mappedOrders });
},
getTotalItems: () => get().items.reduce((acc, item) => acc + item.quantity, 0),
getSubtotal: () => get().items.reduce((acc, item) => acc + item.product.priceValue * item.quantity, 0),
getDiscount: () => {
+59
View File
@@ -0,0 +1,59 @@
import { create } from "zustand";
import api from "../services/api";
export interface ScientificTerm {
key: string;
term: string;
definition: string;
wikiId: string;
}
interface SettingsStore {
texts: Record<string, string>;
scientificTerms: Record<string, ScientificTerm>;
isLoading: boolean;
fetchSettings: () => Promise<void>;
getText: (key: string, fallback: string) => string;
}
export const useSettingsStore = create<SettingsStore>()((set, get) => ({
texts: {},
scientificTerms: {},
isLoading: false,
fetchSettings: async () => {
set({ isLoading: true });
try {
const [textsRes, termsRes] = await Promise.all([
api.get('/settings/ui-texts'),
api.get('/settings/scientific-terms'),
]);
const textsObj: Record<string, string> = {};
if (Array.isArray(textsRes.data)) {
textsRes.data.forEach((item: { key: string; value: string }) => {
textsObj[item.key] = item.value;
});
}
const termsObj: Record<string, ScientificTerm> = {};
if (Array.isArray(termsRes.data)) {
termsRes.data.forEach((item: ScientificTerm) => {
termsObj[item.key] = item;
});
}
set({ texts: textsObj, scientificTerms: termsObj });
} catch (error) {
console.error("Failed to fetch settings/ui-texts:", error);
} finally {
set({ isLoading: false });
}
},
getText: (key, fallback) => {
const value = get().texts[key];
if (value === undefined || value === null) {
return fallback;
}
return value;
}
}));
+32
View File
@@ -51,6 +51,7 @@ interface PetStore {
addReminder: (petId: string, reminder: Omit<Reminder, "id" | "completedDates">) => void;
toggleReminder: (petId: string, reminderId: string, date: string) => void;
addHealthLog: (petId: string, log: Omit<HealthLog, "id" | "date">) => void;
setPets: (pets: any[]) => void;
}
export const usePetStore = create<PetStore>()(
@@ -176,6 +177,37 @@ export const usePetStore = create<PetStore>()(
)
}));
},
setPets: (backendPets) => {
const mappedPets: PetProfile[] = backendPets.map(bp => ({
id: bp.id,
name: bp.name,
type: bp.type as any,
breed: bp.breed,
age: Number(bp.age),
weight: Number(bp.weight),
activityLevel: bp.activityLevel as any,
medicalConditions: bp.medicalConditions?.map((mc: any) => mc.condition) || [],
image: bp.imageUrl || undefined,
reminders: bp.reminders?.map((r: any) => ({
id: r.id,
title: r.title,
time: r.time,
frequency: r.frequency as any,
productId: r.productId,
completedDates: r.completions?.map((c: any) => c.completedDate) || []
})) || [],
logs: bp.healthLogs?.map((hl: any) => ({
id: hl.id,
date: hl.loggedDate,
appetite: hl.appetite as any,
energy: hl.energy as any,
digestion: hl.digestion as any,
note: hl.note || undefined
})) || [],
consumptions: []
}));
set({ pets: mappedPets, activePetId: get().activePetId && mappedPets.some(p => p.id === get().activePetId) ? get().activePetId : (mappedPets[0]?.id || null) });
},
}),
{ name: "canina-pets" }
)
+114 -45
View File
@@ -1,5 +1,11 @@
import { create } from "zustand";
import { persist } from "zustand/middleware";
import { authService } from "../services/authService";
import api from "../services/api";
import { useCartStore } from "./cartStore";
import { usePetStore } from "./usePetStore";
export type UserRole = "User_Guest" | "User_PetOwner" | "User_Partner";
@@ -27,6 +33,7 @@ interface UserProfile {
firstName: string;
lastName: string;
email: string;
mobile: string;
walletBalance: number;
charityDonationTotal: number;
addresses: Address[];
@@ -39,13 +46,14 @@ interface UserStore {
profile: UserProfile;
setRole: (role: UserRole) => void;
setLoggedIn: (isLoggedIn: boolean) => void;
updateProfile: (profile: Partial<UserProfile>) => void;
addAddress: (address: Address) => void;
updateAddress: (id: string, address: Address) => void;
deleteAddress: (id: string) => void;
setDefaultAddress: (id: string) => void;
updateProfile: (profile: Partial<UserProfile>) => Promise<void>;
addAddress: (address: Address) => Promise<void>;
updateAddress: (id: string, address: Address) => Promise<void>;
deleteAddress: (id: string) => Promise<void>;
setDefaultAddress: (id: string) => Promise<void>;
topUpWallet: (amount: number) => void;
logout: () => void;
fetchProfile: () => Promise<void>;
}
export const useUserStore = create<UserStore>()(
@@ -57,6 +65,7 @@ export const useUserStore = create<UserStore>()(
firstName: "پارسا",
lastName: "آقایی",
email: "parsa.aghaee@gmail.com",
mobile: "09121234567",
walletBalance: 2450000,
charityDonationTotal: 45000,
addresses: [
@@ -79,48 +88,61 @@ export const useUserStore = create<UserStore>()(
},
setRole: (role) => set({ role }),
setLoggedIn: (isLoggedIn) => set({ isLoggedIn }),
updateProfile: (updates) => {
// TODO: [BACKEND_API] PATCH /api/user/profile | Payload: Partial<UserProfile> | Expected: UserProfile | Errors: [400, 401]
set((state) => ({ profile: { ...state.profile, ...updates } }));
updateProfile: async (updates) => {
try {
const profileData = await authService.updateProfile(updates);
set((state) => ({
profile: {
...state.profile,
firstName: profileData.firstName,
lastName: profileData.lastName,
email: profileData.email,
mobile: profileData.mobile || "",
}
}));
} catch (error) {
console.error("Failed to update profile:", error);
throw error;
}
},
addAddress: (address) => {
// TODO: [BACKEND_API] POST /api/user/addresses | Payload: Omit<Address, "id"> | Expected: Address | Errors: [400, 401]
set((state) => ({
profile: {
...state.profile,
addresses: [...(state.profile.addresses || []), address]
}
}));
addAddress: async (address) => {
try {
// Remove ID so backend generates UUID
const { id, ...addressData } = address;
await api.post('/users/addresses', addressData);
await useUserStore.getState().fetchProfile();
} catch (error) {
console.error("Failed to add address:", error);
throw error;
}
},
updateAddress: (id, updated) => {
// TODO: [BACKEND_API] PATCH /api/user/addresses/{id} | Payload: Address | Expected: Address | Errors: [400, 401, 404]
set((state) => ({
profile: {
...state.profile,
addresses: state.profile.addresses.map(a => a.id === id ? updated : a)
}
}));
updateAddress: async (id, updated) => {
try {
const { id: _, ...addressData } = updated;
await api.patch(`/users/addresses/${id}`, addressData);
await useUserStore.getState().fetchProfile();
} catch (error) {
console.error("Failed to update address:", error);
throw error;
}
},
deleteAddress: (id) => {
// TODO: [BACKEND_API] DELETE /api/user/addresses/{id} | Expected: { success: boolean } | Errors: [401, 404]
set((state) => ({
profile: {
...state.profile,
addresses: state.profile.addresses.filter(a => a.id !== id)
}
}));
deleteAddress: async (id) => {
try {
await api.delete(`/users/addresses/${id}`);
await useUserStore.getState().fetchProfile();
} catch (error) {
console.error("Failed to delete address:", error);
throw error;
}
},
setDefaultAddress: (id) => {
// TODO: [BACKEND_API] POST /api/user/addresses/{id}/set-default | Expected: { success: boolean } | Errors: [401, 404]
set((state) => ({
profile: {
...state.profile,
addresses: state.profile.addresses.map(a => ({
...a,
isDefault: a.id === id
}))
}
}));
setDefaultAddress: async (id) => {
try {
await api.patch(`/users/addresses/${id}/default`);
await useUserStore.getState().fetchProfile();
} catch (error) {
console.error("Failed to set default address:", error);
throw error;
}
},
topUpWallet: (amount) => {
// TODO: [BACKEND_API] POST /api/user/wallet/top-up | Payload: { amount: number } | Expected: { transactionId: string, newBalance: number } | Errors: [400, 401]
@@ -141,8 +163,55 @@ export const useUserStore = create<UserStore>()(
};
})},
logout: () => {
// TODO: [BACKEND_API] POST /api/auth/logout | Expected: { success: boolean } | Errors: [401]
set({ role: "User_Guest", isLoggedIn: false });
authService.logout();
set({ role: "User_Guest", isLoggedIn: false, profile: {
firstName: "",
lastName: "",
email: "",
mobile: "",
walletBalance: 0,
charityDonationTotal: 0,
addresses: [],
transactions: []
}});
},
fetchProfile: async () => {
try {
const profileData = await authService.getProfile();
set({
isLoggedIn: true,
role: (profileData.role as UserRole) || "User_PetOwner",
profile: {
firstName: profileData.firstName,
lastName: profileData.lastName,
email: profileData.email,
mobile: profileData.mobile || "",
walletBalance: Number(profileData.walletBalance),
charityDonationTotal: Number(profileData.charityDonationTotal),
addresses: (profileData as any).addresses || [],
transactions: (profileData as any).walletTransactions?.map((t: any) => ({
id: t.id,
type: t.type === 'deposit' ? 'top_up' : 'purchase',
amount: Number(t.amount),
date: t.createdAt,
status: t.status === 'completed' ? 'success' : t.status === 'failed' ? 'failed' : 'pending'
})) || []
}
});
// Sync orders list to CartStore
if (profileData.orders) {
useCartStore.getState().setOrders(profileData.orders);
}
// Sync pets list to PetStore
if (profileData.pets) {
usePetStore.getState().setPets(profileData.pets);
}
} catch (error) {
console.error("Failed to fetch user profile:", error);
authService.logout();
set({ isLoggedIn: false, role: "User_Guest" });
}
},
}),
{ name: "canina-user" }