Add SQL query for average cost retrieval and generate TriggerLog model

This commit is contained in:
2025-12-14 10:15:57 +03:30
parent 41d7dd8802
commit 9d7d94b5f8
45 changed files with 3742 additions and 440 deletions
@@ -0,0 +1,12 @@
/*
Warnings:
- You are about to alter the column `quantity` on the `Stock_Balance` table. The data in that column could be lost. The data in that column will be cast from `Decimal(65,30)` to `Decimal(10,2)`.
- You are about to alter the column `totalCost` on the `Stock_Balance` table. The data in that column could be lost. The data in that column will be cast from `Decimal(65,30)` to `Decimal(10,2)`.
- You are about to alter the column `avgCost` on the `Stock_Balance` table. The data in that column could be lost. The data in that column will be cast from `Decimal(65,30)` to `Decimal(10,2)`.
*/
-- AlterTable
ALTER TABLE `Stock_Balance` MODIFY `quantity` DECIMAL(10, 2) NOT NULL,
MODIFY `totalCost` DECIMAL(10, 2) NOT NULL,
MODIFY `avgCost` DECIMAL(10, 2) NOT NULL;
@@ -0,0 +1,21 @@
/*
Warnings:
- The primary key for the `Stock_Balance` table will be changed. If it partially fails, the table could be left without primary key constraint.
- You are about to drop the column `ProductId` on the `Stock_Balance` table. All the data in the column will be lost.
- Added the required column `inventoryId` to the `Stock_Balance` table without a default value. This is not possible if the table is not empty.
- Added the required column `productId` to the `Stock_Balance` table without a default value. This is not possible if the table is not empty.
*/
-- AlterTable
ALTER TABLE `Stock_Balance` DROP PRIMARY KEY,
DROP COLUMN `ProductId`,
ADD COLUMN `inventoryId` INTEGER NOT NULL,
ADD COLUMN `productId` INTEGER NOT NULL,
ADD PRIMARY KEY (`productId`);
-- AddForeignKey
ALTER TABLE `Stock_Balance` ADD CONSTRAINT `Stock_Balance_productId_fkey` FOREIGN KEY (`productId`) REFERENCES `Products`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Stock_Balance` ADD CONSTRAINT `Stock_Balance_inventoryId_fkey` FOREIGN KEY (`inventoryId`) REFERENCES `Inventories`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE `Inventories` ADD COLUMN `isPointOfSale` BOOLEAN NOT NULL DEFAULT false;
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE `Stock_Movements` MODIFY `referenceType` ENUM('PURCHASE', 'SALES', 'ADJUSTMENT', 'INVENTORY_TRANSFER') NOT NULL;
@@ -0,0 +1,77 @@
/*
Warnings:
- The primary key for the `Stock_Balance` table will be changed. If it partially fails, the table could be left without primary key constraint.
- You are about to alter the column `quantity` on the `Stock_Balance` table. The data in that column could be lost. The data in that column will be cast from `Decimal(10,2)` to `Decimal(14,3)`.
- You are about to alter the column `totalCost` on the `Stock_Balance` table. The data in that column could be lost. The data in that column will be cast from `Decimal(10,2)` to `Decimal(14,2)`.
- You are about to alter the column `avgCost` on the `Stock_Balance` table. The data in that column could be lost. The data in that column will be cast from `Decimal(10,2)` to `Decimal(14,2)`.
- A unique constraint covering the columns `[productId,inventoryId]` on the table `Stock_Balance` will be added. If there are existing duplicate values, this will fail.
- Added the required column `id` to the `Stock_Balance` table without a default value. This is not possible if the table is not empty.
*/
-- DropForeignKey
ALTER TABLE `Stock_Balance` DROP FOREIGN KEY `Stock_Balance_inventoryId_fkey`;
-- DropForeignKey
ALTER TABLE `Stock_Balance` DROP FOREIGN KEY `Stock_Balance_productId_fkey`;
-- AlterTable
ALTER TABLE `Products` ADD COLUMN `stockBalanceId` INTEGER NULL;
-- AlterTable
ALTER TABLE `Stock_Balance` DROP PRIMARY KEY,
ADD COLUMN `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
ADD COLUMN `id` INTEGER NOT NULL AUTO_INCREMENT,
MODIFY `quantity` DECIMAL(14, 3) NOT NULL DEFAULT 0,
MODIFY `totalCost` DECIMAL(14, 2) NOT NULL DEFAULT 0,
MODIFY `updatedAt` DATETIME(3) NOT NULL,
MODIFY `avgCost` DECIMAL(14, 2) NOT NULL DEFAULT 0,
ADD PRIMARY KEY (`id`);
-- CreateTable
CREATE TABLE `Trigger_Logs` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`message` TEXT NOT NULL,
`createdAt` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `_StockBalance_product` (
`A` INTEGER NOT NULL,
`B` INTEGER NOT NULL,
UNIQUE INDEX `_StockBalance_product_AB_unique`(`A`, `B`),
INDEX `_StockBalance_product_B_index`(`B`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `_StockBalance_inventory` (
`A` INTEGER NOT NULL,
`B` INTEGER NOT NULL,
UNIQUE INDEX `_StockBalance_inventory_AB_unique`(`A`, `B`),
INDEX `_StockBalance_inventory_B_index`(`B`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateIndex
CREATE INDEX `Stock_Balance_productId_idx` ON `Stock_Balance`(`productId`);
-- CreateIndex
CREATE UNIQUE INDEX `Stock_Balance_productId_inventoryId_key` ON `Stock_Balance`(`productId`, `inventoryId`);
-- AddForeignKey
ALTER TABLE `_StockBalance_product` ADD CONSTRAINT `_StockBalance_product_A_fkey` FOREIGN KEY (`A`) REFERENCES `Products`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `_StockBalance_product` ADD CONSTRAINT `_StockBalance_product_B_fkey` FOREIGN KEY (`B`) REFERENCES `Stock_Balance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `_StockBalance_inventory` ADD CONSTRAINT `_StockBalance_inventory_A_fkey` FOREIGN KEY (`A`) REFERENCES `Inventories`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `_StockBalance_inventory` ADD CONSTRAINT `_StockBalance_inventory_B_fkey` FOREIGN KEY (`B`) REFERENCES `Stock_Balance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
-- RenameIndex
ALTER TABLE `Stock_Balance` RENAME INDEX `Stock_Balance_inventoryId_fkey` TO `Stock_Balance_inventoryId_idx`;
@@ -0,0 +1,12 @@
/*
Warnings:
- Added the required column `name` to the `Trigger_Logs` table without a default value. This is not possible if the table is not empty.
*/
-- AlterTable
ALTER TABLE `Stock_Balance` MODIFY `updatedAt` TIMESTAMP(0) NOT NULL,
MODIFY `createdAt` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0);
-- AlterTable
ALTER TABLE `Trigger_Logs` ADD COLUMN `name` TEXT NOT NULL;
@@ -0,0 +1,40 @@
/*
Warnings:
- You are about to drop the column `stockBalanceId` on the `Products` table. All the data in the column will be lost.
- You are about to drop the `_StockBalance_inventory` table. If the table is not empty, all the data it contains will be lost.
- You are about to drop the `_StockBalance_product` table. If the table is not empty, all the data it contains will be lost.
*/
-- DropForeignKey
ALTER TABLE `_StockBalance_inventory` DROP FOREIGN KEY `_StockBalance_inventory_A_fkey`;
-- DropForeignKey
ALTER TABLE `_StockBalance_inventory` DROP FOREIGN KEY `_StockBalance_inventory_B_fkey`;
-- DropForeignKey
ALTER TABLE `_StockBalance_product` DROP FOREIGN KEY `_StockBalance_product_A_fkey`;
-- DropForeignKey
ALTER TABLE `_StockBalance_product` DROP FOREIGN KEY `_StockBalance_product_B_fkey`;
-- AlterTable
ALTER TABLE `Products` DROP COLUMN `stockBalanceId`;
-- AlterTable
ALTER TABLE `Stock_Movements` ADD COLUMN `supplierId` INTEGER NULL;
-- DropTable
DROP TABLE `_StockBalance_inventory`;
-- DropTable
DROP TABLE `_StockBalance_product`;
-- AddForeignKey
ALTER TABLE `Stock_Movements` ADD CONSTRAINT `Stock_Movements_supplierId_fkey` FOREIGN KEY (`supplierId`) REFERENCES `Suppliers`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Stock_Balance` ADD CONSTRAINT `Stock_Balance_productId_fkey` FOREIGN KEY (`productId`) REFERENCES `Products`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Stock_Balance` ADD CONSTRAINT `Stock_Balance_inventoryId_fkey` FOREIGN KEY (`inventoryId`) REFERENCES `Inventories`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
@@ -0,0 +1,8 @@
/*
Warnings:
- Added the required column `remainedInStock` to the `Stock_Movements` table without a default value. This is not possible if the table is not empty.
*/
-- AlterTable
ALTER TABLE `Stock_Movements` ADD COLUMN `remainedInStock` DECIMAL(10, 2) NOT NULL;
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE `Stock_Movements` MODIFY `remainedInStock` DECIMAL(10, 2) NOT NULL DEFAULT 0;
+49 -18
View File
@@ -82,6 +82,8 @@ model Product {
stockAdjustments StockAdjustment[] @relation("Product_Stock_Adjustments")
stockMovements StockMovement[] @relation("StockMovement_Product")
stockBalances StockBalance[] @relation("StockBalance_Product")
@@index([brandId], map: "Products_brandId_fkey")
@@index([categoryId], map: "Products_categoryId_fkey")
@@map("Products")
@@ -129,6 +131,7 @@ model Supplier {
deletedAt DateTime? @db.Timestamp(0)
productCharges ProductCharge[] @relation("Supplier_Product_Charges")
purchaseReceipts PurchaseReceipt[]
stockMovements StockMovement[] @relation("StockMovement_Supplier")
@@map("Suppliers")
}
@@ -158,6 +161,7 @@ model Inventory {
name String @db.VarChar(255)
location String? @db.VarChar(255)
isActive Boolean @default(true)
isPointOfSale Boolean @default(false)
createdAt DateTime @default(now()) @db.Timestamp(0)
updatedAt DateTime @updatedAt @db.Timestamp(0)
deletedAt DateTime? @db.Timestamp(0)
@@ -167,6 +171,7 @@ model Inventory {
purchaseReceipts PurchaseReceipt[]
stockAdjustments StockAdjustment[] @relation("Inventory_Stock_Adjustments")
stockMovements StockMovement[] @relation("StockMovement_Inventory")
stockBalances StockBalance[] @relation("StockBalance_inventory")
@@map("Inventories")
}
@@ -290,19 +295,22 @@ model SalesInvoiceItem {
}
model StockMovement {
id Int @id @default(autoincrement())
type MovementType
quantity Decimal @db.Decimal(10, 2)
fee Decimal @db.Decimal(10, 2)
totalCost Decimal @db.Decimal(10, 2)
referenceType MovementReferenceType
referenceId String
createdAt DateTime @default(now()) @db.Timestamp(0)
productId Int
inventoryId Int
avgCost Decimal @db.Decimal(10, 2)
inventory Inventory @relation("StockMovement_Inventory", fields: [inventoryId], references: [id])
product Product @relation("StockMovement_Product", fields: [productId], references: [id])
id Int @id @default(autoincrement())
type MovementType
quantity Decimal @db.Decimal(10, 2)
fee Decimal @db.Decimal(10, 2)
totalCost Decimal @db.Decimal(10, 2)
referenceType MovementReferenceType
referenceId String
createdAt DateTime @default(now()) @db.Timestamp(0)
productId Int
inventoryId Int
avgCost Decimal @db.Decimal(10, 2)
remainedInStock Decimal @default(0) @db.Decimal(10, 2)
inventory Inventory @relation("StockMovement_Inventory", fields: [inventoryId], references: [id])
product Product @relation("StockMovement_Product", fields: [productId], references: [id])
supplierId Int?
supplier Supplier? @relation("StockMovement_Supplier", fields: [supplierId], references: [id])
@@index([inventoryId], map: "Stock_Movements_inventoryId_fkey")
@@index([productId], map: "Stock_Movements_productId_fkey")
@@ -310,12 +318,25 @@ model StockMovement {
}
model StockBalance {
quantity Decimal
totalCost Decimal
updatedAt DateTime @default(now()) @updatedAt @db.Timestamp(0)
ProductId Int @id
avgCost Decimal
id Int @id @default(autoincrement())
productId Int
inventoryId Int
quantity Decimal @default(0) @db.Decimal(14, 3)
avgCost Decimal @default(0) @db.Decimal(14, 2)
totalCost Decimal @default(0) @db.Decimal(14, 2)
createdAt DateTime @default(now()) @db.Timestamp(0)
updatedAt DateTime @updatedAt @db.Timestamp(0)
product Product @relation("StockBalance_Product", fields: [productId], references: [id])
inventory Inventory @relation("StockBalance_inventory", fields: [inventoryId], references: [id])
@@unique([productId, inventoryId])
@@index([productId])
@@index([inventoryId])
@@map("Stock_Balance")
}
@@ -432,6 +453,7 @@ enum MovementReferenceType {
PURCHASE
SALES
ADJUSTMENT
INVENTORY_TRANSFER
}
enum stock_cardex_type {
@@ -451,3 +473,12 @@ enum stock_movements_view_referenceType {
SALES
ADJUSTMENT
}
model TriggerLog {
id Int @id @default(autoincrement())
name String @db.Text
message String @db.Text
createdAt DateTime @default(now()) @db.Timestamp(0)
@@map("Trigger_Logs")
}
+66 -8
View File
@@ -1,16 +1,74 @@
import { prisma } from '../src/lib/prisma'
async function main() {
console.log('first')
if ((await prisma.role.count()) === 0) {
await prisma.role.upsert({
where: { id: 0, name: 'Admin' },
update: {},
create: {
name: 'Admin',
},
})
}
await prisma.role.upsert({
where: { id: 0, name: 'Admin' },
update: {},
create: {
name: 'Admin',
},
})
if ((await prisma.inventory.count()) === 0) {
await prisma.inventory.createMany({
data: [
{ name: 'انبار مرکزی', location: 'تهران', isPointOfSale: false, isActive: true },
{
name: 'فروشگاه حضوری',
location: 'مرکز شهر',
isPointOfSale: true,
isActive: true,
},
{
name: 'فروشگاه اینترنتی',
location: 'مرکز شهر',
isPointOfSale: true,
isActive: true,
},
],
})
}
if ((await prisma.productCategory.count()) === 0) {
await prisma.productCategory.createMany({
data: [{ name: 'دسته‌ی ۱' }, { name: 'دسته‌ی ۲' }, { name: 'دسته‌ی ۳' }],
})
}
if ((await prisma.productBrand.count()) === 0) {
await prisma.productBrand.createMany({
data: [{ name: 'برند ۱' }, { name: 'برند ۲' }, { name: 'برند ۳' }],
})
}
if ((await prisma.supplier.count()) === 0) {
await prisma.supplier.createMany({
data: [
{
firstName: 'تامین‌',
lastName: 'کننده ۱',
mobileNumber: '09120000001',
email: 'supplier1@example.com',
},
{
firstName: 'تامین‌',
lastName: 'کننده ۲',
mobileNumber: '09120000002',
email: 'supplier2@example.com',
},
{
firstName: 'تامین‌',
lastName: 'کننده 3',
mobileNumber: '09120000003',
email: 'supplier3@example.com',
},
],
})
}
}
main()
.then(async () => {
await prisma.$disconnect()
+145 -262
View File
@@ -1,5 +1,5 @@
-- AUTO-GENERATED MYSQL TRIGGER DUMP
-- Generated at: 2025-12-10T10:03:36.966Z
-- Generated at: 2025-12-13T15:37:15.132Z
-- ------------------------------------------
-- Trigger: trg_transfer_item_after_insert
@@ -9,23 +9,34 @@
DROP TRIGGER IF EXISTS `trg_transfer_item_after_insert`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_transfer_item_after_insert` AFTER INSERT ON `Inventory_Transfer_Items` FOR EACH ROW begin
DECLARE fromInv INT;
DECLARE toInv INT;
SELECT fromInventoryId, toInventoryId INTO fromInv, toInv
FROM Inventory_Transfers WHERE id = NEW.transferId;
DECLARE fromInv INT;
DECLARE toInv INT;
DECLARE _avgCost DECIMAL(10,2);
DECLARE latestQuantityInOrigin DECIMAL(10,2);
DECLARE latestQuantityInDestination DECIMAL(10,2);
-- OUT from source
INSERT INTO Stock_Movements
(type, quantity, referenceType, referenceId, productId, inventoryId, createdAt)
VALUES
('OUT', NEW.count, 'InventoryTransfer', NEW.transferId, NEW.productId, fromInv, NOW());
SELECT fromInventoryId, toInventoryId INTO fromInv, toInv
FROM Inventory_Transfers WHERE id = NEW.transferId;
-- IN to destination
INSERT INTO Stock_Movements
(type, quantity, referenceType, referenceId, productId, inventoryId, createdAt)
VALUES
('IN', NEW.count, 'InventoryTransfer', NEW.transferId, NEW.productId, toInv, NOW());
SELECT COALESCE(avgCost, 0), COALESCE(quantity, 0) INTO _avgCost, latestQuantityInOrigin FROM Stock_Balance
WHERE ProductId = NEW.productId AND inventoryId = fromInv LIMIT 1;
SELECT COALESCE(quantity, 0) INTO latestQuantityInDestination FROM Stock_Balance
WHERE ProductId = NEW.productId AND inventoryId = toInv LIMIT 1;
-- OUT from source
INSERT INTO Stock_Movements
(type, quantity, fee, totalCost, avgCost, referenceType, referenceId, productId, inventoryId, createdAt, remainedInStock)
VALUES
('OUT', NEW.count, _avgCost, _avgCost*NEW.count, _avgCost, 'INVENTORY_TRANSFER', NEW.transferId, NEW.productId, fromInv, NOW(), latestQuantityInOrigin-NEW.count);
-- IN to destination
INSERT INTO Stock_Movements
(type, quantity, fee, totalCost, avgCost, referenceType, referenceId, productId, inventoryId, createdAt, remainedInStock)
VALUES
('IN', NEW.count,_avgCost, _avgCost*NEW.count,_avgCost, 'INVENTORY_TRANSFER', NEW.transferId, NEW.productId, toInv, NOW(), latestQuantityInOrigin-NEW.count);
end;
-- ------------------------------------------
@@ -34,158 +45,140 @@ end;
-- Table: Purchase_Receipt_Items
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_purchase_receipt_item_after_insert`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_purchase_receipt_item_after_insert` AFTER INSERT ON `Purchase_Receipt_Items` FOR EACH ROW begin
INSERT INTO Stock_Movements
(
type,
quantity,
referenceType,
referenceId,
productId,
inventoryId,
createdAt
)
VALUES
(
'IN',
NEW.count,
'PURCHASE',
NEW.receiptId,
NEW.productId,
(SELECT inventoryId FROM Purchase_Receipts WHERE id = NEW.receiptId),
NOW()
);
end;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_purchase_receipt_item_after_insert` AFTER INSERT ON `Purchase_Receipt_Items` FOR EACH ROW BEGIN
DECLARE latestQuantity DECIMAL(10,2) DEFAULT 0;
DECLARE invId INT;
DECLARE suppId INT;
-- ------------------------------------------
-- Trigger: trg_purchase_receipt_item_after_update
-- Event: UPDATE
-- Table: Purchase_Receipt_Items
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_purchase_receipt_item_after_update`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_purchase_receipt_item_after_update` AFTER UPDATE ON `Purchase_Receipt_Items` FOR EACH ROW begin
DELETE FROM Stock_Movements
WHERE referenceType = 'PURCHASE'
AND referenceId = NEW.receiptId
AND productId = NEW.productId;
-- Get inventory & supplier from receipt
SELECT inventoryId, supplierId
INTO invId, suppId
FROM Purchase_Receipts
WHERE id = NEW.receiptId;
INSERT INTO Stock_Movements
(
type,
quantity,
referenceType,
referenceId,
productId,
inventoryId,
createdAt
)
VALUES
(
'IN',
NEW.count,
'SALES',
NEW.id,
NEW.productId,
(SELECT inventoryId FROM Stores LIMIT 1),
NOW()
);
end;
-- ------------------------------------------
-- Trigger: trg_purchase_receipt_item_after_delete
-- Event: DELETE
-- Table: Purchase_Receipt_Items
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_purchase_receipt_item_after_delete`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_purchase_receipt_item_after_delete` AFTER DELETE ON `Purchase_Receipt_Items` FOR EACH ROW begin
DELETE FROM Stock_Movements
WHERE referenceType = 'PURCHASE'
AND referenceId = OLD.receiptId
AND productId = OLD.productId;
end;
-- ------------------------------------------
-- Trigger: trg_sales_invoice_items_before_insert
-- Event: INSERT
-- Table: Sales_Invoice_Items
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_sales_invoice_items_before_insert`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_sales_invoice_items_before_insert` BEFORE INSERT ON `Sales_Invoice_Items` FOR EACH ROW begin
DECLARE current_stock DECIMAL(10,2);
SELECT stock INTO current_stock
FROM stock_view
WHERE productId = NEW.productId
-- Get current stock quantity (if exists)
SELECT COALESCE(quantity, 0)
INTO latestQuantity
FROM Stock_Balance sb
WHERE sb.inventoryId = invId
AND sb.productId = NEW.productId
LIMIT 1;
IF current_stock IS NULL THEN
SET current_stock = 0;
END IF;
IF NEW.count > current_stock THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Not enough stock to complete sale.';
END IF;
end;
-- ------------------------------------------
-- Trigger: trg_sales_invoice_items_after_insert
-- Event: INSERT
-- Table: Sales_Invoice_Items
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_sales_invoice_items_after_insert`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_sales_invoice_items_after_insert` AFTER INSERT ON `Sales_Invoice_Items` FOR EACH ROW begin
INSERT INTO Stock_Movements
(
-- Insert stock movement
INSERT INTO Stock_Movements (
type,
quantity,
fee,
totalCost,
referenceType,
referenceId,
productId,
inventoryId,
avgCost,
supplierId,
remainedInStock,
createdAt
)
VALUES
(
'IN',
NEW.count,
'PURCHASE',
NEW.id,
NEW.productId,
(SELECT inventoryId FROM Sales_Invoices WHERE id = NEW.id),
NOW()
);
end;
VALUES (
'IN',
NEW.count,
NEW.fee,
NEW.total,
'PURCHASE',
NEW.receiptId,
NEW.productId,
invId,
CASE
WHEN NEW.count = 0 THEN 0
ELSE NEW.total / NEW.count
END,
suppId,
latestQuantity + NEW.count,
NOW()
);
END;
-- ------------------------------------------
-- Trigger: trg_stock_adjustment_after_insert
-- Event: INSERT
-- Table: Stock_Adjustments
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_stock_adjustment_after_insert`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_stock_adjustment_after_insert` AFTER INSERT ON `Stock_Adjustments` FOR EACH ROW begin
INSERT INTO Stock_Movements
(type, quantity, referenceType, referenceId, productId, inventoryId, createdAt)
VALUES
('ADJUST', NEW.adjustedQuantity, 'ADJUSTMENT', NEW.id, NEW.productId, NEW.inventoryId, NOW());
end;
-- ------------------------------------------
-- Trigger: trg_stock_sale_insert
-- Trigger: trg_stock_transfer
-- Event: INSERT
-- Table: Stock_Movements
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_stock_sale_insert`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_stock_sale_insert` AFTER INSERT ON `Stock_Movements` FOR EACH ROW BEGIN
IF NEW.referenceType = 'SALES' THEN
DROP TRIGGER IF EXISTS `trg_stock_transfer`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_stock_transfer` AFTER INSERT ON `Stock_Movements` FOR EACH ROW BEGIN
IF NEW.referenceType = 'INVENTORY_TRANSFER' THEN
IF NEW.type = 'IN' THEN
INSERT INTO Stock_Balance (
productId,
inventoryId,
quantity,
totalCost,
avgCost,
updatedAt
)
VALUES (
NEW.productId,
NEW.inventoryId,
NEW.quantity,
NEW.totalCost,
CASE
WHEN NEW.quantity = 0 THEN 0
ELSE NEW.totalCost / NEW.quantity
END,
NOW()
)
ON DUPLICATE KEY UPDATE
quantity = quantity + NEW.quantity,
totalCost = totalCost + NEW.totalCost,
avgCost = CASE
WHEN (quantity + NEW.quantity) = 0 THEN 0
ELSE (totalCost + NEW.totalCost) / (quantity + NEW.quantity)
END,
updatedAt = NOW();
END IF;
IF NEW.type = 'OUT' THEN
IF EXISTS(
SELECT 1 FROM Stock_Balance sb
WHERE sb.productId = NEW.productId
AND sb.inventoryId = NEW.inventoryId
) THEN
UPDATE stock_balance
SET
quantity = quantity - NEW.quantity,
totalCost = quantity * avgCost
WHERE productId = NEW.productId ;
UPDATE Stock_Balance sb
SET
sb.quantity = sb.quantity - NEW.quantity,
sb.totalCost = sb.totalCost - (sb.avgCost * NEW.quantity),
sb.updatedAt = NOW()
WHERE sb.productId = NEW.productId
AND sb.inventoryId = NEW.inventoryId;
ELSE
INSERT INTO Stock_Balance (
productId,
inventoryId,
quantity,
totalCost,
avgCost,
updatedAt
)
VALUES (
NEW.productId,
NEW.inventoryId,
-NEW.quantity,
-COALESCE(NEW.fee, 0) * NEW.quantity,
COALESCE(NEW.fee, 0),
NOW()
);
END IF;
END IF;
END IF;
END;
-- ------------------------------------------
@@ -196,13 +189,15 @@ END;
DROP TRIGGER IF EXISTS `trg_stock_purchase_insert`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_stock_purchase_insert` AFTER INSERT ON `Stock_Movements` FOR EACH ROW BEGIN
IF NEW.referenceType = 'PURCHASE' THEN
INSERT INTO stock_balance (productId, quantity, avgCost, totalCost)
INSERT INTO Stock_Balance (productId, quantity, avgCost, totalCost, inventoryId, updatedAt)
VALUES (
NEW.productId,
NEW.quantity,
NEW.fee,
NEW.totalCost
NEW.totalCost,
NEW.inventoryId,
NOW()
)
ON DUPLICATE KEY UPDATE
quantity = quantity + NEW.quantity,
@@ -212,115 +207,3 @@ CREATE DEFINER=`pos`@`%` TRIGGER `trg_stock_purchase_insert` AFTER INSERT ON `St
END IF;
END;
-- ------------------------------------------
-- Trigger: trg_stock_movement_after_insert
-- Event: INSERT
-- Table: Stock_Movements
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_stock_movement_after_insert`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_stock_movement_after_insert` AFTER INSERT ON `Stock_Movements` FOR EACH ROW begin
UPDATE Products pv
SET pv.quantity = (
SELECT COALESCE(SUM(
CASE
WHEN type = 'IN' THEN quantity
WHEN type = 'OUT' THEN -quantity
WHEN type = 'ADJUST' THEN quantity
END
), 0)
FROM Stock_Movements
WHERE productId = NEW.productId
)
WHERE pv.id = NEW.productId;
end;
-- ------------------------------------------
-- Trigger: trg_stock_sale_update
-- Event: UPDATE
-- Table: Stock_Movements
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_stock_sale_update`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_stock_sale_update` AFTER UPDATE ON `Stock_Movements` FOR EACH ROW BEGIN
IF OLD.referenceType = 'SALES' THEN
UPDATE stock_balance
SET
quantity = quantity + OLD.quantity,
totalCost = (quantity + OLD.quantity) * avgCost
WHERE productId = OLD.productId;
END IF;
IF NEW.referenceType = 'SALES' THEN
UPDATE stock_balance
SET
quantity = quantity - NEW.quantity,
totalCost = (quantity - NEW.quantity) * avgCost
WHERE productId = NEW.productId;
END IF;
END;
-- ------------------------------------------
-- Trigger: trg_stock_purchase_update
-- Event: UPDATE
-- Table: Stock_Movements
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_stock_purchase_update`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_stock_purchase_update` AFTER UPDATE ON `Stock_Movements` FOR EACH ROW BEGIN
IF OLD.referenceType = 'PURCHASE' THEN
UPDATE stock_balance
SET
quantity = quantity - OLD.quantity,
totalCost = totalCost - (OLD.quantity * OLD.fee)
WHERE productId = OLD.productId;
END IF;
IF NEW.referenceType = 'PURCHASE' THEN
INSERT INTO stock_balance (productId, quantity, avgCost, totalCost)
VALUES (
NEW.productId,
NEW.quantity,
NEW.fee,
NEW.totalCost
)
ON DUPLICATE KEY UPDATE
quantity = quantity + NEW.quantity,
totalCost = totalCost + NEW.totalCost,
avgCost = totalCost / quantity;
END IF;
END;
-- ------------------------------------------
-- Trigger: trg_stock_sale_delete
-- Event: DELETE
-- Table: Stock_Movements
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_stock_sale_delete`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_stock_sale_delete` AFTER DELETE ON `Stock_Movements` FOR EACH ROW BEGIN
IF OLD.ReferenceType = 'SALES' THEN
UPDATE stock_balance
SET
quantity = quantity + OLD.quantity,
totalCost = (quantity + OLD.quantity) * avgCost
WHERE productId = OLD.productId;
END IF;
END;
-- ------------------------------------------
-- Trigger: trg_stock_purchase_delete
-- Event: DELETE
-- Table: Stock_Movements
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_stock_purchase_delete`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_stock_purchase_delete` AFTER DELETE ON `Stock_Movements` FOR EACH ROW BEGIN
IF OLD.referenceType = 'PURCHASE' THEN
UPDATE stock_balance
SET
quantity = quantity - OLD.quantity,
totalCost = totalCost - (OLD.quantity * OLD.fee),
avgCost = CASE
WHEN quantity - OLD.quantity = 0 THEN 0
ELSE (totalCost - (OLD.quantity * OLD.fee)) / (quantity - OLD.quantity)
END
WHERE productId = OLD.productId;
END IF;
END;
+476
View File
@@ -0,0 +1,476 @@
-- AUTO-GENERATED MYSQL TRIGGER DUMP
-- Generated at: 2025-12-10T10:03:36.966Z
-- ------------------------------------------
-- Trigger: trg_transfer_item_after_insert
-- Event: INSERT
-- Table: Inventory_Transfer_Items
-- Status: ACTIVE
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_transfer_item_after_insert`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_transfer_item_after_insert` AFTER INSERT ON `Inventory_Transfer_Items` FOR EACH ROW begin
DECLARE fromInv INT;
DECLARE toInv INT;
DECLARE _avgCost DECIMAL(10,2);
SELECT fromInventoryId, toInventoryId INTO fromInv, toInv
FROM Inventory_Transfers WHERE id = NEW.transferId;
SELECT COALESCE(avgCost, 0) INTO _avgCost FROM Stock_Balance
WHERE ProductId = NEW.productId AND inventoryId = fromInv LIMIT 1;
-- OUT from source
INSERT INTO Stock_Movements
(type, quantity, fee, totalCost, avgCost, referenceType, referenceId, productId, inventoryId, createdAt)
VALUES
('OUT', NEW.count, _avgCost, _avgCost*NEW.count, _avgCost, 'INVENTORY_TRANSFER', NEW.transferId, NEW.productId, fromInv, NOW());
-- IN to destination
INSERT INTO Stock_Movements
(type, quantity, fee, totalCost, avgCost, referenceType, referenceId, productId, inventoryId, createdAt)
VALUES
('IN', NEW.count,_avgCost, _avgCost*NEW.count,_avgCost, 'INVENTORY_TRANSFER', NEW.transferId, NEW.productId, toInv, NOW());
end;
-- ------------------------------------------
-- Trigger: trg_stock_purchase_insert
-- Event: INSERT
-- Table: Stock_Movements
-- Status: ACTIVE
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_stock_purchase_insert`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_stock_purchase_insert` AFTER INSERT ON `Stock_Movements` FOR EACH ROW BEGIN
IF NEW.referenceType = 'PURCHASE' THEN
INSERT INTO Stock_Balance (productId, quantity, avgCost, totalCost, inventoryId, updatedAt)
VALUES (
NEW.productId,
NEW.quantity,
NEW.fee,
NEW.totalCost,
NEW.inventoryId,
NOW()
)
ON DUPLICATE KEY UPDATE
quantity = quantity + NEW.quantity,
totalCost = totalCost + NEW.totalCost,
avgCost = totalCost / quantity;
END IF;
END
-- ------------------------------------------
-- Trigger: trg_stock_transfer
-- Event: INSERT
-- Table: Stock_Movements
-- Status: ACTIVE
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_stock_transfer`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_stock_transfer` AFTER INSERT ON `Stock_Movements` FOR EACH ROW BEGIN
IF NEW.referenceType = 'INVENTORY_TRANSFER' THEN
IF NEW.type = 'IN' THEN
INSERT INTO Stock_Balance (
productId,
inventoryId,
quantity,
totalCost,
avgCost,
updatedAt
)
VALUES (
NEW.productId,
NEW.inventoryId,
NEW.quantity,
NEW.totalCost,
CASE
WHEN NEW.quantity = 0 THEN 0
ELSE NEW.totalCost / NEW.quantity
END,
NOW()
)
ON DUPLICATE KEY UPDATE
quantity = quantity + NEW.quantity,
totalCost = totalCost + NEW.totalCost,
avgCost = CASE
WHEN (quantity + NEW.quantity) = 0 THEN 0
ELSE (totalCost + NEW.totalCost) / (quantity + NEW.quantity)
END,
updatedAt = NOW();
END IF;
IF NEW.type = 'OUT' THEN
IF EXISTS(
SELECT 1 FROM Stock_Balance sb
WHERE sb.productId = NEW.productId
AND sb.inventoryId = NEW.inventoryId
) THEN
UPDATE Stock_Balance sb
SET
sb.quantity = sb.quantity - NEW.quantity,
sb.totalCost = sb.totalCost - (sb.avgCost * NEW.quantity),
sb.updatedAt = NOW()
WHERE sb.productId = NEW.productId
AND sb.inventoryId = NEW.inventoryId;
ELSE
INSERT INTO Stock_Balance (
productId,
inventoryId,
quantity,
totalCost,
avgCost,
updatedAt
)
VALUES (
NEW.productId,
NEW.inventoryId,
-NEW.quantity,
-COALESCE(NEW.fee, 0) * NEW.quantity,
COALESCE(NEW.fee, 0),
NOW()
);
END IF;
END IF;
END IF;
END
-- ------------------------------------------
-- Trigger: trg_purchase_receipt_item_after_insert
-- Event: INSERT
-- Table: Purchase_Receipt_Items
-- Status: ACTIVE
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_purchase_receipt_item_after_insert`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_purchase_receipt_item_after_insert` AFTER INSERT ON `Purchase_Receipt_Items` FOR EACH ROW begin
INSERT INTO Stock_Movements
(
type,
quantity,
fee,
totalCost,
referenceType,
referenceId,
productId,
inventoryId,
supplierId,
avgCost,
createdAt
)
VALUES
(
'IN',
NEW.count,
NEW.fee,
NEW.total,
'PURCHASE',
NEW.receiptId,
NEW.productId,
(SELECT inventoryId FROM Purchase_Receipts WHERE id = NEW.receiptId),
(SELECT supplierId FROM Purchase_Receipts WHERE id = NEW.receiptId),
NEW.total/NEW.count,
NOW()
);
end
-- NEW --
-- ------------------------------------------
-- Trigger: trg_purchase_receipt_item_after_insert
-- Event: INSERT
-- Table: Purchase_Receipt_Items
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_purchase_receipt_item_after_insert`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_purchase_receipt_item_after_insert` AFTER INSERT ON `Purchase_Receipt_Items` FOR EACH ROW begin
INSERT INTO Stock_Movements
(
type,
quantity,
referenceType,
referenceId,
productId,
inventoryId,
createdAt
)
VALUES
(
'IN',
NEW.count,
'PURCHASE',
NEW.receiptId,
NEW.productId,
(SELECT inventoryId FROM Purchase_Receipts WHERE id = NEW.receiptId),
NOW()
);
end;
-- ------------------------------------------
-- Trigger: trg_purchase_receipt_item_after_update
-- Event: UPDATE
-- Table: Purchase_Receipt_Items
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_purchase_receipt_item_after_update`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_purchase_receipt_item_after_update` AFTER UPDATE ON `Purchase_Receipt_Items` FOR EACH ROW begin
DELETE FROM Stock_Movements
WHERE referenceType = 'PURCHASE'
AND referenceId = NEW.receiptId
AND productId = NEW.productId;
INSERT INTO Stock_Movements
(
type,
quantity,
referenceType,
referenceId,
productId,
inventoryId,
createdAt
)
VALUES
(
'IN',
NEW.count,
'SALES',
NEW.id,
NEW.productId,
(SELECT inventoryId FROM Stores LIMIT 1),
NOW()
);
end;
-- ------------------------------------------
-- Trigger: trg_purchase_receipt_item_after_delete
-- Event: DELETE
-- Table: Purchase_Receipt_Items
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_purchase_receipt_item_after_delete`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_purchase_receipt_item_after_delete` AFTER DELETE ON `Purchase_Receipt_Items` FOR EACH ROW begin
DELETE FROM Stock_Movements
WHERE referenceType = 'PURCHASE'
AND referenceId = OLD.receiptId
AND productId = OLD.productId;
end;
-- ------------------------------------------
-- Trigger: trg_sales_invoice_items_before_insert
-- Event: INSERT
-- Table: Sales_Invoice_Items
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_sales_invoice_items_before_insert`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_sales_invoice_items_before_insert` BEFORE INSERT ON `Sales_Invoice_Items` FOR EACH ROW begin
DECLARE current_stock DECIMAL(10,2);
SELECT stock INTO current_stock
FROM stock_view
WHERE productId = NEW.productId
LIMIT 1;
IF current_stock IS NULL THEN
SET current_stock = 0;
END IF;
IF NEW.count > current_stock THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Not enough stock to complete sale.';
END IF;
end;
-- ------------------------------------------
-- Trigger: trg_sales_invoice_items_after_insert
-- Event: INSERT
-- Table: Sales_Invoice_Items
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_sales_invoice_items_after_insert`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_sales_invoice_items_after_insert` AFTER INSERT ON `Sales_Invoice_Items` FOR EACH ROW begin
INSERT INTO Stock_Movements
(
type,
quantity,
referenceType,
referenceId,
productId,
inventoryId,
createdAt
)
VALUES
(
'IN',
NEW.count,
'PURCHASE',
NEW.id,
NEW.productId,
(SELECT inventoryId FROM Sales_Invoices WHERE id = NEW.id),
NOW()
);
end;
-- ------------------------------------------
-- Trigger: trg_stock_adjustment_after_insert
-- Event: INSERT
-- Table: Stock_Adjustments
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_stock_adjustment_after_insert`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_stock_adjustment_after_insert` AFTER INSERT ON `Stock_Adjustments` FOR EACH ROW begin
INSERT INTO Stock_Movements
(type, quantity, referenceType, referenceId, productId, inventoryId, createdAt)
VALUES
('ADJUST', NEW.adjustedQuantity, 'ADJUSTMENT', NEW.id, NEW.productId, NEW.inventoryId, NOW());
end;
-- ------------------------------------------
-- Trigger: trg_stock_sale_insert
-- Event: INSERT
-- Table: Stock_Movements
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_stock_sale_insert`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_stock_sale_insert` AFTER INSERT ON `Stock_Movements` FOR EACH ROW BEGIN
IF NEW.referenceType = 'SALES' THEN
UPDATE stock_balance
SET
quantity = quantity - NEW.quantity,
totalCost = quantity * avgCost
WHERE productId = NEW.productId ;
END IF;
END;
-- ------------------------------------------
-- Trigger: trg_stock_movement_after_insert
-- Event: INSERT
-- Table: Stock_Movements
-- Status: ARCHIVED
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_stock_movement_after_insert`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_stock_movement_after_insert` AFTER INSERT ON `Stock_Movements` FOR EACH ROW begin
UPDATE Products pv
SET pv.quantity = (
SELECT COALESCE(SUM(
CASE
WHEN type = 'IN' THEN quantity
WHEN type = 'OUT' THEN -quantity
WHEN type = 'ADJUST' THEN quantity
END
), 0)
FROM Stock_Movements
WHERE productId = NEW.productId
)
WHERE pv.id = NEW.productId;
end;
-- ------------------------------------------
-- Trigger: trg_stock_sale_update
-- Event: UPDATE
-- Table: Stock_Movements
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_stock_sale_update`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_stock_sale_update` AFTER UPDATE ON `Stock_Movements` FOR EACH ROW BEGIN
IF OLD.referenceType = 'SALES' THEN
UPDATE stock_balance
SET
quantity = quantity + OLD.quantity,
totalCost = (quantity + OLD.quantity) * avgCost
WHERE productId = OLD.productId;
END IF;
IF NEW.referenceType = 'SALES' THEN
UPDATE stock_balance
SET
quantity = quantity - NEW.quantity,
totalCost = (quantity - NEW.quantity) * avgCost
WHERE productId = NEW.productId;
END IF;
END;
-- ------------------------------------------
-- Trigger: trg_stock_purchase_update
-- Event: UPDATE
-- Table: Stock_Movements
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_stock_purchase_update`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_stock_purchase_update` AFTER UPDATE ON `Stock_Movements` FOR EACH ROW BEGIN
IF OLD.referenceType = 'PURCHASE' THEN
UPDATE stock_balance
SET
quantity = quantity - OLD.quantity,
totalCost = totalCost - (OLD.quantity * OLD.fee)
WHERE productId = OLD.productId;
END IF;
IF NEW.referenceType = 'PURCHASE' THEN
INSERT INTO stock_balance (productId, quantity, avgCost, totalCost)
VALUES (
NEW.productId,
NEW.quantity,
NEW.fee,
NEW.totalCost
)
ON DUPLICATE KEY UPDATE
quantity = quantity + NEW.quantity,
totalCost = totalCost + NEW.totalCost,
avgCost = totalCost / quantity;
END IF;
END;
-- ------------------------------------------
-- Trigger: trg_stock_sale_delete
-- Event: DELETE
-- Table: Stock_Movements
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_stock_sale_delete`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_stock_sale_delete` AFTER DELETE ON `Stock_Movements` FOR EACH ROW BEGIN
IF OLD.ReferenceType = 'SALES' THEN
UPDATE stock_balance
SET
quantity = quantity + OLD.quantity,
totalCost = (quantity + OLD.quantity) * avgCost
WHERE productId = OLD.productId;
END IF;
END;
-- ------------------------------------------
-- Trigger: trg_stock_purchase_delete
-- Event: DELETE
-- Table: Stock_Movements
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_stock_purchase_delete`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_stock_purchase_delete` AFTER DELETE ON `Stock_Movements` FOR EACH ROW BEGIN
IF OLD.referenceType = 'PURCHASE' THEN
UPDATE stock_balance
SET
quantity = quantity - OLD.quantity,
totalCost = totalCost - (OLD.quantity * OLD.fee),
avgCost = CASE
WHEN quantity - OLD.quantity = 0 THEN 0
ELSE (totalCost - (OLD.quantity * OLD.fee)) / (quantity - OLD.quantity)
END
WHERE productId = OLD.productId;
END IF;
END;