Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 32x 32x 32x 32x 32x 2x 2x 2x 2x 2x 1x 1x 1x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2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | /**
* Inventory Management Utilities
* Handles stock tracking, movement history, and low stock alerts
*/
import { prisma } from '@/lib/prisma';
import { notifyWishlistUsersBackInStock } from '@/lib/notifications';
import { logger } from '@/lib/logging';
export interface InventoryMovement {
id: number;
productId: number;
type: "in" | "out" | "adjustment";
quantity: number;
reason?: string;
notes?: string;
date: Date;
createdBy?: string;
}
export interface StockAlert {
productId: number;
productTitle: string;
currentStock: number;
reorderLevel: number;
needsReorder: boolean;
}
export interface InventorySummary {
totalProducts: number;
totalStockValue: number;
lowStockCount: number;
outOfStockCount: number;
totalStockQuantity: number;
}
/**
* Get or create inventory record for a product
*/
export async function getOrCreateInventory(productId: number) {
let inventory = await prisma.inventory.findUnique({
where: { productId },
include: { product: true }});
if (!inventory) {
// Get current stock from product
const product = await prisma.product.findUnique({
where: { id: productId }});
if (!product) {
throw new Error(`Product with ID ${productId} not found`);
}
// Create inventory record based on product's stock
inventory = await prisma.inventory.create({
data: {
productId,
quantity: product.stock,
reorderLevel: 10, // Default reorder level
},
include: { product: true }});
}
return inventory;
}
/**
* Record a stock movement (in, out, or adjustment)
*/
export async function recordStockMovement(
productId: number,
type: "in" | "out" | "adjustment",
quantity: number,
reason?: string,
notes?: string,
createdBy?: string
): Promise<InventoryMovement> {
// Validate quantity
if (quantity <= 0) {
throw new Error('Quantity must be greater than 0');
}
// Get or create inventory
const inventory = await getOrCreateInventory(productId);
// Calculate new quantity
let newQuantity = inventory.quantity;
if (type === 'in') {
newQuantity += quantity;
} else if (type === 'out') {
newQuantity -= quantity;
if (newQuantity < 0) {
throw new Error('Insufficient stock. Cannot have negative inventory.');
}
} else if (type === 'adjustment') {
// Adjustment sets the stock to a specific quantity
newQuantity = quantity;
}
// Use transaction to ensure atomicity
const [movement] = await prisma.$transaction([
// Create stock movement record
prisma.stockMovement.create({
data: {
productId,
type,
quantity,
reason,
notes,
createdBy}}),
// Update inventory
prisma.inventory.update({
where: { productId },
data: {
quantity: newQuantity,
...(type === 'in' ? { lastRestocked: new Date() } : {})}}),
// Sync stock with product table
prisma.product.update({
where: { id: productId },
data: { stock: newQuantity }}),
]);
// Check if product went from out of stock to in stock
if (type === 'in' && inventory.quantity === 0 && newQuantity > 0) {
// Product is now back in stock - notify wishlist users asynchronously
void notifyWishlistUsersBackInStock(productId).catch((error) => {
logger.error('Failed to notify wishlist users', error instanceof Error ? error : new Error(String(error)), { category: 'INVENTORY' });
});
}
return {
id: movement.id,
productId: movement.productId,
type: movement.type as "in" | "out" | "adjustment",
quantity: movement.quantity,
reason: movement.reason || undefined,
notes: movement.notes || undefined,
date: movement.date,
createdBy: movement.createdBy || undefined};
}
/**
* Get stock movement history for a product
*/
export async function getStockMovementHistory(
productId: number,
limit: number = 50
): Promise<InventoryMovement[]> {
const movements = await prisma.stockMovement.findMany({
where: { productId },
orderBy: { date: 'desc' },
take: limit});
return movements.map(m => ({
id: m.id,
productId: m.productId,
type: m.type as "in" | "out" | "adjustment",
quantity: m.quantity,
reason: m.reason || undefined,
notes: m.notes || undefined,
date: m.date,
createdBy: m.createdBy || undefined}));
}
/**
* Decrease stock when an order is placed
*/
export async function decreaseStockOnOrder(
productId: number,
quantity: number,
orderId: number
): Promise<InventoryMovement> {
return recordStockMovement(
productId,
'out',
quantity,
'Order placed',
`Order ID: ${orderId}`,
'system'
);
}
/**
* Increase stock when an order is returned
*/
export async function increaseStockOnReturn(
productId: number,
quantity: number,
orderId: number
): Promise<InventoryMovement> {
return recordStockMovement(
productId,
'in',
quantity,
'Order return',
`Return for Order ID: ${orderId}`,
'system'
);
}
/**
* Get products with low stock that need reordering
*/
export async function getLowStockAlerts(): Promise<StockAlert[]> {
// Fetch all inventories and filter in-memory
// This is necessary because Prisma doesn't support comparing columns in where clause
const inventories = await prisma.inventory.findMany({
include: {
product: {
select: {
id: true,
title: true}}},
orderBy: {
quantity: 'asc'}});
// Filter to only include products at or below reorder level
const lowStockItems = inventories.filter(inv => inv.quantity <= inv.reorderLevel);
return lowStockItems.map(inv => ({
productId: inv.productId,
productTitle: inv.product.title,
currentStock: inv.quantity,
reorderLevel: inv.reorderLevel,
needsReorder: true}));
}
/**
* Check if a product is in stock
*/
export async function isProductInStock(productId: number): Promise<boolean> {
const inventory = await getOrCreateInventory(productId);
return inventory.quantity > 0;
}
/**
* Get current stock quantity for a product
*/
export async function getProductStock(productId: number): Promise<number> {
const inventory = await getOrCreateInventory(productId);
return inventory.quantity;
}
/**
* Update the reorder level for a product
*/
export async function updateReorderLevel(
productId: number,
reorderLevel: number
): Promise<void> {
if (reorderLevel < 0) {
throw new Error('Reorder level must be 0 or greater');
}
await prisma.inventory.upsert({
where: { productId },
update: { reorderLevel },
create: {
productId,
quantity: 0,
reorderLevel}});
}
/**
* Bulk update stock for multiple products
*/
export async function bulkUpdateStock(
updates: Array<{ productId: number; quantity: number }>
): Promise<{ updated: number; errors: Array<{ productId: number; error: string }> }> {
const errors: Array<{ productId: number; error: string }> = [];
let updated = 0;
for (const { productId, quantity } of updates) {
try {
if (quantity < 0) {
throw new Error('Quantity cannot be negative');
}
await recordStockMovement(
productId,
'adjustment',
quantity,
'Bulk update',
'Stock level adjusted via bulk update',
'admin'
);
updated++;
} catch (error) {
errors.push({
productId,
error: error instanceof Error ? error.message : 'Unknown error'});
}
}
return { updated, errors };
}
/**
* Get inventory summary statistics
*/
export async function getInventorySummary(): Promise<InventorySummary> {
const [inventories, products] = await Promise.all([
prisma.inventory.findMany({
include: {
product: {
select: {
price: true,
discountedPrice: true}}}}),
prisma.product.count(),
]);
const totalStockQuantity = inventories.reduce((sum, inv) => sum + inv.quantity, 0);
const totalStockValue = inventories.reduce(
(sum, inv) => sum + inv.quantity * inv.product.discountedPrice,
0
);
const lowStockCount = inventories.filter(inv => inv.quantity <= inv.reorderLevel).length;
const outOfStockCount = inventories.filter(inv => inv.quantity === 0).length;
return {
totalProducts: products,
totalStockValue,
lowStockCount,
outOfStockCount,
totalStockQuantity};
}
/**
* Sync inventory quantity with product stock
* Useful for maintaining consistency
*/
export async function syncInventoryWithProducts(): Promise<{ synced: number }> {
const products = await prisma.product.findMany({
select: { id: true, stock: true }});
let synced = 0;
for (const product of products) {
await prisma.inventory.upsert({
where: { productId: product.id },
update: { quantity: product.stock },
create: {
productId: product.id,
quantity: product.stock,
reorderLevel: 10}});
synced++;
}
return { synced };
}
/**
* Get products that are out of stock
*/
export async function getOutOfStockProducts(): Promise<Array<{
productId: number;
productTitle: string;
sku: string | null;
}>> {
const inventories = await prisma.inventory.findMany({
where: { quantity: 0 },
include: {
product: {
select: {
id: true,
title: true,
sku: true}}}});
return inventories.map(inv => ({
productId: inv.productId,
productTitle: inv.product.title,
sku: inv.product.sku}));
}
/**
* Reserve stock for an order (marks as pending)
* This prevents overselling during checkout process
*/
export async function reserveStock(
productId: number,
quantity: number,
orderId: number
): Promise<void> {
const inventory = await getOrCreateInventory(productId);
if (inventory.quantity < quantity) {
throw new Error('Insufficient stock to reserve');
}
// Record as a stock movement with reservation note
await recordStockMovement(
productId,
'out',
quantity,
'Stock reserved',
`Reserved for Order ID: ${orderId}`,
'system'
);
}
/**
* Release reserved stock (if order is cancelled)
*/
export async function releaseReservedStock(
productId: number,
quantity: number,
orderId: number
): Promise<void> {
await recordStockMovement(
productId,
'in',
quantity,
'Reservation released',
`Released from Order ID: ${orderId}`,
'system'
);
}
|