import { PrismaClient } from '@prisma/client' import { PrismaLibSql } from '@prisma/adapter-libsql' const adapter = new PrismaLibSql({ url: 'file:dev.db', }) const prisma = new PrismaClient({ adapter }) async function main() { const items = await prisma.item.findMany({ include: { requests: { where: { status: 'approved_2' } } } }) let updatedCount = 0; for (const item of items) { let borrowedQty = 0; let trialQty = 0; let billedQty = 0; let soldQty = 0; let damagedQty = 0; for (const req of item.requests) { const qty = req.quantity; let type = req.type.toLowerCase(); if (type === 'manage service') type = 'billed'; if (type === 'outright purchase') type = 'outright_purchase'; if (type !== req.type) { await prisma.request.update({ where: { id: req.id }, data: { type } }); } // Borrowed if (type === 'borrow') borrowedQty += qty; if (type === 'return_borrow' || type === 'return_damaged_borrow') borrowedQty -= qty; // Trial if (type === 'trial') trialQty += qty; if (type === 'return_trial' || type === 'return_damaged_trial') trialQty -= qty; // Billed if (type === 'billed') billedQty += qty; if (type === 'return_billed' || type === 'return_damaged_billed') billedQty -= qty; // Sold if (type === 'outright_purchase') soldQty += qty; if (type === 'return_damaged_sold') soldQty -= qty; // Damaged if (type === 'return_damaged_borrow' || type === 'return_damaged_trial' || type === 'return_damaged_billed' || type === 'return_damaged_sold') { damagedQty += qty; } } borrowedQty = Math.max(0, borrowedQty); trialQty = Math.max(0, trialQty); billedQty = Math.max(0, billedQty); soldQty = Math.max(0, soldQty); damagedQty = Math.max(0, damagedQty); const availableQty = Math.max(0, item.totalQuantity - borrowedQty - trialQty - billedQty - damagedQty - soldQty); await prisma.item.update({ where: { id: item.id }, data: { borrowedQty, trialQty, billedQty, soldQty, damagedQty, availableQty } }) updatedCount++; } console.log(`Resynced ${updatedCount} items.`); } main() .catch(console.error) .finally(() => prisma.$disconnect())