public function updateRawMaterialQty($raw_material_data) { if (!empty($raw_material_data)) { // Handle composite product_id (e.g. "1924|B2|" or "1919||") $composite = explode('|', $raw_material_data['product_id']); $product_id = $raw_material_data['product_id']; $batch_no = $raw_material_data['batch_no'] ? $raw_material_data['batch_no'] : null; $expiry = $raw_material_data['expiry'] ? $raw_material_data['expiry'] : null; $location_id = $raw_material_data['location_id']; $raw_material_quantity = $raw_material_data['quantity']; // --- Fetch existing purchase item --- $this->db->where('product_id', $product_id); $this->db->where('warehouse_id', $location_id); if ($batch_no) { $this->db->where('batch_number', $batch_no); } else { // Handle NULL, empty string, or no batch $this->db->where("(batch_number IS NULL OR batch_number = '')", NULL, FALSE); } if ($expiry) { $this->db->where('expiry', $expiry); } else { // Handle NULL, empty string, or legacy '0000-00-00' $this->db->where("(expiry IS NULL OR expiry = '' OR expiry = '0000-00-00')", NULL, FALSE); } $purchase_item = $this->db->get('purchase_items')->row(); // --- Warehouse stock record --- $Warehouse_products = $this->site->getWarehouseProductQuantity($location_id, $product_id); // --- Update purchase_items table --- if ($purchase_item) { $quantity_balance = $purchase_item->quantity_balance - $raw_material_quantity; $this->db->update('purchase_items', ['quantity_balance' => $quantity_balance], ['id' => $purchase_item->id]); } else { $pr = $this->site->getProductByID($product_id); $item = [ 'product_id' => $product_id, 'product_code' => $pr->code, 'product_name' => $pr->name, 'net_unit_cost' => $pr->cost, 'unit_cost' => $pr->cost, 'real_unit_cost' => $pr->cost, 'quantity' => $raw_material_quantity, 'option_id' => 0, 'quantity_balance' => $raw_material_quantity, 'item_tax' => 0, 'tax_rate_id' => 1, 'tax' => 0, 'tax_method' => $pr->tax_method, 'subtotal' => ($pr->cost * $raw_material_quantity), 'warehouse_id' => $location_id, 'date' => date('Y-m-d'), 'status' => 'received', 'expiry' => $expiry, 'batch_number' => $batch_no, 'product_unit_id' => $pr->purchase_unit, 'hsn_code' => $pr->hsn_code, 'unit_quantity' => $raw_material_quantity ?: 1 ]; $this->db->insert('purchase_items', $item); } // --- Update warehouse quantity --- if ($Warehouse_products) { $existing_stock = $Warehouse_products->quantity; $new_stock = $existing_stock - $raw_material_quantity; $this->db->where('product_id', $product_id); $this->db->where('warehouse_id', $location_id); $this->db->update('sma_warehouses_products', ['quantity' => $new_stock]); } // --- Sync master product quantity --- $this->site->syncProductQtyForPU($product_id, $location_id); } }