@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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), ';', '"', '');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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> */
|
||||
|
||||
@@ -21,9 +21,9 @@ use Tempo\Purchasing\Internal\InternalRequisitions;
|
||||
* @property int $requester_id
|
||||
* @property string $number
|
||||
* @property string $status
|
||||
* @property int $subtotal_minor
|
||||
* @property int $tax_minor
|
||||
* @property int $total_minor
|
||||
* @property int|null $subtotal_minor
|
||||
* @property int|null $tax_minor
|
||||
* @property int|null $total_minor
|
||||
* @property Carbon|null $submitted_at
|
||||
* @property Carbon|null $needed_by
|
||||
* @property array<string,mixed>|null $comparison_policy
|
||||
@@ -39,7 +39,7 @@ class Requisition extends Model
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['approval_snapshot' => 'array', 'comparison_policy' => 'array', 'submitted_at' => 'datetime', 'needed_by' => 'date:Y-m-d'];
|
||||
return ['draft_input' => 'array', 'approval_snapshot' => 'array', 'comparison_policy' => 'array', 'submitted_at' => 'datetime', 'needed_by' => 'date:Y-m-d'];
|
||||
}
|
||||
|
||||
/** @return HasMany<RequisitionItem, $this> */
|
||||
|
||||
@@ -6,6 +6,7 @@ use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* @property array{country:string,catalogue:string,record_id:string}|null $geography_reference
|
||||
* @property array<string,mixed>|null $company_details
|
||||
* @property int $id
|
||||
* @property string $name
|
||||
* @property int $first_limit_minor
|
||||
@@ -23,6 +24,6 @@ class Tenant extends Model
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['geography_reference' => 'array', 'work_context_policy' => 'array', 'approval_includes_tax' => 'boolean', 'rules_provisional' => 'boolean', 'default_tax_rate' => 'decimal:2', 'comparison_policy' => 'array', 'intelligence_policy' => 'array'];
|
||||
return ['company_details' => 'array', 'geography_reference' => 'array', 'work_context_policy' => 'array', 'approval_includes_tax' => 'boolean', 'rules_provisional' => 'boolean', 'default_tax_rate' => 'decimal:2', 'comparison_policy' => 'array', 'intelligence_policy' => 'array'];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\SupplyRecord;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/** Current approved versions only. Dates describe vigency, never renewal or purchase authority. */
|
||||
final class AgreementFollowup
|
||||
{
|
||||
public function authorize(User $actor): User
|
||||
{
|
||||
$current = User::query()->findOrFail($actor->id);
|
||||
abort_unless(auth()->id() === $current->id && $current->tenant_id !== null && $current->tenant_id === $actor->tenant_id, 403);
|
||||
$planning = app(SupplyPlanning::class);
|
||||
abort_unless(collect(['supply_read', 'supply_prepare', 'supply_review'])->contains(fn (string $permission) => $planning->allows($current, $permission)), 403);
|
||||
abort_unless(Schema::hasTable('supply_records'), 503, 'Instalação do fornecimento pendente.');
|
||||
|
||||
return $current;
|
||||
}
|
||||
|
||||
/** @return array{search:string,validity:string,expires_by:string} */
|
||||
public function filters(Request $request): array
|
||||
{
|
||||
$v = $request->validate(['search' => 'nullable|string|max:100', 'validity' => 'nullable|in:all,current,expired,future,unknown',
|
||||
'expires_by' => 'nullable|date_format:Y-m-d', 'page' => 'nullable|integer|min:1|max:1000000']);
|
||||
|
||||
return ['search' => trim($v['search'] ?? ''), 'validity' => $v['validity'] ?? 'all', 'expires_by' => $v['expires_by'] ?? ''];
|
||||
}
|
||||
|
||||
/** @param array{search:string,validity:string,expires_by:string} $filters
|
||||
* @return Builder<SupplyRecord>
|
||||
*/
|
||||
public function query(User $actor, array $filters, string $today, string $kind = 'agreement'): Builder
|
||||
{
|
||||
abort_unless(in_array($kind, ['agreement', 'contract'], true), 404);
|
||||
if ($kind === 'contract') {
|
||||
abort_unless(app(AgreementOrderLimits::class)->ready(), 503);
|
||||
}
|
||||
$query = app(SupplyPlanning::class)->latest($kind)->where('tenant_id', $actor->tenant_id)->where('state', 'approved');
|
||||
if ($filters['search'] !== '') {
|
||||
$query->where(fn (Builder $q) => $q->whereLike('data->reference', '%'.$filters['search'].'%')
|
||||
->orWhereLike('snapshot->supplier->name', '%'.$filters['search'].'%')->orWhereLike('snapshot->item->code', '%'.$filters['search'].'%')
|
||||
->orWhereLike('snapshot->item->name', '%'.$filters['search'].'%')->orWhereLike('snapshot->warehouse->name', '%'.$filters['search'].'%'));
|
||||
}
|
||||
if ($filters['validity'] === 'unknown') {
|
||||
$query->where(fn (Builder $q) => $q->whereNull('data->valid_from')->orWhereNull('data->valid_until')->orWhere('data->valid_from', '')->orWhere('data->valid_until', ''));
|
||||
} elseif ($filters['validity'] !== 'all') {
|
||||
$query->whereNotNull('data->valid_from')->where('data->valid_from', '!=', '')->whereNotNull('data->valid_until')->where('data->valid_until', '!=', '');
|
||||
match ($filters['validity']) {
|
||||
'current' => $query->where('data->valid_from', '<=', $today)->where('data->valid_until', '>=', $today),
|
||||
'expired' => $query->where('data->valid_until', '<', $today),
|
||||
'future' => $query->where('data->valid_from', '>', $today),
|
||||
default => throw new \InvalidArgumentException('Situação de vigência desconhecida.'),
|
||||
};
|
||||
}
|
||||
if ($filters['expires_by'] !== '') {
|
||||
$query->where('data->valid_until', '!=', '')->where('data->valid_until', '<=', $filters['expires_by']);
|
||||
}
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
/** @param Collection<int,SupplyRecord> $records
|
||||
* @return list<array<string,mixed>>
|
||||
*/
|
||||
public function rows(Collection $records, string $today): array
|
||||
{
|
||||
$counts = app(SupplyPlanning::class)->latest('policy')->where('state', 'approved')->whereIn('data->agreement_key', $records->pluck('record_key'))
|
||||
->select('data->agreement_key as agreement_key')->selectRaw('COUNT(*) as policy_count')->groupBy('data->agreement_key')->get()
|
||||
->mapWithKeys(fn (SupplyRecord $record) => [(string) $record->getAttribute('agreement_key') => (int) $record->getAttribute('policy_count')]);
|
||||
$articles = app(SupplyPlanning::class)->latest('agreement')->where('state', 'approved')->whereIn('data->contract_key', $records->where('kind', 'contract')->pluck('record_key'))
|
||||
->select('data->contract_key as contract_key')->selectRaw('COUNT(*) as article_count')->groupBy('data->contract_key')->get()
|
||||
->mapWithKeys(fn (SupplyRecord $record) => [(string) $record->getAttribute('contract_key') => (int) $record->getAttribute('article_count')]);
|
||||
|
||||
return array_values($records->map(function (SupplyRecord $record) use ($today, $counts, $articles) {
|
||||
$from = $this->date($record->data['valid_from'] ?? null);
|
||||
$until = $this->date($record->data['valid_until'] ?? null);
|
||||
$validity = $from === null || $until === null ? 'unknown' : ($until < $from ? 'unknown' : ($until < $today ? 'expired' : ($from > $today ? 'future' : 'current')));
|
||||
|
||||
return ['id' => $record->id, 'record_key' => $record->record_key, 'version' => $record->version, 'reference' => $record->data['reference'] ?? null,
|
||||
'supplier' => $record->snapshot['supplier']['name'] ?? null, 'item_code' => $record->snapshot['item']['code'] ?? null,
|
||||
'item' => $record->snapshot['item']['name'] ?? null, 'warehouse' => $record->snapshot['warehouse']['name'] ?? null,
|
||||
'valid_from' => $from, 'valid_until' => $until, 'validity' => $validity, 'approved_policies' => $counts->get($record->record_key, 0),
|
||||
'kind' => $record->kind, 'currency' => $record->data['currency'] ?? null, 'max_order_value_minor' => $record->data['max_order_value_minor'] ?? null,
|
||||
'periodicity_days' => $record->data['periodicity_days'] ?? null, 'approved_articles' => $articles->get($record->record_key, 0),
|
||||
'articles_href' => '/compras/fornecimento?view=agreements&linked_contract_key='.$record->record_key,
|
||||
'href' => '/compras/fornecimento?view='.($record->kind === 'contract' ? 'contracts' : 'agreements').'&record_id='.$record->id.'#supply-record-'.$record->id,
|
||||
'policies_href' => '/compras/fornecimento?view=calendar&linked_agreement_key='.$record->record_key];
|
||||
})->all());
|
||||
}
|
||||
|
||||
private function date(mixed $value): ?string
|
||||
{
|
||||
if (! is_string($value)) {
|
||||
return null;
|
||||
}
|
||||
$date = \DateTimeImmutable::createFromFormat('!Y-m-d', $value);
|
||||
|
||||
return $date !== false && $date->format('Y-m-d') === $value ? $value : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\PurchaseOrder;
|
||||
use App\Models\Quotation;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\StockItem;
|
||||
use App\Models\SupplyRecord;
|
||||
use App\Models\User;
|
||||
use Brick\Math\BigDecimal;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Tempo\Inventory\QuantityConversion;
|
||||
|
||||
/** Owner decision: each order has the full optional limit. No cumulative balance or financial writer. */
|
||||
final class AgreementOrderLimits
|
||||
{
|
||||
public function ready(): bool
|
||||
{
|
||||
$db = DB::connection();
|
||||
|
||||
return config('agreement_order_limits.qa_enabled') === true && app()->environment('testing')
|
||||
&& (($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|
||||
|| ($db->getDriverName() === 'pgsql' && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName()) === 1));
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function terms(array $input): array
|
||||
{
|
||||
foreach (['order_limit_amount', 'order_limit_quantity', 'max_order_value_minor', 'max_order_quantity_milli'] as $field) {
|
||||
if (isset($input[$field]) && is_string($input[$field]) && trim($input[$field]) === '') {
|
||||
$input[$field] = null;
|
||||
}
|
||||
}
|
||||
if (! array_intersect(['order_limit_amount', 'order_limit_quantity', 'max_order_value_minor', 'max_order_quantity_milli'], array_keys($input))) {
|
||||
return [];
|
||||
}
|
||||
abort_unless($this->ready(), 503, 'Limites por ordem preparados apenas em QA isolada.');
|
||||
Validator::make($input, ['order_limit_basis' => 'sometimes|in:per_order'])->validate();
|
||||
$result = ['order_limit_basis' => 'per_order'];
|
||||
foreach (['amount' => ['max_order_value_minor', 100, 2], 'quantity' => ['max_order_quantity_milli', 1000, 3]] as $name => [$key,$scale,$decimals]) {
|
||||
$field = 'order_limit_'.$name;
|
||||
if (array_key_exists($field, $input)) {
|
||||
$digits = $name === 'amount' ? 11 : 10;
|
||||
$v = Validator::make($input, [$field => ['nullable', 'string', 'regex:/^\d{1,'.$digits.'}(\.\d{1,'.$decimals.'})?$/D']])->validate();
|
||||
$result[$key] = ($v[$field] ?? null) === null ? null : BigDecimal::of($v[$field])->multipliedBy($scale)->toScale(0)->toInt();
|
||||
if ($result[$key] !== null && $result[$key] > 1000000000000) {
|
||||
throw ValidationException::withMessages([$field => 'O limite excede o intervalo decimal suportado.']);
|
||||
}
|
||||
} else {
|
||||
$v = Validator::make($input, [$key => 'nullable|integer|min:0|max:1000000000000'])->validate();
|
||||
$result[$key] = isset($v[$key]) ? (int) $v[$key] : null;
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function canRead(User $actor): bool
|
||||
{
|
||||
$planning = app(SupplyPlanning::class);
|
||||
|
||||
return collect(['supply_read', 'supply_prepare', 'supply_review'])->contains(fn (string $p) => $planning->allows($actor, $p));
|
||||
}
|
||||
|
||||
/** @param list<array<string,mixed>> $bindings
|
||||
* @return list<array<string,mixed>>
|
||||
*/
|
||||
private function canonical(array $bindings): array
|
||||
{
|
||||
$v = Validator::make(['agreement_bindings' => $bindings], [
|
||||
'agreement_bindings' => 'array|max:100', 'agreement_bindings.*' => 'array:requisition_item_id,agreement_id,conversion',
|
||||
'agreement_bindings.*.requisition_item_id' => 'required|integer|min:1|distinct',
|
||||
'agreement_bindings.*.agreement_id' => 'required|integer|min:1',
|
||||
'agreement_bindings.*.conversion' => 'sometimes|nullable|array:numerator,denominator,source,version',
|
||||
'agreement_bindings.*.conversion.numerator' => ['required_with:agreement_bindings.*.conversion', 'string', 'regex:/^[1-9]\d{0,8}$/D'],
|
||||
'agreement_bindings.*.conversion.denominator' => ['required_with:agreement_bindings.*.conversion', 'string', 'regex:/^[1-9]\d{0,8}$/D'],
|
||||
'agreement_bindings.*.conversion.source' => 'required_with:agreement_bindings.*.conversion|string|max:500',
|
||||
'agreement_bindings.*.conversion.version' => 'required_with:agreement_bindings.*.conversion|string|max:100',
|
||||
])->validate();
|
||||
$rows = [];
|
||||
foreach ($v['agreement_bindings'] as $row) {
|
||||
$entry = ['requisition_item_id' => (int) $row['requisition_item_id'], 'agreement_id' => (int) $row['agreement_id']];
|
||||
if (! empty($row['conversion'])) {
|
||||
$entry['conversion'] = ['numerator' => $row['conversion']['numerator'], 'denominator' => $row['conversion']['denominator'],
|
||||
'source' => trim($row['conversion']['source']), 'version' => trim($row['conversion']['version'])];
|
||||
}
|
||||
$rows[] = $entry;
|
||||
}
|
||||
usort($rows, fn ($a, $b) => $a['requisition_item_id'] <=> $b['requisition_item_id']);
|
||||
|
||||
return $rows;
|
||||
}
|
||||
|
||||
/** @param list<array<string,mixed>> $bindings */
|
||||
public function assertReplay(PurchaseOrder $order, array $bindings): void
|
||||
{
|
||||
if ($bindings === []) {
|
||||
return;
|
||||
} // Native callers may recover an existing order without proposing a new association.
|
||||
$hash = hash('sha256', json_encode($this->canonical($bindings), JSON_THROW_ON_ERROR));
|
||||
abort_unless(($order->snapshot['agreement_order_input_hash'] ?? null) === $hash, 409, 'A ordem já foi emitida com outra base; não associe acordos retroactivamente.');
|
||||
}
|
||||
|
||||
/** @param list<array<string,mixed>> $lines
|
||||
* @param list<array<string,mixed>> $bindings
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function freeze(User $actor, Quotation $quote, Requisition $request, array $lines, array $bindings): array
|
||||
{
|
||||
if ($bindings === []) {
|
||||
return [];
|
||||
}
|
||||
abort_unless($this->ready() && Schema::hasTable('supply_records'), 503, 'Limites por ordem preparados apenas em QA isolada.');
|
||||
abort_unless($this->canRead($actor), 403);
|
||||
$bindings = $this->canonical($bindings);
|
||||
$sources = $request->items()->get()->keyBy('id');
|
||||
$frozen = [];
|
||||
$groups = [];
|
||||
foreach ($bindings as $binding) {
|
||||
$line = collect($lines)->firstWhere('requisition_item_id', $binding['requisition_item_id']);
|
||||
$source = $sources->get($binding['requisition_item_id']);
|
||||
$agreement = app(SupplyPlanning::class)->latest('agreement')->where('tenant_id', $actor->tenant_id)->whereKey($binding['agreement_id'])->lockForUpdate()->first();
|
||||
$this->check($line !== null && $source !== null && $agreement !== null, 'Seleccione uma linha desta ordem e a versão actual do acordo da sua empresa.');
|
||||
$stock = StockItem::query()->whereKey($agreement->stock_item_id)->lockForUpdate()->first();
|
||||
$this->check($agreement->state === 'approved' && ($agreement->data['valid_from'] ?? '9999-12-31') <= today()->toDateString()
|
||||
&& ($agreement->data['valid_until'] ?? '0000-01-01') >= today()->toDateString(), 'O acordo deve estar aprovado e vigente na emissão.');
|
||||
$this->check($agreement->supplier_id === $quote->supplier_id && ($agreement->data['currency'] ?? null) === $quote->currency, 'Conserve o fornecedor e a moeda do acordo; não há conversão monetária implícita.');
|
||||
$this->check($stock !== null && ($source->catalogue_snapshot['stock_item_id'] ?? null) === $stock->id
|
||||
&& ($agreement->snapshot['item'] ?? null) === $stock->only(['id', 'code', 'name', 'unit']), 'A linha deve ter ligação documental ao artigo do acordo e cadastro actual. Não associe por nome.');
|
||||
$this->check(($agreement->snapshot['supplier'] ?? null) === $quote->supplier?->only(['id', 'name', 'version']), 'A referência do fornecedor no acordo mudou; reveja o acordo.');
|
||||
$quantity = (string) ReceiptWorkflow::milli((string) $line['quantity']);
|
||||
$conversion = $binding['conversion'] ?? null;
|
||||
if (mb_strtolower(trim($line['unit'])) !== mb_strtolower(trim($stock->unit))) {
|
||||
$this->check(is_array($conversion) && trim($conversion['source']) !== '' && trim($conversion['version']) !== '', 'Indique factor, fonte e versão para converter a quantidade à unidade do acordo.');
|
||||
$this->loadArithmetic();
|
||||
try {
|
||||
$quantity = QuantityConversion::toBase($quantity, $conversion['numerator'], $conversion['denominator']);
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
throw ValidationException::withMessages(['agreement_bindings' => $e->getMessage()]);
|
||||
}
|
||||
} else {
|
||||
$this->check($conversion === null, 'Unidades coincidentes não exigem um factor.');
|
||||
}
|
||||
$terms = $this->terms($agreement->data);
|
||||
$frozen[$source->id] = ['schema' => 'sgc.agreement.order_limit.v1', 'basis' => 'per_order', 'agreement_id' => $agreement->id,
|
||||
'record_key' => $agreement->record_key, 'version' => $agreement->version, 'reference' => $agreement->data['reference'], 'currency' => $quote->currency,
|
||||
'stock_item_id' => $stock->id, 'warehouse_id' => $agreement->warehouse_id, 'unit' => $stock->unit,
|
||||
'document_unit' => $line['unit'], 'document_quantity_milli' => (string) ReceiptWorkflow::milli((string) $line['quantity']),
|
||||
'description' => $line['description'],
|
||||
'agreement_quantity_milli' => $quantity, 'total_minor' => $line['total_minor'], 'includes_tax' => true,
|
||||
'max_order_value_minor' => $terms['max_order_value_minor'] ?? null, 'max_order_quantity_milli' => $terms['max_order_quantity_milli'] ?? null,
|
||||
...($conversion === null ? [] : ['conversion' => $conversion])];
|
||||
$groups[$agreement->id][] = $frozen[$source->id];
|
||||
}
|
||||
foreach ($groups as $rows) {
|
||||
$value = BigDecimal::zero();
|
||||
$quantity = BigDecimal::zero();
|
||||
foreach ($rows as $row) {
|
||||
$value = $value->plus($row['total_minor']);
|
||||
$quantity = $quantity->plus($row['agreement_quantity_milli']);
|
||||
}
|
||||
$first = $rows[0];
|
||||
$this->check($first['max_order_value_minor'] === null || $value->isLessThanOrEqualTo($first['max_order_value_minor']), 'O total com impostos das linhas ligadas excede o limite deste acordo por ordem.');
|
||||
$this->check($first['max_order_quantity_milli'] === null || $quantity->isLessThanOrEqualTo($first['max_order_quantity_milli']), 'A quantidade das linhas ligadas excede o limite deste acordo por ordem.');
|
||||
foreach ($frozen as &$row) {
|
||||
if ($row['agreement_id'] === $first['agreement_id']) {
|
||||
$row['checked_order_value_minor'] = $value->toInt();
|
||||
$row['checked_order_quantity_milli'] = (string) $quantity;
|
||||
}
|
||||
}
|
||||
unset($row);
|
||||
}
|
||||
|
||||
$contracts = [];
|
||||
foreach ($groups as $agreementId => $rows) {
|
||||
$agreement = app(SupplyPlanning::class)->latest('agreement')->where('tenant_id', $actor->tenant_id)->whereKey($agreementId)->firstOrFail();
|
||||
if (empty($agreement->data['contract_key'])) {
|
||||
continue;
|
||||
}
|
||||
$contract = $this->contract($agreement->data, $actor->tenant_id);
|
||||
$this->check(($contract->snapshot['supplier'] ?? null) === $quote->supplier?->only(['id', 'name', 'version']), 'O fornecedor mudou desde a preparação do contrato.');
|
||||
$terms = $this->terms($contract->data);
|
||||
$contracts[$contract->id] ??= ['id' => $contract->id, 'record_key' => $contract->record_key, 'version' => $contract->version,
|
||||
'reference' => $contract->data['reference'], 'currency' => $contract->data['currency'], 'basis' => 'per_order',
|
||||
'max_order_value_minor' => $terms['max_order_value_minor'] ?? null, 'checked_order_value_minor' => 0];
|
||||
foreach ($rows as $row) {
|
||||
$contracts[$contract->id]['checked_order_value_minor'] = BigDecimal::of($contracts[$contract->id]['checked_order_value_minor'])->plus($row['total_minor'])->toInt();
|
||||
}
|
||||
foreach ($frozen as &$row) {
|
||||
if ($row['agreement_id'] === $agreementId) {
|
||||
$row['contract_id'] = $contract->id;
|
||||
}
|
||||
}
|
||||
unset($row);
|
||||
}
|
||||
foreach ($contracts as $contract) {
|
||||
$this->check($contract['max_order_value_minor'] === null || $contract['checked_order_value_minor'] <= $contract['max_order_value_minor'], 'O total com impostos dos artigos ligados excede o limite global do contrato nesta ordem.');
|
||||
}
|
||||
foreach ($frozen as &$row) {
|
||||
if (isset($row['contract_id'])) {
|
||||
$row['contract'] = $contracts[$row['contract_id']];
|
||||
}
|
||||
}
|
||||
unset($row);
|
||||
|
||||
return ['agreement_order_input_hash' => hash('sha256', json_encode($bindings, JSON_THROW_ON_ERROR)), 'agreement_bindings' => $frozen];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $data */
|
||||
public function contract(array $data, int $tenantId): SupplyRecord
|
||||
{
|
||||
abort_unless($this->ready(), 503);
|
||||
$contract = app(SupplyPlanning::class)->latest('contract')->where('tenant_id', $tenantId)
|
||||
->where('record_key', $data['contract_key'])->lockForUpdate()->first();
|
||||
$this->check($contract !== null && $contract->state === 'approved', 'Seleccione um contrato aprovado e actual da sua empresa.');
|
||||
$this->check(! isset($data['contract_version']) || $data['contract_version'] === $contract->version, 'O contrato mudou; devolva e actualize a associação antes de aprovar.');
|
||||
$this->check($contract->supplier_id === (int) $data['supplier_id'] && $contract->data['currency'] === $data['currency'], 'O artigo deve conservar o fornecedor e a moeda do contrato.');
|
||||
$this->check($data['valid_from'] >= $contract->data['valid_from'] && $data['valid_until'] <= $contract->data['valid_until'], 'A vigência do artigo deve estar contida na vigência do contrato.');
|
||||
|
||||
return $contract;
|
||||
}
|
||||
|
||||
/** @param list<int|string> $selected
|
||||
* @return list<array<string,mixed>>
|
||||
*/
|
||||
public function options(User $actor, Requisition $request, ?Quotation $quote, string $search = '', array $selected = []): array
|
||||
{
|
||||
if (! $this->ready() || ! $this->canRead($actor) || $quote === null || ! Schema::hasTable('supply_records')) {
|
||||
return [];
|
||||
}
|
||||
$stockIds = $request->items()->get()->map(fn ($item) => $item->catalogue_snapshot['stock_item_id'] ?? null)->filter()->unique();
|
||||
$base = app(SupplyPlanning::class)->latest('agreement')->where('state', 'approved')->where('supplier_id', $quote->supplier_id)
|
||||
->whereIn('stock_item_id', $stockIds)->where('data->currency', $quote->currency)->where('data->valid_from', '<=', today()->toDateString())->where('data->valid_until', '>=', today()->toDateString());
|
||||
$recent = (clone $base)->when($search !== '', fn ($q) => $q->whereLike('data->reference', '%'.$search.'%'))->orderByDesc('id')->limit(100)->pluck('id');
|
||||
|
||||
return array_values($base->where(fn ($q) => $q->whereIn('id', $recent)->orWhereIn('id', $selected))->orderByDesc('id')->get()->map(fn ($record) => [
|
||||
'id' => $record->id, 'version' => $record->version, 'reference' => $record->data['reference'], 'stock_item_id' => $record->stock_item_id,
|
||||
'contract' => $record->snapshot['contract'] ?? null,
|
||||
'warehouse' => $record->snapshot['warehouse']['name'] ?? null, 'unit' => $record->snapshot['item']['unit'] ?? null, 'currency' => $record->data['currency'],
|
||||
'max_order_value_minor' => $record->data['max_order_value_minor'] ?? null, 'max_order_quantity_milli' => $record->data['max_order_quantity_milli'] ?? null,
|
||||
])->all());
|
||||
}
|
||||
|
||||
private function loadArithmetic(): void
|
||||
{
|
||||
$root = base_path('packages/inventory-write/development');
|
||||
$bytes = file_get_contents($root.'/manifest.json');
|
||||
if ($bytes === false || ! hash_equals('90cf565537e7fd48eb54a87bcfd6d585cf53239f075764910047838b3b8b4c38', hash('sha256', $bytes))) {
|
||||
throw new \LogicException('Artefacto aritmético incompatível.');
|
||||
}
|
||||
$manifest = json_decode($bytes, true, 512, JSON_THROW_ON_ERROR);
|
||||
$file = $root.'/src/QuantityConversion.php';
|
||||
$hash = hash_file('sha256', $file);
|
||||
if (! is_string($hash) || ! hash_equals($manifest['files']['src/QuantityConversion.php'], $hash)) {
|
||||
throw new \LogicException('Aritmética alterada.');
|
||||
}
|
||||
require_once $file;
|
||||
}
|
||||
|
||||
/** @phpstan-assert true $condition */
|
||||
private function check(bool $condition, string $message): void
|
||||
{
|
||||
if (! $condition) {
|
||||
throw ValidationException::withMessages(['agreement_bindings' => $message]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -248,7 +248,8 @@ class AutomaticPurchases
|
||||
foreach ($request->snapshot['lines'] as $index => $line) {
|
||||
if ($line['item']['id'] === $item && $p['remaining'][$index] > 0) {
|
||||
$unreserved += max(0, $p['remaining'][$index] - $p['reserved'][$index]);
|
||||
$origins[] = ['warehouse_request_id' => $request->id, 'version' => $p['version'], 'line_index' => $index, 'destination' => $line['destination'], 'equipment' => $line['equipment'], 'remaining_milli' => $p['remaining'][$index], 'reserved_milli' => $p['reserved'][$index]];
|
||||
$origins[] = ['warehouse_request_id' => $request->id, 'version' => $p['version'], 'line_index' => $index, 'destination' => $line['destination'], 'equipment' => $line['equipment'], 'remaining_milli' => $p['remaining'][$index], 'reserved_milli' => $p['reserved'][$index],
|
||||
...(isset($line['production']) ? ['production' => $line['production']] : [])];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
class CompanyDetails
|
||||
{
|
||||
public const FIELDS = [
|
||||
'legal_name' => 'Denominação social', 'nuel' => 'NUEL', 'address' => 'Endereço',
|
||||
'nuit' => 'NUIT', 'phone' => 'Telefone', 'email' => 'Email', 'legal_representative' => 'Representante legal',
|
||||
];
|
||||
|
||||
public const BANK_FIELDS = [
|
||||
'bank' => 'Banco', 'branch' => 'Balcão', 'account_number' => 'Número de conta',
|
||||
'currency' => 'Moeda', 'nib' => 'NIB', 'iban' => 'IBAN', 'nuib' => 'NUIB', 'account_holder' => 'Titular da conta',
|
||||
];
|
||||
|
||||
public const LOCATION_FIELDS = ['name' => 'Designação', 'address' => 'Endereço', 'phone' => 'Telefone', 'email' => 'Email'];
|
||||
|
||||
/** @return array<string,string> */
|
||||
public function rules(): array
|
||||
{
|
||||
$rules = ['reason' => 'required|string|min:10|max:4000'];
|
||||
foreach (self::FIELDS as $field => $label) {
|
||||
$rules[$field] = 'present|nullable|string|max:255';
|
||||
}
|
||||
$rules['address'] = 'present|nullable|string|max:1000';
|
||||
$rules['email'] = 'present|nullable|email|max:255';
|
||||
$rules['nuit'] = 'present|nullable|regex:/^\d{9}$/D';
|
||||
$rules['bank_accounts'] = 'present|array';
|
||||
$rules['establishments'] = 'present|array';
|
||||
foreach (['bank_accounts' => self::BANK_FIELDS, 'establishments' => self::LOCATION_FIELDS] as $collection => $fields) {
|
||||
$extra = $collection === 'establishments' ? ',kind' : '';
|
||||
$rules[$collection.'.*'] = 'array:id,'.implode(',', array_keys($fields)).$extra;
|
||||
$rules[$collection.'.*.id'] = 'required|uuid|distinct';
|
||||
foreach ($fields as $field => $label) {
|
||||
$rules[$collection.'.*.'.$field] = 'present|nullable|string|max:'.($field === 'address' ? '1000' : '255');
|
||||
}
|
||||
}
|
||||
$rules['bank_accounts.*.currency'] = 'present|nullable|regex:/^[A-Z]{3}$/D';
|
||||
$rules['establishments.*.email'] = 'present|nullable|email|max:255';
|
||||
$rules['establishments.*.name'] = 'required|string|max:255';
|
||||
$rules['establishments.*.kind'] = 'required|in:headquarters,branch';
|
||||
|
||||
return $rules;
|
||||
}
|
||||
}
|
||||
@@ -103,6 +103,9 @@ final class InternalRequisitionPort implements RequisitionPort
|
||||
public function policy(array $record): array
|
||||
{
|
||||
$r = $this->model($record['id']);
|
||||
if ($r->getAttribute('draft_input') !== null || $r->getAttribute('cost_center_id') === null || $r->needed_by === null || $r->subtotal_minor === null || $r->total_minor === null) {
|
||||
throw ValidationException::withMessages(['submission' => 'Complete os campos e as linhas do rascunho antes de submeter. Não foram criadas aprovações ou reservas.']);
|
||||
}
|
||||
if ($this->actor->department_id !== $r->department_id) {
|
||||
throw ValidationException::withMessages(['submission' => 'O departamento do solicitante mudou. Reveja o rascunho e o centro de custo antes de submeter.']);
|
||||
}
|
||||
|
||||
@@ -48,7 +48,16 @@ class OrganizationConfiguration
|
||||
throw ValidationException::withMessages(['version' => 'A parametrização foi alterada. Actualize e compare antes de guardar.']);
|
||||
}
|
||||
$before = null;
|
||||
if ($command === 'profile') {
|
||||
if ($command === 'company_details') {
|
||||
abort_unless(Schema::hasColumn('tenants', 'company_details'), 503, 'Instalação dos dados da empresa pendente.');
|
||||
if (count(array_filter($data['establishments'], fn (array $row) => $row['kind'] === 'headquarters')) > 1) {
|
||||
throw ValidationException::withMessages(['establishments' => 'Identifique apenas um estabelecimento como sede.']);
|
||||
}
|
||||
$company = Tenant::query()->findOrFail($actor->tenant_id);
|
||||
$before = $company->only(['company_details']);
|
||||
$company->update(['company_details' => array_intersect_key($data, CompanyDetails::FIELDS + ['bank_accounts' => true, 'establishments' => true])]);
|
||||
$after = [...$company->only(['company_details']), 'reason' => $data['reason']];
|
||||
} elseif ($command === 'profile') {
|
||||
$profile = isset($data['id']) ? DB::table('organization_profiles')->where('tenant_id', $actor->tenant_id)->where('id', $data['id'])->first() : null;
|
||||
abort_if(isset($data['id']) && ! $profile, 404);
|
||||
if ($profile && in_array('admin', $data['permissions'], true) && DB::table('organization_memberships')->where('tenant_id', $actor->tenant_id)->where('profile_id', $profile->id)->where('maintenance', true)->exists()) {
|
||||
|
||||
@@ -20,7 +20,8 @@ class ProcurementOperationalInsights
|
||||
$today = $instant->setTimezone(config('app.timezone'))->startOfDay();
|
||||
$total = $pending = $missingSubmission = $neededPast = $approved = $withoutQuotes = $withoutOrder = 0;
|
||||
$oldest = [];
|
||||
foreach ((clone $query)->reorder()->lazyById(200) as $record) {
|
||||
$approvalTimes = ['measured' => 0, 'unknown' => 0, 'total_seconds' => 0, 'min_seconds' => null, 'max_seconds' => null];
|
||||
foreach ((clone $query)->with('steps:id,requisition_id,decision,decided_at')->reorder()->lazyById(200) as $record) {
|
||||
$total++;
|
||||
if (in_array($record->status, ['draft', 'pending'], true) && $record->needed_by !== null && $record->needed_by->toDateString() < $today->toDateString()) {
|
||||
$neededPast++;
|
||||
@@ -43,6 +44,19 @@ class ProcurementOperationalInsights
|
||||
}
|
||||
if ($record->status === 'approved') {
|
||||
$approved++;
|
||||
$steps = $record->steps;
|
||||
$valid = $record->submitted_at !== null && $steps->isNotEmpty() && $steps->every(fn ($step) => $step->decision === 'approved' && $step->decided_at !== null);
|
||||
$dates = $valid ? $steps->map(fn ($step) => CarbonImmutable::parse($step->decided_at, config('app.timezone'))) : collect();
|
||||
$end = $dates->max();
|
||||
if (! $valid || $end === null || $end < $record->submitted_at || $end > $instant || $dates->contains(fn ($date) => $date < $record->submitted_at)) {
|
||||
$approvalTimes['unknown']++;
|
||||
} else {
|
||||
$seconds = $end->getTimestamp() - $record->submitted_at->getTimestamp();
|
||||
$approvalTimes['measured']++;
|
||||
$approvalTimes['total_seconds'] += $seconds;
|
||||
$approvalTimes['min_seconds'] = $approvalTimes['min_seconds'] === null ? $seconds : min($approvalTimes['min_seconds'], $seconds);
|
||||
$approvalTimes['max_seconds'] = $approvalTimes['max_seconds'] === null ? $seconds : max($approvalTimes['max_seconds'], $seconds);
|
||||
}
|
||||
$withoutQuotes += (int) $record->getAttribute('quotations_count') === 0 ? 1 : 0;
|
||||
$withoutOrder += $record->getAttribute('order_number') === null ? 1 : 0;
|
||||
}
|
||||
@@ -51,6 +65,7 @@ class ProcurementOperationalInsights
|
||||
return ['method' => 'procurement_facts_v1', 'generated_at' => $instant->toIso8601String(), 'processes' => $total,
|
||||
'pending' => ['count' => $pending, 'unknown_submission_age' => $missingSubmission, 'oldest' => $oldest],
|
||||
'unapproved_past_needed_date' => $neededPast,
|
||||
'approval_times' => $approvalTimes,
|
||||
'approved' => ['count' => $approved, 'without_registered_quotes' => $withoutQuotes, 'without_visible_order' => $withoutOrder]];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -102,6 +102,42 @@ class ProcurementReviewCsv
|
||||
}
|
||||
}
|
||||
$fulfilment = $report['fulfilment'];
|
||||
$limits = $report['agreement_limits'] ?? [];
|
||||
if (! is_array($limits)) {
|
||||
throw new \UnexpectedValueException('A projecção de acordos deve ser uma lista ou mapa de bases preservadas.');
|
||||
}
|
||||
$seen = [];
|
||||
$seenContracts = [];
|
||||
foreach ($limits as $binding) {
|
||||
if (! is_array($binding) || ! isset($binding['agreement_id']) || ! is_int($binding['agreement_id']) || $binding['agreement_id'] < 1) {
|
||||
throw new \UnexpectedValueException('Base contratual sem identidade válida.');
|
||||
}
|
||||
if (isset($seen[$binding['agreement_id']])) {
|
||||
continue;
|
||||
}
|
||||
$seen[$binding['agreement_id']] = true;
|
||||
if (isset($binding['contract']) && is_array($binding['contract'])) {
|
||||
$contract = $binding['contract'];
|
||||
if (! isset($contract['id']) || ! is_int($contract['id']) || $contract['id'] < 1) {
|
||||
throw new \UnexpectedValueException('Contrato global sem identidade válida.');
|
||||
}
|
||||
if (! isset($seenContracts[$contract['id']])) {
|
||||
$seenContracts[$contract['id']] = true;
|
||||
$fields('Contrato global por ordem', (string) $contract['id'], [...$contract, 'max_order_value_minor' => $contract['max_order_value_minor'] ?? 'Não definido'], [
|
||||
'record_key' => 'Identidade do contrato', 'reference' => 'Referência', 'version' => 'Versão preservada', 'currency' => 'Moeda',
|
||||
'max_order_value_minor' => 'Limite global por ordem (centavos)', 'checked_order_value_minor' => 'Total conferido nesta ordem (centavos)',
|
||||
]);
|
||||
}
|
||||
}
|
||||
$fields('Acordo por ordem', (string) $binding['agreement_id'], [...$binding,
|
||||
'basis' => 'Por ordem', 'max_order_value_minor' => $binding['max_order_value_minor'] ?? 'Não definido',
|
||||
'max_order_quantity_milli' => $binding['max_order_quantity_milli'] ?? 'Não definido'], [
|
||||
'record_key' => 'Identidade do acordo', 'version' => 'Versão preservada', 'reference' => 'Referência', 'basis' => 'Aplicação do limite',
|
||||
'currency' => 'Moeda', 'unit' => 'Unidade contratual', 'includes_tax' => 'Inclui impostos',
|
||||
'max_order_value_minor' => 'Limite por ordem (centavos)', 'max_order_quantity_milli' => 'Limite por ordem (milésimos)',
|
||||
'checked_order_value_minor' => 'Total conferido nesta ordem (centavos)', 'checked_order_quantity_milli' => 'Quantidade conferida nesta ordem (milésimos)',
|
||||
]);
|
||||
}
|
||||
$write(['Recepções', '', 'Registos disponíveis', count($fulfilment['receipts'])]);
|
||||
foreach ($fulfilment['receipts'] as $receipt) {
|
||||
$fields('Recepção', (string) $receipt['id'], $receipt, ['received_on' => 'Recebida em', 'delivery_note' => 'Guia']);
|
||||
|
||||
@@ -83,6 +83,7 @@ class ProcurementReviewReport
|
||||
'opening' => $opening ? [...$opening->only(['id', 'revision', 'reference']), 'source_changed' => $opening->basis_hash !== $basis] : null,
|
||||
'award' => $award?->only(['id', 'status', 'total_minor']),
|
||||
'order' => $order?->only(['id', 'number', 'currency', 'total_minor']),
|
||||
'agreement_limits' => $order?->snapshot['agreement_bindings'] ?? [],
|
||||
'fulfilment' => [
|
||||
'receipts' => $receipts, 'finance_visible' => $financeVisible,
|
||||
'invoices' => $financeVisible ? $invoices->map(fn (Invoice $invoice) => ['id' => $invoice->id, 'number' => $invoice->number, 'status' => $invoice->status, 'issued_on' => $invoice->issued_on, 'total_minor' => (string) $invoice->total_minor, 'currency' => $invoice->snapshot['currency'] ?? null])->all() : null,
|
||||
|
||||
@@ -112,9 +112,10 @@ class PurchaseWorkflow
|
||||
});
|
||||
}
|
||||
|
||||
public function issue(User $user, PurchaseAward $award): PurchaseOrder
|
||||
/** @param list<array<string,mixed>> $agreementBindings */
|
||||
public function issue(User $user, PurchaseAward $award, array $agreementBindings = []): PurchaseOrder
|
||||
{
|
||||
return DB::transaction(function () use ($user, $award) {
|
||||
return DB::transaction(function () use ($user, $award, $agreementBindings) {
|
||||
$this->guard->lockCompany($user);
|
||||
$user = app(CurrentActor::class)->lock($user, [PurchasingRole::Procurement]);
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($user), 403);
|
||||
@@ -125,6 +126,7 @@ class PurchaseWorkflow
|
||||
$existing = PurchaseOrder::query()->where('requisition_id', $requisition->id)->first();
|
||||
if ($existing) {
|
||||
app(OrderCancellationWorkflow::class)->assertOperational($existing);
|
||||
app(AgreementOrderLimits::class)->assertReplay($existing, $agreementBindings);
|
||||
|
||||
return $existing;
|
||||
}
|
||||
@@ -163,6 +165,7 @@ class PurchaseWorkflow
|
||||
}
|
||||
}
|
||||
$snapshot = [
|
||||
...app(AgreementOrderLimits::class)->freeze($user, $quote, $requisition, $lines, $agreementBindings),
|
||||
...($quote->exchange_basis === null ? [] : ['exchange_basis' => $quote->exchange_basis, 'reference_amounts' => app(QuotationExchange::class)->amounts($quote)]),
|
||||
...($catalogueSources === [] ? [] : ['catalogue_sources' => $catalogueSources]),
|
||||
'development_only' => true, 'budget_checked' => false,
|
||||
|
||||
@@ -89,6 +89,21 @@ class ReceiptWorkflow
|
||||
$supplyMappings = Schema::hasTable('supply_records')
|
||||
? app(SupplyPlanning::class)->latest('delivery')->where('purchase_order_id', $order->id)->get() : collect();
|
||||
foreach ($requested as $line) {
|
||||
// Snapshot keys identify requisition lines; resolve the order-line identity explicitly.
|
||||
$boundOrderLine = empty($order->snapshot['agreement_bindings']) ? null : $order->items()->whereKey($line['purchase_order_item_id'])->first();
|
||||
$orderBinding = $boundOrderLine === null ? null : ($order->snapshot['agreement_bindings'][$boundOrderLine->requisition_item_id] ?? null);
|
||||
if ($orderBinding !== null) {
|
||||
if ((int) ($data['warehouse_id'] ?? 0) !== (int) $orderBinding['warehouse_id'] || (! empty($line['stock_item_id']) && (int) $line['stock_item_id'] !== (int) $orderBinding['stock_item_id'])) {
|
||||
throw ValidationException::withMessages(['items' => 'Conserve o artigo e armazém do acordo preservado na ordem.']);
|
||||
}
|
||||
$line['stock_item_id'] = $orderBinding['stock_item_id'];
|
||||
if (isset($orderBinding['conversion'])) {
|
||||
if (isset($line['conversion']) && $line['conversion'] !== $orderBinding['conversion']) {
|
||||
throw ValidationException::withMessages(['items' => 'Conserve a conversão preservada na ordem.']);
|
||||
}
|
||||
$line['conversion'] = $orderBinding['conversion'];
|
||||
}
|
||||
}
|
||||
$mapping = $supplyMappings->first(fn ($record) => $record->data['purchase_order_item_id'] == $line['purchase_order_item_id']);
|
||||
if ($mapping !== null) {
|
||||
if ((! empty($line['stock_item_id']) && (int) $line['stock_item_id'] !== $mapping->stock_item_id) || (int) ($data['warehouse_id'] ?? 0) !== $mapping->warehouse_id) {
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class RequisitionDraftInput
|
||||
{
|
||||
public function available(): bool
|
||||
{
|
||||
return Schema::hasColumn('requisitions', 'draft_input');
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function completeRules(User $user): array
|
||||
{
|
||||
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 array<string,mixed> */
|
||||
public function rules(User $user): array
|
||||
{
|
||||
$rules = $this->completeRules($user);
|
||||
if (! $this->available()) {
|
||||
return $rules;
|
||||
}
|
||||
foreach ($rules as $key => $list) {
|
||||
$list = is_array($list) ? $list : explode('|', $list);
|
||||
$rules[$key] = array_values(array_filter($list, fn ($rule) => ! is_string($rule) || (! str_starts_with($rule, 'required') && $rule !== 'after_or_equal:today' && ! ($key === 'justification' && $rule === 'min:10'))));
|
||||
if (! in_array('nullable', $rules[$key], true)) {
|
||||
$rules[$key][] = 'nullable';
|
||||
}
|
||||
}
|
||||
$rules['items'] = ['present', 'array', 'max:50'];
|
||||
|
||||
return $rules;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $data */
|
||||
public function complete(User $user, array $data): bool
|
||||
{
|
||||
return Validator::make($data, $this->completeRules($user))->passes();
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $data
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function preparation(User $user, array $data): array
|
||||
{
|
||||
$keys = [];
|
||||
foreach (array_keys($this->completeRules($user)) as $key) {
|
||||
if (str_starts_with($key, 'items.*.')) {
|
||||
$keys[substr($key, 8)] = true;
|
||||
}
|
||||
}
|
||||
$values = array_intersect_key($data, array_flip(['cost_center_id', 'priority', 'needed_by', 'justification', 'items']));
|
||||
$values['items'] = array_map(fn (array $line) => array_intersect_key($line, $keys), $data['items']);
|
||||
|
||||
return $values;
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Tempo\Purchasing\Internal\InternalRequisitions;
|
||||
use Tempo\Purchasing\Internal\RequisitionFailure;
|
||||
@@ -64,7 +65,10 @@ class RequisitionWorkflow
|
||||
} else {
|
||||
abort_unless(app(OrganizationAccess::class)->canRequest($user), 403);
|
||||
}
|
||||
if (! $user->department_id || ! CostCenter::query()->whereKey($data['cost_center_id'])->where('department_id', $user->department_id)->exists()) {
|
||||
$drafts = app(RequisitionDraftInput::class);
|
||||
$data = Validator::make($data, $drafts->rules($user))->validate();
|
||||
$incomplete = $drafts->available() && ! $drafts->complete($user, $data);
|
||||
if (! $user->department_id || ((! $incomplete || ! empty($data['cost_center_id'])) && ! CostCenter::query()->whereKey($data['cost_center_id'] ?? null)->where('department_id', $user->department_id)->exists())) {
|
||||
throw ValidationException::withMessages(['cost_center_id' => 'O departamento ou centro de custo mudou. Actualize o pedido antes de guardar.']);
|
||||
}
|
||||
$requisition = $existing ? Requisition::query()->lockForUpdate()->findOrFail($existing->id) : new Requisition;
|
||||
@@ -73,6 +77,24 @@ class RequisitionWorkflow
|
||||
app(ConflictGuard::class)->assertParticipation($user, $requisition);
|
||||
}
|
||||
$before = $existing ? $requisition->load('items')->toArray() : null;
|
||||
if ($incomplete) {
|
||||
$requisition->fill([
|
||||
'tenant_id' => $user->tenant_id, 'requester_id' => $user->id, 'department_id' => $user->department_id,
|
||||
'cost_center_id' => $data['cost_center_id'] ?? null, 'priority' => $data['priority'] ?? 'normal',
|
||||
'needed_by' => $data['needed_by'] ?? null, 'justification' => $data['justification'] ?? null,
|
||||
'subtotal_minor' => null, 'tax_minor' => null, 'total_minor' => null,
|
||||
'draft_input' => ['incomplete' => true, 'values' => $drafts->preparation($user, $data)],
|
||||
...($existing ? [] : ['comparison_policy' => app(ComparisonPolicy::class)->company(Tenant::query()->findOrFail($user->tenant_id))]),
|
||||
...(Schema::hasColumn('requisitions', 'process_version') ? ['process_version' => $existing ? (int) $requisition->getAttribute('process_version') + 1 : 1] : []),
|
||||
])->save();
|
||||
if (! $existing) {
|
||||
$requisition->update(['number' => sprintf('REQ-%s-%06d', now()->format('Y'), $requisition->id)]);
|
||||
}
|
||||
// Earlier complete lines remain for catalogue identity, never for approval or totals.
|
||||
$this->audit($executor, $existing ? 'requisition.updated' : 'requisition.created', $requisition, $before, $requisition->fresh()->toArray());
|
||||
|
||||
return $requisition;
|
||||
}
|
||||
$items = [];
|
||||
$subtotal = 0;
|
||||
$tax = 0;
|
||||
@@ -106,6 +128,7 @@ class RequisitionWorkflow
|
||||
'cost_center_id' => $data['cost_center_id'], 'priority' => $data['priority'],
|
||||
'needed_by' => $data['needed_by'], 'justification' => $data['justification'],
|
||||
'subtotal_minor' => $subtotal, 'tax_minor' => $tax, 'total_minor' => $subtotal + $tax,
|
||||
...($drafts->available() ? ['draft_input' => null] : []),
|
||||
...($existing ? [] : ['comparison_policy' => app(ComparisonPolicy::class)->company(Tenant::query()->findOrFail($user->tenant_id))]),
|
||||
...(Schema::hasColumn('requisitions', 'process_version') ? ['process_version' => $existing ? (int) $requisition->getAttribute('process_version') + 1 : 1] : []),
|
||||
])->save();
|
||||
|
||||
@@ -34,7 +34,7 @@ class SupplyPlanning
|
||||
/** Eligibility to confer, not a promise that changed sources permit approval. */
|
||||
public function canReview(User $actor, SupplyRecord $record, string $action = 'approve'): bool
|
||||
{
|
||||
if (! in_array($record->kind, ['agreement', 'policy'], true) || ! in_array($action, ['approve', 'return', 'suspend'], true)
|
||||
if (! in_array($record->kind, ['agreement', 'contract', 'policy'], true) || ($record->kind === 'contract' && ! app(AgreementOrderLimits::class)->ready()) || ! in_array($action, ['approve', 'return', 'suspend'], true)
|
||||
|| ! $this->independentReviewer($actor, $record)) {
|
||||
return false;
|
||||
}
|
||||
@@ -69,6 +69,12 @@ class SupplyPlanning
|
||||
&& $agreement->stock_item_id === $policy->stock_item_id && $agreement->warehouse_id === $policy->warehouse_id
|
||||
&& $agreement->data['valid_from'] <= $date && $agreement->data['valid_until'] >= $date && $supplier !== null && $supplier->eligible()
|
||||
&& $supplier->only(['id', 'name', 'version']) === $agreement->snapshot['supplier'];
|
||||
if ($valid && ! empty($agreement->data['contract_key'])) {
|
||||
$header = $this->latest('contract')->where('record_key', $agreement->data['contract_key'])->first();
|
||||
$valid = $header !== null && $header->state === 'approved' && $header->version === ($agreement->data['contract_version'] ?? null)
|
||||
&& $header->supplier_id === $agreement->supplier_id && $header->data['currency'] === $agreement->data['currency']
|
||||
&& $header->data['valid_from'] <= $date && $header->data['valid_until'] >= $date;
|
||||
}
|
||||
if (! $valid) {
|
||||
$projection = [...$projection, 'lead_time_available' => false, 'lead_time_issue' => 'O acordo, fornecedor ou validação documental deixou de sustentar o prazo aprovado. Reconfirme o fornecimento; as datas de pedir/encomendar ficam por determinar.',
|
||||
'request_date' => null, 'order_date' => null, 'reorder_point_milli' => null];
|
||||
@@ -90,7 +96,10 @@ class SupplyPlanning
|
||||
if (in_array($kind, ['reservation', 'delivery', 'alternative'], true)) {
|
||||
return app(SupplyCoordination::class)->save($actor, $kind, $input);
|
||||
}
|
||||
abort_unless(in_array($kind, ['policy', 'agreement', 'import'], true), 404);
|
||||
abort_unless(in_array($kind, ['policy', 'agreement', 'contract', 'import'], true), 404);
|
||||
if ($kind === 'contract') {
|
||||
abort_unless(app(AgreementOrderLimits::class)->ready(), 503, 'Contratos multiartigo preparados apenas em QA isolada.');
|
||||
}
|
||||
abort_unless(Schema::hasTable('supply_records'), 503, 'Instalação do fornecimento pendente.');
|
||||
|
||||
return DB::transaction(function () use ($actor, $kind, $input) {
|
||||
@@ -124,6 +133,9 @@ class SupplyPlanning
|
||||
$agreement = $this->latest('agreement')->where('record_key', $data['agreement_key'])->firstOrFail();
|
||||
$this->check($agreement->state === 'approved' && $agreement->stock_item_id === (int) $data['stock_item_id'] && $agreement->warehouse_id === (int) $data['warehouse_id'], 'data.agreement_key', 'Seleccione um acordo aprovado deste artigo/local.');
|
||||
$this->check($agreement->data['lead_days'] !== null && $agreement->data['valid_from'] <= today()->toDateString() && $agreement->data['valid_until'] >= today()->toDateString(), 'data.agreement_key', 'O acordo deve estar vigente e ter prazo conhecido.');
|
||||
if (! empty($agreement->data['contract_key'])) {
|
||||
app(AgreementOrderLimits::class)->contract($agreement->data, $actor->tenant_id);
|
||||
}
|
||||
$data['lead_days'] = $agreement->data['lead_days'];
|
||||
$data['origin'] = $agreement->data['origin'];
|
||||
$data['agreement_version'] = $agreement->version;
|
||||
@@ -131,6 +143,9 @@ class SupplyPlanning
|
||||
} else {
|
||||
$this->check($old !== null, 'action', 'Guarde primeiro a preparação.');
|
||||
$data = $old->data;
|
||||
if (in_array($kind, ['agreement', 'contract'], true)) {
|
||||
app(AgreementOrderLimits::class)->terms($data);
|
||||
}
|
||||
if ($kind !== 'import') {
|
||||
$this->check(in_array($action, ['approve', 'return', 'suspend'], true), 'action', 'Acção incompatível com este registo.');
|
||||
$this->check($this->independentReviewer($actor, $old), 'action', 'A conferência exige uma pessoa que não tenha preparado esta versão ou as anteriores.');
|
||||
@@ -156,11 +171,15 @@ class SupplyPlanning
|
||||
if ($order !== null) {
|
||||
app(OrderCancellationWorkflow::class)->assertOperational($order);
|
||||
}
|
||||
if ($kind === 'agreement' && $state === 'approved') {
|
||||
if (in_array($kind, ['agreement', 'contract'], true) && $state === 'approved') {
|
||||
$this->check($supplier !== null && $supplier->eligible(), 'supplier_id', 'O fornecedor deve estar activo e com revisão documental vigente.');
|
||||
$this->check(! app(ConflictGuard::class)->hasConflict($actor->id, $supplier->id, null), 'supplier_id', 'Existe conflito declarado com este fornecedor.');
|
||||
$this->check(($old->snapshot['supplier'] ?? null) === $supplier->only(['id', 'name', 'version']), 'supplier_id', 'O fornecedor mudou desde a preparação. Devolva e actualize a versão.');
|
||||
}
|
||||
if ($kind === 'agreement' && ! empty($data['contract_key']) && in_array($action, ['save', 'approve'], true)) {
|
||||
$contract = app(AgreementOrderLimits::class)->contract($data, $actor->tenant_id);
|
||||
$data['contract_version'] = $contract->version;
|
||||
}
|
||||
if ($kind === 'policy' && $state === 'approved') {
|
||||
if (($data['forecast_method'] ?? 'manual') === 'historical') {
|
||||
$history = app(SupplyHistory::class)->reference($data);
|
||||
@@ -169,6 +188,9 @@ class SupplyPlanning
|
||||
if (! empty($data['agreement_key'])) {
|
||||
$agreement = $this->latest('agreement')->where('record_key', $data['agreement_key'])->firstOrFail();
|
||||
$this->check($agreement->state === 'approved' && $agreement->version === $data['agreement_version'], 'action', 'O acordo mudou desde a preparação. Devolva e seleccione a versão actual.');
|
||||
if (! empty($agreement->data['contract_key'])) {
|
||||
app(AgreementOrderLimits::class)->contract($agreement->data, $actor->tenant_id);
|
||||
}
|
||||
}
|
||||
$clash = $this->latest('policy')->where('state', 'approved')->where('stock_item_id', $item->id)->where('warehouse_id', $warehouse->id)->where('record_key', '!=', $old->record_key)->exists();
|
||||
$this->check(! $clash, 'action', 'Suspenda a política anterior deste artigo/local antes de aprovar a substituição.');
|
||||
@@ -184,6 +206,11 @@ class SupplyPlanning
|
||||
}
|
||||
$snapshot = $action === 'save' ? ['prepared_by' => $actor->id, 'contributors' => array_values(array_unique([...($old?->snapshot['contributors'] ?? []), $actor->id])), 'item' => $item?->only(['id', 'code', 'name', 'unit']), 'warehouse' => $warehouse?->only(['id', 'code', 'name']),
|
||||
'supplier' => $supplier?->only(['id', 'name', 'version']), 'order' => $order?->only(['id', 'number', 'currency', 'supplier_id', 'total_minor'])] : $old->snapshot;
|
||||
if ($action === 'save' && $kind === 'agreement' && ! empty($data['contract_key'])) {
|
||||
$header = app(AgreementOrderLimits::class)->contract($data, $actor->tenant_id);
|
||||
$snapshot['contract'] = ['id' => $header->id, 'record_key' => $header->record_key, 'version' => $header->version, 'reference' => $header->data['reference'],
|
||||
'currency' => $header->data['currency'], 'max_order_value_minor' => $header->data['max_order_value_minor'] ?? null];
|
||||
}
|
||||
if ($state === 'approved') {
|
||||
$this->check($snapshot['item'] === $item?->only(['id', 'code', 'name', 'unit']), 'action', 'O cadastro do artigo mudou. Devolva e actualize a preparação.');
|
||||
}
|
||||
@@ -223,7 +250,10 @@ class SupplyPlanning
|
||||
'daily_milli' => 'nullable|integer|min:0|max:1000000000', 'lead_days' => 'required|integer|min:0|max:3650', 'approval_days' => 'required|integer|min:0|max:365',
|
||||
'horizon_days' => 'required|integer|min:1|max:366', 'minimum_milli' => 'required|integer|min:0|max:1000000000', 'pack_milli' => 'required|integer|min:1|max:1000000000',
|
||||
'basis' => 'required|string|min:5|max:2000'],
|
||||
'agreement' => ['stock_item_id' => 'required|integer|min:1', 'warehouse_id' => 'required|integer|min:1', 'supplier_id' => 'required|integer|min:1',
|
||||
'contract' => ['supplier_id' => 'required|integer|min:1', 'reference' => 'required|string|max:200',
|
||||
'currency' => 'required|regex:/^[A-Z]{3}$/', 'valid_from' => 'required|date_format:Y-m-d', 'valid_until' => 'required|date_format:Y-m-d|after_or_equal:valid_from',
|
||||
'periodicity_days' => 'nullable|integer|min:1|max:3650'],
|
||||
'agreement' => ['contract_key' => 'nullable|uuid', 'stock_item_id' => 'required|integer|min:1', 'warehouse_id' => 'required|integer|min:1', 'supplier_id' => 'required|integer|min:1',
|
||||
'habitual' => 'required|boolean', 'valid_from' => 'required|date_format:Y-m-d', 'valid_until' => 'required|date_format:Y-m-d|after_or_equal:valid_from',
|
||||
'origin' => 'required|in:local,import', 'currency' => 'required|regex:/^[A-Z]{3}$/', 'price_minor' => 'nullable|integer|min:0|max:1000000000000',
|
||||
'lead_days' => 'nullable|integer|min:0|max:3650', 'reference' => 'required|string|max:200'],
|
||||
@@ -233,6 +263,12 @@ class SupplyPlanning
|
||||
default => throw new \InvalidArgumentException('Tipo de fornecimento desconhecido.'),
|
||||
};
|
||||
$data = Validator::make($input, $rules)->validate();
|
||||
if (in_array($kind, ['agreement', 'contract'], true)) {
|
||||
$data = [...$data, ...app(AgreementOrderLimits::class)->terms($input)];
|
||||
}
|
||||
if ($kind === 'contract') {
|
||||
$this->check(($data['max_order_quantity_milli'] ?? null) === null, 'data.order_limit_quantity', 'O limite de quantidade pertence a cada artigo, não ao conjunto de unidades distintas.');
|
||||
}
|
||||
if ($predecessor !== null) {
|
||||
$this->check((int) $data['stock_item_id'] === $predecessor->stock_item_id && (int) $data['warehouse_id'] === $predecessor->warehouse_id, 'data.stock_item_id', 'A política reutilizada mantém o artigo e local de origem.');
|
||||
$data['predecessor_version'] = (int) $data['predecessor_version'];
|
||||
|
||||
@@ -162,7 +162,8 @@ class WarehouseFulfilment
|
||||
'idempotency_key' => (string) Str::uuid(), 'responsible_id' => $r->created_by, 'warehouse_id' => $r->warehouse_id, 'stock_item_id' => $line['item']['id'],
|
||||
'quantity' => intdiv($quantity, 1000).'.'.str_pad((string) ($quantity % 1000), 3, '0', STR_PAD_LEFT), 'destination' => $r->snapshot['destination'], 'reason' => 'Saída pela requisição RA-'.$r->id.': '.$data['reason'],
|
||||
...($line['equipment'] === null ? [] : ['equipment_id' => $line['equipment']['id']])]);
|
||||
$eventData['lines'][] = ['index' => $index, 'quantity_milli' => $quantity, 'stock_operation_id' => $operation->id];
|
||||
$eventData['lines'][] = ['index' => $index, 'quantity_milli' => $quantity, 'stock_operation_id' => $operation->id,
|
||||
...(isset($line['production']) ? ['production' => $line['production']] : [])];
|
||||
}
|
||||
$eventData['recipient'] = $r->snapshot['requester'];
|
||||
}
|
||||
|
||||
@@ -27,7 +27,16 @@ class WarehouseRequests
|
||||
$data = Validator::make($input, ['operation_key' => 'required|uuid', 'warehouse_id' => 'required|integer|min:1', 'cost_center_id' => 'required|integer|min:1',
|
||||
'destination' => 'required|string|min:3|max:300', 'reason' => 'required|string|min:10|max:4000', 'priority' => 'required|in:normal,urgent',
|
||||
'lines' => 'required|array|min:1|max:50', 'lines.*.stock_item_id' => 'required|integer|min:1', 'lines.*.quantity' => 'required|string|regex:/^[0-9]{1,6}(\.[0-9]{1,3})?$/D',
|
||||
'lines.*.use' => 'required|in:internal,equipment', 'lines.*.equipment_id' => 'nullable|integer|min:1'])->validate();
|
||||
'lines.*.use' => 'required|in:internal,equipment,production', 'lines.*.equipment_id' => 'nullable|integer|min:1',
|
||||
'lines.*.production_reference' => 'nullable|string|max:120'])->validate();
|
||||
foreach ($data['lines'] as &$inputLine) {
|
||||
if ($inputLine['use'] !== 'production' && (($inputLine['production_reference'] ?? null) === null || $inputLine['production_reference'] === '')) {
|
||||
unset($inputLine['production_reference']);
|
||||
} elseif ($inputLine['use'] === 'production') {
|
||||
$inputLine['production_reference'] ??= null;
|
||||
}
|
||||
}
|
||||
unset($inputLine);
|
||||
$hash = hash('sha256', json_encode($data, JSON_THROW_ON_ERROR));
|
||||
$old = WarehouseRequest::query()->where('created_by', $actor->id)->where('operation_key', $data['operation_key'])->first();
|
||||
if ($old !== null) {
|
||||
@@ -47,6 +56,9 @@ class WarehouseRequests
|
||||
throw ValidationException::withMessages(['lines.'.$index.'.quantity' => 'A quantidade deve ser positiva.']);
|
||||
}
|
||||
$equipment = null;
|
||||
if ($line['use'] !== 'production' && ($line['production_reference'] ?? null) !== null && $line['production_reference'] !== '') {
|
||||
throw ValidationException::withMessages(['lines.'.$index.'.production_reference' => 'A referência de produção aplica-se apenas ao destino de produção.']);
|
||||
}
|
||||
if ($line['use'] === 'equipment') {
|
||||
if (empty($line['equipment_id'])) {
|
||||
throw ValidationException::withMessages(['lines.'.$index.'.equipment_id' => 'Seleccione o equipamento de destino.']);
|
||||
@@ -60,7 +72,8 @@ class WarehouseRequests
|
||||
throw ValidationException::withMessages(['lines.'.$index.'.equipment_id' => 'Escolha utilização em equipamento para associar este destino.']);
|
||||
}
|
||||
$lines[] = ['item' => $item->only(['id', 'code', 'name', 'unit']), 'quantity_milli' => $quantity, 'use' => $line['use'],
|
||||
'destination' => $data['destination'], 'equipment' => $equipment?->only(['id', 'code', 'description'])];
|
||||
'destination' => $data['destination'], 'equipment' => $equipment?->only(['id', 'code', 'description']),
|
||||
...($line['use'] === 'production' ? ['production' => ['reference' => $line['production_reference'] ?? null, 'verification' => 'user_supplied']] : [])];
|
||||
}
|
||||
$record = WarehouseRequest::query()->create(['tenant_id' => $actor->tenant_id, 'created_by' => $actor->id, 'warehouse_id' => $warehouse->id,
|
||||
'cost_center_id' => $center->id, 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'status' => 'draft', 'created_at' => now(),
|
||||
|
||||
@@ -538,7 +538,10 @@ class WorkflowTaskInbox
|
||||
return [];
|
||||
}
|
||||
$rows = [];
|
||||
foreach (['agreement', 'policy', 'auto_rule', 'history', 'alternative'] as $kind) {
|
||||
foreach (['contract', 'agreement', 'policy', 'auto_rule', 'history', 'alternative'] as $kind) {
|
||||
if ($kind === 'contract' && ! app(AgreementOrderLimits::class)->ready()) {
|
||||
continue;
|
||||
}
|
||||
$permission = match ($kind) {
|
||||
'history' => 'supply_history_review', 'alternative' => 'supply_technical_review', default => 'supply_review'
|
||||
};
|
||||
@@ -556,13 +559,13 @@ class WorkflowTaskInbox
|
||||
continue;
|
||||
}
|
||||
$rows[] = ['id' => 'supply:'.$record->id.':review', 'module' => 'supply',
|
||||
'reference' => trim(($record->snapshot['item']['code'] ?? 'Fornecimento').' '.($record->snapshot['warehouse']['code'] ?? '')),
|
||||
'reference' => $kind === 'contract' ? $record->data['reference'] : trim(($record->snapshot['item']['code'] ?? 'Fornecimento').' '.($record->snapshot['warehouse']['code'] ?? '')),
|
||||
'label' => match ($kind) {
|
||||
'agreement' => 'Conferir acordo de fornecimento', 'policy' => 'Conferir política de reposição', 'history' => 'Conferir histórico de consumo', 'alternative' => 'Conferir alternativa técnica', default => 'Conferir parametrização de compra automática',
|
||||
'contract' => 'Conferir contrato multiartigo', 'agreement' => 'Conferir acordo de fornecimento', 'policy' => 'Conferir política de reposição', 'history' => 'Conferir histórico de consumo', 'alternative' => 'Conferir alternativa técnica', default => 'Conferir parametrização de compra automática',
|
||||
}, 'task' => $kind.'_review', 'status' => $record->state, 'blocked' => false, 'created_at' => $this->date($record->created_at), 'due_on' => null,
|
||||
'href' => $kind === 'auto_rule' ? '/stock/reposicao?rule_id='.$record->id.'#supply-rule-'.$record->id
|
||||
: '/compras/fornecimento?view='.match ($kind) {
|
||||
'agreement' => 'agreements', 'history' => 'history', 'alternative' => 'alternatives', default => 'calendar'
|
||||
'contract' => 'contracts', 'agreement' => 'agreements', 'history' => 'history', 'alternative' => 'alternatives', default => 'calendar'
|
||||
}.'&record_id='.$record->id.'#supply-record-'.$record->id];
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user