-- AUTO-GENERATED MYSQL TRIGGER DUMP
-- Generated at: 2025-12-10T10:03:36.966Z

-- ------------------------------------------
-- Trigger: trg_transfer_item_after_insert
-- Event: INSERT
-- Table: Inventory_Transfer_Items
-- Status: ACTIVE
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_transfer_item_after_insert`;

CREATE DEFINER=`pos`@`%` TRIGGER `trg_transfer_item_after_insert` AFTER INSERT ON `Inventory_Transfer_Items` FOR EACH ROW begin


    DECLARE fromInv INT;
    DECLARE toInv INT;
    DECLARE _avgCost DECIMAL(10,2);

    SELECT fromInventoryId, toInventoryId INTO fromInv, toInv
    FROM Inventory_Transfers WHERE id = NEW.transferId;

    SELECT COALESCE(avgCost, 0) INTO _avgCost FROM Stock_Balance
    WHERE ProductId = NEW.productId AND inventoryId = fromInv LIMIT 1;


    -- OUT from source
    INSERT INTO Stock_Movements
    (type, quantity, fee, totalCost, avgCost, referenceType, referenceId, productId, inventoryId, createdAt)
    VALUES
        ('OUT', NEW.count,  _avgCost, _avgCost*NEW.count, _avgCost, 'INVENTORY_TRANSFER', NEW.transferId, NEW.productId, fromInv, NOW());

    -- IN to destination
    INSERT INTO Stock_Movements
    (type, quantity, fee, totalCost, avgCost, referenceType, referenceId, productId, inventoryId, createdAt)
    VALUES
        ('IN', NEW.count,_avgCost, _avgCost*NEW.count,_avgCost, 'INVENTORY_TRANSFER', NEW.transferId, NEW.productId, toInv, NOW());
end;

-- ------------------------------------------
-- Trigger: trg_stock_purchase_insert
-- Event: INSERT
-- Table: Stock_Movements
-- Status: ACTIVE
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_stock_purchase_insert`;

CREATE DEFINER=`pos`@`%` TRIGGER `trg_stock_purchase_insert` AFTER INSERT ON `Stock_Movements` FOR EACH ROW BEGIN
    IF NEW.referenceType = 'PURCHASE' THEN

        INSERT INTO Stock_Balance (productId, quantity, avgCost, totalCost, inventoryId, updatedAt)
        VALUES (
            NEW.productId,
            NEW.quantity,
            NEW.fee,
            NEW.totalCost,
            NEW.inventoryId,
            NOW()
        )
        ON DUPLICATE KEY UPDATE
            quantity = quantity + NEW.quantity,
            totalCost = totalCost + NEW.totalCost,
            avgCost = totalCost / quantity;

    END IF;
END

-- ------------------------------------------
-- Trigger: trg_stock_transfer
-- Event: INSERT
-- Table: Stock_Movements
-- Status: ACTIVE
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_stock_transfer`;

CREATE DEFINER=`pos`@`%` TRIGGER `trg_stock_transfer` AFTER INSERT ON `Stock_Movements` FOR EACH ROW BEGIN

  IF NEW.referenceType = 'INVENTORY_TRANSFER' THEN

    IF NEW.type = 'IN' THEN
      INSERT INTO Stock_Balance (
        productId,
        inventoryId,
        quantity,
        totalCost,
        avgCost,
        updatedAt
      )
      VALUES (
        NEW.productId,
        NEW.inventoryId,
        NEW.quantity,
        NEW.totalCost,
        CASE
          WHEN NEW.quantity = 0 THEN 0
          ELSE NEW.totalCost / NEW.quantity
        END,
        NOW()
      )
      ON DUPLICATE KEY UPDATE
        quantity = quantity + NEW.quantity,
        totalCost = totalCost + NEW.totalCost,
        avgCost = CASE
                   WHEN (quantity + NEW.quantity) = 0 THEN 0
                   ELSE (totalCost + NEW.totalCost) / (quantity + NEW.quantity)
                 END,
        updatedAt = NOW();
    END IF;


    IF NEW.type = 'OUT' THEN


      IF EXISTS(
        SELECT 1 FROM Stock_Balance sb
        WHERE sb.productId = NEW.productId
          AND sb.inventoryId = NEW.inventoryId
      ) THEN


        UPDATE Stock_Balance sb
        SET
          sb.quantity = sb.quantity - NEW.quantity,
          sb.totalCost = sb.totalCost - (sb.avgCost * NEW.quantity),
          sb.updatedAt = NOW()
        WHERE sb.productId = NEW.productId
          AND sb.inventoryId = NEW.inventoryId;

      ELSE
        INSERT INTO Stock_Balance (
          productId,
          inventoryId,
          quantity,
          totalCost,
          avgCost,
          updatedAt
        )
        VALUES (
          NEW.productId,
          NEW.inventoryId,
          -NEW.quantity,
          -COALESCE(NEW.fee, 0) * NEW.quantity,
          COALESCE(NEW.fee, 0),
          NOW()
        );
      END IF;

    END IF;

  END IF;
END

-- ------------------------------------------
-- Trigger: trg_purchase_receipt_item_after_insert
-- Event: INSERT
-- Table: Purchase_Receipt_Items
-- Status: ACTIVE
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_purchase_receipt_item_after_insert`;

CREATE DEFINER=`pos`@`%` TRIGGER `trg_purchase_receipt_item_after_insert` AFTER INSERT ON `Purchase_Receipt_Items` FOR EACH ROW begin
    INSERT INTO Stock_Movements
    (
        type,
        quantity,
        fee,
        totalCost,
        referenceType,
        referenceId,
        productId,
        inventoryId,
        supplierId,
        avgCost,
        createdAt
    )
    VALUES
        (
            'IN',
            NEW.count,
            NEW.fee,
            NEW.total,
            'PURCHASE',
            NEW.receiptId,
            NEW.productId,
            (SELECT inventoryId FROM Purchase_Receipts WHERE id = NEW.receiptId),
            (SELECT supplierId FROM Purchase_Receipts WHERE id = NEW.receiptId),
            NEW.total/NEW.count,
            NOW()
        );
end

-- NEW --

-- ------------------------------------------
-- Trigger: trg_purchase_receipt_item_after_insert
-- Event: INSERT
-- Table: Purchase_Receipt_Items
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_purchase_receipt_item_after_insert`;

CREATE DEFINER=`pos`@`%` TRIGGER `trg_purchase_receipt_item_after_insert` AFTER INSERT ON `Purchase_Receipt_Items` FOR EACH ROW begin
    INSERT INTO Stock_Movements
    (
        type,
        quantity,
        referenceType,
        referenceId,
        productId,
        inventoryId,
        createdAt
    )
    VALUES
        (
            'IN',
            NEW.count,
            'PURCHASE',
            NEW.receiptId,
            NEW.productId,
            (SELECT inventoryId FROM Purchase_Receipts WHERE id = NEW.receiptId),
            NOW()
        );
end;

-- ------------------------------------------
-- Trigger: trg_purchase_receipt_item_after_update
-- Event: UPDATE
-- Table: Purchase_Receipt_Items
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_purchase_receipt_item_after_update`;

CREATE DEFINER=`pos`@`%` TRIGGER `trg_purchase_receipt_item_after_update` AFTER UPDATE ON `Purchase_Receipt_Items` FOR EACH ROW begin
    DELETE FROM Stock_Movements
    WHERE referenceType = 'PURCHASE'
      AND referenceId = NEW.receiptId
      AND productId = NEW.productId;

    INSERT INTO Stock_Movements
    (
        type,
        quantity,
        referenceType,
        referenceId,
        productId,
        inventoryId,
        createdAt
    )
    VALUES
        (
            'IN',
            NEW.count,
            'SALES',
            NEW.id,
            NEW.productId,
            (SELECT inventoryId FROM Stores LIMIT 1),
            NOW()
        );
end;

-- ------------------------------------------
-- Trigger: trg_purchase_receipt_item_after_delete
-- Event: DELETE
-- Table: Purchase_Receipt_Items
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_purchase_receipt_item_after_delete`;

CREATE DEFINER=`pos`@`%` TRIGGER `trg_purchase_receipt_item_after_delete` AFTER DELETE ON `Purchase_Receipt_Items` FOR EACH ROW begin
        DELETE FROM Stock_Movements
        WHERE referenceType = 'PURCHASE'
          AND referenceId = OLD.receiptId
          AND productId = OLD.productId;
end;

-- ------------------------------------------
-- Trigger: trg_sales_invoice_items_before_insert
-- Event: INSERT
-- Table: Sales_Invoice_Items
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_sales_invoice_items_before_insert`;

CREATE DEFINER=`pos`@`%` TRIGGER `trg_sales_invoice_items_before_insert` BEFORE INSERT ON `Sales_Invoice_Items` FOR EACH ROW begin
    DECLARE current_stock DECIMAL(10,2);

    SELECT stock INTO current_stock
    FROM stock_view
    WHERE productId = NEW.productId
    LIMIT 1;

    IF current_stock IS NULL THEN
        SET current_stock = 0;
    END IF;

    IF NEW.count > current_stock THEN
        SIGNAL SQLSTATE '45000'
            SET MESSAGE_TEXT = 'Not enough stock to complete sale.';
    END IF;
end;

-- ------------------------------------------
-- Trigger: trg_sales_invoice_items_after_insert
-- Event: INSERT
-- Table: Sales_Invoice_Items
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_sales_invoice_items_after_insert`;

CREATE DEFINER=`pos`@`%` TRIGGER `trg_sales_invoice_items_after_insert` AFTER INSERT ON `Sales_Invoice_Items` FOR EACH ROW begin
    INSERT INTO Stock_Movements
    (
        type,
        quantity,
        referenceType,
        referenceId,
        productId,
        inventoryId,
        createdAt
    )
    VALUES
        (
            'IN',
            NEW.count,
            'PURCHASE',
            NEW.id,
            NEW.productId,
            (SELECT inventoryId FROM Sales_Invoices WHERE id = NEW.id),
            NOW()
        );
end;

-- ------------------------------------------
-- Trigger: trg_stock_adjustment_after_insert
-- Event: INSERT
-- Table: Stock_Adjustments
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_stock_adjustment_after_insert`;

CREATE DEFINER=`pos`@`%` TRIGGER `trg_stock_adjustment_after_insert` AFTER INSERT ON `Stock_Adjustments` FOR EACH ROW begin
    INSERT INTO Stock_Movements
    (type, quantity, referenceType, referenceId, productId, inventoryId, createdAt)
    VALUES
        ('ADJUST', NEW.adjustedQuantity, 'ADJUSTMENT', NEW.id, NEW.productId, NEW.inventoryId, NOW());
end;

-- ------------------------------------------
-- Trigger: trg_stock_sale_insert
-- Event: INSERT
-- Table: Stock_Movements
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_stock_sale_insert`;

CREATE DEFINER=`pos`@`%` TRIGGER `trg_stock_sale_insert` AFTER INSERT ON `Stock_Movements` FOR EACH ROW BEGIN
    IF NEW.referenceType = 'SALES' THEN

        UPDATE stock_balance
        SET
            quantity = quantity - NEW.quantity,
            totalCost = quantity * avgCost
        WHERE productId  = NEW.productId  ;

    END IF;
END;

-- ------------------------------------------
-- Trigger: trg_stock_movement_after_insert
-- Event: INSERT
-- Table: Stock_Movements
-- Status: ARCHIVED
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_stock_movement_after_insert`;

CREATE DEFINER=`pos`@`%` TRIGGER `trg_stock_movement_after_insert` AFTER INSERT ON `Stock_Movements` FOR EACH ROW begin
    UPDATE Products pv
    SET pv.quantity = (
        SELECT COALESCE(SUM(
                                CASE
                                    WHEN type = 'IN' THEN quantity
                                    WHEN type = 'OUT' THEN -quantity
                                    WHEN type = 'ADJUST' THEN quantity
                                    END
                        ), 0)
        FROM Stock_Movements
        WHERE productId = NEW.productId
    )
    WHERE pv.id = NEW.productId;
end;

-- ------------------------------------------
-- Trigger: trg_stock_sale_update
-- Event: UPDATE
-- Table: Stock_Movements
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_stock_sale_update`;

CREATE DEFINER=`pos`@`%` TRIGGER `trg_stock_sale_update` AFTER UPDATE ON `Stock_Movements` FOR EACH ROW BEGIN
    IF OLD.referenceType = 'SALES' THEN
        UPDATE stock_balance
        SET
            quantity = quantity + OLD.quantity,
            totalCost = (quantity + OLD.quantity) * avgCost
        WHERE productId = OLD.productId;
    END IF;

    IF NEW.referenceType = 'SALES' THEN
        UPDATE stock_balance
        SET
            quantity = quantity - NEW.quantity,
            totalCost = (quantity - NEW.quantity) * avgCost
        WHERE productId = NEW.productId;
    END IF;
END;

-- ------------------------------------------
-- Trigger: trg_stock_purchase_update
-- Event: UPDATE
-- Table: Stock_Movements
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_stock_purchase_update`;

CREATE DEFINER=`pos`@`%` TRIGGER `trg_stock_purchase_update` AFTER UPDATE ON `Stock_Movements` FOR EACH ROW BEGIN
    IF OLD.referenceType = 'PURCHASE' THEN
        UPDATE stock_balance
        SET
            quantity = quantity - OLD.quantity,
            totalCost = totalCost - (OLD.quantity * OLD.fee)
        WHERE productId = OLD.productId;
    END IF;

    IF NEW.referenceType = 'PURCHASE' THEN
        INSERT INTO stock_balance (productId, quantity, avgCost, totalCost)
        VALUES (
            NEW.productId,
            NEW.quantity,
            NEW.fee,
            NEW.totalCost
        )
        ON DUPLICATE KEY UPDATE
            quantity = quantity + NEW.quantity,
            totalCost = totalCost + NEW.totalCost,
            avgCost = totalCost / quantity;
    END IF;
END;

-- ------------------------------------------
-- Trigger: trg_stock_sale_delete
-- Event: DELETE
-- Table: Stock_Movements
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_stock_sale_delete`;

CREATE DEFINER=`pos`@`%` TRIGGER `trg_stock_sale_delete` AFTER DELETE ON `Stock_Movements` FOR EACH ROW BEGIN
    IF OLD.ReferenceType = 'SALES' THEN
        UPDATE stock_balance
        SET
            quantity = quantity + OLD.quantity,
            totalCost = (quantity + OLD.quantity) * avgCost
        WHERE productId = OLD.productId;
    END IF;
END;

-- ------------------------------------------
-- Trigger: trg_stock_purchase_delete
-- Event: DELETE
-- Table: Stock_Movements
-- ------------------------------------------
DROP TRIGGER IF EXISTS `trg_stock_purchase_delete`;

CREATE DEFINER=`pos`@`%` TRIGGER `trg_stock_purchase_delete` AFTER DELETE ON `Stock_Movements` FOR EACH ROW BEGIN
    IF OLD.referenceType = 'PURCHASE' THEN
        UPDATE stock_balance
        SET
            quantity = quantity - OLD.quantity,
            totalCost = totalCost - (OLD.quantity * OLD.fee),
            avgCost = CASE
                          WHEN quantity - OLD.quantity = 0 THEN 0
                          ELSE (totalCost - (OLD.quantity * OLD.fee)) / (quantity - OLD.quantity)
                       END
        WHERE productId = OLD.productId;
    END IF;
END;
