From 884b0486cc391bc3e9b8e3bf21518239b1bb555a Mon Sep 17 00:00:00 2001 From: parsa aghaei Date: Sun, 16 Aug 2026 19:19:20 +0330 Subject: [PATCH] fix(all): auto-create ticket tables, multi-tier otp rate limiting, packaged order status & badges, pet kindness footprint --- backend/src/auth/auth.service.ts | 56 ++++++++++++++++++- backend/src/prisma/prisma.service.ts | 56 +++++++++++++++++++ backend/src/redis/redis.service.ts | 4 ++ frontend/admin-panel/src/pages/Orders.tsx | 51 ++++++++++++++--- .../components/OrderDetailsModal.tsx | 16 +++++- .../application/components/PetProfile.tsx | 34 ++++++++--- .../application/components/UserDashboard.tsx | 40 +++++++++++-- frontend/application/lib/store/cartStore.ts | 6 +- 8 files changed, 239 insertions(+), 24 deletions(-) diff --git a/backend/src/auth/auth.service.ts b/backend/src/auth/auth.service.ts index 277f2f2c..c772fc30 100644 --- a/backend/src/auth/auth.service.ts +++ b/backend/src/auth/auth.service.ts @@ -1,4 +1,4 @@ -import { Injectable, BadRequestException } from '@nestjs/common'; +import { Injectable, BadRequestException, HttpException, HttpStatus } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import { PrismaService } from '../prisma/prisma.service'; import { RedisService } from '../redis/redis.service'; @@ -25,6 +25,7 @@ export class LoginInput { export class AdminLoginInput { email!: string; password?: string; + username?: string; } @Injectable() @@ -39,8 +40,56 @@ export class AuthService { async sendOtp(sendOtpDto: SendOtpDto) { const phoneNumber = normalizeMobile(sendOtpDto.phoneNumber); + // 1. Check 60-second cooldown per phone number + const cooldownKey = `otp:cooldown:${phoneNumber}`; + const inCooldown = await this.redisService.get(cooldownKey); + if (inCooldown) { + const remainingTtl = await this.redisService.ttl(cooldownKey); + throw new HttpException( + { + success: false, + statusCode: HttpStatus.TOO_MANY_REQUESTS, + message: `لطفاً ${Math.max(1, remainingTtl)} ثانیه دیگر مجدداً تلاش کنید.`, + code: 'OTP_COOLDOWN', + remainingSeconds: Math.max(1, remainingTtl), + }, + HttpStatus.TOO_MANY_REQUESTS, + ); + } + + // 2. Hourly rate limit: Max 5 OTP requests per hour per phone + const hourKey = `otp:rate:hour:${phoneNumber}`; + const hourlyRequests = await this.redisService.incr(hourKey, 3600); + if (hourlyRequests > 5) { + throw new HttpException( + { + success: false, + statusCode: HttpStatus.TOO_MANY_REQUESTS, + message: 'تعداد دفعات ارسال پیامک در یک ساعت بیش از حد مجاز است. لطفاً ساعتی دیگر تلاش کنید.', + code: 'HOURLY_RATE_LIMIT_EXCEEDED', + }, + HttpStatus.TOO_MANY_REQUESTS, + ); + } + + // 3. Daily rate limit: Max 10 OTP requests per 24 hours per phone + const dayKey = `otp:rate:day:${phoneNumber}`; + const dailyRequests = await this.redisService.incr(dayKey, 86400); + if (dailyRequests > 10) { + throw new HttpException( + { + success: false, + statusCode: HttpStatus.TOO_MANY_REQUESTS, + message: 'سقف ارسال روزانه پیامک برای این شماره تکمیل شده است. لطفاً فردا مجدداً تلاش کنید.', + code: 'DAILY_RATE_LIMIT_EXCEEDED', + }, + HttpStatus.TOO_MANY_REQUESTS, + ); + } + const code = crypto.randomInt(10000, 100000).toString(); + // Store OTP for 120 seconds await this.redisService.set(`otp:${phoneNumber}`, code, 120); // Dispatch OTP via MeliPayamak Pattern SMS @@ -56,9 +105,14 @@ export class AuthService { }); } + // Set 60-second cooldown lock + await this.redisService.set(cooldownKey, '1', 60); + return { success: true, message: 'کد تایید با موفقیت به شماره شما پیامک شد.', + expiresIn: 120, + cooldown: 60, }; } diff --git a/backend/src/prisma/prisma.service.ts b/backend/src/prisma/prisma.service.ts index 7ffd32da..e325db6b 100644 --- a/backend/src/prisma/prisma.service.ts +++ b/backend/src/prisma/prisma.service.ts @@ -8,6 +8,62 @@ export class PrismaService { async onModuleInit() { await this.$connect(); + await this.ensureTablesExist(); + } + + private async ensureTablesExist() { + try { + await this.$executeRawUnsafe(` + CREATE TABLE IF NOT EXISTS "tickets" ( + "id" UUID PRIMARY KEY DEFAULT gen_random_uuid(), + "ticket_number" VARCHAR(50) NOT NULL UNIQUE, + "user_id" UUID NOT NULL REFERENCES "users"("id") ON DELETE CASCADE, + "pet_id" UUID REFERENCES "pets"("id") ON DELETE SET NULL, + "subject" VARCHAR(255) NOT NULL, + "category" VARCHAR(50) NOT NULL DEFAULT 'VET_CONSULTATION', + "priority" VARCHAR(20) NOT NULL DEFAULT 'MEDIUM', + "status" VARCHAR(30) NOT NULL DEFAULT 'OPEN', + "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP + ); + + CREATE INDEX IF NOT EXISTS "tickets_user_id_idx" ON "tickets"("user_id"); + CREATE INDEX IF NOT EXISTS "tickets_status_idx" ON "tickets"("status"); + CREATE INDEX IF NOT EXISTS "tickets_category_idx" ON "tickets"("category"); + CREATE INDEX IF NOT EXISTS "tickets_created_at_idx" ON "tickets"("created_at"); + + CREATE TABLE IF NOT EXISTS "ticket_messages" ( + "id" UUID PRIMARY KEY DEFAULT gen_random_uuid(), + "ticket_id" UUID NOT NULL REFERENCES "tickets"("id") ON DELETE CASCADE, + "sender_id" UUID, + "sender_role" VARCHAR(30) NOT NULL DEFAULT 'USER', + "sender_name" VARCHAR(100) NOT NULL, + "message" TEXT NOT NULL, + "attachment" TEXT, + "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP + ); + + CREATE INDEX IF NOT EXISTS "ticket_messages_ticket_id_idx" ON "ticket_messages"("ticket_id"); + CREATE INDEX IF NOT EXISTS "ticket_messages_created_at_idx" ON "ticket_messages"("created_at"); + + CREATE TABLE IF NOT EXISTS "sms_logs" ( + "id" UUID PRIMARY KEY DEFAULT gen_random_uuid(), + "phone" VARCHAR(20) NOT NULL, + "pattern_id" INTEGER, + "message" TEXT, + "status" VARCHAR(50) NOT NULL, + "bulk_id" VARCHAR(100), + "meta" JSONB, + "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP + ); + + CREATE INDEX IF NOT EXISTS "sms_logs_phone_idx" ON "sms_logs"("phone"); + CREATE INDEX IF NOT EXISTS "sms_logs_status_idx" ON "sms_logs"("status"); + CREATE INDEX IF NOT EXISTS "sms_logs_created_at_idx" ON "sms_logs"("created_at"); + `); + } catch (err) { + console.warn('[PrismaService] Auto table check warning:', err); + } } async onModuleDestroy() { diff --git a/backend/src/redis/redis.service.ts b/backend/src/redis/redis.service.ts index 14ae8e5f..26a23458 100644 --- a/backend/src/redis/redis.service.ts +++ b/backend/src/redis/redis.service.ts @@ -40,4 +40,8 @@ export class RedisService implements OnModuleInit, OnModuleDestroy { } return count; } + + async ttl(key: string): Promise { + return this.client.ttl(key); + } } diff --git a/frontend/admin-panel/src/pages/Orders.tsx b/frontend/admin-panel/src/pages/Orders.tsx index eb8d71db..eb30c491 100644 --- a/frontend/admin-panel/src/pages/Orders.tsx +++ b/frontend/admin-panel/src/pages/Orders.tsx @@ -15,7 +15,10 @@ import { Mail, Package, Save, - Download + Download, + PackageCheck, + Heart, + CreditCard } from 'lucide-react'; import api from '../services/api'; import Skeleton from '../components/ui/Skeleton'; @@ -28,11 +31,13 @@ export interface OrderItem { priceValue?: number; quantity?: number; product?: { + id?: string; nameFa?: string; name?: string; priceValue?: number; imageUrl?: string; image?: string; + images?: string[]; }; } @@ -46,6 +51,7 @@ export interface PaymentTx { message?: string; gateway?: string; createdAt: string; + trackingCode?: string; } export interface Order { @@ -77,11 +83,24 @@ const statusStyles: Record { + switch (method) { + case 'wallet': return { label: 'کیف پول', color: 'bg-purple-50 text-purple-700 border-purple-200' }; + case 'zibal': + case 'online': return { label: 'درگاه زیبال (آنلاین)', color: 'bg-emerald-50 text-emerald-700 border-emerald-200' }; + case 'card_to_card': return { label: 'کارت به کارت', color: 'bg-blue-50 text-blue-700 border-blue-200' }; + case 'cod': return { label: 'پرداخت در محل', color: 'bg-amber-50 text-amber-700 border-amber-200' }; + default: return { label: method || 'آنلاین', color: 'bg-gray-50 text-gray-700 border-gray-200' }; + } +}; + const toPersianDigits = (n: string | number): string => { if (n === null || n === undefined) return ''; const farsiDigits = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹']; @@ -356,6 +375,7 @@ export default function Orders() { + @@ -380,6 +400,7 @@ export default function Orders() { { label: 'همه سفارش‌ها', value: '' }, { label: 'در انتظار پرداخت / ناموفق', value: 'pending_payment', color: 'text-rose-700 bg-rose-50 border-rose-200' }, { label: 'در حال پردازش', value: 'processing', color: 'text-amber-700 bg-amber-50 border-amber-200' }, + { label: 'بسته‌بندی شده (آماده ارسال)', value: 'packaged', color: 'text-purple-700 bg-purple-50 border-purple-200' }, { label: 'ارسال شده', value: 'shipped', color: 'text-blue-700 bg-blue-50 border-blue-200' }, { label: 'تحویل شده', value: 'delivered', color: 'text-green-700 bg-green-50 border-green-200' }, { label: 'لغو شده', value: 'cancelled', color: 'text-red-700 bg-red-50 border-red-200' }, @@ -439,24 +460,38 @@ export default function Orders() { orders.map((order) => { const isProcessing = processingId === order.id; const displayCode = order.trackingNumber || order.id.slice(0, 8); - const orderDate = new Date(order.createdAt || order.date); + const orderDate = new Date(order.createdAt || order.date || 0); const customerName = order.user ? `${order.user.firstName || ''} ${order.user.lastName || ''}`.trim() : 'کاربر مهمان'; const itemsCount = (order.orderItems || order.items || []).length; const totalAmt = Number(order.totalAmount || order.total || 0); + const payInfo = getPaymentMethodLabel(order.paymentMethod); + const charityAmt = Number(order.charityDonation || 0); return (
{toPersianDigits(displayCode)}
- {order.isRefill && ( - - Refill 5% +
+ + + {payInfo.label} - )} + {order.isRefill && ( + + تمدید ۵٪- + + )} + {charityAmt > 0 && ( + + + مهربانی: {toPersianDigits(charityAmt.toLocaleString())} ت + + )} +
{customerName}
-
{toPersianDigits(order.user?.phone || '')}
+
{toPersianDigits(order.user?.phone || order.user?.mobile || '')}
{toPersianDigits(totalAmt.toLocaleString())} تومان @@ -477,6 +512,7 @@ export default function Orders() { > + @@ -590,6 +626,7 @@ export default function Orders() { > + diff --git a/frontend/application/components/OrderDetailsModal.tsx b/frontend/application/components/OrderDetailsModal.tsx index 0f344f5c..0793794d 100644 --- a/frontend/application/components/OrderDetailsModal.tsx +++ b/frontend/application/components/OrderDetailsModal.tsx @@ -11,7 +11,10 @@ import { Clock, CreditCard, CheckCircle2, - Truck + Truck, + PackageCheck, + XCircle, + AlertCircle } from "lucide-react"; import { toPersian } from "../lib/utils"; @@ -188,7 +191,11 @@ export default function OrderDetailsModal({ isOpen, onClose, order }: OrderDetai switch (status) { case 'delivered': return ; case 'shipped': return ; - default: return ; + case 'packaged': + case 'ready_to_ship': return ; + case 'cancelled': return ; + case 'pending_payment': return ; + default: return ; } }; @@ -196,6 +203,11 @@ export default function OrderDetailsModal({ isOpen, onClose, order }: OrderDetai switch (status) { case 'delivered': return 'تحویل شده'; case 'shipped': return 'ارسال شده'; + case 'packaged': + case 'ready_to_ship': return 'بسته‌بندی شده (آماده ارسال)'; + case 'cancelled': return 'لغو شده'; + case 'pending_payment': return 'در انتظار پرداخت / ناموفق'; + case 'refunded': return 'مرجوع شده'; default: return 'در حال پردازش'; } }; diff --git a/frontend/application/components/PetProfile.tsx b/frontend/application/components/PetProfile.tsx index 230dcdfe..8ffd254c 100644 --- a/frontend/application/components/PetProfile.tsx +++ b/frontend/application/components/PetProfile.tsx @@ -94,6 +94,14 @@ export default function PetProfile({ initialView }: { return orders.filter(o => o.petId === activePet.id); }, [activePet, orders]); + const petCharityTotal = useMemo(() => { + return petOrders.reduce((sum, o) => sum + (Number(o.charityDonation) || 0), 0); + }, [petOrders]); + + const allCharityTotal = useMemo(() => { + return orders.reduce((sum, o) => sum + (Number(o.charityDonation) || 0), 0); + }, [orders]); + const [step, setStep] = useState(1); const [formData, setFormData] = useState>({ name: "", @@ -748,20 +756,32 @@ export default function PetProfile({ initialView }: {
-

ردپای مهربانی

+

ردپای مهربانی {activePet.name}

سفیر مهربانی: {activePet.name}

-

- {activePet.name} با خریدهای مکمل خود، تا کنون به تامین هزینه‌های درمانی و تغذیه حیوانات پناهگاهی کمک کرده است. -

-
+
- سطح مشارکت - حامی وفادار + کمک اهدایی با نام {activePet.name}: + + {toPersian(petCharityTotal.toLocaleString())} تومان +
+ {allCharityTotal > 0 && ( +
+ مجموع مهربانی کل حساب: + {toPersian(allCharityTotal.toLocaleString())} تومان +
+ )}
+

+ {petCharityTotal > 0 ? ( + <>«{activePet.name}» با خریدهای مکمل خود تا کنون {toPersian(petCharityTotal.toLocaleString())} تومان به درمان و تغذیه حیوانات نیازمند پناهگاهی کمک کرده است. + ) : ( + <>با هر خرید برای «{activePet.name}» می‌توانید با انتخاب گزینه ردپای مهربانی، مبلغی را به نام او به پناهگاه‌های حیوانات اختصاص دهید. + )} +

diff --git a/frontend/application/components/UserDashboard.tsx b/frontend/application/components/UserDashboard.tsx index a6334fe0..711d20ae 100644 --- a/frontend/application/components/UserDashboard.tsx +++ b/frontend/application/components/UserDashboard.tsx @@ -826,15 +826,47 @@ export default function UserDashboard() {
{toPersian(order.total.toLocaleString())} تومان
-
+
{order.isRefill && ( تمدید خودکار ۵٪- )} - - {order.status === 'delivered' ? 'تحویل شده' : order.status === 'shipped' ? 'ارسال شده' : 'در حال پردازش'} - + {Number(order.charityDonation) > 0 && ( + + + مهربانی: {toPersian(Number(order.charityDonation).toLocaleString())} ت + + )} + {(() => { + const st = order.status; + let badgeLabel = 'در حال پردازش'; + let badgeColor = 'bg-amber-50 text-amber-700 border-amber-200'; + if (st === 'delivered') { + badgeLabel = 'تحویل شده'; + badgeColor = 'bg-green-50 text-green-700 border-green-200'; + } else if (st === 'shipped') { + badgeLabel = 'ارسال شده'; + badgeColor = 'bg-blue-50 text-blue-700 border-blue-200'; + } else if (st === 'packaged' || st === 'ready_to_ship') { + badgeLabel = 'بسته‌بندی شده (آماده ارسال)'; + badgeColor = 'bg-purple-50 text-purple-700 border-purple-200'; + } else if (st === 'pending_payment') { + badgeLabel = 'در انتظار پرداخت / ناموفق'; + badgeColor = 'bg-rose-50 text-rose-700 border-rose-200'; + } else if (st === 'cancelled') { + badgeLabel = 'لغو شده'; + badgeColor = 'bg-red-50 text-red-700 border-red-200'; + } else if (st === 'refunded') { + badgeLabel = 'مرجوع شده'; + badgeColor = 'bg-gray-100 text-gray-700 border-gray-200'; + } + return ( + + {badgeLabel} + + ); + })()}
diff --git a/frontend/application/lib/store/cartStore.ts b/frontend/application/lib/store/cartStore.ts index 539d7ff2..68c2c591 100644 --- a/frontend/application/lib/store/cartStore.ts +++ b/frontend/application/lib/store/cartStore.ts @@ -23,7 +23,7 @@ interface Order { charityDonation?: number; paymentMethod?: string; isRefill?: boolean; - status: 'processing' | 'shipped' | 'delivered'; + status: 'pending_payment' | 'processing' | 'packaged' | 'ready_to_ship' | 'shipped' | 'delivered' | 'cancelled' | 'refunded' | string; petId?: string; shippingAddress?: string; trackingNumber: string; @@ -128,7 +128,7 @@ export const useCartStore = create()( date: backendOrder.createdAt, total: Number(backendOrder.totalAmount), charityDonation: Number(backendOrder.charityDonation), - status: (['processing', 'shipped', 'delivered'].includes(backendOrder.status) ? backendOrder.status : 'processing') as Order['status'], + status: (backendOrder.status ? String(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}` @@ -153,7 +153,7 @@ export const useCartStore = create()( })) || [], total: Number(bo.totalAmount), charityDonation: Number(bo.charityDonation), - status: (['processing', 'shipped', 'delivered'].includes(String(bo.status)) ? bo.status : 'processing') as Order['status'], + status: (bo.status ? String(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),