feat(inventory): implement numeric stock inventory across fullstack and improve prescription UX handoff
Deploy Canina / deploy (push) Failing after 2m31s
E2E Playwright Tests / Run Full E2E & Security Suites (push) Failing after 7s

This commit is contained in:
devops committed 2026-10-12 19:29:48 +00:00
1 parent e9582430e6
commit 741365f04c
13 files changed
+177 -47

No files matched your search

+1
View File
@@ -230,6 +230,7 @@ model Product {
metaDescription String? @map("meta_description") @db.Text
canonicalUrl String? @map("canonical_url") @db.Text
keywords String? @db.Text
stock Int @default(100) @map("stock")
stockStatus StockStatus @default(IN_STOCK) @map("stock_status")
noIndex Boolean @default(false) @map("no_index")
noFollow Boolean @default(false) @map("no_follow")
+9 -2
View File
@@ -581,7 +581,8 @@ export class AdminService {
metaDescription: data.metaDescription || '',
keywords: data.keywords || '',
canonicalUrl: data.canonicalUrl || '',
stockStatus: data.stockStatus || 'IN_STOCK',
stock: data.stock !== undefined ? Number(data.stock) : (data.stockStatus === 'OUT_OF_STOCK' ? 0 : 100),
stockStatus: data.stockStatus || (data.stock !== undefined && Number(data.stock) <= 0 ? 'OUT_OF_STOCK' : 'IN_STOCK'),
noIndex: data.noIndex ?? false,
noFollow: data.noFollow ?? false,
ogImage: data.ogImage || null,
@@ -761,8 +762,14 @@ export class AdminService {
metaDescription: data.metaDescription,
keywords: data.keywords,
canonicalUrl: data.canonicalUrl,
stock:
data.stock !== undefined ? Number(data.stock) : undefined,
stockStatus:
data.stockStatus !== undefined ? data.stockStatus : undefined,
data.stockStatus !== undefined
? data.stockStatus
: (data.stock !== undefined
? (Number(data.stock) <= 0 ? 'OUT_OF_STOCK' : 'IN_STOCK')
: undefined),
noIndex: data.noIndex !== undefined ? data.noIndex : undefined,
noFollow: data.noFollow !== undefined ? data.noFollow : undefined,
ogImage: data.ogImage !== undefined ? data.ogImage : undefined,
+5
View File
@@ -241,6 +241,11 @@ export class ProductDto {
@IsString()
stockStatus?: 'IN_STOCK' | 'OUT_OF_STOCK' | 'PRE_ORDER' | 'DISCONTINUED';
@ApiPropertyOptional({ description: 'تعداد موجودی در انبار' })
@IsOptional()
@IsNumber()
stock?: number;
@ApiPropertyOptional({ description: 'عدم ایندکس توسط موتورهای جستجو' })
@IsOptional()
@IsBoolean()
+66 -23
View File
@@ -141,18 +141,23 @@ export class OrdersService {
const productMap = new Map(products.map((p) => [p.id, p]));
for (const productId of productIds) {
const product = productMap.get(productId);
for (const item of createOrderDto.items) {
const product = productMap.get(item.productId);
if (!product) {
throw new NotFoundException(`محصول یافت نشد`);
}
const isOutOfStock =
product.stockStatus === 'OUT_OF_STOCK' ||
product.stockStatus === 'DISCONTINUED' ||
(product.packageSize !== null && Number(product.packageSize) <= 0);
product.stock <= 0;
if (isOutOfStock) {
throw new BadRequestException(
`محصول «${product.nameFa || product.name}» در حال حاضر ناموجود است و امکان ثبت سفارش آن وجود ندارد`,
`محصول «${product.nameFa || (product as any).name}» در حال حاضر ناموجود است و امکان ثبت سفارش آن وجود ندارد`,
);
}
if (item.quantity > product.stock) {
throw new BadRequestException(
`تعداد درخواستی برای محصول «${product.nameFa || (product as any).name}» (${item.quantity} عدد) بیشتر از موجودی انبار (${product.stock} عدد) است`,
);
}
}
@@ -272,6 +277,22 @@ export class OrdersService {
.catch(() => {});
}
// Deduct inventory atomically for wallet orders
for (const item of createOrderDto.items) {
const updated = await tx.product.update({
where: { id: item.productId },
data: {
stock: { decrement: item.quantity },
},
});
if (updated.stock <= 0) {
await tx.product.update({
where: { id: item.productId },
data: { stockStatus: 'OUT_OF_STOCK' },
});
}
}
return newOrder;
});
@@ -289,27 +310,49 @@ export class OrdersService {
const isOnline = createOrderDto.paymentMethod === 'online';
const initialStatus = isOnline ? 'pending_payment' : 'processing';
const createdOrder = await this.prisma.order.create({
data: {
userId,
couponId,
totalAmount: Number(finalAmount),
charityDonation: Number(charityAmount),
isRefill: Boolean(createOrderDto.isRefill),
refillIntervalDays: createOrderDto.refillIntervalDays || 60,
trackingNumber,
status: initialStatus,
paymentMethod: createOrderDto.paymentMethod || 'card',
shippingAddress: createOrderDto.shippingAddress,
orderItems: {
create: orderItemsData,
const createdOrder = await this.prisma.$transaction(async (tx) => {
const order = await tx.order.create({
data: {
userId,
couponId,
totalAmount: Number(finalAmount),
charityDonation: Number(charityAmount),
isRefill: Boolean(createOrderDto.isRefill),
refillIntervalDays: createOrderDto.refillIntervalDays || 60,
trackingNumber,
status: initialStatus,
paymentMethod: createOrderDto.paymentMethod || 'card',
shippingAddress: createOrderDto.shippingAddress,
orderItems: {
create: orderItemsData,
},
},
},
include: {
orderItems: {
include: { product: true },
include: {
orderItems: {
include: { product: true },
},
},
},
});
// Deduct inventory immediately for non-online orders (card to card)
if (!isOnline) {
for (const item of createOrderDto.items) {
const updated = await tx.product.update({
where: { id: item.productId },
data: {
stock: { decrement: item.quantity },
},
});
if (updated.stock <= 0) {
await tx.product.update({
where: { id: item.productId },
data: { stockStatus: 'OUT_OF_STOCK' },
});
}
}
}
return order;
});
// Send Order Confirmation SMS (for card-to-card or non-online orders, online orders get SMS on verify)
+25 -1
View File
@@ -433,12 +433,36 @@ export class PaymentService {
},
});
// Mark inventory reservations as CONSUMED
// Mark inventory reservations as CONSUMED and decrement product stock
await tx.inventoryReservation.updateMany({
where: { orderId: transaction.orderId, status: 'ACTIVE' },
data: { status: 'CONSUMED' },
});
const orderWithItems = await tx.order.findUnique({
where: { id: transaction.orderId },
include: { orderItems: true },
});
if (orderWithItems?.orderItems) {
for (const item of orderWithItems.orderItems) {
if (item.productId) {
const updated = await tx.product.update({
where: { id: item.productId },
data: {
stock: { decrement: item.quantity },
},
});
if (updated.stock <= 0) {
await tx.product.update({
where: { id: item.productId },
data: { stockStatus: 'OUT_OF_STOCK' },
});
}
}
}
}
// If charity donation was made, update user's total charity
if (
transaction.order &&
+1 -1
View File
@@ -187,7 +187,7 @@ export class TorobController {
const isInStock =
product.stockStatus !== 'DISCONTINUED' &&
product.stockStatus !== 'OUT_OF_STOCK' &&
(product.packageSize === null || Number(product.packageSize) > 0) &&
(product.stock === undefined || product.stock > 0) &&
String(product.stockStatus || '')
.toLowerCase()
.includes('in');
+35 -8
View File
@@ -96,6 +96,7 @@ export interface Product {
keywords?: string;
canonicalUrl?: string;
slug?: string;
stock?: number;
stockStatus?: 'IN_STOCK' | 'OUT_OF_STOCK' | 'PRE_ORDER' | 'DISCONTINUED';
noIndex?: boolean;
noFollow?: boolean;
@@ -249,6 +250,7 @@ export default function Products() {
priceDisplay: '',
unit: '',
packageSize: '' as number | string,
stock: '' as number | string,
dosageLogic: '',
suitableFor: 'سگ و گربه',
imageUrl: '',
@@ -518,6 +520,7 @@ export default function Products() {
priceDisplay: product.priceDisplay || '',
unit: product.unit || '',
packageSize: product.packageSize !== undefined && product.packageSize !== null ? Number(product.packageSize) : '',
stock: product.stock !== undefined && product.stock !== null ? Number(product.stock) : (product.stockStatus === 'OUT_OF_STOCK' ? 0 : 100),
dosageLogic: product.dosageLogic || '',
feedingAdvice: dosageConfig.feedingAdvice || product.feedingAdvice || product.dosageLogic || '',
showFaqs: dosageConfig.showFaqs !== undefined ? Boolean(dosageConfig.showFaqs) : (product.showFaqs !== undefined ? Boolean(product.showFaqs) : true),
@@ -576,7 +579,7 @@ export default function Products() {
wholesaleMarginPercent: pricingSettings.defaultWholesaleMarginPercent,
roundingStep: '',
roundingMode: '',
priceDisplay: '', unit: '', packageSize: '', dosageLogic: '',
priceDisplay: '', unit: '', packageSize: '', stock: '', dosageLogic: '',
feedingAdvice: '',
showFaqs: true,
faqs: [],
@@ -906,7 +909,8 @@ export default function Products() {
roundingMode: formData.roundingMode || null,
priceDisplay: formData.priceDisplay || `${Number(formData.priceValue || 0).toLocaleString('fa-IR')} تومان`,
unit: (formData.unit || '').trim() || undefined,
packageSize: Number(formData.packageSize) || 0,
packageSize: formData.packageSize !== '' ? Number(formData.packageSize) : 100,
stock: formData.stock !== '' ? Number(formData.stock) : (formData.stockStatus === 'OUT_OF_STOCK' ? 0 : 100),
dosageLogic: (formData.dosageLogic || '').trim() || undefined,
suitableFor: formData.suitableFor || 'سگ و گربه',
imageUrl: (formData.imageUrl || '').trim() || undefined,
@@ -927,7 +931,7 @@ export default function Products() {
metaDescription: (formData.metaDescription || '').trim() || formData.shortDescription || 'خرید آنلاین مکمل اصل کنینا آلمان با بالاترین کیفیت بالینی...',
keywords: (formData.keywords || '').trim() || undefined,
canonicalUrl: (formData.canonicalUrl || '').trim() || `/shop/${derivedSlug}`,
stockStatus: (Number(formData.packageSize) <= 0) ? 'OUT_OF_STOCK' : (formData.stockStatus || 'IN_STOCK'),
stockStatus: (formData.stock !== '' && Number(formData.stock) <= 0) ? 'OUT_OF_STOCK' : (formData.stockStatus || 'IN_STOCK'),
noIndex: Boolean(formData.noIndex),
noFollow: Boolean(formData.noFollow),
ogImage: (formData.ogImage || '').trim() || undefined,
@@ -1303,7 +1307,14 @@ export default function Products() {
<td className="py-4 px-6">
<div className="flex flex-col">
<span className="font-bold text-gray-900">{Number(product.priceValue).toLocaleString()} تومان</span>
<span className="text-xs text-gray-500">{product.packageSize} موجودی</span>
<div className="flex items-center gap-1.5 mt-0.5">
<span className={`text-xs font-bold ${Number(product.stock ?? 100) > 0 ? 'text-emerald-600' : 'text-rose-600'}`}>
{product.stock !== undefined ? `${product.stock} عدد موجود` : (product.stockStatus === 'OUT_OF_STOCK' ? 'ناموجود' : 'موجود')}
</span>
{product.packageSize && (
<span className="text-[11px] text-gray-400 font-mono">({product.packageSize} {product.unit || 'واحد'})</span>
)}
</div>
</div>
</td>
<td className="py-4 px-6 text-center">
@@ -2822,23 +2833,39 @@ export default function Products() {
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 pt-2">
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 pt-2">
<div className="space-y-2">
<label className="text-sm font-bold text-gray-700">موجودی *</label>
<label className="text-sm font-bold text-gray-700">تعداد موجودی انبار *</label>
<input
required
type="number"
min="0"
placeholder="0"
placeholder="100"
value={formData.stock === '' ? '' : formData.stock}
onChange={(e) => setFormData({ ...formData, stock: e.target.value === '' ? '' : Number(e.target.value) })}
className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-left font-mono font-bold"
dir="ltr"
/>
<span className="text-[11px] text-gray-400">تعداد فیزیکی کالا برای خرید و کنترل سقف سفارش</span>
</div>
<div className="space-y-2">
<label className="text-sm font-bold text-gray-700">حجم / وزن بسته *</label>
<input
required
type="number"
min="0"
placeholder="مثال: 75 یا 250"
value={formData.packageSize === '' ? '' : formData.packageSize}
onChange={(e) => setFormData({ ...formData, packageSize: e.target.value === '' ? '' : Number(e.target.value) })}
className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-left font-mono font-bold"
dir="ltr"
/>
<span className="text-[11px] text-gray-400">جهت محاسبه روز مصرف و سئو</span>
</div>
<div className="space-y-2">
<label className="text-sm font-bold text-gray-700">واحد سنجش</label>
<input type="text" placeholder="مثال: عدد / بسته" value={formData.unit} onChange={(e) => setFormData({ ...formData, unit: e.target.value })} className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-sm" />
<input type="text" placeholder="مثال: گرم / قرص / میلی‌لیتر" value={formData.unit} onChange={(e) => setFormData({ ...formData, unit: e.target.value })} className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-sm" />
<span className="text-[11px] text-gray-400">واحد بسته (گرم، قرص، میلی‌لیتر)</span>
</div>
</div>
+7 -1
View File
@@ -231,7 +231,13 @@ export default function ClientLayout({ children }: { children: React.ReactNode }
onClose={() => setIsPrescriptionModalOpen(false)}
/>
<MobileBottomNav
onPrescriptionOpen={() => setIsPrescriptionModalOpen(true)}
onPrescriptionOpen={() => {
if (!isLoggedIn) {
setAuthModalOpen(true);
} else {
setIsPrescriptionModalOpen(true);
}
}}
/>
<Toaster position="top-center" expand={true} richColors closeButton />
</>
@@ -122,10 +122,10 @@ export default async function ShopProductPage({ params }: { params: Promise<{ sl
const productUrl = `${siteUrl}/shop/${resolvedParams.slug}`;
const priceInRial = product.priceValue * 10;
// Map stock status and packageSize to Schema.org availability
// Map stock status and stock quantity to Schema.org availability
const isOutOfStock =
product.stockStatus === 'OUT_OF_STOCK' ||
(typeof product.packageSize === 'number' && product.packageSize <= 0);
(typeof product.stock === 'number' && product.stock <= 0);
let availabilityUrl = 'https://schema.org/InStock';
if (product.stockStatus === 'DISCONTINUED') {
+12 -2
View File
@@ -250,7 +250,13 @@ export default function Header({
{/* Prescription Upload Button (Desktop & Mobile) */}
{isPrescriptionEnabled && (
<button
onClick={() => setIsPrescriptionModalOpen(true)}
onClick={() => {
if (!isLoggedIn) {
setIsAuthModalOpen(true);
} else {
setIsPrescriptionModalOpen(true);
}
}}
className="flex items-center gap-1.5 px-2.5 sm:px-3 py-2 bg-emerald-50 text-emerald-700 border border-emerald-200 hover:bg-emerald-100 rounded-xl text-[11px] sm:text-xs font-black transition-all shadow-xs cursor-pointer"
title="ثبت نسخه دامپزشک"
>
@@ -545,7 +551,11 @@ export default function Header({
type="button"
onClick={() => {
setIsMobileMenuOpen(false);
setIsPrescriptionModalOpen(true);
if (!isLoggedIn) {
setIsAuthModalOpen(true);
} else {
setIsPrescriptionModalOpen(true);
}
}}
className="w-full flex items-center justify-between p-3.5 bg-gradient-to-r from-emerald-500 to-teal-600 text-white rounded-2xl font-black text-xs shadow-md shadow-emerald-500/20 hover:brightness-105 transition-all cursor-pointer font-vazir"
>
@@ -348,17 +348,17 @@ export default function PrescriptionUploadModal({ isOpen, onClose }: Prescriptio
{/* Phone Number */}
<div>
<label className="block text-xs font-black text-medical-gray-700 mb-1">
شماره همراه جهت هماهنگی و پیامک تایید *
شماره همراه جهت هماهنگی و پیامک تایید
</label>
<div className="relative">
<input
type="tel"
dir="ltr"
required
readOnly={isLoggedIn && !!profile?.mobile}
placeholder="۰۹۱۲۳۴۵۶۷۸۹"
value={phone}
onChange={(e) => setPhone(e.target.value)}
className="w-full bg-white border border-medical-gray-200 rounded-xl py-2.5 pr-3 pl-11 text-xs font-mono font-bold text-medical-gray-900 focus:outline-none focus:ring-2 focus:ring-canina-blue/20"
className={`w-full border border-medical-gray-200 rounded-xl py-2.5 pr-3 pl-11 text-xs font-mono font-bold text-medical-gray-900 focus:outline-none focus:ring-2 focus:ring-canina-blue/20 ${isLoggedIn && profile?.mobile ? 'bg-medical-gray-100 text-medical-gray-600 cursor-not-allowed' : 'bg-white'}`}
/>
<Phone className="w-4 h-4 text-medical-gray-400 absolute left-3.5 top-1/2 -translate-y-1/2 pointer-events-none" />
</div>
@@ -83,6 +83,7 @@ export interface Product {
metaDescription?: string;
canonicalUrl?: string;
keywords?: string;
stock?: number;
stockStatus?: 'IN_STOCK' | 'OUT_OF_STOCK' | 'PRE_ORDER' | 'DISCONTINUED';
noIndex?: boolean;
noFollow?: boolean;
+10 -4
View File
@@ -61,23 +61,26 @@ export const useCartStore = create<CartStore>()(
orders: [],
addItem: (product, quantity, dose) => {
// Prevent adding out-of-stock products
const maxStock = typeof product.stock === 'number' ? product.stock : (product.stockStatus === 'OUT_OF_STOCK' ? 0 : 999);
const isOutOfStock =
product.stockStatus === 'OUT_OF_STOCK' ||
product.stockStatus === 'DISCONTINUED' ||
(typeof product.packageSize === 'number' && product.packageSize <= 0);
maxStock <= 0;
if (isOutOfStock || quantity <= 0) {
return;
}
const items = get().items;
const existing = items.find((i) => i.product.id === product.id);
if (existing) {
const newQty = Math.min(existing.quantity + quantity, maxStock);
set({
items: items.map((i) =>
i.product.id === product.id ? { ...i, quantity: i.quantity + quantity } : i
i.product.id === product.id ? { ...i, quantity: newQty } : i
),
});
} else {
set({ items: [...items, { product, quantity, calculatedDose: dose }] });
const initialQty = Math.min(quantity, maxStock);
set({ items: [...items, { product, quantity: initialQty, calculatedDose: dose }] });
}
},
removeItem: (productId) => {
@@ -88,9 +91,12 @@ export const useCartStore = create<CartStore>()(
get().removeItem(productId);
return;
}
const currentItem = get().items.find((i) => i.product.id === productId);
const maxStock = currentItem && typeof currentItem.product.stock === 'number' ? currentItem.product.stock : 999;
const boundedQty = Math.min(quantity, maxStock);
set({
items: get().items.map((i) =>
i.product.id === productId ? { ...i, quantity } : i
i.product.id === productId ? { ...i, quantity: boundedQty } : i
),
});
},