93 lines
3.1 KiB
PHP
Executable File
93 lines
3.1 KiB
PHP
Executable File
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use Modules\Erprawmaterials\Models\RawMaterial;
|
|
use Modules\ErpStock\Models\RawMaterialStockMovement;
|
|
use Illuminate\Database\Capsule\Manager as DB;
|
|
use App\Helpers\Log;
|
|
|
|
class RawMaterialStockMovementService
|
|
{
|
|
/**
|
|
* Create a stock movement for a raw material.
|
|
*
|
|
* @param array $data Normalized data for the movement
|
|
* @param object $user The current user
|
|
* @return RawMaterialStockMovement
|
|
* @throws \Exception
|
|
*/
|
|
public function createMovement(array $data, $user)
|
|
{
|
|
// Validate required fields
|
|
if (empty($data['mp_id'])) {
|
|
throw new \Exception("Raw Material ID is required.");
|
|
}
|
|
|
|
// Find the raw material
|
|
$material = RawMaterial::where('mp_id', $data['mp_id'])
|
|
->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;
|
|
}
|
|
}
|
|
}
|