feat(statistics): implement top alert stocks, top last sales, top supplier debts, and top selling products endpoints with SQL queries

This commit is contained in:
2026-01-04 13:45:26 +03:30
parent eb6e0e7a0d
commit a2db2daa70
72 changed files with 11934 additions and 2559 deletions
@@ -1 +0,0 @@
-- This is an empty migration.
@@ -1,347 +0,0 @@
-- AUTO-GENERATED MYSQL TRIGGER DUMP
-- Generated at: 2025-12-22T15:32:20.184Z
-- ------------------------------------------
-- Trigger: trg_transfer_item_after_insert
-- Event: INSERT
-- Table: Inventory_Transfer_Items
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_transfer_item_after_insert`;
CREATE 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);
DECLARE latestQuantityInOrigin DECIMAL(10,2);
DECLARE latestQuantityInDestination DECIMAL(10,2);
SELECT fromInventoryId, toInventoryId INTO fromInv, toInv
FROM Inventory_Transfers WHERE id = NEW.transferId;
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, counterInventoryId, createdAt, remainedInStock)
VALUES
('OUT', NEW.count, _avgCost, _avgCost*NEW.count, _avgCost, 'INVENTORY_TRANSFER', NEW.transferId, NEW.productId, fromInv, toInv, NOW(), latestQuantityInOrigin-NEW.count);
-- IN to destination
INSERT INTO Stock_Movements
(type, quantity, fee, totalCost, avgCost, referenceType, referenceId, productId, inventoryId, counterInventoryId, createdAt, remainedInStock)
VALUES
('IN', NEW.count,_avgCost, _avgCost*NEW.count,_avgCost, 'INVENTORY_TRANSFER', NEW.transferId, NEW.productId, toInv, fromInv, NOW(), latestQuantityInOrigin-NEW.count);
end;
-- ------------------------------------------
-- Trigger: trg_purchase_receipt_item_after_insert
-- Event: INSERT
-- Table: Purchase_Receipt_Items
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_purchase_receipt_item_after_insert`;
CREATE 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;
-- Get inventory & supplier from receipt
SELECT inventoryId, supplierId
INTO invId, suppId
FROM Purchase_Receipts
WHERE id = NEW.receiptId;
-- 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;
-- Insert stock movement
INSERT INTO Stock_Movements (
type,
quantity,
fee,
totalCost,
referenceType,
referenceId,
productId,
inventoryId,
avgCost,
supplierId,
remainedInStock,
createdAt
)
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_sales_invoice_items_before_insert
-- Event: INSERT
-- Table: Sales_Invoice_Items
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_sales_invoice_items_before_insert`;
CREATE TRIGGER `trg_sales_invoice_items_before_insert` BEFORE INSERT ON `Sales_Invoice_Items` FOR EACH ROW begin DECLARE current_stock DECIMAL(10, 2);
DECLARE inventory_id INT;
SELECT inventoryId INTO inventory_id
FROM Sales_Invoices si
WHERE si.id = NEW.invoiceId
LIMIT 1;
SELECT COALESCE(quantity, 0) INTO current_stock
FROM Stock_Balance sb
WHERE productId = NEW.productId AND sb.inventoryId = inventory_id
LIMIT 1;
IF NEW.count > current_stock THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'موجودی کالا در انبار کافی نیست.';
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 TRIGGER `trg_sales_invoice_items_after_insert` AFTER INSERT ON `Sales_Invoice_Items` FOR EACH ROW begin DECLARE current_stock DECIMAL(10, 2);
DECLARE inventory_id INT;
DECLARE customer_id INT;
SELECT inventoryId , customerId INTO inventory_id, customer_id
FROM Sales_Invoices si
WHERE si.id = NEW.invoiceId
LIMIT 1;
SELECT COALESCE(quantity, 0) INTO current_stock
FROM Stock_Balance sb
WHERE productId = NEW.productId AND sb.inventoryId = inventory_id
LIMIT 1;
INSERT INTO Stock_Movements (
type,
quantity,
fee,
totalCost,
referenceType,
referenceId,
productId,
inventoryId,
avgCost,
remainedInStock,
customerId,
createdAt
)
VALUES (
'OUT',
NEW.count,
NEW.fee,
NEW.total,
'SALES',
NEW.invoiceId,
NEW.productId,
inventory_id,
CASE
WHEN NEW.count = 0 THEN 0
ELSE NEW.total / NEW.count
END,
current_stock + NEW.count,
customer_id,
NOW()
);
END;
-- ------------------------------------------
-- Trigger: trg_stock_transfer
-- Event: INSERT
-- Table: Stock_Movements
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_stock_transfer`;
CREATE 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_stock_purchase_insert
-- Event: INSERT
-- Table: Stock_Movements
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_stock_purchase_insert`;
CREATE 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_sale_insert
-- Event: INSERT
-- Table: Stock_Movements
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_stock_sale_insert`;
CREATE TRIGGER `trg_stock_sale_insert` AFTER INSERT ON `Stock_Movements` FOR EACH ROW BEGIN IF NEW.referenceType = 'SALES' 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;
@@ -1,18 +0,0 @@
/*
Warnings:
- You are about to drop the column `bankAccountId` on the `Inventories` table. All the data in the column will be lost.
- You are about to drop the `_Bank_Accounts_inventoryId_fkey` table. If the table is not empty, all the data it contains will be lost.
*/
-- DropForeignKey
ALTER TABLE `_Bank_Accounts_inventoryId_fkey` DROP FOREIGN KEY `_Bank_Accounts_inventoryId_fkey_A_fkey`;
-- DropForeignKey
ALTER TABLE `_Bank_Accounts_inventoryId_fkey` DROP FOREIGN KEY `_Bank_Accounts_inventoryId_fkey_B_fkey`;
-- AlterTable
ALTER TABLE `Inventories` DROP COLUMN `bankAccountId`;
-- DropTable
DROP TABLE `_Bank_Accounts_inventoryId_fkey`;
@@ -1,158 +0,0 @@
/*
Warnings:
- You are about to alter the column `count` on the `Inventory_Transfer_Items` table. The data in that column could be lost. The data in that column will be cast from `Decimal(10,2)` to `Decimal(10,0)`.
- You are about to alter the column `totalAmount` on the `Orders` table. The data in that column could be lost. The data in that column will be cast from `Decimal(10,2)` to `Decimal(15,2)`.
- You are about to alter the column `basePrice` on the `Product_Variants` table. The data in that column could be lost. The data in that column will be cast from `Decimal(10,2)` to `Decimal(15,2)`.
- You are about to alter the column `salePrice` on the `Product_Variants` table. The data in that column could be lost. The data in that column will be cast from `Decimal(10,2)` to `Decimal(15,2)`.
- You are about to alter the column `quantity` on the `Product_Variants` table. The data in that column could be lost. The data in that column will be cast from `Decimal(10,2)` to `Decimal(10,0)`.
- You are about to alter the column `alertQuantity` on the `Product_Variants` table. The data in that column could be lost. The data in that column will be cast from `Decimal(10,2)` to `Decimal(10,0)`.
- You are about to alter the column `salePrice` on the `Products` table. The data in that column could be lost. The data in that column will be cast from `Decimal(10,2)` to `Decimal(15,0)`.
- You are about to alter the column `count` on the `Purchase_Receipt_Items` table. The data in that column could be lost. The data in that column will be cast from `Decimal(10,2)` to `Decimal(10,0)`.
- You are about to alter the column `fee` on the `Purchase_Receipt_Items` table. The data in that column could be lost. The data in that column will be cast from `Decimal(10,2)` to `Decimal(15,2)`.
- You are about to alter the column `total` on the `Purchase_Receipt_Items` table. The data in that column could be lost. The data in that column will be cast from `Decimal(10,2)` to `Decimal(15,2)`.
- You are about to alter the column `amount` on the `Purchase_Receipt_Payments` table. The data in that column could be lost. The data in that column will be cast from `Decimal(10,2)` to `Decimal(15,2)`.
- You are about to drop the column `isSettled` on the `Purchase_Receipts` table. All the data in the column will be lost.
- You are about to alter the column `totalAmount` on the `Purchase_Receipts` table. The data in that column could be lost. The data in that column will be cast from `Decimal(10,2)` to `Decimal(15,2)`.
- You are about to alter the column `paidAmount` on the `Purchase_Receipts` table. The data in that column could be lost. The data in that column will be cast from `Decimal(10,2)` to `Decimal(15,2)`.
- You are about to alter the column `count` on the `Sales_Invoice_Items` table. The data in that column could be lost. The data in that column will be cast from `Decimal(10,2)` to `Decimal(10,0)`.
- You are about to alter the column `fee` on the `Sales_Invoice_Items` table. The data in that column could be lost. The data in that column will be cast from `Decimal(10,2)` to `Decimal(15,2)`.
- You are about to alter the column `total` on the `Sales_Invoice_Items` table. The data in that column could be lost. The data in that column will be cast from `Decimal(10,2)` to `Decimal(15,2)`.
- You are about to alter the column `totalAmount` on the `Sales_Invoices` table. The data in that column could be lost. The data in that column will be cast from `Decimal(10,2)` to `Decimal(15,2)`.
- You are about to alter the column `adjustedQuantity` on the `Stock_Adjustments` table. The data in that column could be lost. The data in that column will be cast from `Decimal(10,2)` to `Decimal(10,0)`.
- You are about to alter the column `quantity` on the `Stock_Movements` table. The data in that column could be lost. The data in that column will be cast from `Decimal(10,2)` to `Decimal(10,0)`.
- You are about to alter the column `fee` on the `Stock_Movements` table. The data in that column could be lost. The data in that column will be cast from `Decimal(10,2)` to `Decimal(15,2)`.
- You are about to alter the column `totalCost` on the `Stock_Movements` table. The data in that column could be lost. The data in that column will be cast from `Decimal(10,2)` to `Decimal(15,2)`.
- You are about to alter the column `avgCost` on the `Stock_Movements` table. The data in that column could be lost. The data in that column will be cast from `Decimal(10,2)` to `Decimal(15,2)`.
- You are about to alter the column `remainedInStock` on the `Stock_Movements` table. The data in that column could be lost. The data in that column will be cast from `Decimal(10,2)` to `Decimal(10,0)`.
- You are about to alter the column `debit` on the `Supplier_Ledger` table. The data in that column could be lost. The data in that column will be cast from `Decimal(10,2)` to `Decimal(15,2)`.
- You are about to alter the column `credit` on the `Supplier_Ledger` table. The data in that column could be lost. The data in that column will be cast from `Decimal(10,2)` to `Decimal(15,2)`.
- You are about to alter the column `balance` on the `Supplier_Ledger` table. The data in that column could be lost. The data in that column will be cast from `Decimal(10,2)` to `Decimal(15,2)`.
- A unique constraint covering the columns `[iban]` on the table `Bank_Accounts` will be added. If there are existing duplicate values, this will fail.
- Made the column `bankAccountId` on table `Pos_Accounts` required. This step will fail if there are existing NULL values in that column.
- Added the required column `inventoryId` to the `Purchase_Receipt_Payments` table without a default value. This is not possible if the table is not empty.
- Added the required column `type` to the `Purchase_Receipt_Payments` table without a default value. This is not possible if the table is not empty.
- Made the column `bankAccountId` on table `Purchase_Receipt_Payments` required. This step will fail if there are existing NULL values in that column.
*/
-- DropForeignKey
ALTER TABLE `Pos_Accounts`
DROP FOREIGN KEY `Pos_Accounts_bankAccountId_fkey`;
-- DropForeignKey
ALTER TABLE `Pos_Accounts`
DROP FOREIGN KEY `Pos_Accounts_bankAccountId_inventoryId_fkey`;
-- DropForeignKey
ALTER TABLE `Pos_Accounts`
DROP FOREIGN KEY `Pos_Accounts_inventoryId_fkey`;
-- DropForeignKey
ALTER TABLE `Purchase_Receipt_Payments`
DROP FOREIGN KEY `Purchase_Receipt_Payments_bankAccountId_fkey`;
-- DropIndex
DROP INDEX `Pos_Accounts_bankAccountId_inventoryId_fkey` ON `Pos_Accounts`;
-- DropIndex
DROP INDEX `Purchase_Receipt_Payments_bankAccountId_fkey` ON `Purchase_Receipt_Payments`;
-- AlterTable
ALTER TABLE `Inventory_Transfer_Items`
MODIFY `count` DECIMAL(10, 0) NOT NULL;
-- AlterTable
ALTER TABLE `Orders` MODIFY `totalAmount` DECIMAL(15, 2) NOT NULL;
-- AlterTable
ALTER TABLE `Pos_Accounts` MODIFY `bankAccountId` INTEGER NOT NULL;
-- AlterTable
ALTER TABLE `Product_Variants`
MODIFY `basePrice` DECIMAL(15, 2) NOT NULL,
MODIFY `salePrice` DECIMAL(15, 2) NOT NULL,
MODIFY `quantity` DECIMAL(10, 0) NULL DEFAULT 0.00,
MODIFY `alertQuantity` DECIMAL(10, 0) NULL DEFAULT 5.00;
-- AlterTable
ALTER TABLE `Products`
MODIFY `salePrice` DECIMAL(15, 0) NOT NULL DEFAULT 0.00;
-- AlterTable
ALTER TABLE `Purchase_Receipt_Items`
MODIFY `count` DECIMAL(10, 0) NOT NULL,
MODIFY `fee` DECIMAL(15, 2) NOT NULL,
MODIFY `total` DECIMAL(15, 2) NOT NULL;
-- AlterTable
ALTER TABLE `Purchase_Receipt_Payments`
ADD COLUMN `inventoryId` INTEGER NOT NULL,
ADD COLUMN `type` ENUM('PAYMENT', 'REFUND') NOT NULL,
MODIFY `amount` DECIMAL(15, 2) NOT NULL,
MODIFY `bankAccountId` INTEGER NOT NULL;
-- AlterTable
ALTER TABLE `Purchase_Receipts`
DROP COLUMN `isSettled`,
ADD COLUMN `status` ENUM(
'UNPAID',
'PARTIALLY_PAID',
'PAID'
) NOT NULL DEFAULT 'UNPAID',
MODIFY `totalAmount` DECIMAL(15, 2) NOT NULL,
MODIFY `paidAmount` DECIMAL(15, 2) NOT NULL DEFAULT 0.00;
-- AlterTable
ALTER TABLE `Sales_Invoice_Items`
MODIFY `count` DECIMAL(10, 0) NOT NULL,
MODIFY `fee` DECIMAL(15, 2) NOT NULL,
MODIFY `total` DECIMAL(15, 2) NOT NULL;
-- AlterTable
ALTER TABLE `Sales_Invoices`
MODIFY `totalAmount` DECIMAL(15, 2) NOT NULL;
-- AlterTable
ALTER TABLE `Stock_Adjustments`
MODIFY `adjustedQuantity` DECIMAL(10, 0) NOT NULL;
-- AlterTable
ALTER TABLE `Stock_Movements`
MODIFY `quantity` DECIMAL(10, 0) NOT NULL,
MODIFY `fee` DECIMAL(15, 2) NOT NULL,
MODIFY `totalCost` DECIMAL(15, 2) NOT NULL,
MODIFY `avgCost` DECIMAL(15, 2) NOT NULL,
MODIFY `remainedInStock` DECIMAL(10, 0) NOT NULL DEFAULT 0.00;
-- AlterTable
ALTER TABLE `Supplier_Ledger`
MODIFY `debit` DECIMAL(15, 2) NOT NULL DEFAULT 0,
MODIFY `credit` DECIMAL(15, 2) NOT NULL DEFAULT 0,
MODIFY `balance` DECIMAL(15, 2) NOT NULL;
-- CreateIndex
CREATE UNIQUE INDEX `Bank_Accounts_iban_key` ON `Bank_Accounts` (`iban`);
-- AddForeignKey
ALTER TABLE `Pos_Accounts`
ADD CONSTRAINT `Pos_Accounts_inventoryId_bankAccountId_fkey` FOREIGN KEY (
`inventoryId`,
`bankAccountId`
) REFERENCES `Inventory_Bank_Accounts` (
`inventoryId`,
`bankAccountId`
) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Purchase_Receipt_Payments`
ADD CONSTRAINT `Purchase_Receipt_Payments_inventoryId_bankAccountId_fkey` FOREIGN KEY (
`inventoryId`,
`bankAccountId`
) REFERENCES `Inventory_Bank_Accounts` (
`inventoryId`,
`bankAccountId`
) ON DELETE RESTRICT ON UPDATE CASCADE;
-- RenameIndex
ALTER TABLE `Supplier_Ledger`
RENAME INDEX `Supplier_Ledger_supplierId_fkey` TO `Supplier_Ledger_supplierId_idx`;
@@ -1,2 +0,0 @@
-- CreateIndex
CREATE INDEX `Pos_Accounts_inventoryId_idx` ON `Pos_Accounts`(`inventoryId`);
@@ -1,14 +0,0 @@
/*
Warnings:
- You are about to drop the column `inventoryId` on the `Purchase_Receipt_Payments` table. All the data in the column will be lost.
*/
-- DropForeignKey
ALTER TABLE `Purchase_Receipt_Payments` DROP FOREIGN KEY `Purchase_Receipt_Payments_inventoryId_bankAccountId_fkey`;
-- DropIndex
DROP INDEX `Purchase_Receipt_Payments_inventoryId_bankAccountId_fkey` ON `Purchase_Receipt_Payments`;
-- AlterTable
ALTER TABLE `Purchase_Receipt_Payments` DROP COLUMN `inventoryId`;
@@ -1,2 +0,0 @@
-- AddForeignKey
ALTER TABLE `Purchase_Receipt_Payments` ADD CONSTRAINT `Purchase_Receipt_Payments_bankAccountId_fkey` FOREIGN KEY (`bankAccountId`) REFERENCES `Bank_Accounts`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
@@ -1,50 +0,0 @@
/*
Warnings:
- You are about to drop the column `inventoryId` on the `Sales_Invoices` table. All the data in the column will be lost.
- Added the required column `posAccountId` to the `Sales_Invoices` table without a default value. This is not possible if the table is not empty.
*/
-- DropForeignKey
ALTER TABLE `Sales_Invoices` DROP FOREIGN KEY `Sales_Invoices_inventoryId_fkey`;
-- DropIndex
DROP INDEX `Sales_Invoices_inventoryId_fkey` ON `Sales_Invoices`;
-- AlterTable
ALTER TABLE `Purchase_Receipt_Payments` ADD COLUMN `inventoryBankAccountBankAccountId` INTEGER NULL,
ADD COLUMN `inventoryBankAccountInventoryId` INTEGER NULL;
-- AlterTable
ALTER TABLE `Sales_Invoices` DROP COLUMN `inventoryId`,
ADD COLUMN `posAccountId` INTEGER NOT NULL;
-- CreateIndex
CREATE INDEX `Sales_Invoices_posAccountId_idx` ON `Sales_Invoices`(`posAccountId`);
-- AddForeignKey
ALTER TABLE `Sales_Invoices` ADD CONSTRAINT `Sales_Invoices_posAccountId_fkey` FOREIGN KEY (`posAccountId`) REFERENCES `Pos_Accounts`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Purchase_Receipt_Payments` ADD CONSTRAINT `Purchase_Receipt_Payments_inventoryBankAccountInventoryId_i_fkey` FOREIGN KEY (`inventoryBankAccountInventoryId`, `inventoryBankAccountBankAccountId`) REFERENCES `Inventory_Bank_Accounts`(`inventoryId`, `bankAccountId`) ON DELETE SET NULL ON UPDATE CASCADE;
-- RenameIndex
ALTER TABLE `Orders` RENAME INDEX `Orders_customerId_fkey` TO `Orders_customerId_idx`;
-- RenameIndex
ALTER TABLE `Product_Variants` RENAME INDEX `products_barcode_unique` TO `Product_Variants_barcode_key`;
-- RenameIndex
ALTER TABLE `Products` RENAME INDEX `products_barcode_unique` TO `Products_barcode_key`;
-- RenameIndex
ALTER TABLE `Products` RENAME INDEX `products_sku_unique` TO `Products_sku_key`;
-- RenameIndex
ALTER TABLE `Sales_Invoice_Items` RENAME INDEX `Sales_Invoice_Items_invoiceId_fkey` TO `Sales_Invoice_Items_invoiceId_idx`;
-- RenameIndex
ALTER TABLE `Sales_Invoice_Items` RENAME INDEX `Sales_Invoice_Items_productId_fkey` TO `Sales_Invoice_Items_productId_idx`;
-- RenameIndex
ALTER TABLE `Sales_Invoices` RENAME INDEX `Sales_Invoices_customerId_fkey` TO `Sales_Invoices_customerId_idx`;
@@ -1,2 +0,0 @@
-- AlterTable
ALTER TABLE `Products` ADD COLUMN `minimumStockAlertLevel` DECIMAL(10, 0) NOT NULL DEFAULT 1.00;
@@ -84,9 +84,35 @@ CREATE TABLE `Bank_Accounts` (
UNIQUE INDEX `Bank_Accounts_accountNumber_key`(`accountNumber`),
UNIQUE INDEX `Bank_Accounts_cardNumber_key`(`cardNumber`),
UNIQUE INDEX `Bank_Accounts_iban_key`(`iban`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `Bank_Account_Transactions` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`bankAccountId` INTEGER NOT NULL,
`type` ENUM('DEPOSIT', 'WITHDRAWAL') NOT NULL,
`amount` DECIMAL(15, 2) NOT NULL,
`balanceAfter` DECIMAL(15, 2) NOT NULL,
`referenceId` INTEGER NOT NULL,
`referenceType` ENUM('PURCHASE_PAYMENT', 'PURCHASE_REFUND', 'POS_SALE', 'POS_REFUND', 'BANK_TRANSFER', 'MANUAL_ADJUSTMENT') NOT NULL,
`description` TEXT NULL,
`createdAt` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
INDEX `Bank_Account_Transactions_bankAccountId_idx`(`bankAccountId`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `Bank_Account_Balance` (
`bankAccountId` INTEGER NOT NULL,
`balance` DECIMAL(15, 2) NOT NULL,
`updatedAt` TIMESTAMP(0) NOT NULL,
UNIQUE INDEX `Bank_Account_Balance_bankAccountId_key`(`bankAccountId`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `Inventories` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
@@ -97,11 +123,36 @@ CREATE TABLE `Inventories` (
`updatedAt` TIMESTAMP(0) NOT NULL,
`deletedAt` TIMESTAMP(0) NULL,
`isPointOfSale` BOOLEAN NOT NULL DEFAULT false,
`bankAccountId` INTEGER NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `Inventory_Bank_Accounts` (
`inventoryId` INTEGER NOT NULL,
`bankAccountId` INTEGER NOT NULL,
INDEX `Inventory_Bank_Accounts_bankAccountId_idx`(`bankAccountId`),
PRIMARY KEY (`inventoryId`, `bankAccountId`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `Pos_Accounts` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
`code` VARCHAR(10) NOT NULL,
`description` VARCHAR(500) NULL,
`bankAccountId` INTEGER NOT NULL,
`inventoryId` INTEGER NOT NULL,
`createdAt` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`updatedAt` TIMESTAMP(0) NOT NULL,
`deletedAt` TIMESTAMP(0) NULL,
UNIQUE INDEX `Pos_Accounts_code_key`(`code`),
INDEX `Pos_Accounts_inventoryId_idx`(`inventoryId`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `Inventory_Transfers` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
@@ -120,7 +171,7 @@ CREATE TABLE `Inventory_Transfers` (
-- CreateTable
CREATE TABLE `Inventory_Transfer_Items` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`count` DECIMAL(10, 2) NOT NULL,
`count` DECIMAL(10, 0) NOT NULL,
`productId` INTEGER NOT NULL,
`transferId` INTEGER NOT NULL,
@@ -129,31 +180,6 @@ CREATE TABLE `Inventory_Transfer_Items` (
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `Inventory_Bank_Accounts` (
`inventoryId` INTEGER NOT NULL,
`bankAccountId` INTEGER NOT NULL,
INDEX `Inventory_Bank_Accounts_bankAccountId_idx`(`bankAccountId`),
PRIMARY KEY (`inventoryId`, `bankAccountId`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `Pos_Accounts` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
`code` VARCHAR(10) NOT NULL,
`description` VARCHAR(500) NULL,
`bankAccountId` INTEGER NULL,
`inventoryId` INTEGER NOT NULL,
`createdAt` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`updatedAt` TIMESTAMP(0) NOT NULL,
`deletedAt` TIMESTAMP(0) NULL,
UNIQUE INDEX `Pos_Accounts_code_key`(`code`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `Banks` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
@@ -168,38 +194,34 @@ CREATE TABLE `Banks` (
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `Suppliers` (
CREATE TABLE `Orders` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`firstName` VARCHAR(255) NOT NULL,
`lastName` VARCHAR(255) NOT NULL,
`email` VARCHAR(255) NULL,
`mobileNumber` CHAR(11) NOT NULL,
`address` TEXT NULL,
`city` VARCHAR(100) NULL,
`state` VARCHAR(100) NULL,
`country` VARCHAR(100) NULL,
`isActive` BOOLEAN NOT NULL DEFAULT true,
`orderNumber` VARCHAR(100) NOT NULL,
`status` ENUM('PENDING', 'REJECT', 'DONE') NOT NULL DEFAULT 'PENDING',
`totalAmount` DECIMAL(15, 2) NOT NULL,
`description` TEXT NULL,
`createdAt` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`updatedAt` TIMESTAMP(0) NOT NULL,
`deletedAt` TIMESTAMP(0) NULL,
`customerId` INTEGER NULL,
UNIQUE INDEX `Suppliers_mobileNumber_key`(`mobileNumber`),
UNIQUE INDEX `Orders_orderNumber_key`(`orderNumber`),
INDEX `Orders_customerId_idx`(`customerId`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `Supplier_Ledger` (
CREATE TABLE `Order_Items` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`description` TEXT NULL,
`debit` DECIMAL(10, 2) NOT NULL,
`credit` DECIMAL(10, 2) NOT NULL,
`balance` DECIMAL(10, 2) NOT NULL,
`sourceType` ENUM('PURCHASE', 'PAYMENT', 'ADJUSTMENT', 'REFUND') NOT NULL,
`sourceId` INTEGER NOT NULL,
`quantity` DECIMAL(10, 0) NOT NULL,
`unitPrice` DECIMAL(15, 2) NOT NULL,
`totalPrice` DECIMAL(15, 2) NOT NULL,
`createdAt` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`supplierId` INTEGER NOT NULL,
`orderId` INTEGER NOT NULL,
`productId` INTEGER NOT NULL,
INDEX `Supplier_Ledger_supplierId_fkey`(`supplierId`),
INDEX `Order_Items_orderId_idx`(`orderId`),
INDEX `Order_Items_productId_idx`(`productId`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
@@ -223,56 +245,6 @@ CREATE TABLE `Customers` (
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `Orders` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`orderNumber` VARCHAR(100) NOT NULL,
`status` ENUM('PENDING', 'REJECT', 'DONE') NOT NULL DEFAULT 'PENDING',
`paymentMethod` ENUM('CASH', 'CARD', 'BANK', 'CHECK', 'OTHER') NOT NULL DEFAULT 'CARD',
`totalAmount` DECIMAL(10, 2) NOT NULL,
`description` TEXT NULL,
`createdAt` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`updatedAt` TIMESTAMP(0) NOT NULL,
`deletedAt` TIMESTAMP(0) NULL,
`customerId` INTEGER NOT NULL,
UNIQUE INDEX `Orders_orderNumber_key`(`orderNumber`),
INDEX `Orders_customerId_fkey`(`customerId`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `Sales_Invoices` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`code` VARCHAR(100) NOT NULL,
`totalAmount` DECIMAL(10, 2) NOT NULL,
`description` TEXT NULL,
`createdAt` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`updatedAt` TIMESTAMP(0) NOT NULL,
`customerId` INTEGER NULL,
`inventoryId` INTEGER NOT NULL,
UNIQUE INDEX `Sales_Invoices_code_key`(`code`),
INDEX `Sales_Invoices_inventoryId_fkey`(`inventoryId`),
INDEX `Sales_Invoices_customerId_fkey`(`customerId`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `Sales_Invoice_Items` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`count` DECIMAL(10, 2) NOT NULL,
`fee` DECIMAL(10, 2) NOT NULL,
`total` DECIMAL(10, 2) NOT NULL,
`createdAt` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`invoiceId` INTEGER NOT NULL,
`productId` INTEGER NOT NULL,
INDEX `Sales_Invoice_Items_invoiceId_fkey`(`invoiceId`),
INDEX `Sales_Invoice_Items_productId_fkey`(`productId`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `Trigger_Logs` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
@@ -287,14 +259,14 @@ CREATE TABLE `Trigger_Logs` (
CREATE TABLE `Product_Variants` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
`basePrice` DECIMAL(10, 2) NOT NULL,
`salePrice` DECIMAL(10, 2) NOT NULL,
`basePrice` DECIMAL(15, 2) NOT NULL,
`salePrice` DECIMAL(15, 2) NOT NULL,
`description` TEXT NULL,
`barcode` VARCHAR(100) NULL,
`imageUrl` VARCHAR(255) NULL,
`unit` VARCHAR(10) NULL,
`quantity` DECIMAL(10, 2) NULL DEFAULT 0.00,
`alertQuantity` DECIMAL(10, 2) NULL DEFAULT 5.00,
`quantity` DECIMAL(10, 0) NULL DEFAULT 0.00,
`alertQuantity` DECIMAL(10, 0) NULL DEFAULT 5.00,
`isActive` BOOLEAN NOT NULL DEFAULT true,
`isFeatured` BOOLEAN NOT NULL DEFAULT false,
`createdAt` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
@@ -302,7 +274,7 @@ CREATE TABLE `Product_Variants` (
`deletedAt` TIMESTAMP(0) NULL,
`productId` INTEGER NOT NULL,
UNIQUE INDEX `products_barcode_unique`(`barcode`),
UNIQUE INDEX `Product_Variants_barcode_key`(`barcode`),
INDEX `Product_Variants_productId_fkey`(`productId`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
@@ -319,10 +291,11 @@ CREATE TABLE `Products` (
`deletedAt` TIMESTAMP(0) NULL,
`brandId` INTEGER NULL,
`categoryId` INTEGER NULL,
`salePrice` DECIMAL(10, 2) NOT NULL DEFAULT 0.00,
`salePrice` DECIMAL(15, 0) NOT NULL DEFAULT 0.00,
`minimumStockAlertLevel` DECIMAL(10, 0) NOT NULL DEFAULT 1.00,
UNIQUE INDEX `products_sku_unique`(`sku`),
UNIQUE INDEX `products_barcode_unique`(`barcode`),
UNIQUE INDEX `Products_sku_key`(`sku`),
UNIQUE INDEX `Products_barcode_key`(`barcode`),
INDEX `Products_brandId_fkey`(`brandId`),
INDEX `Products_categoryId_fkey`(`categoryId`),
PRIMARY KEY (`id`)
@@ -358,12 +331,12 @@ CREATE TABLE `Product_categories` (
CREATE TABLE `Purchase_Receipts` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`code` VARCHAR(100) NOT NULL,
`totalAmount` DECIMAL(10, 2) NOT NULL,
`paidAmount` DECIMAL(10, 2) NOT NULL DEFAULT 0.00,
`isSettled` BOOLEAN NOT NULL DEFAULT false,
`totalAmount` DECIMAL(15, 2) NOT NULL,
`paidAmount` DECIMAL(15, 2) NOT NULL DEFAULT 0.00,
`description` TEXT NULL,
`createdAt` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`updatedAt` TIMESTAMP(0) NOT NULL,
`status` ENUM('UNPAID', 'PARTIALLY_PAID', 'PAID') NOT NULL DEFAULT 'UNPAID',
`supplierId` INTEGER NOT NULL,
`inventoryId` INTEGER NOT NULL,
@@ -376,13 +349,13 @@ CREATE TABLE `Purchase_Receipts` (
-- CreateTable
CREATE TABLE `Purchase_Receipt_Items` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`count` DECIMAL(10, 2) NOT NULL,
`fee` DECIMAL(10, 2) NOT NULL,
`total` DECIMAL(10, 2) NOT NULL,
`description` TEXT NULL,
`createdAt` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`count` DECIMAL(10, 0) NOT NULL,
`unitPrice` DECIMAL(15, 2) NOT NULL,
`totalPrice` DECIMAL(15, 2) NOT NULL,
`receiptId` INTEGER NOT NULL,
`productId` INTEGER NOT NULL,
`description` TEXT NULL,
`createdAt` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
INDEX `Purchase_Receipt_Items_productId_fkey`(`productId`),
INDEX `Purchase_Receipt_Items_receiptId_fkey`(`receiptId`),
@@ -392,16 +365,63 @@ CREATE TABLE `Purchase_Receipt_Items` (
-- CreateTable
CREATE TABLE `Purchase_Receipt_Payments` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`amount` DECIMAL(10, 2) NOT NULL,
`amount` DECIMAL(15, 2) NOT NULL,
`paymentMethod` ENUM('CASH', 'CARD', 'BANK', 'CHECK', 'OTHER') NOT NULL,
`bankAccountId` INTEGER NULL,
`description` TEXT NULL,
`payedAt` TIMESTAMP(0) NOT NULL,
`type` ENUM('PAYMENT', 'REFUND') NOT NULL,
`bankAccountId` INTEGER NOT NULL,
`receiptId` INTEGER NOT NULL,
`payedAt` TIMESTAMP(0) NOT NULL,
`description` TEXT NULL,
`createdAt` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`inventoryBankAccountInventoryId` INTEGER NULL,
`inventoryBankAccountBankAccountId` INTEGER NULL,
INDEX `Purchase_Receipt_Payments_receiptId_fkey`(`receiptId`),
INDEX `Purchase_Receipt_Payments_bankAccountId_fkey`(`bankAccountId`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `Sales_Invoices` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`code` VARCHAR(100) NOT NULL,
`totalAmount` DECIMAL(15, 2) NOT NULL,
`description` TEXT NULL,
`createdAt` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`updatedAt` TIMESTAMP(0) NOT NULL,
`customerId` INTEGER NULL,
`posAccountId` INTEGER NOT NULL,
UNIQUE INDEX `Sales_Invoices_code_key`(`code`),
INDEX `Sales_Invoices_customerId_idx`(`customerId`),
INDEX `Sales_Invoices_posAccountId_idx`(`posAccountId`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `Sales_Invoice_Items` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`count` DECIMAL(10, 0) NOT NULL,
`unitPrice` DECIMAL(15, 2) NOT NULL DEFAULT 0.00,
`totalPrice` DECIMAL(15, 2) NOT NULL DEFAULT 0.00,
`createdAt` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`invoiceId` INTEGER NOT NULL,
`productId` INTEGER NOT NULL,
INDEX `Sales_Invoice_Items_invoiceId_idx`(`invoiceId`),
INDEX `Sales_Invoice_Items_productId_idx`(`productId`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `SalesInvoicePayment` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`invoiceId` INTEGER NOT NULL,
`amount` DECIMAL(15, 2) NOT NULL,
`paymentMethod` ENUM('CASH', 'CARD', 'BANK', 'CHECK', 'OTHER') NOT NULL,
`paidAt` DATETIME(3) NOT NULL,
`createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
INDEX `SalesInvoicePayment_invoiceId_idx`(`invoiceId`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
@@ -409,17 +429,17 @@ CREATE TABLE `Purchase_Receipt_Payments` (
CREATE TABLE `Stock_Movements` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`type` ENUM('IN', 'OUT', 'ADJUST') NOT NULL,
`quantity` DECIMAL(10, 2) NOT NULL,
`fee` DECIMAL(10, 2) NOT NULL,
`totalCost` DECIMAL(10, 2) NOT NULL,
`quantity` DECIMAL(10, 0) NOT NULL,
`unitPrice` DECIMAL(15, 2) NOT NULL,
`totalCost` DECIMAL(15, 2) NOT NULL,
`referenceType` ENUM('PURCHASE', 'SALES', 'ADJUSTMENT', 'INVENTORY_TRANSFER') NOT NULL,
`referenceId` VARCHAR(191) NOT NULL,
`createdAt` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`productId` INTEGER NOT NULL,
`inventoryId` INTEGER NOT NULL,
`avgCost` DECIMAL(10, 2) NOT NULL,
`avgCost` DECIMAL(15, 2) NOT NULL,
`supplierId` INTEGER NULL,
`remainedInStock` DECIMAL(10, 2) NOT NULL DEFAULT 0.00,
`remainedInStock` DECIMAL(10, 0) NOT NULL DEFAULT 0.00,
`counterInventoryId` INTEGER NULL,
`customerId` INTEGER NULL,
@@ -451,7 +471,7 @@ CREATE TABLE `Stock_Balance` (
-- CreateTable
CREATE TABLE `Stock_Adjustments` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`adjustedQuantity` DECIMAL(10, 2) NOT NULL,
`adjustedQuantity` DECIMAL(10, 0) NOT NULL,
`createdAt` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`productId` INTEGER NOT NULL,
`inventoryId` INTEGER NOT NULL,
@@ -462,12 +482,54 @@ CREATE TABLE `Stock_Adjustments` (
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `_Bank_Accounts_inventoryId_fkey` (
`A` INTEGER NOT NULL,
`B` INTEGER NOT NULL,
CREATE TABLE `Stock_Reservations` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`quantity` DECIMAL(10, 0) NOT NULL,
`expiresAt` TIMESTAMP(0) NOT NULL,
`createdAt` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`productId` INTEGER NOT NULL,
`inventoryId` INTEGER NOT NULL,
`orderId` INTEGER NOT NULL,
UNIQUE INDEX `_Bank_Accounts_inventoryId_fkey_AB_unique`(`A`, `B`),
INDEX `_Bank_Accounts_inventoryId_fkey_B_index`(`B`)
INDEX `Stock_Reservations_inventoryId_idx`(`inventoryId`),
INDEX `Stock_Reservations_productId_idx`(`productId`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `Suppliers` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`firstName` VARCHAR(255) NOT NULL,
`lastName` VARCHAR(255) NOT NULL,
`email` VARCHAR(255) NULL,
`mobileNumber` CHAR(11) NOT NULL,
`address` TEXT NULL,
`city` VARCHAR(100) NULL,
`state` VARCHAR(100) NULL,
`country` VARCHAR(100) NULL,
`isActive` BOOLEAN NOT NULL DEFAULT true,
`createdAt` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`updatedAt` TIMESTAMP(0) NOT NULL,
`deletedAt` TIMESTAMP(0) NULL,
UNIQUE INDEX `Suppliers_mobileNumber_key`(`mobileNumber`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `Supplier_Ledger` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`description` TEXT NULL,
`debit` DECIMAL(15, 2) NOT NULL DEFAULT 0,
`credit` DECIMAL(15, 2) NOT NULL DEFAULT 0,
`balance` DECIMAL(15, 2) NOT NULL,
`sourceType` ENUM('PURCHASE', 'PAYMENT', 'ADJUSTMENT', 'REFUND') NOT NULL,
`sourceId` INTEGER NOT NULL,
`createdAt` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`supplierId` INTEGER NOT NULL,
INDEX `Supplier_Ledger_supplierId_idx`(`supplierId`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- AddForeignKey
@@ -482,6 +544,21 @@ ALTER TABLE `Bank_Branches` ADD CONSTRAINT `Bank_Branches_bankId_fkey` FOREIGN K
-- AddForeignKey
ALTER TABLE `Bank_Accounts` ADD CONSTRAINT `Bank_Accounts_branchId_fkey` FOREIGN KEY (`branchId`) REFERENCES `Bank_Branches`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Bank_Account_Transactions` ADD CONSTRAINT `Bank_Account_Transactions_bankAccountId_fkey` FOREIGN KEY (`bankAccountId`) REFERENCES `Bank_Accounts`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Bank_Account_Balance` ADD CONSTRAINT `Bank_Account_Balance_bankAccountId_fkey` FOREIGN KEY (`bankAccountId`) REFERENCES `Bank_Accounts`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Inventory_Bank_Accounts` ADD CONSTRAINT `Inventory_Bank_Accounts_inventoryId_fkey` FOREIGN KEY (`inventoryId`) REFERENCES `Inventories`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Inventory_Bank_Accounts` ADD CONSTRAINT `Inventory_Bank_Accounts_bankAccountId_fkey` FOREIGN KEY (`bankAccountId`) REFERENCES `Bank_Accounts`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Pos_Accounts` ADD CONSTRAINT `Pos_Accounts_inventoryId_bankAccountId_fkey` FOREIGN KEY (`inventoryId`, `bankAccountId`) REFERENCES `Inventory_Bank_Accounts`(`inventoryId`, `bankAccountId`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Inventory_Transfers` ADD CONSTRAINT `Inventory_Transfers_fromInventoryId_fkey` FOREIGN KEY (`fromInventoryId`) REFERENCES `Inventories`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
@@ -495,37 +572,13 @@ ALTER TABLE `Inventory_Transfer_Items` ADD CONSTRAINT `Inventory_Transfer_Items_
ALTER TABLE `Inventory_Transfer_Items` ADD CONSTRAINT `Inventory_Transfer_Items_transferId_fkey` FOREIGN KEY (`transferId`) REFERENCES `Inventory_Transfers`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Inventory_Bank_Accounts` ADD CONSTRAINT `Inventory_Bank_Accounts_inventoryId_fkey` FOREIGN KEY (`inventoryId`) REFERENCES `Inventories`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE `Orders` ADD CONSTRAINT `Orders_customerId_fkey` FOREIGN KEY (`customerId`) REFERENCES `Customers`(`id`) ON DELETE SET NULL ON UPDATE NO ACTION;
-- AddForeignKey
ALTER TABLE `Inventory_Bank_Accounts` ADD CONSTRAINT `Inventory_Bank_Accounts_bankAccountId_fkey` FOREIGN KEY (`bankAccountId`) REFERENCES `Bank_Accounts`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE `Order_Items` ADD CONSTRAINT `Order_Items_orderId_fkey` FOREIGN KEY (`orderId`) REFERENCES `Orders`(`id`) ON DELETE RESTRICT ON UPDATE NO ACTION;
-- AddForeignKey
ALTER TABLE `Pos_Accounts` ADD CONSTRAINT `Pos_Accounts_inventoryId_fkey` FOREIGN KEY (`inventoryId`) REFERENCES `Inventories`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Pos_Accounts` ADD CONSTRAINT `Pos_Accounts_bankAccountId_inventoryId_fkey` FOREIGN KEY (`bankAccountId`, `inventoryId`) REFERENCES `Inventory_Bank_Accounts`(`bankAccountId`, `inventoryId`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Pos_Accounts` ADD CONSTRAINT `Pos_Accounts_bankAccountId_fkey` FOREIGN KEY (`bankAccountId`) REFERENCES `Bank_Accounts`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Supplier_Ledger` ADD CONSTRAINT `Supplier_Ledger_supplierId_fkey` FOREIGN KEY (`supplierId`) REFERENCES `Suppliers`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Orders` ADD CONSTRAINT `Orders_customerId_fkey` FOREIGN KEY (`customerId`) REFERENCES `Customers`(`id`) ON DELETE RESTRICT ON UPDATE NO ACTION;
-- AddForeignKey
ALTER TABLE `Sales_Invoices` ADD CONSTRAINT `Sales_Invoices_customerId_fkey` FOREIGN KEY (`customerId`) REFERENCES `Customers`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Sales_Invoices` ADD CONSTRAINT `Sales_Invoices_inventoryId_fkey` FOREIGN KEY (`inventoryId`) REFERENCES `Inventories`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Sales_Invoice_Items` ADD CONSTRAINT `Sales_Invoice_Items_invoiceId_fkey` FOREIGN KEY (`invoiceId`) REFERENCES `Sales_Invoices`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Sales_Invoice_Items` ADD CONSTRAINT `Sales_Invoice_Items_productId_fkey` FOREIGN KEY (`productId`) REFERENCES `Products`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE `Order_Items` ADD CONSTRAINT `Order_Items_productId_fkey` FOREIGN KEY (`productId`) REFERENCES `Products`(`id`) ON DELETE RESTRICT ON UPDATE NO ACTION;
-- AddForeignKey
ALTER TABLE `Product_Variants` ADD CONSTRAINT `Product_Variants_productId_fkey` FOREIGN KEY (`productId`) REFERENCES `Products`(`id`) ON DELETE RESTRICT ON UPDATE NO ACTION;
@@ -552,7 +605,25 @@ ALTER TABLE `Purchase_Receipt_Items` ADD CONSTRAINT `Purchase_Receipt_Items_rece
ALTER TABLE `Purchase_Receipt_Payments` ADD CONSTRAINT `Purchase_Receipt_Payments_receiptId_fkey` FOREIGN KEY (`receiptId`) REFERENCES `Purchase_Receipts`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Purchase_Receipt_Payments` ADD CONSTRAINT `Purchase_Receipt_Payments_bankAccountId_fkey` FOREIGN KEY (`bankAccountId`) REFERENCES `Bank_Accounts`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE `Purchase_Receipt_Payments` ADD CONSTRAINT `Purchase_Receipt_Payments_bankAccountId_fkey` FOREIGN KEY (`bankAccountId`) REFERENCES `Bank_Accounts`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Purchase_Receipt_Payments` ADD CONSTRAINT `Purchase_Receipt_Payments_inventoryBankAccountInventoryId_i_fkey` FOREIGN KEY (`inventoryBankAccountInventoryId`, `inventoryBankAccountBankAccountId`) REFERENCES `Inventory_Bank_Accounts`(`inventoryId`, `bankAccountId`) ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Sales_Invoices` ADD CONSTRAINT `Sales_Invoices_customerId_fkey` FOREIGN KEY (`customerId`) REFERENCES `Customers`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Sales_Invoices` ADD CONSTRAINT `Sales_Invoices_posAccountId_fkey` FOREIGN KEY (`posAccountId`) REFERENCES `Pos_Accounts`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Sales_Invoice_Items` ADD CONSTRAINT `Sales_Invoice_Items_invoiceId_fkey` FOREIGN KEY (`invoiceId`) REFERENCES `Sales_Invoices`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Sales_Invoice_Items` ADD CONSTRAINT `Sales_Invoice_Items_productId_fkey` FOREIGN KEY (`productId`) REFERENCES `Products`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `SalesInvoicePayment` ADD CONSTRAINT `SalesInvoicePayment_invoiceId_fkey` FOREIGN KEY (`invoiceId`) REFERENCES `Sales_Invoices`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Stock_Movements` ADD CONSTRAINT `Stock_Movements_counterInventoryId_fkey` FOREIGN KEY (`counterInventoryId`) REFERENCES `Inventories`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
@@ -582,7 +653,10 @@ ALTER TABLE `Stock_Adjustments` ADD CONSTRAINT `Stock_Adjustments_inventoryId_fk
ALTER TABLE `Stock_Adjustments` ADD CONSTRAINT `Stock_Adjustments_productId_fkey` FOREIGN KEY (`productId`) REFERENCES `Products`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `_Bank_Accounts_inventoryId_fkey` ADD CONSTRAINT `_Bank_Accounts_inventoryId_fkey_A_fkey` FOREIGN KEY (`A`) REFERENCES `Bank_Accounts`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE `Stock_Reservations` ADD CONSTRAINT `Stock_Reservations_inventoryId_fkey` FOREIGN KEY (`inventoryId`) REFERENCES `Inventories`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `_Bank_Accounts_inventoryId_fkey` ADD CONSTRAINT `_Bank_Accounts_inventoryId_fkey_B_fkey` FOREIGN KEY (`B`) REFERENCES `Inventories`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE `Stock_Reservations` ADD CONSTRAINT `Stock_Reservations_productId_fkey` FOREIGN KEY (`productId`) REFERENCES `Products`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Supplier_Ledger` ADD CONSTRAINT `Supplier_Ledger_supplierId_fkey` FOREIGN KEY (`supplierId`) REFERENCES `Suppliers`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
@@ -0,0 +1,21 @@
/*
Warnings:
- You are about to drop the column `totalPrice` on the `Order_Items` table. All the data in the column will be lost.
- You are about to drop the column `totalPrice` on the `Purchase_Receipt_Items` table. All the data in the column will be lost.
- You are about to drop the column `totalPrice` on the `Sales_Invoice_Items` table. All the data in the column will be lost.
- Added the required column `totalAmount` to the `Order_Items` table without a default value. This is not possible if the table is not empty.
- Added the required column `totalAmount` to the `Purchase_Receipt_Items` table without a default value. This is not possible if the table is not empty.
*/
-- AlterTable
ALTER TABLE `Order_Items` DROP COLUMN `totalPrice`,
ADD COLUMN `totalAmount` DECIMAL(15, 2) NOT NULL;
-- AlterTable
ALTER TABLE `Purchase_Receipt_Items` DROP COLUMN `totalPrice`,
ADD COLUMN `totalAmount` DECIMAL(15, 2) NOT NULL;
-- AlterTable
ALTER TABLE `Sales_Invoice_Items` DROP COLUMN `totalPrice`,
ADD COLUMN `totalAmount` DECIMAL(15, 2) NOT NULL DEFAULT 0.00;
@@ -0,0 +1,27 @@
/*
Warnings:
- You are about to drop the `SalesInvoicePayment` table. If the table is not empty, all the data it contains will be lost.
*/
-- DropForeignKey
ALTER TABLE `SalesInvoicePayment` DROP FOREIGN KEY `SalesInvoicePayment_invoiceId_fkey`;
-- DropTable
DROP TABLE `SalesInvoicePayment`;
-- CreateTable
CREATE TABLE `Sales_Invoice_Payments` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`invoiceId` INTEGER NOT NULL,
`amount` DECIMAL(15, 2) NOT NULL,
`paymentMethod` ENUM('CASH', 'CARD', 'BANK', 'CHECK', 'OTHER') NOT NULL,
`paidAt` DATETIME(3) NOT NULL,
`createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
INDEX `Sales_Invoice_Payments_invoiceId_idx`(`invoiceId`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- AddForeignKey
ALTER TABLE `Sales_Invoice_Payments` ADD CONSTRAINT `Sales_Invoice_Payments_invoiceId_fkey` FOREIGN KEY (`invoiceId`) REFERENCES `Sales_Invoices`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
@@ -0,0 +1,8 @@
/*
Warnings:
- The values [REJECT] on the enum `Orders_status` will be removed. If these variants are still used in the database, this will fail.
*/
-- AlterTable
ALTER TABLE `Orders` MODIFY `status` ENUM('PENDING', 'REJECTED', 'CANCELED', 'DONE') NOT NULL DEFAULT 'PENDING';
+10 -10
View File
@@ -25,13 +25,13 @@ DECLARE fromInv INT;
-- OUT from source
INSERT INTO Stock_Movements
(type, quantity, fee, totalCost, avgCost, referenceType, referenceId, productId, inventoryId, counterInventoryId, createdAt, remainedInStock)
(type, quantity, unitPrice, totalCost, avgCost, referenceType, referenceId, productId, inventoryId, counterInventoryId, createdAt, remainedInStock)
VALUES
('OUT', NEW.count, _avgCost, _avgCost*NEW.count, _avgCost, 'INVENTORY_TRANSFER', NEW.transferId, NEW.productId, fromInv, toInv, NOW(), latestQuantityInOrigin-NEW.count);
-- IN to destination
INSERT INTO Stock_Movements
(type, quantity, fee, totalCost, avgCost, referenceType, referenceId, productId, inventoryId, counterInventoryId, createdAt, remainedInStock)
(type, quantity, unitPrice, totalCost, avgCost, referenceType, referenceId, productId, inventoryId, counterInventoryId, createdAt, remainedInStock)
VALUES
('IN', NEW.count,_avgCost, _avgCost*NEW.count,_avgCost, 'INVENTORY_TRANSFER', NEW.transferId, NEW.productId, toInv, fromInv, NOW(), latestQuantityInOrigin-NEW.count);
end;
@@ -66,7 +66,7 @@ DECLARE invId INT;
INSERT INTO Stock_Movements (
type,
quantity,
fee,
unitPrice,
totalCost,
referenceType,
referenceId,
@@ -80,7 +80,7 @@ DECLARE invId INT;
VALUES (
'IN',
NEW.count,
NEW.fee,
NEW.unitPrice,
NEW.total,
'PURCHASE',
NEW.receiptId,
@@ -157,7 +157,7 @@ DECLARE customer_id INT;
INSERT INTO Stock_Movements (
type,
quantity,
fee,
unitPrice,
totalCost,
referenceType,
referenceId,
@@ -171,7 +171,7 @@ DECLARE customer_id INT;
VALUES (
'OUT',
NEW.count,
NEW.fee,
NEW.unitPrice,
NEW.total,
'SALES',
NEW.invoiceId,
@@ -260,8 +260,8 @@ VALUES (
NEW.productId,
NEW.inventoryId,
- NEW.quantity,
- COALESCE(NEW.fee, 0) * NEW.quantity,
COALESCE(NEW.fee, 0),
- COALESCE(NEW.unitPrice, 0) * NEW.quantity,
COALESCE(NEW.unitPrice, 0),
NOW()
);
@@ -294,7 +294,7 @@ INSERT INTO
VALUES (
NEW.productId,
NEW.quantity,
NEW.fee,
NEW.unitPrice,
NEW.totalCost,
NEW.inventoryId,
NOW()
@@ -329,7 +329,7 @@ INSERT INTO
VALUES (
NEW.productId,
NEW.quantity,
NEW.fee,
NEW.unitPrice,
NEW.totalCost,
NEW.inventoryId,
NOW()
+29
View File
@@ -28,6 +28,35 @@ model BankAccount {
branch BankBranch @relation("Bank_Accounts_branchId_fkey", fields: [branchId], references: [id])
inventoryBankAccounts InventoryBankAccount[]
purchaseReceiptPayments PurchaseReceiptPayments[]
bankAccountTransactions BankAccountTransaction[]
bankAccountBalances BankAccountBalance[]
@@map("Bank_Accounts")
}
model BankAccountTransaction {
id Int @id @default(autoincrement())
bankAccountId Int
type BankAccountTransactionType
amount Decimal @db.Decimal(15, 2)
balanceAfter Decimal @db.Decimal(15, 2)
referenceId Int
referenceType BankTransactionRefType
description String? @db.Text
createdAt DateTime @default(now()) @db.Timestamp(0)
bankAccount BankAccount @relation(fields: [bankAccountId], references: [id])
@@index([bankAccountId])
@@map("Bank_Account_Transactions")
}
model BankAccountBalance {
bankAccountId Int @unique
balance Decimal @db.Decimal(15, 2)
updatedAt DateTime @updatedAt @db.Timestamp(0)
bankAccount BankAccount @relation(fields: [bankAccountId], references: [id])
@@map("Bank_Account_Balance")
}
+16 -1
View File
@@ -1,6 +1,7 @@
enum OrderStatus {
PENDING
REJECT
REJECTED
CANCELED
DONE
}
@@ -42,3 +43,17 @@ enum PurchaseReceiptStatus {
PARTIALLY_PAID
PAID
}
enum BankAccountTransactionType {
DEPOSIT
WITHDRAWAL
}
enum BankTransactionRefType {
PURCHASE_PAYMENT
PURCHASE_REFUND
POS_SALE
POS_REFUND
BANK_TRANSFER
MANUAL_ADJUSTMENT
}
+1
View File
@@ -15,6 +15,7 @@ model Inventory {
counterStockMovements StockMovement[] @relation("StockMovement_CounterInventory")
stockMovements StockMovement[] @relation("StockMovement_Inventory")
inventoryBankAccounts InventoryBankAccount[]
stockReservations StockReservation[]
@@map("Inventories")
}
+33
View File
@@ -0,0 +1,33 @@
model Order {
id Int @id @default(autoincrement())
orderNumber String @unique @db.VarChar(100)
status OrderStatus @default(PENDING)
totalAmount Decimal @db.Decimal(15, 2)
description String? @db.Text
createdAt DateTime @default(now()) @db.Timestamp(0)
updatedAt DateTime @updatedAt @db.Timestamp(0)
deletedAt DateTime? @db.Timestamp(0)
customerId Int?
customer Customer? @relation(fields: [customerId], references: [id], onUpdate: NoAction)
orderItems OrderItem[]
@@index([customerId])
@@map("Orders")
}
model OrderItem {
id Int @id @default(autoincrement())
quantity Decimal @db.Decimal(10, 0)
unitPrice Decimal @db.Decimal(15, 2)
totalAmount Decimal @db.Decimal(15, 2)
createdAt DateTime @default(now()) @db.Timestamp(0)
orderId Int
productId Int
order Order @relation(fields: [orderId], references: [id], onUpdate: NoAction)
product Product @relation(fields: [productId], references: [id], onUpdate: NoAction)
@@index([orderId])
@@index([productId])
@@map("Order_Items")
}
-51
View File
@@ -19,57 +19,6 @@ model Customer {
@@map("Customers")
}
model Order {
id Int @id @default(autoincrement())
orderNumber String @unique @db.VarChar(100)
status OrderStatus @default(PENDING)
paymentMethod PaymentMethodType @default(CARD)
totalAmount Decimal @db.Decimal(15, 2)
description String? @db.Text
createdAt DateTime @default(now()) @db.Timestamp(0)
updatedAt DateTime @updatedAt @db.Timestamp(0)
deletedAt DateTime? @db.Timestamp(0)
customerId Int
customer Customer @relation(fields: [customerId], references: [id], onUpdate: NoAction)
@@index([customerId])
@@map("Orders")
}
model SalesInvoice {
id Int @id @default(autoincrement())
code String @unique @db.VarChar(100)
totalAmount Decimal @db.Decimal(15, 2)
description String? @db.Text
createdAt DateTime @default(now()) @db.Timestamp(0)
updatedAt DateTime @updatedAt @db.Timestamp(0)
customerId Int?
posAccountId Int
items SalesInvoiceItem[]
customer Customer? @relation(fields: [customerId], references: [id])
posAccount PosAccount @relation(fields: [posAccountId], references: [id])
@@index([customerId])
@@index([posAccountId])
@@map("Sales_Invoices")
}
model SalesInvoiceItem {
id Int @id @default(autoincrement())
count Decimal @db.Decimal(10, 0)
fee Decimal @db.Decimal(15, 2)
total Decimal @db.Decimal(15, 2)
createdAt DateTime @default(now()) @db.Timestamp(0)
invoiceId Int
productId Int
invoice SalesInvoice @relation(fields: [invoiceId], references: [id])
product Product @relation(fields: [productId], references: [id])
@@index([invoiceId])
@@index([productId])
@@map("Sales_Invoice_Items")
}
model TriggerLog {
id Int @id @default(autoincrement())
message String @db.Text
+2
View File
@@ -43,6 +43,8 @@ model Product {
stockBalances StockBalance[] @relation("StockBalance_Product")
stockMovements StockMovement[] @relation("StockMovement_Product")
salesInvoiceItems SalesInvoiceItem[]
stockReservations StockReservation[]
orderItems OrderItem[]
@@index([brandId], map: "Products_brandId_fkey")
@@index([categoryId], map: "Products_categoryId_fkey")
+2 -2
View File
@@ -22,8 +22,8 @@ model PurchaseReceipt {
model PurchaseReceiptItem {
id Int @id @default(autoincrement())
count Decimal @db.Decimal(10, 0)
fee Decimal @db.Decimal(15, 2)
total Decimal @db.Decimal(15, 2)
unitPrice Decimal @db.Decimal(15, 2)
totalAmount Decimal @db.Decimal(15, 2)
receiptId Int
productId Int
description String? @db.Text
+48
View File
@@ -0,0 +1,48 @@
model SalesInvoice {
id Int @id @default(autoincrement())
code String @unique @db.VarChar(100)
totalAmount Decimal @db.Decimal(15, 2)
description String? @db.Text
createdAt DateTime @default(now()) @db.Timestamp(0)
updatedAt DateTime @updatedAt @db.Timestamp(0)
customerId Int?
posAccountId Int
customer Customer? @relation(fields: [customerId], references: [id])
posAccount PosAccount @relation(fields: [posAccountId], references: [id])
items SalesInvoiceItem[]
salesInvoicePayments SalesInvoicePayment[]
@@index([customerId])
@@index([posAccountId])
@@map("Sales_Invoices")
}
model SalesInvoiceItem {
id Int @id @default(autoincrement())
count Decimal @db.Decimal(10, 0)
unitPrice Decimal @default(0.00) @db.Decimal(15, 2)
totalAmount Decimal @default(0.00) @db.Decimal(15, 2)
createdAt DateTime @default(now()) @db.Timestamp(0)
invoiceId Int
productId Int
invoice SalesInvoice @relation(fields: [invoiceId], references: [id])
product Product @relation(fields: [productId], references: [id])
@@index([invoiceId])
@@index([productId])
@@map("Sales_Invoice_Items")
}
model SalesInvoicePayment {
id Int @id @default(autoincrement())
invoiceId Int
amount Decimal @db.Decimal(15, 2)
paymentMethod PaymentMethodType
paidAt DateTime
createdAt DateTime @default(now())
invoice SalesInvoice @relation(fields: [invoiceId], references: [id])
@@index([invoiceId])
@@map("Sales_Invoice_Payments")
}
+17 -1
View File
@@ -2,7 +2,7 @@ model StockMovement {
id Int @id @default(autoincrement())
type MovementType
quantity Decimal @db.Decimal(10, 0)
fee Decimal @db.Decimal(15, 2)
unitPrice Decimal @db.Decimal(15, 2)
totalCost Decimal @db.Decimal(15, 2)
referenceType MovementReferenceType
referenceId String
@@ -59,3 +59,19 @@ model StockAdjustment {
@@index([productId], map: "Stock_Adjustments_productId_fkey")
@@map("Stock_Adjustments")
}
model StockReservation {
id Int @id @default(autoincrement())
quantity Decimal @db.Decimal(10, 0)
expiresAt DateTime @db.Timestamp(0)
createdAt DateTime @default(now()) @db.Timestamp(0)
productId Int
inventoryId Int
orderId Int
inventory Inventory @relation(fields: [inventoryId], references: [id])
product Product @relation(fields: [productId], references: [id])
@@index([inventoryId])
@@index([productId])
@@map("Stock_Reservations")
}
+49 -61
View File
@@ -10,7 +10,6 @@ async function main() {
},
})
}
if ((await prisma.user.count()) === 0) {
const adminRole = await prisma.role.findUnique({ where: { name: 'Admin' } })
if (!adminRole) {
@@ -28,7 +27,6 @@ async function main() {
},
})
}
if ((await prisma.inventory.count()) === 0) {
await prisma.inventory.createMany({
data: [
@@ -48,19 +46,16 @@ async function main() {
],
})
}
if ((await prisma.productCategory.count()) === 0) {
await prisma.productCategory.createMany({
data: Array.from({ length: 10 }, (_, i) => ({ name: `دسته‌ی ${i + 1}` })),
})
}
if ((await prisma.productBrand.count()) === 0) {
await prisma.productBrand.createMany({
data: Array.from({ length: 10 }, (_, i) => ({ name: `برند ${i + 1}` })),
})
}
if ((await prisma.supplier.count()) === 0) {
await prisma.supplier.createMany({
data: Array.from({ length: 9 }, (_, i) => ({
@@ -71,7 +66,6 @@ async function main() {
})),
})
}
if ((await prisma.customer.count()) === 0) {
await prisma.customer.createMany({
data: Array.from({ length: 5 }, (_, i) => ({
@@ -82,12 +76,11 @@ async function main() {
})),
})
}
if ((await prisma.product.count()) === 0) {
const categories = await prisma.productCategory.findMany()
const brands = await prisma.productBrand.findMany()
await prisma.product.createMany({
data: Array.from({ length: 100 }, (_, i) => ({
data: Array.from({ length: 20 }, (_, i) => ({
name: `کالای ${i + 1}`,
sku: `SKU-${1000 + i + 1}`,
salePrice: parseInt((Math.random() * (100 - 10) + 10).toString()) * 10000,
@@ -96,7 +89,6 @@ async function main() {
})),
})
}
if ((await prisma.bank.count()) === 0) {
await prisma.bank.createMany({
data: [
@@ -231,7 +223,6 @@ async function main() {
],
})
}
if ((await prisma.bankBranch.count()) === 0) {
await prisma.bankBranch.createMany({
data: [
@@ -253,7 +244,6 @@ async function main() {
],
})
}
if ((await prisma.bankAccount.count()) === 0) {
await prisma.bankAccount.createMany({
data: [
@@ -278,56 +268,54 @@ async function main() {
],
})
}
if ((await prisma.inventoryBankAccount.count()) === 0) {
const inventories = await prisma.inventory.findMany()
const bankAccounts = await prisma.bankAccount.findMany()
if (inventories.length || bankAccounts.length) {
// Assign bank accounts to inventories
const inventoryBankAccounts = []
for (let i = 0; i < inventories.length; i++) {
const inventory = inventories[i]
const bankAccount = bankAccounts[i % bankAccounts.length] // Cycle through bank accounts
// @ts-ignore
inventoryBankAccounts.push({
inventoryId: inventory.id,
bankAccountId: bankAccount.id,
})
}
await prisma.inventoryBankAccount.createMany({
data: inventoryBankAccounts,
})
}
}
if ((await prisma.posAccount.count()) === 0) {
const inventories = await prisma.inventory.findMany({
where: { isPointOfSale: true },
})
const inventoryBankAccounts = await prisma.inventoryBankAccount.findMany()
const posAccounts = []
for (let i = 0; i < inventories.length; i++) {
const inventory = inventories[i]
// Find a bank account assigned to this inventory
const inventoryBankAccount = inventoryBankAccounts.find(
iba => iba.inventoryId === inventory.id,
)
if (inventoryBankAccount) {
// @ts-ignore
// if ((await prisma.inventoryBankAccount.count()) === 0) {
// const inventories = await prisma.inventory.findMany()
// const bankAccounts = await prisma.bankAccount.findMany()
// // Assign bank accounts to inventories
// const inventoryBankAccounts = []
// for (let i = 0; i < inventories.length; i++) {
// const inventory = inventories[i]
// const bankAccount = bankAccounts[i % bankAccounts.length] // Cycle through bank accounts
// inventoryBankAccounts.push({
// inventoryId: inventory.id,
// bankAccountId: bankAccount.id,
// })
// }
// await prisma.inventoryBankAccount.createMany({
// data: inventoryBankAccounts,
// })
// }
// if ((await prisma.posAccount.count()) === 0) {
// const inventories = await prisma.inventory.findMany({
// where: { isPointOfSale: true },
// })
// const inventoryBankAccounts = await prisma.inventoryBankAccount.findMany()
// const posAccounts = []
// for (let i = 0; i < inventories.length; i++) {
// const inventory = inventories[i]
// // Find a bank account assigned to this inventory
// const inventoryBankAccount = inventoryBankAccounts.find(
// iba => iba.inventoryId === inventory.id,
// )
// if (inventoryBankAccount) {
// posAccounts.push({
// name: `پوز ${inventory.name}`,
// code: `POS${(i + 1).toString().padStart(3, '0')}`,
// description: `پوز فروشگاه ${inventory.name}`,
// inventoryId: inventory.id,
// bankAccountId: inventoryBankAccount.bankAccountId,
// })
// }
// }
// await prisma.posAccount.createMany({
// data: posAccounts,
// })
// }
posAccounts.push({
name: `پوز ${inventory.name}`,
code: `POS${(i + 1).toString().padStart(3, '0')}`,
description: `پوز فروشگاه ${inventory.name}`,
inventoryId: inventory.id,
bankAccountId: inventoryBankAccount.bankAccountId,
})
}
}
await prisma.posAccount.createMany({
data: posAccounts,
})
}
// Seed purchase, transfer, and sales transactions
// const inventories = await prisma.inventory.findMany()
// const products = await prisma.product.findMany({ take: 5 }) // select 5 products for demo
@@ -343,7 +331,7 @@ async function main() {
// items: products.map(product => ({
// productId: product.id,
// count: 10,
// fee: Number(product.salePrice),
// unitPrice: Number(product.salePrice),
// total: 10 * Number(product.salePrice),
// })),
// })
@@ -1,332 +0,0 @@
-- 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
-- ------------------------------------------
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;
-- 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());
-- 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());
end;
-- ------------------------------------------
-- 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,
fee,
totalCost,
referenceType,
referenceId,
productId,
inventoryId,
avgCost,
createdAt
)
VALUES
(
'IN',
NEW.count,
NEW.fee,
NEW.total,
'PURCHASE',
NEW.receiptId,
NEW.productId,
(SELECT inventoryId FROM Purchase_Receipts WHERE id = NEW.receiptId),
NEW.total / NEW.count,
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_purchase_insert
-- Event: INSERT
-- Table: Stock_Movements
-- ------------------------------------------
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)
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_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;
-5
View File
@@ -1,5 +0,0 @@
-- Auto-generated trigger dump
DELIMITER 8488
-- Trigger: 1
8488
DELIMITER ;
+303 -23
View File
@@ -1,7 +1,34 @@
-- AUTO-GENERATED MYSQL TRIGGER DUMP
-- Generated at: 2025-12-30T15:42:45.224Z
-- Generated at: 2026-01-04T09:46:30.365Z
-- ------------------------------------------
-- index: 1
-- Trigger: trg_bank_account_transaction_after_insert
-- Event: INSERT
-- Table: Bank_Account_Transactions
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_bank_account_transaction_after_insert`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_bank_account_transaction_after_insert` AFTER INSERT ON `Bank_Account_Transactions` FOR EACH ROW BEGIN
IF NEW.type = 'DEPOSIT' THEN
UPDATE Bank_Account_Balance SET balance = balance + NEW.amount WHERE bankAccountId = NEW.bankAccountId;
ELSEIF NEW.type = 'WITHDRAWAL' THEN
UPDATE Bank_Account_Balance SET balance = balance - NEW.amount WHERE bankAccountId = NEW.bankAccountId;
END IF;
END;
-- ------------------------------------------
-- index: 2
-- Trigger: trg_bank_account_transaction_after_delete
-- Event: DELETE
-- Table: Bank_Account_Transactions
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_bank_account_transaction_after_delete`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_bank_account_transaction_after_delete` AFTER DELETE ON `Bank_Account_Transactions` FOR EACH ROW BEGIN
UPDATE Bank_Accounts SET balance = balance - OLD.amount;
END;
-- ------------------------------------------
-- index: 3
-- Trigger: trg_transfer_item_after_insert
-- Event: INSERT
-- Table: Inventory_Transfer_Items
@@ -27,18 +54,71 @@ DECLARE fromInv INT;
-- OUT from source
INSERT INTO Stock_Movements
(type, quantity, fee, totalCost, avgCost, referenceType, referenceId, productId, inventoryId, counterInventoryId, createdAt, remainedInStock)
(type, quantity, unitPrice, totalCost, avgCost, referenceType, referenceId, productId, inventoryId, counterInventoryId, createdAt, remainedInStock)
VALUES
('OUT', NEW.count, _avgCost, _avgCost*NEW.count, _avgCost, 'INVENTORY_TRANSFER', NEW.transferId, NEW.productId, fromInv, toInv, NOW(), latestQuantityInOrigin-NEW.count);
-- IN to destination
INSERT INTO Stock_Movements
(type, quantity, fee, totalCost, avgCost, referenceType, referenceId, productId, inventoryId, counterInventoryId, createdAt, remainedInStock)
(type, quantity, unitPrice, totalCost, avgCost, referenceType, referenceId, productId, inventoryId, counterInventoryId, createdAt, remainedInStock)
VALUES
('IN', NEW.count,_avgCost, _avgCost*NEW.count,_avgCost, 'INVENTORY_TRANSFER', NEW.transferId, NEW.productId, toInv, fromInv, NOW(), latestQuantityInOrigin-NEW.count);
end;
-- ------------------------------------------
-- index: 4
-- Trigger: trg_order_item_after_insert
-- Event: INSERT
-- Table: Order_Items
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_order_item_after_insert`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_order_item_after_insert` AFTER INSERT ON `Order_Items` FOR EACH ROW BEGIN
UPDATE Stock_Reservations SET quantity = quantity + NEW.quantity
WHERE orderId = NEW.orderId AND productId = NEW.productId;
END;
-- ------------------------------------------
-- index: 5
-- Trigger: trg_order_item_after_update
-- Event: UPDATE
-- Table: Order_Items
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_order_item_after_update`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_order_item_after_update` AFTER UPDATE ON `Order_Items` FOR EACH ROW BEGIN
UPDATE Stock_Reservations
SET quantity = quantity - OLD.quantity + NEW.quantity
WHERE orderId = NEW.orderId AND productId = NEW.productId;
END;
-- ------------------------------------------
-- index: 6
-- Trigger: trg_order_item_after_delete
-- Event: DELETE
-- Table: Order_Items
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_order_item_after_delete`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_order_item_after_delete` AFTER DELETE ON `Order_Items` FOR EACH ROW BEGIN
UPDATE Stock_Reservations SET quantity = quantity - OLD.quantity
WHERE orderId = OLD.orderId AND productId = OLD.productId;
END;
-- ------------------------------------------
-- index: 7
-- Trigger: trg_order_after_cancel
-- Event: UPDATE
-- Table: Orders
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_order_after_cancel`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_order_after_cancel` AFTER UPDATE ON `Orders` FOR EACH ROW BEGIN
IF NEW.status = 'CANCELED' OR NEW.status = 'REJECTED' OR NEW.status = 'DONE' THEN
UPDATE Stock_Reservations sr SET quantity = 0
WHERE sr.orderId = NEW.id;
END IF;
END;
-- ------------------------------------------
-- index: 8
-- Trigger: trg_purchase_receipt_item_after_insert
-- Event: INSERT
-- Table: Purchase_Receipt_Items
@@ -49,7 +129,7 @@ CREATE DEFINER=`pos`@`%` TRIGGER `trg_purchase_receipt_item_after_insert` AFTER
DECLARE invId INT;
DECLARE suppId INT;
-- Get inventory & supplier from
-- Get inventory & supplier from
SELECT inventoryId, supplierId
INTO invId, suppId
FROM Purchase_Receipts
@@ -67,7 +147,7 @@ DECLARE invId INT;
INSERT INTO Stock_Movements (
type,
quantity,
fee,
unitPrice,
totalCost,
referenceType,
referenceId,
@@ -81,15 +161,15 @@ DECLARE invId INT;
VALUES (
'IN',
NEW.count,
NEW.fee,
NEW.total,
NEW.unitPrice,
NEW.totalAmount,
'PURCHASE',
NEW.receiptId,
NEW.productId,
invId,
CASE
WHEN NEW.count = 0 THEN 0
ELSE NEW.total / NEW.count
ELSE NEW.totalAmount / NEW.count
END
,
@@ -101,16 +181,18 @@ DECLARE invId INT;
END;
-- ------------------------------------------
-- index: 9
-- Trigger: trg_pr_payment_before_insert
-- Event: INSERT
-- Table: Purchase_Receipt_Payments
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_pr_payment_before_insert`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_pr_payment_before_insert` BEFORE INSERT ON `Purchase_Receipt_Payments` FOR EACH ROW BEGIN
DECLARE receiptTotal DECIMAL(14,2);
DECLARE paid DECIMAL(14,2);
INSERT INTO Trigger_Logs (name , message) VALUES ('trigger' , 'started');
SELECT totalAmount, paidAmount
INTO receiptTotal, paid
@@ -125,6 +207,121 @@ CREATE DEFINER=`pos`@`%` TRIGGER `trg_pr_payment_before_insert` BEFORE INSERT ON
END;
-- ------------------------------------------
-- index: 10
-- Trigger: trg_purchase_payment_update_receipt
-- Event: INSERT
-- Table: Purchase_Receipt_Payments
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_purchase_payment_update_receipt`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_purchase_payment_update_receipt` AFTER INSERT ON `Purchase_Receipt_Payments` FOR EACH ROW BEGIN
DECLARE paid DECIMAL(15,2);
DECLARE total DECIMAL(15,2);
SELECT
COALESCE(SUM(
CASE WHEN type = 'PAYMENT' THEN amount ELSE -amount END
),0)
INTO paid
FROM Purchase_Receipt_Payments
WHERE receiptId = NEW.receiptId;
SELECT totalAmount INTO total
FROM Purchase_Receipts
WHERE id = NEW.receiptId;
UPDATE Purchase_Receipts
SET
paidAmount = paid,
status = CASE
WHEN paid = 0 THEN 'UNPAID'
WHEN paid < total THEN 'PARTIALLY_PAID'
ELSE 'PAID'
END
WHERE id = NEW.receiptId;
END;
-- ------------------------------------------
-- index: 11
-- Trigger: trg_purchase_payment_after_insert
-- Event: INSERT
-- Table: Purchase_Receipt_Payments
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_purchase_payment_after_insert`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_purchase_payment_after_insert` AFTER INSERT ON `Purchase_Receipt_Payments` FOR EACH ROW BEGIN
DECLARE currentBalance DECIMAL(15, 2);
SELECT balance INTO currentBalance
FROM Bank_Account_Balance
WHERE
bankAccountId = NEW.bankAccountId FOR
UPDATE;
IF currentBalance IS NULL THEN SET currentBalance = 0;
INSERT INTO
Bank_Account_Balance (bankAccountId, balance, updatedAt)
VALUES (NEW.bankAccountId, 0, NOW());
END IF;
IF NEW.type = 'PAYMENT' THEN
SET
currentBalance = currentBalance - NEW.amount;
INSERT INTO
Bank_Account_Transactions (
bankAccountId,
type,
amount,
balanceAfter,
referenceType,
referenceId
)
VALUES (
NEW.bankAccountId,
'WITHDRAWAL',
NEW.amount,
currentBalance,
'PURCHASE_PAYMENT',
NEW.id
);
ELSE SET currentBalance = currentBalance + NEW.amount;
INSERT INTO
Bank_Account_Transactions (
bankAccountId,
type,
amount,
balanceAfter,
referenceType,
referenceId
)
VALUES (
NEW.bankAccountId,
'DEPOSIT',
NEW.amount,
currentBalance,
'PURCHASE_REFUND',
NEW.id
);
END IF;
UPDATE Bank_Account_Balance
SET
balance = currentBalance
WHERE
bankAccountId = NEW.bankAccountId;
END;
-- ------------------------------------------
-- index: 12
-- Trigger: trg_pr_payment_after_insert
-- Event: INSERT
-- Table: Purchase_Receipt_Payments
@@ -134,7 +331,8 @@ CREATE DEFINER=`pos`@`%` TRIGGER `trg_pr_payment_after_insert` AFTER INSERT ON `
DECLARE receiptTotal DECIMAL(14,2) Default 0;
DECLARE newPaid DECIMAL(14,2) Default 0;
DECLARE _supplierId INT;
DECLARE lastBalance DECIMAL(14,2)Default 0;
DECLARE lastBalance DECIMAL(14,2) Default 0;
-- Lock receipt row
SELECT COALESCE(totalAmount, 0), COALESCE(paidAmount, 0), supplierId
@@ -142,8 +340,6 @@ SELECT COALESCE(totalAmount, 0), COALESCE(paidAmount, 0), supplierId
FROM Purchase_Receipts
WHERE id = NEW.receiptId
FOR UPDATE;
INSERT INTO Trigger_Logs (name, message) VALUES ('supplierId', _supplierId);
-- Apply payment or refund
IF NEW.type = 'PAYMENT' THEN
@@ -172,6 +368,8 @@ SELECT COALESCE(totalAmount, 0), COALESCE(paidAmount, 0), supplierId
ORDER BY id DESC
LIMIT 1;
-- Insert supplier ledger
INSERT INTO Supplier_Ledger
(
@@ -198,6 +396,7 @@ SELECT COALESCE(totalAmount, 0), COALESCE(paidAmount, 0), supplierId
END;
-- ------------------------------------------
-- index: 13
-- Trigger: trg_pr_payment_after_delete
-- Event: DELETE
-- Table: Purchase_Receipt_Payments
@@ -232,6 +431,7 @@ CREATE DEFINER=`pos`@`%` TRIGGER `trg_pr_payment_after_delete` AFTER DELETE ON `
END;
-- ------------------------------------------
-- index: 14
-- Trigger: trg_purchase_receipt_after_insert
-- Event: INSERT
-- Table: Purchase_Receipts
@@ -270,23 +470,24 @@ CREATE DEFINER=`pos`@`%` TRIGGER `trg_purchase_receipt_after_insert` AFTER INSER
END;
-- ------------------------------------------
-- index: 15
-- 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
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);
DECLARE inventory_id INT;
SELECT pa.inventoryId INTO inventory_id
FROM Pos_Accounts pa
INNER JOIN Sales_Invoices si ON pa.id = si.posAccountId
WHERE si.id = NEW.invoiceId;
SELECT COALESCE(quantity, 0) INTO current_stock
FROM Stock_Balance sb
@@ -302,6 +503,7 @@ CREATE DEFINER=`pos`@`%` TRIGGER `trg_sales_invoice_items_before_insert` BEFORE
end;
-- ------------------------------------------
-- index: 16
-- Trigger: trg_sales_invoice_items_after_insert
-- Event: INSERT
-- Table: Sales_Invoice_Items
@@ -340,7 +542,7 @@ DECLARE pos_id INT;
INSERT INTO Stock_Movements (
type,
quantity,
fee,
unitPrice,
totalCost,
referenceType,
referenceId,
@@ -354,8 +556,8 @@ DECLARE pos_id INT;
VALUES (
'OUT',
NEW.count,
NEW.fee,
NEW.total,
NEW.unitPrice,
NEW.totalAmount,
'SALES',
NEW.invoiceId,
NEW.productId,
@@ -363,7 +565,7 @@ DECLARE pos_id INT;
CASE
WHEN NEW.count = 0 THEN 0
ELSE NEW.total / NEW.count
ELSE NEW.totalAmount / NEW.count
END,
current_stock - NEW.count,
customer_id,
@@ -374,6 +576,82 @@ DECLARE pos_id INT;
END;
-- ------------------------------------------
-- index: 17
-- Trigger: trg_sales_invoice_payment_after_insert
-- Event: INSERT
-- Table: Sales_Invoice_Payments
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_sales_invoice_payment_after_insert`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_sales_invoice_payment_after_insert` AFTER INSERT ON `Sales_Invoice_Payments` FOR EACH ROW BEGIN
DECLARE currentBalance DECIMAL(15,2);
DECLARE bankAccountId INT;
SELECT pa.bankAccountId INTO bankAccountId
FROM Pos_Accounts pa
INNER JOIN Sales_Invoices si ON pa.id = si.posAccountId
WHERE si.id = NEW.invoiceId;
SELECT balance INTO currentBalance
FROM Bank_Account_Balance
WHERE bankAccountId = bankAccountId
FOR UPDATE;
IF currentBalance IS NULL THEN
SET currentBalance = 0;
INSERT INTO Bank_Account_Balance (bankAccountId, balance)
VALUES (bankAccountId, 0);
END IF;
SET currentBalance = currentBalance + NEW.amount;
INSERT INTO Bank_Account_Transactions
(bankAccountId, type, amount, balanceAfter, referenceType, referenceId)
VALUES
(bankAccountId, 'DEPOSIT', NEW.amount, currentBalance, 'POS_SALE', NEW.id);
UPDATE Bank_Account_Balance
SET balance = currentBalance
WHERE bankAccountId = bankAccountId;
END;
-- ------------------------------------------
-- index: 18
-- Trigger: trg_pos_account_payment_after_insert
-- Event: INSERT
-- Table: Sales_Invoice_Payments
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_pos_account_payment_after_insert`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_pos_account_payment_after_insert` AFTER INSERT ON `Sales_Invoice_Payments` FOR EACH ROW BEGIN
DECLARE _bankAccountId INT;
IF(NEW.paymentMethod != 'CASH') THEN
SELECT cashBankAccountId INTO _bankAccountId
FROM Pos_Accounts pa
INNER JOIN Sales_Invoices si ON pa.id = si.posAccountId
WHERE si.id = NEW.invoiceId;
End IF;
INSERT INTO Bank_Account_Transactions (
bankAccountId,
type,
amount,
balanceAfter,
referenceType,
referenceId
)
VALUES(
_bankAccountId,
'DEPOSIT',
NEW.amount,
0,
'POS_SALE',
NEW.id
);
END;
-- ------------------------------------------
-- index: 19
-- Trigger: trg_stock_transfer
-- Event: INSERT
-- Table: Stock_Movements
@@ -442,8 +720,8 @@ VALUES (
NEW.productId,
NEW.inventoryId,
- NEW.quantity,
- COALESCE(NEW.fee, 0) * NEW.quantity,
COALESCE(NEW.fee, 0),
- COALESCE(NEW.unitPrice, 0) * NEW.quantity,
COALESCE(NEW.unitPrice, 0),
NOW()
);
@@ -456,6 +734,7 @@ END IF;
END;
-- ------------------------------------------
-- index: 20
-- Trigger: trg_stock_purchase_insert
-- Event: INSERT
-- Table: Stock_Movements
@@ -475,7 +754,7 @@ INSERT INTO
VALUES (
NEW.productId,
NEW.quantity,
NEW.fee,
NEW.unitPrice,
NEW.totalCost,
NEW.inventoryId,
NOW()
@@ -490,6 +769,7 @@ END IF;
END;
-- ------------------------------------------
-- index: 21
-- Trigger: trg_stock_sale_insert
-- Event: INSERT
-- Table: Stock_Movements
@@ -509,7 +789,7 @@ INSERT INTO
VALUES (
NEW.productId,
NEW.quantity,
NEW.fee,
NEW.unitPrice,
NEW.totalCost,
NEW.inventoryId,
NOW()
File diff suppressed because it is too large Load Diff
+633
View File
@@ -0,0 +1,633 @@
-- Stored Procedures equivalent to triggers
DELIMITER //
-- Procedure for trg_bank_account_transaction_after_insert
CREATE PROCEDURE update_bank_balance(IN p_bankAccountId INT, IN p_type VARCHAR(20), IN p_amount DECIMAL(15,2))
BEGIN
IF p_type = 'DEPOSIT' THEN
UPDATE Bank_Account_Balance SET balance = balance + p_amount WHERE bankAccountId = p_bankAccountId;
ELSEIF p_type = 'WITHDRAWAL' THEN
UPDATE Bank_Account_Balance SET balance = balance - p_amount WHERE bankAccountId = p_bankAccountId;
END IF;
END //
-- Procedure for trg_bank_account_transaction_after_delete
CREATE PROCEDURE update_bank_balance_on_delete(IN p_bankAccountId INT, IN p_amount DECIMAL(15,2))
BEGIN
UPDATE Bank_Accounts SET balance = balance - p_amount WHERE id = p_bankAccountId;
END //
-- Procedure for trg_transfer_item_after_insert
CREATE PROCEDURE process_transfer_item(IN p_transferId INT, IN p_productId INT, IN p_count DECIMAL(10,2))
BEGIN
DECLARE fromInv INT;
DECLARE toInv INT;
DECLARE _avgCost DECIMAL(10,2);
DECLARE latestQuantityInOrigin DECIMAL(10,2);
DECLARE latestQuantityInDestination DECIMAL(10,2);
SELECT fromInventoryId, toInventoryId INTO fromInv, toInv
FROM Inventory_Transfers WHERE id = p_transferId;
SELECT COALESCE(avgCost, 0), COALESCE(quantity, 0) INTO _avgCost, latestQuantityInOrigin FROM Stock_Balance
WHERE ProductId = p_productId AND inventoryId = fromInv LIMIT 1;
SELECT COALESCE(quantity, 0) INTO latestQuantityInDestination FROM Stock_Balance
WHERE ProductId = p_productId AND inventoryId = toInv LIMIT 1;
-- OUT from source
INSERT INTO Stock_Movements
(type, quantity, unitPrice, totalCost, avgCost, referenceType, referenceId, productId, inventoryId, counterInventoryId, createdAt, remainedInStock)
VALUES
('OUT', p_count, _avgCost, _avgCost*p_count, _avgCost, 'INVENTORY_TRANSFER', p_transferId, p_productId, fromInv, toInv, NOW(), latestQuantityInOrigin-p_count);
-- IN to destination
INSERT INTO Stock_Movements
(type, quantity, unitPrice, totalCost, avgCost, referenceType, referenceId, productId, inventoryId, counterInventoryId, createdAt, remainedInStock)
VALUES
('IN', p_count, _avgCost, _avgCost*p_count, _avgCost, 'INVENTORY_TRANSFER', p_transferId, p_productId, toInv, fromInv, NOW(), latestQuantityInOrigin-p_count);
END //
-- Procedure for trg_order_item_after_insert
CREATE PROCEDURE update_stock_reservation_insert(IN p_orderId INT, IN p_productId INT, IN p_quantity DECIMAL(10,2))
BEGIN
UPDATE Stock_Reservations SET quantity = quantity + p_quantity
WHERE orderId = p_orderId AND productId = p_productId;
END //
-- Procedure for trg_order_item_after_update
CREATE PROCEDURE update_stock_reservation_update(IN p_orderId INT, IN p_productId INT, IN p_old_quantity DECIMAL(10,2), IN p_new_quantity DECIMAL(10,2))
BEGIN
UPDATE Stock_Reservations
SET quantity = quantity - p_old_quantity + p_new_quantity
WHERE orderId = p_orderId AND productId = p_productId;
END //
-- Procedure for trg_order_item_after_delete
CREATE PROCEDURE update_stock_reservation_delete(IN p_orderId INT, IN p_productId INT, IN p_quantity DECIMAL(10,2))
BEGIN
UPDATE Stock_Reservations SET quantity = quantity - p_quantity
WHERE orderId = p_orderId AND productId = p_productId;
END //
-- Procedure for trg_order_after_cancel
CREATE PROCEDURE cancel_order_stock(IN p_orderId INT, IN p_status VARCHAR(20))
BEGIN
IF p_status = 'CANCELED' OR p_status = 'REJECTED' OR p_status = 'DONE' THEN
UPDATE Stock_Reservations sr SET quantity = 0
WHERE sr.orderId = p_orderId;
END IF;
END //
-- Procedure for trg_purchase_receipt_item_after_insert
CREATE PROCEDURE process_purchase_item(IN p_receiptId INT, IN p_productId INT, IN p_count DECIMAL(10,2), IN p_unitPrice DECIMAL(15,2), IN p_totalAmount DECIMAL(15,2))
BEGIN
DECLARE latestQuantity DECIMAL(10, 2) DEFAULT 0;
DECLARE invId INT;
DECLARE suppId INT;
-- Get inventory & supplier from
SELECT inventoryId, supplierId
INTO invId, suppId
FROM Purchase_Receipts
WHERE id = p_receiptId;
-- Get current stock quantity (if exists)
SELECT COALESCE(quantity, 0)
INTO latestQuantity
FROM Stock_Balance sb
WHERE sb.inventoryId = invId
AND sb.productId = p_productId
LIMIT 1;
-- Insert stock movement
INSERT INTO Stock_Movements (
type,
quantity,
unitPrice,
totalCost,
referenceType,
referenceId,
productId,
inventoryId,
avgCost,
supplierId,
remainedInStock,
createdAt
)
VALUES (
'IN',
p_count,
p_unitPrice,
p_totalAmount,
'PURCHASE',
p_receiptId,
p_productId,
invId,
CASE
WHEN p_count = 0 THEN 0
ELSE p_totalAmount / p_count
END,
suppId,
latestQuantity + p_count,
NOW()
);
END //
-- Procedure for trg_pr_payment_before_insert
CREATE PROCEDURE validate_payment_before_insert(IN p_receiptId INT, IN p_type VARCHAR(20), IN p_amount DECIMAL(15,2))
BEGIN
DECLARE receiptTotal DECIMAL(14,2);
DECLARE paid DECIMAL(14,2);
SELECT totalAmount, paidAmount
INTO receiptTotal, paid
FROM Purchase_Receipts
WHERE id = p_receiptId
FOR UPDATE;
IF p_type = 'PAYMENT' AND paid + p_amount > receiptTotal THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'مجموع مبلغ پرداختی بیشتر از مبلغ فاکتور است.';
END IF;
END //
-- Procedure for trg_purchase_payment_update_receipt
CREATE PROCEDURE update_receipt_payment(IN p_receiptId INT)
BEGIN
DECLARE paid DECIMAL(15,2);
DECLARE total DECIMAL(15,2);
SELECT
COALESCE(SUM(
CASE WHEN type = 'PAYMENT' THEN amount ELSE -amount END
),0)
INTO paid
FROM Purchase_Receipt_Payments
WHERE receiptId = p_receiptId;
SELECT totalAmount INTO total
FROM Purchase_Receipts
WHERE id = p_receiptId;
UPDATE Purchase_Receipts
SET
paidAmount = paid,
status = CASE
WHEN paid = 0 THEN 'UNPAID'
WHEN paid < total THEN 'PARTIALLY_PAID'
ELSE 'PAID'
END
WHERE id = p_receiptId;
END //
-- Procedure for trg_purchase_payment_after_insert
CREATE PROCEDURE process_purchase_payment(IN p_bankAccountId INT, IN p_type VARCHAR(20), IN p_amount DECIMAL(15,2), IN p_id INT)
BEGIN
DECLARE currentBalance DECIMAL(15, 2);
SELECT balance INTO currentBalance
FROM Bank_Account_Balance
WHERE bankAccountId = p_bankAccountId FOR UPDATE;
IF currentBalance IS NULL THEN SET currentBalance = 0;
INSERT INTO Bank_Account_Balance (bankAccountId, balance, updatedAt)
VALUES (p_bankAccountId, 0, NOW());
END IF;
IF p_type = 'PAYMENT' THEN
SET currentBalance = currentBalance - p_amount;
INSERT INTO Bank_Account_Transactions (
bankAccountId,
type,
amount,
balanceAfter,
referenceType,
referenceId
)
VALUES (
p_bankAccountId,
'WITHDRAWAL',
p_amount,
currentBalance,
'PURCHASE_PAYMENT',
p_id
);
ELSE
SET currentBalance = currentBalance + p_amount;
INSERT INTO Bank_Account_Transactions (
bankAccountId,
type,
amount,
balanceAfter,
referenceType,
referenceId
)
VALUES (
p_bankAccountId,
'DEPOSIT',
p_amount,
currentBalance,
'PURCHASE_REFUND',
p_id
);
END IF;
UPDATE Bank_Account_Balance
SET balance = currentBalance
WHERE bankAccountId = p_bankAccountId;
END //
-- Procedure for trg_pr_payment_after_insert
CREATE PROCEDURE update_supplier_ledger(IN p_receiptId INT, IN p_type VARCHAR(20), IN p_amount DECIMAL(15,2), IN p_id INT)
BEGIN
DECLARE receiptTotal DECIMAL(14,2) DEFAULT 0;
DECLARE newPaid DECIMAL(14,2) DEFAULT 0;
DECLARE _supplierId INT;
DECLARE lastBalance DECIMAL(14,2) DEFAULT 0;
-- Lock receipt row
SELECT COALESCE(totalAmount, 0), COALESCE(paidAmount, 0), supplierId
INTO receiptTotal, newPaid, _supplierId
FROM Purchase_Receipts
WHERE id = p_receiptId
FOR UPDATE;
-- Apply payment or refund
IF p_type = 'PAYMENT' THEN
SET newPaid = newPaid + p_amount;
ELSE
SET newPaid = newPaid - p_amount;
END IF;
-- Update receipt
UPDATE Purchase_Receipts
SET
paidAmount = newPaid,
status =
CASE
WHEN newPaid = 0 THEN 'UNPAID'
WHEN newPaid < receiptTotal THEN 'PARTIALLY_PAID'
ELSE 'PAID'
END
WHERE id = p_receiptId;
-- Get last supplier balance
SELECT IFNULL(balance, 0)
INTO lastBalance
FROM Supplier_Ledger
WHERE supplierId = _supplierId
ORDER BY id DESC
LIMIT 1;
-- Insert supplier ledger
INSERT INTO Supplier_Ledger
(
supplierId,
debit,
credit,
balance,
sourceType,
sourceId,
createdAt
)
VALUES
(
_supplierId,
IF(p_type = 'REFUND', p_amount, 0),
IF(p_type = 'PAYMENT', p_amount, 0),
lastBalance
+ IF(p_type = 'PAYMENT', p_amount, 0)
- IF(p_type = 'REFUND', p_amount, 0),
'PAYMENT',
p_id,
NOW()
);
END //
-- Procedure for trg_pr_payment_after_delete
CREATE PROCEDURE update_receipt_on_payment_delete(IN p_receiptId INT, IN p_type VARCHAR(20), IN p_amount DECIMAL(15,2))
BEGIN
DECLARE receiptTotal DECIMAL(14,2);
DECLARE newPaid DECIMAL(14,2);
SELECT totalAmount, paidAmount
INTO receiptTotal, newPaid
FROM Purchase_Receipts
WHERE id = p_receiptId
FOR UPDATE;
IF p_type = 'PAYMENT' THEN
SET newPaid = newPaid - p_amount;
ELSE
SET newPaid = newPaid + p_amount;
END IF;
UPDATE Purchase_Receipts
SET
paidAmount = newPaid,
status =
CASE
WHEN newPaid = 0 THEN 'UNPAID'
WHEN newPaid < receiptTotal THEN 'PARTIALLY_PAID'
ELSE 'PAID'
END
WHERE id = p_receiptId;
END //
-- Procedure for trg_purchase_receipt_after_insert
CREATE PROCEDURE insert_supplier_ledger_purchase(IN p_supplierId INT, IN p_totalAmount DECIMAL(15,2), IN p_id INT)
BEGIN
DECLARE lastBalance DECIMAL(14,2) DEFAULT 0;
SELECT COALESCE(balance, 0)
INTO lastBalance
FROM Supplier_Ledger
WHERE supplierId = p_supplierId
ORDER BY id DESC
LIMIT 1;
INSERT INTO Supplier_Ledger
(
supplierId,
debit,
credit,
balance,
sourceType,
sourceId,
createdAt
)
VALUES
(
p_supplierId,
p_totalAmount,
0,
lastBalance - p_totalAmount,
'PURCHASE',
p_id,
NOW()
);
END //
-- Procedure for trg_sales_invoice_items_before_insert
CREATE PROCEDURE validate_stock_before_sale(IN p_invoiceId INT, IN p_productId INT, IN p_count DECIMAL(10,2))
BEGIN
DECLARE current_stock DECIMAL(10, 2);
DECLARE inventory_id INT;
SELECT pa.inventoryId INTO inventory_id
FROM Pos_Accounts pa
INNER JOIN Sales_Invoices si ON pa.id = si.posAccountId
WHERE si.id = p_invoiceId;
SELECT COALESCE(quantity, 0) INTO current_stock
FROM Stock_Balance sb
WHERE productId = p_productId AND sb.inventoryId = inventory_id
LIMIT 1;
IF p_count > current_stock THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'موجودی کالا در انبار کافی نیست.';
END IF;
END //
-- Procedure for trg_sales_invoice_items_after_insert
CREATE PROCEDURE process_sale_item(IN p_invoiceId INT, IN p_productId INT, IN p_count DECIMAL(10,2), IN p_unitPrice DECIMAL(15,2), IN p_totalAmount DECIMAL(15,2))
BEGIN
DECLARE current_stock DECIMAL(10, 2);
DECLARE inventory_id INT;
DECLARE customer_id INT;
DECLARE pos_id INT;
SELECT posAccountId, customerId INTO pos_id, customer_id
FROM Sales_Invoices si
WHERE si.id = p_invoiceId
LIMIT 1;
SELECT pa.inventoryId INTO inventory_id
FROM Pos_Accounts pa
INNER JOIN Sales_Invoices si ON pa.id = si.posAccountId
WHERE si.id = p_invoiceId;
SELECT COALESCE(quantity, 0) INTO current_stock
FROM Stock_Balance sb
WHERE productId = p_productId AND sb.inventoryId = inventory_id
LIMIT 1;
INSERT INTO Stock_Movements (
type,
quantity,
unitPrice,
totalCost,
referenceType,
referenceId,
productId,
inventoryId,
avgCost,
remainedInStock,
customerId,
createdAt
)
VALUES (
'OUT',
p_count,
p_unitPrice,
p_totalAmount,
'SALES',
p_invoiceId,
p_productId,
inventory_id,
CASE
WHEN p_count = 0 THEN 0
ELSE p_totalAmount / p_count
END,
current_stock - p_count,
customer_id,
NOW()
);
END //
-- Procedure for trg_sales_invoice_payment_after_insert
CREATE PROCEDURE process_sale_payment(IN p_invoiceId INT, IN p_amount DECIMAL(15,2), IN p_id INT)
BEGIN
DECLARE currentBalance DECIMAL(15,2);
DECLARE bankAccountId INT;
SELECT pa.bankAccountId INTO bankAccountId
FROM Pos_Accounts pa
INNER JOIN Sales_Invoices si ON pa.id = si.posAccountId
WHERE si.id = p_invoiceId;
SELECT balance INTO currentBalance
FROM Bank_Account_Balance
WHERE bankAccountId = bankAccountId
FOR UPDATE;
IF currentBalance IS NULL THEN
SET currentBalance = 0;
INSERT INTO Bank_Account_Balance (bankAccountId, balance, updatedAt)
VALUES (bankAccountId, 0, NOW());
END IF;
SET currentBalance = currentBalance + p_amount;
INSERT INTO Bank_Account_Transactions
(bankAccountId, type, amount, balanceAfter, referenceType, referenceId)
VALUES
(bankAccountId, 'DEPOSIT', p_amount, currentBalance, 'POS_SALE', p_id);
UPDATE Bank_Account_Balance
SET balance = currentBalance
WHERE bankAccountId = bankAccountId;
END //
-- Procedure for trg_pos_account_payment_after_insert
CREATE PROCEDURE process_pos_payment(IN p_invoiceId INT, IN p_paymentMethod VARCHAR(20), IN p_amount DECIMAL(15,2), IN p_id INT)
BEGIN
DECLARE _bankAccountId INT;
IF(p_paymentMethod != 'CASH') THEN
SELECT cashBankAccountId INTO _bankAccountId
FROM Pos_Accounts pa
INNER JOIN Sales_Invoices si ON pa.id = si.posAccountId
WHERE si.id = p_invoiceId;
END IF;
INSERT INTO Bank_Account_Transactions (
bankAccountId,
type,
amount,
balanceAfter,
referenceType,
referenceId
)
VALUES(
_bankAccountId,
'DEPOSIT',
p_amount,
0,
'POS_SALE',
p_id
);
END //
-- Procedure for trg_stock_transfer
CREATE PROCEDURE update_stock_balance_transfer(IN p_productId INT, IN p_inventoryId INT, IN p_quantity DECIMAL(10,2), IN p_unitPrice DECIMAL(15,2), IN p_totalCost DECIMAL(15,2), IN p_type VARCHAR(10))
BEGIN
IF p_type = 'IN' THEN
INSERT INTO Stock_Balance (
productId,
inventoryId,
quantity,
totalCost,
avgCost,
updatedAt
)
VALUES (
p_productId,
p_inventoryId,
p_quantity,
p_totalCost,
CASE
WHEN p_quantity = 0 THEN 0
ELSE p_totalCost / p_quantity
END,
NOW()
)
ON DUPLICATE KEY UPDATE
quantity = quantity + p_quantity,
totalCost = totalCost + p_totalCost,
avgCost = CASE
WHEN (quantity + p_quantity) = 0 THEN 0
ELSE (totalCost + p_totalCost) / (quantity + p_quantity)
END,
updatedAt = NOW();
END IF;
IF p_type = 'OUT' THEN
IF EXISTS (
SELECT 1
FROM Stock_Balance sb
WHERE sb.productId = p_productId AND sb.inventoryId = p_inventoryId
) THEN
UPDATE Stock_Balance sb
SET
sb.quantity = sb.quantity - p_quantity,
sb.totalCost = sb.totalCost - (sb.avgCost * p_quantity),
sb.updatedAt = NOW()
WHERE
sb.productId = p_productId
AND sb.inventoryId = p_inventoryId;
ELSE
INSERT INTO Stock_Balance (
productId,
inventoryId,
quantity,
totalCost,
avgCost,
updatedAt
)
VALUES (
p_productId,
p_inventoryId,
- p_quantity,
- COALESCE(p_unitPrice, 0) * p_quantity,
COALESCE(p_unitPrice, 0),
NOW()
);
END IF;
END IF;
END //
-- Procedure for trg_stock_purchase_insert
CREATE PROCEDURE update_stock_balance_purchase(IN p_productId INT, IN p_quantity DECIMAL(10,2), IN p_unitPrice DECIMAL(15,2), IN p_totalCost DECIMAL(15,2), IN p_inventoryId INT)
BEGIN
INSERT INTO Stock_Balance (
productId,
quantity,
avgCost,
totalCost,
inventoryId,
updatedAt
)
VALUES (
p_productId,
p_quantity,
p_unitPrice,
p_totalCost,
p_inventoryId,
NOW()
)
ON DUPLICATE KEY UPDATE
quantity = quantity + p_quantity,
totalCost = totalCost + p_totalCost,
avgCost = totalCost / quantity;
END //
-- Procedure for trg_stock_sale_insert
CREATE PROCEDURE update_stock_balance_sale(IN p_productId INT, IN p_quantity DECIMAL(10,2), IN p_unitPrice DECIMAL(15,2), IN p_totalCost DECIMAL(15,2), IN p_inventoryId INT)
BEGIN
INSERT INTO Stock_Balance (
productId,
quantity,
avgCost,
totalCost,
inventoryId,
updatedAt
)
VALUES (
p_productId,
p_quantity,
p_unitPrice,
p_totalCost,
p_inventoryId,
NOW()
)
ON DUPLICATE KEY UPDATE
quantity = quantity - p_quantity,
totalCost = totalCost - p_totalCost,
avgCost = totalCost / quantity;
END //
DELIMITER ;