Files
compras/app/Http/Controllers/ProcurementSearchController.php
T
nala eb32c74c56
tests / ci (push) Waiting to run
commit compras1 2811
2026-11-28 07:11:35 +02:00

165 lines
13 KiB
PHP

<?php
namespace App\Http\Controllers;
use App\Enums\PurchasingRole;
use App\Models\Equipment;
use App\Models\GoodsReceipt;
use App\Models\Invoice;
use App\Models\PurchaseOrder;
use App\Models\Requisition;
use App\Models\StockItem;
use App\Models\Supplier;
use App\Models\User;
use App\Models\Warehouse;
use App\Services\AgreementOrderLimits;
use App\Services\OrganizationAccess;
use App\Services\SavedProcurementSearches;
use App\Services\SupplyPlanning;
use App\Services\WarehouseWorkdesk;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Schema;
use Inertia\Inertia;
use Symfony\Component\HttpFoundation\Response;
class ProcurementSearchController extends Controller
{
public function index(Request $request): Response
{
$identity = $request->user('web');
abort_unless($identity instanceof User && $identity->tenant_id !== null, 403);
$actor = User::query()->where('tenant_id', $identity->tenant_id)->findOrFail($identity->id);
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
abort_unless(app(OrganizationAccess::class)->permissions($actor) !== [], 403);
$request->setUserResolver(fn () => $actor);
$data = $request->validate(['q' => 'nullable|string|max:100', 'archived_page' => 'nullable|integer|min:1|max:1000000', 'requests_page' => 'nullable|integer|min:1|max:1000000', 'orders_page' => 'nullable|integer|min:1|max:1000000', 'suppliers_page' => 'nullable|integer|min:1|max:1000000']);
$term = trim($data['q'] ?? '');
$request->validate(['invoices_page' => 'nullable|integer|min:1|max:1000000']);
$request->validate(['agreements_page' => 'nullable|integer|min:1|max:1000000', 'contracts_page' => 'nullable|integer|min:1|max:1000000']);
$request->validate(['warehouse_requests_page' => 'nullable|integer|min:1|max:1000000']);
$planning = app(SupplyPlanning::class);
$supplySelectors = match (DB::getDriverName()) {
'pgsql' => ['LOWER("data"->>\'reference\') LIKE ? ESCAPE \'!\'', 'LOWER("snapshot"->\'supplier\'->>\'name\') LIKE ? ESCAPE \'!\''],
'sqlite' => ["LOWER(json_extract(data, '$.reference')) LIKE ? ESCAPE '!'", "LOWER(json_extract(snapshot, '$.supplier.name')) LIKE ? ESCAPE '!'"],
default => null,
};
$supplySearchAvailable = config('procurement_search.supply_metadata_enabled') === true && Schema::hasTable('supply_records')
&& $supplySelectors !== null
&& collect(['supply_read', 'supply_prepare', 'supply_review'])->contains(fn ($permission) => $planning->allows($actor, $permission));
$warehouseSelectors = match (DB::getDriverName()) {
'pgsql' => ['LOWER("snapshot"->>\'destination\') LIKE ? ESCAPE \'!\'', 'LOWER("snapshot"->\'requester\'->>\'name\') LIKE ? ESCAPE \'!\''],
'sqlite' => ["LOWER(json_extract(snapshot, '$.destination')) LIKE ? ESCAPE '!'", "LOWER(json_extract(snapshot, '$.requester.name')) LIKE ? ESCAPE '!'"],
default => null,
};
$warehouseRequestSearchAvailable = config('procurement_search.warehouse_requests_metadata_enabled') === true
&& $warehouseSelectors !== null && Schema::hasTable('warehouse_requests')
&& $actor->hasFunctions(['admin', 'warehouse_request_read', 'warehouse_request_prepare', 'warehouse_request_review', 'warehouse_request_deliver']);
$request->validate(['equipment_page' => 'nullable|integer|min:1|max:1000000', 'stock_page' => 'nullable|integer|min:1|max:1000000', 'warehouses_page' => 'nullable|integer|min:1|max:1000000', 'receipts_page' => 'nullable|integer|min:1|max:1000000']);
$groups = DB::transaction(function () use ($actor, $term, $planning, $supplySearchAvailable, $supplySelectors, $warehouseRequestSearchAvailable, $warehouseSelectors) {
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
}
if (mb_strlen($term) < 2) {
return [];
}
// Treat wildcard characters as text; never expand a term into an unrestricted match.
$pattern = '%'.str_replace(['!', '%', '_'], ['!!', '!%', '!_'], mb_strtolower($term)).'%';
$requests = Requisition::query()->visibleTo($actor)->where(function ($query) use ($pattern) {
$query->whereRaw("LOWER(number) LIKE ? ESCAPE '!'", [$pattern])->orWhereRaw("LOWER(justification) LIKE ? ESCAPE '!'", [$pattern]);
})->latest('id')->paginate(15, ['id', 'number', 'status'], 'requests_page')->withQueryString()
->through(fn ($row) => ['id' => $row->id, 'title' => $row->number, 'detail' => $row->status, 'href' => '/requisicoes/'.$row->id]);
$groups = [['key' => 'requests', 'title' => 'Requisições', 'records' => $requests]];
if ($actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead])) {
$orders = PurchaseOrder::query()->visibleTo($actor)->whereRaw("LOWER(number) LIKE ? ESCAPE '!'", [$pattern])->latest('id')
->paginate(15, ['id', 'number', 'status'], 'orders_page')->withQueryString()
->through(fn ($row) => ['id' => $row->id, 'title' => $row->number, 'detail' => $row->status, 'href' => '/ordens/'.$row->id]);
$groups[] = ['key' => 'orders', 'title' => 'Ordens', 'records' => $orders];
}
if (Gate::forUser($actor)->allows('viewAny', Supplier::class)) {
$suppliers = Supplier::query()->where(function ($query) use ($pattern) {
$query->whereRaw("LOWER(name) LIKE ? ESCAPE '!'", [$pattern])->orWhereRaw("LOWER(nuit) LIKE ? ESCAPE '!'", [$pattern]);
})->latest('id')->paginate(15, ['id', 'name', 'status'], 'suppliers_page')->withQueryString()
->through(fn ($row) => ['id' => $row->id, 'title' => $row->name, 'detail' => $row->status, 'href' => '/fornecedores/'.$row->id]);
$groups[] = ['key' => 'suppliers', 'title' => 'Fornecedores', 'records' => $suppliers];
}
if ($actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Warehouse, PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead])) {
$equipment = Equipment::query()->when($actor->departmentScoped(), fn ($query) => $query->where('department_id', $actor->department_id))
->where(fn ($query) => $query->whereRaw("LOWER(code) LIKE ? ESCAPE '!'", [$pattern])->orWhereRaw("LOWER(description) LIKE ? ESCAPE '!'", [$pattern]))
->latest('id')->paginate(15, ['id', 'code', 'description'], 'equipment_page')->withQueryString()
->through(fn ($row) => ['id' => $row->id, 'title' => $row->code.' · '.$row->description, 'detail' => 'Equipamento', 'href' => '/equipamentos/'.$row->id]);
$groups[] = ['key' => 'equipment', 'title' => 'Equipamentos', 'records' => $equipment];
}
if ($actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Warehouse, PurchasingRole::Procurement, PurchasingRole::Finance])) {
foreach (['stock' => [StockItem::class, 'Artigos de stock'], 'warehouses' => [Warehouse::class, 'Armazéns']] as $key => [$model, $label]) {
$records = $model::query()->where(fn ($query) => $query->whereRaw("LOWER(code) LIKE ? ESCAPE '!'", [$pattern])->orWhereRaw("LOWER(name) LIKE ? ESCAPE '!'", [$pattern]))
->latest('id')->paginate(15, ['id', 'code', 'name'], $key.'_page')->withQueryString()
->through(fn ($row) => ['id' => $row->id, 'title' => $row->code.' · '.$row->name, 'detail' => $label,
'href' => $key === 'stock' ? '/stock?search='.rawurlencode($row->code) : '/stock?warehouse_id='.$row->id]);
$groups[] = ['key' => $key, 'title' => $label, 'records' => $records];
}
}
if (Gate::forUser($actor)->allows('viewAny', GoodsReceipt::class)) {
$orders = PurchaseOrder::query()->when($actor->departmentScoped(), fn ($query) => $query->visibleTo($actor));
$receipts = GoodsReceipt::query()->whereIn('purchase_order_id', $orders->select('id'))->whereRaw("LOWER(delivery_note) LIKE ? ESCAPE '!'", [$pattern])
->latest('id')->paginate(15, ['id', 'delivery_note'], 'receipts_page')->withQueryString()
->through(fn ($row) => ['id' => $row->id, 'title' => 'Recepção #'.$row->id.' · '.$row->delivery_note, 'detail' => 'Recepção', 'href' => '/recepcoes/'.$row->id]);
$groups[] = ['key' => 'receipts', 'title' => 'Recepções', 'records' => $receipts];
}
if (config('procurement_search.finance_metadata_enabled') === true && $actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance])) {
$invoices = Invoice::query()->whereIn('purchase_order_id', PurchaseOrder::query()->visibleTo($actor)->select('id'))
->whereRaw("LOWER(number) LIKE ? ESCAPE '!'", [$pattern])->latest('id')
->paginate(15, ['id', 'number', 'status'], 'invoices_page')->withQueryString()
->through(fn ($row) => ['id' => $row->id, 'title' => $row->number, 'detail' => $row->status, 'href' => '/facturas?invoice_id='.$row->id]);
$groups[] = ['key' => 'invoices', 'title' => 'Facturas de fornecedor', 'records' => $invoices];
}
if ($supplySearchAvailable) {
foreach (['agreement' => ['agreements', 'Acordos'], 'contract' => ['contracts', 'Contratos globais']] as $kind => [$key, $title]) {
if ($kind === 'contract' && ! app(AgreementOrderLimits::class)->ready()) {
continue;
}
$query = $planning->latest($kind)->where('tenant_id', $actor->tenant_id);
$query->where(function ($query) use ($supplySelectors, $pattern) {
// Fixed SQL for the supported engines; the user's term stays bound.
$query->whereRaw($supplySelectors[0], [$pattern])->orWhereRaw($supplySelectors[1], [$pattern]);
});
$records = $query->latest('id')->paginate(15, ['id', 'version', 'state', 'data->reference as reference'], $key.'_page')->withQueryString()
->through(fn ($row) => ['id' => $row->id, 'title' => ($row->getAttribute('reference') ?: 'Referência por completar').' · v'.$row->version,
'detail' => $row->state, 'href' => '/compras/fornecimento?view='.$key.'&record_id='.$row->id.'#supply-record-'.$row->id]);
$groups[] = ['key' => $key, 'title' => $title, 'records' => $records];
}
}
if ($warehouseRequestSearchAvailable) {
$desk = app(WarehouseWorkdesk::class);
$query = $desk->visible($actor)->where('tenant_id', $actor->tenant_id);
if (preg_match('/^(?:RA-)?([1-9][0-9]{0,9})$/iD', $term, $match)) {
$query->whereKey($match[1]);
} else {
$query->where(fn ($query) => $query->whereRaw($warehouseSelectors[0], [$pattern])->orWhereRaw($warehouseSelectors[1], [$pattern]));
}
$records = $query->select('warehouse_requests.id')->selectRaw($desk->stateExpression().' as projected_state')->latest('id')
->paginate(15, ['id'], 'warehouse_requests_page')->withQueryString()->through(fn ($row) => [
'id' => $row->id, 'title' => 'RA-'.$row->id, 'detail' => $row->getAttribute('projected_state'), 'href' => '/stock/requisicoes/'.$row->id]);
$groups[] = ['key' => 'warehouse_requests', 'title' => 'Requisições internas de armazém', 'records' => $records];
}
return $groups;
});
Inertia::encryptHistory();
$response = Inertia::render('search/procurement', ['term' => $term, 'groups' => $groups,
'savedSearches' => app(SavedProcurementSearches::class)->read($actor),
'invoiceSearchAvailable' => config('procurement_search.finance_metadata_enabled') === true && $actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance]),
'supplySearchAvailable' => $supplySearchAvailable,
'warehouseRequestSearchAvailable' => $warehouseRequestSearchAvailable,
])->toResponse($request);
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
return $response;
}
}