where('mp_idbus', $user->users_bus_id) ->first(); if (!$material) { throw new \Exception("Raw Material not found."); } $quantity = $data['quantity'] ?? 0; if ($quantity <= 0) { throw new \Exception("Invalid quantity: must be greater than zero."); } $type = $data['type'] ?? 'E'; // E = Entry, S = Exit // Prepare data for model $movementData = [ 'memp_idbus' => $user->users_bus_id, 'memp_idmp' => $material->mp_id, 'memp_data' => date('Y-m-d'), 'memp_idoperador' => $user->users_id, 'memp_tipoes' => $type, 'memp_qtdade' => $quantity, 'memp_historico' => $data['history'] ?? '', 'memp_documento' => $data['document'] ?? '', 'memp_lote' => $data['batch'] ?? '', 'memp_custo' => $data['cost'] ?? 0, 'memp_preco' => $data['price'] ?? 0, 'memp_ipi' => $data['ipi'] ?? 0, 'memp_icms' => $data['icms'] ?? 0, 'memp_oimpostos' => $data['other_taxes'] ?? 0, 'memp_obs' => $data['observation'] ?? '', 'memp_codigo' => $material->mp_codigo, 'memp_nome' => $material->mp_descricao, 'memp_idfornecedor' => $data['supplier_id'] ?? 0, 'memp_idcliente' => $data['customer_id'] ?? 0, 'memp_idarmazem' => $data['warehouse_id'] ?? 0, ]; // Begin transaction DB::beginTransaction(); try { // Create movement record using the ErpStock model which includes warehouse support $movement = RawMaterialStockMovement::create($movementData); // Update raw material stock level if ($type === 'E') { $material->mp_estocado += $quantity; } else { $material->mp_estocado -= $quantity; } $material->save(); DB::commit(); Log::write("Movimentação de estoque ({$type}) para: {$material->mp_descricao} (Qtd: {$quantity})", 'erprawmaterials'); return $movement; } catch (\Exception $e) { DB::rollBack(); throw $e; } } }