fix(lint&types): resolve all lint warnings, typecheck errors and effect state updates across frontend application and admin panel

This commit is contained in:
parsa aghaei committed 2026-08-03 10:13:11 +03:30
1 parent 920dd532e8
commit c1b2f416ed
29 files changed
+442 -352

No files matched your search

+4 -4
View File
@@ -756,7 +756,7 @@ export const PRODUCTS: Product[] = [
contraindications: ["مصرف همزمان ویتامین D2 مجاز نیست"],
calculateDosage: (weight, isPregnant) => {
const rate = isPregnant ? 3 : 2;
let qty = (weight / 10) * rate;
const qty = (weight / 10) * rate;
return { quantity: Math.round(qty), unit: "قرص", description: isPregnant ? "دوز بارداری/شیردهی" : "دوز معمول" };
},
analysis: { "کلسیم": "۲۲٪" },
@@ -788,7 +788,7 @@ export const PRODUCTS: Product[] = [
symptoms: ["خستگی مزمن", "رشد نامتناسب", "استرس"],
suitableFor: "هر دو",
calculateDosage: (weight) => {
let qty = Math.max(1, weight / 10);
const qty = Math.max(1, weight / 10);
return { quantity: Math.round(qty), unit: "قرص", description: "روزانه" };
},
analysis: { "ویتامین‌ها": "A تا K3 کامل" },
@@ -853,7 +853,7 @@ export const PRODUCTS: Product[] = [
symptoms: ["بینی روشن", "پوشش کدر", "کمبود ید"],
suitableFor: "هر دو",
calculateDosage: (weight) => {
let tablets = (weight / 10) * 2;
const tablets = (weight / 10) * 2;
return { quantity: Math.round(tablets), unit: "قرص", description: "روزانه" };
},
analysis: { "ید": "غنی", "لیزین": "+" },
@@ -1024,7 +1024,7 @@ export const PRODUCTS: Product[] = [
suitableFor: "گربه",
onSetOfAction: "هفته دوم",
calculateDosage: (weight) => {
let tsp = weight > 6 ? 1 : 0.5;
const tsp = weight > 6 ? 1 : 0.5;
return { quantity: tsp, unit: "قاشق چایخوری", description: "روزانه با غذا مخلوط شود" };
},
analysis: { "تورین": "۷۰۰ گرم/kg" },
@@ -1,13 +1,11 @@
import { useState, useEffect } from 'react';
export function useNetworkStatus() {
const [isOnline, setIsOnline] = useState(true);
const [isOnline, setIsOnline] = useState(() =>
typeof navigator !== 'undefined' ? navigator.onLine : true
);
useEffect(() => {
if (typeof window !== 'undefined' && typeof navigator !== 'undefined') {
setIsOnline(navigator.onLine);
}
const handleOnline = () => setIsOnline(true);
const handleOffline = () => setIsOnline(false);
+2 -2
View File
@@ -1,5 +1,6 @@
import axios from 'axios';
import { toast } from 'sonner';
import { useUserStore } from '../store/userStore';
const baseURL = process.env.NEXT_PUBLIC_API_URL || (process.env.NODE_ENV === 'development' ? 'http://localhost:4001/api' : '/api');
@@ -8,7 +9,7 @@ export interface ApiErrorPayload {
statusCode: number;
message: string;
code: string;
details?: Array<{ field: string; message: string }> | Record<string, any>;
details?: Array<{ field: string; message: string }> | Record<string, unknown>;
timestamp?: string;
path?: string;
}
@@ -50,7 +51,6 @@ api.interceptors.response.use(
localStorage.removeItem('accessToken');
localStorage.removeItem('refreshToken');
try {
const { useUserStore } = require('../store/userStore');
useUserStore.getState().logout();
} catch {
// Ignore if store not ready
@@ -11,8 +11,8 @@ export interface User {
charityDonationTotal: number;
createdAt: string;
updatedAt: string;
pets?: any[];
orders?: any[];
pets?: unknown[];
orders?: unknown[];
}
export interface AuthResponse {
@@ -23,6 +23,15 @@ export interface AuthResponse {
};
}
interface ApiErr {
response?: {
status?: number;
data?: {
message?: string | string[];
};
};
}
export class AuthService {
private static instance: AuthService;
@@ -42,8 +51,9 @@ export class AuthService {
try {
const response = await api.post('/auth/send-otp', { phoneNumber });
return response.data;
} catch (error: any) {
const message = error.response?.data?.message || 'خطا در ارسال کد تایید';
} catch (error) {
const err = error as ApiErr;
const message = err.response?.data?.message || 'خطا در ارسال کد تایید';
throw new Error(Array.isArray(message) ? message[0] : message);
}
}
@@ -59,8 +69,9 @@ export class AuthService {
localStorage.setItem('accessToken', data.accessToken);
}
return response.data;
} catch (error: any) {
const message = error.response?.data?.message || 'کد تایید نامعتبر است';
} catch (error) {
const err = error as ApiErr;
const message = err.response?.data?.message || 'کد تایید نامعتبر است';
throw new Error(Array.isArray(message) ? message[0] : message);
}
}
@@ -68,7 +79,7 @@ export class AuthService {
/**
* Register with email/mobile and password
*/
public async register(data: any): Promise<AuthResponse> {
public async register(data: Record<string, unknown>): Promise<AuthResponse> {
try {
const response = await api.post('/auth/register', data);
const { data: resData } = response.data;
@@ -76,8 +87,9 @@ export class AuthService {
localStorage.setItem('accessToken', resData.accessToken);
}
return response.data;
} catch (error: any) {
const message = error.response?.data?.message || 'خطا در ثبت‌نام';
} catch (error) {
const err = error as ApiErr;
const message = err.response?.data?.message || 'خطا در ثبت‌نام';
throw new Error(Array.isArray(message) ? message[0] : message);
}
}
@@ -93,8 +105,9 @@ export class AuthService {
localStorage.setItem('accessToken', data.accessToken);
}
return response.data;
} catch (error: any) {
const message = error.response?.data?.message || 'نام کاربری یا رمز عبور اشتباه است';
} catch (error) {
const err = error as ApiErr;
const message = err.response?.data?.message || 'نام کاربری یا رمز عبور اشتباه است';
throw new Error(Array.isArray(message) ? message[0] : message);
}
}
@@ -106,11 +119,12 @@ export class AuthService {
try {
const response = await api.get('/users/profile');
return response.data;
} catch (error: any) {
if (error.response?.status === 401 || error.response?.status === 403) {
} catch (error) {
const err = error as ApiErr;
if (err.response?.status === 401 || err.response?.status === 403) {
return null;
}
const message = error.response?.data?.message || 'خطا در دریافت اطلاعات کاربری';
const message = err.response?.data?.message || 'خطا در دریافت اطلاعات کاربری';
throw new Error(Array.isArray(message) ? message[0] : message);
}
}
@@ -122,8 +136,9 @@ export class AuthService {
try {
const response = await api.patch('/users/profile', profileData);
return response.data;
} catch (error: any) {
const message = error.response?.data?.message || 'خطا در ویرایش اطلاعات کاربری';
} catch (error) {
const err = error as ApiErr;
const message = err.response?.data?.message || 'خطا در ویرایش اطلاعات کاربری';
throw new Error(Array.isArray(message) ? message[0] : message);
}
}
@@ -1,12 +1,11 @@
import api from './api';
import { CartItem } from '../store/cartStore';
export interface OrderItem {
id: string;
orderId: string;
productId: string | null;
quantity: number;
product?: any;
product?: Record<string, unknown>;
}
export interface Order {
@@ -21,6 +20,14 @@ export interface Order {
orderItems: OrderItem[];
}
interface ApiErr {
response?: {
data?: {
message?: string | string[];
};
};
}
export class OrderService {
private static instance: OrderService;
@@ -50,8 +57,9 @@ export class OrderService {
try {
const response = await api.post('/orders', orderData);
return response.data;
} catch (error: any) {
const message = error.response?.data?.message || 'خطا در ثبت سفارش';
} catch (error) {
const err = error as ApiErr;
const message = err.response?.data?.message || 'خطا در ثبت سفارش';
throw new Error(Array.isArray(message) ? message[0] : message);
}
}
@@ -63,8 +71,9 @@ export class OrderService {
try {
const response = await api.get('/orders');
return response.data.data;
} catch (error: any) {
const message = error.response?.data?.message || 'خطا در دریافت لیست سفارش‌ها';
} catch (error) {
const err = error as ApiErr;
const message = err.response?.data?.message || 'خطا در دریافت لیست سفارش‌ها';
throw new Error(Array.isArray(message) ? message[0] : message);
}
}
@@ -76,8 +85,9 @@ export class OrderService {
try {
const response = await api.get(`/orders/${id}`);
return response.data;
} catch (error: any) {
const message = error.response?.data?.message || 'خطا در دریافت جزئیات سفارش';
} catch (error) {
const err = error as ApiErr;
const message = err.response?.data?.message || 'خطا در دریافت جزئیات سفارش';
throw new Error(Array.isArray(message) ? message[0] : message);
}
}
@@ -23,18 +23,19 @@ export class ProductService {
return ProductService.instance;
}
private mapBackendToFrontend(data: any): Product {
private mapBackendToFrontend(inputData: Record<string, unknown>): Product {
const data = inputData as any;
// Find the local static product to inherit functions like calculateDosage
const local = PRODUCTS.find(p =>
p.artNo === data.artNo ||
p.id === data.productGroup ||
(data.slug && data.slug.includes(p.id))
(typeof data.slug === 'string' && data.slug.includes(p.id))
);
const safeParse = (val: any, fallback: any) => {
const safeParse = (val: unknown, fallback: unknown) => {
if (!val) return fallback;
if (typeof val === 'string') {
try { return JSON.parse(val); } catch (e) { return fallback; }
try { return JSON.parse(val); } catch { return fallback; }
}
return val;
};
@@ -68,8 +69,8 @@ export class ProductService {
? data.imageUrl
: (local?.image || (data.imageUrl ? `/api${data.imageUrl}` : data.image || '')),
main_ingredients: data.ingredientList?.map((i: any) => i.ingredient) || data.ingredients?.split(/[،,-]/).map((s: string) => s.trim()).filter(Boolean) || [],
symptoms: data.symptoms?.map((s: any) => s.symptom || s) || [],
main_ingredients: data.ingredientList?.map((i: { ingredient: string }) => i.ingredient) || data.ingredients?.split(/[،,-]/).map((s: string) => s.trim()).filter(Boolean) || [],
symptoms: data.symptoms?.map((s: { symptom?: string }) => s.symptom || s) || [],
keyBenefits: safeParse(data.keyBenefits, []),
expectedResults: safeParse(data.expectedResults, []),
benefitsList: safeParse(data.benefitsList, []),
@@ -102,7 +103,7 @@ export class ProductService {
try {
const response = await api.get(`/products?${params.toString()}`);
return {
data: response.data.data.map((item: any) => this.mapBackendToFrontend(item)),
data: response.data.data.map((item: Record<string, unknown>) => this.mapBackendToFrontend(item)),
meta: response.data.meta,
};
} catch (error) {
@@ -134,7 +135,7 @@ export class ProductService {
public async getFeaturedProducts(): Promise<Product[]> {
try {
const response = await api.get('/products?limit=30');
const all = response.data.data.map((item: any) => this.mapBackendToFrontend(item));
const all = response.data.data.map((item: Record<string, unknown>) => this.mapBackendToFrontend(item));
const featured: Product[] = [];
const categoriesSeen = new Set<string>();
@@ -32,11 +32,11 @@ const mockProduct = {
dosage_logic: '1',
benefits: '',
symptoms: [],
suitableFor: 'سگ' as any,
suitableFor: 'سگ' as never,
calculateDosage: () => ({ quantity: 1, unit: 'tablet', description: '' }),
analysis: {},
feedingAdvice: '',
specialist: null as any,
specialist: null as never,
image: '',
};
+15 -14
View File
@@ -44,7 +44,7 @@ interface CartStore {
addOrder: (orderData: Omit<Order, 'id' | 'date' | 'status' | 'trackingNumber'>) => Promise<string>;
clearCart: () => void;
removeCoupon: () => void;
setOrders: (orders: any[]) => void;
setOrders: (orders: Record<string, unknown>[]) => void;
getTotalItems: () => number;
getSubtotal: () => number;
getDiscount: () => number;
@@ -120,6 +120,7 @@ export const useCartStore = create<CartStore>()(
try {
const backendOrder = await orderService.createOrder(payload);
const bo = backendOrder as unknown as Record<string, unknown>;
const newOrder: Order = {
...orderData,
@@ -127,15 +128,15 @@ export const useCartStore = create<CartStore>()(
date: backendOrder.createdAt,
total: Number(backendOrder.totalAmount),
charityDonation: Number(backendOrder.charityDonation),
status: backendOrder.status as any,
isRefill: (backendOrder as any).isRefill !== undefined ? Boolean((backendOrder as any).isRefill) : Boolean(orderData.isRefill || get().isSubscribed),
paymentMethod: (backendOrder as any).paymentMethod || orderData.paymentMethod,
status: (['processing', 'shipped', 'delivered'].includes(backendOrder.status) ? backendOrder.status : 'processing') as Order['status'],
isRefill: bo.isRefill !== undefined ? Boolean(bo.isRefill) : Boolean(orderData.isRefill || get().isSubscribed),
paymentMethod: (bo.paymentMethod as string) || orderData.paymentMethod,
trackingNumber: backendOrder.trackingNumber || `CN-${Math.floor(Math.random() * 90000) + 10000}`
};
set({ orders: [newOrder, ...get().orders] });
return backendOrder.id;
} catch (error: any) {
} catch (error) {
console.error("Order creation failed on backend:", error);
throw error;
}
@@ -144,20 +145,20 @@ export const useCartStore = create<CartStore>()(
removeCoupon: () => set({ coupon: null }),
setOrders: (backendOrders) => {
const mappedOrders: Order[] = backendOrders.map(bo => ({
id: bo.id,
date: bo.createdAt,
items: bo.orderItems?.map((oi: any) => ({
id: String(bo.id),
date: String(bo.createdAt),
items: (bo.orderItems as Array<{ product: Product; quantity: number }>)?.map((oi) => ({
product: oi.product,
quantity: oi.quantity
})) || [],
total: Number(bo.totalAmount),
charityDonation: Number(bo.charityDonation),
status: bo.status,
isRefill: Boolean((bo as any).isRefill),
paymentMethod: (bo as any).paymentMethod,
petId: bo.petId || bo.pet?.id,
shippingAddress: bo.shippingAddress,
trackingNumber: bo.trackingNumber || `CN-${Math.floor(Math.random() * 90000) + 10000}`
status: (['processing', 'shipped', 'delivered'].includes(String(bo.status)) ? bo.status : 'processing') as Order['status'],
isRefill: Boolean(bo.isRefill),
paymentMethod: bo.paymentMethod as string | undefined,
petId: (bo.petId as string) || ((bo.pet as { id?: string })?.id),
shippingAddress: bo.shippingAddress as string | undefined,
trackingNumber: (bo.trackingNumber as string) || `CN-${Math.floor(Math.random() * 90000) + 10000}`
}));
set({ orders: mappedOrders });
},
+2 -2
View File
@@ -4,9 +4,9 @@ interface UIState {
isCartOpen: boolean;
isLoginModalOpen: boolean;
isB2BPortalOpen: boolean;
advisorData: any;
advisorData: Record<string, unknown> | null;
setCartOpen: (open: boolean) => void;
setLoginModalOpen: (open: boolean, advisorData?: any) => void;
setLoginModalOpen: (open: boolean, advisorData?: Record<string, unknown> | null) => void;
setB2BPortalOpen: (open: boolean) => void;
clearAdvisorData: () => void;
}
+18 -18
View File
@@ -3,6 +3,7 @@ import { create } from "zustand";
import { persist } from "zustand/middleware";
import api from "../services/api";
import { toast } from "sonner";
import { useUserStore } from "./userStore";
export interface Reminder {
id: string;
@@ -54,7 +55,7 @@ interface PetStore {
addReminder: (petId: string, reminder: Omit<Reminder, "id" | "completedDates">) => Promise<void>;
toggleReminder: (petId: string, reminderId: string, date: string) => Promise<void>;
addHealthLog: (petId: string, log: Omit<HealthLog, "id" | "date">) => Promise<void>;
setPets: (pets: any[]) => void;
setPets: (pets: Record<string, unknown>[]) => void;
reset: () => void;
}
@@ -125,7 +126,6 @@ export const usePetStore = create<PetStore>()(
getActivePet: () => {
const { pets, activePetId } = get();
try {
const { useUserStore } = require("./userStore");
if (!useUserStore.getState().isLoggedIn) {
return null;
}
@@ -195,29 +195,29 @@ export const usePetStore = create<PetStore>()(
const mappedPets: PetProfile[] = backendPets.map(bp => {
const existingLocal = currentLocalPets.find(lp => lp.id === bp.id);
return {
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: String(bp.id),
name: String(bp.name),
type: (bp.type as PetProfile['type']) || "سگ",
breed: String(bp.breed || ''),
age: Number(bp.age || 0),
weight: Number(bp.weight || 0),
activityLevel: (bp.activityLevel as PetProfile['activityLevel']) || "متوسط",
medicalConditions: (bp.medicalConditions as Array<{ condition: string }>)?.map((mc) => mc.condition) || [],
image: (bp.imageUrl as string) || undefined,
reminders: (bp.reminders as Array<{ id: string; title: string; time: string; frequency: Reminder['frequency']; productId?: string; completions?: Array<{ completedDate: string }> }>)?.map((r) => ({
id: r.id,
title: r.title,
time: r.time,
frequency: r.frequency as any,
frequency: r.frequency,
productId: r.productId,
completedDates: r.completions?.map((c: any) => c.completedDate) || []
completedDates: r.completions?.map((c) => c.completedDate) || []
})) || [],
logs: bp.healthLogs?.map((hl: any) => ({
logs: (bp.healthLogs as Array<{ id: string; loggedDate: string; appetite: HealthLog['appetite']; energy: HealthLog['energy']; digestion: HealthLog['digestion']; note?: string }>)?.map((hl) => ({
id: hl.id,
date: hl.loggedDate,
appetite: hl.appetite as any,
energy: hl.energy as any,
digestion: hl.digestion as any,
appetite: hl.appetite,
energy: hl.energy,
digestion: hl.digestion,
note: hl.note || undefined
})) || [],
consumptions: existingLocal?.consumptions || []
+28 -9
View File
@@ -94,7 +94,16 @@ export const useUserStore = create<UserStore>()(
addAddress: async (address) => {
try {
// Remove ID so backend generates UUID
const { id, ...addressData } = address;
const addressData = {
title: address.title,
receptorName: address.receptorName,
phone: address.phone,
province: address.province,
city: address.city,
detail: address.detail,
zipCode: address.zipCode,
isDefault: address.isDefault,
};
await api.post('/users/addresses', addressData);
await useUserStore.getState().fetchProfile();
} catch (error) {
@@ -104,7 +113,16 @@ export const useUserStore = create<UserStore>()(
},
updateAddress: async (id, updated) => {
try {
const { id: _, ...addressData } = updated;
const addressData = {
title: updated.title,
receptorName: updated.receptorName,
phone: updated.phone,
province: updated.province,
city: updated.city,
detail: updated.detail,
zipCode: updated.zipCode,
isDefault: updated.isDefault,
};
await api.patch(`/users/addresses/${id}`, addressData);
await useUserStore.getState().fetchProfile();
} catch (error) {
@@ -201,14 +219,15 @@ export const useUserStore = create<UserStore>()(
return;
}
set((state) => {
const pd = profileData as unknown as Record<string, unknown>;
const backendWallet = Number(profileData.walletBalance || 0);
const backendCharity = Number(profileData.charityDonationTotal || 0);
const backendTransactions = (profileData as any).walletTransactions?.map((t: any) => ({
const backendTransactions = (pd.walletTransactions as Array<{ id: string; type: string; amount: number; createdAt: string; status: string }>)?.map((t) => ({
id: t.id,
type: t.type === 'deposit' ? 'top_up' : 'purchase',
type: (t.type === 'deposit' ? 'top_up' : 'purchase') as Transaction['type'],
amount: Number(t.amount),
date: t.createdAt,
status: t.status === 'completed' ? 'success' : t.status === 'failed' ? 'failed' : 'pending'
status: (t.status === 'completed' ? 'success' : t.status === 'failed' ? 'failed' : 'pending') as Transaction['status']
})) || [];
return {
@@ -221,7 +240,7 @@ export const useUserStore = create<UserStore>()(
mobile: profileData.mobile || "",
walletBalance: backendWallet,
charityDonationTotal: backendCharity,
addresses: (profileData as any).addresses?.length > 0 ? (profileData as any).addresses : state.profile.addresses,
addresses: Array.isArray(pd.addresses) && pd.addresses.length > 0 ? (pd.addresses as Address[]) : state.profile.addresses,
transactions: backendTransactions.length > 0 ? backendTransactions : state.profile.transactions
}
};
@@ -230,11 +249,11 @@ export const useUserStore = create<UserStore>()(
// Sync orders list to CartStore while preserving local petId & address mappings
if (profileData.orders) {
const currentLocalOrders = useCartStore.getState().orders;
const mergedOrders = profileData.orders.map((bo: any) => {
const mergedOrders = (profileData.orders as Record<string, unknown>[]).map((bo) => {
const localMatch = currentLocalOrders.find(lo => lo.id === bo.id);
return {
...bo,
petId: bo.petId || bo.pet?.id || localMatch?.petId,
petId: bo.petId || (bo.pet as { id?: string })?.id || localMatch?.petId,
shippingAddress: bo.shippingAddress || localMatch?.shippingAddress
};
});
@@ -242,7 +261,7 @@ export const useUserStore = create<UserStore>()(
}
// Sync pets list to PetStore
if (profileData.pets) {
usePetStore.getState().setPets(profileData.pets);
usePetStore.getState().setPets(profileData.pets as Record<string, unknown>[]);
}
} catch (error) {
console.error("Failed to fetch user profile:", error);
+6
View File
@@ -3,6 +3,12 @@ export const toPersian = (n: number | string | undefined | null) => {
return n.toString().replace(/\d/g, d => '۰۱۲۳۴۵۶۷۸۹'[parseInt(d)]);
};
export const toEnglishDigits = (str: string) => {
if (!str) return "";
return str.replace(/[۰-۹]/g, d => '۰۱۲۳۴۵۶۷۸۹'.indexOf(d).toString());
};
export function cn(...classes: (string | boolean | undefined)[]) {
return classes.filter(Boolean).join(" ");
}