feat(inventories): add cardex retrieval for inventory and product

feat(pos): update sale invoice creation to include customer and item details
feat(pos): enhance POS account service to include today's sales information
feat(pos): refactor order DTO to create sale invoice with detailed item structure
feat(products): add minimum stock alert level to product creation and update DTOs
fix(triggers): implement stock validation and movement logging for sales invoice items
refactor(database): update sales invoices schema to include posAccountId and remove inventoryId
This commit is contained in:
2025-12-30 21:04:01 +03:30
parent 1bb206a608
commit eb6e0e7a0d
30 changed files with 1265 additions and 648 deletions
@@ -0,0 +1,50 @@
/*
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`;
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE `Products` ADD COLUMN `minimumStockAlertLevel` DECIMAL(10, 0) NOT NULL DEFAULT 1.00;
+5 -4
View File
@@ -10,7 +10,6 @@ model Inventory {
inventoryTransfersFrom InventoryTransfer[] @relation("Inventory_From")
inventoryTransfersTo InventoryTransfer[] @relation("Inventory_To")
purchaseReceipts PurchaseReceipt[]
salesInvoices SalesInvoice[] @relation("Inventory_SalesInvoices")
stockAdjustments StockAdjustment[] @relation("Inventory_Stock_Adjustments")
stockBalances StockBalance[] @relation("StockBalance_inventory")
counterStockMovements StockMovement[] @relation("StockMovement_CounterInventory")
@@ -24,9 +23,10 @@ model InventoryBankAccount {
inventoryId Int
bankAccountId Int
inventory Inventory @relation(fields: [inventoryId], references: [id])
bankAccount BankAccount @relation(fields: [bankAccountId], references: [id])
posAccounts PosAccount[]
inventory Inventory @relation(fields: [inventoryId], references: [id])
bankAccount BankAccount @relation(fields: [bankAccountId], references: [id])
posAccounts PosAccount[]
purchaseReceiptPayments PurchaseReceiptPayments[]
@@id([inventoryId, bankAccountId])
@@index([bankAccountId])
@@ -45,6 +45,7 @@ model PosAccount {
deletedAt DateTime? @db.Timestamp(0)
inventoryBankAccount InventoryBankAccount @relation(fields: [inventoryId, bankAccountId], references: [inventoryId, bankAccountId])
salesInvoices SalesInvoice[]
@@index([inventoryId])
@@map("Pos_Accounts")
+22 -22
View File
@@ -12,9 +12,9 @@ model Customer {
createdAt DateTime @default(now()) @db.Timestamp(0)
updatedAt DateTime @updatedAt @db.Timestamp(0)
deletedAt DateTime? @db.Timestamp(0)
orders Order[] @relation("Customer_Orders")
salesInvoices SalesInvoice[] @relation("Customer_Sales_Invoices")
stockMovements StockMovement[] @relation("StockMovement_Customer")
orders Order[] @relation()
stockMovements StockMovement[] @relation()
salesInvoices SalesInvoice[]
@@map("Customers")
}
@@ -30,27 +30,27 @@ model Order {
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(fields: [customerId], references: [id], onUpdate: NoAction)
@@index([customerId], map: "Orders_customerId_fkey")
@@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?
inventoryId Int
items SalesInvoiceItem[] @relation("SalesInvoice_Items")
customer Customer? @relation("Customer_Sales_Invoices", fields: [customerId], references: [id])
inventory Inventory @relation("Inventory_SalesInvoices", fields: [inventoryId], references: [id])
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([inventoryId], map: "Sales_Invoices_inventoryId_fkey")
@@index([customerId], map: "Sales_Invoices_customerId_fkey")
@@index([customerId])
@@index([posAccountId])
@@map("Sales_Invoices")
}
@@ -62,11 +62,11 @@ model SalesInvoiceItem {
createdAt DateTime @default(now()) @db.Timestamp(0)
invoiceId Int
productId Int
invoice SalesInvoice @relation("SalesInvoice_Items", fields: [invoiceId], references: [id])
product Product @relation("Product_SalesInvoiceItems", fields: [productId], references: [id])
invoice SalesInvoice @relation(fields: [invoiceId], references: [id])
product Product @relation(fields: [productId], references: [id])
@@index([invoiceId], map: "Sales_Invoice_Items_invoiceId_fkey")
@@index([productId], map: "Sales_Invoice_Items_productId_fkey")
@@index([invoiceId])
@@index([productId])
@@map("Sales_Invoice_Items")
}
+5 -5
View File
@@ -4,7 +4,7 @@ model ProductVariant {
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)
barcode String? @unique() @db.VarChar(100)
imageUrl String? @db.VarChar(255)
unit String? @db.VarChar(10)
quantity Decimal? @default(0.00) @db.Decimal(10, 0)
@@ -25,24 +25,24 @@ model Product {
id Int @id @default(autoincrement())
name String @db.VarChar(255)
description String? @db.Text
sku String? @unique(map: "products_sku_unique") @db.VarChar(100)
barcode String? @unique(map: "products_barcode_unique") @db.VarChar(100)
sku String? @unique() @db.VarChar(100)
barcode String? @unique() @db.VarChar(100)
createdAt DateTime @default(now()) @db.Timestamp(0)
updatedAt DateTime @updatedAt @db.Timestamp(0)
deletedAt DateTime? @db.Timestamp(0)
brandId Int?
categoryId Int?
salePrice Decimal @default(0.00) @db.Decimal(15, 0)
minimumStockAlertLevel Decimal @default(1.00) @db.Decimal(10, 0)
inventoryTransferItems InventoryTransferItem[] @relation("InventoryTransferItem_Product")
// productCharges ProductCharge[] @relation("Product_Charges")
variants ProductVariant[] @relation("Product_Variant")
brand ProductBrand? @relation("Product_Brand", fields: [brandId], references: [id], onUpdate: NoAction)
category ProductCategory? @relation("Product_Category", fields: [categoryId], references: [id], onUpdate: NoAction)
purchaseReceiptItems PurchaseReceiptItem[] @relation("Product_PurchaseReceiptItems")
salesInvoiceItems SalesInvoiceItem[] @relation("Product_SalesInvoiceItems")
stockAdjustments StockAdjustment[] @relation("Product_Stock_Adjustments")
stockBalances StockBalance[] @relation("StockBalance_Product")
stockMovements StockMovement[] @relation("StockMovement_Product")
salesInvoiceItems SalesInvoiceItem[]
@@index([brandId], map: "Products_brandId_fkey")
@@index([categoryId], map: "Products_categoryId_fkey")
+5 -2
View File
@@ -47,8 +47,11 @@ model PurchaseReceiptPayments {
description String? @db.Text
createdAt DateTime @default(now()) @db.Timestamp(0)
receipt PurchaseReceipt @relation(fields: [receiptId], references: [id])
bankAccount BankAccount @relation(fields: [bankAccountId], references: [id])
receipt PurchaseReceipt @relation(fields: [receiptId], references: [id])
bankAccount BankAccount @relation(fields: [bankAccountId], references: [id])
inventoryBankAccount InventoryBankAccount? @relation(fields: [inventoryBankAccountInventoryId, inventoryBankAccountBankAccountId], references: [inventoryId, bankAccountId])
inventoryBankAccountInventoryId Int?
inventoryBankAccountBankAccountId Int?
@@index([receiptId], map: "Purchase_Receipt_Payments_receiptId_fkey")
@@map("Purchase_Receipt_Payments")
+1 -1
View File
@@ -15,7 +15,7 @@ model StockMovement {
counterInventoryId Int?
customerId Int?
counterInventory Inventory? @relation("StockMovement_CounterInventory", fields: [counterInventoryId], references: [id])
customer Customer? @relation("StockMovement_Customer", fields: [customerId], references: [id])
customer Customer? @relation(fields: [customerId], references: [id])
inventory Inventory @relation("StockMovement_Inventory", fields: [inventoryId], references: [id])
product Product @relation("StockMovement_Product", fields: [productId], references: [id])
supplier Supplier? @relation("StockMovement_Supplier", fields: [supplierId], references: [id])
+39 -30
View File
@@ -1,5 +1,5 @@
-- AUTO-GENERATED MYSQL TRIGGER DUMP
-- Generated at: 2025-12-26T18:34:53.930Z
-- Generated at: 2025-12-30T15:42:45.224Z
-- ------------------------------------------
-- 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;
@@ -45,13 +44,12 @@ 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;
DECLARE suppId INT;
-- Get inventory & supplier from receipt
-- Get inventory & supplier from
SELECT inventoryId, supplierId
INTO invId, suppId
FROM Purchase_Receipts
@@ -108,11 +106,12 @@ END;
-- 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
FROM Purchase_Receipts
@@ -131,19 +130,20 @@ END;
-- 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) DEFAULT 0;
DECLARE newPaid DECIMAL(14,2) DEFAULT 0;
DECLARE supplierId INT;
DECLARE lastBalance DECIMAL(14,2) DEFAULT 0;
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
SELECT COALESCE(totalAmount, 0), COALESCE(paidAmount, 0), supplierId
INTO receiptTotal, newPaid, _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
@@ -168,7 +168,7 @@ CREATE DEFINER=`pos`@`%` TRIGGER `trg_pr_payment_after_insert` AFTER INSERT ON `
SELECT IFNULL(balance, 0)
INTO lastBalance
FROM Supplier_Ledger
WHERE supplierId = supplierId
WHERE supplierId = _supplierId
ORDER BY id DESC
LIMIT 1;
@@ -185,13 +185,13 @@ CREATE DEFINER=`pos`@`%` TRIGGER `trg_pr_payment_after_insert` AFTER INSERT ON `
)
VALUES
(
supplierId,
_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',
'PAYMENT',
NEW.id,
NOW()
);
@@ -203,7 +203,6 @@ END;
-- 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);
@@ -238,7 +237,6 @@ END;
-- 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;
@@ -277,16 +275,18 @@ END;
-- 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;
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 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
@@ -307,17 +307,28 @@ 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;
DECLARE customer_id INT;
DECLARE pos_id INT;
SELECT inventoryId , customerId INTO inventory_id, customer_id
SELECT posAccountId, customerId INTO pos_id, customer_id
FROM Sales_Invoices si
WHERE si.id = NEW.invoiceId
LIMIT 1;
INSERT INTO Trigger_Logs (name , message) VALUES ('pos_id', pos_id);
INSERT INTO Trigger_Logs (name , message) VALUES ('customer_id', customer_id);
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
@@ -354,7 +365,7 @@ DECLARE customer_id INT;
WHEN NEW.count = 0 THEN 0
ELSE NEW.total / NEW.count
END,
current_stock + NEW.count,
current_stock - NEW.count,
customer_id,
NOW()
);
@@ -368,7 +379,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 (
@@ -451,7 +461,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
@@ -486,7 +495,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
@@ -514,3 +522,4 @@ ON DUPLICATE KEY UPDATE
END IF;
END;