fix: update SupplierLedger model to use correct enum casing and adjust types

feat: enhance PosAccountsService to include inventoryBankAccount details in responses

refactor: modify PosService to return structured inventory and bank account data

chore: remove isSettled field from CreatePurchaseReceiptDto and adjust related logic

feat: add payments selection in SuppliersService for better payment tracking

chore: apply database migrations to adjust decimal types and enforce constraints

chore: create index on Pos_Accounts for improved query performance

feat: define Supplier and SupplierLedger models in Prisma schema for better data management
This commit is contained in:
2025-12-26 22:09:46 +03:30
parent d59be5995d
commit d98507fc1f
35 changed files with 2670 additions and 2802 deletions
@@ -28,13 +28,13 @@ DECLARE fromInv INT;
-- OUT from source
INSERT INTO Stock_Movements
(type, quantity, fee, totalCost, avgCost, referenceType, referenceId, productId, inventoryId, cuonterInventoryId, createdAt, remainedInStock)
(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, cuonterInventoryId, createdAt, remainedInStock)
(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;
@@ -0,0 +1,158 @@
/*
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`;
@@ -0,0 +1,2 @@
-- CreateIndex
CREATE INDEX `Pos_Accounts_inventoryId_idx` ON `Pos_Accounts`(`inventoryId`);
+1 -3
View File
@@ -26,9 +26,7 @@ model BankAccount {
deletedAt DateTime? @db.Timestamp(0)
branch BankBranch @relation("Bank_Accounts_branchId_fkey", fields: [branchId], references: [id])
purchaseReceiptPayments PurchaseReceiptPayments[]
posAccounts PosAccount[]
inventoryBankAccounts InventoryBankAccount[] @relation("Inventory_Bank_Accounts_bankAccountId_fkey")
inventoryBankAccounts InventoryBankAccount[]
@@map("Bank_Accounts")
}
+13 -2
View File
@@ -17,7 +17,7 @@ enum MovementReferenceType {
INVENTORY_TRANSFER
}
enum payment_method_type {
enum PaymentMethodType {
CASH
CARD
BANK
@@ -25,9 +25,20 @@ enum payment_method_type {
OTHER
}
enum ledgerSourceType {
enum LedgerSourceType {
PURCHASE
PAYMENT
ADJUSTMENT
REFUND
}
enum PaymentType {
PAYMENT
REFUND
}
enum PurchaseReceiptStatus {
UNPAID
PARTIALLY_PAID
PAID
}
+33 -35
View File
@@ -9,19 +9,48 @@ model Inventory {
isPointOfSale Boolean @default(false)
inventoryTransfersFrom InventoryTransfer[] @relation("Inventory_From")
inventoryTransfersTo InventoryTransfer[] @relation("Inventory_To")
// productCharges ProductCharge[] @relation("Inventory_Product_Charges")
purchaseReceipts PurchaseReceipt[]
salesInvoices SalesInvoice[] @relation("Inventory_SalesInvoices")
stockAdjustments StockAdjustment[] @relation("Inventory_Stock_Adjustments")
stockBalances StockBalance[] @relation("StockBalance_inventory")
counterStockMovements StockMovement[] @relation("StockMovement_CounterInventory")
stockMovements StockMovement[] @relation("StockMovement_Inventory")
posAccounts PosAccount[] @relation("Inventory_PosAccounts")
inventoryBankAccounts InventoryBankAccount[] @relation("Inventory_Bank_Accounts_inventoryId_fkey")
inventoryBankAccounts InventoryBankAccount[]
@@map("Inventories")
}
model InventoryBankAccount {
inventoryId Int
bankAccountId Int
inventory Inventory @relation(fields: [inventoryId], references: [id])
bankAccount BankAccount @relation(fields: [bankAccountId], references: [id])
posAccounts PosAccount[]
purchaseReceiptPayments PurchaseReceiptPayments[]
@@id([inventoryId, bankAccountId])
@@index([bankAccountId])
@@map("Inventory_Bank_Accounts")
}
model PosAccount {
id Int @id @default(autoincrement())
name String @db.VarChar(255)
code String @unique() @db.VarChar(10)
description String? @db.VarChar(500)
bankAccountId Int
inventoryId Int
createdAt DateTime @default(now()) @db.Timestamp(0)
updatedAt DateTime @updatedAt @db.Timestamp(0)
deletedAt DateTime? @db.Timestamp(0)
inventoryBankAccount InventoryBankAccount @relation(fields: [inventoryId, bankAccountId], references: [inventoryId, bankAccountId])
@@index([inventoryId])
@@map("Pos_Accounts")
}
model InventoryTransfer {
id Int @id @default(autoincrement())
code String @unique @db.VarChar(100)
@@ -40,7 +69,7 @@ model InventoryTransfer {
model InventoryTransferItem {
id Int @id @default(autoincrement())
count Decimal @db.Decimal(10, 2)
count Decimal @db.Decimal(10, 0)
productId Int
transferId Int
product Product @relation("InventoryTransferItem_Product", fields: [productId], references: [id])
@@ -50,34 +79,3 @@ model InventoryTransferItem {
@@index([transferId], map: "Inventory_Transfer_Items_transferId_fkey")
@@map("Inventory_Transfer_Items")
}
model InventoryBankAccount {
inventoryId Int
bankAccountId Int
inventory Inventory @relation("Inventory_Bank_Accounts_inventoryId_fkey", fields: [inventoryId], references: [id])
bankAccount BankAccount @relation("Inventory_Bank_Accounts_bankAccountId_fkey", fields: [bankAccountId], references: [id])
posAccounts PosAccount[] @relation("Pos_Accounts_inventoryBankAccountId_fkey")
@@id([inventoryId, bankAccountId])
@@index([bankAccountId])
@@map("Inventory_Bank_Accounts")
}
model PosAccount {
id Int @id @default(autoincrement())
name String @db.VarChar(255)
code String @unique() @db.VarChar(10)
description String? @db.VarChar(500)
bankAccountId Int
inventoryId Int
createdAt DateTime @default(now()) @db.Timestamp(0)
updatedAt DateTime @updatedAt @db.Timestamp(0)
deletedAt DateTime? @db.Timestamp(0)
inventory Inventory @relation("Inventory_PosAccounts", fields: [inventoryId], references: [id])
inventoryBankAccount InventoryBankAccount? @relation("Pos_Accounts_inventoryBankAccountId_fkey", fields: [bankAccountId, inventoryId], references: [bankAccountId, inventoryId])
bankAccount BankAccount? @relation(fields: [bankAccountId], references: [id])
@@map("Pos_Accounts")
}
+14 -52
View File
@@ -1,41 +1,3 @@
model Supplier {
id Int @id @default(autoincrement())
firstName String @db.VarChar(255)
lastName String @db.VarChar(255)
email String? @db.VarChar(255)
mobileNumber String @unique @db.Char(11)
address String? @db.Text
city String? @db.VarChar(100)
state String? @db.VarChar(100)
country String? @db.VarChar(100)
isActive Boolean @default(true)
createdAt DateTime @default(now()) @db.Timestamp(0)
updatedAt DateTime @updatedAt @db.Timestamp(0)
deletedAt DateTime? @db.Timestamp(0)
purchaseReceipts PurchaseReceipt[]
stockMovements StockMovement[] @relation("StockMovement_Supplier")
supplierLedgers SupplierLedger[]
@@map("Suppliers")
}
model SupplierLedger {
id Int @id @default(autoincrement())
description String? @db.Text
debit Decimal @db.Decimal(10, 2)
credit Decimal @db.Decimal(10, 2)
balance Decimal @db.Decimal(10, 2)
sourceType ledgerSourceType
sourceId Int
createdAt DateTime @default(now()) @db.Timestamp(0)
supplierId Int
supplier Supplier @relation(fields: [supplierId], references: [id])
@@index([supplierId], map: "Supplier_Ledger_supplierId_fkey")
@@map("Supplier_Ledger")
}
model Customer {
id Int @id @default(autoincrement())
firstName String @db.VarChar(255)
@@ -58,17 +20,17 @@ model Customer {
}
model Order {
id Int @id @default(autoincrement())
orderNumber String @unique @db.VarChar(100)
status OrderStatus @default(PENDING)
paymentMethod payment_method_type @default(CARD)
totalAmount Decimal @db.Decimal(10, 2)
description String? @db.Text
createdAt DateTime @default(now()) @db.Timestamp(0)
updatedAt DateTime @updatedAt @db.Timestamp(0)
deletedAt DateTime? @db.Timestamp(0)
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("Customer_Orders", fields: [customerId], references: [id], onUpdate: NoAction)
customer Customer @relation("Customer_Orders", fields: [customerId], references: [id], onUpdate: NoAction)
@@index([customerId], map: "Orders_customerId_fkey")
@@map("Orders")
@@ -77,7 +39,7 @@ model Order {
model SalesInvoice {
id Int @id @default(autoincrement())
code String @unique @db.VarChar(100)
totalAmount Decimal @db.Decimal(10, 2)
totalAmount Decimal @db.Decimal(15, 2)
description String? @db.Text
createdAt DateTime @default(now()) @db.Timestamp(0)
updatedAt DateTime @updatedAt @db.Timestamp(0)
@@ -94,9 +56,9 @@ model SalesInvoice {
model SalesInvoiceItem {
id Int @id @default(autoincrement())
count Decimal @db.Decimal(10, 2)
fee Decimal @db.Decimal(10, 2)
total Decimal @db.Decimal(10, 2)
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
+5 -5
View File
@@ -1,14 +1,14 @@
model ProductVariant {
id Int @id @default(autoincrement())
name String @db.VarChar(255)
basePrice Decimal @db.Decimal(10, 2)
salePrice Decimal @db.Decimal(10, 2)
basePrice Decimal @db.Decimal(15, 2)
salePrice Decimal @db.Decimal(15, 2)
description String? @db.Text
barcode String? @unique(map: "products_barcode_unique") @db.VarChar(100)
imageUrl String? @db.VarChar(255)
unit String? @db.VarChar(10)
quantity Decimal? @default(0.00) @db.Decimal(10, 2)
alertQuantity Decimal? @default(5.00) @db.Decimal(10, 2)
quantity Decimal? @default(0.00) @db.Decimal(10, 0)
alertQuantity Decimal? @default(5.00) @db.Decimal(10, 0)
isActive Boolean @default(true)
isFeatured Boolean @default(false)
createdAt DateTime @default(now()) @db.Timestamp(0)
@@ -32,7 +32,7 @@ model Product {
deletedAt DateTime? @db.Timestamp(0)
brandId Int?
categoryId Int?
salePrice Decimal @default(0.00) @db.Decimal(10, 2)
salePrice Decimal @default(0.00) @db.Decimal(15, 0)
inventoryTransferItems InventoryTransferItem[] @relation("InventoryTransferItem_Product")
// productCharges ProductCharge[] @relation("Product_Charges")
variants ProductVariant[] @relation("Product_Variant")
+28 -27
View File
@@ -1,18 +1,18 @@
model PurchaseReceipt {
id Int @id @default(autoincrement())
code String @unique @db.VarChar(100)
totalAmount Decimal @db.Decimal(10, 2)
paidAmount Decimal @default(0.00) @db.Decimal(10, 2)
isSettled Boolean @default(false)
description String? @db.Text
createdAt DateTime @default(now()) @db.Timestamp(0)
updatedAt DateTime @updatedAt @db.Timestamp(0)
supplierId Int
inventoryId Int
items PurchaseReceiptItem[] @relation("PurchaseReceipt_Items")
inventory Inventory @relation(fields: [inventoryId], references: [id])
supplier Supplier @relation(fields: [supplierId], references: [id])
purchaseReceiptPayments PurchaseReceiptPayments[]
id Int @id @default(autoincrement())
code String @unique @db.VarChar(100)
totalAmount Decimal @db.Decimal(15, 2)
paidAmount Decimal @default(0.00) @db.Decimal(15, 2)
description String? @db.Text
createdAt DateTime @default(now()) @db.Timestamp(0)
updatedAt DateTime @updatedAt @db.Timestamp(0)
status PurchaseReceiptStatus @default(UNPAID)
supplierId Int
inventoryId Int
items PurchaseReceiptItem[] @relation("PurchaseReceipt_Items")
inventory Inventory @relation(fields: [inventoryId], references: [id])
supplier Supplier @relation(fields: [supplierId], references: [id])
payments PurchaseReceiptPayments[]
@@index([inventoryId], map: "Purchase_Receipts_inventoryId_fkey")
@@index([supplierId], map: "Purchase_Receipts_supplierId_fkey")
@@ -21,9 +21,9 @@ model PurchaseReceipt {
model PurchaseReceiptItem {
id Int @id @default(autoincrement())
count Decimal @db.Decimal(10, 2)
fee Decimal @db.Decimal(10, 2)
total Decimal @db.Decimal(10, 2)
count Decimal @db.Decimal(10, 0)
fee Decimal @db.Decimal(15, 2)
total Decimal @db.Decimal(15, 2)
description String? @db.Text
createdAt DateTime @default(now()) @db.Timestamp(0)
receiptId Int
@@ -37,19 +37,20 @@ model PurchaseReceiptItem {
}
model PurchaseReceiptPayments {
id Int @id @default(autoincrement())
amount Decimal @db.Decimal(10, 2)
paymentMethod payment_method_type
bankAccountId Int?
description String? @db.Text
payedAt DateTime @db.Timestamp(0)
id Int @id @default(autoincrement())
amount Decimal @db.Decimal(15, 2)
paymentMethod PaymentMethodType
type PaymentType
bankAccountId Int
inventoryId Int
description String? @db.Text
payedAt DateTime @db.Timestamp(0)
receiptId Int
createdAt DateTime @default(now()) @db.Timestamp(0)
createdAt DateTime @default(now()) @db.Timestamp(0)
purchaseReceipt PurchaseReceipt @relation(fields: [receiptId], references: [id])
bankAccount BankAccount? @relation(fields: [bankAccountId], references: [id])
purchaseReceipt PurchaseReceipt @relation(fields: [receiptId], references: [id])
inventoryBankAccount InventoryBankAccount @relation(fields: [inventoryId, bankAccountId], references: [inventoryId, bankAccountId])
@@index([receiptId], map: "Purchase_Receipt_Payments_receiptId_fkey")
@@index([bankAccountId], map: "Purchase_Receipt_Payments_bankAccountId_fkey")
@@map("Purchase_Receipt_Payments")
}
+6 -6
View File
@@ -1,17 +1,17 @@
model StockMovement {
id Int @id @default(autoincrement())
type MovementType
quantity Decimal @db.Decimal(10, 2)
fee Decimal @db.Decimal(10, 2)
totalCost Decimal @db.Decimal(10, 2)
quantity Decimal @db.Decimal(10, 0)
fee Decimal @db.Decimal(15, 2)
totalCost Decimal @db.Decimal(15, 2)
referenceType MovementReferenceType
referenceId String
createdAt DateTime @default(now()) @db.Timestamp(0)
productId Int
inventoryId Int
avgCost Decimal @db.Decimal(10, 2)
avgCost Decimal @db.Decimal(15, 2)
supplierId Int?
remainedInStock Decimal @default(0.00) @db.Decimal(10, 2)
remainedInStock Decimal @default(0.00) @db.Decimal(10, 0)
counterInventoryId Int?
customerId Int?
counterInventory Inventory? @relation("StockMovement_CounterInventory", fields: [counterInventoryId], references: [id])
@@ -48,7 +48,7 @@ model StockBalance {
model StockAdjustment {
id Int @id @default(autoincrement())
adjustedQuantity Decimal @db.Decimal(10, 2)
adjustedQuantity Decimal @db.Decimal(10, 0)
createdAt DateTime @default(now()) @db.Timestamp(0)
productId Int
inventoryId Int
+37
View File
@@ -0,0 +1,37 @@
model Supplier {
id Int @id @default(autoincrement())
firstName String @db.VarChar(255)
lastName String @db.VarChar(255)
email String? @db.VarChar(255)
mobileNumber String @unique @db.Char(11)
address String? @db.Text
city String? @db.VarChar(100)
state String? @db.VarChar(100)
country String? @db.VarChar(100)
isActive Boolean @default(true)
createdAt DateTime @default(now()) @db.Timestamp(0)
updatedAt DateTime @updatedAt @db.Timestamp(0)
deletedAt DateTime? @db.Timestamp(0)
stockMovements StockMovement[] @relation("StockMovement_Supplier")
receipts PurchaseReceipt[]
ledger SupplierLedger[]
@@map("Suppliers")
}
model SupplierLedger {
id Int @id @default(autoincrement())
description String? @db.Text
debit Decimal @default(0) @db.Decimal(15, 2)
credit Decimal @default(0) @db.Decimal(15, 2)
balance Decimal @db.Decimal(15, 2)
sourceType LedgerSourceType
sourceId Int
createdAt DateTime @default(now()) @db.Timestamp(0)
supplierId Int
supplier Supplier @relation(fields: [supplierId], references: [id])
@@index([supplierId])
@@map("Supplier_Ledger")
}
+339 -290
View File
@@ -1,304 +1,353 @@
import { prisma } from '../src/lib/prisma'
import { PurchaseReceiptsService } from '../src/purchase-receipts/purchase-receipts.service'
async function main() {
// if ((await prisma.role.count()) === 0) {
// await prisma.role.upsert({
// where: { id: 0, name: 'Admin' },
// update: {},
// create: {
// name: 'Admin',
// },
// })
// }
if ((await prisma.role.count()) === 0) {
await prisma.role.upsert({
where: { id: 0, name: 'Admin' },
update: {},
create: {
name: 'Admin',
},
})
}
// if ((await prisma.user.count()) === 0) {
// const adminRole = await prisma.role.findUnique({ where: { name: 'Admin' } })
// if (!adminRole) {
// return
// }
// await prisma.user.upsert({
// where: { id: 1, firstName: 'عباس', lastName: 'حسنی' },
// update: {},
// create: {
// firstName: 'عباس',
// lastName: 'حسنی',
// roleId: adminRole.id,
// mobileNumber: '09120258156',
// password: '12345678',
// },
// })
// }
if ((await prisma.user.count()) === 0) {
const adminRole = await prisma.role.findUnique({ where: { name: 'Admin' } })
if (!adminRole) {
return
}
await prisma.user.upsert({
where: { id: 1, firstName: 'عباس', lastName: 'حسنی' },
update: {},
create: {
firstName: 'عباس',
lastName: 'حسنی',
roleId: adminRole.id,
mobileNumber: '09120258156',
password: '12345678',
},
})
}
// if ((await prisma.inventory.count()) === 0) {
// await prisma.inventory.createMany({
// data: [
// { name: 'انبار مرکزی', location: 'تهران', isPointOfSale: false, isActive: true },
// {
// name: 'فروشگاه حضوری',
// location: 'مرکز شهر',
// isPointOfSale: true,
// isActive: true,
// },
// {
// name: 'فروشگاه اینترنتی',
// location: 'مرکز شهر',
// isPointOfSale: true,
// isActive: true,
// },
// ],
// })
// }
if ((await prisma.inventory.count()) === 0) {
await prisma.inventory.createMany({
data: [
{ name: 'انبار مرکزی', location: 'تهران', isPointOfSale: false, isActive: true },
{
name: 'فروشگاه حضوری',
location: 'مرکز شهر',
isPointOfSale: true,
isActive: true,
},
{
name: 'فروشگاه اینترنتی',
location: 'مرکز شهر',
isPointOfSale: true,
isActive: true,
},
],
})
}
// if ((await prisma.productCategory.count()) === 0) {
// await prisma.productCategory.createMany({
// data: Array.from({ length: 10 }, (_, i) => ({ name: `دسته‌ی ${i + 1}` })),
// })
// }
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.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) => ({
// firstName: 'تامین‌',
// lastName: `کننده ${i + 1}`,
// mobileNumber: `0912000000${i + 1}`,
// email: `supplier${i + 1}@example.com`,
// })),
// })
// }
// if ((await prisma.customer.count()) === 0) {
// await prisma.customer.createMany({
// data: Array.from({ length: 5 }, (_, i) => ({
// firstName: 'مشتری',
// lastName: `${i + 1}`,
// mobileNumber: `0913000000${i + 1}`,
// email: `customer${i + 1}@example.com`,
// })),
// })
// }
// 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) => ({
// name: `کالای ${i + 1}`,
// sku: `SKU-${1000 + i + 1}`,
// salePrice: parseInt((Math.random() * (100 - 10) + 10).toString()) * 10000,
// categoryId: categories[i % categories.length].id,
// brandId: brands[i % brands.length].id,
// })),
// })
// }
// if ((await prisma.bank.count()) === 0) {
// await prisma.bank.createMany({
// data: [
// {
// name: 'آینده',
// shortName: 'ain',
// },
// {
// name: 'ایران زمین',
// shortName: 'irz',
// },
// {
// name: 'اقتصاد نوین',
// shortName: 'eqn',
// },
// {
// name: 'انصار',
// shortName: 'ans',
// },
// {
// name: 'پاسارگاد',
// shortName: 'pas',
// },
// {
// name: 'پارسیان',
// shortName: 'prs',
// },
// {
// name: 'پست‌ بانک ایران',
// shortName: 'pbi',
// },
// {
// name: 'تجارت',
// shortName: 'tej',
// },
// {
// name: 'توسعه تعاون',
// shortName: 'tav',
// },
// {
// name: 'توسعه صادرات',
// shortName: 'tes',
// },
// {
// name: 'حکمت ایرانیان',
// shortName: 'hek',
// },
// {
// name: 'رفاه کارگران',
// shortName: 'ref',
// },
// {
// name: 'قرض‌الحسنه رسالت',
// shortName: 'res',
// },
// {
// name: 'قرض‌الحسنه مهر ایران',
// shortName: 'meh',
// },
// {
// name: 'قوامین',
// shortName: 'qva',
// },
// {
// name: 'کشاورزی',
// shortName: 'kes',
// },
// {
// name: 'کوثر',
// shortName: 'kos',
// },
// {
// name: 'دی',
// shortName: 'diy',
// },
// {
// name: 'صنعت و معدن',
// shortName: 'san',
// },
// {
// name: 'سینا',
// shortName: 'sin',
// },
// {
// name: 'سرمایه',
// shortName: 'sar',
// },
// {
// name: 'سپه',
// shortName: 'sep',
// },
// {
// name: 'شهر',
// shortName: 'shr',
// },
// {
// name: 'صادرات ایران',
// shortName: 'sir',
// },
// {
// name: 'سامان',
// shortName: 'sam',
// },
// {
// name: 'مرکزی',
// shortName: 'mar',
// },
// {
// name: 'مسکن',
// shortName: 'mas',
// },
// {
// name: 'ملت',
// shortName: 'mel',
// },
// {
// name: 'ملی ایران',
// shortName: 'mli',
// },
// {
// name: 'مهر اقتصاد',
// shortName: 'meg',
// },
// {
// name: 'کارآفرین',
// shortName: 'kar',
// },
// {
// name: 'تات',
// shortName: 'tat',
// },
// ],
// })
// }
// if ((await prisma.bankBranch.count()) === 0) {
// await prisma.bankBranch.createMany({
// data: [
// {
// bankId: 1,
// name: 'شعبه مرکزی',
// code: '001',
// },
// {
// bankId: 2,
// name: 'شعبه مرکزی',
// code: '002',
// },
// {
// bankId: 1,
// name: 'شعبه ونک',
// code: '003',
// },
// ],
// })
// }
// if ((await prisma.bankAccount.count()) === 0) {
// await prisma.bankAccount.createMany({
// data: [
// {
// branchId: 4,
// accountNumber: '1234567890',
// name: 'حساب اصلی آینده',
// iban: 'IR000123456789012345678901',
// },
// {
// branchId: 5,
// accountNumber: '0987654321',
// name: 'حساب اصلی ایران زمین',
// iban: 'IR000987654321098765432109',
// },
// {
// branchId: 6,
// accountNumber: '1122334455',
// name: 'حساب ونک آینده',
// iban: 'IR000112233445566778899001',
// },
// ],
// })
// }
// // 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
const supplier = await prisma.supplier.findFirst()
const customers = await prisma.customer.findMany({ take: 2 })
if (supplier && customers.length > 0) {
PurchaseReceiptsService.prototype.create({
code: '123123',
inventoryId: inventories[0].id,
supplierId: supplier.id,
paidAmount: 0,
totalAmount: products.reduce((acc, a) => (acc += Number(a.salePrice) * 10), 0),
items: products.map(product => ({
productId: product.id,
count: 10,
fee: Number(product.salePrice),
total: 10 * Number(product.salePrice),
if ((await prisma.supplier.count()) === 0) {
await prisma.supplier.createMany({
data: Array.from({ length: 9 }, (_, i) => ({
firstName: 'تامین‌',
lastName: `کننده ${i + 1}`,
mobileNumber: `0912000000${i + 1}`,
email: `supplier${i + 1}@example.com`,
})),
})
}
if ((await prisma.customer.count()) === 0) {
await prisma.customer.createMany({
data: Array.from({ length: 5 }, (_, i) => ({
firstName: 'مشتری',
lastName: `${i + 1}`,
mobileNumber: `0913000000${i + 1}`,
email: `customer${i + 1}@example.com`,
})),
})
}
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) => ({
name: `کالای ${i + 1}`,
sku: `SKU-${1000 + i + 1}`,
salePrice: parseInt((Math.random() * (100 - 10) + 10).toString()) * 10000,
categoryId: categories[i % categories.length].id,
brandId: brands[i % brands.length].id,
})),
})
}
if ((await prisma.bank.count()) === 0) {
await prisma.bank.createMany({
data: [
{
name: 'آینده',
shortName: 'ain',
},
{
name: 'ایران زمین',
shortName: 'irz',
},
{
name: 'اقتصاد نوین',
shortName: 'eqn',
},
{
name: 'انصار',
shortName: 'ans',
},
{
name: 'پاسارگاد',
shortName: 'pas',
},
{
name: 'پارسیان',
shortName: 'prs',
},
{
name: 'پست‌ بانک ایران',
shortName: 'pbi',
},
{
name: 'تجارت',
shortName: 'tej',
},
{
name: 'توسعه تعاون',
shortName: 'tav',
},
{
name: 'توسعه صادرات',
shortName: 'tes',
},
{
name: 'حکمت ایرانیان',
shortName: 'hek',
},
{
name: 'رفاه کارگران',
shortName: 'ref',
},
{
name: 'قرض‌الحسنه رسالت',
shortName: 'res',
},
{
name: 'قرض‌الحسنه مهر ایران',
shortName: 'meh',
},
{
name: 'قوامین',
shortName: 'qva',
},
{
name: 'کشاورزی',
shortName: 'kes',
},
{
name: 'کوثر',
shortName: 'kos',
},
{
name: 'دی',
shortName: 'diy',
},
{
name: 'صنعت و معدن',
shortName: 'san',
},
{
name: 'سینا',
shortName: 'sin',
},
{
name: 'سرمایه',
shortName: 'sar',
},
{
name: 'سپه',
shortName: 'sep',
},
{
name: 'شهر',
shortName: 'shr',
},
{
name: 'صادرات ایران',
shortName: 'sir',
},
{
name: 'سامان',
shortName: 'sam',
},
{
name: 'مرکزی',
shortName: 'mar',
},
{
name: 'مسکن',
shortName: 'mas',
},
{
name: 'ملت',
shortName: 'mel',
},
{
name: 'ملی ایران',
shortName: 'mli',
},
{
name: 'مهر اقتصاد',
shortName: 'meg',
},
{
name: 'کارآفرین',
shortName: 'kar',
},
{
name: 'تات',
shortName: 'tat',
},
],
})
}
if ((await prisma.bankBranch.count()) === 0) {
await prisma.bankBranch.createMany({
data: [
{
bankId: 1,
name: 'شعبه مرکزی',
code: '001',
},
{
bankId: 2,
name: 'شعبه مرکزی',
code: '002',
},
{
bankId: 1,
name: 'شعبه ونک',
code: '003',
},
],
})
}
if ((await prisma.bankAccount.count()) === 0) {
await prisma.bankAccount.createMany({
data: [
{
branchId: 1,
accountNumber: '1234567890',
name: 'حساب اصلی آینده',
iban: 'IR000123456789012345678901',
},
{
branchId: 2,
accountNumber: '0987654321',
name: 'حساب اصلی ایران زمین',
iban: 'IR000987654321098765432109',
},
{
branchId: 3,
accountNumber: '1122334455',
name: 'حساب ونک آینده',
iban: 'IR000112233445566778899001',
},
],
})
}
// 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,
// })
// }
// 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
// const supplier = await prisma.supplier.findFirst()
// const customers = await prisma.customer.findMany({ take: 2 })
// if (supplier && customers.length > 0) {
// PurchaseReceiptsService.prototype.create({
// code: '123123',
// inventoryId: inventories[0].id,
// supplierId: supplier.id,
// paidAmount: 0,
// totalAmount: products.reduce((acc, a) => (acc += Number(a.salePrice) * 10), 0),
// items: products.map(product => ({
// productId: product.id,
// count: 10,
// fee: Number(product.salePrice),
// total: 10 * Number(product.salePrice),
// })),
// })
// }
}
main()
+169 -10
View File
@@ -1,5 +1,5 @@
-- AUTO-GENERATED MYSQL TRIGGER DUMP
-- Generated at: 2025-12-22T15:32:20.184Z
-- Generated at: 2025-12-26T18:34:53.930Z
-- ------------------------------------------
-- Trigger: trg_transfer_item_after_insert
@@ -7,7 +7,6 @@
-- 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;
@@ -28,13 +27,13 @@ DECLARE fromInv INT;
-- OUT from source
INSERT INTO Stock_Movements
(type, quantity, fee, totalCost, avgCost, referenceType, referenceId, productId, inventoryId, cuonterInventoryId, createdAt, remainedInStock)
(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, cuonterInventoryId, createdAt, remainedInStock)
(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;
@@ -45,7 +44,6 @@ end;
-- Table: Purchase_Receipt_Items
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_purchase_receipt_item_after_insert`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_purchase_receipt_item_after_insert` AFTER INSERT ON `Purchase_Receipt_Items` FOR EACH ROW BEGIN DECLARE latestQuantity DECIMAL(10, 2) DEFAULT 0;
DECLARE invId INT;
@@ -102,13 +100,177 @@ DECLARE invId INT;
END;
-- ------------------------------------------
-- 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);
SELECT totalAmount, paidAmount
INTO receiptTotal, paid
FROM Purchase_Receipts
WHERE id = NEW.receiptId
FOR UPDATE;
IF NEW.type = 'PAYMENT' AND paid + NEW.amount > receiptTotal THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'مجموع مبلغ پرداختی بیشتر از مبلغ فاکتور است.';
END IF;
END;
-- ------------------------------------------
-- Trigger: trg_pr_payment_after_insert
-- Event: INSERT
-- Table: Purchase_Receipt_Payments
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_pr_payment_after_insert`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_pr_payment_after_insert` AFTER INSERT ON `Purchase_Receipt_Payments` FOR EACH ROW BEGIN
DECLARE receiptTotal DECIMAL(14,2);
DECLARE newPaid DECIMAL(14,2);
DECLARE supplierId INT;
DECLARE lastBalance DECIMAL(14,2);
-- Lock receipt row
SELECT totalAmount, paidAmount, supplierId
INTO receiptTotal, newPaid, supplierId
FROM Purchase_Receipts
WHERE id = NEW.receiptId
FOR UPDATE;
-- Apply payment or refund
IF NEW.type = 'PAYMENT' THEN
SET newPaid = newPaid + NEW.amount;
ELSE
SET newPaid = newPaid - NEW.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 = NEW.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(NEW.type = 'REFUND', NEW.amount, 0),
IF(NEW.type = 'PAYMENT', NEW.amount, 0),
lastBalance
+ IF(NEW.type = 'PAYMENT', NEW.amount, 0)
- IF(NEW.type = 'REFUND', NEW.amount, 0),
'PURCHASE_PAYMENT',
NEW.id,
NOW()
);
END;
-- ------------------------------------------
-- Trigger: trg_pr_payment_after_delete
-- Event: DELETE
-- Table: Purchase_Receipt_Payments
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_pr_payment_after_delete`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_pr_payment_after_delete` AFTER DELETE ON `Purchase_Receipt_Payments` FOR EACH ROW BEGIN
DECLARE receiptTotal DECIMAL(14,2);
DECLARE newPaid DECIMAL(14,2);
SELECT totalAmount, paidAmount
INTO receiptTotal, newPaid
FROM Purchase_Receipts
WHERE id = OLD.receiptId
FOR UPDATE;
IF OLD.type = 'PAYMENT' THEN
SET newPaid = newPaid - OLD.amount;
ELSE
SET newPaid = newPaid + OLD.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 = OLD.receiptId;
END;
-- ------------------------------------------
-- Trigger: trg_purchase_receipt_after_insert
-- Event: INSERT
-- Table: Purchase_Receipts
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_purchase_receipt_after_insert`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_purchase_receipt_after_insert` AFTER INSERT ON `Purchase_Receipts` FOR EACH ROW BEGIN
DECLARE lastBalance DECIMAL(14,2) DEFAULT 0;
SELECT COALESCE(balance, 0)
INTO lastBalance
FROM Supplier_Ledger
WHERE supplierId = NEW.supplierId
ORDER BY id DESC
LIMIT 1;
INSERT INTO Supplier_Ledger
(
supplierId,
debit,
credit,
balance,
sourceType,
sourceId,
createdAt
)
VALUES
(
NEW.supplierId,
NEW.totalAmount,
0,
lastBalance - NEW.totalAmount,
'PURCHASE',
NEW.id,
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 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;
@@ -138,7 +300,6 @@ end;
-- 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 DECLARE current_stock DECIMAL(10, 2);
DECLARE inventory_id INT;
@@ -199,7 +360,6 @@ END;
-- Table: Stock_Movements
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_stock_transfer`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_stock_transfer` AFTER INSERT ON `Stock_Movements` FOR EACH ROW BEGIN IF NEW.referenceType = 'INVENTORY_TRANSFER' THEN IF NEW.type = 'IN' THEN
INSERT INTO
Stock_Balance (
@@ -282,7 +442,6 @@ END;
-- 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
@@ -317,7 +476,6 @@ END;
-- 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
INSERT INTO
@@ -345,3 +503,4 @@ ON DUPLICATE KEY UPDATE
END IF;
END;