fix(all): auto-create ticket tables, multi-tier otp rate limiting, packaged order status & badges, pet kindness footprint
Deploy Canina / deploy (push) Successful in 1m46s

This commit is contained in:
parsa aghaei committed 2026-08-16 19:19:20 +03:30
1 parent d9254e9b01
commit 884b0486cc
8 files changed
+239 -24

No files matched your search

+55 -1
View File
@@ -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,
};
}
+56
View File
@@ -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() {
+4
View File
@@ -40,4 +40,8 @@ export class RedisService implements OnModuleInit, OnModuleDestroy {
}
return count;
}
async ttl(key: string): Promise<number> {
return this.client.ttl(key);
}
}
+44 -7
View File
@@ -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<string, { label: string; color: string; icon: React.E
pending_payment: { label: 'در انتظار پرداخت / ناموفق', color: 'bg-rose-100 text-rose-800 border-rose-200', icon: Clock },
pending: { label: 'در حال بررسی', color: 'bg-orange-100 text-orange-700 border-orange-200', icon: Clock },
processing: { label: 'در حال پردازش', color: 'bg-amber-100 text-amber-800 border-amber-200', icon: Clock },
packaged: { label: 'بسته‌بندی شده (آماده ارسال)', color: 'bg-purple-100 text-purple-800 border-purple-200', icon: PackageCheck },
ready_to_ship: { label: 'آماده ارسال', color: 'bg-purple-100 text-purple-800 border-purple-200', icon: PackageCheck },
shipped: { label: 'ارسال شده', color: 'bg-blue-100 text-blue-700 border-blue-200', icon: Truck },
delivered: { label: 'تحویل داده شده', color: 'bg-green-100 text-green-700 border-green-200', icon: CheckCircle2 },
cancelled: { label: 'لغو شده', color: 'bg-red-100 text-red-700 border-red-200', icon: XCircle },
};
const getPaymentMethodLabel = (method?: string): { label: string; color: string } => {
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() {
<option value="">همه وضعیت‌ها</option>
<option value="pending_payment">در انتظار پرداخت / ناموفق</option>
<option value="processing">در حال پردازش</option>
<option value="packaged">بسته‌بندی شده (آماده ارسال)</option>
<option value="shipped">ارسال شده</option>
<option value="delivered">تحویل داده شده</option>
<option value="cancelled">لغو شده</option>
@@ -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 (
<tr key={order.id} className="hover:bg-gray-50/50 transition-colors">
<td className="py-4 px-6 font-bold text-purple-600 font-mono" dir="ltr">
<div>{toPersianDigits(displayCode)}</div>
{order.isRefill && (
<span className="inline-block mt-1 text-[9px] font-black px-2 py-0.5 rounded-full bg-green-50 text-green-700 border border-green-200">
Refill 5%
<div className="flex flex-wrap gap-1 mt-1.5" dir="rtl">
<span className={`text-[9px] font-black px-2 py-0.5 rounded-md border flex items-center gap-1 ${payInfo.color}`}>
<CreditCard className="w-2.5 h-2.5" />
{payInfo.label}
</span>
)}
{order.isRefill && (
<span className="text-[9px] font-black px-2 py-0.5 rounded-md bg-emerald-50 text-emerald-700 border border-emerald-200">
تمدید ۵٪-
</span>
)}
{charityAmt > 0 && (
<span className="text-[9px] font-black px-2 py-0.5 rounded-md bg-rose-50 text-rose-700 border border-rose-200 flex items-center gap-1">
<Heart className="w-2.5 h-2.5 fill-rose-500 text-rose-500" />
مهربانی: {toPersianDigits(charityAmt.toLocaleString())} ت
</span>
)}
</div>
</td>
<td className="py-4 px-6">
<div className="font-bold text-gray-900">{customerName}</div>
<div className="text-xs text-gray-400 font-medium" dir="ltr">{toPersianDigits(order.user?.phone || '')}</div>
<div className="text-xs text-gray-400 font-medium" dir="ltr">{toPersianDigits(order.user?.phone || order.user?.mobile || '')}</div>
</td>
<td className="py-4 px-6 font-black text-gray-900">
{toPersianDigits(totalAmt.toLocaleString())} <span className="text-xs font-normal">تومان</span>
@@ -477,6 +512,7 @@ export default function Orders() {
>
<option value="pending_payment">در انتظار پرداخت / ناموفق</option>
<option value="processing">در حال پردازش</option>
<option value="packaged">بسته‌بندی شده (آماده ارسال)</option>
<option value="shipped">ارسال شده</option>
<option value="delivered">تحویل داده شده</option>
<option value="cancelled">لغو شده</option>
@@ -590,6 +626,7 @@ export default function Orders() {
>
<option value="pending_payment">در انتظار پرداخت / ناموفق</option>
<option value="processing">در حال پردازش</option>
<option value="packaged">بسته‌بندی شده (آماده ارسال)</option>
<option value="shipped">ارسال شده</option>
<option value="delivered">تحویل داده شده</option>
<option value="cancelled">لغو شده</option>
@@ -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 <CheckCircle2 className="w-5 h-5 text-green-500" />;
case 'shipped': return <Truck className="w-5 h-5 text-blue-500" />;
default: return <Clock className="w-5 h-5 text-orange-500" />;
case 'packaged':
case 'ready_to_ship': return <PackageCheck className="w-5 h-5 text-purple-600" />;
case 'cancelled': return <XCircle className="w-5 h-5 text-red-500" />;
case 'pending_payment': return <AlertCircle className="w-5 h-5 text-rose-500" />;
default: return <Clock className="w-5 h-5 text-amber-500" />;
}
};
@@ -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 'در حال پردازش';
}
};
+27 -7
View File
@@ -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<Omit<GlobalPetProfile, "id">>({
name: "",
@@ -748,20 +756,32 @@ export default function PetProfile({ initialView }: {
<Heart className="w-6 h-6 fill-white" />
</div>
<div>
<h3 className="text-xl font-black text-medical-gray-900 italic">ردپای مهربانی</h3>
<h3 className="text-xl font-black text-medical-gray-900 italic">ردپای مهربانی {activePet.name}</h3>
<p className="text-[10px] font-black text-pink-500 uppercase tracking-widest mt-1">سفیر مهربانی: {activePet.name}</p>
</div>
</div>
<div className="space-y-4 relative z-10">
<p className="text-sm text-medical-gray-600 font-medium leading-relaxed">
{activePet.name} با خریدهای مکمل خود، تا کنون به تامین هزینه‌های درمانی و تغذیه حیوانات پناهگاهی کمک کرده است.
</p>
<div className="bg-white/80 backdrop-blur-sm rounded-2xl p-4 border border-pink-100">
<div className="bg-white/90 backdrop-blur-sm rounded-2xl p-4 border border-pink-100 space-y-2.5">
<div className="flex items-center justify-between">
<span className="text-[10px] font-black text-medical-gray-400">سطح مشارکت</span>
<span className="text-sm font-black text-pink-500 italic">حامی وفادار</span>
<span className="text-xs font-bold text-medical-gray-500">کمک اهدایی با نام {activePet.name}:</span>
<span className="text-sm font-black text-pink-600 font-mono">
{toPersian(petCharityTotal.toLocaleString())} <span className="text-[10px] font-normal">تومان</span>
</span>
</div>
{allCharityTotal > 0 && (
<div className="flex items-center justify-between text-[11px] font-bold text-medical-gray-400 pt-2 border-t border-pink-50">
<span>مجموع مهربانی کل حساب:</span>
<span>{toPersian(allCharityTotal.toLocaleString())} تومان</span>
</div>
)}
</div>
<p className="text-xs text-medical-gray-600 font-medium leading-relaxed">
{petCharityTotal > 0 ? (
<>«{activePet.name}» با خریدهای مکمل خود تا کنون <strong className="text-pink-600">{toPersian(petCharityTotal.toLocaleString())} تومان</strong> به درمان و تغذیه حیوانات نیازمند پناهگاهی کمک کرده است.</>
) : (
<>با هر خرید برای «{activePet.name}» می‌توانید با انتخاب گزینه ردپای مهربانی، مبلغی را به نام او به پناهگاه‌های حیوانات اختصاص دهید.</>
)}
</p>
</div>
</div>
</section>
@@ -826,15 +826,47 @@ export default function UserDashboard() {
</div>
<div className="text-left">
<div className="text-lg font-black text-medical-gray-900 italic">{toPersian(order.total.toLocaleString())} <span className="text-xs">تومان</span></div>
<div className="flex items-center gap-2 justify-end mt-1">
<div className="flex flex-wrap items-center gap-2 justify-end mt-1.5">
{order.isRefill && (
<span className="text-[9px] font-black px-2 py-0.5 rounded-full bg-emerald-50 text-emerald-600 border border-emerald-100">
تمدید خودکار ۵٪-
</span>
)}
<span className={`text-[9px] font-black px-2.5 py-0.5 rounded-full uppercase tracking-tighter ${order.status === 'delivered' ? 'bg-green-50 text-green-600' : order.status === 'shipped' ? 'bg-blue-50 text-blue-600' : 'bg-amber-50 text-amber-600'}`}>
{order.status === 'delivered' ? 'تحویل شده' : order.status === 'shipped' ? 'ارسال شده' : 'در حال پردازش'}
</span>
{Number(order.charityDonation) > 0 && (
<span className="text-[9px] font-black px-2 py-0.5 rounded-full bg-rose-50 text-rose-600 border border-rose-100 flex items-center gap-1">
<Heart className="w-2.5 h-2.5 fill-rose-500 text-rose-500" />
مهربانی: {toPersian(Number(order.charityDonation).toLocaleString())} ت
</span>
)}
{(() => {
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 (
<span className={`text-[9px] font-black px-2.5 py-0.5 rounded-full border uppercase tracking-tighter ${badgeColor}`}>
{badgeLabel}
</span>
);
})()}
<ChevronRight className="w-4 h-4 text-medical-gray-300 -rotate-180" />
</div>
</div>
+3 -3
View File
@@ -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<CartStore>()(
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<CartStore>()(
})) || [],
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),