commit melhorias compras3
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-11-22 10:56:58 +02:00
parent 4fac443dda
commit efd97e265b
130 changed files with 8917 additions and 363 deletions
@@ -0,0 +1,87 @@
<?php
namespace App\Http\Controllers;
use App\Services\AgreementFollowup;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Symfony\Component\HttpFoundation\Response;
final class AgreementFollowupController extends Controller
{
public function index(Request $request, AgreementFollowup $read): Response
{
return $this->respond($request, $read, false);
}
public function csv(Request $request, AgreementFollowup $read): Response
{
return $this->respond($request, $read, true);
}
private function respond(Request $request, AgreementFollowup $read, bool $csv): Response
{
$actor = $this->staffIdentity($request);
return DB::transaction(function () use ($request, $read, $csv, $actor) {
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
}
$actor = $read->authorize($actor);
$filters = $read->filters($request);
$kind = $request->validate(['kind' => 'nullable|in:agreement,contract'])['kind'] ?? 'agreement';
$today = today()->toDateString();
$query = $read->query($actor, $filters, $today, $kind)->orderBy('id');
if (! $csv) {
$page = $query->paginate(25)->withQueryString();
Inertia::encryptHistory();
$response = Inertia::render('supply/agreement-followup', ['kind' => $kind, 'asOf' => $today, 'filters' => $filters, 'records' => [
'data' => $read->rows($page->getCollection(), $today), 'total' => $page->total(), 'current_page' => $page->currentPage(),
'last_page' => $page->lastPage(), 'prev_page_url' => $page->previousPageUrl(), 'next_page_url' => $page->nextPageUrl(),
]])->toResponse($request);
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
$response->headers->set('X-Content-Type-Options', 'nosniff');
return $response;
}
$file = fopen('php://temp', 'w+');
if ($file === false) {
throw new \RuntimeException('Não foi possível preparar o CSV.');
}
try {
fwrite($file, "\xEF\xBB\xBF");
$write = static function (array $cells) use ($file): void {
fputcsv($file, array_map(static function (mixed $value): string {
$text = $value === null ? 'Não disponível' : (string) $value;
return preg_match('/^[\s\x00-\x1F]*[=+@-]/u', $text) ? "'".$text : $text;
}, $cells), ';', '"', '');
};
$write([$kind === 'contract' ? 'Vigência de contratos globais aprovados' : 'Vigência de acordos aprovados', 'Data de consulta', $today]);
$write(['Pesquisa', $filters['search'], 'Situação', $filters['validity'], 'Termina até', $filters['expires_by']]);
$write(['Registo', 'Versão', 'Referência', 'Fornecedor preservado', 'Código do artigo', 'Artigo preservado', 'Armazém preservado', 'Início', 'Fim', 'Situação de vigência', 'Políticas aprovadas ligadas', 'Acordo', 'Políticas',
...($kind === 'contract' ? ['Moeda', 'Limite global por ordem (centavos)', 'Periodicidade prevista (dias)', 'Artigos aprovados', 'Artigos ligados'] : [])]);
$query->chunk(100, function ($batch) use ($read, $today, $write, $kind) {
foreach ($read->rows($batch, $today) as $row) {
$write([$row['record_key'], $row['version'], $row['reference'], $row['supplier'], $kind === 'contract' ? 'Não aplicável' : $row['item_code'], $kind === 'contract' ? 'Não aplicável' : $row['item'], $kind === 'contract' ? 'Não aplicável' : $row['warehouse'],
$row['valid_from'], $row['valid_until'], match ($row['validity']) {
'current' => 'Vigente','expired' => 'Expirado','future' => 'Por iniciar',default => 'Datas indeterminadas'
}, $kind === 'contract' ? 'Não aplicável' : $row['approved_policies'], $row['href'], $kind === 'contract' ? 'Não aplicável' : $row['policies_href'],
...($kind === 'contract' ? [$row['currency'], $row['max_order_value_minor'] ?? 'Não definido', $row['periodicity_days'], $row['approved_articles'], $row['articles_href']] : [])]);
}
});
rewind($file);
$body = stream_get_contents($file);
if ($body === false) {
throw new \RuntimeException('Não foi possível ler o CSV preparado.');
}
} finally {
fclose($file);
}
return response($body, 200, ['Content-Type' => 'text/csv; charset=UTF-8', 'Content-Disposition' => 'attachment; filename="vigencia-'.($kind === 'contract' ? 'contratos' : 'acordos').'-'.$today.'.csv"',
'Cache-Control' => 'private, no-store, max-age=0', 'X-Content-Type-Options' => 'nosniff']);
});
}
}
@@ -6,6 +6,7 @@ use App\Models\Tenant;
use App\Models\User;
use App\Services\AdministrativeGeography;
use App\Services\AiPreparationPlan;
use App\Services\CompanyDetails;
use App\Services\ComparisonPolicy;
use App\Services\IntelligencePolicy;
use App\Services\OrganizationAccess;
@@ -40,6 +41,8 @@ class OrganizationConfigurationController extends Controller
'activationPreview' => app(OrganizationActivationPreview::class)->build($actor),
'geographyEnabled' => app(AdministrativeGeography::class)->enabled(),
'geography' => app(AdministrativeGeography::class)->describe(Tenant::query()->findOrFail($actor->tenant_id)->geography_reference),
'companyDetailsReady' => Schema::hasColumn('tenants', 'company_details'),
'companyDetails' => Tenant::query()->findOrFail($actor->tenant_id)->company_details,
'companyRules' => $this->companyRules((int) $actor->tenant_id),
'comparisonPolicy' => app(ComparisonPolicy::class)->company(Tenant::query()->findOrFail($actor->tenant_id)),
'intelligencePolicy' => app(IntelligencePolicy::class)->company(Tenant::query()->findOrFail($actor->tenant_id)),
@@ -68,7 +71,9 @@ class OrganizationConfigurationController extends Controller
$actor = $service->administrator($user);
abort_unless(Schema::hasTable('organization_access'), 503, 'A instalação da parametrização ainda não está concluída.');
$rules = ['version' => 'required|integer|min:1', 'tenant_id' => 'prohibited', 'purchasing_role' => 'prohibited'];
if ($command === 'profile') {
if ($command === 'company_details') {
$rules += app(CompanyDetails::class)->rules();
} elseif ($command === 'profile') {
$rules += ['work_contexts' => 'sometimes|array', 'work_contexts.*' => ['string', 'distinct', Rule::in(array_keys(WorkContext::OPTIONS))]];
$rules += ['id' => 'nullable|integer|min:1', 'name' => ['required', 'string', 'max:120', Rule::unique('organization_profiles')->where('tenant_id', $actor->tenant_id)->ignore($request->integer('id'))],
'permissions' => 'present|array', 'permissions.*' => ['string', 'distinct', Rule::in(array_keys(OrganizationAccess::PERMISSIONS))]];
@@ -131,7 +131,7 @@ class ProcurementReportController extends Controller
'created_at' => $record->created_at?->toIso8601String(),
'needed_by' => $record->needed_by?->toDateString(),
'department' => $record->department?->name, 'requester' => $record->requester?->name,
'total_minor' => (string) $record->total_minor,
'total_minor' => $record->total_minor === null ? null : (string) $record->total_minor,
'quotations_count' => (int) $record->getAttribute('quotations_count'),
'order_number' => $record->getAttribute('order_number'),
];
@@ -181,7 +181,7 @@ class ProcurementReportController extends Controller
foreach ($query->lazyById(200) as $record) {
$row = $this->row($record);
$base = url('/requisicoes/'.$record->id);
fputcsv($output, [$text($record->number), $row['created_at'], $text($row['department']), $text($row['requester']), $record->status, $row['total_minor'], $row['quotations_count'], $text($row['order_number']), $base.'/processo', $base.'/relatorio', $row['needed_by']], ';', '"', '');
fputcsv($output, [$text($record->number), $row['created_at'], $text($row['department']), $text($row['requester']), $record->status, $row['total_minor'] ?? 'Por completar', $row['quotations_count'], $text($row['order_number']), $base.'/processo', $base.'/relatorio', $row['needed_by']], ';', '"', '');
}
fclose($output);
}), 'relatorio-compras-'.now()->format('Ymd-His').'.csv', ['Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'private, no-store, max-age=0']);
@@ -0,0 +1,104 @@
<?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\OrganizationAccess;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
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', '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(['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) {
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->whereIn('requisition_id', Requisition::query()->visibleTo($actor)->select('id')));
$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];
}
return $groups;
});
Inertia::encryptHistory();
$response = Inertia::render('search/procurement', ['term' => $term, 'groups' => $groups])->toResponse($request);
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
return $response;
}
}
+11 -2
View File
@@ -7,9 +7,11 @@ use App\Models\AuditLog;
use App\Models\AwardCancellation;
use App\Models\PurchaseAward;
use App\Models\PurchaseOrder;
use App\Models\Quotation;
use App\Models\RecommendationAttempt;
use App\Models\Requisition;
use App\Models\User;
use App\Services\AgreementOrderLimits;
use App\Services\FormalRecommendation;
use App\Services\OrderCancellationWorkflow;
use App\Services\OrganizationAccess;
@@ -56,7 +58,13 @@ class PurchaseController extends Controller
}
}
$agreementFilters = $request->validate(['agreement_search' => 'nullable|string|max:100', 'selected_agreement_ids' => 'nullable|array|max:100', 'selected_agreement_ids.*' => 'integer|min:1|distinct']);
return Inertia::render('purchases/award', [
'agreementOrderLimitsReady' => app(AgreementOrderLimits::class)->ready() && app(AgreementOrderLimits::class)->canRead($actor),
'agreementSearch' => $agreementFilters['agreement_search'] ?? '',
'agreementOptions' => $award === null ? [] : app(AgreementOrderLimits::class)->options($actor, $requisition, Quotation::query()->find($award->quotation_id), trim($agreementFilters['agreement_search'] ?? ''), $agreementFilters['selected_agreement_ids'] ?? []),
'agreementLines' => $requisition->items()->get()->map(fn ($line) => ['id' => $line->id, 'description' => $line->description, 'unit' => $line->unit, 'stock_item_id' => $line->catalogue_snapshot['stock_item_id'] ?? null]),
'requisition' => $requisition, 'comparison' => $comparison->inspect($requisition), 'award' => $award,
'canSelect' => ! app(OrganizationAccess::class)->maintenanceOnly($actor) && $actor->hasFunctions([PurchasingRole::Procurement]) && $award === null && $actor->id !== $requisition->requester_id && (! $adoption || $candidate !== null),
'recommendation' => ['adopted' => $adoption !== null, 'quotation_id' => $candidate],
@@ -93,11 +101,12 @@ class PurchaseController extends Controller
public function issue(Request $request, PurchaseAward $award, PurchaseWorkflow $workflow): RedirectResponse
{
$actor = $this->access($request);
$request->validate([
$validated = $request->validate([
'status' => 'prohibited', 'snapshot' => 'prohibited', 'total_minor' => 'prohibited', 'subtotal_minor' => 'prohibited', 'tax_minor' => 'prohibited',
'issued_by' => 'prohibited', 'tenant_id' => 'prohibited', 'quotation_id' => 'prohibited', 'override' => 'prohibited', 'exception' => 'prohibited',
'agreement_bindings' => 'sometimes|array|max:100',
]);
$order = $workflow->issue($actor, $award);
$order = $workflow->issue($actor, $award, $validated['agreement_bindings'] ?? []);
return to_route('orders.show', $order);
}
@@ -20,6 +20,7 @@ use App\Services\InternalSupplyTrace;
use App\Services\OrganizationAccess;
use App\Services\RequisitionAuditTrail;
use App\Services\RequisitionCatalogue;
use App\Services\RequisitionDraftInput;
use App\Services\RequisitionWorkflow;
use App\Services\SupplySuggestions;
use App\Services\WorkContext;
@@ -74,6 +75,7 @@ class RequisitionController extends Controller
return Inertia::render('requisitions/form', [
'costCenters' => CostCenter::query()->where('department_id', $this->actor($request)->department_id)->orderBy('code')->get(),
'requisition' => null,
'incompleteDraftsAvailable' => app(RequisitionDraftInput::class)->available(),
'defaultTaxRate' => (string) (Tenant::query()->findOrFail($this->actor($request)->tenant_id)->default_tax_rate ?? '16.00'),
...$this->equipmentOptions($request),
'catalogue' => $this->catalogueOptions($request),
@@ -135,6 +137,7 @@ class RequisitionController extends Controller
return Inertia::render('requisitions/form', [
'requisition' => $requisition->load('items'),
'incompleteDraftsAvailable' => app(RequisitionDraftInput::class)->available(),
'defaultTaxRate' => (string) (Tenant::query()->findOrFail($this->actor($request)->tenant_id)->default_tax_rate ?? '16.00'),
'costCenters' => CostCenter::query()->where('department_id', $this->actor($request)->department_id)->orderBy('code')->get(),
...$this->equipmentOptions($request),
@@ -6,6 +6,7 @@ use App\Models\SupplyRecord;
use App\Models\User;
use App\Services\SupplyCoordination;
use App\Services\SupplyCoordinationRead;
use Brick\Math\BigDecimal;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
@@ -50,20 +51,24 @@ class SupplyCoordinationReportController extends Controller
fwrite($out, "\xEF\xBB\xBF");
fputcsv($out, ['Acompanhamento de fornecimentos', $view, 'Conferido em', now()->toIso8601String()], ';', '"', '');
fputcsv($out, ['Filtros', $text(json_encode($filters, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)), 'Registo em foco', $focus['record_id'] ?? ''], ';', '"', '');
fputcsv($out, ['Registo', 'Versão', 'Estado registado', 'Artigo', 'Designação preservada', 'Local preservado', 'Referência', 'Encomenda', 'Quantidade', 'Unidade', 'Data prevista/necessidade', 'Quantidade por satisfazer (ver estado)', 'Substituto', 'Aplicação', 'Validade', 'Processo'], ';', '"', '');
fputcsv($out, ['Registo', 'Versão', 'Estado registado', 'Artigo', 'Designação preservada', 'Local preservado', 'Referência', 'Encomenda', 'Quantidade', 'Unidade', 'Data prevista/necessidade', 'Quantidade por satisfazer (ver estado)', 'Substituto', 'Aplicação', 'Validade', 'Processo', 'Unidade da quantidade pendente', 'Factor físico', 'Fonte da conversão', 'Versão da conversão'], ';', '"', '');
foreach ($query->lazyById(100) as $record) {
$pending = match ($kind) {
'reservation' => app(SupplyCoordination::class)->remainingReservation($record),
'delivery' => app(SupplyCoordination::class)->remainingDelivery($record),
default => null,
};
$basis = $record->snapshot['quantity_conversion'] ?? null;
$quantity = static fn (int|string $milli): string => (string) BigDecimal::of($milli)->dividedBy(1000, 3)->strippedOfTrailingZeros();
fputcsv($out, array_map($text, [$record->record_key, $record->version, $record->state,
$record->snapshot['item']['code'] ?? '', $record->snapshot['item']['name'] ?? '', $record->snapshot['warehouse']['name'] ?? '',
$record->data['reference'] ?? '', $record->snapshot['order']['number'] ?? '',
isset($record->data['quantity_milli']) ? $record->data['quantity_milli'] / 1000 : '', $record->snapshot['item']['unit'] ?? '',
$record->data['needed_on'] ?? $record->data['expected_on'] ?? '', $pending === null ? '' : $pending / 1000,
isset($record->data['quantity_milli']) ? $quantity($record->data['quantity_milli']) : '', $basis['document_unit'] ?? $record->snapshot['item']['unit'] ?? '',
$record->data['needed_on'] ?? $record->data['expected_on'] ?? '', $pending === null ? '' : $quantity($pending),
$record->snapshot['substitute']['code'] ?? '', $record->data['application'] ?? '', $record->data['valid_until'] ?? '',
url('/compras/fornecimento?view='.$view.'&record_id='.$record->id).'#supply-record-'.$record->id]), ';', '"', '');
url('/compras/fornecimento?view='.$view.'&record_id='.$record->id).'#supply-record-'.$record->id,
$pending === null ? '' : ($record->snapshot['item']['unit'] ?? ''), $basis === null ? '' : $basis['numerator'].'/'.$basis['denominator'],
$basis['source'] ?? '', $basis['version'] ?? '']), ';', '"', '');
}
} finally {
fclose($out);
@@ -13,6 +13,7 @@ use App\Models\Supplier;
use App\Models\SupplyRecord;
use App\Models\User;
use App\Models\Warehouse;
use App\Services\AgreementOrderLimits;
use App\Services\InventoryReversals;
use App\Services\OrganizationAccess;
use App\Services\ReceiptWorkflow;
@@ -52,7 +53,10 @@ class SupplyPlanningController extends Controller
private function page(Request $request, SupplyPlanning $planning, User $actor): HttpResponse
{
Inertia::encryptHistory();
$view = $request->validate(['view' => 'nullable|in:agreements,calendar,imports,alternatives,reservations,deliveries,suggestions,history'])['view'] ?? 'agreements';
$view = $request->validate(['view' => 'nullable|in:contracts,agreements,calendar,imports,alternatives,reservations,deliveries,suggestions,history'])['view'] ?? 'agreements';
if ($view === 'contracts') {
abort_unless(app(AgreementOrderLimits::class)->ready(), 503);
}
if ($view === 'history') {
return $this->privateResponse($request, $this->history($request, $actor, $planning));
}
@@ -66,7 +70,7 @@ class SupplyPlanningController extends Controller
$capabilities = $import ? ['import_read', 'import_prepare', 'import_customs'] : ['supply_read', 'supply_prepare', 'supply_review'];
abort_unless(collect($capabilities)->contains(fn ($p) => $planning->allows($actor, $p)), 403);
$ready = Schema::hasTable('supply_records');
$kind = $import ? 'import' : ($view === 'calendar' ? 'policy' : 'agreement');
$kind = $import ? 'import' : ($view === 'calendar' ? 'policy' : ($view === 'contracts' ? 'contract' : 'agreement'));
$focus = $this->focusedRecord($request, $actor, $kind);
[$records, $page] = $this->recordPage($request, $planning, $ready, $kind, $focus);
$projections = [];
@@ -98,7 +102,15 @@ class SupplyPlanningController extends Controller
'agreement_form_key' => 'nullable|string|max:80',
]) : [];
$contractFilters = $request->validate(['contract_search' => 'nullable|string|max:100', 'selected_contract_key' => 'nullable|uuid']);
return $this->privateResponse($request, Inertia::render('supply/index', ['view' => $view, 'kind' => $kind, 'ready' => $ready,
'contractSearch' => $contractFilters['contract_search'] ?? '',
'contracts' => $ready && $prepare && $kind === 'agreement' && app(AgreementOrderLimits::class)->ready()
? $this->approvedOptions($planning, 'contract', $records->pluck('data.contract_key')->push($contractFilters['selected_contract_key'] ?? null), ['agreement_search' => $contractFilters['contract_search'] ?? ''])->map(fn ($r) => $r->only(['record_key', 'version', 'data', 'snapshot'])) : [],
'orderLimitsReady' => app(AgreementOrderLimits::class)->ready(),
'linkedAgreementKey' => $kind === 'policy' ? $request->query('linked_agreement_key') : null,
'linkedContractKey' => $kind === 'agreement' ? $request->query('linked_contract_key') : null,
'agreementSearch' => $agreementFilters['agreement_search'] ?? '', 'agreementFormKey' => $agreementFilters['agreement_form_key'] ?? null,
'recordPagination' => $this->pagination($page),
'focusRecordId' => $focus->id ?? null, 'focusChanged' => $focus !== null && $records->first()?->id !== $focus->id,
@@ -143,6 +155,18 @@ class SupplyPlanningController extends Controller
return [collect(), null];
}
$query = $planning->latest($kind)->latest('id');
if ($kind === 'agreement') {
$linked = $request->validate(['linked_contract_key' => 'nullable|uuid']);
if (! empty($linked['linked_contract_key'])) {
$query->where('data->contract_key', $linked['linked_contract_key']);
}
}
if ($kind === 'policy') {
$linked = $request->validate(['linked_agreement_key' => 'nullable|uuid']);
if (! empty($linked['linked_agreement_key'])) {
$query->where('data->agreement_key', $linked['linked_agreement_key']);
}
}
if ($focus !== null) {
return [$query->where('record_key', $focus->record_key)->get(), null];
}
@@ -98,7 +98,14 @@ class WarehouseRequestController extends Controller
$p = app(WarehouseFulfilment::class)->progress($record);
$s = $record->snapshot;
foreach ($s['lines'] as $index => $line) {
$row = ['RA-'.$record->id, $p['state'], (string) $p['version'], $s['requester']['name'], $s['warehouse']['code'], $s['cost_center']['code'], $s['destination'], $s['reason'], (string) ($index + 1), $line['item']['code'], $line['item']['name'], $line['item']['unit'], $line['destination'], $line['equipment']['code'] ?? '', ...array_map(fn ($quantity) => number_format($quantity / 1000, 3, '.', ''), [$line['quantity_milli'], $p['reserved'][$index], $p['delivered'][$index], $p['remaining'][$index], $p['cancelled'][$index]]), $p['reservation_ready'] ? 'Sim' : 'Não', url('/stock/requisicoes/'.$record->id)];
$usage = $line['destination'];
if (($line['use'] ?? null) === 'production') {
$usage .= ' · Insumos para produção';
if (($line['production']['reference'] ?? null) !== null && $line['production']['reference'] !== '') {
$usage .= ' · Referência declarada: '.$line['production']['reference'];
}
}
$row = ['RA-'.$record->id, $p['state'], (string) $p['version'], $s['requester']['name'], $s['warehouse']['code'], $s['cost_center']['code'], $s['destination'], $s['reason'], (string) ($index + 1), $line['item']['code'], $line['item']['name'], $line['item']['unit'], $usage, $line['equipment']['code'] ?? '', ...array_map(fn ($quantity) => number_format($quantity / 1000, 3, '.', ''), [$line['quantity_milli'], $p['reserved'][$index], $p['delivered'][$index], $p['remaining'][$index], $p['cancelled'][$index]]), $p['reservation_ready'] ? 'Sim' : 'Não', url('/stock/requisicoes/'.$record->id)];
fputcsv($out, array_map($safe, $row), ';', '"', '');
}
}
+2 -24
View File
@@ -3,8 +3,8 @@
namespace App\Http\Requests;
use App\Models\User;
use App\Services\RequisitionDraftInput;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class StoreRequisitionRequest extends FormRequest
{
@@ -21,29 +21,7 @@ class StoreRequisitionRequest extends FormRequest
$user = $this->user('web');
abort_unless($user instanceof User, 403);
return [
'operation_key' => 'nullable|uuid',
'process_version' => 'nullable|integer|min:1',
'cost_center_id' => ['required', 'integer', Rule::exists('cost_centers', 'id')->where('tenant_id', $user->tenant_id)->where('department_id', $user->department_id)],
'priority' => ['required', Rule::in(['normal', 'high', 'urgent'])],
'needed_by' => ['required', 'date_format:Y-m-d', 'after_or_equal:today'],
'justification' => ['required', 'string', 'min:10', 'max:5000'],
'items' => ['required', 'array', 'min:1', 'max:50'],
'items.*.catalogue_entry_id' => 'nullable|integer|min:1',
'items.*.catalogue_version' => 'nullable|required_with:items.*.catalogue_entry_id|integer|min:1',
'items.*.source_line_id' => 'nullable|integer|min:1',
'items.*.description' => ['required_without:items.*.catalogue_entry_id', 'string', 'max:255'],
'items.*.category' => ['required_without:items.*.catalogue_entry_id', 'string', 'max:100'],
'items.*.purchase_type' => ['required_without:items.*.catalogue_entry_id', Rule::in(['consumable', 'service', 'other', 'equipment', 'spare_part'])],
'items.*.equipment_id' => ['exclude_unless:items.*.purchase_type,spare_part', 'required', 'integer', Rule::exists('equipment', 'id')->where('tenant_id', $user->tenant_id)->where('department_id', $user->department_id)],
'items.*.spare_part_id' => ['exclude_unless:items.*.purchase_type,spare_part', 'required', 'integer', Rule::exists('spare_parts', 'id')->where('tenant_id', $user->tenant_id)],
'items.*.production_area' => 'exclude_unless:items.*.purchase_type,equipment|required|string|max:200',
'items.*.downtime_started_at' => 'exclude_unless:items.*.purchase_type,spare_part|nullable|date_format:Y-m-d\TH:i|before_or_equal:now',
'items.*.quantity' => ['required', 'numeric', 'min:0.001', 'max:1000000', 'regex:/^\d+(\.\d{1,3})?$/'],
'items.*.unit' => ['required_without:items.*.catalogue_entry_id', 'string', 'max:30'],
'items.*.unit_price' => ['required', 'numeric', 'min:0.01', 'max:100000000', 'regex:/^\d+(\.\d{1,2})?$/'],
'items.*.tax_rate' => ['required', 'numeric', 'between:0,100', 'regex:/^\d+(\.\d{1,2})?$/'],
];
return app(RequisitionDraftInput::class)->rules($user);
}
/** @return array<string, string> */