@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Requisition;
|
||||
use App\Models\User;
|
||||
use App\Services\OrganizationAccess;
|
||||
use Illuminate\Database\Query\Builder;
|
||||
@@ -27,7 +28,7 @@ class AuditMetadataController extends Controller
|
||||
/** @return array<string,mixed> */
|
||||
private function filters(Request $request): array
|
||||
{
|
||||
return $request->validate(['action' => 'nullable|string|max:100', 'actor_id' => 'nullable|integer|min:1',
|
||||
return $request->validate(['request_reference' => 'nullable|string|max:100', 'action' => 'nullable|string|max:100', 'actor_id' => 'nullable|integer|min:1',
|
||||
'from' => 'nullable|date_format:Y-m-d', 'to' => ['nullable', 'date_format:Y-m-d', Rule::when($request->filled('from'), 'after_or_equal:from')], 'page' => 'nullable|integer|min:1|max:1000000']);
|
||||
}
|
||||
|
||||
@@ -35,7 +36,10 @@ class AuditMetadataController extends Controller
|
||||
private function query(User $actor, array $filters): Builder
|
||||
{
|
||||
return DB::table('audit_logs')->where('tenant_id', $actor->tenant_id)
|
||||
->when(! empty($filters['action']), fn ($q) => $q->where('action', $filters['action']))
|
||||
->when(isset($filters['request_reference']) && $filters['request_reference'] !== '', fn ($q) => $q->whereExists(fn ($source) => $source
|
||||
->selectRaw('1')->from('requisitions')->whereColumn('requisitions.id', 'audit_logs.requisition_id')
|
||||
->whereColumn('requisitions.tenant_id', 'audit_logs.tenant_id')->where('requisitions.number', $filters['request_reference'])))
|
||||
->when(isset($filters['action']) && $filters['action'] !== '', fn ($q) => $q->where('action', $filters['action']))
|
||||
->when(! empty($filters['actor_id']), fn ($q) => $q->where('user_id', $filters['actor_id']))
|
||||
->when(! empty($filters['from']), fn ($q) => $q->whereDate('created_at', '>=', $filters['from']))
|
||||
->when(! empty($filters['to']), fn ($q) => $q->whereDate('created_at', '<=', $filters['to']))
|
||||
@@ -51,8 +55,11 @@ class AuditMetadataController extends Controller
|
||||
$this->readOnly();
|
||||
$actor = $this->actor($request);
|
||||
Inertia::encryptHistory();
|
||||
$source = isset($filters['request_reference']) && $filters['request_reference'] !== ''
|
||||
? Requisition::query()->visibleTo($actor)->where('number', $filters['request_reference'])->first(['id', 'number']) : null;
|
||||
|
||||
$response = Inertia::render('audit/metadata', ['filters' => $filters,
|
||||
'requestContext' => $source === null ? null : ['number' => $source->number, 'href' => '/requisicoes/'.$source->id.'#requisition-history'],
|
||||
'events' => $this->query($actor, $filters)->orderBy('id')->paginate(25)->withQueryString()])->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
@@ -80,7 +87,9 @@ class AuditMetadataController extends Controller
|
||||
};
|
||||
try {
|
||||
fwrite($out, "\xEF\xBB\xBF");
|
||||
fputcsv($out, ['Metadados de eventos da empresa', 'Consulta', now()->toIso8601String()], ';', '"', '');
|
||||
fputcsv($out, ['Metadados de eventos da empresa', 'Consulta', now()->toIso8601String(),
|
||||
'Referência exacta da requisição', $text($filters['request_reference'] ?? ''), 'Acção exacta', $text($filters['action'] ?? ''),
|
||||
'Utilizador (id)', $text($filters['actor_id'] ?? ''), 'Desde', $text($filters['from'] ?? ''), 'Até', $text($filters['to'] ?? '')], ';', '"', '');
|
||||
fputcsv($out, ['Registo', 'Data', 'Acção', 'Utilizador (id)'], ';', '"', '');
|
||||
foreach ($this->query($actor, $filters)->lazyById(100) as $event) {
|
||||
fputcsv($out, array_map($text, [$event->id, $event->created_at, $event->action, $event->user_id]), ';', '"', '');
|
||||
|
||||
@@ -15,7 +15,7 @@ use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class BudgetController extends Controller
|
||||
{
|
||||
@@ -27,12 +27,16 @@ class BudgetController extends Controller
|
||||
public function index(Request $request): Response
|
||||
{
|
||||
$this->access($request);
|
||||
Inertia::encryptHistory();
|
||||
|
||||
return Inertia::render('budgets/index', ['centers' => CostCenter::query()->orderBy('code')->get(), 'budgets' => Budget::query()->latest('id')->get()->map(function (Budget $budget) use ($request) {
|
||||
$response = Inertia::render('budgets/index', ['centers' => CostCenter::query()->orderBy('code')->get(), 'budgets' => Budget::query()->latest('id')->get()->map(function (Budget $budget) use ($request) {
|
||||
$adapter = app(CommonBudget::class);
|
||||
|
||||
return [...$budget->toArray(), ...$adapter->execute(fn () => $adapter->for($this->staffIdentity($request))->balance($budget->id))];
|
||||
}), 'reinforcements' => BudgetReinforcement::query()->latest('id')->paginate(20)]);
|
||||
}), 'reinforcements' => BudgetReinforcement::query()->latest('id')->paginate(20)])->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
public function store(Request $request): RedirectResponse
|
||||
|
||||
@@ -15,13 +15,20 @@ use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class CompanyController extends Controller
|
||||
{
|
||||
public function setup(Request $request): Response|RedirectResponse
|
||||
public function setup(Request $request): Response
|
||||
{
|
||||
return $this->staffIdentity($request)->tenant_id ? to_route('dashboard') : Inertia::render('company/setup');
|
||||
if ($this->staffIdentity($request)->tenant_id) {
|
||||
return to_route('dashboard');
|
||||
}
|
||||
Inertia::encryptHistory();
|
||||
$response = Inertia::render('company/setup')->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
public function store(Request $request, RequisitionWorkflow $workflow): RedirectResponse
|
||||
@@ -46,20 +53,24 @@ class CompanyController extends Controller
|
||||
return to_route('dashboard');
|
||||
}
|
||||
|
||||
public function index(Request $request): Response|RedirectResponse
|
||||
public function index(Request $request): Response
|
||||
{
|
||||
$this->admin($request);
|
||||
if (app(OrganizationAccess::class)->active($this->staffIdentity($request)->tenant_id)) {
|
||||
return to_route('organization.parameters');
|
||||
}
|
||||
|
||||
return Inertia::render('company/index', [
|
||||
Inertia::encryptHistory();
|
||||
$response = Inertia::render('company/index', [
|
||||
'company' => Tenant::query()->findOrFail($this->staffIdentity($request)->tenant_id),
|
||||
'departments' => Department::query()->orderBy('name')->get(),
|
||||
'costCenters' => CostCenter::query()->orderBy('code')->get(),
|
||||
'users' => User::query()->where('tenant_id', $this->staffIdentity($request)->tenant_id)->orderBy('name')->get(['id', 'name', 'email', 'department_id', 'purchasing_role']),
|
||||
'roles' => collect(PurchasingRole::cases())->reject(fn (PurchasingRole $role) => $role === PurchasingRole::Configured)->values()->map(fn (PurchasingRole $role) => ['value' => $role->value, 'label' => $role->label()]),
|
||||
]);
|
||||
])->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
public function department(Request $request, RequisitionWorkflow $workflow): RedirectResponse
|
||||
|
||||
@@ -13,20 +13,24 @@ use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class ConflictDeclarationController extends Controller
|
||||
{
|
||||
public function index(Request $request): Response
|
||||
{
|
||||
return Inertia::render('conflicts/index', [
|
||||
Inertia::encryptHistory();
|
||||
$response = Inertia::render('conflicts/index', [
|
||||
'declarations' => ConflictDeclaration::query()->visibleTo($this->staffIdentity($request))
|
||||
->with(['author:id,name', 'supplier:id,name', 'requisition:id,number', 'successor:id,previous_id'])
|
||||
->latest('id')->paginate(15),
|
||||
// These minimal choices allow personal declarations without granting supplier-management access.
|
||||
'suppliers' => Supplier::query()->orderBy('name')->get(['id', 'name']),
|
||||
'requisitions' => Requisition::query()->visibleTo($this->staffIdentity($request))->latest()->get(['id', 'number']),
|
||||
]);
|
||||
])->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
public function store(Request $request, ConflictGuard $guard, RequisitionWorkflow $workflow): RedirectResponse
|
||||
@@ -65,7 +69,11 @@ class ConflictDeclarationController extends Controller
|
||||
->with(['author:id,name', 'supplier:id,name', 'requisition:id,number'])->orderBy('id')->get();
|
||||
$latest = $history->last();
|
||||
|
||||
return Inertia::render('conflicts/show', ['history' => $history, 'canCorrect' => $latest?->user_id === $this->staffIdentity($request)->id]);
|
||||
Inertia::encryptHistory();
|
||||
$response = Inertia::render('conflicts/show', ['history' => $history, 'canCorrect' => $latest?->user_id === $this->staffIdentity($request)->id])->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
public function update(Request $request, ConflictDeclaration $declaration, ConflictGuard $guard, RequisitionWorkflow $workflow): RedirectResponse
|
||||
|
||||
@@ -29,7 +29,7 @@ use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class EquipmentController extends Controller
|
||||
{
|
||||
@@ -41,7 +41,7 @@ class EquipmentController extends Controller
|
||||
return $actor;
|
||||
}
|
||||
|
||||
public function show(Request $request, int $equipment): \Symfony\Component\HttpFoundation\Response
|
||||
public function show(Request $request, int $equipment): Response
|
||||
{
|
||||
$actor = $request->user('web');
|
||||
abort_unless($actor instanceof User, 403);
|
||||
@@ -67,6 +67,7 @@ class EquipmentController extends Controller
|
||||
Inertia::encryptHistory();
|
||||
|
||||
$response = Inertia::render('equipment/show', ['equipment' => $asset->only(['id', 'code', 'description', 'area', 'status']),
|
||||
'capitalReference' => app(CapitalRegister::class)->referenceForEquipment($actor, $asset),
|
||||
'geography' => app(AdministrativeGeography::class)->describe($asset->geography_reference),
|
||||
'warehouseRequests' => app(EquipmentWarehouseRequests::class)->page($actor, $asset),
|
||||
'purchases' => $purchases, 'movements' => $movements])->toResponse($request);
|
||||
@@ -110,7 +111,8 @@ class EquipmentController extends Controller
|
||||
}
|
||||
}
|
||||
|
||||
return Inertia::render('equipment/index', [
|
||||
Inertia::encryptHistory();
|
||||
$response = Inertia::render('equipment/index', [
|
||||
'geographyEnabled' => $geography->availableFor('equipment'), 'equipmentGeography' => $equipment->mapWithKeys(fn (Equipment $asset) => [$asset->id => $geography->describe($asset->geography_reference)])->all(),
|
||||
'filters' => $filters, 'geographyFilter' => empty($filters['location']) ? null : $geography->describe(['catalogue' => config('geography.source_sha256'), 'record_id' => $filters['location'], 'country' => 'MZ']),
|
||||
'equipment' => $equipment, 'parts' => $parts, 'links' => $links, 'levels' => CriticalityLevel::query()->orderBy('code')->get(),
|
||||
@@ -120,7 +122,10 @@ class EquipmentController extends Controller
|
||||
'canManage' => $this->actor($request)->hasFunctions([PurchasingRole::Admin, PurchasingRole::Warehouse, PurchasingRole::Procurement]),
|
||||
'capitalRegisterReady' => app(CapitalRegister::class)->ready(),
|
||||
'canConfigure' => $this->actor($request)->hasFunctions([PurchasingRole::Admin]),
|
||||
]);
|
||||
])->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
public function store(Request $request, string $kind): RedirectResponse
|
||||
|
||||
@@ -61,6 +61,7 @@ class GoodsReceiptController extends Controller
|
||||
public function order(Request $request, PurchaseOrder $order, ReceiptWorkflow $workflow): Response
|
||||
{
|
||||
Gate::authorize('viewOrder', [GoodsReceipt::class, $order]);
|
||||
Inertia::encryptHistory();
|
||||
|
||||
return Inertia::render('receipts/order', [
|
||||
'order' => $order->only(['id', 'number', 'issued_by']), 'supplier_name' => $order->snapshot['supplier']['name'],
|
||||
|
||||
@@ -9,7 +9,7 @@ use App\Services\InvestmentWorkflow;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class InvestmentPolicyController extends Controller
|
||||
{
|
||||
@@ -18,7 +18,11 @@ class InvestmentPolicyController extends Controller
|
||||
abort_unless($this->staffIdentity($request)->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance, PurchasingRole::Procurement]), 403);
|
||||
$current = $workflow->current();
|
||||
|
||||
return Inertia::render('investment/index', ['policies' => InvestmentPolicy::query()->latest('revision')->get(), 'reviews' => InvestmentPolicyReview::query()->orderBy('id')->get(), 'currentPolicyId' => $current && $current->valid_until >= today()->format('Y-m-d') ? $current->id : null, 'canManage' => $this->staffIdentity($request)->hasFunctions([PurchasingRole::Admin])]);
|
||||
Inertia::encryptHistory();
|
||||
$response = Inertia::render('investment/index', ['policies' => InvestmentPolicy::query()->latest('revision')->get(), 'reviews' => InvestmentPolicyReview::query()->orderBy('id')->get(), 'currentPolicyId' => $current && $current->valid_until >= today()->format('Y-m-d') ? $current->id : null, 'canManage' => $this->staffIdentity($request)->hasFunctions([PurchasingRole::Admin])])->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
public function store(Request $request, InvestmentWorkflow $workflow): RedirectResponse
|
||||
|
||||
@@ -12,11 +12,15 @@ use App\Models\StockItem;
|
||||
use App\Models\Supplier;
|
||||
use App\Models\User;
|
||||
use App\Models\Warehouse;
|
||||
use App\Services\AgreementOrderLimits;
|
||||
use App\Services\OrganizationAccess;
|
||||
use App\Services\SavedProcurementSearches;
|
||||
use App\Services\SupplyPlanning;
|
||||
use App\Services\WarehouseWorkdesk;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Inertia\Inertia;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
@@ -33,8 +37,27 @@ class ProcurementSearchController extends Controller
|
||||
$data = $request->validate(['q' => 'nullable|string|max:100', 'archived_page' => 'nullable|integer|min:1|max:1000000', 'requests_page' => 'nullable|integer|min:1|max:1000000', 'orders_page' => 'nullable|integer|min:1|max:1000000', 'suppliers_page' => 'nullable|integer|min:1|max:1000000']);
|
||||
$term = trim($data['q'] ?? '');
|
||||
$request->validate(['invoices_page' => 'nullable|integer|min:1|max:1000000']);
|
||||
$request->validate(['agreements_page' => 'nullable|integer|min:1|max:1000000', 'contracts_page' => 'nullable|integer|min:1|max:1000000']);
|
||||
$request->validate(['warehouse_requests_page' => 'nullable|integer|min:1|max:1000000']);
|
||||
$planning = app(SupplyPlanning::class);
|
||||
$supplySelectors = match (DB::getDriverName()) {
|
||||
'pgsql' => ['LOWER("data"->>\'reference\') LIKE ? ESCAPE \'!\'', 'LOWER("snapshot"->\'supplier\'->>\'name\') LIKE ? ESCAPE \'!\''],
|
||||
'sqlite' => ["LOWER(json_extract(data, '$.reference')) LIKE ? ESCAPE '!'", "LOWER(json_extract(snapshot, '$.supplier.name')) LIKE ? ESCAPE '!'"],
|
||||
default => null,
|
||||
};
|
||||
$supplySearchAvailable = config('procurement_search.supply_metadata_enabled') === true && Schema::hasTable('supply_records')
|
||||
&& $supplySelectors !== null
|
||||
&& collect(['supply_read', 'supply_prepare', 'supply_review'])->contains(fn ($permission) => $planning->allows($actor, $permission));
|
||||
$warehouseSelectors = match (DB::getDriverName()) {
|
||||
'pgsql' => ['LOWER("snapshot"->>\'destination\') LIKE ? ESCAPE \'!\'', 'LOWER("snapshot"->\'requester\'->>\'name\') LIKE ? ESCAPE \'!\''],
|
||||
'sqlite' => ["LOWER(json_extract(snapshot, '$.destination')) LIKE ? ESCAPE '!'", "LOWER(json_extract(snapshot, '$.requester.name')) LIKE ? ESCAPE '!'"],
|
||||
default => null,
|
||||
};
|
||||
$warehouseRequestSearchAvailable = config('procurement_search.warehouse_requests_metadata_enabled') === true
|
||||
&& $warehouseSelectors !== null && Schema::hasTable('warehouse_requests')
|
||||
&& $actor->hasFunctions(['admin', 'warehouse_request_read', 'warehouse_request_prepare', 'warehouse_request_review', 'warehouse_request_deliver']);
|
||||
$request->validate(['equipment_page' => 'nullable|integer|min:1|max:1000000', 'stock_page' => 'nullable|integer|min:1|max:1000000', 'warehouses_page' => 'nullable|integer|min:1|max:1000000', 'receipts_page' => 'nullable|integer|min:1|max:1000000']);
|
||||
$groups = DB::transaction(function () use ($actor, $term) {
|
||||
$groups = DB::transaction(function () use ($actor, $term, $planning, $supplySearchAvailable, $supplySelectors, $warehouseRequestSearchAvailable, $warehouseSelectors) {
|
||||
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
|
||||
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
}
|
||||
@@ -94,12 +117,45 @@ class ProcurementSearchController extends Controller
|
||||
$groups[] = ['key' => 'invoices', 'title' => 'Facturas de fornecedor', 'records' => $invoices];
|
||||
}
|
||||
|
||||
if ($supplySearchAvailable) {
|
||||
foreach (['agreement' => ['agreements', 'Acordos'], 'contract' => ['contracts', 'Contratos globais']] as $kind => [$key, $title]) {
|
||||
if ($kind === 'contract' && ! app(AgreementOrderLimits::class)->ready()) {
|
||||
continue;
|
||||
}
|
||||
$query = $planning->latest($kind)->where('tenant_id', $actor->tenant_id);
|
||||
$query->where(function ($query) use ($supplySelectors, $pattern) {
|
||||
// Fixed SQL for the supported engines; the user's term stays bound.
|
||||
$query->whereRaw($supplySelectors[0], [$pattern])->orWhereRaw($supplySelectors[1], [$pattern]);
|
||||
});
|
||||
$records = $query->latest('id')->paginate(15, ['id', 'version', 'state', 'data->reference as reference'], $key.'_page')->withQueryString()
|
||||
->through(fn ($row) => ['id' => $row->id, 'title' => ($row->getAttribute('reference') ?: 'Referência por completar').' · v'.$row->version,
|
||||
'detail' => $row->state, 'href' => '/compras/fornecimento?view='.$key.'&record_id='.$row->id.'#supply-record-'.$row->id]);
|
||||
$groups[] = ['key' => $key, 'title' => $title, 'records' => $records];
|
||||
}
|
||||
}
|
||||
|
||||
if ($warehouseRequestSearchAvailable) {
|
||||
$desk = app(WarehouseWorkdesk::class);
|
||||
$query = $desk->visible($actor)->where('tenant_id', $actor->tenant_id);
|
||||
if (preg_match('/^(?:RA-)?([1-9][0-9]{0,9})$/iD', $term, $match)) {
|
||||
$query->whereKey($match[1]);
|
||||
} else {
|
||||
$query->where(fn ($query) => $query->whereRaw($warehouseSelectors[0], [$pattern])->orWhereRaw($warehouseSelectors[1], [$pattern]));
|
||||
}
|
||||
$records = $query->select('warehouse_requests.id')->selectRaw($desk->stateExpression().' as projected_state')->latest('id')
|
||||
->paginate(15, ['id'], 'warehouse_requests_page')->withQueryString()->through(fn ($row) => [
|
||||
'id' => $row->id, 'title' => 'RA-'.$row->id, 'detail' => $row->getAttribute('projected_state'), 'href' => '/stock/requisicoes/'.$row->id]);
|
||||
$groups[] = ['key' => 'warehouse_requests', 'title' => 'Requisições internas de armazém', 'records' => $records];
|
||||
}
|
||||
|
||||
return $groups;
|
||||
});
|
||||
Inertia::encryptHistory();
|
||||
$response = Inertia::render('search/procurement', ['term' => $term, 'groups' => $groups,
|
||||
'savedSearches' => app(SavedProcurementSearches::class)->read($actor),
|
||||
'invoiceSearchAvailable' => config('procurement_search.finance_metadata_enabled') === true && $actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance]),
|
||||
'supplySearchAvailable' => $supplySearchAvailable,
|
||||
'warehouseRequestSearchAvailable' => $warehouseRequestSearchAvailable,
|
||||
])->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
|
||||
@@ -16,19 +16,20 @@ use App\Services\PurchaseRevisionWorkflow;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class PurchaseControlController extends Controller
|
||||
{
|
||||
public function index(Request $request): Response
|
||||
{
|
||||
$user = $this->staffIdentity($request);
|
||||
Inertia::encryptHistory();
|
||||
$operational = $user->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance]);
|
||||
$sources = Requisition::query()->where('requester_id', $user->id)->select('id');
|
||||
$ownAwards = PurchaseAward::query()->whereIn('requisition_id', $sources)->select('id');
|
||||
$cancellations = AwardCancellation::query()->whereIn('purchase_award_id', $ownAwards)->where('status', 'approved')->get(['id', 'purchase_award_id']);
|
||||
|
||||
return Inertia::render('purchase-controls/index', [
|
||||
$response = Inertia::render('purchase-controls/index', [
|
||||
'role' => $user->purchasing_role->value ?? '', 'permissions' => app(OrganizationAccess::class)->permissions($user), 'actorId' => $user->id,
|
||||
'policies' => $operational ? PurchaseControlPolicy::query()->latest('revision')->get() : [],
|
||||
'reviews' => $operational ? PurchaseControlReview::query()->get() : [],
|
||||
@@ -40,7 +41,10 @@ class PurchaseControlController extends Controller
|
||||
|
||||
return ['id' => $cancellation->id, 'number' => $source->number, 'revision_id' => PurchaseRevision::query()->where('award_cancellation_id', $cancellation->id)->value('requisition_id')];
|
||||
}),
|
||||
]);
|
||||
])->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
public function propose(Request $request, PurchaseControlPolicyWorkflow $workflow): RedirectResponse
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Requisition;
|
||||
use App\Models\User;
|
||||
use App\Services\RequisitionAccountAssignments;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
final class RequisitionAccountsController extends Controller
|
||||
{
|
||||
public function show(Request $request, Requisition $requisition, RequisitionAccountAssignments $service): Response
|
||||
{
|
||||
$actor = $request->user('web');
|
||||
abort_unless($actor instanceof User, 403);
|
||||
$filters = $request->validate(['account_search' => 'nullable|string|max:100', 'accounts_page' => 'nullable|integer|min:1|max:1000000',
|
||||
'history_page' => 'nullable|integer|min:1|max:1000000']);
|
||||
Inertia::encryptHistory();
|
||||
$response = Inertia::render('requisitions/accounts', $service->workspace($actor, $requisition, $filters['account_search'] ?? ''))->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
public function store(Request $request, Requisition $requisition, RequisitionAccountAssignments $service): Response
|
||||
{
|
||||
$actor = $request->user('web');
|
||||
abort_unless($actor instanceof User, 403);
|
||||
$service->save($actor, $requisition, $request->all());
|
||||
|
||||
return back()->with('success', 'Imputação contabilística preservada.');
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,10 @@ use App\Services\RequisitionBudgetDistributions;
|
||||
use App\Services\RequisitionCatalogue;
|
||||
use App\Services\RequisitionCategories;
|
||||
use App\Services\RequisitionDraftInput;
|
||||
use App\Services\RequisitionDuplicateHints;
|
||||
use App\Services\RequisitionExpiry;
|
||||
use App\Services\RequisitionLedgerAccounts;
|
||||
use App\Services\RequisitionSubmissionPreview;
|
||||
use App\Services\RequisitionWorkflow;
|
||||
use App\Services\SupplySuggestions;
|
||||
use App\Services\WorkContext;
|
||||
@@ -59,7 +62,7 @@ class RequisitionController extends Controller
|
||||
->filter(fn (Requisition $requisition) => $requisition->canDecide($this->actor($request)))->modelKeys();
|
||||
$query->whereIn('id', $eligible);
|
||||
} elseif (($filters['view'] ?? 'all') === 'decided') {
|
||||
$query->whereHas('steps', fn ($steps) => $steps->where('approver_id', $this->actor($request)->id)->whereIn('decision', ['approved', 'rejected']));
|
||||
$query->whereHas('allSteps', fn ($steps) => $steps->where('approver_id', $this->actor($request)->id)->whereIn('decision', ['approved', 'rejected']));
|
||||
}
|
||||
if (! empty($filters['search'])) {
|
||||
$query->where('number', 'like', '%'.$filters['search'].'%');
|
||||
@@ -119,6 +122,10 @@ class RequisitionController extends Controller
|
||||
|
||||
return Inertia::render('requisitions/show', [
|
||||
'requisition' => $requisition,
|
||||
'submissionPreview' => app(RequisitionSubmissionPreview::class)->for($this->actor($request), $requisition),
|
||||
'duplicateHints' => app(RequisitionDuplicateHints::class)->for($this->actor($request), $requisition),
|
||||
'canReadAuditMetadata' => ! app(OrganizationAccess::class)->maintenanceOnly($this->actor($request))
|
||||
&& in_array('audit_metadata_read', app(OrganizationAccess::class)->permissions($this->actor($request)), true),
|
||||
'approvalRouting' => app(ApprovalRouting::class)->current($requisition, $this->actor($request)),
|
||||
'canRefreshRouting' => $requisition->status === 'pending' && $this->actor($request)->hasFunctions(['admin', 'procurement']) && ! app(OrganizationAccess::class)->maintenanceOnly($this->actor($request)) && Schema::hasTable('workflow_notices'),
|
||||
'replenishmentSource' => app(SupplySuggestions::class)->origin($requisition),
|
||||
@@ -128,6 +135,7 @@ class RequisitionController extends Controller
|
||||
'importTariffsReady' => app(ImportTariffCodes::class)->ready(),
|
||||
'importEstimatesReady' => app(ImportEstimates::class)->ready(),
|
||||
'capitalRegisterReady' => app(CapitalRegister::class)->ready(),
|
||||
'accountsReady' => app(RequisitionLedgerAccounts::class)->ready(),
|
||||
'expiryReady' => app(RequisitionExpiry::class)->ready(),
|
||||
'canDecide' => $requisition->canDecide($this->actor($request)),
|
||||
'canPrepareDistributions' => app(RequisitionBudgetDistributions::class)->ready() && $requisition->status === 'draft'
|
||||
|
||||
@@ -22,7 +22,7 @@ use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class StockController extends Controller
|
||||
{
|
||||
@@ -78,13 +78,17 @@ class StockController extends Controller
|
||||
'lot_control' => app(InventoryLots::class)->summary($balance->stock_item_id, $balance->warehouse_id),
|
||||
]);
|
||||
|
||||
return Inertia::render('stock/index', [
|
||||
Inertia::encryptHistory();
|
||||
$response = Inertia::render('stock/index', [
|
||||
'items' => $items, 'warehouses' => $warehouses, 'balances' => $balances,
|
||||
'geographyEnabled' => $geography->availableFor('warehouses'), 'warehouseGeography' => $warehouseGeography,
|
||||
'geographyFilter' => empty($filters['location']) ? null : $geography->describe(['catalogue' => config('geography.source_sha256'), 'record_id' => $filters['location'], 'country' => 'MZ']),
|
||||
'movements' => $movements->latest('id')->paginate(20)->withQueryString(), 'filters' => $filters,
|
||||
'canManage' => $this->actor($request)->hasFunctions([PurchasingRole::Admin, PurchasingRole::Warehouse]),
|
||||
]);
|
||||
])->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
public function item(Request $request, RequisitionWorkflow $audit): RedirectResponse
|
||||
|
||||
@@ -11,6 +11,7 @@ use App\Models\Warehouse;
|
||||
use App\Services\InventoryCounts;
|
||||
use App\Services\InventoryLots;
|
||||
use App\Services\InventoryReversals;
|
||||
use App\Services\OrganizationAccess;
|
||||
use App\Services\StockWorkflow;
|
||||
use Brick\Math\BigDecimal;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
@@ -20,7 +21,7 @@ use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class StockOperationController extends Controller
|
||||
{
|
||||
@@ -48,8 +49,9 @@ class StockOperationController extends Controller
|
||||
}
|
||||
}
|
||||
|
||||
return Inertia::render('stock/operations', [
|
||||
'canViewReturns' => config('stock_returns.enabled') && $actor->hasFunctions(['warehouse_return_read']) && ! app(\App\Services\OrganizationAccess::class)->maintenanceOnly($actor),
|
||||
Inertia::encryptHistory();
|
||||
$response = Inertia::render('stock/operations', [
|
||||
'canViewReturns' => config('stock_returns.enabled') && $actor->hasFunctions(['warehouse_return_read']) && ! app(OrganizationAccess::class)->maintenanceOnly($actor),
|
||||
'correctedOperations' => collect(app(InventoryReversals::class)->corrections('operation'))->map(fn ($r) => $r->data['reference']),
|
||||
'items' => $items, 'warehouses' => $warehouses, 'balances' => $balances,
|
||||
'users' => User::query()->where('tenant_id', $actor->tenant_id)->orderBy('name')->get(['id', 'name']),
|
||||
@@ -58,7 +60,10 @@ class StockOperationController extends Controller
|
||||
'canOperate' => $actor->hasFunctions([PurchasingRole::Warehouse]),
|
||||
'canAdjust' => app(InventoryLots::class)->allows($actor, 'inventory_adjust_review'), 'lotCounts' => $lotCounts,
|
||||
'equipment' => Equipment::query()->orderBy('code')->get(['id', 'code', 'description']),
|
||||
]);
|
||||
])->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
public function store(Request $request, StockWorkflow $workflow): JsonResponse|RedirectResponse
|
||||
|
||||
@@ -93,6 +93,7 @@ class SupplierController extends Controller
|
||||
public function edit(Supplier $supplier): Response
|
||||
{
|
||||
Gate::authorize('update', $supplier);
|
||||
Inertia::encryptHistory();
|
||||
|
||||
return Inertia::render('suppliers/edit', ['supplier' => $supplier, 'geographyEnabled' => app(AdministrativeGeography::class)->enabled(), 'geography' => app(AdministrativeGeography::class)->describe($supplier->geography_reference)]);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Requisition;
|
||||
use App\Models\User;
|
||||
use App\Services\UrgentRequisitionReviews;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Inertia\Inertia;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
final class UrgentRequisitionReviewController extends Controller
|
||||
{
|
||||
private function actor(Request $request): User
|
||||
{
|
||||
$actor = $request->user('web');
|
||||
abort_unless($actor instanceof User, 403);
|
||||
|
||||
return $actor;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $props */
|
||||
private function page(Request $request, string $name, array $props): Response
|
||||
{
|
||||
Inertia::encryptHistory();
|
||||
$response = Inertia::render($name, $props)->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
public function index(Request $request, UrgentRequisitionReviews $service): Response
|
||||
{
|
||||
$filters = $request->validate(['page' => 'nullable|integer|min:1|max:1000000',
|
||||
'state' => ['nullable', Rule::in(['all', 'pending', 'reviewed', 'indeterminate'])]]);
|
||||
|
||||
return $this->page($request, 'requisitions/urgent-reviews', $service->queue($this->actor($request), (int) ($filters['page'] ?? 1), $filters['state'] ?? 'pending'));
|
||||
}
|
||||
|
||||
public function show(Request $request, Requisition $requisition, int $cycle, UrgentRequisitionReviews $service): Response
|
||||
{
|
||||
$request->validate(['page' => 'nullable|integer|min:1|max:1000000']);
|
||||
|
||||
return $this->page($request, 'requisitions/urgent-review', $service->workspace($this->actor($request), $requisition->id, $cycle));
|
||||
}
|
||||
|
||||
public function store(Request $request, Requisition $requisition, int $cycle, UrgentRequisitionReviews $service): Response
|
||||
{
|
||||
$service->review($this->actor($request), $requisition->id, $cycle, $request->all());
|
||||
|
||||
return back()->with('success', 'Revisão posterior preservada para este ciclo.');
|
||||
}
|
||||
|
||||
public function settings(Request $request, UrgentRequisitionReviews $service): Response
|
||||
{
|
||||
$request->validate(['page' => 'nullable|integer|min:1|max:1000000']);
|
||||
|
||||
return $this->page($request, 'organization/urgent-review-policy', $service->settings($this->actor($request)));
|
||||
}
|
||||
|
||||
public function saveSettings(Request $request, UrgentRequisitionReviews $service): Response
|
||||
{
|
||||
$service->savePolicy($this->actor($request), $request->all());
|
||||
|
||||
return back()->with('success', 'Designação dos perfis de revisão preservada.');
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\UrgentRequisitionReviews;
|
||||
use App\Services\WorkflowTaskInbox;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
@@ -59,6 +60,7 @@ class WorkflowTaskInboxController extends Controller
|
||||
$page = (int) ($filters['page'] ?? 1);
|
||||
Inertia::encryptHistory();
|
||||
$response = Inertia::render('workflow/tasks', ['area' => $area, 'modules' => $modules, 'counts' => $counts,
|
||||
'urgentReviewsReady' => $area === 'procurement' && app(UrgentRequisitionReviews::class)->ready() && $actor->hasFunctions(['admin', 'procurement']),
|
||||
'checkedAt' => now()->toIso8601String(), 'asOf' => $today, 'deadlineCounts' => $deadlineCounts,
|
||||
'filters' => ['module' => $filters['module'] ?? 'all', 'search' => $filters['search'] ?? '', 'due' => $filters['due'] ?? 'all'],
|
||||
'tasks' => (new LengthAwarePaginator($rows->slice(($page - 1) * 25, 25)->values(), $rows->count(), 25, $page, ['path' => $request->url()]))->withQueryString()])->toResponse($request);
|
||||
|
||||
@@ -67,6 +67,30 @@ final class CapitalRegister
|
||||
});
|
||||
}
|
||||
|
||||
/** Read-only backlink; equipment access does not grant access to a capital reference.
|
||||
* @return array{record_key:string,code:string,name:string,version:int,state:string,href:string}|null
|
||||
*/
|
||||
public function referenceForEquipment(User $actor, Equipment $equipment): ?array
|
||||
{
|
||||
if (! $this->ready() || auth()->id() !== $actor->id || $actor->tenant_id !== $equipment->tenant_id) {
|
||||
return null;
|
||||
}
|
||||
$actor = User::query()->where('tenant_id', $actor->tenant_id)->find($actor->id);
|
||||
if ($actor === null || app(OrganizationAccess::class)->maintenanceOnly($actor)
|
||||
|| ! $actor->hasFunctions(['admin', 'warehouse', 'procurement', 'finance', 'department_head'])
|
||||
|| ($actor->departmentScoped() && $actor->department_id !== $equipment->department_id)) {
|
||||
return null;
|
||||
}
|
||||
$record = $this->visible($actor)->where('tenant_id', $actor->tenant_id)->where('data->type', 'asset')
|
||||
->where('data->equipment_id', $equipment->id)->first();
|
||||
if ($record === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return ['record_key' => $record->record_key, 'code' => (string) $record->data['code'], 'name' => (string) $record->data['name'],
|
||||
'version' => $record->version, 'state' => $record->state, 'href' => '/projectos-imobilizado?history='.rawurlencode($record->record_key)];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function save(User $actor, array $input): SupplyRecord
|
||||
{
|
||||
|
||||
@@ -129,12 +129,21 @@ final class InternalRequisitionPort implements ExpiryRequisitionPort
|
||||
app(EquipmentWorkflow::class)->line($item->toArray(), $r->department_id, $r->priority);
|
||||
}
|
||||
app(CapitalAssignments::class)->assertSubmission($this->actor, $r);
|
||||
app(RequisitionAccountAssignments::class)->assertSubmission($this->actor, $r);
|
||||
app(EquipmentWorkflow::class)->assertTechnical($r);
|
||||
if ($r->needed_by < today()) {
|
||||
throw ValidationException::withMessages(['submission' => 'Actualize a data de entrega antes de submeter.']);
|
||||
}
|
||||
|
||||
$base = Tenant::query()->findOrFail($this->actor->tenant_id)->only(['first_limit_minor', 'second_limit_minor', 'approval_includes_tax', 'rules_provisional']);
|
||||
return $this->approvalPlan($r);
|
||||
}
|
||||
|
||||
/** Read-only plan shared by submission and its provisional presentation.
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function approvalPlan(Requisition $r): array
|
||||
{
|
||||
$base = Tenant::query()->findOrFail($r->tenant_id)->only(['first_limit_minor', 'second_limit_minor', 'approval_includes_tax', 'rules_provisional']);
|
||||
$estimate = app(ImportEstimates::class)->approval($r);
|
||||
$basis = $estimate['plan']['reference_totals'] ?? null;
|
||||
$amount = $basis === null ? null : $basis[$base['approval_includes_tax'] ? 'total_minor' : 'subtotal_minor'];
|
||||
|
||||
@@ -196,7 +196,7 @@ final class OrderPartsWorkflow
|
||||
$prepared = app(OrderPartsPreparation::class)->prepare($actor, $selection);
|
||||
abort_unless(hash_equals($prepared['fingerprint'], $data['fingerprint']), 409, 'A preparação mudou; consulte as origens actuais.');
|
||||
$this->checkAllocations($actor, $prepared['sources'], $budgetSources);
|
||||
$frames = $requests = $lines = $catalogue = $tariffs = $capital = [];
|
||||
$frames = $requests = $lines = $catalogue = $tariffs = $capital = $accounts = [];
|
||||
$firstQuote = null;
|
||||
foreach ($prepared['sources'] as $source) {
|
||||
$request = Requisition::query()->whereKey($source['requisition_id'])->firstOrFail();
|
||||
@@ -210,6 +210,7 @@ final class OrderPartsWorkflow
|
||||
$requested = $request->items()->get()->keyBy('id');
|
||||
$tariffs += app(ImportTariffCodes::class)->freezeForItems($actor, array_column($source['items'], 'requisition_item_id'));
|
||||
$capital += app(CapitalAssignments::class)->freezeForItems($actor, array_column($source['items'], 'requisition_item_id'));
|
||||
$accounts += app(RequisitionAccountAssignments::class)->freezeForItems($actor, array_column($source['items'], 'requisition_item_id'));
|
||||
foreach ($source['items'] as $item) {
|
||||
$native = $requested->get($item['requisition_item_id']);
|
||||
abort_unless($native !== null, 409);
|
||||
@@ -242,7 +243,7 @@ final class OrderPartsWorkflow
|
||||
$exchange = $foreign ? ['exchange_basis' => null,
|
||||
'exchange_sources' => array_map(fn ($s) => ['requisition_id' => $s['requisition_id'], 'exchange_basis' => $s['exchange_basis']], $prepared['sources']),
|
||||
'reference_amounts' => app(OrderPartsExchange::class)->sum(array_column($prepared['sources'], 'reference_amounts'))] : [];
|
||||
$snapshot = [...$frames[0], ...$limits, ...$exchange, ...($tariffs === [] ? [] : ['import_tariffs' => $tariffs]), ...($capital === [] ? [] : ['capital_assignments' => $capital]), 'company' => Tenant::query()->whereKey($actor->tenant_id)->firstOrFail()->only(['id', 'name']),
|
||||
$snapshot = [...$frames[0], ...$limits, ...$exchange, ...($tariffs === [] ? [] : ['import_tariffs' => $tariffs]), ...($capital === [] ? [] : ['capital_assignments' => $capital]), ...($accounts === [] ? [] : ['account_assignments' => $accounts]), 'company' => Tenant::query()->whereKey($actor->tenant_id)->firstOrFail()->only(['id', 'name']),
|
||||
'supplier' => $firstQuote->supplier?->only(['id', 'name', 'nuit', 'contact', 'email', 'phone', 'address']),
|
||||
'issuer' => $actor->only(['id', 'name']), 'items' => $lines, 'catalogue_sources' => $catalogue,
|
||||
'budget_control' => $commit, 'development_only' => true, 'budget_checked' => true,
|
||||
|
||||
@@ -56,7 +56,7 @@ final class ProcurementDeliveryInsights
|
||||
$today = $instant->setTimezone(config('app.timezone'))->toDateString();
|
||||
$coverage = array_fill_keys(array_keys(self::LABELS), 0);
|
||||
$records = [];
|
||||
$pendingLines = $unknownLines = 0;
|
||||
$pendingLines = $unknownLines = $unverifiedReceipts = 0;
|
||||
$reversed = array_keys(app(InventoryReversals::class)->corrections('receipt'));
|
||||
foreach (PurchaseOrder::query()->visibleTo($actor)->operational()->forRequisitions($requests)->with('items')->lazyById(100) as $order) {
|
||||
app(OrderPartsAccess::class)->origins($order);
|
||||
@@ -66,7 +66,7 @@ final class ProcurementDeliveryInsights
|
||||
->where('gr.tenant_id', $actor->tenant_id)->where('gr.purchase_order_id', $order->id)->whereNotIn('goods_receipt_items.id', $reversed)
|
||||
->orderBy('gr.received_on')->orderBy('gr.id')->orderBy('goods_receipt_items.id')
|
||||
->get(['goods_receipt_items.id', 'goods_receipt_items.purchase_order_item_id', 'goods_receipt_items.received_milli', 'gr.received_on'])->groupBy('purchase_order_item_id');
|
||||
$pending = $unknown = $latePending = $lateCompleted = $maxDays = 0;
|
||||
$pending = $unknown = $unverified = $latePending = $lateCompleted = $maxDays = 0;
|
||||
$details = [];
|
||||
foreach ($progress['lines'] as $line) {
|
||||
$item = $items->get($line['id']);
|
||||
@@ -85,10 +85,12 @@ final class ProcurementDeliveryInsights
|
||||
}
|
||||
}
|
||||
$verified = $verified && $quantity === $line['received_milli'];
|
||||
$unverified += $verified ? 0 : 1;
|
||||
$waiting = $line['received_milli'] < $line['ordered_milli'];
|
||||
$pending += $waiting ? 1 : 0;
|
||||
if (! $verified || $due === null || (! $waiting && $completed === null)) {
|
||||
$unknown++;
|
||||
|
||||
continue;
|
||||
}
|
||||
$end = $waiting ? $today : $completed;
|
||||
@@ -105,7 +107,9 @@ final class ProcurementDeliveryInsights
|
||||
$coverage[$state]++;
|
||||
$pendingLines += $pending;
|
||||
$unknownLines += $unknown;
|
||||
$unverifiedReceipts += $unverified;
|
||||
$records[] = ['id' => $order->id, 'number' => $order->number, 'state' => $state, 'pending_lines' => $pending, 'unknown_lines' => $unknown,
|
||||
'unverified_receipt_lines' => $unverified,
|
||||
'late_days' => $state === 'unknown' && $maxDays === 0 ? null : $maxDays,
|
||||
'quality_pending' => $progress['state'] === 'quality_pending', 'late_lines' => $details, 'href' => '/ordens/'.$order->id];
|
||||
}
|
||||
@@ -116,7 +120,7 @@ final class ProcurementDeliveryInsights
|
||||
$current = $page === null ? 1 : max(1, min($page, $last));
|
||||
|
||||
return ['method' => 'frozen_promised_dates_native_receipts_v1', 'generated_at' => $instant->toIso8601String(), 'view' => $view,
|
||||
'coverage' => $coverage, 'pending_lines' => $pendingLines, 'unknown_lines' => $unknownLines,
|
||||
'coverage' => $coverage, 'pending_lines' => $pendingLines, 'unknown_lines' => $unknownLines, 'unverified_receipt_lines' => $unverifiedReceipts,
|
||||
'records' => ['data' => $page === null ? $filtered : array_slice($filtered, ($current - 1) * 20, 20),
|
||||
'total' => count($filtered), 'current_page' => $current, 'last_page' => $last]];
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Tempo\Purchasing\Internal\InternalRequisitions;
|
||||
|
||||
class PurchaseWorkflow
|
||||
{
|
||||
@@ -171,7 +172,9 @@ class PurchaseWorkflow
|
||||
}
|
||||
$tariffs = app(ImportTariffCodes::class)->freezeForItems($user, array_column($lines, 'requisition_item_id'));
|
||||
$capital = app(CapitalAssignments::class)->freezeForItems($user, array_column($lines, 'requisition_item_id'));
|
||||
$accounts = app(RequisitionAccountAssignments::class)->freezeForItems($user, array_column($lines, 'requisition_item_id'));
|
||||
$snapshot = [
|
||||
...($accounts === [] ? [] : ['account_assignments' => $accounts]),
|
||||
...($capital === [] ? [] : ['capital_assignments' => $capital]),
|
||||
...($tariffs === [] ? [] : ['import_tariffs' => $tariffs]),
|
||||
...app(AgreementOrderLimits::class)->freeze($user, $quote, $requisition, $lines, $agreementBindings),
|
||||
@@ -314,7 +317,9 @@ class PurchaseWorkflow
|
||||
/** @param array{first_limit_minor: int, second_limit_minor: int, approval_includes_tax: bool, rules_provisional: bool} $rules */
|
||||
private function sourceApproved(Requisition $requisition, array $rules): void
|
||||
{
|
||||
$roles = $this->roles($rules, $rules['approval_includes_tax'] ? $requisition->total_minor : $requisition->subtotal_minor, $requisition->items()->where('purchase_type', 'equipment')->exists());
|
||||
$policy = $requisition->approval_snapshot;
|
||||
$roles = InternalRequisitions::roles(['subtotal_minor' => $requisition->subtotal_minor, 'total_minor' => $requisition->total_minor,
|
||||
'has_equipment' => $requisition->items()->where('purchase_type', 'equipment')->exists()], $policy);
|
||||
$steps = $requisition->steps()->get();
|
||||
$seen = [$requisition->requester_id];
|
||||
if ($requisition->status !== 'approved' || $steps->count() !== count($roles)) {
|
||||
@@ -322,6 +327,7 @@ class PurchaseWorkflow
|
||||
}
|
||||
foreach ($steps as $index => $step) {
|
||||
if ($step->decision !== 'approved' || $step->decided_at === null || $step->role !== $roles[$index] || $step->approver_id === null || in_array($step->approver_id, $seen, true) ||
|
||||
(isset($policy['additional_levels'][$step->role]) && $step->routing !== $policy['additional_levels'][$step->role]) ||
|
||||
! User::query()->where('tenant_id', $requisition->tenant_id)->whereKey($step->approver_id)->exists()) {
|
||||
throw ValidationException::withMessages(['approvals' => 'O histórico de aprovação da estimativa está incompleto ou inconsistente.']);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Requisition;
|
||||
use App\Models\RequisitionItem;
|
||||
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\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/** Documentary account imputations; the common ledger remains the sole journal writer. */
|
||||
final class RequisitionAccountAssignments
|
||||
{
|
||||
/** @return array{User,Requisition} */
|
||||
private function context(User $actor, Requisition $request): array
|
||||
{
|
||||
abort_unless(app(RequisitionLedgerAccounts::class)->ready(), 503);
|
||||
app(ConflictGuard::class)->lockCompany($actor);
|
||||
$actor = app(CurrentActor::class)->lock($actor);
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||
|
||||
return [$actor, Requisition::query()->visibleTo($actor)->lockForUpdate()->findOrFail($request->id)];
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function basis(RequisitionItem $item, Requisition $request): array
|
||||
{
|
||||
return ['line' => $item->only(['id', 'description', 'category', 'purchase_type', 'quantity', 'unit', 'unit_price_minor', 'tax_rate',
|
||||
'subtotal_minor', 'tax_minor', 'total_minor', 'equipment_id', 'spare_part_id', 'category_context', 'catalogue_entry_id']),
|
||||
'cost_center_id' => $request->cost_center_id, 'budget_distribution_preparation' => $request->budget_distribution_preparation];
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function workspace(User $actor, Requisition $request, string $search = ''): array
|
||||
{
|
||||
return DB::transaction(function () use ($actor, $request, $search) {
|
||||
[$actor, $request] = $this->context($actor, $request);
|
||||
$write = $request->status === 'draft' && $request->getAttribute('draft_input') === null && $request->total_minor !== null
|
||||
&& $request->requester_id === $actor->id && app(OrganizationAccess::class)->canRequest($actor)
|
||||
&& ! app(ConflictGuard::class)->participationBlocked($actor, $request);
|
||||
$items = $request->items()->orderBy('id')->get();
|
||||
|
||||
return ['requisition' => $request->only(['id', 'number', 'status']),
|
||||
'items' => $items->map(fn ($line) => [...$this->basis($line, $request)['line'], 'subtotal_minor' => (string) $line->subtotal_minor,
|
||||
'total_minor' => (string) $line->total_minor, 'basis_hash' => hash('sha256', json_encode($this->basis($line, $request), JSON_THROW_ON_ERROR))]),
|
||||
'current' => app(SupplyPlanning::class)->latest('req_account')->where('data->requisition_id', $request->id)->get(),
|
||||
'history' => SupplyRecord::query()->where('kind', 'req_account')->where('data->requisition_id', $request->id)
|
||||
->latest('id')->paginate(15, ['*'], 'history_page')->withQueryString(),
|
||||
'accounts' => $write ? app(RequisitionLedgerAccounts::class)->options($actor, $search) : null,
|
||||
'canWrite' => $write, 'search' => $search, 'actorId' => $actor->id, 'tenantId' => $actor->tenant_id];
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function save(User $actor, Requisition $request, array $input): SupplyRecord
|
||||
{
|
||||
$data = Validator::make($input, ['operation_key' => 'required|uuid', 'version' => 'required|integer|min:0', 'item_id' => 'required|integer|min:1',
|
||||
'basis_hash' => ['required', 'regex:/^[a-f0-9]{64}$/D'], 'reason' => 'required|string|min:10|max:4000',
|
||||
'allocations' => 'required|array|min:1|max:20', 'allocations.*.account_id' => 'required|integer|min:1|distinct',
|
||||
'allocations.*.source_hash' => ['required', 'regex:/^[a-f0-9]{64}$/D'],
|
||||
'allocations.*.subtotal' => ['required', 'regex:/^\d{1,18}(\.\d{1,2})?$/D'],
|
||||
'allocations.*.total' => ['required', 'regex:/^\d{1,18}(\.\d{1,2})?$/D']])->validate();
|
||||
$data['operation_key'] = strtolower($data['operation_key']);
|
||||
usort($data['allocations'], fn ($a, $b) => $a['account_id'] <=> $b['account_id']);
|
||||
$hash = hash('sha256', json_encode([$request->id, $data], JSON_THROW_ON_ERROR));
|
||||
|
||||
return DB::transaction(function () use ($actor, $request, $data, $hash) {
|
||||
[$actor, $request] = $this->context($actor, $request);
|
||||
abort_unless($request->requester_id === $actor->id && app(OrganizationAccess::class)->canRequest($actor), 403);
|
||||
app(ConflictGuard::class)->assertParticipation($actor, $request);
|
||||
$retry = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
|
||||
if ($retry !== null) {
|
||||
abort_unless($retry->kind === 'req_account' && $retry->created_by === $actor->id && hash_equals($retry->input_hash, $hash), 409);
|
||||
|
||||
return $retry;
|
||||
}
|
||||
abort_unless($request->status === 'draft', 409);
|
||||
abort_unless($request->getAttribute('draft_input') === null && $request->total_minor !== null, 409, 'Complete primeiro as linhas e os campos da requisição.');
|
||||
$item = $request->items()->whereKey($data['item_id'])->firstOrFail();
|
||||
$basis = $this->basis($item, $request);
|
||||
abort_unless(hash_equals(hash('sha256', json_encode($basis, JSON_THROW_ON_ERROR)), $data['basis_hash']), 409, 'A linha ou a distribuição mudou. Reveja a imputação.');
|
||||
$old = app(SupplyPlanning::class)->latest('req_account')->where('data->requisition_item_id', $item->id)->first();
|
||||
abort_unless((int) ($old->version ?? 0) === (int) $data['version'], 409);
|
||||
$subtotal = BigDecimal::of(0);
|
||||
$total = BigDecimal::of(0);
|
||||
$allocations = [];
|
||||
foreach ($data['allocations'] as $allocation) {
|
||||
$account = app(RequisitionLedgerAccounts::class)->resolve($actor, (int) $allocation['account_id'], $allocation['source_hash']);
|
||||
$net = BigDecimal::of($allocation['subtotal'])->multipliedBy(100)->toScale(0);
|
||||
$gross = BigDecimal::of($allocation['total'])->multipliedBy(100)->toScale(0);
|
||||
if ($gross->isLessThan($net)) {
|
||||
throw ValidationException::withMessages(['allocations' => 'O total de cada parcela não pode ser inferior à base sem IVA.']);
|
||||
}
|
||||
$subtotal = $subtotal->plus($net);
|
||||
$total = $total->plus($gross);
|
||||
$allocations[] = ['account' => $account, 'subtotal_minor' => (string) $net, 'total_minor' => (string) $gross];
|
||||
}
|
||||
if (! $subtotal->isEqualTo($item->subtotal_minor) || ! $total->isEqualTo($item->total_minor)) {
|
||||
throw ValidationException::withMessages(['allocations' => 'As parcelas devem corresponder exactamente à base sem IVA e ao total da linha.']);
|
||||
}
|
||||
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'req_account',
|
||||
'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1,
|
||||
'state' => 'assigned', 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'reason' => $data['reason'],
|
||||
'data' => ['requisition_id' => $request->id, 'requisition_item_id' => $item->id, 'allocations' => $allocations],
|
||||
'snapshot' => $basis, 'created_by' => $actor->id, 'created_at' => now()]);
|
||||
app(RequisitionWorkflow::class)->audit($actor, 'requisition.accounts_assigned', $request, $old?->toArray(), ['record' => $record->toArray()]);
|
||||
|
||||
return $record;
|
||||
});
|
||||
}
|
||||
|
||||
public function assertSubmission(User $actor, Requisition $request): void
|
||||
{
|
||||
$items = $request->items()->get();
|
||||
$ids = [];
|
||||
foreach ($items as $item) {
|
||||
$ids[] = $item->id;
|
||||
}
|
||||
$frozen = $this->freezeForItems($actor, $ids);
|
||||
if (! app(RequisitionLedgerAccounts::class)->ready()) {
|
||||
abort_if(config('requisition-accounts.qa_enabled') === true && $items->isNotEmpty(),
|
||||
503, 'Plano de contas indisponível. Não foram criadas reservas ou aprovações.');
|
||||
|
||||
return;
|
||||
}
|
||||
foreach ($items as $item) {
|
||||
if (! isset($frozen[$item->id])) {
|
||||
throw ValidationException::withMessages(['account_assignment' => 'Indique a conta contabilística de cada linha antes de submeter. Não foram criadas reservas ou aprovações.']);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @param list<int> $ids
|
||||
* @return array<int,array<string,mixed>>
|
||||
*/
|
||||
public function freezeForItems(User $actor, array $ids): array
|
||||
{
|
||||
if (! Schema::hasTable('supply_records')) {
|
||||
return [];
|
||||
}
|
||||
$records = app(SupplyPlanning::class)->latest('req_account')->whereIn('data->requisition_item_id', $ids)->get();
|
||||
if ($records->isEmpty()) {
|
||||
return [];
|
||||
}
|
||||
abort_unless(app(RequisitionLedgerAccounts::class)->ready(), 503, 'Preserve a origem das contas atribuídas antes de prosseguir.');
|
||||
$result = [];
|
||||
foreach ($records as $record) {
|
||||
$audit = DB::table('audit_logs')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $record->data['requisition_id'])
|
||||
->where('action', 'requisition.accounts_assigned')->where('user_id', $record->created_by)->where('after->record->id', $record->id)->first();
|
||||
$saved = $audit === null ? null : json_decode($audit->after, true, 64, JSON_THROW_ON_ERROR)['record'] ?? null;
|
||||
abort_unless(is_array($saved) && ($saved['data'] ?? null) === $record->data && ($saved['snapshot'] ?? null) === $record->snapshot
|
||||
&& ($saved['version'] ?? null) === $record->version && ($saved['input_hash'] ?? null) === $record->input_hash, 409,
|
||||
'A imputação não corresponde ao registo auditado. Confira a origem antes de prosseguir.');
|
||||
$item = RequisitionItem::query()->whereKey($record->data['requisition_item_id'])->firstOrFail();
|
||||
$request = Requisition::query()->visibleTo($actor)->whereKey($item->requisition_id)->firstOrFail();
|
||||
abort_unless($record->snapshot === $this->basis($item, $request), 409, 'A linha ou a distribuição mudou. Reveja a imputação contabilística.');
|
||||
$result[$item->id] = $record->only(['id', 'version', 'data', 'snapshot', 'reason']);
|
||||
}
|
||||
ksort($result, SORT_NUMERIC);
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Requisition;
|
||||
use App\Models\RequisitionItem;
|
||||
use App\Models\User;
|
||||
|
||||
/** Advisory exact-content comparison, never an eligibility or approval rule. */
|
||||
final class RequisitionDuplicateHints
|
||||
{
|
||||
/** @return list<string> */
|
||||
private function lines(Requisition $request): array
|
||||
{
|
||||
$rows = $request->items->map(function (RequisitionItem $item): string {
|
||||
return json_encode($item->only(['description', 'category', 'purchase_type', 'quantity', 'unit', 'unit_price_minor',
|
||||
'tax_rate', 'equipment_id', 'spare_part_id', 'production_area', 'downtime_started_at', 'catalogue_entry_id', 'category_context']), JSON_THROW_ON_ERROR);
|
||||
})->all();
|
||||
sort($rows, SORT_STRING);
|
||||
|
||||
return $rows;
|
||||
}
|
||||
|
||||
/** @return array{matches:list<array{id:int,number:string,status:string}>,complete:bool}|null */
|
||||
public function for(User $actor, Requisition $request): ?array
|
||||
{
|
||||
if ($request->status !== 'draft' || $request->requester_id !== $actor->id || $request->tenant_id !== $actor->tenant_id
|
||||
|| ! app(OrganizationAccess::class)->canRequest($actor) || app(OrganizationAccess::class)->maintenanceOnly($actor)
|
||||
|| $request->total_minor === null || $request->needed_by === null || $request->items->isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
$source = $this->lines($request);
|
||||
$candidates = Requisition::query()->visibleTo($actor)->where('requester_id', $actor->id)->where('id', '!=', $request->id)
|
||||
->whereIn('status', ['draft', 'pending', 'approved'])->where('cost_center_id', $request->cost_center_id)
|
||||
->whereDate('needed_by', $request->needed_by->toDateString())->where('total_minor', $request->total_minor)
|
||||
->latest('id')->limit(101)->with('items')->get();
|
||||
$matches = [];
|
||||
foreach ($candidates->take(100) as $candidate) {
|
||||
if ($this->lines($candidate) === $source) {
|
||||
$matches[] = ['id' => $candidate->id, 'number' => $candidate->number, 'status' => $candidate->status];
|
||||
}
|
||||
}
|
||||
|
||||
return ['matches' => $matches, 'complete' => $candidates->count() <= 100];
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ use App\Models\Requisition;
|
||||
use App\Models\SupplyRecord;
|
||||
use App\Models\User;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
@@ -109,8 +110,31 @@ final class RequisitionExpiry
|
||||
$deadline = $this->deadline($request);
|
||||
unset($deadline['profile_ids']);
|
||||
$history = SupplyRecord::query()->where('kind', 'req_expiration')->where('data->requisition_id', $request->id)->latest('id')->paginate(15)->withQueryString();
|
||||
$history->through(fn ($row) => ['id' => $row->id, 'data' => $row->data, 'reason' => $row->reason,
|
||||
'request' => $row->snapshot['request'], 'steps' => $row->snapshot['steps'], 'created_at' => $row->created_at]);
|
||||
$history->through(function (SupplyRecord $row) {
|
||||
$sourceItems = $row->snapshot['items'] ?? null;
|
||||
$items = null;
|
||||
if (is_array($sourceItems)) {
|
||||
$items = [];
|
||||
foreach ($sourceItems as $item) {
|
||||
if (! is_array($item)) {
|
||||
$items = null;
|
||||
break;
|
||||
}
|
||||
$items[] = Arr::only($item, ['id', 'description', 'category', 'quantity', 'unit', 'unit_price_minor', 'tax_rate', 'subtotal_minor', 'tax_minor', 'total_minor']);
|
||||
}
|
||||
}
|
||||
$rules = $row->snapshot['approval_snapshot'] ?? null;
|
||||
$basis = is_array($rules) ? ($rules['approval_basis'] ?? $row->snapshot['request']) : null;
|
||||
$basisField = is_array($rules) && is_bool($rules['approval_includes_tax'] ?? null)
|
||||
? ($rules['approval_includes_tax'] ? 'total_minor' : 'subtotal_minor') : null;
|
||||
$approvalAmount = is_array($basis) && $basisField !== null ? ($basis[$basisField] ?? null) : null;
|
||||
|
||||
return ['id' => $row->id, 'data' => $row->data, 'reason' => $row->reason,
|
||||
'request' => $row->snapshot['request'], 'steps' => $row->snapshot['steps'], 'created_at' => $row->created_at,
|
||||
'items' => $items, 'rules' => is_array($rules) ? Arr::only($rules, ['first_limit_minor', 'second_limit_minor', 'approval_includes_tax', 'rules_provisional', 'routing_plan_revision']) : [],
|
||||
'approval_amount_minor' => is_int($approvalAmount) && $approvalAmount >= 0 ? $approvalAmount : null,
|
||||
'approval_uses_separate_basis' => is_array($rules) && is_array($rules['approval_basis'] ?? null)];
|
||||
});
|
||||
|
||||
return ['requisition' => [...$request->only(['id', 'number', 'status', 'process_version', 'requester_id']),
|
||||
'approval_cycle' => $request->getAttribute('approval_cycle') ?? 1], 'deadline' => $deadline, 'history' => $history,
|
||||
@@ -127,25 +151,44 @@ final class RequisitionExpiry
|
||||
{
|
||||
abort_unless($this->ready(), 503);
|
||||
$data = Validator::make($input, ['operation_key' => 'required|uuid', 'version' => 'required|integer|min:0', 'enabled' => 'required|boolean',
|
||||
'levels' => 'present|array|list|max:8', 'levels.*' => 'array:role,expire_minutes,reminder_minutes,escalation_minutes,profile_ids',
|
||||
'levels' => 'present|array|list|max:8', 'levels.*' => 'array:role,expire_minutes,reminder_minutes,escalation_minutes,profile_ids,urgent_expire_minutes,urgent_reminder_minutes,urgent_escalation_minutes',
|
||||
'levels.*.role' => ['required', 'distinct', Rule::in(self::ROLES)], 'levels.*.expire_minutes' => 'required|integer|min:1|max:5256000',
|
||||
'levels.*.reminder_minutes' => 'present|nullable|integer|min:1|max:5256000',
|
||||
'levels.*.escalation_minutes' => 'present|nullable|integer|min:1|max:5256000', 'levels.*.profile_ids' => 'present|array|list|max:50',
|
||||
'levels.*.profile_ids.*' => 'required|distinct|integer|min:1', 'reason' => 'required|string|min:10|max:4000'])->validate();
|
||||
'levels.*.profile_ids.*' => 'required|distinct|integer|min:1',
|
||||
'levels.*.urgent_expire_minutes' => 'sometimes|nullable|integer|min:1|max:5256000',
|
||||
'levels.*.urgent_reminder_minutes' => 'sometimes|nullable|integer|min:1|max:5256000',
|
||||
'levels.*.urgent_escalation_minutes' => 'sometimes|nullable|integer|min:1|max:5256000',
|
||||
'reason' => 'required|string|min:10|max:4000'])->validate();
|
||||
$data['operation_key'] = strtolower($data['operation_key']);
|
||||
$data['enabled'] = (bool) $data['enabled'];
|
||||
foreach ($data['levels'] as $index => &$level) {
|
||||
foreach (['expire_minutes', 'reminder_minutes', 'escalation_minutes'] as $field) {
|
||||
$level[$field] = $level[$field] === null ? null : (int) $level[$field];
|
||||
if (array_key_exists('urgent_'.$field, $level)) {
|
||||
$level['urgent_'.$field] = $level['urgent_'.$field] === null ? null : (int) $level['urgent_'.$field];
|
||||
}
|
||||
}
|
||||
$level['profile_ids'] = array_map(intval(...), $level['profile_ids']);
|
||||
sort($level['profile_ids'], SORT_NUMERIC);
|
||||
if (($level['reminder_minutes'] !== null && $level['reminder_minutes'] >= $level['expire_minutes'])
|
||||
|| ($level['escalation_minutes'] !== null && ($level['escalation_minutes'] >= $level['expire_minutes'] || $level['profile_ids'] === []))
|
||||
|| ($level['reminder_minutes'] !== null && $level['escalation_minutes'] !== null && $level['reminder_minutes'] >= $level['escalation_minutes'])
|
||||
|| ($level['escalation_minutes'] === null && $level['profile_ids'] !== [])) {
|
||||
|| ($level['escalation_minutes'] === null && ($level['urgent_escalation_minutes'] ?? null) === null && $level['profile_ids'] !== [])) {
|
||||
throw ValidationException::withMessages(['levels.'.$index => 'Configure lembrete e escalamento antes da expiração, com destinatários explícitos apenas quando houver escalamento.']);
|
||||
}
|
||||
$urgent = $level['urgent_expire_minutes'] ?? null;
|
||||
$reminder = $level['urgent_reminder_minutes'] ?? null;
|
||||
$escalation = $level['urgent_escalation_minutes'] ?? null;
|
||||
if (($urgent === null && ($reminder !== null || $escalation !== null))
|
||||
|| ($urgent !== null && ($urgent >= $level['expire_minutes']
|
||||
|| ($reminder !== null && $reminder >= $urgent)
|
||||
|| ($escalation !== null && ($escalation >= $urgent || $level['profile_ids'] === []))
|
||||
|| ($reminder !== null && $escalation !== null && $reminder >= $escalation)
|
||||
|| ($level['reminder_minutes'] !== null && ($reminder === null || $reminder >= $level['reminder_minutes']))
|
||||
|| ($level['escalation_minutes'] !== null && ($escalation === null || $escalation >= $level['escalation_minutes']))))) {
|
||||
throw ValidationException::withMessages(['levels.'.$index => 'Nas urgências, indique prazos reduzidos e conserve os alertas configurados, antes da expiração, com destinatários explícitos.']);
|
||||
}
|
||||
}
|
||||
unset($level);
|
||||
usort($data['levels'], fn ($a, $b) => strcmp($a['role'], $b['role']));
|
||||
@@ -193,7 +236,7 @@ final class RequisitionExpiry
|
||||
return null;
|
||||
}
|
||||
|
||||
return ['id' => $source->id, 'version' => $source->version, 'data' => $source->data,
|
||||
return ['id' => $source->id, 'version' => $source->version, 'data' => $source->data, 'request_priority' => $request->priority,
|
||||
'fingerprint' => hash('sha256', json_encode($source->data, JSON_THROW_ON_ERROR))];
|
||||
}
|
||||
|
||||
@@ -212,6 +255,7 @@ final class RequisitionExpiry
|
||||
$source = SupplyRecord::query()->where('kind', 'req_expiry_policy')->whereKey($policy['id'])->firstOrFail();
|
||||
abort_unless($source->version === $policy['version'] && $source->data === $policy['data']
|
||||
&& hash_equals(hash('sha256', json_encode($source->data, JSON_THROW_ON_ERROR)), $policy['fingerprint']), 409, 'A política preservada requer conferência.');
|
||||
abort_unless(! isset($policy['request_priority']) || $policy['request_priority'] === $request->priority, 409, 'A prioridade diverge da submissão preservada.');
|
||||
$steps = $request->steps()->orderBy('position')->get();
|
||||
$step = $steps->firstWhere('decision', 'pending');
|
||||
$settings = null;
|
||||
@@ -226,6 +270,13 @@ final class RequisitionExpiry
|
||||
if ($step === null || $settings === null || $request->submitted_at === null) {
|
||||
return [...$inactive, 'state' => 'unconfigured', 'step_id' => $step?->id];
|
||||
}
|
||||
$timing = 'standard';
|
||||
if (($policy['request_priority'] ?? null) === 'urgent' && ($settings['urgent_expire_minutes'] ?? null) !== null) {
|
||||
foreach (['expire_minutes', 'reminder_minutes', 'escalation_minutes'] as $field) {
|
||||
$settings[$field] = $settings['urgent_'.$field] ?? null;
|
||||
}
|
||||
$timing = 'urgent_override';
|
||||
}
|
||||
$start = CarbonImmutable::parse($request->submitted_at);
|
||||
foreach ($steps->where('position', '<', $step->position) as $previous) {
|
||||
if ($previous->decision !== 'approved' || $previous->decided_at === null) {
|
||||
@@ -242,9 +293,9 @@ final class RequisitionExpiry
|
||||
}
|
||||
$end = $start->addMinutes($settings['expire_minutes']);
|
||||
$basis = [$request->id, $request->getAttribute('approval_cycle') ?? 1, $request->getAttribute('process_version'), $step->id,
|
||||
$policy['fingerprint'], $start->toIso8601String(), $end->toIso8601String()];
|
||||
$policy['fingerprint'], $start->toIso8601String(), $end->toIso8601String(), ...($timing === 'urgent_override' ? ['urgent_override'] : [])];
|
||||
|
||||
return ['state' => now()->greaterThanOrEqualTo($end) ? 'expired' : 'running', 'step_id' => $step->id,
|
||||
return ['state' => now()->greaterThanOrEqualTo($end) ? 'expired' : 'running', 'step_id' => $step->id, 'timing' => $timing,
|
||||
'started_at' => $start->toIso8601String(), 'expires_at' => $end->toIso8601String(),
|
||||
'reminder_at' => $settings['reminder_minutes'] === null ? null : $start->addMinutes($settings['reminder_minutes'])->toIso8601String(),
|
||||
'escalation_at' => $settings['escalation_minutes'] === null ? null : $start->addMinutes($settings['escalation_minutes'])->toIso8601String(),
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/** Minimal read-only catalogue of the common ledger in this Compras database. */
|
||||
final class RequisitionLedgerAccounts
|
||||
{
|
||||
public function ready(): bool
|
||||
{
|
||||
$db = DB::connection();
|
||||
|
||||
return config('requisition-accounts.qa_enabled') === true && app()->environment('testing')
|
||||
&& (($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|
||||
|| ($db->getDriverName() === 'pgsql' && $db->getConfig('host') === '127.0.0.1'
|
||||
&& preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName())))
|
||||
&& Schema::hasColumns('gl_accounts', ['id', 'tenant_id', 'company_id', 'unit_id', 'code', 'label', 'currency', 'is_movement']);
|
||||
}
|
||||
|
||||
private function query(User $actor): Builder
|
||||
{
|
||||
abort_unless($this->ready(), 503, 'Plano de contas do núcleo comum indisponível nesta composição.');
|
||||
abort_unless(auth()->id() === $actor->id && $actor->tenant_id !== null, 403);
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||
|
||||
// Standalone Compras uses its existing native company/unit zero context.
|
||||
// Only code/label/currency are exposed; ledger balances, grants and journals are never read.
|
||||
return DB::table('gl_accounts')->where(['tenant_id' => $actor->tenant_id, 'company_id' => 0, 'unit_id' => 0]);
|
||||
}
|
||||
|
||||
/** @return array{id:int,code:string,label:string,currency:string,source_hash:string} */
|
||||
private function row(\stdClass $account): array
|
||||
{
|
||||
$source = ['id' => (int) $account->id, 'tenant_id' => (int) $account->tenant_id, 'company_id' => (int) $account->company_id,
|
||||
'unit_id' => (int) $account->unit_id, 'code' => (string) $account->code, 'label' => (string) $account->label,
|
||||
'currency' => (string) $account->currency, 'is_movement' => (bool) $account->is_movement];
|
||||
|
||||
return ['id' => $source['id'], 'code' => $source['code'], 'label' => $source['label'], 'currency' => $source['currency'],
|
||||
'source_hash' => hash('sha256', json_encode($source, JSON_THROW_ON_ERROR))];
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function options(User $actor, string $search = ''): array
|
||||
{
|
||||
abort_unless(app(OrganizationAccess::class)->canRequest($actor), 403);
|
||||
$query = $this->query($actor)->where('is_movement', true)->where('currency', 'MZN');
|
||||
$search = trim($search);
|
||||
if ($search !== '') {
|
||||
// Literal substring search: user wildcards never widen the catalogue unexpectedly.
|
||||
$search = str_replace(['!', '%', '_'], ['!!', '!%', '!_'], $search);
|
||||
$query->where(fn ($q) => $q->whereRaw("LOWER(code) LIKE LOWER(?) ESCAPE '!'", ['%'.$search.'%'])
|
||||
->orWhereRaw("LOWER(label) LIKE LOWER(?) ESCAPE '!'", ['%'.$search.'%']));
|
||||
}
|
||||
$page = $query->orderBy('code')->orderBy('id')->paginate(20, ['*'], 'accounts_page')->withQueryString();
|
||||
$page->setCollection($page->getCollection()->map(fn ($row) => $this->row($row)));
|
||||
|
||||
return $page->toArray();
|
||||
}
|
||||
|
||||
/** Current movement account, checked again inside the host's company transaction. No account is created.
|
||||
* @return array{id:int,code:string,label:string,currency:string,source_hash:string}
|
||||
*/
|
||||
public function resolve(User $actor, int $id, string $hash): array
|
||||
{
|
||||
$account = $this->query($actor)->where('id', $id)->where('is_movement', true)->where('currency', 'MZN')->first();
|
||||
abort_unless($account !== null, 409, 'Conta indisponível no plano próprio de Compras.');
|
||||
$row = $this->row($account);
|
||||
abort_unless(hash_equals($row['source_hash'], $hash), 409, 'A conta mudou. Confira a referência actual antes de guardar.');
|
||||
|
||||
return $row;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Requisition;
|
||||
use App\Models\User;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
use Tempo\Purchasing\Internal\InternalRequisitions;
|
||||
use Tempo\Purchasing\Internal\RequisitionFailure;
|
||||
|
||||
/** Provisional presentation only: no reservation, authorization grant or command receipt. */
|
||||
final class RequisitionSubmissionPreview
|
||||
{
|
||||
/** @return array<string,mixed>|null */
|
||||
public function for(User $viewer, Requisition $request): ?array
|
||||
{
|
||||
if (auth()->id() !== $viewer->id) {
|
||||
return null;
|
||||
}
|
||||
$actor = User::query()->findOrFail($viewer->id);
|
||||
if ($actor->tenant_id !== $request->tenant_id || $request->requester_id !== $actor->id || $request->status !== 'draft'
|
||||
|| ! app(OrganizationAccess::class)->canRequest($actor) || app(OrganizationAccess::class)->maintenanceOnly($actor)) {
|
||||
return null;
|
||||
}
|
||||
Requisition::query()->visibleTo($actor)->findOrFail($request->id);
|
||||
if ($request->getAttribute('draft_input') !== null || $request->total_minor === null || $request->subtotal_minor === null) {
|
||||
return ['state' => 'incomplete', 'message' => 'Complete e guarde o pedido antes de conferir a submissão.'];
|
||||
}
|
||||
try {
|
||||
$port = new InternalRequisitionPort($actor, static function (): never {
|
||||
throw new \LogicException('A conferência não pode gravar a requisição.');
|
||||
});
|
||||
$policy = $port->approvalPlan($request);
|
||||
$record = ['subtotal_minor' => $request->subtotal_minor, 'total_minor' => $request->total_minor,
|
||||
'has_equipment' => $request->items()->where('purchase_type', 'equipment')->exists()];
|
||||
$roles = InternalRequisitions::roles($record, $policy);
|
||||
$basis = $policy['approval_basis'] ?? $record;
|
||||
|
||||
return ['state' => 'planned', 'process_version' => $request->getAttribute('process_version'),
|
||||
'subtotal_minor' => (string) $request->subtotal_minor, 'total_minor' => (string) $request->total_minor,
|
||||
'approval_amount_minor' => (string) $basis[$policy['approval_includes_tax'] ? 'total_minor' : 'subtotal_minor'],
|
||||
'includes_tax' => $policy['approval_includes_tax'], 'provisional_rules' => $policy['rules_provisional'],
|
||||
'import_basis' => isset($policy['import_estimate']),
|
||||
'steps' => array_map(fn ($role) => ['role' => $role, 'label' => $policy['additional_levels'][$role]['name'] ?? null], $roles)];
|
||||
} catch (ValidationException $error) {
|
||||
return ['state' => 'unavailable', 'message' => collect($error->errors())->flatten()->first()];
|
||||
} catch (HttpExceptionInterface|RequisitionFailure $error) {
|
||||
$status = $error instanceof RequisitionFailure ? $error->status : $error->getStatusCode();
|
||||
if (! in_array($status, [409, 422, 503], true)) {
|
||||
throw $error;
|
||||
}
|
||||
|
||||
return ['state' => 'unavailable', 'message' => $error->getMessage()];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Requisition;
|
||||
use App\Models\SupplyRecord;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
|
||||
/** Posterior documentary review of a concluded cycle, never another approval or financial writer. */
|
||||
final class UrgentRequisitionReviews
|
||||
{
|
||||
public function ready(): bool
|
||||
{
|
||||
$db = DB::connection();
|
||||
|
||||
return config('urgent-reviews.qa_enabled') === true && app()->environment('testing')
|
||||
&& (($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|
||||
|| ($db->getDriverName() === 'pgsql' && $db->getConfig('host') === '127.0.0.1'
|
||||
&& preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName())));
|
||||
}
|
||||
|
||||
private function actor(User $actor, bool $settings = false, bool $write = true): User
|
||||
{
|
||||
abort_unless($this->ready(), 503);
|
||||
if ($write) {
|
||||
app(ConflictGuard::class)->lockCompany($actor);
|
||||
$actor = app(CurrentActor::class)->lock($actor);
|
||||
} else {
|
||||
abort_unless(auth()->id() === $actor->id && $actor->tenant_id !== null, 403);
|
||||
$actor = User::query()->where('tenant_id', $actor->tenant_id)->whereKey($actor->id)->firstOrFail();
|
||||
}
|
||||
abort_unless($actor->hasFunctions($settings ? ['admin'] : ['admin', 'procurement']) && ! app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||
|
||||
return $actor;
|
||||
}
|
||||
|
||||
public function canReview(User $actor): bool
|
||||
{
|
||||
if (! $this->ready() || auth()->id() !== $actor->id) {
|
||||
return false;
|
||||
}
|
||||
$actor = User::query()->where('tenant_id', $actor->tenant_id)->whereKey($actor->id)->first();
|
||||
if ($actor === null || ! $actor->hasFunctions(['procurement']) || app(OrganizationAccess::class)->maintenanceOnly($actor)) {
|
||||
return false;
|
||||
}
|
||||
$policy = SupplyRecord::query()->where('kind', 'urgent_review_policy')->latest('id')->first();
|
||||
if ($policy === null || $policy->state !== 'active') {
|
||||
return false;
|
||||
}
|
||||
$members = DB::table('organization_memberships as m')->join('organization_profiles as p', 'p.id', '=', 'm.profile_id')
|
||||
->where('m.tenant_id', $actor->tenant_id)->where('p.tenant_id', $actor->tenant_id)->where('m.user_id', $actor->id)
|
||||
->whereIn('p.id', $policy->data['profile_ids'])->where('m.maintenance', false)
|
||||
->where(fn ($q) => $q->whereNull('m.expires_at')->orWhere('m.expires_at', '>', now()));
|
||||
if (app(WorkContext::class)->enforced($actor)) {
|
||||
$members->whereJsonContains('p.work_contexts', 'procurement.internal');
|
||||
}
|
||||
|
||||
return $members->exists();
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function settings(User $actor): array
|
||||
{
|
||||
return DB::transaction(function () use ($actor) {
|
||||
$actor = $this->actor($actor, true, false);
|
||||
|
||||
return ['current' => SupplyRecord::query()->where('kind', 'urgent_review_policy')->latest('id')->first(),
|
||||
'history' => SupplyRecord::query()->where('kind', 'urgent_review_policy')->latest('id')->paginate(15)->withQueryString(),
|
||||
'profiles' => DB::table('organization_profiles')->where('tenant_id', $actor->tenant_id)->orderBy('name')->get(['id', 'name']),
|
||||
'actorId' => $actor->id, 'tenantId' => $actor->tenant_id];
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function savePolicy(User $actor, array $input): SupplyRecord
|
||||
{
|
||||
$data = Validator::make($input, ['operation_key' => 'required|uuid', 'version' => 'required|integer|min:0', 'enabled' => 'required|boolean',
|
||||
'profile_ids' => 'present|array|list|max:50', 'profile_ids.*' => 'required|integer|min:1|distinct', 'reason' => 'required|string|min:10|max:4000'])->validate();
|
||||
$data['operation_key'] = strtolower($data['operation_key']);
|
||||
$data['enabled'] = (bool) $data['enabled'];
|
||||
$data['profile_ids'] = array_map(intval(...), $data['profile_ids']);
|
||||
sort($data['profile_ids'], SORT_NUMERIC);
|
||||
$hash = hash('sha256', json_encode($data, JSON_THROW_ON_ERROR));
|
||||
|
||||
return DB::transaction(function () use ($actor, $data, $hash) {
|
||||
$actor = $this->actor($actor, true);
|
||||
$retry = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
|
||||
if ($retry !== null) {
|
||||
abort_unless($retry->kind === 'urgent_review_policy' && $retry->created_by === $actor->id && hash_equals($retry->input_hash, $hash), 409);
|
||||
|
||||
return $retry;
|
||||
}
|
||||
abort_unless(! $data['enabled'] || $data['profile_ids'] !== [], 422, 'Seleccione os perfis responsáveis pela revisão posterior.');
|
||||
abort_unless(DB::table('organization_profiles')->where('tenant_id', $actor->tenant_id)->whereIn('id', $data['profile_ids'])->count() === count($data['profile_ids']), 422);
|
||||
$old = SupplyRecord::query()->where('kind', 'urgent_review_policy')->latest('id')->first();
|
||||
abort_unless((int) $data['version'] === ($old->version ?? 0), 409);
|
||||
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'urgent_review_policy',
|
||||
'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1, 'state' => $data['enabled'] ? 'active' : 'inactive',
|
||||
'data' => ['enabled' => $data['enabled'], 'profile_ids' => $data['profile_ids'], 'trigger' => 'final_decision_including_rejection_expiry'],
|
||||
'snapshot' => ['new_permissions' => false, 'financial_effects' => false], 'reason' => $data['reason'], 'created_by' => $actor->id,
|
||||
'created_at' => now(), 'operation_key' => $data['operation_key'], 'input_hash' => $hash]);
|
||||
app(RequisitionWorkflow::class)->audit($actor, 'urgent.review_policy_saved', null, $old?->toArray(), ['record' => $record->toArray()]);
|
||||
|
||||
return $record;
|
||||
});
|
||||
}
|
||||
|
||||
/** Resolve the actual concluded cycle; drafts/pending work and later edited drafts are never substituted.
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
private function source(User $actor, int $id, int $cycle): array
|
||||
{
|
||||
$request = Requisition::query()->visibleTo($actor)->whereKey($id)->firstOrFail();
|
||||
$expiration = SupplyRecord::query()->where('kind', 'req_expiration')->where('data->requisition_id', $id)->where('data->cycle', $cycle)->first();
|
||||
if ($expiration !== null) {
|
||||
$header = $expiration->snapshot['request'] ?? null;
|
||||
abort_unless(is_array($header) && is_array($expiration->snapshot['items'] ?? null) && is_array($expiration->snapshot['steps'] ?? null), 409,
|
||||
'O ciclo expirado exige conferência dos dados preservados.');
|
||||
abort_unless(($header['priority'] ?? null) === 'urgent', 404);
|
||||
$audit = DB::table('audit_logs')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $id)
|
||||
->where('action', 'requisition.expired_returned')->where('after->expiration_record_id', $expiration->id)->first();
|
||||
abort_unless($audit !== null && is_string($audit->before) && json_decode($audit->before, true, 64, JSON_THROW_ON_ERROR) === $header, 409, 'A expiração exige conferência da sua origem auditada.');
|
||||
$source = ['kind' => 'expiry', 'id' => $expiration->id, 'outcome' => 'expired', 'closed_at' => (string) $expiration->created_at,
|
||||
'request' => $header, 'items' => $expiration->snapshot['items'], 'steps' => $expiration->snapshot['steps']];
|
||||
} else {
|
||||
abort_unless($request->priority === 'urgent' && in_array($request->status, ['approved', 'rejected'], true)
|
||||
&& (int) ($request->getAttribute('approval_cycle') ?? 1) === $cycle, 409, 'O ciclo ainda não tem uma decisão final disponível para revisão.');
|
||||
$steps = $request->steps()->get();
|
||||
abort_unless($steps->isNotEmpty() && ($request->status !== 'approved' || $steps->every(fn ($step) => $step->decision === 'approved')), 409,
|
||||
'As etapas preservadas não demonstram a conclusão da aprovação.');
|
||||
$audit = DB::table('audit_logs')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $id)
|
||||
->where('action', 'approval.'.$request->status)->where('after->status', $request->status)->whereIn('after->step_id', $steps->modelKeys())->latest('id')->first();
|
||||
abort_unless($audit !== null, 409, 'A decisão final exige conferência da sua origem auditada.');
|
||||
$decision = json_decode($audit->after, true, 64, JSON_THROW_ON_ERROR);
|
||||
abort_unless($steps->where('id', $decision['step_id'])->where('decision', $request->status)->isNotEmpty(), 409);
|
||||
$source = ['kind' => 'decision', 'id' => $audit->id, 'outcome' => $request->status, 'closed_at' => $audit->created_at,
|
||||
'request' => $request->only(['id', 'number', 'requester_id', 'department_id', 'cost_center_id', 'priority', 'needed_by', 'justification', 'subtotal_minor', 'tax_minor', 'total_minor']),
|
||||
'items' => $request->items()->orderBy('id')->get()->toArray(), 'steps' => $steps->toArray()];
|
||||
}
|
||||
abort_unless($source['items'] !== [] && $source['steps'] !== [], 409, 'O ciclo concluído exige conferência das linhas e etapas conservadas.');
|
||||
foreach ($source['steps'] as $step) {
|
||||
abort_unless(is_array($step) && isset($step['id'], $step['role'], $step['decision']), 409, 'As etapas conservadas exigem conferência.');
|
||||
}
|
||||
foreach (['subtotal_minor', 'tax_minor', 'total_minor'] as $field) {
|
||||
$source['request'][$field] = isset($source['request'][$field]) ? (string) $source['request'][$field] : null;
|
||||
}
|
||||
foreach ($source['items'] as &$item) {
|
||||
abort_unless(is_array($item) && isset($item['id'], $item['description'], $item['quantity'], $item['unit']), 409,
|
||||
'As linhas conservadas exigem conferência antes da revisão.');
|
||||
foreach (['unit_price_minor', 'subtotal_minor', 'tax_minor', 'total_minor'] as $field) {
|
||||
$item[$field] = isset($item[$field]) ? (string) $item[$field] : null;
|
||||
}
|
||||
}
|
||||
unset($item);
|
||||
$source['cycle'] = $cycle;
|
||||
$source['fingerprint'] = hash('sha256', json_encode($source, JSON_THROW_ON_ERROR));
|
||||
|
||||
return $source;
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function workspace(User $actor, int $id, int $cycle): array
|
||||
{
|
||||
return DB::transaction(function () use ($actor, $id, $cycle) {
|
||||
$actor = $this->actor($actor, false, false);
|
||||
$source = $this->source($actor, $id, $cycle);
|
||||
$current = $this->current($id, $cycle);
|
||||
$audited = $current === null || $this->audited($current);
|
||||
$verified = $audited && ($current === null || ($current->snapshot['fingerprint'] ?? null) === $source['fingerprint']);
|
||||
|
||||
return ['source' => $source, 'current' => $current, 'currentVerified' => $verified,
|
||||
'canReview' => $this->canReview($actor) && $audited,
|
||||
'history' => SupplyRecord::query()->where('kind', 'urgent_review')->where('data->requisition_id', $id)->where('data->cycle', $cycle)
|
||||
->latest('id')->paginate(15)->withQueryString(), 'actorId' => $actor->id, 'tenantId' => $actor->tenant_id];
|
||||
});
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function queue(User $actor, ?int $page = 1, string $state = 'pending'): array
|
||||
{
|
||||
return DB::transaction(function () use ($actor, $page, $state) {
|
||||
$actor = $this->actor($actor, false, false);
|
||||
$candidates = [];
|
||||
foreach (Requisition::query()->visibleTo($actor)->where('priority', 'urgent')->whereIn('status', ['approved', 'rejected'])->lazyById(100) as $request) {
|
||||
$cycle = (int) ($request->getAttribute('approval_cycle') ?? 1);
|
||||
$candidates[$request->id.':'.$cycle] = ['request_id' => $request->id, 'cycle' => $cycle, 'number' => $request->number,
|
||||
'outcome' => $request->status];
|
||||
}
|
||||
foreach (SupplyRecord::query()->where('kind', 'req_expiration')->where('snapshot->request->priority', 'urgent')->lazyById(100) as $expiration) {
|
||||
$id = (int) $expiration->data['requisition_id'];
|
||||
$visible = Requisition::query()->visibleTo($actor)->whereKey($id)->first(['id', 'number']);
|
||||
if ($visible === null) {
|
||||
continue;
|
||||
}
|
||||
$cycle = (int) $expiration->data['cycle'];
|
||||
$candidates[$id.':'.$cycle] = ['request_id' => $id, 'cycle' => $cycle, 'number' => $expiration->snapshot['request']['number'] ?? $visible->number,
|
||||
'outcome' => 'expired'];
|
||||
}
|
||||
$coverage = ['pending' => 0, 'reviewed' => 0, 'indeterminate' => 0];
|
||||
$rows = [];
|
||||
foreach ($candidates as $key => $candidate) {
|
||||
$status = 'indeterminate';
|
||||
$closed = null;
|
||||
try {
|
||||
$source = $this->source($actor, $candidate['request_id'], $candidate['cycle']);
|
||||
$closed = $source['closed_at'];
|
||||
$review = $this->current($candidate['request_id'], $candidate['cycle']);
|
||||
$status = $review === null ? 'pending' : ($this->audited($review) && ($review->snapshot['fingerprint'] ?? null) === $source['fingerprint'] ? 'reviewed' : 'indeterminate');
|
||||
} catch (HttpExceptionInterface $error) {
|
||||
if ($error->getStatusCode() !== 409) {
|
||||
throw $error;
|
||||
}
|
||||
}
|
||||
$coverage[$status]++;
|
||||
if ($state === 'all' || $state === $status) {
|
||||
$rows[] = [...$candidate, 'key' => $key, 'status' => $status, 'closed_at' => $closed,
|
||||
'href' => $status === 'indeterminate' ? '/requisicoes/'.$candidate['request_id']
|
||||
: '/requisicoes/'.$candidate['request_id'].'/ciclos/'.$candidate['cycle'].'/revisao-urgencia'];
|
||||
}
|
||||
}
|
||||
usort($rows, fn ($a, $b) => strcmp($a['closed_at'] ?? '', $b['closed_at'] ?? '') ?: strcmp($a['key'], $b['key']));
|
||||
$last = max(1, (int) ceil(count($rows) / 20));
|
||||
$current = $page === null ? 1 : max(1, min($last, $page));
|
||||
|
||||
return ['coverage' => $coverage, 'state' => $state, 'canReview' => $this->canReview($actor),
|
||||
'canConfigure' => $actor->hasFunctions(['admin']), 'records' => ['data' => $page === null ? $rows : array_slice($rows, ($current - 1) * 20, 20),
|
||||
'total' => count($rows), 'current_page' => $current, 'last_page' => $last]];
|
||||
});
|
||||
}
|
||||
|
||||
/** @return list<array<string,mixed>> */
|
||||
public function tasks(User $actor): array
|
||||
{
|
||||
if (! $this->canReview($actor)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return array_values(array_map(fn ($row) => ['id' => 'urgent-review:'.$row['key'], 'module' => 'purchases', 'reference' => $row['number'],
|
||||
'label' => 'Revisão posterior de urgência · ciclo '.$row['cycle'], 'task' => 'urgent_requisition_review', 'status' => 'pending',
|
||||
'blocked' => false, 'created_at' => $row['closed_at'], 'due_on' => null, 'href' => $row['href']], $this->queue($actor, null)['records']['data']));
|
||||
}
|
||||
|
||||
private function current(int $id, int $cycle): ?SupplyRecord
|
||||
{
|
||||
return SupplyRecord::query()->where('kind', 'urgent_review')->where('data->requisition_id', $id)->where('data->cycle', $cycle)->latest('version')->first();
|
||||
}
|
||||
|
||||
private function audited(SupplyRecord $record): bool
|
||||
{
|
||||
$audit = DB::table('audit_logs')->where('tenant_id', $record->tenant_id)->where('requisition_id', $record->data['requisition_id'])
|
||||
->where('action', 'urgent.review_recorded')->where('user_id', $record->created_by)->where('after->record->id', $record->id)->first();
|
||||
$saved = $audit === null || ! is_string($audit->after) ? null : json_decode($audit->after, true, 64, JSON_THROW_ON_ERROR)['record'] ?? null;
|
||||
|
||||
return is_array($saved) && ($saved['data'] ?? null) === $record->data && ($saved['snapshot'] ?? null) === $record->snapshot
|
||||
&& ($saved['version'] ?? null) === $record->version && ($saved['input_hash'] ?? null) === $record->input_hash;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function review(User $actor, int $id, int $cycle, array $input): SupplyRecord
|
||||
{
|
||||
$data = Validator::make($input, ['operation_key' => 'required|uuid', 'version' => 'required|integer|min:0',
|
||||
'source_hash' => ['required', 'regex:/^[a-f0-9]{64}$/D'], 'notes' => 'required|string|min:10|max:4000'])->validate();
|
||||
$data['operation_key'] = strtolower($data['operation_key']);
|
||||
$hash = hash('sha256', json_encode([$id, $cycle, $data], JSON_THROW_ON_ERROR));
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $cycle, $data, $hash) {
|
||||
$actor = $this->actor($actor);
|
||||
abort_unless($this->canReview($actor), 403, 'A revisão exige o perfil designado e a função de Compras actualmente válidos.');
|
||||
$source = $this->source($actor, $id, $cycle);
|
||||
$request = Requisition::query()->whereKey($id)->firstOrFail();
|
||||
app(ConflictGuard::class)->assertParticipation($actor, $request);
|
||||
$retry = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
|
||||
if ($retry !== null) {
|
||||
abort_unless($retry->kind === 'urgent_review' && $retry->created_by === $actor->id && hash_equals($retry->input_hash, $hash), 409);
|
||||
|
||||
return $retry;
|
||||
}
|
||||
abort_unless(hash_equals($source['fingerprint'], $data['source_hash']), 409, 'A origem mudou. Confira o ciclo concluído antes de registar a revisão.');
|
||||
$old = $this->current($id, $cycle);
|
||||
abort_unless($old === null || $this->audited($old), 409, 'A revisão anterior exige conferência da sua origem auditada.');
|
||||
abort_unless((int) $data['version'] === ($old->version ?? 0), 409);
|
||||
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'urgent_review',
|
||||
'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1, 'state' => 'reviewed',
|
||||
'data' => ['requisition_id' => $id, 'cycle' => $cycle, 'outcome' => $source['outcome'], 'notes' => trim($data['notes'])],
|
||||
'snapshot' => $source, 'reason' => trim($data['notes']), 'created_by' => $actor->id, 'created_at' => now(),
|
||||
'operation_key' => $data['operation_key'], 'input_hash' => $hash]);
|
||||
app(RequisitionWorkflow::class)->audit($actor, 'urgent.review_recorded', $request, $old?->toArray(), ['record' => $record->toArray()]);
|
||||
|
||||
return $record;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -51,7 +51,10 @@ class WarehouseWorkdesk
|
||||
$query = WarehouseRequest::query();
|
||||
if (! $actor->hasFunctions(['admin', 'warehouse_request_read']) && ! ($actor->hasFunctions(['warehouse_request_deliver']) && $actor->hasFunctions(['warehouse']))) {
|
||||
$query->where(function ($q) use ($actor) {
|
||||
$q->where('created_by', $actor->id);
|
||||
$q->whereRaw('1 = 0');
|
||||
if ($actor->hasFunctions(['warehouse_request_prepare'])) {
|
||||
$q->orWhere('created_by', $actor->id);
|
||||
}
|
||||
if ($actor->hasFunctions(['warehouse_request_review']) && $actor->department_id !== null) {
|
||||
$q->orWhere('snapshot->requester->department_id', $actor->department_id);
|
||||
}
|
||||
|
||||
@@ -67,6 +67,7 @@ class WorkflowTaskInbox
|
||||
}
|
||||
$rows = $area === 'people' ? $this->people($actor) : [...$this->purchases($actor), ...$this->suppliers($actor), ...$this->quotations($actor), ...$this->documentary($actor), ...$this->formalReviews($actor), ...$this->supply($actor), ...$this->suggestions($actor), ...$this->awards($actor), ...$this->warehouse($actor), ...$this->inventoryCorrections($actor), ...$this->lotSetups($actor), ...$this->finance($actor)];
|
||||
if ($area === 'procurement') {
|
||||
$rows = [...$rows, ...app(UrgentRequisitionReviews::class)->tasks($actor)];
|
||||
$rows = [...$rows, ...$this->supplierImprovements($actor), ...$this->supplierQuality($actor), ...$this->supplyFollowUp($actor), ...$this->lotQuality($actor), ...$this->bankReviews($actor)];
|
||||
if (config('order_cancellation.enabled') && Schema::hasTable('order_cancellations')) {
|
||||
foreach (OrderCancellation::query()->where('status', 'pending')->lazyById(100) as $record) {
|
||||
|
||||
Reference in New Issue
Block a user