@@ -14,6 +14,7 @@ use App\Services\OrganizationActivationPreview;
|
|||||||
use App\Services\OrganizationConfiguration;
|
use App\Services\OrganizationConfiguration;
|
||||||
use App\Services\RequisitionApprovalLevels;
|
use App\Services\RequisitionApprovalLevels;
|
||||||
use App\Services\RequisitionCategories;
|
use App\Services\RequisitionCategories;
|
||||||
|
use App\Services\RequisitionExpiry;
|
||||||
use App\Services\WorkContext;
|
use App\Services\WorkContext;
|
||||||
use App\Services\WorkflowTasks;
|
use App\Services\WorkflowTasks;
|
||||||
use Brick\Math\BigDecimal;
|
use Brick\Math\BigDecimal;
|
||||||
@@ -45,6 +46,7 @@ class OrganizationConfigurationController extends Controller
|
|||||||
'geography' => app(AdministrativeGeography::class)->describe(Tenant::query()->findOrFail($actor->tenant_id)->geography_reference),
|
'geography' => app(AdministrativeGeography::class)->describe(Tenant::query()->findOrFail($actor->tenant_id)->geography_reference),
|
||||||
'companyDetailsReady' => Schema::hasColumn('tenants', 'company_details'),
|
'companyDetailsReady' => Schema::hasColumn('tenants', 'company_details'),
|
||||||
'approvalLevelsReady' => app(RequisitionApprovalLevels::class)->ready(),
|
'approvalLevelsReady' => app(RequisitionApprovalLevels::class)->ready(),
|
||||||
|
'expiryReady' => app(RequisitionExpiry::class)->ready(),
|
||||||
'requisitionCategoryOptions' => app(RequisitionCategories::class)->available() ? RequisitionCategories::LABELS : [],
|
'requisitionCategoryOptions' => app(RequisitionCategories::class)->available() ? RequisitionCategories::LABELS : [],
|
||||||
'approvalLevels' => Tenant::query()->findOrFail($actor->tenant_id)->requisition_approval_policy,
|
'approvalLevels' => Tenant::query()->findOrFail($actor->tenant_id)->requisition_approval_policy,
|
||||||
'companyDetails' => Tenant::query()->findOrFail($actor->tenant_id)->company_details,
|
'companyDetails' => Tenant::query()->findOrFail($actor->tenant_id)->company_details,
|
||||||
|
|||||||
@@ -79,7 +79,7 @@ class ProcurementSearchController extends Controller
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (Gate::forUser($actor)->allows('viewAny', GoodsReceipt::class)) {
|
if (Gate::forUser($actor)->allows('viewAny', GoodsReceipt::class)) {
|
||||||
$orders = PurchaseOrder::query()->when($actor->departmentScoped(), fn ($query) => $query->whereIn('requisition_id', Requisition::query()->visibleTo($actor)->select('id')));
|
$orders = PurchaseOrder::query()->when($actor->departmentScoped(), fn ($query) => $query->visibleTo($actor));
|
||||||
$receipts = GoodsReceipt::query()->whereIn('purchase_order_id', $orders->select('id'))->whereRaw("LOWER(delivery_note) LIKE ? ESCAPE '!'", [$pattern])
|
$receipts = GoodsReceipt::query()->whereIn('purchase_order_id', $orders->select('id'))->whereRaw("LOWER(delivery_note) LIKE ? ESCAPE '!'", [$pattern])
|
||||||
->latest('id')->paginate(15, ['id', 'delivery_note'], 'receipts_page')->withQueryString()
|
->latest('id')->paginate(15, ['id', 'delivery_note'], 'receipts_page')->withQueryString()
|
||||||
->through(fn ($row) => ['id' => $row->id, 'title' => 'Recepção #'.$row->id.' · '.$row->delivery_note, 'detail' => 'Recepção', 'href' => '/recepcoes/'.$row->id]);
|
->through(fn ($row) => ['id' => $row->id, 'title' => 'Recepção #'.$row->id.' · '.$row->delivery_note, 'detail' => 'Recepção', 'href' => '/recepcoes/'.$row->id]);
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ use App\Services\RequisitionBudgetDistributions;
|
|||||||
use App\Services\RequisitionCatalogue;
|
use App\Services\RequisitionCatalogue;
|
||||||
use App\Services\RequisitionCategories;
|
use App\Services\RequisitionCategories;
|
||||||
use App\Services\RequisitionDraftInput;
|
use App\Services\RequisitionDraftInput;
|
||||||
|
use App\Services\RequisitionExpiry;
|
||||||
use App\Services\RequisitionWorkflow;
|
use App\Services\RequisitionWorkflow;
|
||||||
use App\Services\SupplySuggestions;
|
use App\Services\SupplySuggestions;
|
||||||
use App\Services\WorkContext;
|
use App\Services\WorkContext;
|
||||||
@@ -127,6 +128,7 @@ class RequisitionController extends Controller
|
|||||||
'importTariffsReady' => app(ImportTariffCodes::class)->ready(),
|
'importTariffsReady' => app(ImportTariffCodes::class)->ready(),
|
||||||
'importEstimatesReady' => app(ImportEstimates::class)->ready(),
|
'importEstimatesReady' => app(ImportEstimates::class)->ready(),
|
||||||
'capitalRegisterReady' => app(CapitalRegister::class)->ready(),
|
'capitalRegisterReady' => app(CapitalRegister::class)->ready(),
|
||||||
|
'expiryReady' => app(RequisitionExpiry::class)->ready(),
|
||||||
'canDecide' => $requisition->canDecide($this->actor($request)),
|
'canDecide' => $requisition->canDecide($this->actor($request)),
|
||||||
'canPrepareDistributions' => app(RequisitionBudgetDistributions::class)->ready() && $requisition->status === 'draft'
|
'canPrepareDistributions' => app(RequisitionBudgetDistributions::class)->ready() && $requisition->status === 'draft'
|
||||||
&& $requisition->requester_id === $this->actor($request)->id && app(OrganizationAccess::class)->canRequest($this->actor($request)),
|
&& $requisition->requester_id === $this->actor($request)->id && app(OrganizationAccess::class)->canRequest($this->actor($request)),
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\Requisition;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\RequisitionExpiry;
|
||||||
|
use App\Services\RequisitionWorkflow;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
final class RequisitionExpiryController 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 $component, array $props): Response
|
||||||
|
{
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render($component, $props)->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function settings(Request $request, RequisitionExpiry $service): Response
|
||||||
|
{
|
||||||
|
$request->validate(['page' => 'nullable|integer|min:1|max:1000000']);
|
||||||
|
|
||||||
|
return $this->page($request, 'organization/approval-timeouts', $service->settings($this->actor($request)));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function saveSettings(Request $request, RequisitionExpiry $service): Response
|
||||||
|
{
|
||||||
|
$service->savePolicy($this->actor($request), $request->all());
|
||||||
|
|
||||||
|
return back()->with('success', 'Política preservada para novas submissões.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function show(Request $request, Requisition $requisition, RequisitionExpiry $service): Response
|
||||||
|
{
|
||||||
|
$request->validate(['page' => 'nullable|integer|min:1|max:1000000']);
|
||||||
|
|
||||||
|
return $this->page($request, 'requisitions/expiry', $service->workspace($this->actor($request), $requisition));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function expire(Request $request, Requisition $requisition, RequisitionWorkflow $workflow): Response
|
||||||
|
{
|
||||||
|
$data = $request->validate(['operation_key' => 'required|uuid', 'process_version' => 'required|integer|min:1',
|
||||||
|
'basis_hash' => ['required', 'regex:/^[a-f0-9]{64}$/D'], 'comment' => 'nullable|string|max:2000']);
|
||||||
|
$workflow->expire($this->actor($request), $requisition, $data['basis_hash'], $data['operation_key'], (int) $data['process_version'], $data['comment'] ?? null);
|
||||||
|
|
||||||
|
return back()->with('success', 'Pedido devolvido ao requisitante; decisões e reservas anteriores preservadas no histórico.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -21,6 +21,6 @@ class ApprovalStep extends Model
|
|||||||
|
|
||||||
protected function casts(): array
|
protected function casts(): array
|
||||||
{
|
{
|
||||||
return ['routing' => 'array'];
|
return ['approval_cycle' => 'integer', 'routing' => 'array'];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ use Illuminate\Database\Eloquent\Model;
|
|||||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||||
use Illuminate\Support\Carbon;
|
use Illuminate\Support\Carbon;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
use Tempo\Purchasing\Internal\InternalRequisitions;
|
use Tempo\Purchasing\Internal\InternalRequisitions;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -29,6 +30,7 @@ use Tempo\Purchasing\Internal\InternalRequisitions;
|
|||||||
* @property Carbon|null $needed_by
|
* @property Carbon|null $needed_by
|
||||||
* @property array<string,mixed>|null $comparison_policy
|
* @property array<string,mixed>|null $comparison_policy
|
||||||
* @property array<string,mixed>|null $budget_distribution_preparation
|
* @property array<string,mixed>|null $budget_distribution_preparation
|
||||||
|
* @property array<string,mixed>|null $approval_snapshot
|
||||||
* @property Collection<int, ApprovalStep> $steps
|
* @property Collection<int, ApprovalStep> $steps
|
||||||
* @property Collection<int, RequisitionItem> $items
|
* @property Collection<int, RequisitionItem> $items
|
||||||
*/
|
*/
|
||||||
@@ -44,7 +46,7 @@ class Requisition extends Model
|
|||||||
|
|
||||||
protected function casts(): array
|
protected function casts(): array
|
||||||
{
|
{
|
||||||
return ['draft_input' => 'array', 'budget_distribution_preparation' => 'array', 'approval_snapshot' => 'array', 'comparison_policy' => 'array', 'submitted_at' => 'datetime', 'needed_by' => 'date:Y-m-d'];
|
return ['approval_cycle' => 'integer', 'draft_input' => 'array', 'budget_distribution_preparation' => 'array', 'approval_snapshot' => 'array', 'comparison_policy' => 'array', 'submitted_at' => 'datetime', 'needed_by' => 'date:Y-m-d'];
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return HasMany<RequisitionItem, $this> */
|
/** @return HasMany<RequisitionItem, $this> */
|
||||||
@@ -56,7 +58,15 @@ class Requisition extends Model
|
|||||||
/** @return HasMany<ApprovalStep, $this> */
|
/** @return HasMany<ApprovalStep, $this> */
|
||||||
public function steps(): HasMany
|
public function steps(): HasMany
|
||||||
{
|
{
|
||||||
return $this->hasMany(ApprovalStep::class)->orderBy('position');
|
return $this->hasMany(ApprovalStep::class)->when(Schema::hasColumn('approval_steps', 'approval_cycle'), fn ($query) => $query->whereExists(fn ($current) => $current
|
||||||
|
->selectRaw('1')->from('requisitions as current_cycle_request')->whereColumn('current_cycle_request.id', 'approval_steps.requisition_id')
|
||||||
|
->whereColumn('current_cycle_request.approval_cycle', 'approval_steps.approval_cycle')))->orderBy('position');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return HasMany<ApprovalStep, $this> */
|
||||||
|
public function allSteps(): HasMany
|
||||||
|
{
|
||||||
|
return $this->hasMany(ApprovalStep::class)->orderBy('id');
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return BelongsTo<User, $this> */
|
/** @return BelongsTo<User, $this> */
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ class BudgetWorkflow
|
|||||||
}
|
}
|
||||||
$adapter = app(CommonBudget::class);
|
$adapter = app(CommonBudget::class);
|
||||||
|
|
||||||
return $adapter->execute(fn () => $adapter->for($user)->record(
|
return $adapter->execute(fn () => $adapter->for($user, RequisitionExpiry::cycles($request))->record(
|
||||||
$request->id, $request->cost_center_id,
|
$request->id, $request->cost_center_id,
|
||||||
$request->items()->where('purchase_type', 'equipment')->exists() ? 'investment' : 'operating',
|
$request->items()->where('purchase_type', 'equipment')->exists() ? 'investment' : 'operating',
|
||||||
$kind, $amount, $subtotal,
|
$kind, $amount, $subtotal,
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ use Illuminate\Support\Facades\DB;
|
|||||||
use Illuminate\Support\Facades\Schema;
|
use Illuminate\Support\Facades\Schema;
|
||||||
use Illuminate\Support\Facades\Validator;
|
use Illuminate\Support\Facades\Validator;
|
||||||
use Illuminate\Support\Str;
|
use Illuminate\Support\Str;
|
||||||
|
use Illuminate\Validation\ValidationException;
|
||||||
|
|
||||||
/** Explicit documentary destination per line. Budget allocations retain their native authority. */
|
/** Explicit documentary destination per line. Budget allocations retain their native authority. */
|
||||||
final class CapitalAssignments
|
final class CapitalAssignments
|
||||||
@@ -31,15 +32,17 @@ final class CapitalAssignments
|
|||||||
{
|
{
|
||||||
return DB::transaction(function () use ($actor, $request) {
|
return DB::transaction(function () use ($actor, $request) {
|
||||||
[$actor, $request] = $this->context($actor, $request);
|
[$actor, $request] = $this->context($actor, $request);
|
||||||
|
$canWrite = $request->status === 'draft' && $request->requester_id === $actor->id && app(OrganizationAccess::class)->canRequest($actor)
|
||||||
|
&& ! app(ConflictGuard::class)->participationBlocked($actor, $request);
|
||||||
|
|
||||||
return ['requisition' => $request->only(['id', 'number', 'status']), 'items' => $request->items()->orderBy('id')->get(['id', 'description']),
|
return ['requisition' => $request->only(['id', 'number', 'status']), 'items' => $request->items()->orderBy('id')->get(['id', 'description']),
|
||||||
'current' => app(SupplyPlanning::class)->latest('capital_assignment')->where('data->requisition_id', $request->id)->get(),
|
'current' => app(SupplyPlanning::class)->latest('capital_assignment')->where('data->requisition_id', $request->id)->get(),
|
||||||
'choices' => app(SupplyPlanning::class)->latest('capital_register')->where('state', 'active')->where('data->department_id', $request->department_id)
|
'choices' => app(SupplyPlanning::class)->latest('capital_register')->where('state', 'active')->where('data->department_id', $request->department_id)
|
||||||
|
->when(! $canWrite, fn ($q) => $q->whereRaw('1 = 0'))
|
||||||
->orderBy('data->code')->paginate(15, ['id', 'version', 'data'], 'choices_page')->withQueryString(),
|
->orderBy('data->code')->paginate(15, ['id', 'version', 'data'], 'choices_page')->withQueryString(),
|
||||||
'history' => SupplyRecord::query()->where('kind', 'capital_assignment')->where('data->requisition_id', $request->id)
|
'history' => SupplyRecord::query()->where('kind', 'capital_assignment')->where('data->requisition_id', $request->id)
|
||||||
->latest('id')->paginate(15, ['*'], 'history_page')->withQueryString(),
|
->latest('id')->paginate(15, ['*'], 'history_page')->withQueryString(),
|
||||||
'canWrite' => $request->status === 'draft' && $request->requester_id === $actor->id && app(OrganizationAccess::class)->canRequest($actor)
|
'canWrite' => $canWrite,
|
||||||
&& ! app(ConflictGuard::class)->participationBlocked($actor, $request),
|
|
||||||
'actorId' => $actor->id, 'tenantId' => $actor->tenant_id];
|
'actorId' => $actor->id, 'tenantId' => $actor->tenant_id];
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -86,6 +89,24 @@ final class CapitalAssignments
|
|||||||
return $item->only(['id', 'description', 'unit', 'quantity', 'purchase_type', 'equipment_id', 'category_context']);
|
return $item->only(['id', 'description', 'unit', 'quantity', 'purchase_type', 'equipment_id', 'category_context']);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function assertSubmission(User $actor, Requisition $request): void
|
||||||
|
{
|
||||||
|
$items = $request->items()->orderBy('id')->get();
|
||||||
|
$itemIds = [];
|
||||||
|
foreach ($items as $item) {
|
||||||
|
$itemIds[] = $item->id;
|
||||||
|
}
|
||||||
|
$frozen = $this->freezeForItems($actor, $itemIds);
|
||||||
|
if (! app(CapitalRegister::class)->ready()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
foreach ($items as $item) {
|
||||||
|
if (($item->category_context['category'] ?? null) === 'capital_equipment' && ! isset($frozen[$item->id])) {
|
||||||
|
throw ValidationException::withMessages(['capital_assignment' => 'Maquinaria: ligue cada artigo ao projecto ou imobilizado no cadastro de Compras antes de submeter. Não foram criadas reservas ou aprovações.']);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** Preserve accepted choices even after a later rename/archive. New choices require a current active source.
|
/** Preserve accepted choices even after a later rename/archive. New choices require a current active source.
|
||||||
* @param list<int> $itemIds
|
* @param list<int> $itemIds
|
||||||
* @return array<int,array<string,mixed>>
|
* @return array<int,array<string,mixed>>
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ final class CapitalTrace
|
|||||||
} else {
|
} else {
|
||||||
abort(503, 'A consulta de origens requer um motor verificado.');
|
abort(503, 'A consulta de origens requer um motor verificado.');
|
||||||
}
|
}
|
||||||
|
|
||||||
return $query;
|
return $query;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -42,6 +43,7 @@ final class CapitalTrace
|
|||||||
$documents = GoodsReceipt::query()->whereIn('id', $receipts->getCollection()->pluck('goods_receipt_id'))->get()->keyBy('id');
|
$documents = GoodsReceipt::query()->whereIn('id', $receipts->getCollection()->pluck('goods_receipt_id'))->get()->keyBy('id');
|
||||||
$receipts->through(function (GoodsReceiptItem $item) use ($documents) {
|
$receipts->through(function (GoodsReceiptItem $item) use ($documents) {
|
||||||
$document = $documents->get($item->goods_receipt_id);
|
$document = $documents->get($item->goods_receipt_id);
|
||||||
|
|
||||||
return ['id' => $item->id, 'description' => $item->snapshot['order_item']['description'] ?? null, 'unit' => $item->snapshot['order_item']['unit'] ?? null,
|
return ['id' => $item->id, 'description' => $item->snapshot['order_item']['description'] ?? null, 'unit' => $item->snapshot['order_item']['unit'] ?? null,
|
||||||
'receipt_id' => $item->goods_receipt_id, 'order_id' => $document?->purchase_order_id,
|
'receipt_id' => $item->goods_receipt_id, 'order_id' => $document?->purchase_order_id,
|
||||||
'received_on' => $document?->received_on->toDateString(), 'quality_status' => $item->quality_status,
|
'received_on' => $document?->received_on->toDateString(), 'quality_status' => $item->quality_status,
|
||||||
@@ -49,6 +51,7 @@ final class CapitalTrace
|
|||||||
'reversed' => app(InventoryReversals::class)->receiptReversed($item->id),
|
'reversed' => app(InventoryReversals::class)->receiptReversed($item->id),
|
||||||
'returned_quantity' => (string) BigDecimal::of(app(InventoryDispositions::class)->returnedForReceipt($item->id))->dividedBy(1000, 3)];
|
'returned_quantity' => (string) BigDecimal::of(app(InventoryDispositions::class)->returnedForReceipt($item->id))->dividedBy(1000, 3)];
|
||||||
});
|
});
|
||||||
|
|
||||||
return ['orders' => $orders, 'receipts' => $receipts];
|
return ['orders' => $orders, 'receipts' => $receipts];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,10 +23,19 @@ final class CommonBudget
|
|||||||
|
|
||||||
public const IMPORT_ESTIMATE_CONTRACT = 'COMMON-BUDGET-IMPORT-ESTIMATE-QA-v1';
|
public const IMPORT_ESTIMATE_CONTRACT = 'COMMON-BUDGET-IMPORT-ESTIMATE-QA-v1';
|
||||||
|
|
||||||
public function for(User $user): BudgetControl
|
public const REQUISITION_CYCLES_CONTRACT = 'COMMON-BUDGET-REQUISITION-CYCLES-QA-v1';
|
||||||
|
|
||||||
|
/** @param array<int,int> $cycles */
|
||||||
|
public function for(User $user, array $cycles = []): BudgetControl
|
||||||
{
|
{
|
||||||
abort_unless(auth()->id() === $user->id && $user->tenant_id !== null, 403);
|
abort_unless(auth()->id() === $user->id && $user->tenant_id !== null, 403);
|
||||||
$runtime = new \ReflectionClass(BudgetControl::class);
|
$runtime = new \ReflectionClass(BudgetControl::class);
|
||||||
|
$cycleRuntime = $runtime->hasConstant('REQUISITION_CYCLES_VERSION') && $runtime->getConstant('REQUISITION_CYCLES_VERSION') === self::REQUISITION_CYCLES_CONTRACT;
|
||||||
|
if (! $cycleRuntime) {
|
||||||
|
abort_if(($cycles !== [] && max($cycles) > 1) || (Schema::hasTable('budget_requisition_cycles')
|
||||||
|
&& DB::table('budget_requisition_cycles')->where('tenant_id', $user->tenant_id)->where('cycle', '>', 1)->exists()), 503,
|
||||||
|
'Existem novos ciclos de requisição. Preserve o núcleo compatível antes de operar ou consultar saldos.');
|
||||||
|
}
|
||||||
$landedTables = ['budget_landed_commands', 'budget_landed_entries'];
|
$landedTables = ['budget_landed_commands', 'budget_landed_entries'];
|
||||||
$landedPresent = array_values(array_filter($landedTables, fn ($table) => Schema::hasTable($table)));
|
$landedPresent = array_values(array_filter($landedTables, fn ($table) => Schema::hasTable($table)));
|
||||||
abort_if(count($landedPresent) !== 0 && count($landedPresent) !== count($landedTables), 503, 'Estrutura de aterragem incompleta; saldo não presumido.');
|
abort_if(count($landedPresent) !== 0 && count($landedPresent) !== count($landedTables), 503, 'Estrutura de aterragem incompleta; saldo não presumido.');
|
||||||
@@ -64,7 +73,8 @@ final class CommonBudget
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
abort_unless(DB::table('tenants')->where('id', $user->tenant_id)->value('currency') === 'MZN', 422, 'Controlo comum desta entrega suporta apenas MZN; câmbio permanece pendente.');
|
abort_unless(DB::table('tenants')->where('id', $user->tenant_id)->value('currency') === 'MZN', 422, 'Controlo comum desta entrega suporta apenas MZN; câmbio permanece pendente.');
|
||||||
$context = new BudgetContext($user->id, ['tenant_id' => (int) $user->tenant_id], (int) now()->year, 'MZN');
|
$context = $cycleRuntime ? (new \ReflectionClass(BudgetContext::class))->newInstanceArgs([$user->id, ['tenant_id' => (int) $user->tenant_id], (int) now()->year, 'MZN', $cycles])
|
||||||
|
: new BudgetContext($user->id, ['tenant_id' => (int) $user->tenant_id], (int) now()->year, 'MZN');
|
||||||
|
|
||||||
return new BudgetControl(DB::connection(), $context, '',
|
return new BudgetControl(DB::connection(), $context, '',
|
||||||
function (string $action) use ($user): void {
|
function (string $action) use ($user): void {
|
||||||
|
|||||||
@@ -34,7 +34,12 @@ final class ImportEstimates
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return SupplyRecord::query()->where('kind', 'import_estimate')->where('data->requisition_id', $request->id)->latest('version')->first();
|
$cycle = (int) ($request->getAttribute('approval_cycle') ?? 1);
|
||||||
|
|
||||||
|
return SupplyRecord::query()->where('kind', 'import_estimate')->where('data->requisition_id', $request->id)
|
||||||
|
->when($cycle > 1, fn ($q) => $q->where('data->requisition_cycle', $cycle),
|
||||||
|
fn ($q) => $q->where(fn ($first) => $first->whereNull('data->requisition_cycle')->orWhere('data->requisition_cycle', 1)))
|
||||||
|
->latest('version')->first();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return array<string,mixed> */
|
/** @return array<string,mixed> */
|
||||||
@@ -95,7 +100,7 @@ final class ImportEstimates
|
|||||||
$record = $this->current($request);
|
$record = $this->current($request);
|
||||||
abort_unless($record !== null, 409);
|
abort_unless($record !== null, 409);
|
||||||
$adapter = app(CommonBudget::class);
|
$adapter = app(CommonBudget::class);
|
||||||
$engine = $adapter->for($actor);
|
$engine = $adapter->for($actor, RequisitionExpiry::cycles($request));
|
||||||
abort_unless(in_array('reserveImportEstimate', get_class_methods($engine), true), 503, 'Motor sem reserva pré-documental.');
|
abort_unless(in_array('reserveImportEstimate', get_class_methods($engine), true), 503, 'Motor sem reserva pré-documental.');
|
||||||
$adapter->execute(fn () => (new \ReflectionMethod($engine, 'reserveImportEstimate'))->invoke($engine, $record->record_key, $record->version, $record->data['budget_id'],
|
$adapter->execute(fn () => (new \ReflectionMethod($engine, 'reserveImportEstimate'))->invoke($engine, $record->record_key, $record->version, $record->data['budget_id'],
|
||||||
$request->id, $record->snapshot['plan']['goods'], $record->data['components'], $record->operation_key));
|
$request->id, $record->snapshot['plan']['goods'], $record->data['components'], $record->operation_key));
|
||||||
@@ -110,7 +115,7 @@ final class ImportEstimates
|
|||||||
}
|
}
|
||||||
abort_unless($this->ready(), 503, 'Preserve o motor das estimativas reservadas.');
|
abort_unless($this->ready(), 503, 'Preserve o motor das estimativas reservadas.');
|
||||||
$adapter = app(CommonBudget::class);
|
$adapter = app(CommonBudget::class);
|
||||||
$engine = $adapter->for($actor);
|
$engine = $adapter->for($actor, RequisitionExpiry::cycles($request));
|
||||||
abort_unless(in_array('releaseImportEstimate', get_class_methods($engine), true), 503);
|
abort_unless(in_array('releaseImportEstimate', get_class_methods($engine), true), 503);
|
||||||
$adapter->execute(fn () => (new \ReflectionMethod($engine, 'releaseImportEstimate'))->invoke($engine, $estimate['record_key'], $estimate['version'],
|
$adapter->execute(fn () => (new \ReflectionMethod($engine, 'releaseImportEstimate'))->invoke($engine, $estimate['record_key'], $estimate['version'],
|
||||||
$estimate['plan']['fingerprint'], (string) Str::uuid()));
|
$estimate['plan']['fingerprint'], (string) Str::uuid()));
|
||||||
@@ -267,7 +272,8 @@ final class ImportEstimates
|
|||||||
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'import_estimate',
|
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'import_estimate',
|
||||||
'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1,
|
'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1,
|
||||||
'state' => $plan['complete'] ? 'prepared' : 'incomplete', 'created_by' => $actor->id,
|
'state' => $plan['complete'] ? 'prepared' : 'incomplete', 'created_by' => $actor->id,
|
||||||
'data' => ['requisition_id' => $request->id, 'budget_id' => $budget->id, 'components' => $data['components']],
|
'data' => ['requisition_id' => $request->id, 'budget_id' => $budget->id, 'components' => $data['components'],
|
||||||
|
...((int) ($request->getAttribute('approval_cycle') ?? 1) > 1 ? ['requisition_cycle' => $request->getAttribute('approval_cycle')] : [])],
|
||||||
'snapshot' => ['native' => $native, 'plan' => $plan, 'budget' => $budget->only(['id', 'cost_center_id', 'year', 'kind', 'includes_tax']), 'legal_sources' => $legalSources],
|
'snapshot' => ['native' => $native, 'plan' => $plan, 'budget' => $budget->only(['id', 'cost_center_id', 'year', 'kind', 'includes_tax']), 'legal_sources' => $legalSources],
|
||||||
'reason' => $data['reason'], 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'created_at' => now()]);
|
'reason' => $data['reason'], 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'created_at' => now()]);
|
||||||
app(RequisitionWorkflow::class)->audit($actor, 'import.estimate_prepared', $request, null,
|
app(RequisitionWorkflow::class)->audit($actor, 'import.estimate_prepared', $request, null,
|
||||||
|
|||||||
@@ -9,9 +9,9 @@ use App\Models\User;
|
|||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Support\Facades\Schema;
|
use Illuminate\Support\Facades\Schema;
|
||||||
use Illuminate\Validation\ValidationException;
|
use Illuminate\Validation\ValidationException;
|
||||||
use Tempo\Purchasing\Internal\RequisitionPort;
|
use Tempo\Purchasing\Internal\ExpiryRequisitionPort;
|
||||||
|
|
||||||
final class InternalRequisitionPort implements RequisitionPort
|
final class InternalRequisitionPort implements ExpiryRequisitionPort
|
||||||
{
|
{
|
||||||
/** @param \Closure(array<string,mixed>,?Requisition):Requisition $save */
|
/** @param \Closure(array<string,mixed>,?Requisition):Requisition $save */
|
||||||
public function __construct(private User $actor, private \Closure $save, private ?SupplyRecord $automaticRule = null) {}
|
public function __construct(private User $actor, private \Closure $save, private ?SupplyRecord $automaticRule = null) {}
|
||||||
@@ -57,6 +57,9 @@ final class InternalRequisitionPort implements RequisitionPort
|
|||||||
}
|
}
|
||||||
if ($record !== null) {
|
if ($record !== null) {
|
||||||
$r = $this->model($record['id']);
|
$r = $this->model($record['id']);
|
||||||
|
if ($action !== 'view') {
|
||||||
|
app(RequisitionExpiry::class)->assertOperational($r);
|
||||||
|
}
|
||||||
if ($action === 'view') {
|
if ($action === 'view') {
|
||||||
Requisition::query()->visibleTo($this->actor)->findOrFail($record['id']);
|
Requisition::query()->visibleTo($this->actor)->findOrFail($record['id']);
|
||||||
}
|
}
|
||||||
@@ -74,6 +77,9 @@ final class InternalRequisitionPort implements RequisitionPort
|
|||||||
}
|
}
|
||||||
} elseif ($action === 'decide') {
|
} elseif ($action === 'decide') {
|
||||||
abort_unless($this->actor->hasFunctions(['department_head', 'procurement', 'finance', 'requisition_approve']), 403);
|
abort_unless($this->actor->hasFunctions(['department_head', 'procurement', 'finance', 'requisition_approve']), 403);
|
||||||
|
} elseif ($action === 'expire') {
|
||||||
|
abort_unless($record !== null, 404);
|
||||||
|
Requisition::query()->visibleTo($this->actor)->whereKey($record['id'])->firstOrFail();
|
||||||
} elseif (str_starts_with($action, 'step:')) {
|
} elseif (str_starts_with($action, 'step:')) {
|
||||||
$role = substr($action, 5);
|
$role = substr($action, 5);
|
||||||
if (str_starts_with($role, 'configured_')) {
|
if (str_starts_with($role, 'configured_')) {
|
||||||
@@ -118,6 +124,7 @@ final class InternalRequisitionPort implements RequisitionPort
|
|||||||
foreach ($r->items()->get() as $item) {
|
foreach ($r->items()->get() as $item) {
|
||||||
app(EquipmentWorkflow::class)->line($item->toArray(), $r->department_id, $r->priority);
|
app(EquipmentWorkflow::class)->line($item->toArray(), $r->department_id, $r->priority);
|
||||||
}
|
}
|
||||||
|
app(CapitalAssignments::class)->assertSubmission($this->actor, $r);
|
||||||
app(EquipmentWorkflow::class)->assertTechnical($r);
|
app(EquipmentWorkflow::class)->assertTechnical($r);
|
||||||
if ($r->needed_by < today()) {
|
if ($r->needed_by < today()) {
|
||||||
throw ValidationException::withMessages(['submission' => 'Actualize a data de entrega antes de submeter.']);
|
throw ValidationException::withMessages(['submission' => 'Actualize a data de entrega antes de submeter.']);
|
||||||
@@ -127,8 +134,10 @@ final class InternalRequisitionPort implements RequisitionPort
|
|||||||
$estimate = app(ImportEstimates::class)->approval($r);
|
$estimate = app(ImportEstimates::class)->approval($r);
|
||||||
$basis = $estimate['plan']['reference_totals'] ?? null;
|
$basis = $estimate['plan']['reference_totals'] ?? null;
|
||||||
$amount = $basis === null ? null : $basis[$base['approval_includes_tax'] ? 'total_minor' : 'subtotal_minor'];
|
$amount = $basis === null ? null : $basis[$base['approval_includes_tax'] ? 'total_minor' : 'subtotal_minor'];
|
||||||
|
$expiry = app(RequisitionExpiry::class)->policy($r);
|
||||||
|
|
||||||
return [...$base, ...app(RequisitionApprovalLevels::class)->policy($r, $amount),
|
return [...$base, ...app(RequisitionApprovalLevels::class)->policy($r, $amount),
|
||||||
|
...($expiry === null ? [] : ['approval_expiry' => $expiry]),
|
||||||
...($estimate === null ? [] : ['import_estimate' => $estimate, 'approval_basis' => $basis])];
|
...($estimate === null ? [] : ['import_estimate' => $estimate, 'approval_basis' => $basis])];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -141,12 +150,40 @@ final class InternalRequisitionPort implements RequisitionPort
|
|||||||
return $result;
|
return $result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function prepareCycle(array $record, array $policy, ?string $operation): void
|
||||||
|
{
|
||||||
|
app(RequisitionExpiry::class)->begin($this->actor, $this->model($record['id']), $policy, $operation);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function assertDecisionTimely(array $record): void
|
||||||
|
{
|
||||||
|
abort_if(app(RequisitionExpiry::class)->deadline($this->model($record['id']))['state'] === 'expired', 409,
|
||||||
|
'O prazo desta etapa terminou. Confirme a devolução por expiração antes de uma nova submissão.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function expiration(array $record, array $input): array
|
||||||
|
{
|
||||||
|
return app(RequisitionExpiry::class)->proof($this->actor, $this->model($record['id']), $input);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function expired(array $record, array $proof): array
|
||||||
|
{
|
||||||
|
$request = $this->model($record['id']);
|
||||||
|
app(RequisitionExpiry::class)->returned($this->actor, $request, $proof);
|
||||||
|
|
||||||
|
return $this->snapshot($request);
|
||||||
|
}
|
||||||
|
|
||||||
public function submitted(array $record, array $policy, array $roles): array
|
public function submitted(array $record, array $policy, array $roles): array
|
||||||
{
|
{
|
||||||
$r = $this->model($record['id']);
|
$r = $this->model($record['id']);
|
||||||
foreach ($roles as $position => $role) {
|
foreach ($roles as $position => $role) {
|
||||||
$r->steps()->create(['tenant_id' => $this->actor->tenant_id, 'position' => $position + 1, 'role' => $role,
|
$step = $r->steps()->make(['tenant_id' => $this->actor->tenant_id, 'position' => $position + 1, 'role' => $role,
|
||||||
...(isset($policy['additional_levels'][$role]) ? ['routing' => $policy['additional_levels'][$role]] : [])]);
|
...(isset($policy['additional_levels'][$role]) ? ['routing' => $policy['additional_levels'][$role]] : [])]);
|
||||||
|
if (Schema::hasColumn('approval_steps', 'approval_cycle')) {
|
||||||
|
$step->setAttribute('approval_cycle', $r->getAttribute('approval_cycle') ?? 1);
|
||||||
|
}
|
||||||
|
$step->save();
|
||||||
}
|
}
|
||||||
$values = ['status' => 'pending', 'submitted_at' => now(), 'approval_snapshot' => $policy];
|
$values = ['status' => 'pending', 'submitted_at' => now(), 'approval_snapshot' => $policy];
|
||||||
if (Schema::hasColumn('requisitions', 'process_version')) {
|
if (Schema::hasColumn('requisitions', 'process_version')) {
|
||||||
|
|||||||
@@ -58,7 +58,7 @@ class InvoiceBudgetDistributions
|
|||||||
if (array_sum(array_column($lines, 'subtotal_minor')) !== $reference['subtotal_minor'] || array_sum(array_column($lines, 'total_minor')) !== $reference['total_minor']) {
|
if (array_sum(array_column($lines, 'subtotal_minor')) !== $reference['subtotal_minor'] || array_sum(array_column($lines, 'total_minor')) !== $reference['total_minor']) {
|
||||||
throw ValidationException::withMessages(['allocations' => 'As parcelas em MZN devem reconciliar exactamente com a referência nativa desta factura parcial.']);
|
throw ValidationException::withMessages(['allocations' => 'As parcelas em MZN devem reconciliar exactamente com a referência nativa desta factura parcial.']);
|
||||||
}
|
}
|
||||||
$engine = app(CommonBudget::class)->for($actor);
|
$engine = app(CommonBudget::class)->for($actor, RequisitionExpiry::cycles($request));
|
||||||
$check = new \ReflectionMethod($engine, 'checkDistributionConsumption');
|
$check = new \ReflectionMethod($engine, 'checkDistributionConsumption');
|
||||||
app(CommonBudget::class)->execute(fn () => $check->invoke($engine, $order->requisition_id, $allocations, $lines));
|
app(CommonBudget::class)->execute(fn () => $check->invoke($engine, $order->requisition_id, $allocations, $lines));
|
||||||
|
|
||||||
@@ -95,7 +95,8 @@ class InvoiceBudgetDistributions
|
|||||||
if (! is_array($plan) || $plan['revision'] !== $this->revision($invoice, $order) || $plan['reference'] !== $reference) {
|
if (! is_array($plan) || $plan['revision'] !== $this->revision($invoice, $order) || $plan['reference'] !== $reference) {
|
||||||
throw ValidationException::withMessages(['allocations' => 'Distribuição da factura ausente ou desactualizada; não foi usado o contrato de centro único.']);
|
throw ValidationException::withMessages(['allocations' => 'Distribuição da factura ausente ou desactualizada; não foi usado o contrato de centro único.']);
|
||||||
}
|
}
|
||||||
$engine = app(CommonBudget::class)->for($actor);
|
$request = Requisition::query()->whereKey($order->requisition_id)->firstOrFail();
|
||||||
|
$engine = app(CommonBudget::class)->for($actor, RequisitionExpiry::cycles($request));
|
||||||
$method = new \ReflectionMethod($engine, 'consumeDistribution');
|
$method = new \ReflectionMethod($engine, 'consumeDistribution');
|
||||||
$result = app(CommonBudget::class)->execute(fn () => $method->invoke($engine, $order->requisition_id, $invoice->id,
|
$result = app(CommonBudget::class)->execute(fn () => $method->invoke($engine, $order->requisition_id, $invoice->id,
|
||||||
$plan['allocations'], $plan['lines'], $plan['revision'], $plan['operation_key']));
|
$plan['allocations'], $plan['lines'], $plan['revision'], $plan['operation_key']));
|
||||||
|
|||||||
@@ -176,7 +176,7 @@ class InvoiceWorkflow
|
|||||||
$reference = app(QuotationExchange::class)->invoiceAmounts($order, $invoice);
|
$reference = app(QuotationExchange::class)->invoiceAmounts($order, $invoice);
|
||||||
$effect = app(RequisitionBudgetDistributions::class)->applies($request)
|
$effect = app(RequisitionBudgetDistributions::class)->applies($request)
|
||||||
? app(InvoiceBudgetDistributions::class)->consume($user, $invoice, $order, $reference)
|
? app(InvoiceBudgetDistributions::class)->consume($user, $invoice, $order, $reference)
|
||||||
: $adapter->execute(fn () => $adapter->for($user)->consume($request->id, $invoice->id, $reference['total_minor'], $reference['subtotal_minor']));
|
: $adapter->execute(fn () => $adapter->for($user, RequisitionExpiry::cycles($request))->consume($request->id, $invoice->id, $reference['total_minor'], $reference['subtotal_minor']));
|
||||||
$invoice->update(['status' => 'validated', 'validated_by' => $user->id, 'validated_at' => now()]);
|
$invoice->update(['status' => 'validated', 'validated_by' => $user->id, 'validated_at' => now()]);
|
||||||
app(RequisitionWorkflow::class)->audit($user, 'invoice.validated', $request, null, ['invoice_id' => $invoice->id,
|
app(RequisitionWorkflow::class)->audit($user, 'invoice.validated', $request, null, ['invoice_id' => $invoice->id,
|
||||||
...($order->currency === 'MZN' ? [] : ['reference_amounts' => $reference, 'exchange_basis' => $order->snapshot['exchange_basis']])] + $effect);
|
...($order->currency === 'MZN' ? [] : ['reference_amounts' => $reference, 'exchange_basis' => $order->snapshot['exchange_basis']])] + $effect);
|
||||||
|
|||||||
@@ -236,7 +236,7 @@ class OrderCancellationWorkflow
|
|||||||
}
|
}
|
||||||
unset($source);
|
unset($source);
|
||||||
$adapter = app(CommonBudget::class);
|
$adapter = app(CommonBudget::class);
|
||||||
$engine = $adapter->for($actor);
|
$engine = $adapter->for($actor, RequisitionExpiry::orderCycles($order));
|
||||||
$result = $adapter->execute(fn () => (new \ReflectionMethod($engine, 'cancelOrderParts'))->invoke($engine, $order->getAttribute('order_key'), $sources, $record->operation_key));
|
$result = $adapter->execute(fn () => (new \ReflectionMethod($engine, 'cancelOrderParts'))->invoke($engine, $order->getAttribute('order_key'), $sources, $record->operation_key));
|
||||||
if (! is_array($result)) {
|
if (! is_array($result)) {
|
||||||
throw new \LogicException('Resposta incompatível da reversão por parcelas.');
|
throw new \LogicException('Resposta incompatível da reversão por parcelas.');
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ namespace App\Services;
|
|||||||
|
|
||||||
use App\Enums\PurchasingRole;
|
use App\Enums\PurchasingRole;
|
||||||
use App\Models\PurchaseOrder;
|
use App\Models\PurchaseOrder;
|
||||||
|
use App\Models\Requisition;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use Brick\Math\BigDecimal;
|
use Brick\Math\BigDecimal;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
@@ -23,7 +24,8 @@ final class OrderPartsAmendments
|
|||||||
$sources = [];
|
$sources = [];
|
||||||
foreach ($order->snapshot['order_parts']['budget_sources'] as $original) {
|
foreach ($order->snapshot['order_parts']['budget_sources'] as $original) {
|
||||||
$origin = $original['origin'];
|
$origin = $original['origin'];
|
||||||
$distribution = DB::table('budget_distributions')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $origin)->first();
|
$originRequest = Requisition::query()->whereKey($origin)->firstOrFail();
|
||||||
|
$distribution = app(RequisitionBudgetDistributions::class)->source($originRequest);
|
||||||
abort_unless($distribution !== null && $distribution->phase === 'orders', 409);
|
abort_unless($distribution !== null && $distribution->phase === 'orders', 409);
|
||||||
$snapshot = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR);
|
$snapshot = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR);
|
||||||
$frozen = array_column($snapshot['allocations'], null, 'allocation_key');
|
$frozen = array_column($snapshot['allocations'], null, 'allocation_key');
|
||||||
@@ -70,7 +72,7 @@ final class OrderPartsAmendments
|
|||||||
'subtotal_minor' => BigDecimal::of($row['subtotal'])->multipliedBy(100)->toInt(),
|
'subtotal_minor' => BigDecimal::of($row['subtotal'])->multipliedBy(100)->toInt(),
|
||||||
'total_minor' => BigDecimal::of($row['total'])->multipliedBy(100)->toInt()], $source['allocations'])], $data['sources']);
|
'total_minor' => BigDecimal::of($row['total'])->multipliedBy(100)->toInt()], $source['allocations'])], $data['sources']);
|
||||||
$adapter = app(CommonBudget::class);
|
$adapter = app(CommonBudget::class);
|
||||||
$engine = $adapter->for($actor);
|
$engine = $adapter->for($actor, RequisitionExpiry::orderCycles($order));
|
||||||
$adapter->execute(fn () => (new \ReflectionMethod($engine, 'amendOrderParts'))->invoke($engine,
|
$adapter->execute(fn () => (new \ReflectionMethod($engine, 'amendOrderParts'))->invoke($engine,
|
||||||
$order->getAttribute('order_key'), $sources, $data['reason'], strtolower($data['operation_key'])));
|
$order->getAttribute('order_key'), $sources, $data['reason'], strtolower($data['operation_key'])));
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ namespace App\Services;
|
|||||||
use App\Enums\PurchasingRole;
|
use App\Enums\PurchasingRole;
|
||||||
use App\Models\Invoice;
|
use App\Models\Invoice;
|
||||||
use App\Models\PurchaseOrder;
|
use App\Models\PurchaseOrder;
|
||||||
|
use App\Models\Requisition;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use Brick\Math\BigDecimal;
|
use Brick\Math\BigDecimal;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
@@ -25,7 +26,8 @@ final class OrderPartsInvoices
|
|||||||
app(OrderPartsAccess::class)->assertProcess($actor, $order);
|
app(OrderPartsAccess::class)->assertProcess($actor, $order);
|
||||||
$rows = [];
|
$rows = [];
|
||||||
foreach ($order->snapshot['order_parts']['sources'] as $source) {
|
foreach ($order->snapshot['order_parts']['sources'] as $source) {
|
||||||
$distribution = DB::table('budget_distributions')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $source['requisition_id'])->first();
|
$originRequest = Requisition::query()->whereKey($source['requisition_id'])->firstOrFail();
|
||||||
|
$distribution = app(RequisitionBudgetDistributions::class)->source($originRequest);
|
||||||
abort_unless($distribution !== null, 503);
|
abort_unless($distribution !== null, 503);
|
||||||
$snapshot = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR);
|
$snapshot = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR);
|
||||||
$nativeLines = array_column($source['items'], null, 'requisition_item_id');
|
$nativeLines = array_column($source['items'], null, 'requisition_item_id');
|
||||||
@@ -82,7 +84,7 @@ final class OrderPartsInvoices
|
|||||||
usort($rows, fn ($a, $b) => [$a['origin'], $a['allocation_key']] <=> [$b['origin'], $b['allocation_key']]);
|
usort($rows, fn ($a, $b) => [$a['origin'], $a['allocation_key']] <=> [$b['origin'], $b['allocation_key']]);
|
||||||
$sources = $this->bindings($actor, $order, $rows, $nativeLines);
|
$sources = $this->bindings($actor, $order, $rows, $nativeLines);
|
||||||
$adapter = app(CommonBudget::class);
|
$adapter = app(CommonBudget::class);
|
||||||
$engine = $adapter->for($actor);
|
$engine = $adapter->for($actor, RequisitionExpiry::orderCycles($order));
|
||||||
$adapter->execute(fn () => (new \ReflectionMethod($engine, 'checkOrderPartsConsumption'))->invoke($engine, $sources));
|
$adapter->execute(fn () => (new \ReflectionMethod($engine, 'checkOrderPartsConsumption'))->invoke($engine, $sources));
|
||||||
|
|
||||||
return ['allocations' => $rows, 'source_versions_at_preparation' => array_column($sources, 'version', 'origin'),
|
return ['allocations' => $rows, 'source_versions_at_preparation' => array_column($sources, 'version', 'origin'),
|
||||||
@@ -121,7 +123,8 @@ final class OrderPartsInvoices
|
|||||||
throw ValidationException::withMessages(['order_part_allocations' => 'Origem fora desta ordem.']);
|
throw ValidationException::withMessages(['order_part_allocations' => 'Origem fora desta ordem.']);
|
||||||
}
|
}
|
||||||
if (! isset($sources[$row['origin']])) {
|
if (! isset($sources[$row['origin']])) {
|
||||||
$distribution = DB::table('budget_distributions')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $row['origin'])->lockForUpdate()->first();
|
$originRequest = Requisition::query()->whereKey($row['origin'])->firstOrFail();
|
||||||
|
$distribution = app(RequisitionBudgetDistributions::class)->source($originRequest, true);
|
||||||
abort_unless($distribution !== null, 503, 'Preserve a distribuição da origem.');
|
abort_unless($distribution !== null, 503, 'Preserve a distribuição da origem.');
|
||||||
$snapshot = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR);
|
$snapshot = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR);
|
||||||
$sources[$row['origin']] = ['origin' => $row['origin'], 'version' => DB::table('budget_order_bindings')->where('tenant_id', $actor->tenant_id)->where('distribution_id', $distribution->id)->count(),
|
$sources[$row['origin']] = ['origin' => $row['origin'], 'version' => DB::table('budget_order_bindings')->where('tenant_id', $actor->tenant_id)->where('distribution_id', $distribution->id)->count(),
|
||||||
@@ -187,7 +190,7 @@ final class OrderPartsInvoices
|
|||||||
}
|
}
|
||||||
$sources = $this->bindings($actor, $order, $plan['allocations'], $lines);
|
$sources = $this->bindings($actor, $order, $plan['allocations'], $lines);
|
||||||
$adapter = app(CommonBudget::class);
|
$adapter = app(CommonBudget::class);
|
||||||
$engine = $adapter->for($actor);
|
$engine = $adapter->for($actor, RequisitionExpiry::orderCycles($order));
|
||||||
$result = $adapter->execute(fn () => (new \ReflectionMethod($engine, 'consumeOrderParts'))->invoke($engine, $invoice->id, $sources, $plan['operation_key']));
|
$result = $adapter->execute(fn () => (new \ReflectionMethod($engine, 'consumeOrderParts'))->invoke($engine, $invoice->id, $sources, $plan['operation_key']));
|
||||||
if (! is_array($result)) {
|
if (! is_array($result)) {
|
||||||
throw new \LogicException('Resposta incompatível do consumo por origem.');
|
throw new \LogicException('Resposta incompatível do consumo por origem.');
|
||||||
|
|||||||
@@ -31,7 +31,8 @@ final class OrderPartsWorkflow
|
|||||||
$prepared = app(OrderPartsPreparation::class)->prepare($actor, $selection);
|
$prepared = app(OrderPartsPreparation::class)->prepare($actor, $selection);
|
||||||
$financial = [];
|
$financial = [];
|
||||||
foreach ($prepared['sources'] as $source) {
|
foreach ($prepared['sources'] as $source) {
|
||||||
$distribution = DB::table('budget_distributions')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $source['requisition_id'])->lockForUpdate()->first();
|
$originRequest = Requisition::query()->whereKey($source['requisition_id'])->firstOrFail();
|
||||||
|
$distribution = app(RequisitionBudgetDistributions::class)->source($originRequest, true);
|
||||||
if ($distribution === null) {
|
if ($distribution === null) {
|
||||||
$adoptionLines = Quotation::query()->whereKey($source['quotation_id'])->firstOrFail()->items()->orderBy('id')->get()
|
$adoptionLines = Quotation::query()->whereKey($source['quotation_id'])->firstOrFail()->items()->orderBy('id')->get()
|
||||||
->map(fn ($line) => ['line_id' => $line->requisition_item_id, 'description' => $line->description,
|
->map(fn ($line) => ['line_id' => $line->requisition_item_id, 'description' => $line->description,
|
||||||
@@ -111,7 +112,7 @@ final class OrderPartsWorkflow
|
|||||||
}
|
}
|
||||||
$revision = hash('sha256', json_encode(['quotation_id' => $quote->id, 'lines' => $lines], JSON_THROW_ON_ERROR));
|
$revision = hash('sha256', json_encode(['quotation_id' => $quote->id, 'lines' => $lines], JSON_THROW_ON_ERROR));
|
||||||
$adapter = app(CommonBudget::class);
|
$adapter = app(CommonBudget::class);
|
||||||
$engine = $adapter->for($actor);
|
$engine = $adapter->for($actor, RequisitionExpiry::cycles($request));
|
||||||
$adapter->execute(fn () => (new \ReflectionMethod($engine, 'adoptOrderSource'))->invoke($engine, $request->id,
|
$adapter->execute(fn () => (new \ReflectionMethod($engine, 'adoptOrderSource'))->invoke($engine, $request->id,
|
||||||
$allocations, $lines, $revision, strtolower($operation)));
|
$allocations, $lines, $revision, strtolower($operation)));
|
||||||
});
|
});
|
||||||
@@ -234,7 +235,7 @@ final class OrderPartsWorkflow
|
|||||||
$limits = app(AgreementOrderLimits::class)->freeze($actor, $firstQuote, $requests[0], $lines,
|
$limits = app(AgreementOrderLimits::class)->freeze($actor, $firstQuote, $requests[0], $lines,
|
||||||
$data['agreement_bindings'] ?? [], array_slice($requests, 1));
|
$data['agreement_bindings'] ?? [], array_slice($requests, 1));
|
||||||
$adapter = app(CommonBudget::class);
|
$adapter = app(CommonBudget::class);
|
||||||
$engine = $adapter->for($actor);
|
$engine = $adapter->for($actor, RequisitionExpiry::origins(array_column($prepared['sources'], 'requisition_id')));
|
||||||
$commit = $adapter->execute(fn () => (new \ReflectionMethod($engine, 'commitOrderParts'))->invoke($engine,
|
$commit = $adapter->execute(fn () => (new \ReflectionMethod($engine, 'commitOrderParts'))->invoke($engine,
|
||||||
$orderKey, $budgetSources, strtolower($data['operation_key'])));
|
$orderKey, $budgetSources, strtolower($data['operation_key'])));
|
||||||
$foreign = $prepared['currency'] !== 'MZN';
|
$foreign = $prepared['currency'] !== 'MZN';
|
||||||
@@ -291,7 +292,8 @@ final class OrderPartsWorkflow
|
|||||||
}
|
}
|
||||||
$byOrigin = array_column($financial, null, 'origin');
|
$byOrigin = array_column($financial, null, 'origin');
|
||||||
foreach ($sources as $source) {
|
foreach ($sources as $source) {
|
||||||
$distribution = DB::table('budget_distributions')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $source['requisition_id'])->lockForUpdate()->first();
|
$originRequest = Requisition::query()->whereKey($source['requisition_id'])->firstOrFail();
|
||||||
|
$distribution = app(RequisitionBudgetDistributions::class)->source($originRequest, true);
|
||||||
abort_unless($distribution !== null, 422, 'Prepare a distribuição ou a adopção explícita da reserva antes de emitir parcelas.');
|
abort_unless($distribution !== null, 422, 'Prepare a distribuição ou a adopção explícita da reserva antes de emitir parcelas.');
|
||||||
$snapshot = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR);
|
$snapshot = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR);
|
||||||
$frozen = array_column($snapshot['allocations'], null, 'allocation_key');
|
$frozen = array_column($snapshot['allocations'], null, 'allocation_key');
|
||||||
|
|||||||
@@ -57,7 +57,14 @@ class RequisitionBudgetDistributions
|
|||||||
public function applies(Requisition $request): bool
|
public function applies(Requisition $request): bool
|
||||||
{
|
{
|
||||||
return $request->getAttribute('budget_distribution_preparation') !== null
|
return $request->getAttribute('budget_distribution_preparation') !== null
|
||||||
|| (Schema::hasTable('budget_distributions') && DB::table('budget_distributions')->where('tenant_id', $request->tenant_id)->where('requisition_id', $request->id)->exists());
|
|| (Schema::hasTable('budget_distributions') && $this->source($request) !== null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function source(Requisition $request, bool $lock = false): ?\stdClass
|
||||||
|
{
|
||||||
|
return DB::table('budget_distributions')->where('tenant_id', $request->tenant_id)->where('requisition_id', $request->id)
|
||||||
|
->when(Schema::hasColumn('budget_distributions', 'requisition_cycle'), fn ($q) => $q->where('requisition_cycle', $request->getAttribute('approval_cycle') ?? 1))
|
||||||
|
->when($lock, fn ($q) => $q->lockForUpdate())->first();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return list<array<string,mixed>>|null */
|
/** @return list<array<string,mixed>>|null */
|
||||||
@@ -68,7 +75,7 @@ class RequisitionBudgetDistributions
|
|||||||
}
|
}
|
||||||
abort_unless(auth()->id() === $actor->id && $actor->tenant_id === $request->tenant_id
|
abort_unless(auth()->id() === $actor->id && $actor->tenant_id === $request->tenant_id
|
||||||
&& Requisition::query()->visibleTo($actor)->whereKey($request->id)->exists(), 403);
|
&& Requisition::query()->visibleTo($actor)->whereKey($request->id)->exists(), 403);
|
||||||
$source = DB::table('budget_distributions')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $request->id)->first();
|
$source = $this->source($request);
|
||||||
$plan = $source ? json_decode($source->snapshot, true, 64, JSON_THROW_ON_ERROR)['allocations'] : ($request->budget_distribution_preparation['allocations'] ?? []);
|
$plan = $source ? json_decode($source->snapshot, true, 64, JSON_THROW_ON_ERROR)['allocations'] : ($request->budget_distribution_preparation['allocations'] ?? []);
|
||||||
$lines = $request->items()->get()->keyBy('id');
|
$lines = $request->items()->get()->keyBy('id');
|
||||||
$centres = CostCenter::query()->where('tenant_id', $actor->tenant_id)->whereIn('id', array_column($plan, 'centre_id'))->get()->keyBy('id');
|
$centres = CostCenter::query()->where('tenant_id', $actor->tenant_id)->whereIn('id', array_column($plan, 'centre_id'))->get()->keyBy('id');
|
||||||
@@ -98,7 +105,7 @@ class RequisitionBudgetDistributions
|
|||||||
$request = Requisition::query()->lockForUpdate()->findOrFail($order->requisition_id);
|
$request = Requisition::query()->lockForUpdate()->findOrFail($order->requisition_id);
|
||||||
app(ConflictGuard::class)->assertProcess($request, $order->supplier_id, $actor);
|
app(ConflictGuard::class)->assertProcess($request, $order->supplier_id, $actor);
|
||||||
$data = Validator::make($input, [...$this->rules($request), 'operation_key' => 'required|uuid', 'expected_plan_hash' => ['required', 'regex:/^[a-f0-9]{64}$/D']])->validate();
|
$data = Validator::make($input, [...$this->rules($request), 'operation_key' => 'required|uuid', 'expected_plan_hash' => ['required', 'regex:/^[a-f0-9]{64}$/D']])->validate();
|
||||||
$source = DB::table('budget_distributions')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $request->id)->lockForUpdate()->first();
|
$source = $this->source($request, true);
|
||||||
abort_unless($source !== null && $source->phase === 'commit', 409);
|
abort_unless($source !== null && $source->phase === 'commit', 409);
|
||||||
$snapshot = json_decode($source->snapshot, true, 64, JSON_THROW_ON_ERROR);
|
$snapshot = json_decode($source->snapshot, true, 64, JSON_THROW_ON_ERROR);
|
||||||
$reference = app(QuotationExchange::class)->orderAmounts($order, $order->subtotal_minor, $order->tax_minor);
|
$reference = app(QuotationExchange::class)->orderAmounts($order, $order->subtotal_minor, $order->tax_minor);
|
||||||
@@ -115,7 +122,7 @@ class RequisitionBudgetDistributions
|
|||||||
$lines[$allocation['line_id']]['subtotal_minor'] += $allocation['subtotal_minor'];
|
$lines[$allocation['line_id']]['subtotal_minor'] += $allocation['subtotal_minor'];
|
||||||
$lines[$allocation['line_id']]['total_minor'] += $allocation['total_minor'];
|
$lines[$allocation['line_id']]['total_minor'] += $allocation['total_minor'];
|
||||||
}
|
}
|
||||||
$engine = app(CommonBudget::class)->for($actor);
|
$engine = app(CommonBudget::class)->for($actor, RequisitionExpiry::cycles($request));
|
||||||
$method = new \ReflectionMethod($engine, 'amendDistribution');
|
$method = new \ReflectionMethod($engine, 'amendDistribution');
|
||||||
$result = app(CommonBudget::class)->execute(fn () => $method->invoke($engine, $request->id, $allocations,
|
$result = app(CommonBudget::class)->execute(fn () => $method->invoke($engine, $request->id, $allocations,
|
||||||
$data['expected_plan_hash'], $data['reason'], $data['operation_key'], $lines));
|
$data['expected_plan_hash'], $data['reason'], $data['operation_key'], $lines));
|
||||||
@@ -234,7 +241,7 @@ class RequisitionBudgetDistributions
|
|||||||
{
|
{
|
||||||
abort_unless($this->ready(), 503, 'A distribuição exige a composição compatível; não foi aplicado o contrato antigo.');
|
abort_unless($this->ready(), 503, 'A distribuição exige a composição compatível; não foi aplicado o contrato antigo.');
|
||||||
$prepared = $request->budget_distribution_preparation;
|
$prepared = $request->budget_distribution_preparation;
|
||||||
$source = DB::table('budget_distributions')->where('tenant_id', $request->tenant_id)->where('requisition_id', $request->id)->first();
|
$source = $this->source($request);
|
||||||
if (in_array($kind, ['release', 'cancel'], true) && $source !== null) {
|
if (in_array($kind, ['release', 'cancel'], true) && $source !== null) {
|
||||||
$frozen = json_decode($source->snapshot, true, 64, JSON_THROW_ON_ERROR);
|
$frozen = json_decode($source->snapshot, true, 64, JSON_THROW_ON_ERROR);
|
||||||
$allocations = array_map(fn (array $row) => array_intersect_key($row, array_flip(['allocation_key', 'line_id', 'centre_id', 'subtotal_minor', 'total_minor'])), $frozen['allocations']);
|
$allocations = array_map(fn (array $row) => array_intersect_key($row, array_flip(['allocation_key', 'line_id', 'centre_id', 'subtotal_minor', 'total_minor'])), $frozen['allocations']);
|
||||||
@@ -269,7 +276,7 @@ class RequisitionBudgetDistributions
|
|||||||
}
|
}
|
||||||
$revision = $quote === null ? $prepared['source_revision'] : hash('sha256', json_encode(['quotation_id' => $quote->id, 'lines' => $lines], JSON_THROW_ON_ERROR));
|
$revision = $quote === null ? $prepared['source_revision'] : hash('sha256', json_encode(['quotation_id' => $quote->id, 'lines' => $lines], JSON_THROW_ON_ERROR));
|
||||||
}
|
}
|
||||||
$engine = app(CommonBudget::class)->for($actor);
|
$engine = app(CommonBudget::class)->for($actor, RequisitionExpiry::cycles($request));
|
||||||
$method = new \ReflectionMethod($engine, 'recordDistribution');
|
$method = new \ReflectionMethod($engine, 'recordDistribution');
|
||||||
$result = app(CommonBudget::class)->execute(fn () => $method->invoke($engine, $request->id, $kind, $allocations, $lines, $revision, (string) Str::uuid()));
|
$result = app(CommonBudget::class)->execute(fn () => $method->invoke($engine, $request->id, $kind, $allocations, $lines, $revision, (string) Str::uuid()));
|
||||||
if (! is_array($result)) {
|
if (! is_array($result)) {
|
||||||
|
|||||||
@@ -0,0 +1,315 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services;
|
||||||
|
|
||||||
|
use App\Models\PurchaseOrder;
|
||||||
|
use App\Models\Requisition;
|
||||||
|
use App\Models\SupplyRecord;
|
||||||
|
use App\Models\User;
|
||||||
|
use Carbon\CarbonImmutable;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
use Illuminate\Support\Facades\Validator;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Illuminate\Validation\Rule;
|
||||||
|
use Illuminate\Validation\ValidationException;
|
||||||
|
use Tempo\Finance\Budget\BudgetControl;
|
||||||
|
use Tempo\Purchasing\Internal\InternalRequisitions;
|
||||||
|
|
||||||
|
/** Company-defined elapsed-time policy; no default deadlines, approvers or grants. */
|
||||||
|
final class RequisitionExpiry
|
||||||
|
{
|
||||||
|
public const ROLES = ['department_head', 'procurement', 'finance', 'configured_1', 'configured_2', 'configured_3', 'configured_4', 'configured_5'];
|
||||||
|
|
||||||
|
public function ready(): bool
|
||||||
|
{
|
||||||
|
$db = DB::connection();
|
||||||
|
$purchasing = new \ReflectionClass(InternalRequisitions::class);
|
||||||
|
|
||||||
|
return config('requisition-expiry.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())))
|
||||||
|
&& $purchasing->hasMethod('supportsExpiryCycles') && $purchasing->getMethod('supportsExpiryCycles')->invoke(null) === true
|
||||||
|
&& defined(BudgetControl::class.'::REQUISITION_CYCLES_VERSION')
|
||||||
|
&& constant(BudgetControl::class.'::REQUISITION_CYCLES_VERSION') === CommonBudget::REQUISITION_CYCLES_CONTRACT
|
||||||
|
&& Schema::hasTable('budget_requisition_cycles') && Schema::hasColumn('requisitions', 'approval_cycle')
|
||||||
|
&& Schema::hasTable('workflow_notices') && Schema::hasTable('requisition_commands') && Schema::hasColumn('requisitions', 'process_version')
|
||||||
|
&& Schema::hasColumn('approval_steps', 'approval_cycle') && Schema::hasColumn('budget_entries', 'requisition_cycle');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<int,int> */
|
||||||
|
public static function cycles(Requisition $request): array
|
||||||
|
{
|
||||||
|
return [$request->id => (int) ($request->getAttribute('approval_cycle') ?? 1)];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Identifiers can originate in a validated command payload; resolve actual scoped models.
|
||||||
|
* @param array<mixed> $originIds
|
||||||
|
* @return array<int,int>
|
||||||
|
*/
|
||||||
|
public static function origins(array $originIds): array
|
||||||
|
{
|
||||||
|
Validator::make(['origins' => $originIds], ['origins' => 'required|array|list', 'origins.*' => 'required|integer|min:1'])->validate();
|
||||||
|
$requests = Requisition::query()->whereIn('id', $originIds)->get(Schema::hasColumn('requisitions', 'approval_cycle') ? ['id', 'approval_cycle'] : ['id']);
|
||||||
|
abort_unless($requests->count() === count(array_unique($originIds)), 404);
|
||||||
|
$result = [];
|
||||||
|
foreach ($requests as $request) {
|
||||||
|
$result += self::cycles($request);
|
||||||
|
}
|
||||||
|
ksort($result, SORT_NUMERIC);
|
||||||
|
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<int,int> */
|
||||||
|
public static function orderCycles(PurchaseOrder $order): array
|
||||||
|
{
|
||||||
|
return self::origins(app(OrderPartsAccess::class)->origins($order));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function assertOperational(Requisition $request): void
|
||||||
|
{
|
||||||
|
if ((int) ($request->getAttribute('approval_cycle') ?? 1) > 1 || isset($request->approval_snapshot['approval_expiry'])) {
|
||||||
|
abort_unless($this->ready(), 503, 'Preserve a composição compatível dos ciclos antes de alterar esta requisição.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string,mixed> */
|
||||||
|
public function settings(User $actor): array
|
||||||
|
{
|
||||||
|
abort_unless($this->ready(), 503);
|
||||||
|
|
||||||
|
return DB::transaction(function () use ($actor) {
|
||||||
|
app(ConflictGuard::class)->lockCompany($actor);
|
||||||
|
$actor = app(CurrentActor::class)->lock($actor);
|
||||||
|
abort_unless($actor->hasFunctions(['admin']) && ! app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||||
|
|
||||||
|
return ['current' => SupplyRecord::query()->where('kind', 'req_expiry_policy')->latest('id')->first(),
|
||||||
|
'history' => SupplyRecord::query()->where('kind', 'req_expiry_policy')->latest('id')->paginate(15)->withQueryString(),
|
||||||
|
'profiles' => DB::table('organization_profiles')->where('tenant_id', $actor->tenant_id)->orderBy('name')->get(['id', 'name']),
|
||||||
|
'roles' => ['department_head' => 'Chefia de departamento', 'procurement' => 'Compras', 'finance' => 'Finanças',
|
||||||
|
'configured_1' => 'Nível adicional 1', 'configured_2' => 'Nível adicional 2', 'configured_3' => 'Nível adicional 3',
|
||||||
|
'configured_4' => 'Nível adicional 4', 'configured_5' => 'Nível adicional 5'],
|
||||||
|
'actorId' => $actor->id, 'tenantId' => $actor->tenant_id];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string,mixed> */
|
||||||
|
public function workspace(User $actor, Requisition $request): array
|
||||||
|
{
|
||||||
|
abort_unless($this->ready(), 503);
|
||||||
|
|
||||||
|
return DB::transaction(function () use ($actor, $request) {
|
||||||
|
app(ConflictGuard::class)->lockCompany($actor);
|
||||||
|
$actor = app(CurrentActor::class)->lock($actor);
|
||||||
|
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||||
|
abort_unless(app(OrganizationAccess::class)->permissions($actor) !== [], 403);
|
||||||
|
$request = Requisition::query()->visibleTo($actor)->whereKey($request->id)->firstOrFail();
|
||||||
|
$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]);
|
||||||
|
|
||||||
|
return ['requisition' => [...$request->only(['id', 'number', 'status', 'process_version', 'requester_id']),
|
||||||
|
'approval_cycle' => $request->getAttribute('approval_cycle') ?? 1], 'deadline' => $deadline, 'history' => $history,
|
||||||
|
'canExpire' => $deadline['state'] === 'expired' && ! app(ConflictGuard::class)->participationBlocked($actor, $request),
|
||||||
|
'canEdit' => $request->status === 'draft' && (int) ($request->getAttribute('approval_cycle') ?? 1) > 1
|
||||||
|
&& $request->requester_id === $actor->id && app(OrganizationAccess::class)->canRequest($actor),
|
||||||
|
'actorId' => $actor->id, 'tenantId' => $actor->tenant_id];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array<string,mixed> $input */
|
||||||
|
public function savePolicy(User $actor, array $input): SupplyRecord
|
||||||
|
{
|
||||||
|
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.*.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();
|
||||||
|
$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];
|
||||||
|
}
|
||||||
|
$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'] !== [])) {
|
||||||
|
throw ValidationException::withMessages(['levels.'.$index => 'Configure lembrete e escalamento antes da expiração, com destinatários explícitos apenas quando houver escalamento.']);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
unset($level);
|
||||||
|
usort($data['levels'], fn ($a, $b) => strcmp($a['role'], $b['role']));
|
||||||
|
if ($data['enabled'] && $data['levels'] === []) {
|
||||||
|
throw ValidationException::withMessages(['levels' => 'Configure pelo menos um nível antes de activar a política.']);
|
||||||
|
}
|
||||||
|
$hash = hash('sha256', json_encode($data, JSON_THROW_ON_ERROR));
|
||||||
|
|
||||||
|
return DB::transaction(function () use ($actor, $data, $hash) {
|
||||||
|
app(ConflictGuard::class)->lockCompany($actor);
|
||||||
|
$actor = app(CurrentActor::class)->lock($actor);
|
||||||
|
abort_unless($actor->hasFunctions(['admin']) && ! app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||||
|
$retry = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
|
||||||
|
if ($retry !== null) {
|
||||||
|
abort_unless($retry->kind === 'req_expiry_policy' && $retry->created_by === $actor->id && hash_equals($retry->input_hash, $hash), 409);
|
||||||
|
|
||||||
|
return $retry;
|
||||||
|
}
|
||||||
|
$old = SupplyRecord::query()->where('kind', 'req_expiry_policy')->latest('id')->first();
|
||||||
|
abort_unless((int) $data['version'] === ($old->version ?? 0), 409, 'A política mudou. Consulte a versão actual.');
|
||||||
|
foreach ($data['levels'] as $level) {
|
||||||
|
abort_unless(DB::table('organization_profiles')->where('tenant_id', $actor->tenant_id)->whereIn('id', $level['profile_ids'])->count() === count($level['profile_ids']), 422);
|
||||||
|
}
|
||||||
|
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'req_expiry_policy',
|
||||||
|
'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1,
|
||||||
|
'state' => $data['enabled'] ? 'active' : 'inactive', 'created_by' => $actor->id,
|
||||||
|
'data' => ['enabled' => $data['enabled'], 'levels' => $data['levels'], 'time_basis' => 'elapsed_minutes', 'expiry_effect' => 'return_to_requester_draft'],
|
||||||
|
'snapshot' => ['new_permissions' => false], 'reason' => trim($data['reason']), 'operation_key' => $data['operation_key'],
|
||||||
|
'input_hash' => $hash, 'created_at' => now()]);
|
||||||
|
app(RequisitionWorkflow::class)->audit($actor, 'requisition.expiry_policy_saved', null, $old?->toArray(), ['record' => $record->toArray()]);
|
||||||
|
|
||||||
|
return $record;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string,mixed>|null */
|
||||||
|
public function policy(Requisition $request): ?array
|
||||||
|
{
|
||||||
|
$this->assertOperational($request);
|
||||||
|
if (! $this->ready()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
$source = SupplyRecord::query()->where('kind', 'req_expiry_policy')->latest('id')->first();
|
||||||
|
if ($source === null || $source->state !== 'active') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return ['id' => $source->id, 'version' => $source->version, 'data' => $source->data,
|
||||||
|
'fingerprint' => hash('sha256', json_encode($source->data, JSON_THROW_ON_ERROR))];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string,mixed> */
|
||||||
|
public function deadline(Requisition $request): array
|
||||||
|
{
|
||||||
|
$this->assertOperational($request);
|
||||||
|
$inactive = ['state' => 'inactive', 'step_id' => null, 'expires_at' => null, 'basis_hash' => null];
|
||||||
|
if ($request->status !== 'pending') {
|
||||||
|
return $inactive;
|
||||||
|
}
|
||||||
|
$policy = $request->approval_snapshot['approval_expiry'] ?? null;
|
||||||
|
if ($policy === null) {
|
||||||
|
return [...$inactive, 'state' => 'unconfigured'];
|
||||||
|
}
|
||||||
|
$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.');
|
||||||
|
$steps = $request->steps()->orderBy('position')->get();
|
||||||
|
$step = $steps->firstWhere('decision', 'pending');
|
||||||
|
$settings = null;
|
||||||
|
if ($step !== null) {
|
||||||
|
foreach ($policy['data']['levels'] as $level) {
|
||||||
|
if ($level['role'] === $step->role) {
|
||||||
|
$settings = $level;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($step === null || $settings === null || $request->submitted_at === null) {
|
||||||
|
return [...$inactive, 'state' => 'unconfigured', 'step_id' => $step?->id];
|
||||||
|
}
|
||||||
|
$start = CarbonImmutable::parse($request->submitted_at);
|
||||||
|
foreach ($steps->where('position', '<', $step->position) as $previous) {
|
||||||
|
if ($previous->decision !== 'approved' || $previous->decided_at === null) {
|
||||||
|
return [...$inactive, 'state' => 'unverified', 'step_id' => $step->id];
|
||||||
|
}
|
||||||
|
$date = CarbonImmutable::parse($previous->decided_at, config('app.timezone'));
|
||||||
|
if ($date < $start || $date > now()) {
|
||||||
|
return [...$inactive, 'state' => 'unverified', 'step_id' => $step->id];
|
||||||
|
}
|
||||||
|
$start = $date;
|
||||||
|
}
|
||||||
|
if ($start > now()) {
|
||||||
|
return [...$inactive, 'state' => 'unverified', 'step_id' => $step->id];
|
||||||
|
}
|
||||||
|
$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()];
|
||||||
|
|
||||||
|
return ['state' => now()->greaterThanOrEqualTo($end) ? 'expired' : 'running', 'step_id' => $step->id,
|
||||||
|
'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(),
|
||||||
|
'profile_ids' => $settings['profile_ids'], 'policy_id' => $source->id, 'basis_hash' => hash('sha256', json_encode($basis, JSON_THROW_ON_ERROR))];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array<string,mixed> $policy */
|
||||||
|
public function begin(User $actor, Requisition $request, array $policy, ?string $operation): void
|
||||||
|
{
|
||||||
|
$cycle = (int) ($request->getAttribute('approval_cycle') ?? 1);
|
||||||
|
if ($cycle === 1 && ! isset($policy['approval_expiry'])) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
abort_unless($this->ready(), 503);
|
||||||
|
if ($operation === null) {
|
||||||
|
throw ValidationException::withMessages(['operation_key' => 'A submissão por ciclos exige uma operação identificada.']);
|
||||||
|
}
|
||||||
|
$engine = app(CommonBudget::class)->for($actor, self::cycles($request));
|
||||||
|
app(CommonBudget::class)->execute(fn () => (new \ReflectionMethod($engine, 'beginRequisitionCycle'))->invoke($engine, $request->id, $cycle, $operation));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array<string,mixed> $input
|
||||||
|
* @return array<string,mixed>
|
||||||
|
*/
|
||||||
|
public function proof(User $actor, Requisition $request, array $input): array
|
||||||
|
{
|
||||||
|
abort_unless($this->ready() && DB::transactionLevel() > 0, 503);
|
||||||
|
Requisition::query()->visibleTo($actor)->whereKey($request->id)->firstOrFail();
|
||||||
|
$data = Validator::make($input, ['operation_key' => 'required|uuid', 'basis_hash' => ['required', 'regex:/^[a-f0-9]{64}$/D'],
|
||||||
|
'comment' => 'nullable|string|max:2000'])->validate();
|
||||||
|
$deadline = $this->deadline($request);
|
||||||
|
abort_unless($deadline['state'] === 'expired' && hash_equals($deadline['basis_hash'], $data['basis_hash']), 409,
|
||||||
|
'O prazo ou a etapa mudou, ou ainda não terminou. Actualize a conferência antes de devolver o pedido.');
|
||||||
|
abort_if(SupplyRecord::query()->where('operation_key', $data['operation_key'])->exists(), 409, 'A operação pertence a outro registo.');
|
||||||
|
|
||||||
|
return [...$deadline, 'operation_key' => strtolower($data['operation_key']),
|
||||||
|
'reason' => 'Prazo da etapa terminado em '.$deadline['expires_at'].'; devolução para nova submissão conforme a política #'.$deadline['policy_id'].'.'
|
||||||
|
.(empty($data['comment']) ? '' : ' '.trim($data['comment']))];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array<string,mixed> $proof */
|
||||||
|
public function returned(User $actor, Requisition $request, array $proof): void
|
||||||
|
{
|
||||||
|
abort_unless($this->ready() && DB::transactionLevel() > 0 && $request->status === 'pending', 409);
|
||||||
|
$cycle = (int) $request->getAttribute('approval_cycle');
|
||||||
|
abort_unless($cycle > 0 && $cycle < 1000000, 409);
|
||||||
|
$engine = app(CommonBudget::class)->for($actor, self::cycles($request));
|
||||||
|
app(CommonBudget::class)->execute(fn () => (new \ReflectionMethod($engine, 'closeRequisitionCycle'))->invoke($engine, $request->id, $cycle, $proof['operation_key']));
|
||||||
|
$before = $request->only(['id', 'number', 'status', 'approval_cycle', 'submitted_at', 'process_version', 'requester_id', 'department_id',
|
||||||
|
'cost_center_id', 'priority', 'needed_by', 'justification', 'subtotal_minor', 'tax_minor', 'total_minor']);
|
||||||
|
$steps = $request->steps()->get()->toArray();
|
||||||
|
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'req_expiration', 'record_key' => (string) Str::uuid(),
|
||||||
|
'version' => 1, 'state' => 'returned', 'created_by' => $actor->id,
|
||||||
|
'data' => ['requisition_id' => $request->id, 'cycle' => $cycle, 'step_id' => $proof['step_id'], 'expires_at' => $proof['expires_at'],
|
||||||
|
'policy_id' => $proof['policy_id'], 'next_cycle' => $cycle + 1],
|
||||||
|
'snapshot' => ['request' => $before, 'items' => $request->items()->orderBy('id')->get()->toArray(), 'steps' => $steps,
|
||||||
|
'approval_snapshot' => $request->approval_snapshot, 'proof' => $proof],
|
||||||
|
'reason' => $proof['reason'], 'operation_key' => $proof['operation_key'], 'input_hash' => hash('sha256', json_encode($proof, JSON_THROW_ON_ERROR)), 'created_at' => now()]);
|
||||||
|
// Close only unacted tasks. Approved decisions remain unchanged in their original rows.
|
||||||
|
$request->steps()->where('decision', 'pending')->update(['decision' => 'expired', 'comment' => $proof['reason']]);
|
||||||
|
$request->setAttribute('status', 'draft');
|
||||||
|
$request->setAttribute('approval_cycle', $cycle + 1);
|
||||||
|
$request->setAttribute('submitted_at', null);
|
||||||
|
$request->setAttribute('process_version', (int) $request->getAttribute('process_version') + 1);
|
||||||
|
$request->save();
|
||||||
|
app(WorkflowNotices::class)->expired($request, $proof['step_id']);
|
||||||
|
app(RequisitionWorkflow::class)->audit($actor, 'requisition.expired_returned', $request, $before,
|
||||||
|
['status' => 'draft', 'cycle' => $cycle + 1, 'expiration_record_id' => $record->id, 'reason' => $proof['reason']]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -173,6 +173,11 @@ class RequisitionWorkflow
|
|||||||
app(AutomaticPurchases::class)->requisitionChanged($user, $requisition);
|
app(AutomaticPurchases::class)->requisitionChanged($user, $requisition);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function expire(User $user, Requisition $requisition, string $basisHash, string $operationKey, int $version, ?string $comment = null): void
|
||||||
|
{
|
||||||
|
$this->execute($user, 'expire', $requisition->id, $version, $operationKey, ['basis_hash' => $basisHash, 'comment' => $comment]);
|
||||||
|
}
|
||||||
|
|
||||||
/** @param array<string, mixed>|null $before
|
/** @param array<string, mixed>|null $before
|
||||||
* @param array<string, mixed> $after
|
* @param array<string, mixed> $after
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -80,6 +80,23 @@ class WorkflowNotices
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function expired(Requisition $requisition, int $stepId): void
|
||||||
|
{
|
||||||
|
if (! Schema::hasTable('workflow_notices')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (DB::transactionLevel() === 0) {
|
||||||
|
throw new \LogicException('Aviso de devolução exige a transacção da expiração.');
|
||||||
|
}
|
||||||
|
$step = $requisition->allSteps()->whereKey($stepId)->firstOrFail();
|
||||||
|
if ($requisition->status !== 'draft' || $step->decision !== 'expired') {
|
||||||
|
throw new \LogicException('O aviso exige a devolução efectivamente registada.');
|
||||||
|
}
|
||||||
|
$recipient = User::query()->where('tenant_id', $requisition->tenant_id)->whereKey($requisition->requester_id)->firstOrFail();
|
||||||
|
DB::table('workflow_notices')->insertOrIgnore(['tenant_id' => $requisition->tenant_id, 'requisition_id' => $requisition->id,
|
||||||
|
'approval_step_id' => $step->id, 'recipient_id' => $recipient->id, 'reference' => $requisition->number, 'role' => $step->role, 'created_at' => now()]);
|
||||||
|
}
|
||||||
|
|
||||||
/** @return list<array<string,mixed>> */
|
/** @return list<array<string,mixed>> */
|
||||||
public function visible(User $actor): array
|
public function visible(User $actor): array
|
||||||
{
|
{
|
||||||
@@ -92,14 +109,15 @@ class WorkflowNotices
|
|||||||
if ($request === null) {
|
if ($request === null) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
$step = $request->steps->firstWhere('id', $notice->approval_step_id);
|
$step = $request->steps->firstWhere('id', $notice->approval_step_id)
|
||||||
$outcome = $request->requester_id === $actor->id && $step !== null && in_array($step->decision, ['approved', 'rejected'], true);
|
?? $request->allSteps()->whereKey($notice->approval_step_id)->first();
|
||||||
|
$outcome = $request->requester_id === $actor->id && $step !== null && in_array($step->decision, ['approved', 'rejected', 'expired'], true);
|
||||||
if (! $outcome && (! $request->canDecide($actor) || $request->steps->firstWhere('decision', 'pending')?->id !== $notice->approval_step_id)) {
|
if (! $outcome && (! $request->canDecide($actor) || $request->steps->firstWhere('decision', 'pending')?->id !== $notice->approval_step_id)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
$items[] = ['id' => $notice->id, 'reference' => $notice->reference, 'role' => $notice->role, 'role_label' => $step?->routing['name'] ?? null,
|
$items[] = ['id' => $notice->id, 'reference' => $notice->reference, 'role' => $notice->role, 'role_label' => $step?->routing['name'] ?? null,
|
||||||
'kind' => $outcome ? 'outcome' : 'task', 'outcome' => $outcome ? $step->decision : null, 'current_status' => $request->status,
|
'kind' => $outcome ? 'outcome' : 'task', 'outcome' => $outcome ? $step->decision : null, 'current_status' => $request->status,
|
||||||
'created_at' => $notice->created_at, 'read_at' => $notice->read_at, 'href' => '/requisicoes/'.$request->id];
|
'created_at' => $notice->created_at, 'read_at' => $notice->read_at, 'href' => '/requisicoes/'.$request->id.($outcome && $step->decision === 'expired' ? '/prazos' : '')];
|
||||||
}
|
}
|
||||||
|
|
||||||
return $items;
|
return $items;
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
return ['qa_enabled' => false];
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
|
// Explicit cycle-contract QA only. Never discovered by operational migrate.
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
$db = DB::connection();
|
||||||
|
$isolated = ($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()));
|
||||||
|
if (! app()->environment('testing') || ! $isolated) {
|
||||||
|
throw new LogicException('Approval and budget cycle schema requires isolated QA.');
|
||||||
|
}
|
||||||
|
$schema = $db->getSchemaBuilder();
|
||||||
|
if ($schema->hasTable('budget_requisition_cycles') || $schema->hasColumn('requisitions', 'approval_cycle')
|
||||||
|
|| $schema->hasColumn('budget_entries', 'requisition_cycle')) {
|
||||||
|
throw new LogicException('Do not reinstall or repair partial cycle structures automatically.');
|
||||||
|
}
|
||||||
|
$schema->table('requisitions', fn (Blueprint $table) => $table->unsignedInteger('approval_cycle')->default(1));
|
||||||
|
$schema->table('approval_steps', function (Blueprint $table) {
|
||||||
|
$table->unsignedInteger('approval_cycle')->default(1);
|
||||||
|
$table->dropUnique(['requisition_id', 'position']);
|
||||||
|
$table->unique(['requisition_id', 'approval_cycle', 'position'], 'approval_step_cycle_position');
|
||||||
|
});
|
||||||
|
$schema->table('budget_entries', function (Blueprint $table) {
|
||||||
|
$table->unsignedInteger('requisition_cycle')->default(1);
|
||||||
|
$table->dropUnique(['requisition_id', 'kind']);
|
||||||
|
$table->unique(['requisition_id', 'requisition_cycle', 'kind'], 'budget_entry_cycle_kind');
|
||||||
|
});
|
||||||
|
if ($schema->hasTable('budget_distributions')) {
|
||||||
|
$schema->table('budget_distributions', function (Blueprint $table) {
|
||||||
|
$table->unsignedInteger('requisition_cycle')->default(1);
|
||||||
|
$table->dropUnique(['requisition_id']);
|
||||||
|
$table->unique(['requisition_id', 'requisition_cycle'], 'budget_distribution_cycle');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
$schema->create('budget_requisition_cycles', function (Blueprint $table) {
|
||||||
|
$table->id();
|
||||||
|
$table->foreignId('tenant_id')->constrained()->restrictOnDelete();
|
||||||
|
$table->foreignId('requisition_id')->constrained()->restrictOnDelete();
|
||||||
|
$table->unsignedInteger('cycle');
|
||||||
|
$table->string('state', 20);
|
||||||
|
$table->uuid('open_operation');
|
||||||
|
$table->foreignId('opened_by')->constrained('users')->restrictOnDelete();
|
||||||
|
$table->timestamp('opened_at');
|
||||||
|
$table->uuid('close_operation')->nullable();
|
||||||
|
$table->foreignId('closed_by')->nullable()->constrained('users')->restrictOnDelete();
|
||||||
|
$table->timestamp('closed_at')->nullable();
|
||||||
|
$table->unique(['tenant_id', 'requisition_id', 'cycle'], 'budget_requisition_cycle');
|
||||||
|
$table->unique(['tenant_id', 'open_operation']);
|
||||||
|
$table->unique(['tenant_id', 'close_operation']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
throw new LogicException('Restore the verified pre-cycle backup and compatible artifact; never delete previous approval or financial cycles.');
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -1,5 +1,11 @@
|
|||||||
# Desenvolvimento do SGC
|
# Desenvolvimento do SGC
|
||||||
|
|
||||||
|
## Uniformização dos formulários e relatórios — 27/11/2026
|
||||||
|
|
||||||
|
Aplicado o benchmark aprovado aos componentes existentes `PageTitle`, `Panel` e `controlClass`; barras `ActionBar` e tabelas `TableViewport` partilhadas. Base visual consumida por 91 páginas; 31 páginas adaptadas explicitamente, incluindo requisições/distribuições, fornecedores, compras, relatórios de Compras/Pessoas, stock, importações e administração. Títulos responsivos, painéis identificados para acessibilidade, acções adaptáveis ao telemóvel, tabelas com deslocamento por teclado e resumo comum de erros nos relatórios. Campos, handlers, condicionais de acesso, filtros/CSV, valores e destinos preservados; sem alterações ao servidor, regras, permissões ou migrações nesta tarefa. Trabalho financeiro/cadastro em curso preservado.
|
||||||
|
|
||||||
|
Verificação: 45 ficheiros/193 testes frontend aprovados; TypeScript, formatação/lint dirigido sem avisos e build exclusivamente privado aprovados. Pré-visualização estática dos componentes reais com dados sintéticos: requisição e fornecedor a390px, relatório de25linhas a390/1280px; sem transbordo da página a390px e deslocamento horizontal da tabela por teclado observado. Servidor de pré-visualização encerrado, viewport reposto e separador temporário fechado. Isto não demonstra gravação ponta a ponta, revisão visual de todas as91páginas nem impressão multipágina. Não actualizado `public/build` do piloto, sem instalação/activação/publicação. Prova: `proofs/screen-standardisation-qa.json`. Próximo critério: conferência nativa dos formulários restantes e impressão multipágina, com dados sintéticos e sem repetir provas válidas.
|
||||||
|
|
||||||
Decisão expressa nesta continuação: projectos e imobilizado terão cadastro próprio em Compras, independente do SGF. Implementação em curso, apenas QA, sem efeitos contabilísticos nem instalação no piloto. Reutilizar as fichas físicas de equipamento existentes; não criar dependência SGF. Revisão bancária nativa posterior gravou versão 2 com comprovativo/data/fundamento sintéticos, conservou versão 1 e retirou os avisos de entrega pendente/prazo de hoje. Ambiente privado encerrado e removido.
|
Decisão expressa nesta continuação: projectos e imobilizado terão cadastro próprio em Compras, independente do SGF. Implementação em curso, apenas QA, sem efeitos contabilísticos nem instalação no piloto. Reutilizar as fichas físicas de equipamento existentes; não criar dependência SGF. Revisão bancária nativa posterior gravou versão 2 com comprovativo/data/fundamento sintéticos, conservou versão 1 e retirou os avisos de entrega pendente/prazo de hoje. Ambiente privado encerrado e removido.
|
||||||
|
|
||||||
Revisão nativa posterior em Edge: base legal observada a 390/823px sem transbordo horizontal; reutilização explícita da base sintética de 100 MZN gravou versão 2 de 7,50 MZN. Plano anterior conservou a origem escolhida #5 e total 107,50 MZN. Acompanhamento apresentou desconhecidos e pendências bancárias esperados. Servidor/raiz/base QA removidos, separadores do utilizador preservados. Prova ampliada em `proofs/import-legal-amounts-qa.json`. Esta revisão substitui apenas a indicação de revisão ainda não iniciada; impressão e aceitação visual transversal continuam por verificar.
|
Revisão nativa posterior em Edge: base legal observada a 390/823px sem transbordo horizontal; reutilização explícita da base sintética de 100 MZN gravou versão 2 de 7,50 MZN. Plano anterior conservou a origem escolhida #5 e total 107,50 MZN. Acompanhamento apresentou desconhecidos e pendências bancárias esperados. Servidor/raiz/base QA removidos, separadores do utilizador preservados. Prova ampliada em `proofs/import-legal-amounts-qa.json`. Esta revisão substitui apenas a indicação de revisão ainda não iniciada; impressão e aceitação visual transversal continuam por verificar.
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
# Matriz reconciliada do SGC — 03/11/2026
|
# Matriz reconciliada do SGC — 03/11/2026
|
||||||
|
|
||||||
|
**Delta de apresentação — 27/11/2026:** uniformização autorizada com os componentes existentes e benchmark de29/10. Títulos/painéis/controlos partilhados (91páginas), barras de acções e tabelas adaptadas explicitamente em31páginas; resumos de erro dos relatórios alinhados.193testes frontend, tipos, formato/lint e build privado aprovados. Revisão estática sintética de requisição/fornecedor a390px e relatório25linhas a390/1280px, com deslocamento da tabela por teclado. Sem alteração de campos, handlers, permissões, dados ou activação de assets do piloto. Não encerra aceitação visual transversal, gravação nativa ou impressão multipágina. Ver `proofs/screen-standardisation-qa.json` e o registo em `desenvolvimento.md`; provas funcionais anteriores preservadas.
|
||||||
|
|
||||||
Decisão expressa nesta continuação: projectos e imobilizado terão cadastro próprio em Compras, independente do SGF. Implementação em curso, apenas QA, sem efeitos contabilísticos nem instalação no piloto. Reutilizar as fichas físicas de equipamento existentes; não criar dependência SGF. Revisão bancária nativa posterior gravou versão 2 com comprovativo/data/fundamento sintéticos, conservou versão 1 e retirou os avisos de entrega pendente/prazo de hoje. Ambiente privado encerrado e removido.
|
Decisão expressa nesta continuação: projectos e imobilizado terão cadastro próprio em Compras, independente do SGF. Implementação em curso, apenas QA, sem efeitos contabilísticos nem instalação no piloto. Reutilizar as fichas físicas de equipamento existentes; não criar dependência SGF. Revisão bancária nativa posterior gravou versão 2 com comprovativo/data/fundamento sintéticos, conservou versão 1 e retirou os avisos de entrega pendente/prazo de hoje. Ambiente privado encerrado e removido.
|
||||||
|
|
||||||
Revisão nativa posterior em Edge: base legal observada a 390/823px sem transbordo horizontal; reutilização explícita da base sintética de 100 MZN gravou versão 2 de 7,50 MZN. Plano anterior conservou a origem escolhida #5 e total 107,50 MZN. Acompanhamento apresentou desconhecidos e pendências bancárias esperados. Servidor/raiz/base QA removidos, separadores do utilizador preservados. Prova ampliada em `proofs/import-legal-amounts-qa.json`. Esta revisão substitui apenas a indicação de revisão ainda não iniciada; impressão e aceitação visual transversal continuam por verificar.
|
Revisão nativa posterior em Edge: base legal observada a 390/823px sem transbordo horizontal; reutilização explícita da base sintética de 100 MZN gravou versão 2 de 7,50 MZN. Plano anterior conservou a origem escolhida #5 e total 107,50 MZN. Acompanhamento apresentou desconhecidos e pendências bancárias esperados. Servidor/raiz/base QA removidos, separadores do utilizador preservados. Prova ampliada em `proofs/import-legal-amounts-qa.json`. Esta revisão substitui apenas a indicação de revisão ainda não iniciada; impressão e aceitação visual transversal continuam por verificar.
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
# Continuidade do desenvolvimento do SGC
|
# Continuidade do desenvolvimento do SGC
|
||||||
|
|
||||||
|
**27/11/2026 — uniformização de ecrãs autorizada, concluída no recorte de apresentação comum/QA:** base `PageTitle`/`Panel`/controlos em91páginas e adaptação explícita de31páginas com acções/tabelas comuns; erros dos relatórios uniformizados.45ficheiros/193testes frontend, tipos, formato/lint e build privado aprovados. Pré-visualização estática sintética de requisição/fornecedor a390px e relatório25linhas a390/1280px, deslocamento por teclado observado. Sem gravações, servidor/configuração de negócio ou `public/build` alterados por esta tarefa. Não confundir esta prova com validação nativa de todos os formulários ou impressão multipágina; estes critérios continuam pendentes. Preservar o trabalho financeiro/capital paralelo. Prova `proofs/screen-standardisation-qa.json`; benchmark/regras/permissões existentes mantidos.
|
||||||
|
|
||||||
Decisão expressa nesta continuação: projectos e imobilizado terão cadastro próprio em Compras, independente do SGF. Implementação em curso, apenas QA, sem efeitos contabilísticos nem instalação no piloto. Reutilizar as fichas físicas de equipamento existentes; não criar dependência SGF. Revisão bancária nativa posterior gravou versão 2 com comprovativo/data/fundamento sintéticos, conservou versão 1 e retirou os avisos de entrega pendente/prazo de hoje. Ambiente privado encerrado e removido.
|
Decisão expressa nesta continuação: projectos e imobilizado terão cadastro próprio em Compras, independente do SGF. Implementação em curso, apenas QA, sem efeitos contabilísticos nem instalação no piloto. Reutilizar as fichas físicas de equipamento existentes; não criar dependência SGF. Revisão bancária nativa posterior gravou versão 2 com comprovativo/data/fundamento sintéticos, conservou versão 1 e retirou os avisos de entrega pendente/prazo de hoje. Ambiente privado encerrado e removido.
|
||||||
|
|
||||||
Revisão nativa posterior em Edge: base legal observada a 390/823px sem transbordo horizontal; reutilização explícita da base sintética de 100 MZN gravou versão 2 de 7,50 MZN. Plano anterior conservou a origem escolhida #5 e total 107,50 MZN. Acompanhamento apresentou desconhecidos e pendências bancárias esperados. Servidor/raiz/base QA removidos, separadores do utilizador preservados. Prova ampliada em `proofs/import-legal-amounts-qa.json`. Esta revisão substitui apenas a indicação de revisão ainda não iniciada; impressão e aceitação visual transversal continuam por verificar.
|
Revisão nativa posterior em Edge: base legal observada a 390/823px sem transbordo horizontal; reutilização explícita da base sintética de 100 MZN gravou versão 2 de 7,50 MZN. Plano anterior conservou a origem escolhida #5 e total 107,50 MZN. Acompanhamento apresentou desconhecidos e pendências bancárias esperados. Servidor/raiz/base QA removidos, separadores do utilizador preservados. Prova ampliada em `proofs/import-legal-amounts-qa.json`. Esta revisão substitui apenas a indicação de revisão ainda não iniciada; impressão e aceitação visual transversal continuam por verificar.
|
||||||
|
|||||||
@@ -11,14 +11,17 @@
|
|||||||
"Frozen origin in ordinary and partial/consolidated native order snapshots and print",
|
"Frozen origin in ordinary and partial/consolidated native order snapshots and print",
|
||||||
"Later register rename/archive does not rewrite accepted choices or issued orders"
|
"Later register rename/archive does not rewrite accepted choices or issued orders"
|
||||||
],
|
],
|
||||||
"sqlite_register_and_assignments": {"tests": 7, "assertions": 89, "passed": true},
|
"sqlite_register_and_assignments": {"tests": 9, "assertions": 101, "passed": true},
|
||||||
"postgresql_directed_native_integration": {"tests": 11, "assertions": 181, "passed": true, "database_removed": true},
|
"postgresql_directed_native_integration": {"tests": 13, "assertions": 282, "passed": true, "database_removed": true},
|
||||||
"frontend_directed": {"tests": 2, "passed": true},
|
"postgresql_submission_category_approval_regression": {"tests": 56, "assertions": 941, "passed": true, "database_removed": true},
|
||||||
|
"sqlite_native_search_regression": {"tests": 6, "assertions": 210, "passed": true},
|
||||||
|
"native_search_delta": "Department-scoped receipt search now checks all consolidated order origins; native company-wide warehouse visibility is preserved and regression-tested",
|
||||||
|
"frontend_directed": {"files": 2, "tests": 11, "passed": true, "includes_journey_help": true},
|
||||||
"checks": {"types": "passed", "phpstan": "passed", "scoped_format_lint": "passed", "scoped_pint": "passed", "diff_whitespace": "passed"},
|
"checks": {"types": "passed", "phpstan": "passed", "scoped_format_lint": "passed", "scoped_pint": "passed", "diff_whitespace": "passed"},
|
||||||
"concurrency": {
|
"concurrency": {
|
||||||
"same_operation": [200, 200], "same_version": [200, 409], "blocked_writers_observed": 2,
|
"same_operation": [200, 200], "same_version": [200, 409], "blocked_writers_observed": 2,
|
||||||
"new_versions_per_scenario": 1, "audits_per_scenario": 1, "new_files": 0, "database_removed": true,
|
"new_versions_per_scenario": 1, "audits_per_scenario": 1, "new_files": 0, "database_removed": true,
|
||||||
"receipt_protocol_regression": {"tests": 10, "assertions": 46, "passed": true}
|
"receipt_protocol_regression": {"tests": 10, "assertions": 49, "passed": true}
|
||||||
},
|
},
|
||||||
"native_edge_review": {
|
"native_edge_review": {
|
||||||
"synthetic_project_created_through_native_form": true,
|
"synthetic_project_created_through_native_form": true,
|
||||||
@@ -31,16 +34,18 @@
|
|||||||
"user_tabs_preserved": true,
|
"user_tabs_preserved": true,
|
||||||
"layout_follow_up": "Align page padding with native equipment/requisition pages; mobile overflow was not observed."
|
"layout_follow_up": "Align page padding with native equipment/requisition pages; mobile overflow was not observed."
|
||||||
},
|
},
|
||||||
|
"lineage_delta": {"issued_snapshot_used_as_authority": true, "native_receipt_confirmed_and_visible": true, "accepted_quantity": "1.000", "read_did_not_change_stock": true, "pagination_independent_for_orders_and_receipts": true, "later_reversal_and_return_projection": "uses_native_inventory_services; native correction execution not repeated in this increment"},
|
||||||
|
"recovery": {"register_versions_restored": 2, "frozen_assignment_source_version_restored": 1, "archived_head_preserved": true, "replay_without_effects": true, "previous_tables_preserved": 115, "private_originals_preserved": 11, "pre_and_post_extension_restore_equal": true, "source_and_restore_databases_removed": true},
|
||||||
"private_build": {
|
"private_build": {
|
||||||
"path": "storage/framework/testing/sgc-capital-register-qa-20261127",
|
"path": "storage/framework/testing/sgc-capital-register-qa-20261127",
|
||||||
"manifest_sha256": "baaf8095659bb678e449133dfdd07d1862bb89870f8fbcf44fd2d079474faed1",
|
"manifest_sha256": "baaf8095659bb678e449133dfdd07d1862bb89870f8fbcf44fd2d079474faed1",
|
||||||
"passed": true
|
"passed": true
|
||||||
},
|
},
|
||||||
|
"private_trace_build": {"path": "storage/framework/testing/sgc-capital-register-trace-qa-20261127", "manifest_sha256": "a17c52e7d05335c54f7fd0f34510cb38af9979388fabb30cf7cc110600870e23", "passed": true},
|
||||||
"preserved": {"pilot_manifest_sha256": "1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e", "pilot_activated": false, "migration_created": false, "new_financial_or_stock_writer": false, "sgf_dependency": false},
|
"preserved": {"pilot_manifest_sha256": "1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e", "pilot_activated": false, "migration_created": false, "new_financial_or_stock_writer": false, "sgf_dependency": false},
|
||||||
"remaining": [
|
"remaining": [
|
||||||
"Native receipt-to-asset entry lineage and current correction/return visibility",
|
"Visual review of the added origin/receipt panels and final page padding",
|
||||||
"Full assignment/account applicability across RQ-01 categories",
|
"Full assignment/account applicability across RQ-01 categories",
|
||||||
"Backup/recovery proof for new register and assignments",
|
|
||||||
"Final visual/mobile/print review after remaining implementation",
|
"Final visual/mobile/print review after remaining implementation",
|
||||||
"Other existing matrix gaps and separately scoped operational preparation"
|
"Other existing matrix gaps and separately scoped operational preparation"
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
{
|
||||||
|
"date": "2026-11-27",
|
||||||
|
"status": "approved_for_development_and_isolated_qa_only",
|
||||||
|
"owner_response": "Autorizar a extensão em QA",
|
||||||
|
"proposal": "requisition-expiry-contract-proposal.json",
|
||||||
|
"proposal_sha256": "725e2999601cf5fe77c1d9bc959b4511b5ab69fac6d0ecadf99f1c47106c51c5",
|
||||||
|
"scope": "Optional common approval/reservation cycle contract and Compras host adaptation exactly as proposed, including expiry returning to draft and a new independently reserved and approved submission",
|
||||||
|
"excluded": ["Pilot installation/migration/activation", "SGF operational installation or activation", "Real data, permissions or business operations", "A second financial writer or shared database"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
{
|
||||||
|
"date": "2026-11-27",
|
||||||
|
"status": "prepared_for_specific_owner_validation_not_implemented",
|
||||||
|
"approved_product_decision": "Devolver o pedido ao requisitante para nova submissão",
|
||||||
|
"concrete_dependency": {
|
||||||
|
"approval_step_identity": "approval_steps is unique by requisition_id and position; another submission needs a separate cycle while retaining all earlier decisions",
|
||||||
|
"financial_operation_identity": "budget_entries is unique by requisition_id and kind; BudgetControl.record replays an earlier reserve instead of reserving a new cycle after release",
|
||||||
|
"common_lifecycle": "InternalRequisitions currently supports save, submit and decide, without an expiry/return transition",
|
||||||
|
"risk_without_extension": "Deleting earlier steps would lose history; replaying an earlier reserve would leave the new submission without its own current reservation"
|
||||||
|
},
|
||||||
|
"proposed_scope": [
|
||||||
|
"Optional versioned approval-cycle and budget-cycle contract in the common kernels, with the Compras host adapter",
|
||||||
|
"Keep the real requisition identity; never use a fake requisition or a compensating arbitrary financial amount",
|
||||||
|
"Preserve original cycle-one records and decisions; add explicit subsequent cycles and independent operation identities",
|
||||||
|
"Snapshot the company-configured reminder, escalation and expiry policy at submission; no invented default deadlines or recipients",
|
||||||
|
"On eligible pending expiry, atomically record the reason, close the current cycle, release only its remaining reservations through the existing common financial authority and return the same requisition to its requester as a draft",
|
||||||
|
"A new submission creates fresh approval steps and a fresh reservation after the native budget and investment checks; previous approvals never carry forward automatically",
|
||||||
|
"Preserve amount/cost-centre/category changes as a new reviewed draft; do not rewrite previous policy snapshots or financial movements",
|
||||||
|
"Keep goods reservations, distributed allocations and import-estimate reservations within their single native financial authority",
|
||||||
|
"A decision/expiry race has one winner; duplicate expiry or submission has one effect and one audit",
|
||||||
|
"Older runtimes must refuse new-cycle records before a financial effect; package and database recovery must be verified together"
|
||||||
|
],
|
||||||
|
"implementation_boundary": {
|
||||||
|
"allowed_if_approved": "Common development source and Compras adaptation, optional QA schema, synthetic tests, private portable artifact preparation",
|
||||||
|
"operational_installation": false,
|
||||||
|
"pilot_migration_or_activation": false,
|
||||||
|
"sgf_operational_changes": false,
|
||||||
|
"real_data_permissions_or_business_operations": false,
|
||||||
|
"new_financial_writer_or_shared_database": false
|
||||||
|
},
|
||||||
|
"acceptance_examples_synthetic_minor_units": [
|
||||||
|
{"cycle": 1, "reserve": 10000, "expiry_release": 10000, "remaining_reserve": 0, "old_steps_preserved": true},
|
||||||
|
{"cycle": 2, "revised_amount": 12000, "new_reserve": 12000, "old_approvals_reused": false},
|
||||||
|
{"cycle": 2, "rejection_release": 12000, "remaining_reserve": 0}
|
||||||
|
],
|
||||||
|
"required_verification": [
|
||||||
|
"Focused common-kernel and native-host success/error/version/isolation tests",
|
||||||
|
"Cycle-one and installed-runtime regression, ordinary/distributed/import reservation coverage",
|
||||||
|
"Genuine concurrent decision versus expiry and duplicate operation tests",
|
||||||
|
"Pre/post extension backup and recovery with equal source data and preserved old decisions",
|
||||||
|
"Native requester return/edit/resubmit flow and administrator policy review"
|
||||||
|
],
|
||||||
|
"authorization_basis": "Existing repository policy requires explicit authorization for concrete contract/architecture changes; earlier multi-order and landed-cost contract authorizations do not specify approval/reservation cycles"
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
{
|
||||||
|
"date": "2026-11-27",
|
||||||
|
"scope": "shared presentation and isolated QA, not whole-product or production acceptance",
|
||||||
|
"benchmark": "docs/referencias/benchmark-menus-20261029.txt",
|
||||||
|
"shared_page_consumers": 91,
|
||||||
|
"explicitly_adapted_pages": 31,
|
||||||
|
"frontend": {
|
||||||
|
"files": 45,
|
||||||
|
"tests": 193,
|
||||||
|
"passed": true
|
||||||
|
},
|
||||||
|
"checks": {
|
||||||
|
"typescript": "passed",
|
||||||
|
"scoped_format_and_lint": "passed without warnings",
|
||||||
|
"private_build": "passed",
|
||||||
|
"diff_whitespace": "passed"
|
||||||
|
},
|
||||||
|
"visual": {
|
||||||
|
"type": "static render of real React components with synthetic props; no backend business operations",
|
||||||
|
"requisition_and_supplier_mobile_width": 390,
|
||||||
|
"report_rows": 25,
|
||||||
|
"report_widths": [
|
||||||
|
390,
|
||||||
|
1280
|
||||||
|
],
|
||||||
|
"mobile_document_scroll_width": 375,
|
||||||
|
"mobile_viewport_width": 390,
|
||||||
|
"table_client_width": 301,
|
||||||
|
"table_scroll_width": 960,
|
||||||
|
"table_keyboard_scroll_left": 40,
|
||||||
|
"temporary_tab_closed": true,
|
||||||
|
"viewport_reset": true,
|
||||||
|
"preview_server_stopped": true
|
||||||
|
},
|
||||||
|
"private_build_directory": "storage/framework/testing/sgc-screen-standardisation-20261127/assets",
|
||||||
|
"private_build_manifest_sha256": "b81b6539a9ba8dfc213d2c55e55761ab4625f67e96e62be029261d380ea10b2e",
|
||||||
|
"remaining": [
|
||||||
|
"Native end-to-end interaction and visual review across remaining pages",
|
||||||
|
"Multi-page print verification"
|
||||||
|
],
|
||||||
|
"preserved": {
|
||||||
|
"business_handlers_and_fields": true,
|
||||||
|
"permissions": true,
|
||||||
|
"backend_unchanged_by_this_task": true,
|
||||||
|
"existing_parallel_work": true,
|
||||||
|
"production_publication": false,
|
||||||
|
"pilot_assets_activated": false,
|
||||||
|
"sgf_changed": false
|
||||||
|
},
|
||||||
|
"files": {
|
||||||
|
"resources/js/components/procurement.tsx": "780f7dbee345c3827f4e1eb54c57be9af9180865e474c78da2821360664e6015",
|
||||||
|
"resources/css/app.css": "c459b354cd3b8ae6e263e92588c6c315dfd785a1520dbeaef47319cff9db9369",
|
||||||
|
"resources/js/pages/audit/metadata.tsx": "e9d908733bb1c8166d7cb9ff1aa2454e6e0f0baf25f784311451485d74ae8387",
|
||||||
|
"resources/js/pages/company/geography-review.tsx": "d7c19ad0413a7a663cce1830a06459452aa1918135850822588dc3f6487cfe13",
|
||||||
|
"resources/js/pages/company/index.tsx": "2fda2ed14fe49f28fef898d64a1fd1845ca042af6c32e4586c88359ff9845e62",
|
||||||
|
"resources/js/pages/company/parameters.tsx": "6063442ce39d336205f0490e51c7176d2773bbff40c4894263711a38733f5bcb",
|
||||||
|
"resources/js/pages/conflicts/index.tsx": "b3e6265eb516c282402baca5dae7fabe48f803776dedb142492335a613538a33",
|
||||||
|
"resources/js/pages/people/index.tsx": "cc8ec8010f6fc4f292e1b5a541fe3857e2ebd3f7cc7c35e761137e0b6195c081",
|
||||||
|
"resources/js/pages/people/reports.tsx": "9c972568e586d7af190cd062bd3671db95ae01160ad330e286ae3183a97b325f",
|
||||||
|
"resources/js/pages/preview/admission.tsx": "309069e8a4a37e04a09168e6b03a01b728004d25aefa56778fa1f9dd8c71f3f3",
|
||||||
|
"resources/js/pages/preview/index.tsx": "38d9541c5d6747cf0f7fe12d8233aa3b0c72f418c49bc9a2dba8c0bb42e62369",
|
||||||
|
"resources/js/pages/preview/inventory-demo.tsx": "6a9b8ff2755472c84d3e8a5efa12f3673f02e4ee29fa0aaeba5e0e5ab7029e09",
|
||||||
|
"resources/js/pages/preview/recommendation.tsx": "77ba13e2d12db8032f6e90815d8dff6bff8d929660e63e82edd3e27c62da897e",
|
||||||
|
"resources/js/pages/purchases/award.tsx": "fa438ae156beff044aeaadfc25d29fbf15aebb601e51e6a61f26f6eaf9eeb25b",
|
||||||
|
"resources/js/pages/purchases/distribution-amendment.tsx": "f19ebbd1021edd1abf38a8f6868cd6a69267e2c577f60c45db8b2c17c2950262",
|
||||||
|
"resources/js/pages/purchases/index.tsx": "9e01a52fbfb679b893263a793993d55c7441eecef50f0f4f155707e0f1354ed7",
|
||||||
|
"resources/js/pages/purchases/recommendation.tsx": "197dab87dd01c4c1afda4c3d9b308a8d0825c3e8f14f5074284ae1cae34035a6",
|
||||||
|
"resources/js/pages/purchases/review-report.tsx": "95d1374fb97f4dd9e4661b3987dadba924333959f7dcb339f1f9933020d6e5d1",
|
||||||
|
"resources/js/pages/purchases/show.tsx": "5f7c50858be4fde54ddb7e2adca9c2454e023a59eafd608a50d6de1381b6089e",
|
||||||
|
"resources/js/pages/reports/procurement.tsx": "fea24e8fbce82102a80657826471fed9269236e9b547ce224508798e04903650",
|
||||||
|
"resources/js/pages/reports/supplier-improvements.tsx": "9ccb17a91c1fdcd88a221f1f90e1ae393a480202e3d45bb11ae63114781184e6",
|
||||||
|
"resources/js/pages/requisitions/distributions.tsx": "67a9e5425354fb0fb2ad67eb7dacde4b1d9a8f1e3288c3dfaec7ed6f4ed3b632",
|
||||||
|
"resources/js/pages/requisitions/form.tsx": "9df5bb72a71e47adfe01303c9da255eacca7c4fb533c331af456b6cac22f3abb",
|
||||||
|
"resources/js/pages/requisitions/show.tsx": "fa472746b5e83eb0b55e93a249bf46d1cbd1a4b692deb58dc0274b5c37a84593",
|
||||||
|
"resources/js/pages/stock/availability.tsx": "c6fd899bfc912ce7ccd96bfd3f8de8984c18d5c99dfaae630c580e9421d7c98a",
|
||||||
|
"resources/js/pages/stock/index.tsx": "03270a0fdc48cc7bac5f0567b3917dff99d3dd79ff4863b14b30505f5f689ff6",
|
||||||
|
"resources/js/pages/stock/request.tsx": "5867aaf30028b9da2d855273081cd20b4c26fc79b6a410cdc825d51ffc06e90a",
|
||||||
|
"resources/js/pages/stock/requests.tsx": "b6e7b1188e0a3f8b302440d263e54872e7686ae8295d5ad8ba7d2668702e19fd",
|
||||||
|
"resources/js/pages/suppliers/edit.tsx": "e298e843d44532a716e11154b4788cedd1b8c2d6e5e436878d8f367d0a75a9c7",
|
||||||
|
"resources/js/pages/suppliers/evaluation.tsx": "cdf125842beb0eb6d868c3311065f453d1872f72272a22e517fae4e8a4257ff6",
|
||||||
|
"resources/js/pages/suppliers/evaluations.tsx": "28597501382081716122c766b0ecdca75e2f1a87c44b787e310c48cf8f23d2fe",
|
||||||
|
"resources/js/pages/supply/agreement-followup.tsx": "8130ba7c20bc033a243de8e4315bd5caf6eed597713f5d4ef9938657d10eca12",
|
||||||
|
"resources/js/pages/supply/import-costs.tsx": "c0a34552d464235578f94defbdcc917ab8459d70eed551785c48d3bf0edac759",
|
||||||
|
"tests/frontend/screen-presentation.test.tsx": "36b9e1159d373ec229c1d7dd9243749da47c9366d603f90b8c11244fc0bff58c"
|
||||||
|
}
|
||||||
|
}
|
||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -4,5 +4,6 @@ require_once __DIR__.'/src/ReplenishmentProjection.php';
|
|||||||
require_once __DIR__.'/src/QuotationPricing.php';
|
require_once __DIR__.'/src/QuotationPricing.php';
|
||||||
require_once __DIR__.'/src/ProposalScoring.php';
|
require_once __DIR__.'/src/ProposalScoring.php';
|
||||||
require_once __DIR__.'/src/RequisitionPort.php';
|
require_once __DIR__.'/src/RequisitionPort.php';
|
||||||
|
require_once __DIR__.'/src/ExpiryRequisitionPort.php';
|
||||||
require_once __DIR__.'/src/RequisitionFailure.php';
|
require_once __DIR__.'/src/RequisitionFailure.php';
|
||||||
require_once __DIR__.'/src/InternalRequisitions.php';
|
require_once __DIR__.'/src/InternalRequisitions.php';
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Tempo\Purchasing\Internal;
|
||||||
|
|
||||||
|
/** Optional cycle extension. Older host ports retain their original interface. */
|
||||||
|
interface ExpiryRequisitionPort extends RequisitionPort
|
||||||
|
{
|
||||||
|
/** @param array<string,mixed> $record
|
||||||
|
* @param array<string,mixed> $policy
|
||||||
|
*/
|
||||||
|
public function prepareCycle(array $record, array $policy, ?string $operation): void;
|
||||||
|
|
||||||
|
/** @param array<string,mixed> $record */
|
||||||
|
public function assertDecisionTimely(array $record): void;
|
||||||
|
|
||||||
|
/** Verify the frozen policy, current pending step and elapsed deadline before financial release.
|
||||||
|
* @param array<string,mixed> $record
|
||||||
|
* @param array<string,mixed> $input
|
||||||
|
* @return array<string,mixed>
|
||||||
|
*/
|
||||||
|
public function expiration(array $record, array $input): array;
|
||||||
|
|
||||||
|
/** Close the released cycle and return the same origin to its requester without deleting prior steps.
|
||||||
|
* @param array<string,mixed> $record
|
||||||
|
* @param array<string,mixed> $proof
|
||||||
|
* @return array<string,mixed>
|
||||||
|
*/
|
||||||
|
public function expired(array $record, array $proof): array;
|
||||||
|
}
|
||||||
@@ -15,6 +15,11 @@ final class InternalRequisitions
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static function supportsExpiryCycles(): bool
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param array<string,mixed> $record
|
* @param array<string,mixed> $record
|
||||||
* @return array<string,mixed>|null
|
* @return array<string,mixed>|null
|
||||||
@@ -130,8 +135,21 @@ final class InternalRequisitions
|
|||||||
throw new RequisitionFailure('Submissão não autorizada.', 403);
|
throw new RequisitionFailure('Submissão não autorizada.', 403);
|
||||||
}
|
}
|
||||||
$policy = $this->port->policy($record);
|
$policy = $this->port->policy($record);
|
||||||
|
if ($this->port instanceof ExpiryRequisitionPort) {
|
||||||
|
$this->port->prepareCycle($record, $policy, $key);
|
||||||
|
}
|
||||||
$this->port->reserve($record);
|
$this->port->reserve($record);
|
||||||
$result = $this->port->submitted($record, $policy, self::roles($record, $policy));
|
$result = $this->port->submitted($record, $policy, self::roles($record, $policy));
|
||||||
|
} elseif ($action === 'expire') {
|
||||||
|
if (! $this->port instanceof ExpiryRequisitionPort) {
|
||||||
|
throw new RequisitionFailure('O adaptador não suporta devolução por expiração.', 503);
|
||||||
|
}
|
||||||
|
if ($record === null || $record['status'] !== 'pending' || $key === null || $version === null) {
|
||||||
|
throw new RequisitionFailure('A expiração exige pedido pendente, versão e operação explícitas.', 409);
|
||||||
|
}
|
||||||
|
$proof = $this->port->expiration($record, [...$input, 'operation_key' => $key]);
|
||||||
|
$this->port->release($record);
|
||||||
|
$result = $this->port->expired($record, $proof);
|
||||||
} elseif ($action === 'decide') {
|
} elseif ($action === 'decide') {
|
||||||
$actor = $this->port->actorId();
|
$actor = $this->port->actorId();
|
||||||
if ($record === null || $record['status'] !== 'pending' || $record['requester_id'] === $actor) {
|
if ($record === null || $record['status'] !== 'pending' || $record['requester_id'] === $actor) {
|
||||||
@@ -141,6 +159,9 @@ final class InternalRequisitions
|
|||||||
if ($step === null) {
|
if ($step === null) {
|
||||||
throw new RequisitionFailure('A decisão exige outra identidade para cada etapa.', 403);
|
throw new RequisitionFailure('A decisão exige outra identidade para cada etapa.', 403);
|
||||||
}
|
}
|
||||||
|
if ($this->port instanceof ExpiryRequisitionPort) {
|
||||||
|
$this->port->assertDecisionTimely($record);
|
||||||
|
}
|
||||||
if (! in_array($input['decision'] ?? '', ['approved', 'rejected'], true)) {
|
if (! in_array($input['decision'] ?? '', ['approved', 'rejected'], true)) {
|
||||||
throw new RequisitionFailure('Decisão inválida.', 422);
|
throw new RequisitionFailure('Decisão inválida.', 422);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -141,3 +141,68 @@
|
|||||||
@apply bg-background text-foreground;
|
@apply bg-background text-foreground;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Shared procurement presentation. Rules and document data remain in their existing owners. */
|
||||||
|
@layer components {
|
||||||
|
.sgc-panel :where(input, select, textarea) {
|
||||||
|
min-inline-size: 0;
|
||||||
|
max-inline-size: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sgc-panel > div {
|
||||||
|
min-inline-size: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sgc-page-actions > .flex {
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sgc-action-bar > :is(button, a) {
|
||||||
|
min-block-size: 2.5rem;
|
||||||
|
white-space: normal;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sgc-table-viewport table {
|
||||||
|
inline-size: 100%;
|
||||||
|
border-collapse: collapse;
|
||||||
|
text-align: start;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sgc-table-viewport th {
|
||||||
|
vertical-align: bottom;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sgc-table-viewport :is(th, td) {
|
||||||
|
padding: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sgc-table-viewport tbody tr:not(:last-child) {
|
||||||
|
border-block-end: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media print {
|
||||||
|
.sgc-table-viewport {
|
||||||
|
overflow: visible;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sgc-table-viewport table {
|
||||||
|
min-inline-size: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sgc-table-viewport thead {
|
||||||
|
display: table-header-group;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sgc-table-viewport tr {
|
||||||
|
break-inside: avoid;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sgc-table-viewport :is(th, td) {
|
||||||
|
white-space: normal;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { Link } from '@inertiajs/react';
|
import { Link } from '@inertiajs/react';
|
||||||
import { ArrowUpRight, ClipboardList } from 'lucide-react';
|
import { ArrowUpRight, ClipboardList } from 'lucide-react';
|
||||||
import type { ReactNode } from 'react';
|
import { useId, type ReactNode } from 'react';
|
||||||
import { Badge } from '@/components/ui/badge';
|
import { Badge } from '@/components/ui/badge';
|
||||||
import { openJourneyHelp } from '@/components/journey-help';
|
import { openJourneyHelp } from '@/components/journey-help';
|
||||||
import { recoveryHints } from '@/lib/journey-help';
|
import { recoveryHints } from '@/lib/journey-help';
|
||||||
@@ -8,7 +8,74 @@ import { date, money, statusLabels } from '@/types/procurement';
|
|||||||
import type { Requisition } from '@/types/procurement';
|
import type { Requisition } from '@/types/procurement';
|
||||||
|
|
||||||
export const controlClass =
|
export const controlClass =
|
||||||
'h-10 w-full rounded-lg border border-input bg-background px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring';
|
'h-10 w-full min-w-0 rounded-lg border border-input bg-background px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20';
|
||||||
|
|
||||||
|
/** Shared layout only: callers retain their actions, permissions and submit behaviour. */
|
||||||
|
export function ActionBar({
|
||||||
|
children,
|
||||||
|
align = 'start',
|
||||||
|
label = 'Acções disponíveis',
|
||||||
|
className = '',
|
||||||
|
}: {
|
||||||
|
children: ReactNode;
|
||||||
|
align?: 'start' | 'end';
|
||||||
|
label?: string;
|
||||||
|
className?: string;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
role="group"
|
||||||
|
aria-label={label}
|
||||||
|
className={`sgc-action-bar flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-center ${align === 'end' ? 'sm:justify-end' : ''} print:hidden ${className}`}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Preserve table semantics and make wide results reachable with a keyboard. */
|
||||||
|
export function TableViewport({
|
||||||
|
children,
|
||||||
|
label = 'Tabela de resultados',
|
||||||
|
}: {
|
||||||
|
children: ReactNode;
|
||||||
|
label?: string;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
role="region"
|
||||||
|
aria-label={label}
|
||||||
|
tabIndex={0}
|
||||||
|
className="sgc-table-viewport max-w-full min-w-0 overflow-x-auto rounded-lg focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Print all already authorised details without changing their on-screen expansion state. */
|
||||||
|
export function PrintableDetails({
|
||||||
|
summary,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
summary: ReactNode;
|
||||||
|
children: ReactNode;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<details className="print:hidden">
|
||||||
|
<summary className="cursor-pointer underline">
|
||||||
|
{summary}
|
||||||
|
</summary>
|
||||||
|
{children}
|
||||||
|
</details>
|
||||||
|
<div className="hidden print:block">
|
||||||
|
<p className="font-medium">{summary}</p>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
export function PageTitle({
|
export function PageTitle({
|
||||||
eyebrow,
|
eyebrow,
|
||||||
title,
|
title,
|
||||||
@@ -21,20 +88,24 @@ export function PageTitle({
|
|||||||
action?: ReactNode;
|
action?: ReactNode;
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-wrap items-end justify-between gap-4">
|
<header className="sgc-page-title flex min-w-0 flex-col gap-4 sm:flex-row sm:flex-wrap sm:items-end sm:justify-between">
|
||||||
<div>
|
<div className="min-w-0">
|
||||||
<p className="mb-2 text-xs font-semibold tracking-widest text-teal-700 uppercase dark:text-teal-400">
|
<p className="mb-2 text-xs font-semibold tracking-widest text-teal-700 uppercase dark:text-teal-400">
|
||||||
{eyebrow}
|
{eyebrow}
|
||||||
</p>
|
</p>
|
||||||
<h1 className="text-3xl font-semibold tracking-tight">
|
<h1 className="text-2xl font-semibold tracking-tight [overflow-wrap:anywhere] sm:text-3xl">
|
||||||
{title}
|
{title}
|
||||||
</h1>
|
</h1>
|
||||||
<p className="mt-2 max-w-2xl text-sm text-muted-foreground">
|
<p className="mt-2 max-w-2xl text-sm text-muted-foreground">
|
||||||
{description}
|
{description}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
{action}
|
{action && (
|
||||||
</div>
|
<div className="sgc-page-actions min-w-0 print:hidden">
|
||||||
|
{action}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</header>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
export function Panel({
|
export function Panel({
|
||||||
@@ -48,12 +119,19 @@ export function Panel({
|
|||||||
description?: string;
|
description?: string;
|
||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
}) {
|
}) {
|
||||||
|
const headingId = useId();
|
||||||
return (
|
return (
|
||||||
<section
|
<section
|
||||||
id={id}
|
id={id}
|
||||||
className="scroll-mt-24 rounded-xl border bg-card p-5 shadow-xs"
|
aria-labelledby={headingId}
|
||||||
|
className="sgc-panel min-w-0 scroll-mt-24 rounded-xl border bg-card p-4 shadow-xs sm:p-5 print:rounded-none print:shadow-none"
|
||||||
>
|
>
|
||||||
<h2 className="font-semibold">{title}</h2>
|
<h2
|
||||||
|
id={headingId}
|
||||||
|
className="font-semibold [overflow-wrap:anywhere]"
|
||||||
|
>
|
||||||
|
{title}
|
||||||
|
</h2>
|
||||||
{description && (
|
{description && (
|
||||||
<p className="mt-1 text-sm text-muted-foreground">
|
<p className="mt-1 text-sm text-muted-foreground">
|
||||||
{description}
|
{description}
|
||||||
|
|||||||
@@ -37,6 +37,23 @@ function topic(
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const journeyHelp: JourneyHelp[] = [
|
export const journeyHelp: JourneyHelp[] = [
|
||||||
|
topic(
|
||||||
|
'capital-register',
|
||||||
|
'Ligar compras a projectos e imobilizado',
|
||||||
|
['equipment/capital-register', 'requisitions/capital-assignments'],
|
||||||
|
'Usar o cadastro próprio de Compras e conservar a origem documental da escolha por artigo.',
|
||||||
|
[
|
||||||
|
'Registe o código, designação, departamento e referência documental. Reutilize a ficha física existente quando o equipamento já estiver identificado.',
|
||||||
|
'No rascunho da requisição, seleccione o artigo e a referência activa do respectivo departamento; justifique e guarde a ligação.',
|
||||||
|
'Consulte versões e origens no cadastro para abrir as ordens efectivamente emitidas e as respectivas recepções.',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'Revisões e arquivo não reescrevem escolhas anteriores nem documentos emitidos; uma alteração do artigo exige rever a ligação.',
|
||||||
|
'A quantidade aceite no original é distinta de devoluções e estornos posteriores. O rastreio não regista capitalização ou depreciação.',
|
||||||
|
],
|
||||||
|
'Se a versão mudou, conserve a preparação, consulte a ligação actual e seleccione a referência activa antes de voltar a guardar.',
|
||||||
|
'Regresse à requisição para os controlos e aprovações existentes; a ligação documental não substitui a distribuição orçamental.',
|
||||||
|
),
|
||||||
topic(
|
topic(
|
||||||
'import-readiness',
|
'import-readiness',
|
||||||
'Acompanhar pendências da importação',
|
'Acompanhar pendências da importação',
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { Head, Link, useForm } from '@inertiajs/react';
|
import { Head, Link, useForm } from '@inertiajs/react';
|
||||||
import {
|
import {
|
||||||
|
TableViewport,
|
||||||
PageTitle,
|
PageTitle,
|
||||||
Panel,
|
Panel,
|
||||||
FormErrors,
|
FormErrors,
|
||||||
@@ -146,7 +147,7 @@ export default function AuditMetadata({ filters, events }: Props) {
|
|||||||
</a>
|
</a>
|
||||||
</Panel>
|
</Panel>
|
||||||
<Panel title={`${events.total} eventos encontrados`}>
|
<Panel title={`${events.total} eventos encontrados`}>
|
||||||
<div className="overflow-x-auto">
|
<TableViewport>
|
||||||
<table className="w-full text-left text-sm">
|
<table className="w-full text-left text-sm">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
@@ -173,7 +174,7 @@ export default function AuditMetadata({ filters, events }: Props) {
|
|||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</TableViewport>
|
||||||
{events.data.length === 0 && (
|
{events.data.length === 0 && (
|
||||||
<p className="mt-4">Sem eventos para estes filtros.</p>
|
<p className="mt-4">Sem eventos para estes filtros.</p>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -1,6 +1,11 @@
|
|||||||
import { Head, Link, router } from '@inertiajs/react';
|
import { Head, Link, router } from '@inertiajs/react';
|
||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { PageTitle, Panel, controlClass } from '@/components/procurement';
|
import {
|
||||||
|
TableViewport,
|
||||||
|
PageTitle,
|
||||||
|
Panel,
|
||||||
|
controlClass,
|
||||||
|
} from '@/components/procurement';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
|
|
||||||
@@ -126,7 +131,7 @@ export default function GeographyReview({
|
|||||||
{total.toLocaleString('pt-PT')} resultados · Página{' '}
|
{total.toLocaleString('pt-PT')} resultados · Página{' '}
|
||||||
{filters.page} de {Math.max(1, Math.ceil(total / 50))}
|
{filters.page} de {Math.max(1, Math.ceil(total / 50))}
|
||||||
</p>
|
</p>
|
||||||
<div className="overflow-x-auto">
|
<TableViewport>
|
||||||
<table className="w-full text-left text-sm">
|
<table className="w-full text-left text-sm">
|
||||||
<thead className="border-b">
|
<thead className="border-b">
|
||||||
<tr>
|
<tr>
|
||||||
@@ -169,7 +174,7 @@ export default function GeographyReview({
|
|||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</TableViewport>
|
||||||
{records.length === 0 && (
|
{records.length === 0 && (
|
||||||
<p className="py-5 text-sm">
|
<p className="py-5 text-sm">
|
||||||
Não existem pendências para estes filtros.
|
Não existem pendências para estes filtros.
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { Head, useForm } from '@inertiajs/react';
|
import { Head, useForm } from '@inertiajs/react';
|
||||||
import {
|
import {
|
||||||
|
TableViewport,
|
||||||
FormErrors,
|
FormErrors,
|
||||||
PageTitle,
|
PageTitle,
|
||||||
Panel,
|
Panel,
|
||||||
@@ -177,7 +178,7 @@ export default function CompanyPage({
|
|||||||
title="Equipa"
|
title="Equipa"
|
||||||
description="O perfil define as operações disponíveis. Um administrador não substitui os aprovadores."
|
description="O perfil define as operações disponíveis. Um administrador não substitui os aprovadores."
|
||||||
>
|
>
|
||||||
<div className="overflow-x-auto">
|
<TableViewport>
|
||||||
<table className="w-full text-left text-sm">
|
<table className="w-full text-left text-sm">
|
||||||
<thead className="border-b text-muted-foreground">
|
<thead className="border-b text-muted-foreground">
|
||||||
<tr>
|
<tr>
|
||||||
@@ -211,7 +212,7 @@ export default function CompanyPage({
|
|||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</TableViewport>
|
||||||
<form
|
<form
|
||||||
className="mt-6 space-y-4 border-t pt-5"
|
className="mt-6 space-y-4 border-t pt-5"
|
||||||
autoComplete="off"
|
autoComplete="off"
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import type { IntelligencePolicy } from '@/components/intelligence-settings';
|
|||||||
import { comparisonCriteria } from '@/components/comparison-policy-summary';
|
import { comparisonCriteria } from '@/components/comparison-policy-summary';
|
||||||
import type { ComparisonPolicy } from '@/components/comparison-policy-summary';
|
import type { ComparisonPolicy } from '@/components/comparison-policy-summary';
|
||||||
import {
|
import {
|
||||||
|
ActionBar,
|
||||||
PageTitle,
|
PageTitle,
|
||||||
Panel,
|
Panel,
|
||||||
FormErrors,
|
FormErrors,
|
||||||
@@ -173,6 +174,7 @@ function Assignment({
|
|||||||
export default function Parameters({
|
export default function Parameters({
|
||||||
approvalLevels,
|
approvalLevels,
|
||||||
approvalLevelsReady = false,
|
approvalLevelsReady = false,
|
||||||
|
expiryReady = false,
|
||||||
requisitionCategoryOptions = {},
|
requisitionCategoryOptions = {},
|
||||||
companyDetails,
|
companyDetails,
|
||||||
companyDetailsReady,
|
companyDetailsReady,
|
||||||
@@ -202,6 +204,7 @@ export default function Parameters({
|
|||||||
}: {
|
}: {
|
||||||
approvalLevels?: RequisitionApprovalPlan | null;
|
approvalLevels?: RequisitionApprovalPlan | null;
|
||||||
approvalLevelsReady?: boolean;
|
approvalLevelsReady?: boolean;
|
||||||
|
expiryReady?: boolean;
|
||||||
requisitionCategoryOptions?: Record<string, string>;
|
requisitionCategoryOptions?: Record<string, string>;
|
||||||
companyDetails: CompanyDetails | null;
|
companyDetails: CompanyDetails | null;
|
||||||
companyDetailsReady: boolean;
|
companyDetailsReady: boolean;
|
||||||
@@ -308,6 +311,15 @@ export default function Parameters({
|
|||||||
{notice}
|
{notice}
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
|
{expiryReady && (
|
||||||
|
<Link
|
||||||
|
className="block underline"
|
||||||
|
href="/administracao/prazos-aprovacao"
|
||||||
|
>
|
||||||
|
Configurar prazos, escalamento e expiração das
|
||||||
|
aprovações
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
{activationPreview && (
|
{activationPreview && (
|
||||||
<OrganizationActivationPreview
|
<OrganizationActivationPreview
|
||||||
preview={activationPreview}
|
preview={activationPreview}
|
||||||
@@ -908,7 +920,7 @@ export default function Parameters({
|
|||||||
</ul>
|
</ul>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex gap-3">
|
<ActionBar>
|
||||||
<Button disabled={profile.processing}>
|
<Button disabled={profile.processing}>
|
||||||
{profile.data.id
|
{profile.data.id
|
||||||
? 'Actualizar perfil'
|
? 'Actualizar perfil'
|
||||||
@@ -929,7 +941,7 @@ export default function Parameters({
|
|||||||
>
|
>
|
||||||
Novo perfil
|
Novo perfil
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</ActionBar>
|
||||||
</form>
|
</form>
|
||||||
</Panel>
|
</Panel>
|
||||||
<Panel title="Utilizadores e atribuições">
|
<Panel title="Utilizadores e atribuições">
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { Head, Link, useForm, usePage } from '@inertiajs/react';
|
import { Head, Link, useForm, usePage } from '@inertiajs/react';
|
||||||
import {
|
import {
|
||||||
|
TableViewport,
|
||||||
FormErrors,
|
FormErrors,
|
||||||
PageTitle,
|
PageTitle,
|
||||||
Panel,
|
Panel,
|
||||||
@@ -220,7 +221,7 @@ export default function Conflicts({
|
|||||||
title="Declarações e correcções"
|
title="Declarações e correcções"
|
||||||
description="O histórico é preservado. Só o autor pode corrigir o fundamento e a data de conhecimento, sem mudar o âmbito ou retirar o conflito."
|
description="O histórico é preservado. Só o autor pode corrigir o fundamento e a data de conhecimento, sem mudar o âmbito ou retirar o conflito."
|
||||||
>
|
>
|
||||||
<div className="overflow-x-auto">
|
<TableViewport>
|
||||||
<table className="w-full text-left text-sm">
|
<table className="w-full text-left text-sm">
|
||||||
<thead className="border-b text-muted-foreground">
|
<thead className="border-b text-muted-foreground">
|
||||||
<tr>
|
<tr>
|
||||||
@@ -278,7 +279,7 @@ export default function Conflicts({
|
|||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</TableViewport>
|
||||||
{declarations.data.length === 0 && (
|
{declarations.data.length === 0 && (
|
||||||
<p className="py-6 text-sm text-muted-foreground">
|
<p className="py-6 text-sm text-muted-foreground">
|
||||||
Ainda não existem declarações disponíveis para o seu
|
Ainda não existem declarações disponíveis para o seu
|
||||||
|
|||||||
@@ -26,8 +26,34 @@ type Record = {
|
|||||||
};
|
};
|
||||||
type Props = {
|
type Props = {
|
||||||
trace?: {
|
trace?: {
|
||||||
orders: { data: { id: number; description: string; quantity: string; unit: string; order_id: number; order_number: string }[]; prev_page_url: string | null; next_page_url: string | null };
|
orders: {
|
||||||
receipts: { data: { id: number; description: string | null; unit: string | null; receipt_id: number; order_id: number | null; received_on: string | null; quality_status: string; accepted_quantity: string; reversed: boolean; returned_quantity: string }[]; prev_page_url: string | null; next_page_url: string | null };
|
data: {
|
||||||
|
id: number;
|
||||||
|
description: string;
|
||||||
|
quantity: string;
|
||||||
|
unit: string;
|
||||||
|
order_id: number;
|
||||||
|
order_number: string;
|
||||||
|
}[];
|
||||||
|
prev_page_url: string | null;
|
||||||
|
next_page_url: string | null;
|
||||||
|
};
|
||||||
|
receipts: {
|
||||||
|
data: {
|
||||||
|
id: number;
|
||||||
|
description: string | null;
|
||||||
|
unit: string | null;
|
||||||
|
receipt_id: number;
|
||||||
|
order_id: number | null;
|
||||||
|
received_on: string | null;
|
||||||
|
quality_status: string;
|
||||||
|
accepted_quantity: string;
|
||||||
|
reversed: boolean;
|
||||||
|
returned_quantity: string;
|
||||||
|
}[];
|
||||||
|
prev_page_url: string | null;
|
||||||
|
next_page_url: string | null;
|
||||||
|
};
|
||||||
} | null;
|
} | null;
|
||||||
history: {
|
history: {
|
||||||
data: Record[];
|
data: Record[];
|
||||||
@@ -133,6 +159,17 @@ export default function CapitalRegister(props: Props) {
|
|||||||
· versão {record.version}
|
· versão {record.version}
|
||||||
</p>
|
</p>
|
||||||
<p>{record.data.reference}</p>
|
<p>{record.data.reference}</p>
|
||||||
|
{record.data.equipment_id && (
|
||||||
|
<p>
|
||||||
|
Equipamento físico:{' '}
|
||||||
|
<Link
|
||||||
|
className="underline"
|
||||||
|
href={`/equipamentos/${record.data.equipment_id}`}
|
||||||
|
>
|
||||||
|
Consultar ficha #{record.data.equipment_id}
|
||||||
|
</Link>
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
<p>{record.reason}</p>
|
<p>{record.reason}</p>
|
||||||
<Link
|
<Link
|
||||||
className="underline"
|
className="underline"
|
||||||
@@ -210,16 +247,130 @@ export default function CapitalRegister(props: Props) {
|
|||||||
</nav>
|
</nav>
|
||||||
</Panel>
|
</Panel>
|
||||||
)}
|
)}
|
||||||
{props.trace && <Panel title="Ordens que preservaram esta referência" description="As ligações vêm dos documentos emitidos, incluindo escolhas anteriores a revisões do cadastro.">
|
{props.trace && (
|
||||||
{props.trace.orders.data.length === 0 && <p>Ainda não há ordens visíveis com esta referência preservada.</p>}
|
<Panel
|
||||||
{props.trace.orders.data.map(line => <article key={line.id} className="space-y-2 border-b py-3 break-words"><Link className="underline" href={`/ordens/${line.order_id}`}>{line.order_number}</Link><p>{line.description} · {line.quantity} {line.unit}</p></article>)}
|
title="Ordens que preservaram esta referência"
|
||||||
<nav className="flex gap-4" aria-label="Ordens de origem">{props.trace.orders.prev_page_url && <Link preserveState href={props.trace.orders.prev_page_url}>Anterior</Link>}{props.trace.orders.next_page_url && <Link preserveState href={props.trace.orders.next_page_url}>Seguinte</Link>}</nav>
|
description="As ligações vêm dos documentos emitidos, incluindo escolhas anteriores a revisões do cadastro."
|
||||||
</Panel>}
|
>
|
||||||
{props.trace && <Panel title="Recepções destas origens" description="A quantidade aceite é a do documento original. Estornos e devoluções actuais são apresentados separadamente; a recepção não certifica capitalização contabilística.">
|
{props.trace.orders.data.length === 0 && (
|
||||||
{props.trace.receipts.data.length === 0 && <p>Ainda não há recepções visíveis nestas origens.</p>}
|
<p>
|
||||||
{props.trace.receipts.data.map(receipt => <article key={receipt.id} className="space-y-2 border-b py-3 break-words"><h3 className="font-semibold">Recepção #{receipt.receipt_id} · {receipt.description || 'Descrição por conferir'}</h3><p>Data: {receipt.received_on || 'Por conferir'} · Aceite no original: {receipt.accepted_quantity} {receipt.unit || ''}</p><p>Qualidade registada: {receipt.quality_status === 'compliant' ? 'Conforme' : receipt.quality_status === 'quarantined' ? 'Em quarentena' : 'Com divergência'}</p>{receipt.reversed && <p className="font-semibold">Recepção estornada; o original permanece no histórico.</p>}{receipt.returned_quantity !== '0.000' && <p>Devolução ao fornecedor: {receipt.returned_quantity} {receipt.unit || ''}</p>}{receipt.order_id && <Link className="underline" href={`/ordens/${receipt.order_id}`}>Conferir documentos e movimentos da ordem</Link>}</article>)}
|
Ainda não há ordens visíveis com esta referência
|
||||||
<nav className="flex gap-4" aria-label="Recepções de origem">{props.trace.receipts.prev_page_url && <Link preserveState href={props.trace.receipts.prev_page_url}>Anterior</Link>}{props.trace.receipts.next_page_url && <Link preserveState href={props.trace.receipts.next_page_url}>Seguinte</Link>}</nav>
|
preservada.
|
||||||
</Panel>}
|
</p>
|
||||||
|
)}
|
||||||
|
{props.trace.orders.data.map((line) => (
|
||||||
|
<article
|
||||||
|
key={line.id}
|
||||||
|
className="space-y-2 border-b py-3 break-words"
|
||||||
|
>
|
||||||
|
<Link
|
||||||
|
className="underline"
|
||||||
|
href={`/ordens/${line.order_id}`}
|
||||||
|
>
|
||||||
|
{line.order_number}
|
||||||
|
</Link>
|
||||||
|
<p>
|
||||||
|
{line.description} · {line.quantity} {line.unit}
|
||||||
|
</p>
|
||||||
|
</article>
|
||||||
|
))}
|
||||||
|
<nav className="flex gap-4" aria-label="Ordens de origem">
|
||||||
|
{props.trace.orders.prev_page_url && (
|
||||||
|
<Link
|
||||||
|
preserveState
|
||||||
|
href={props.trace.orders.prev_page_url}
|
||||||
|
>
|
||||||
|
Anterior
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
{props.trace.orders.next_page_url && (
|
||||||
|
<Link
|
||||||
|
preserveState
|
||||||
|
href={props.trace.orders.next_page_url}
|
||||||
|
>
|
||||||
|
Seguinte
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
</nav>
|
||||||
|
</Panel>
|
||||||
|
)}
|
||||||
|
{props.trace && (
|
||||||
|
<Panel
|
||||||
|
title="Recepções destas origens"
|
||||||
|
description="A quantidade aceite é a do documento original. Estornos e devoluções actuais são apresentados separadamente; a recepção não certifica capitalização contabilística."
|
||||||
|
>
|
||||||
|
{props.trace.receipts.data.length === 0 && (
|
||||||
|
<p>Ainda não há recepções visíveis nestas origens.</p>
|
||||||
|
)}
|
||||||
|
{props.trace.receipts.data.map((receipt) => (
|
||||||
|
<article
|
||||||
|
key={receipt.id}
|
||||||
|
className="space-y-2 border-b py-3 break-words"
|
||||||
|
>
|
||||||
|
<h3 className="font-semibold">
|
||||||
|
Recepção #{receipt.receipt_id} ·{' '}
|
||||||
|
{receipt.description ||
|
||||||
|
'Descrição por conferir'}
|
||||||
|
</h3>
|
||||||
|
<p>
|
||||||
|
Data: {receipt.received_on || 'Por conferir'} ·
|
||||||
|
Aceite no original: {receipt.accepted_quantity}{' '}
|
||||||
|
{receipt.unit || ''}
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
Qualidade registada:{' '}
|
||||||
|
{receipt.quality_status === 'compliant'
|
||||||
|
? 'Conforme'
|
||||||
|
: receipt.quality_status === 'quarantined'
|
||||||
|
? 'Em quarentena'
|
||||||
|
: 'Com divergência'}
|
||||||
|
</p>
|
||||||
|
{receipt.reversed && (
|
||||||
|
<p className="font-semibold">
|
||||||
|
Recepção estornada; o original permanece no
|
||||||
|
histórico.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{receipt.returned_quantity !== '0.000' && (
|
||||||
|
<p>
|
||||||
|
Devolução ao fornecedor:{' '}
|
||||||
|
{receipt.returned_quantity}{' '}
|
||||||
|
{receipt.unit || ''}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{receipt.order_id && (
|
||||||
|
<Link
|
||||||
|
className="underline"
|
||||||
|
href={`/ordens/${receipt.order_id}`}
|
||||||
|
>
|
||||||
|
Conferir documentos e movimentos da ordem
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
</article>
|
||||||
|
))}
|
||||||
|
<nav
|
||||||
|
className="flex gap-4"
|
||||||
|
aria-label="Recepções de origem"
|
||||||
|
>
|
||||||
|
{props.trace.receipts.prev_page_url && (
|
||||||
|
<Link
|
||||||
|
preserveState
|
||||||
|
href={props.trace.receipts.prev_page_url}
|
||||||
|
>
|
||||||
|
Anterior
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
{props.trace.receipts.next_page_url && (
|
||||||
|
<Link
|
||||||
|
preserveState
|
||||||
|
href={props.trace.receipts.next_page_url}
|
||||||
|
>
|
||||||
|
Seguinte
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
</nav>
|
||||||
|
</Panel>
|
||||||
|
)}
|
||||||
{props.canManage && (
|
{props.canManage && (
|
||||||
<Panel
|
<Panel
|
||||||
title={
|
title={
|
||||||
|
|||||||
@@ -0,0 +1,385 @@
|
|||||||
|
import { Head, Link, useForm } from '@inertiajs/react';
|
||||||
|
import { useEffect, useRef } from 'react';
|
||||||
|
import {
|
||||||
|
FormErrors,
|
||||||
|
PageTitle,
|
||||||
|
Panel,
|
||||||
|
controlClass,
|
||||||
|
} from '@/components/procurement';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
|
||||||
|
type Level = {
|
||||||
|
role: string;
|
||||||
|
expire_minutes: number;
|
||||||
|
reminder_minutes: number | null;
|
||||||
|
escalation_minutes: number | null;
|
||||||
|
profile_ids: number[];
|
||||||
|
};
|
||||||
|
type Policy = {
|
||||||
|
id: number;
|
||||||
|
version: number;
|
||||||
|
state: string;
|
||||||
|
reason: string;
|
||||||
|
data: { enabled: boolean; levels: Level[] };
|
||||||
|
};
|
||||||
|
type Props = {
|
||||||
|
current: Policy | null;
|
||||||
|
profiles: { id: number; name: string }[];
|
||||||
|
roles: Record<string, string>;
|
||||||
|
actorId: number;
|
||||||
|
tenantId: number;
|
||||||
|
history: {
|
||||||
|
data: Policy[];
|
||||||
|
prev_page_url: string | null;
|
||||||
|
next_page_url: string | null;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
type Draft = {
|
||||||
|
role: string;
|
||||||
|
expire_minutes: string;
|
||||||
|
reminder_minutes: string;
|
||||||
|
escalation_minutes: string;
|
||||||
|
profile_ids: number[];
|
||||||
|
};
|
||||||
|
const draft = (level: Level): Draft => ({
|
||||||
|
...level,
|
||||||
|
expire_minutes: String(level.expire_minutes),
|
||||||
|
reminder_minutes:
|
||||||
|
level.reminder_minutes === null ? '' : String(level.reminder_minutes),
|
||||||
|
escalation_minutes:
|
||||||
|
level.escalation_minutes === null
|
||||||
|
? ''
|
||||||
|
: String(level.escalation_minutes),
|
||||||
|
profile_ids: [...level.profile_ids],
|
||||||
|
});
|
||||||
|
export default function ApprovalTimeouts(props: Props) {
|
||||||
|
const url = '/administracao/prazos-aprovacao';
|
||||||
|
const form = useForm(
|
||||||
|
`approval-timeouts:${props.tenantId}:${props.actorId}`,
|
||||||
|
{
|
||||||
|
operation_key: '',
|
||||||
|
version: props.current?.version ?? 0,
|
||||||
|
enabled: props.current?.data.enabled ?? false,
|
||||||
|
levels: props.current?.data.levels.map(draft) ?? ([] as Draft[]),
|
||||||
|
reason: '',
|
||||||
|
},
|
||||||
|
);
|
||||||
|
const current = form.data.version === (props.current?.version ?? 0);
|
||||||
|
const ref = useRef<HTMLFormElement>(null);
|
||||||
|
useEffect(() => {
|
||||||
|
const node = ref.current;
|
||||||
|
window.dispatchEvent(
|
||||||
|
new CustomEvent('sgc:context-dirty', {
|
||||||
|
detail: { form: node, dirty: form.isDirty },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
return () => {
|
||||||
|
window.dispatchEvent(
|
||||||
|
new CustomEvent('sgc:context-dirty', {
|
||||||
|
detail: { form: node, dirty: false },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
}, [form.isDirty]);
|
||||||
|
const edit = () =>
|
||||||
|
form.setData({
|
||||||
|
operation_key: '',
|
||||||
|
version: props.current?.version ?? 0,
|
||||||
|
enabled: props.current?.data.enabled ?? false,
|
||||||
|
levels: props.current?.data.levels.map(draft) ?? [],
|
||||||
|
reason: '',
|
||||||
|
});
|
||||||
|
const change = (index: number, patch: Partial<Draft>) =>
|
||||||
|
form.setData((data) => ({
|
||||||
|
...data,
|
||||||
|
levels: data.levels.map((level, i) =>
|
||||||
|
i === index
|
||||||
|
? {
|
||||||
|
...level,
|
||||||
|
...patch,
|
||||||
|
...(patch.escalation_minutes === ''
|
||||||
|
? { profile_ids: [] }
|
||||||
|
: {}),
|
||||||
|
}
|
||||||
|
: level,
|
||||||
|
),
|
||||||
|
operation_key: '',
|
||||||
|
}));
|
||||||
|
return (
|
||||||
|
<div className="mx-auto grid w-full max-w-6xl min-w-0 gap-6 p-5 lg:p-8">
|
||||||
|
<Head title="Prazos das aprovações" />
|
||||||
|
<PageTitle
|
||||||
|
eyebrow="Administração"
|
||||||
|
title="Prazos das aprovações"
|
||||||
|
description="Configure os prazos que a empresa pretende aplicar nas novas submissões. Não são atribuídas permissões aos destinatários do escalamento."
|
||||||
|
/>
|
||||||
|
<Link className="underline" href="/administracao/parametrizacao">
|
||||||
|
Voltar à parametrização
|
||||||
|
</Link>
|
||||||
|
<Panel
|
||||||
|
title={`Política actual · versão ${props.current?.version ?? 0}`}
|
||||||
|
description="Os valores são minutos corridos desde a activação da etapa, sem calendário de dias úteis implícito."
|
||||||
|
>
|
||||||
|
<p>
|
||||||
|
{props.current?.data.enabled
|
||||||
|
? 'Aplicável a novas submissões'
|
||||||
|
: 'Sem prazos activos para novas submissões'}
|
||||||
|
</p>
|
||||||
|
<form
|
||||||
|
ref={ref}
|
||||||
|
className="mt-5 space-y-5"
|
||||||
|
onSubmit={(event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
const operation =
|
||||||
|
form.data.operation_key || crypto.randomUUID();
|
||||||
|
form.setData('operation_key', operation);
|
||||||
|
form.transform((data) => ({
|
||||||
|
...data,
|
||||||
|
operation_key: operation,
|
||||||
|
levels: data.levels.map((level) => ({
|
||||||
|
...level,
|
||||||
|
reminder_minutes:
|
||||||
|
level.reminder_minutes || null,
|
||||||
|
escalation_minutes:
|
||||||
|
level.escalation_minutes || null,
|
||||||
|
})),
|
||||||
|
}));
|
||||||
|
form.post(url, {
|
||||||
|
preserveScroll: true,
|
||||||
|
onSuccess: () => {
|
||||||
|
form.reset();
|
||||||
|
form.clearErrors();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<FormErrors errors={form.errors} />
|
||||||
|
{!current && (
|
||||||
|
<p>
|
||||||
|
A política mudou. Reveja a versão actual antes de
|
||||||
|
guardar outra alteração.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<Button type="button" variant="outline" onClick={edit}>
|
||||||
|
Preparar a política actual
|
||||||
|
</Button>
|
||||||
|
<label className="flex items-center gap-2">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={form.data.enabled}
|
||||||
|
onChange={(e) =>
|
||||||
|
form.setData('enabled', e.target.checked)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
Aplicar a novas submissões
|
||||||
|
</label>
|
||||||
|
{form.data.levels.map((level, index) => (
|
||||||
|
<fieldset
|
||||||
|
className="min-w-0 space-y-4 rounded-lg border p-4"
|
||||||
|
key={index}
|
||||||
|
>
|
||||||
|
<legend>Nível {index + 1}</legend>
|
||||||
|
<label className="grid gap-2">
|
||||||
|
Etapa
|
||||||
|
<select
|
||||||
|
className={controlClass}
|
||||||
|
value={level.role}
|
||||||
|
onChange={(e) =>
|
||||||
|
change(index, { role: e.target.value })
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{Object.entries(props.roles).map(
|
||||||
|
([key, label]) => (
|
||||||
|
<option key={key} value={key}>
|
||||||
|
{label}
|
||||||
|
</option>
|
||||||
|
),
|
||||||
|
)}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<div className="grid gap-4 md:grid-cols-3">
|
||||||
|
{(
|
||||||
|
[
|
||||||
|
'reminder_minutes',
|
||||||
|
'escalation_minutes',
|
||||||
|
'expire_minutes',
|
||||||
|
] as const
|
||||||
|
).map((field) => (
|
||||||
|
<label key={field} className="grid gap-2">
|
||||||
|
{field === 'expire_minutes'
|
||||||
|
? 'Expiração · minutos'
|
||||||
|
: field === 'reminder_minutes'
|
||||||
|
? 'Lembrete · minutos, se aplicável'
|
||||||
|
: 'Escalamento · minutos, se aplicável'}
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
min={1}
|
||||||
|
max={5256000}
|
||||||
|
step={1}
|
||||||
|
required={
|
||||||
|
field === 'expire_minutes'
|
||||||
|
}
|
||||||
|
className={controlClass}
|
||||||
|
value={level[field]}
|
||||||
|
onChange={(e) =>
|
||||||
|
change(index, {
|
||||||
|
[field]: e.target.value,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
{level.escalation_minutes !== '' && (
|
||||||
|
<fieldset className="space-y-2">
|
||||||
|
<legend>
|
||||||
|
Perfis destinatários do escalamento
|
||||||
|
</legend>
|
||||||
|
{props.profiles.length === 0 && (
|
||||||
|
<p>
|
||||||
|
Configure os perfis da empresa antes
|
||||||
|
de seleccionar destinatários.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{props.profiles.map((profile) => (
|
||||||
|
<label
|
||||||
|
key={profile.id}
|
||||||
|
className="flex items-center gap-2"
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={level.profile_ids.includes(
|
||||||
|
profile.id,
|
||||||
|
)}
|
||||||
|
onChange={(e) =>
|
||||||
|
change(index, {
|
||||||
|
profile_ids: e.target
|
||||||
|
.checked
|
||||||
|
? [
|
||||||
|
...level.profile_ids,
|
||||||
|
profile.id,
|
||||||
|
]
|
||||||
|
: level.profile_ids.filter(
|
||||||
|
(id) =>
|
||||||
|
id !==
|
||||||
|
profile.id,
|
||||||
|
),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
{profile.name}
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</fieldset>
|
||||||
|
)}
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() =>
|
||||||
|
form.setData((data) => ({
|
||||||
|
...data,
|
||||||
|
levels: data.levels.filter(
|
||||||
|
(_, i) => i !== index,
|
||||||
|
),
|
||||||
|
operation_key: '',
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
>
|
||||||
|
Retirar este nível da preparação
|
||||||
|
</Button>
|
||||||
|
</fieldset>
|
||||||
|
))}
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
disabled={form.data.levels.length >= 8}
|
||||||
|
onClick={() => {
|
||||||
|
const role = Object.keys(props.roles).find(
|
||||||
|
(key) =>
|
||||||
|
!form.data.levels.some(
|
||||||
|
(level) => level.role === key,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
if (role)
|
||||||
|
form.setData((data) => ({
|
||||||
|
...data,
|
||||||
|
levels: [
|
||||||
|
...data.levels,
|
||||||
|
{
|
||||||
|
role,
|
||||||
|
expire_minutes: '',
|
||||||
|
reminder_minutes: '',
|
||||||
|
escalation_minutes: '',
|
||||||
|
profile_ids: [],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
operation_key: '',
|
||||||
|
}));
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Acrescentar etapa
|
||||||
|
</Button>
|
||||||
|
<label className="grid gap-2">
|
||||||
|
Motivo desta versão
|
||||||
|
<textarea
|
||||||
|
required
|
||||||
|
minLength={10}
|
||||||
|
maxLength={4000}
|
||||||
|
className={controlClass}
|
||||||
|
value={form.data.reason}
|
||||||
|
onChange={(e) =>
|
||||||
|
form.setData('reason', e.target.value)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
Na expiração, o pedido regressa ao requisitante para
|
||||||
|
nova submissão. Os ciclos anteriores ficam preservados;
|
||||||
|
uma alteração desta política não muda os prazos já
|
||||||
|
submetidos.
|
||||||
|
</p>
|
||||||
|
<Button disabled={form.processing || !current}>
|
||||||
|
Guardar política
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
</Panel>
|
||||||
|
<Panel title="Histórico da política">
|
||||||
|
{props.history.data.map((policy) => (
|
||||||
|
<article
|
||||||
|
key={policy.id}
|
||||||
|
className="space-y-2 border-b py-3"
|
||||||
|
>
|
||||||
|
<h3 className="font-semibold">
|
||||||
|
Versão {policy.version} ·{' '}
|
||||||
|
{policy.data.enabled
|
||||||
|
? 'Activa para novas submissões'
|
||||||
|
: 'Inactiva para novas submissões'}
|
||||||
|
</h3>
|
||||||
|
<p>{policy.reason}</p>
|
||||||
|
{policy.data.levels.map((level) => (
|
||||||
|
<p key={level.role}>
|
||||||
|
{props.roles[level.role]} · expiração em{' '}
|
||||||
|
{level.expire_minutes} minutos corridos
|
||||||
|
</p>
|
||||||
|
))}
|
||||||
|
</article>
|
||||||
|
))}
|
||||||
|
<nav
|
||||||
|
className="mt-3 flex gap-4"
|
||||||
|
aria-label="Histórico da política"
|
||||||
|
>
|
||||||
|
{props.history.prev_page_url && (
|
||||||
|
<Link preserveState href={props.history.prev_page_url}>
|
||||||
|
Anterior
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
{props.history.next_page_url && (
|
||||||
|
<Link preserveState href={props.history.next_page_url}>
|
||||||
|
Seguinte
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
</nav>
|
||||||
|
</Panel>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { Head, Link, router, useForm } from '@inertiajs/react';
|
import { Head, Link, router, useForm } from '@inertiajs/react';
|
||||||
import {
|
import {
|
||||||
|
ActionBar,
|
||||||
PageTitle,
|
PageTitle,
|
||||||
Panel,
|
Panel,
|
||||||
FormErrors,
|
FormErrors,
|
||||||
@@ -185,7 +186,7 @@ export default function PeopleIndex({
|
|||||||
description="Contratação de prestadores individuais e recrutamento de trabalhadores, com critérios próprios e decisão independente."
|
description="Contratação de prestadores individuais e recrutamento de trabalhadores, com critérios próprios e decisão independente."
|
||||||
action={
|
action={
|
||||||
ready ? (
|
ready ? (
|
||||||
<div className="flex flex-wrap gap-2">
|
<ActionBar>
|
||||||
<Button asChild>
|
<Button asChild>
|
||||||
<Link href="/pessoas/relatorios">
|
<Link href="/pessoas/relatorios">
|
||||||
Relatórios
|
Relatórios
|
||||||
@@ -197,7 +198,7 @@ export default function PeopleIndex({
|
|||||||
>
|
>
|
||||||
Actualizar
|
Actualizar
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</ActionBar>
|
||||||
) : undefined
|
) : undefined
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
@@ -319,14 +320,14 @@ export default function PeopleIndex({
|
|||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-4">
|
<ActionBar>
|
||||||
<Button disabled={filtering.processing}>
|
<Button disabled={filtering.processing}>
|
||||||
Aplicar filtros
|
Aplicar filtros
|
||||||
</Button>
|
</Button>
|
||||||
<Link className="underline" href="/pessoas">
|
<Link className="underline" href="/pessoas">
|
||||||
Limpar filtros
|
Limpar filtros
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</ActionBar>
|
||||||
</form>
|
</form>
|
||||||
</Panel>
|
</Panel>
|
||||||
{insights && (
|
{insights && (
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import { Head, Link, useForm } from '@inertiajs/react';
|
import { Head, Link, useForm } from '@inertiajs/react';
|
||||||
import {
|
import {
|
||||||
|
ActionBar,
|
||||||
|
TableViewport,
|
||||||
PageTitle,
|
PageTitle,
|
||||||
Panel,
|
Panel,
|
||||||
FormErrors,
|
FormErrors,
|
||||||
@@ -130,7 +132,7 @@ export default function Reports(props: Props) {
|
|||||||
title="Relatórios"
|
title="Relatórios"
|
||||||
description="Dados reutilizados dos processos que está autorizado a consultar, no contexto seleccionado."
|
description="Dados reutilizados dos processos que está autorizado a consultar, no contexto seleccionado."
|
||||||
/>
|
/>
|
||||||
<div className="people-report-tools flex flex-wrap gap-3">
|
<ActionBar className="people-report-tools">
|
||||||
<Link
|
<Link
|
||||||
href={`/pessoas/relatorios?${new URLSearchParams({ ...props.filters, view: 'deadlines' }).toString()}`}
|
href={`/pessoas/relatorios?${new URLSearchParams({ ...props.filters, view: 'deadlines' }).toString()}`}
|
||||||
>
|
>
|
||||||
@@ -161,7 +163,7 @@ export default function Reports(props: Props) {
|
|||||||
>
|
>
|
||||||
Exportar resultados em CSV
|
Exportar resultados em CSV
|
||||||
</a>
|
</a>
|
||||||
</div>
|
</ActionBar>
|
||||||
<div className="people-report-tools">
|
<div className="people-report-tools">
|
||||||
<Panel
|
<Panel
|
||||||
title="Filtrar relatório"
|
title="Filtrar relatório"
|
||||||
@@ -292,12 +294,12 @@ export default function Reports(props: Props) {
|
|||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
<div className="flex items-end gap-3">
|
<ActionBar>
|
||||||
<Button disabled={form.processing}>
|
<Button disabled={form.processing}>
|
||||||
Aplicar filtros
|
Aplicar filtros
|
||||||
</Button>
|
</Button>
|
||||||
<Link href="/pessoas/relatorios">Limpar</Link>
|
<Link href="/pessoas/relatorios">Limpar</Link>
|
||||||
</div>
|
</ActionBar>
|
||||||
<FormErrors errors={form.errors} />
|
<FormErrors errors={form.errors} />
|
||||||
</form>
|
</form>
|
||||||
</Panel>
|
</Panel>
|
||||||
@@ -341,7 +343,7 @@ export default function Reports(props: Props) {
|
|||||||
trabalho da equipa; o mesmo processo pode ter várias
|
trabalho da equipa; o mesmo processo pode ter várias
|
||||||
ocorrências.
|
ocorrências.
|
||||||
</p>
|
</p>
|
||||||
<div className="overflow-x-auto">
|
<TableViewport>
|
||||||
<table className="w-full text-left text-sm">
|
<table className="w-full text-left text-sm">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
@@ -388,7 +390,7 @@ export default function Reports(props: Props) {
|
|||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</TableViewport>
|
||||||
{props.deadlineReport.items.length === 0 && (
|
{props.deadlineReport.items.length === 0 && (
|
||||||
<p className="mt-3">
|
<p className="mt-3">
|
||||||
Sem intervenções ou alertas visíveis neste
|
Sem intervenções ou alertas visíveis neste
|
||||||
@@ -592,7 +594,7 @@ export default function Reports(props: Props) {
|
|||||||
? ` · Pesquisa: ${props.filters.search}`
|
? ` · Pesquisa: ${props.filters.search}`
|
||||||
: ''}
|
: ''}
|
||||||
</p>
|
</p>
|
||||||
<div className="overflow-x-auto">
|
<TableViewport>
|
||||||
<table className="w-full text-left text-sm">
|
<table className="w-full text-left text-sm">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
@@ -641,7 +643,7 @@ export default function Reports(props: Props) {
|
|||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</TableViewport>
|
||||||
<div className="people-report-tools mt-4 flex gap-4">
|
<div className="people-report-tools mt-4 flex gap-4">
|
||||||
{props.processes.prev_page_url && (
|
{props.processes.prev_page_url && (
|
||||||
<Link href={props.processes.prev_page_url}>
|
<Link href={props.processes.prev_page_url}>
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { Head } from '@inertiajs/react';
|
import { Head } from '@inertiajs/react';
|
||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { PageTitle, Panel } from '@/components/procurement';
|
import { ActionBar, PageTitle, Panel } from '@/components/procurement';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Label } from '@/components/ui/label';
|
import { Label } from '@/components/ui/label';
|
||||||
|
|
||||||
@@ -352,7 +352,7 @@ export default function AdmissionProposal() {
|
|||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
</Label>
|
</Label>
|
||||||
<div className="flex flex-wrap gap-2">
|
<ActionBar>
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
disabled={
|
disabled={
|
||||||
@@ -395,7 +395,7 @@ export default function AdmissionProposal() {
|
|||||||
>
|
>
|
||||||
Simular devolução
|
Simular devolução
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</ActionBar>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -14,7 +14,13 @@ import {
|
|||||||
PackageCheck,
|
PackageCheck,
|
||||||
Warehouse,
|
Warehouse,
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import { PageTitle, Panel, Status } from '@/components/procurement';
|
import {
|
||||||
|
ActionBar,
|
||||||
|
TableViewport,
|
||||||
|
PageTitle,
|
||||||
|
Panel,
|
||||||
|
Status,
|
||||||
|
} from '@/components/procurement';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
import { Label } from '@/components/ui/label';
|
import { Label } from '@/components/ui/label';
|
||||||
@@ -145,7 +151,7 @@ export default function Preview({
|
|||||||
.includes(search.toLowerCase()),
|
.includes(search.toLowerCase()),
|
||||||
);
|
);
|
||||||
const requestTable = (
|
const requestTable = (
|
||||||
<div className="overflow-x-auto">
|
<TableViewport>
|
||||||
<table className="w-full text-left text-sm">
|
<table className="w-full text-left text-sm">
|
||||||
<thead className="border-b text-xs text-muted-foreground">
|
<thead className="border-b text-xs text-muted-foreground">
|
||||||
<tr>
|
<tr>
|
||||||
@@ -212,7 +218,7 @@ export default function Preview({
|
|||||||
Nenhum exemplo corresponde à pesquisa.
|
Nenhum exemplo corresponde à pesquisa.
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
</div>
|
</TableViewport>
|
||||||
);
|
);
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -410,7 +416,7 @@ export default function Preview({
|
|||||||
title="Matriz de avaliação · DEMO-001"
|
title="Matriz de avaliação · DEMO-001"
|
||||||
description="Valores ilustrativos. Preço 40% · qualidade 20% · prazo 15% · histórico 15% · pagamento 10%."
|
description="Valores ilustrativos. Preço 40% · qualidade 20% · prazo 15% · histórico 15% · pagamento 10%."
|
||||||
>
|
>
|
||||||
<div className="overflow-x-auto">
|
<TableViewport>
|
||||||
<table className="w-full text-left text-sm">
|
<table className="w-full text-left text-sm">
|
||||||
<thead className="border-b text-xs text-muted-foreground">
|
<thead className="border-b text-xs text-muted-foreground">
|
||||||
<tr>
|
<tr>
|
||||||
@@ -455,7 +461,7 @@ export default function Preview({
|
|||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</TableViewport>
|
||||||
<p className="mt-5 rounded-lg bg-amber-50 p-4 text-sm text-amber-900">
|
<p className="mt-5 rounded-lg bg-amber-50 p-4 text-sm text-amber-900">
|
||||||
Exemplo de comparação incompleta: uma das
|
Exemplo de comparação incompleta: uma das
|
||||||
propostas ainda não tem duas avaliações. A
|
propostas ainda não tem duas avaliações. A
|
||||||
@@ -803,7 +809,7 @@ export default function Preview({
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="mt-6 flex flex-wrap gap-3">
|
<ActionBar className="mt-6">
|
||||||
<Button
|
<Button
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
setDetail({
|
setDetail({
|
||||||
@@ -830,7 +836,7 @@ export default function Preview({
|
|||||||
<Button disabled>
|
<Button disabled>
|
||||||
Acção indisponível
|
Acção indisponível
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</ActionBar>
|
||||||
</Panel>
|
</Panel>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { InventoryNotice, ReceiptProgressTable } from '@/components/inventory';
|
import { InventoryNotice, ReceiptProgressTable } from '@/components/inventory';
|
||||||
import { Panel, controlClass } from '@/components/procurement';
|
import { TableViewport, Panel, controlClass } from '@/components/procurement';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
import { Label } from '@/components/ui/label';
|
import { Label } from '@/components/ui/label';
|
||||||
@@ -227,7 +227,7 @@ export default function InventoryDemo({
|
|||||||
onChange={(event) => setSearch(event.target.value)}
|
onChange={(event) => setSearch(event.target.value)}
|
||||||
className="mb-5 max-w-sm"
|
className="mb-5 max-w-sm"
|
||||||
/>
|
/>
|
||||||
<div className="overflow-x-auto">
|
<TableViewport>
|
||||||
<table className="w-full text-left text-sm">
|
<table className="w-full text-left text-sm">
|
||||||
<thead className="border-b text-muted-foreground">
|
<thead className="border-b text-muted-foreground">
|
||||||
<tr>
|
<tr>
|
||||||
@@ -272,7 +272,7 @@ export default function InventoryDemo({
|
|||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</TableViewport>
|
||||||
{visible.length === 0 && (
|
{visible.length === 0 && (
|
||||||
<p className="py-5 text-sm text-muted-foreground">
|
<p className="py-5 text-sm text-muted-foreground">
|
||||||
Nenhum exemplo corresponde à pesquisa.
|
Nenhum exemplo corresponde à pesquisa.
|
||||||
|
|||||||
@@ -1,7 +1,13 @@
|
|||||||
import { Head, Link } from '@inertiajs/react';
|
import { Head, Link } from '@inertiajs/react';
|
||||||
import { Printer } from 'lucide-react';
|
import { Printer } from 'lucide-react';
|
||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { controlClass, PageTitle, Panel } from '@/components/procurement';
|
import {
|
||||||
|
ActionBar,
|
||||||
|
TableViewport,
|
||||||
|
controlClass,
|
||||||
|
PageTitle,
|
||||||
|
Panel,
|
||||||
|
} from '@/components/procurement';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Label } from '@/components/ui/label';
|
import { Label } from '@/components/ui/label';
|
||||||
|
|
||||||
@@ -312,7 +318,7 @@ export default function RecommendationProposal() {
|
|||||||
. Os três concorrentes são fornecedores distintos;
|
. Os três concorrentes são fornecedores distintos;
|
||||||
no cenário pronto têm duas avaliações por proposta.
|
no cenário pronto têm duas avaliações por proposta.
|
||||||
</p>
|
</p>
|
||||||
<div className="overflow-x-auto">
|
<TableViewport>
|
||||||
<table className="w-full text-left text-sm">
|
<table className="w-full text-left text-sm">
|
||||||
<caption className="mb-3 text-left text-xs text-muted-foreground">
|
<caption className="mb-3 text-left text-xs text-muted-foreground">
|
||||||
Pontuações ilustrativas, sem recálculo de
|
Pontuações ilustrativas, sem recálculo de
|
||||||
@@ -361,7 +367,7 @@ export default function RecommendationProposal() {
|
|||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</TableViewport>
|
||||||
</Panel>
|
</Panel>
|
||||||
</div>
|
</div>
|
||||||
<div className="print:hidden">
|
<div className="print:hidden">
|
||||||
@@ -509,7 +515,7 @@ export default function RecommendationProposal() {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<div className="flex flex-wrap gap-3">
|
<ActionBar>
|
||||||
<Button
|
<Button
|
||||||
disabled={
|
disabled={
|
||||||
(
|
(
|
||||||
@@ -545,7 +551,7 @@ export default function RecommendationProposal() {
|
|||||||
>
|
>
|
||||||
Simular devolução
|
Simular devolução
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</ActionBar>
|
||||||
</article>
|
</article>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import AgreementOrderBindings, {
|
|||||||
import { ComparisonPolicySummary } from '@/components/comparison-policy-summary';
|
import { ComparisonPolicySummary } from '@/components/comparison-policy-summary';
|
||||||
import type { ComparisonPolicy } from '@/components/comparison-policy-summary';
|
import type { ComparisonPolicy } from '@/components/comparison-policy-summary';
|
||||||
import {
|
import {
|
||||||
|
TableViewport,
|
||||||
FormErrors,
|
FormErrors,
|
||||||
PageTitle,
|
PageTitle,
|
||||||
Panel,
|
Panel,
|
||||||
@@ -135,7 +136,7 @@ export default function Award({
|
|||||||
}
|
}
|
||||||
>
|
>
|
||||||
<ComparisonPolicySummary policy={comparison.policy} />
|
<ComparisonPolicySummary policy={comparison.policy} />
|
||||||
<div className="overflow-x-auto">
|
<TableViewport>
|
||||||
<table className="w-full text-left text-sm">
|
<table className="w-full text-left text-sm">
|
||||||
<thead className="border-b text-muted-foreground">
|
<thead className="border-b text-muted-foreground">
|
||||||
<tr>
|
<tr>
|
||||||
@@ -205,7 +206,7 @@ export default function Award({
|
|||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</TableViewport>
|
||||||
</Panel>
|
</Panel>
|
||||||
<p className="text-sm">
|
<p className="text-sm">
|
||||||
{recommendation.adopted
|
{recommendation.adopted
|
||||||
|
|||||||
@@ -4,7 +4,12 @@ import { hasPreparationChanges } from '@/lib/requisition-history';
|
|||||||
import BudgetDistributionFields, {
|
import BudgetDistributionFields, {
|
||||||
type BudgetDistributionOption,
|
type BudgetDistributionOption,
|
||||||
} from '@/components/budget-distribution-fields';
|
} from '@/components/budget-distribution-fields';
|
||||||
import { FormErrors, PageTitle, Panel } from '@/components/procurement';
|
import {
|
||||||
|
ActionBar,
|
||||||
|
FormErrors,
|
||||||
|
PageTitle,
|
||||||
|
Panel,
|
||||||
|
} from '@/components/procurement';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { money } from '@/types/procurement';
|
import { money } from '@/types/procurement';
|
||||||
|
|
||||||
@@ -98,7 +103,7 @@ export default function Amendment({
|
|||||||
reason={form.data.reason}
|
reason={form.data.reason}
|
||||||
onReason={(reason) => form.setData('reason', reason)}
|
onReason={(reason) => form.setData('reason', reason)}
|
||||||
/>
|
/>
|
||||||
<div className="flex flex-wrap gap-3">
|
<ActionBar>
|
||||||
<Button disabled={form.processing}>
|
<Button disabled={form.processing}>
|
||||||
Confirmar nova versão
|
Confirmar nova versão
|
||||||
</Button>
|
</Button>
|
||||||
@@ -107,7 +112,7 @@ export default function Amendment({
|
|||||||
Voltar à ordem
|
Voltar à ordem
|
||||||
</Link>
|
</Link>
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</ActionBar>
|
||||||
</form>
|
</form>
|
||||||
<Panel title="Histórico preservado">
|
<Panel title="Histórico preservado">
|
||||||
{history.map((event, index) => (
|
{history.map((event, index) => (
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Head, Link } from '@inertiajs/react';
|
import { Head, Link } from '@inertiajs/react';
|
||||||
import { PageTitle, Panel } from '@/components/procurement';
|
import { TableViewport, PageTitle, Panel } from '@/components/procurement';
|
||||||
import { money, date } from '@/types/procurement';
|
import { money, date } from '@/types/procurement';
|
||||||
import type { PurchaseAward, PurchaseOrder } from '@/types/purchase';
|
import type { PurchaseAward, PurchaseOrder } from '@/types/purchase';
|
||||||
|
|
||||||
@@ -35,7 +35,7 @@ export default function Orders({
|
|||||||
Preparar ordens por parcelas ou consolidar origens
|
Preparar ordens por parcelas ou consolidar origens
|
||||||
</Link>
|
</Link>
|
||||||
)}
|
)}
|
||||||
<div className="overflow-x-auto">
|
<TableViewport>
|
||||||
<table className="w-full text-left text-sm">
|
<table className="w-full text-left text-sm">
|
||||||
<thead className="border-b text-muted-foreground">
|
<thead className="border-b text-muted-foreground">
|
||||||
<tr>
|
<tr>
|
||||||
@@ -76,7 +76,7 @@ export default function Orders({
|
|||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</TableViewport>
|
||||||
{orders.data.length === 0 && (
|
{orders.data.length === 0 && (
|
||||||
<p className="py-6 text-sm text-muted-foreground">
|
<p className="py-6 text-sm text-muted-foreground">
|
||||||
Ainda não foram emitidas ordens.
|
Ainda não foram emitidas ordens.
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { Head, Link, router, useForm } from '@inertiajs/react';
|
import { Head, Link, router, useForm } from '@inertiajs/react';
|
||||||
import {
|
import {
|
||||||
|
TableViewport,
|
||||||
FormErrors,
|
FormErrors,
|
||||||
PageTitle,
|
PageTitle,
|
||||||
Panel,
|
Panel,
|
||||||
@@ -257,7 +258,7 @@ function Confer({ attempt }: { attempt: Attempt }) {
|
|||||||
}
|
}
|
||||||
function Matrix({ rows, topIds }: { rows: Row[]; topIds?: number[] }) {
|
function Matrix({ rows, topIds }: { rows: Row[]; topIds?: number[] }) {
|
||||||
return (
|
return (
|
||||||
<div className="overflow-x-auto">
|
<TableViewport>
|
||||||
<table className="w-full text-left text-sm">
|
<table className="w-full text-left text-sm">
|
||||||
<thead className="border-b">
|
<thead className="border-b">
|
||||||
<tr>
|
<tr>
|
||||||
@@ -294,7 +295,7 @@ function Matrix({ rows, topIds }: { rows: Row[]; topIds?: number[] }) {
|
|||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</TableViewport>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
export default function Recommendation(props: Props) {
|
export default function Recommendation(props: Props) {
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import { QuotationCommercialTerms } from '@/components/quotation-commercial-term
|
|||||||
import { ExchangeSummary } from '@/components/quotation-exchange-panel';
|
import { ExchangeSummary } from '@/components/quotation-exchange-panel';
|
||||||
import type { ExchangeBasis } from '@/components/quotation-exchange-panel';
|
import type { ExchangeBasis } from '@/components/quotation-exchange-panel';
|
||||||
import type { CommercialTerms } from '@/components/quotation-commercial-terms';
|
import type { CommercialTerms } from '@/components/quotation-commercial-terms';
|
||||||
import { PageTitle, Panel, Status } from '@/components/procurement';
|
import { ActionBar, PageTitle, Panel, Status } from '@/components/procurement';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { date, roleLabels, statusLabels } from '@/types/procurement';
|
import { date, roleLabels, statusLabels } from '@/types/procurement';
|
||||||
|
|
||||||
@@ -204,7 +204,7 @@ export default function ReviewReport({
|
|||||||
title="Relatório de conferência"
|
title="Relatório de conferência"
|
||||||
description={`${report.company} · ${r.department} · Solicitante: ${r.requester}`}
|
description={`${report.company} · ${r.department} · Solicitante: ${r.requester}`}
|
||||||
action={
|
action={
|
||||||
<div className="flex flex-wrap gap-3 print:hidden">
|
<ActionBar>
|
||||||
<Button asChild variant="outline">
|
<Button asChild variant="outline">
|
||||||
<Link href="/relatorios">
|
<Link href="/relatorios">
|
||||||
Relatórios de compras
|
Relatórios de compras
|
||||||
@@ -224,7 +224,7 @@ export default function ReviewReport({
|
|||||||
Exportar conferência completa (CSV)
|
Exportar conferência completa (CSV)
|
||||||
</a>
|
</a>
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</ActionBar>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<div className="rounded-xl border p-4 text-sm">
|
<div className="rounded-xl border p-4 text-sm">
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { AgreementOrderLimitSummary } from '@/components/agreement-order-binding
|
|||||||
import { Printer } from 'lucide-react';
|
import { Printer } from 'lucide-react';
|
||||||
import { ComparisonPolicySummary } from '@/components/comparison-policy-summary';
|
import { ComparisonPolicySummary } from '@/components/comparison-policy-summary';
|
||||||
import { QuotationCommercialTerms } from '@/components/quotation-commercial-terms';
|
import { QuotationCommercialTerms } from '@/components/quotation-commercial-terms';
|
||||||
import { PageTitle, Panel } from '@/components/procurement';
|
import { TableViewport, PageTitle, Panel } from '@/components/procurement';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { date, money, roleLabels } from '@/types/procurement';
|
import { date, money, roleLabels } from '@/types/procurement';
|
||||||
import { ExchangeSummary } from '@/components/quotation-exchange-panel';
|
import { ExchangeSummary } from '@/components/quotation-exchange-panel';
|
||||||
@@ -271,7 +271,7 @@ export default function OrderShow({
|
|||||||
</Panel>
|
</Panel>
|
||||||
</div>
|
</div>
|
||||||
<Panel title="Artigos e valores congelados">
|
<Panel title="Artigos e valores congelados">
|
||||||
<div className="overflow-x-auto">
|
<TableViewport>
|
||||||
<table className="w-full text-left text-sm">
|
<table className="w-full text-left text-sm">
|
||||||
<thead className="border-b text-muted-foreground">
|
<thead className="border-b text-muted-foreground">
|
||||||
<tr>
|
<tr>
|
||||||
@@ -310,7 +310,7 @@ export default function OrderShow({
|
|||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</TableViewport>
|
||||||
<dl className="mt-5 ml-auto max-w-sm space-y-3 text-sm">
|
<dl className="mt-5 ml-auto max-w-sm space-y-3 text-sm">
|
||||||
<div className="flex justify-between gap-4">
|
<div className="flex justify-between gap-4">
|
||||||
<dt>Subtotal sem IVA</dt>
|
<dt>Subtotal sem IVA</dt>
|
||||||
|
|||||||
@@ -5,6 +5,9 @@ import {
|
|||||||
} from '@/components/procurement-payment-insights';
|
} from '@/components/procurement-payment-insights';
|
||||||
import { Download } from 'lucide-react';
|
import { Download } from 'lucide-react';
|
||||||
import {
|
import {
|
||||||
|
FormErrors,
|
||||||
|
ActionBar,
|
||||||
|
TableViewport,
|
||||||
PageTitle,
|
PageTitle,
|
||||||
Panel,
|
Panel,
|
||||||
Status,
|
Status,
|
||||||
@@ -232,7 +235,7 @@ export default function ProcurementReports({
|
|||||||
</option>
|
</option>
|
||||||
</select>
|
</select>
|
||||||
</label>
|
</label>
|
||||||
<div className="flex items-end gap-3">
|
<ActionBar>
|
||||||
<Button type="submit" disabled={form.processing}>
|
<Button type="submit" disabled={form.processing}>
|
||||||
Aplicar filtros
|
Aplicar filtros
|
||||||
</Button>
|
</Button>
|
||||||
@@ -242,16 +245,8 @@ export default function ProcurementReports({
|
|||||||
>
|
>
|
||||||
Limpar
|
Limpar
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</ActionBar>
|
||||||
{Object.entries(form.errors).map(([key, message]) => (
|
<FormErrors errors={form.errors} />
|
||||||
<p
|
|
||||||
key={key}
|
|
||||||
role="alert"
|
|
||||||
className="text-sm text-red-700"
|
|
||||||
>
|
|
||||||
{message}
|
|
||||||
</p>
|
|
||||||
))}
|
|
||||||
</form>
|
</form>
|
||||||
</Panel>
|
</Panel>
|
||||||
<section
|
<section
|
||||||
@@ -279,7 +274,7 @@ export default function ProcurementReports({
|
|||||||
não apenas esta página. Consulta gerada em{' '}
|
não apenas esta página. Consulta gerada em{' '}
|
||||||
{new Date(generatedAt).toLocaleString('pt-MZ')}.
|
{new Date(generatedAt).toLocaleString('pt-MZ')}.
|
||||||
</p>
|
</p>
|
||||||
<div className="overflow-x-auto">
|
<TableViewport>
|
||||||
<table className="w-full min-w-240 text-left text-sm">
|
<table className="w-full min-w-240 text-left text-sm">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
@@ -352,7 +347,7 @@ export default function ProcurementReports({
|
|||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</TableViewport>
|
||||||
{records.data.length === 0 && (
|
{records.data.length === 0 && (
|
||||||
<p className="py-6 text-sm">
|
<p className="py-6 text-sm">
|
||||||
Nenhuma requisição encontrada nos filtros e no
|
Nenhuma requisição encontrada nos filtros e no
|
||||||
|
|||||||
@@ -2,7 +2,15 @@ import { TerritorialFilter } from '@/components/territorial-filter';
|
|||||||
import type { GeographyDescription } from '@/components/administrative-location';
|
import type { GeographyDescription } from '@/components/administrative-location';
|
||||||
import { Head, Link, useForm } from '@inertiajs/react';
|
import { Head, Link, useForm } from '@inertiajs/react';
|
||||||
import { Printer } from 'lucide-react';
|
import { Printer } from 'lucide-react';
|
||||||
import { PageTitle, Panel, controlClass } from '@/components/procurement';
|
import {
|
||||||
|
PrintableDetails,
|
||||||
|
FormErrors,
|
||||||
|
ActionBar,
|
||||||
|
TableViewport,
|
||||||
|
PageTitle,
|
||||||
|
Panel,
|
||||||
|
controlClass,
|
||||||
|
} from '@/components/procurement';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
|
|
||||||
type Filters = {
|
type Filters = {
|
||||||
@@ -96,7 +104,7 @@ export default function SupplierImprovementReport({
|
|||||||
title="Medidas de melhoria"
|
title="Medidas de melhoria"
|
||||||
description="Acompanhar responsáveis, prazos, execução e encerramentos em todas as avaliações autorizadas."
|
description="Acompanhar responsáveis, prazos, execução e encerramentos em todas as avaliações autorizadas."
|
||||||
action={
|
action={
|
||||||
<div className="flex flex-wrap gap-3 print:hidden">
|
<ActionBar>
|
||||||
<Button asChild variant="outline">
|
<Button asChild variant="outline">
|
||||||
<Link href="/fornecedores/avaliacoes">
|
<Link href="/fornecedores/avaliacoes">
|
||||||
Avaliações
|
Avaliações
|
||||||
@@ -114,7 +122,7 @@ export default function SupplierImprovementReport({
|
|||||||
<Printer className="size-4" />
|
<Printer className="size-4" />
|
||||||
Imprimir esta página
|
Imprimir esta página
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</ActionBar>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
{geographyEnabled && (
|
{geographyEnabled && (
|
||||||
@@ -271,24 +279,13 @@ export default function SupplierImprovementReport({
|
|||||||
/>
|
/>
|
||||||
Só prazos ultrapassados
|
Só prazos ultrapassados
|
||||||
</label>
|
</label>
|
||||||
<div className="flex items-end gap-3">
|
<ActionBar>
|
||||||
<Button disabled={form.processing}>Aplicar</Button>
|
<Button disabled={form.processing}>Aplicar</Button>
|
||||||
<Button variant="outline" asChild>
|
<Button variant="outline" asChild>
|
||||||
<Link href={base}>Limpar</Link>
|
<Link href={base}>Limpar</Link>
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</ActionBar>
|
||||||
{Object.keys(form.errors).length > 0 && (
|
<FormErrors errors={form.errors} />
|
||||||
<div
|
|
||||||
role="alert"
|
|
||||||
className="text-sm text-red-700 sm:col-span-2 lg:col-span-4"
|
|
||||||
>
|
|
||||||
{Object.entries(form.errors).map(
|
|
||||||
([key, error]) => (
|
|
||||||
<p key={key}>{error}</p>
|
|
||||||
),
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</form>
|
</form>
|
||||||
<p className="mt-3 text-sm text-muted-foreground">
|
<p className="mt-3 text-sm text-muted-foreground">
|
||||||
Data de referência: {today} · Consulta:{' '}
|
Data de referência: {today} · Consulta:{' '}
|
||||||
@@ -351,7 +348,7 @@ export default function SupplierImprovementReport({
|
|||||||
Não existem medidas autorizadas para estes filtros.
|
Não existem medidas autorizadas para estes filtros.
|
||||||
</p>
|
</p>
|
||||||
) : (
|
) : (
|
||||||
<div className="overflow-x-auto">
|
<TableViewport>
|
||||||
<table className="w-full text-left text-sm">
|
<table className="w-full text-left text-sm">
|
||||||
<thead>
|
<thead>
|
||||||
<tr className="border-b">
|
<tr className="border-b">
|
||||||
@@ -399,10 +396,7 @@ export default function SupplierImprovementReport({
|
|||||||
{states[row.status]} ·
|
{states[row.status]} ·
|
||||||
Versão {row.version}
|
Versão {row.version}
|
||||||
</p>
|
</p>
|
||||||
<details>
|
<PrintableDetails summary="Resultado e evidência">
|
||||||
<summary className="cursor-pointer underline">
|
|
||||||
Resultado e evidência
|
|
||||||
</summary>
|
|
||||||
<div className="mt-2 space-y-2 whitespace-pre-wrap">
|
<div className="mt-2 space-y-2 whitespace-pre-wrap">
|
||||||
<p>{row.description}</p>
|
<p>{row.description}</p>
|
||||||
<p>
|
<p>
|
||||||
@@ -423,7 +417,7 @@ export default function SupplierImprovementReport({
|
|||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</details>
|
</PrintableDetails>
|
||||||
</td>
|
</td>
|
||||||
<td className="space-y-2 p-3 print:hidden">
|
<td className="space-y-2 p-3 print:hidden">
|
||||||
<Link
|
<Link
|
||||||
@@ -443,7 +437,7 @@ export default function SupplierImprovementReport({
|
|||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</TableViewport>
|
||||||
)}
|
)}
|
||||||
<nav
|
<nav
|
||||||
aria-label="Paginação das medidas"
|
aria-label="Paginação das medidas"
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { Head, Link, useForm, usePage } from '@inertiajs/react';
|
|||||||
import { useEffect, useRef } from 'react';
|
import { useEffect, useRef } from 'react';
|
||||||
import { hasPreparationChanges } from '@/lib/requisition-history';
|
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||||
import {
|
import {
|
||||||
|
ActionBar,
|
||||||
FormErrors,
|
FormErrors,
|
||||||
PageTitle,
|
PageTitle,
|
||||||
Panel,
|
Panel,
|
||||||
@@ -245,7 +246,7 @@ export default function Distributions({
|
|||||||
para separar os centavos. Nenhuma diferença será
|
para separar os centavos. Nenhuma diferença será
|
||||||
compensada automaticamente.
|
compensada automaticamente.
|
||||||
</p>
|
</p>
|
||||||
<div className="flex flex-wrap gap-3">
|
<ActionBar>
|
||||||
<Button disabled={form.processing || rows.length === 0}>
|
<Button disabled={form.processing || rows.length === 0}>
|
||||||
Guardar distribuição
|
Guardar distribuição
|
||||||
</Button>
|
</Button>
|
||||||
@@ -254,7 +255,7 @@ export default function Distributions({
|
|||||||
Voltar ao pedido
|
Voltar ao pedido
|
||||||
</Link>
|
</Link>
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</ActionBar>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -0,0 +1,253 @@
|
|||||||
|
import { Head, Link, router, useForm } from '@inertiajs/react';
|
||||||
|
import { useEffect, useRef } from 'react';
|
||||||
|
import {
|
||||||
|
FormErrors,
|
||||||
|
PageTitle,
|
||||||
|
Panel,
|
||||||
|
controlClass,
|
||||||
|
} from '@/components/procurement';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
|
||||||
|
type Deadline = {
|
||||||
|
state: string;
|
||||||
|
step_id: number | null;
|
||||||
|
expires_at: string | null;
|
||||||
|
started_at?: string;
|
||||||
|
reminder_at?: string | null;
|
||||||
|
escalation_at?: string | null;
|
||||||
|
basis_hash: string | null;
|
||||||
|
};
|
||||||
|
type Props = {
|
||||||
|
requisition: {
|
||||||
|
id: number;
|
||||||
|
number: string;
|
||||||
|
status: string;
|
||||||
|
process_version: number;
|
||||||
|
approval_cycle: number;
|
||||||
|
};
|
||||||
|
deadline: Deadline;
|
||||||
|
canExpire: boolean;
|
||||||
|
canEdit: boolean;
|
||||||
|
actorId: number;
|
||||||
|
tenantId: number;
|
||||||
|
history: {
|
||||||
|
data: {
|
||||||
|
id: number;
|
||||||
|
data: { cycle: number; next_cycle: number };
|
||||||
|
reason: string;
|
||||||
|
request: { number: string };
|
||||||
|
steps: {
|
||||||
|
id: number;
|
||||||
|
position: number;
|
||||||
|
role: string;
|
||||||
|
decision: string;
|
||||||
|
}[];
|
||||||
|
}[];
|
||||||
|
prev_page_url: string | null;
|
||||||
|
next_page_url: string | null;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
const labels: Record<string, string> = {
|
||||||
|
inactive: 'Sem etapa pendente',
|
||||||
|
unconfigured: 'Sem prazo configurado',
|
||||||
|
unverified: 'Datas por conferir',
|
||||||
|
running: 'Em prazo',
|
||||||
|
expired: 'Prazo terminado',
|
||||||
|
};
|
||||||
|
const time = (value?: string | null) =>
|
||||||
|
value ? new Date(value).toLocaleString('pt-MZ') : 'Por indicar';
|
||||||
|
export default function Expiry(props: Props) {
|
||||||
|
const r = props.requisition;
|
||||||
|
const form = useForm(`expiry:${props.tenantId}:${props.actorId}:${r.id}`, {
|
||||||
|
operation_key: '',
|
||||||
|
process_version: r.process_version,
|
||||||
|
basis_hash: props.deadline.basis_hash || '',
|
||||||
|
comment: '',
|
||||||
|
});
|
||||||
|
const current =
|
||||||
|
form.data.process_version === r.process_version &&
|
||||||
|
form.data.basis_hash === (props.deadline.basis_hash || '');
|
||||||
|
const ref = useRef<HTMLFormElement>(null);
|
||||||
|
useEffect(() => {
|
||||||
|
const node = ref.current;
|
||||||
|
window.dispatchEvent(
|
||||||
|
new CustomEvent('sgc:context-dirty', {
|
||||||
|
detail: { form: node, dirty: form.isDirty },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
return () => {
|
||||||
|
window.dispatchEvent(
|
||||||
|
new CustomEvent('sgc:context-dirty', {
|
||||||
|
detail: { form: node, dirty: false },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
}, [form.isDirty]);
|
||||||
|
return (
|
||||||
|
<div className="mx-auto grid w-full max-w-6xl min-w-0 gap-6 p-5 lg:p-8">
|
||||||
|
<Head title="Prazos da aprovação" />
|
||||||
|
<PageTitle
|
||||||
|
eyebrow={r.number}
|
||||||
|
title="Prazos da aprovação"
|
||||||
|
description="A política preservada na submissão determina os prazos de cada etapa. A devolução mantém o pedido e o histórico para nova submissão pelo requisitante."
|
||||||
|
/>
|
||||||
|
<Link className="underline" href={`/requisicoes/${r.id}`}>
|
||||||
|
Voltar à requisição
|
||||||
|
</Link>
|
||||||
|
<Panel
|
||||||
|
title={`${labels[props.deadline.state] || 'Por conferir'} · ciclo ${r.approval_cycle}`}
|
||||||
|
>
|
||||||
|
<dl className="grid gap-3 text-sm">
|
||||||
|
<div>
|
||||||
|
<dt>Início da etapa</dt>
|
||||||
|
<dd>{time(props.deadline.started_at)}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt>Expiração</dt>
|
||||||
|
<dd>{time(props.deadline.expires_at)}</dd>
|
||||||
|
</div>
|
||||||
|
{props.deadline.reminder_at && (
|
||||||
|
<div>
|
||||||
|
<dt>Lembrete previsto</dt>
|
||||||
|
<dd>{time(props.deadline.reminder_at)}</dd>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{props.deadline.escalation_at && (
|
||||||
|
<div>
|
||||||
|
<dt>Escalamento previsto</dt>
|
||||||
|
<dd>{time(props.deadline.escalation_at)}</dd>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</dl>
|
||||||
|
<p className="mt-4 text-sm text-muted-foreground">
|
||||||
|
Os prazos usam minutos corridos desde a activação da etapa.
|
||||||
|
Uma alteração posterior da política não reescreve o ciclo já
|
||||||
|
submetido.
|
||||||
|
</p>
|
||||||
|
<Button
|
||||||
|
className="mt-4"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => router.reload()}
|
||||||
|
>
|
||||||
|
Actualizar conferência do prazo
|
||||||
|
</Button>
|
||||||
|
</Panel>
|
||||||
|
{props.canExpire && (
|
||||||
|
<Panel
|
||||||
|
title="Devolver o pedido vencido"
|
||||||
|
description="A reserva remanescente deste ciclo é libertada pelo percurso orçamental. As aprovações anteriores ficam no histórico e a nova submissão exige novas etapas."
|
||||||
|
>
|
||||||
|
<form
|
||||||
|
ref={ref}
|
||||||
|
className="space-y-4"
|
||||||
|
onSubmit={(event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
const operation =
|
||||||
|
form.data.operation_key || crypto.randomUUID();
|
||||||
|
form.setData('operation_key', operation);
|
||||||
|
form.transform((data) => ({
|
||||||
|
...data,
|
||||||
|
operation_key: operation,
|
||||||
|
}));
|
||||||
|
form.post(`/requisicoes/${r.id}/expiracao`, {
|
||||||
|
preserveScroll: true,
|
||||||
|
onSuccess: () => {
|
||||||
|
form.reset();
|
||||||
|
form.clearErrors();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<FormErrors errors={form.errors} />
|
||||||
|
{!current && (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<p>
|
||||||
|
A etapa mudou. Reveja a conferência actual
|
||||||
|
antes de devolver.
|
||||||
|
</p>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() =>
|
||||||
|
form.setData((data) => ({
|
||||||
|
...data,
|
||||||
|
process_version: r.process_version,
|
||||||
|
basis_hash:
|
||||||
|
props.deadline.basis_hash || '',
|
||||||
|
operation_key: '',
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
>
|
||||||
|
Preparar devolução da etapa actual
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<label className="grid gap-2">
|
||||||
|
Comentário adicional, quando necessário
|
||||||
|
<textarea
|
||||||
|
className={controlClass}
|
||||||
|
maxLength={2000}
|
||||||
|
value={form.data.comment}
|
||||||
|
onChange={(event) =>
|
||||||
|
form.setData('comment', event.target.value)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<Button disabled={form.processing || !current}>
|
||||||
|
Devolver ao requisitante
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
</Panel>
|
||||||
|
)}
|
||||||
|
{props.canEdit && (
|
||||||
|
<Panel title="Pedido devolvido para preparação">
|
||||||
|
<p>
|
||||||
|
Reveja os dados do rascunho e submeta novamente quando
|
||||||
|
estiver preparado. O ciclo anterior permanece no
|
||||||
|
histórico.
|
||||||
|
</p>
|
||||||
|
<Button className="mt-3" asChild>
|
||||||
|
<Link href={`/requisicoes/${r.id}/editar`}>
|
||||||
|
Rever rascunho
|
||||||
|
</Link>
|
||||||
|
</Button>
|
||||||
|
</Panel>
|
||||||
|
)}
|
||||||
|
<Panel title="Ciclos anteriores">
|
||||||
|
{props.history.data.length === 0 && (
|
||||||
|
<p>Ainda não há devoluções por expiração registadas.</p>
|
||||||
|
)}
|
||||||
|
{props.history.data.map((row) => (
|
||||||
|
<article
|
||||||
|
key={row.id}
|
||||||
|
className="space-y-2 border-b py-4 break-words"
|
||||||
|
>
|
||||||
|
<h3 className="font-semibold">
|
||||||
|
Ciclo {row.data.cycle} · devolvido para o ciclo{' '}
|
||||||
|
{row.data.next_cycle}
|
||||||
|
</h3>
|
||||||
|
<p>{row.reason}</p>
|
||||||
|
<ul>
|
||||||
|
{row.steps.map((step) => (
|
||||||
|
<li key={step.id}>
|
||||||
|
Etapa {step.position}:{' '}
|
||||||
|
{step.decision === 'approved'
|
||||||
|
? 'Aprovação preservada'
|
||||||
|
: 'Etapa pendente no momento da devolução'}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</article>
|
||||||
|
))}
|
||||||
|
<nav className="mt-3 flex gap-4" aria-label="Ciclos anteriores">
|
||||||
|
{props.history.prev_page_url && (
|
||||||
|
<Link href={props.history.prev_page_url}>Anterior</Link>
|
||||||
|
)}
|
||||||
|
{props.history.next_page_url && (
|
||||||
|
<Link href={props.history.next_page_url}>Seguinte</Link>
|
||||||
|
)}
|
||||||
|
</nav>
|
||||||
|
</Panel>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ import { hasPreparationChanges } from '@/lib/requisition-history';
|
|||||||
import { Plus, Save, Trash2 } from 'lucide-react';
|
import { Plus, Save, Trash2 } from 'lucide-react';
|
||||||
import { useEffect, useRef } from 'react';
|
import { useEffect, useRef } from 'react';
|
||||||
import {
|
import {
|
||||||
|
ActionBar,
|
||||||
FormErrors,
|
FormErrors,
|
||||||
PageTitle,
|
PageTitle,
|
||||||
Panel,
|
Panel,
|
||||||
@@ -718,7 +719,7 @@ export default function RequisitionForm({
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="mt-3 flex justify-end">
|
<ActionBar align="end" className="mt-3">
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
@@ -738,7 +739,7 @@ export default function RequisitionForm({
|
|||||||
<Trash2 className="size-4" />
|
<Trash2 className="size-4" />
|
||||||
Remover linha
|
Remover linha
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</ActionBar>
|
||||||
</fieldset>
|
</fieldset>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
@@ -779,7 +780,7 @@ export default function RequisitionForm({
|
|||||||
O servidor confirma os cálculos ao guardar.
|
O servidor confirma os cálculos ao guardar.
|
||||||
</p>
|
</p>
|
||||||
</Panel>
|
</Panel>
|
||||||
<div className="flex justify-end gap-3">
|
<ActionBar align="end">
|
||||||
<Button variant="outline" asChild>
|
<Button variant="outline" asChild>
|
||||||
<Link
|
<Link
|
||||||
href={
|
href={
|
||||||
@@ -801,7 +802,7 @@ export default function RequisitionForm({
|
|||||||
<Save className="size-4" />
|
<Save className="size-4" />
|
||||||
Guardar rascunho
|
Guardar rascunho
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</ActionBar>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ import { Check, Circle, Pencil, Send } from 'lucide-react';
|
|||||||
import { ComparisonPolicySummary } from '@/components/comparison-policy-summary';
|
import { ComparisonPolicySummary } from '@/components/comparison-policy-summary';
|
||||||
import type { ComparisonPolicy } from '@/components/comparison-policy-summary';
|
import type { ComparisonPolicy } from '@/components/comparison-policy-summary';
|
||||||
import {
|
import {
|
||||||
|
ActionBar,
|
||||||
|
TableViewport,
|
||||||
FormErrors,
|
FormErrors,
|
||||||
PageTitle,
|
PageTitle,
|
||||||
Panel,
|
Panel,
|
||||||
@@ -35,6 +37,10 @@ const actions: Record<string, string> = {
|
|||||||
'budget.distribution_cancel': 'Compromisso distribuído cancelado',
|
'budget.distribution_cancel': 'Compromisso distribuído cancelado',
|
||||||
'budget.distribution_amended': 'Compromisso reafectado por Finanças',
|
'budget.distribution_amended': 'Compromisso reafectado por Finanças',
|
||||||
'requisition.submitted': 'Pedido submetido',
|
'requisition.submitted': 'Pedido submetido',
|
||||||
|
'requisition.expired_returned': 'Pedido devolvido por expiração',
|
||||||
|
'budget.cycle_opened': 'Novo ciclo orçamental preparado',
|
||||||
|
'budget.cycle_closed':
|
||||||
|
'Ciclo orçamental encerrado após libertação da reserva',
|
||||||
'approval.approved': 'Etapa aprovada',
|
'approval.approved': 'Etapa aprovada',
|
||||||
'approval.rejected': 'Pedido rejeitado',
|
'approval.rejected': 'Pedido rejeitado',
|
||||||
};
|
};
|
||||||
@@ -56,9 +62,11 @@ export default function Show({
|
|||||||
importTariffsReady = false,
|
importTariffsReady = false,
|
||||||
importEstimatesReady = false,
|
importEstimatesReady = false,
|
||||||
capitalRegisterReady = false,
|
capitalRegisterReady = false,
|
||||||
|
expiryReady = false,
|
||||||
}: {
|
}: {
|
||||||
importEstimatesReady?: boolean;
|
importEstimatesReady?: boolean;
|
||||||
capitalRegisterReady?: boolean;
|
capitalRegisterReady?: boolean;
|
||||||
|
expiryReady?: boolean;
|
||||||
importTariffsReady?: boolean;
|
importTariffsReady?: boolean;
|
||||||
canPrepareDistributions?: boolean;
|
canPrepareDistributions?: boolean;
|
||||||
requisition: Requisition;
|
requisition: Requisition;
|
||||||
@@ -176,6 +184,13 @@ export default function Show({
|
|||||||
</Link>
|
</Link>
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
|
{expiryReady && (
|
||||||
|
<Button asChild variant="outline">
|
||||||
|
<Link href={`/requisicoes/${r.id}/prazos`}>
|
||||||
|
Prazos e ciclos da aprovação
|
||||||
|
</Link>
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
{importEstimatesReady && (
|
{importEstimatesReady && (
|
||||||
<Button asChild variant="outline">
|
<Button asChild variant="outline">
|
||||||
<Link
|
<Link
|
||||||
@@ -384,7 +399,7 @@ export default function Show({
|
|||||||
Confira o pedido antes de o enviar para
|
Confira o pedido antes de o enviar para
|
||||||
aprovação.
|
aprovação.
|
||||||
</p>
|
</p>
|
||||||
<div className="flex gap-2">
|
<ActionBar>
|
||||||
<Button asChild variant="outline">
|
<Button asChild variant="outline">
|
||||||
<Link href={`/requisicoes/${r.id}/editar`}>
|
<Link href={`/requisicoes/${r.id}/editar`}>
|
||||||
<Pencil className="size-4" />
|
<Pencil className="size-4" />
|
||||||
@@ -402,7 +417,7 @@ export default function Show({
|
|||||||
<Send className="size-4" />
|
<Send className="size-4" />
|
||||||
Submeter para aprovação
|
Submeter para aprovação
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</ActionBar>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
<div className="grid gap-6 lg:grid-cols-3">
|
<div className="grid gap-6 lg:grid-cols-3">
|
||||||
@@ -460,7 +475,7 @@ export default function Show({
|
|||||||
title="Artigos e valores"
|
title="Artigos e valores"
|
||||||
description="Moeda: MZN · Montantes estimados"
|
description="Moeda: MZN · Montantes estimados"
|
||||||
>
|
>
|
||||||
<div className="overflow-x-auto">
|
<TableViewport>
|
||||||
<table className="w-full text-left text-sm">
|
<table className="w-full text-left text-sm">
|
||||||
<thead className="border-b text-xs text-muted-foreground">
|
<thead className="border-b text-xs text-muted-foreground">
|
||||||
<tr>
|
<tr>
|
||||||
@@ -544,7 +559,7 @@ export default function Show({
|
|||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</TableViewport>
|
||||||
<dl className="mt-5 ml-auto max-w-xs space-y-3 text-sm">
|
<dl className="mt-5 ml-auto max-w-xs space-y-3 text-sm">
|
||||||
<div className="flex justify-between">
|
<div className="flex justify-between">
|
||||||
<dt>Subtotal sem IVA</dt>
|
<dt>Subtotal sem IVA</dt>
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { Head, Link, useForm } from '@inertiajs/react';
|
import { Head, Link, useForm } from '@inertiajs/react';
|
||||||
import {
|
import {
|
||||||
|
TableViewport,
|
||||||
PageTitle,
|
PageTitle,
|
||||||
Panel,
|
Panel,
|
||||||
FormErrors,
|
FormErrors,
|
||||||
@@ -111,7 +112,7 @@ export default function Availability(props: Props) {
|
|||||||
<p>Seleccione o armazém para consultar.</p>
|
<p>Seleccione o armazém para consultar.</p>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
<div className="overflow-x-auto">
|
<TableViewport>
|
||||||
<table className="w-full text-left text-sm">
|
<table className="w-full text-left text-sm">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
@@ -201,7 +202,7 @@ export default function Availability(props: Props) {
|
|||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</TableViewport>
|
||||||
{props.rows.data.length === 0 && (
|
{props.rows.data.length === 0 && (
|
||||||
<p>Sem artigos nos filtros seleccionados.</p>
|
<p>Sem artigos nos filtros seleccionados.</p>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { TerritorialFilter } from '@/components/territorial-filter';
|
|||||||
import { Head, Link, useForm } from '@inertiajs/react';
|
import { Head, Link, useForm } from '@inertiajs/react';
|
||||||
import { InventoryNotice, InventoryPagination } from '@/components/inventory';
|
import { InventoryNotice, InventoryPagination } from '@/components/inventory';
|
||||||
import {
|
import {
|
||||||
|
TableViewport,
|
||||||
FormErrors,
|
FormErrors,
|
||||||
PageTitle,
|
PageTitle,
|
||||||
Panel,
|
Panel,
|
||||||
@@ -178,7 +179,7 @@ export default function Stock({
|
|||||||
</select>
|
</select>
|
||||||
<Button variant="outline">Filtrar</Button>
|
<Button variant="outline">Filtrar</Button>
|
||||||
</form>
|
</form>
|
||||||
<div className="overflow-x-auto">
|
<TableViewport>
|
||||||
<table className="w-full text-left text-sm">
|
<table className="w-full text-left text-sm">
|
||||||
<thead className="border-b text-muted-foreground">
|
<thead className="border-b text-muted-foreground">
|
||||||
<tr>
|
<tr>
|
||||||
@@ -229,7 +230,7 @@ export default function Stock({
|
|||||||
})}
|
})}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</TableViewport>
|
||||||
{balances.length === 0 && (
|
{balances.length === 0 && (
|
||||||
<p className="py-6 text-sm text-muted-foreground">
|
<p className="py-6 text-sm text-muted-foreground">
|
||||||
Não há entradas confirmadas para estes filtros.
|
Não há entradas confirmadas para estes filtros.
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { Head, Link, useForm } from '@inertiajs/react';
|
import { Head, Link, useForm } from '@inertiajs/react';
|
||||||
import {
|
import {
|
||||||
|
TableViewport,
|
||||||
PageTitle,
|
PageTitle,
|
||||||
Panel,
|
Panel,
|
||||||
FormErrors,
|
FormErrors,
|
||||||
@@ -490,7 +491,7 @@ export default function WarehouseRequest(props: Props) {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<Panel title="Artigos e atendimento">
|
<Panel title="Artigos e atendimento">
|
||||||
<div className="overflow-x-auto">
|
<TableViewport>
|
||||||
<table className="w-full text-left text-sm">
|
<table className="w-full text-left text-sm">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
@@ -545,7 +546,7 @@ export default function WarehouseRequest(props: Props) {
|
|||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</TableViewport>
|
||||||
<p className="mt-4 text-sm">
|
<p className="mt-4 text-sm">
|
||||||
{p.reservation_ready
|
{p.reservation_ready
|
||||||
? 'A autorização reserva o material utilizável disponível. Só a entrega confirmada reduz o stock. Retenções de qualidade e validade são revalidadas na entrega.'
|
? 'A autorização reserva o material utilizável disponível. Só a entrega confirmada reduz o stock. Retenções de qualidade e validade são revalidadas na entrega.'
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { Head, Link, useForm } from '@inertiajs/react';
|
import { Head, Link, useForm } from '@inertiajs/react';
|
||||||
import {
|
import {
|
||||||
|
ActionBar,
|
||||||
PageTitle,
|
PageTitle,
|
||||||
Panel,
|
Panel,
|
||||||
FormErrors,
|
FormErrors,
|
||||||
@@ -535,7 +536,7 @@ export default function Requests(props: Props) {
|
|||||||
)}
|
)}
|
||||||
</fieldset>
|
</fieldset>
|
||||||
))}
|
))}
|
||||||
<div className="flex gap-3">
|
<ActionBar>
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
variant="outline"
|
variant="outline"
|
||||||
@@ -559,7 +560,7 @@ export default function Requests(props: Props) {
|
|||||||
>
|
>
|
||||||
Guardar rascunho
|
Guardar rascunho
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</ActionBar>
|
||||||
{props.costCenters.length === 0 && (
|
{props.costCenters.length === 0 && (
|
||||||
<p>
|
<p>
|
||||||
É necessário um centro de custo
|
É necessário um centro de custo
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import type {
|
|||||||
} from '@/components/administrative-location';
|
} from '@/components/administrative-location';
|
||||||
import { Head, Link, useForm } from '@inertiajs/react';
|
import { Head, Link, useForm } from '@inertiajs/react';
|
||||||
import {
|
import {
|
||||||
|
ActionBar,
|
||||||
FormErrors,
|
FormErrors,
|
||||||
PageTitle,
|
PageTitle,
|
||||||
Panel,
|
Panel,
|
||||||
@@ -145,7 +146,7 @@ export default function EditSupplier({
|
|||||||
/>
|
/>
|
||||||
Fornecedor consta da lista de impedidos
|
Fornecedor consta da lista de impedidos
|
||||||
</label>
|
</label>
|
||||||
<div className="flex justify-end gap-3">
|
<ActionBar align="end">
|
||||||
<Button asChild variant="outline">
|
<Button asChild variant="outline">
|
||||||
<Link href={`/fornecedores/${supplier.id}`}>
|
<Link href={`/fornecedores/${supplier.id}`}>
|
||||||
Cancelar
|
Cancelar
|
||||||
@@ -154,7 +155,7 @@ export default function EditSupplier({
|
|||||||
<Button disabled={form.processing}>
|
<Button disabled={form.processing}>
|
||||||
Guardar alterações
|
Guardar alterações
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</ActionBar>
|
||||||
</form>
|
</form>
|
||||||
</Panel>
|
</Panel>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -4,7 +4,12 @@ import SupplierImprovements from '@/components/supplier-improvements';
|
|||||||
import type { ImprovementData } from '@/components/supplier-improvements';
|
import type { ImprovementData } from '@/components/supplier-improvements';
|
||||||
import SupplierResponses from '@/components/supplier-responses';
|
import SupplierResponses from '@/components/supplier-responses';
|
||||||
import type { ResponseData } from '@/components/supplier-responses';
|
import type { ResponseData } from '@/components/supplier-responses';
|
||||||
import { PageTitle, Panel, controlClass } from '@/components/procurement';
|
import {
|
||||||
|
ActionBar,
|
||||||
|
PageTitle,
|
||||||
|
Panel,
|
||||||
|
controlClass,
|
||||||
|
} from '@/components/procurement';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import SupplierEvaluationFields, {
|
import SupplierEvaluationFields, {
|
||||||
evaluationStates,
|
evaluationStates,
|
||||||
@@ -204,7 +209,7 @@ export default function SupplierEvaluation({
|
|||||||
{error}
|
{error}
|
||||||
</p>
|
</p>
|
||||||
))}
|
))}
|
||||||
<div className="flex flex-wrap gap-3">
|
<ActionBar>
|
||||||
<Button
|
<Button
|
||||||
disabled={
|
disabled={
|
||||||
form.processing || command.processing
|
form.processing || command.processing
|
||||||
@@ -224,7 +229,7 @@ export default function SupplierEvaluation({
|
|||||||
>
|
>
|
||||||
Submeter para revisão
|
Submeter para revisão
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</ActionBar>
|
||||||
{dirty && (
|
{dirty && (
|
||||||
<p className="text-sm text-muted-foreground">
|
<p className="text-sm text-muted-foreground">
|
||||||
Guarde as alterações antes de submeter. A
|
Guarde as alterações antes de submeter. A
|
||||||
@@ -363,7 +368,7 @@ export default function SupplierEvaluation({
|
|||||||
{error}
|
{error}
|
||||||
</p>
|
</p>
|
||||||
))}
|
))}
|
||||||
<div className="flex flex-wrap gap-3">
|
<ActionBar>
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
disabled={command.processing || waiting > 0}
|
disabled={command.processing || waiting > 0}
|
||||||
@@ -379,7 +384,7 @@ export default function SupplierEvaluation({
|
|||||||
>
|
>
|
||||||
Devolver para correcção
|
Devolver para correcção
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</ActionBar>
|
||||||
{waiting > 0 && (
|
{waiting > 0 && (
|
||||||
<p className="text-sm text-amber-800">
|
<p className="text-sm text-amber-800">
|
||||||
Existem {waiting} critérios pendentes.
|
Existem {waiting} critérios pendentes.
|
||||||
|
|||||||
@@ -1,5 +1,10 @@
|
|||||||
import { Head, Link, useForm } from '@inertiajs/react';
|
import { Head, Link, useForm } from '@inertiajs/react';
|
||||||
import { PageTitle, Panel, controlClass } from '@/components/procurement';
|
import {
|
||||||
|
TableViewport,
|
||||||
|
PageTitle,
|
||||||
|
Panel,
|
||||||
|
controlClass,
|
||||||
|
} from '@/components/procurement';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import SupplierEvaluationFields, {
|
import SupplierEvaluationFields, {
|
||||||
emptyEvaluation,
|
emptyEvaluation,
|
||||||
@@ -156,7 +161,7 @@ export default function SupplierEvaluations({
|
|||||||
{records.total} avaliações/revisões no âmbito
|
{records.total} avaliações/revisões no âmbito
|
||||||
autorizado.
|
autorizado.
|
||||||
</p>
|
</p>
|
||||||
<div className="overflow-x-auto">
|
<TableViewport>
|
||||||
<table className="w-full min-w-180 text-left text-sm">
|
<table className="w-full min-w-180 text-left text-sm">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
@@ -214,7 +219,7 @@ export default function SupplierEvaluations({
|
|||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</TableViewport>
|
||||||
{records.data.length === 0 && (
|
{records.data.length === 0 && (
|
||||||
<p className="py-4 text-sm">
|
<p className="py-4 text-sm">
|
||||||
Sem avaliações nos filtros e no âmbito
|
Sem avaliações nos filtros e no âmbito
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { Head, Link, router } from '@inertiajs/react';
|
import { Head, Link, router } from '@inertiajs/react';
|
||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import {
|
import {
|
||||||
|
ActionBar,
|
||||||
FormErrors,
|
FormErrors,
|
||||||
PageTitle,
|
PageTitle,
|
||||||
Panel,
|
Panel,
|
||||||
@@ -160,7 +161,7 @@ export default function AgreementFollowup({
|
|||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
<div className="flex items-center gap-4">
|
<ActionBar>
|
||||||
<Button type="submit">Aplicar filtros</Button>
|
<Button type="submit">Aplicar filtros</Button>
|
||||||
<Link
|
<Link
|
||||||
href={
|
href={
|
||||||
@@ -172,7 +173,7 @@ export default function AgreementFollowup({
|
|||||||
>
|
>
|
||||||
Limpar filtros
|
Limpar filtros
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</ActionBar>
|
||||||
</form>
|
</form>
|
||||||
<div className="mt-4">
|
<div className="mt-4">
|
||||||
<FormErrors errors={errors} />
|
<FormErrors errors={errors} />
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { Head, Link, useForm, useRemember } from '@inertiajs/react';
|
|||||||
import { useEffect, useRef, type RefObject } from 'react';
|
import { useEffect, useRef, type RefObject } from 'react';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import {
|
import {
|
||||||
|
ActionBar,
|
||||||
FormErrors,
|
FormErrors,
|
||||||
PageTitle,
|
PageTitle,
|
||||||
Panel,
|
Panel,
|
||||||
@@ -998,7 +999,7 @@ function CostPreparation(props: Props & { url: string; historyKey: string }) {
|
|||||||
onChange={(e) => form.setData('reason', e.target.value)}
|
onChange={(e) => form.setData('reason', e.target.value)}
|
||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
<div className="flex flex-wrap gap-3">
|
<ActionBar>
|
||||||
<Button disabled={form.processing}>Conferir valores</Button>
|
<Button disabled={form.processing}>Conferir valores</Button>
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -1027,7 +1028,7 @@ function CostPreparation(props: Props & { url: string; historyKey: string }) {
|
|||||||
>
|
>
|
||||||
Guardar para revisão
|
Guardar para revisão
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</ActionBar>
|
||||||
</form>
|
</form>
|
||||||
</Panel>
|
</Panel>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -145,7 +145,9 @@ export default function Notices({
|
|||||||
Resultado registado:{' '}
|
Resultado registado:{' '}
|
||||||
{notice.outcome === 'approved'
|
{notice.outcome === 'approved'
|
||||||
? 'requisição aprovada'
|
? 'requisição aprovada'
|
||||||
: 'requisição rejeitada'}
|
: notice.outcome === 'expired'
|
||||||
|
? 'pedido devolvido por expiração'
|
||||||
|
: 'requisição rejeitada'}
|
||||||
. Estado actual:{' '}
|
. Estado actual:{' '}
|
||||||
{statusLabels[notice.current_status] ??
|
{statusLabels[notice.current_status] ??
|
||||||
notice.current_status}
|
notice.current_status}
|
||||||
|
|||||||
@@ -49,6 +49,7 @@ use App\Http\Controllers\ReceiptDocumentController;
|
|||||||
use App\Http\Controllers\RequisitionAuditController;
|
use App\Http\Controllers\RequisitionAuditController;
|
||||||
use App\Http\Controllers\RequisitionCatalogueController;
|
use App\Http\Controllers\RequisitionCatalogueController;
|
||||||
use App\Http\Controllers\RequisitionController;
|
use App\Http\Controllers\RequisitionController;
|
||||||
|
use App\Http\Controllers\RequisitionExpiryController;
|
||||||
use App\Http\Controllers\SavedProcurementSearchController;
|
use App\Http\Controllers\SavedProcurementSearchController;
|
||||||
use App\Http\Controllers\SgfInvoiceDispatchController;
|
use App\Http\Controllers\SgfInvoiceDispatchController;
|
||||||
use App\Http\Controllers\StockController;
|
use App\Http\Controllers\StockController;
|
||||||
@@ -303,6 +304,8 @@ Route::middleware(['auth', 'verified', EnsureOrganizationAccess::class])->group(
|
|||||||
Route::post('orcamentos/{budget}/aprovar', [BudgetController::class, 'approve'])->name('budgets.approve');
|
Route::post('orcamentos/{budget}/aprovar', [BudgetController::class, 'approve'])->name('budgets.approve');
|
||||||
Route::get('equipamentos', [EquipmentController::class, 'index'])->name('equipment.index');
|
Route::get('equipamentos', [EquipmentController::class, 'index'])->name('equipment.index');
|
||||||
Route::get('projectos-imobilizado', [CapitalRegisterController::class, 'index'])->name('capital-register.index');
|
Route::get('projectos-imobilizado', [CapitalRegisterController::class, 'index'])->name('capital-register.index');
|
||||||
|
Route::get('administracao/prazos-aprovacao', [RequisitionExpiryController::class, 'settings'])->name('approval-timeouts.index');
|
||||||
|
Route::post('administracao/prazos-aprovacao', [RequisitionExpiryController::class, 'saveSettings'])->name('approval-timeouts.store');
|
||||||
Route::post('projectos-imobilizado', [CapitalRegisterController::class, 'store'])->name('capital-register.store');
|
Route::post('projectos-imobilizado', [CapitalRegisterController::class, 'store'])->name('capital-register.store');
|
||||||
Route::get('ordens/cancelamentos', [OrderCancellationController::class, 'index']);
|
Route::get('ordens/cancelamentos', [OrderCancellationController::class, 'index']);
|
||||||
Route::post('ordens/{order}/cancelamento', [OrderCancellationController::class, 'request'])->whereNumber('order');
|
Route::post('ordens/{order}/cancelamento', [OrderCancellationController::class, 'request'])->whereNumber('order');
|
||||||
@@ -369,6 +372,8 @@ Route::middleware(['auth', 'verified', EnsureOrganizationAccess::class])->group(
|
|||||||
Route::post('requisicoes/{requisition}/submeter', [RequisitionController::class, 'submit'])->name('requisitions.submit');
|
Route::post('requisicoes/{requisition}/submeter', [RequisitionController::class, 'submit'])->name('requisitions.submit');
|
||||||
Route::get('requisicoes/{requisition}/distribuicoes', [RequisitionController::class, 'distributions'])->name('requisitions.distributions');
|
Route::get('requisicoes/{requisition}/distribuicoes', [RequisitionController::class, 'distributions'])->name('requisitions.distributions');
|
||||||
Route::get('requisicoes/{requisition}/projectos-imobilizado', [CapitalRegisterController::class, 'assignments'])->name('requisitions.capital');
|
Route::get('requisicoes/{requisition}/projectos-imobilizado', [CapitalRegisterController::class, 'assignments'])->name('requisitions.capital');
|
||||||
|
Route::get('requisicoes/{requisition}/prazos', [RequisitionExpiryController::class, 'show'])->name('requisitions.expiry');
|
||||||
|
Route::post('requisicoes/{requisition}/expiracao', [RequisitionExpiryController::class, 'expire'])->name('requisitions.expire');
|
||||||
Route::post('requisicoes/{requisition}/projectos-imobilizado', [CapitalRegisterController::class, 'assign'])->name('requisitions.capital.assign');
|
Route::post('requisicoes/{requisition}/projectos-imobilizado', [CapitalRegisterController::class, 'assign'])->name('requisitions.capital.assign');
|
||||||
Route::post('requisicoes/{requisition}/distribuicoes', [RequisitionController::class, 'prepareDistributions'])->name('requisitions.distributions.prepare');
|
Route::post('requisicoes/{requisition}/distribuicoes', [RequisitionController::class, 'prepareDistributions'])->name('requisitions.distributions.prepare');
|
||||||
Route::post('requisicoes/{requisition}/decidir', [RequisitionController::class, 'decide'])->name('requisitions.decide');
|
Route::post('requisicoes/{requisition}/decidir', [RequisitionController::class, 'decide'])->name('requisitions.decide');
|
||||||
|
|||||||
@@ -96,12 +96,23 @@ try {
|
|||||||
}
|
}
|
||||||
if (in_array('--capital-focused', $argv, true)) {
|
if (in_array('--capital-focused', $argv, true)) {
|
||||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/CapitalRegisterTest.php', 'tests/Feature/PurchaseAwardOrderTest.php',
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/CapitalRegisterTest.php', 'tests/Feature/PurchaseAwardOrderTest.php',
|
||||||
'--filter=capital|register|line destination|submitted requisitions|confirmed import classifications|partial native order retains']];
|
'--filter=capital|register|line destination|submitted requisitions|revoked requester|confirmed import classifications|partial native order retains|native consolidated order retains']];
|
||||||
|
}
|
||||||
|
if (in_array('--capital-approval-focused', $argv, true)) {
|
||||||
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/CapitalRegisterTest.php', 'tests/Feature/RequisitionCategoriesTest.php',
|
||||||
|
'tests/Feature/InternalRequisitionCandidateTest.php', 'tests/Feature/RequisitionApprovalLevelsTest.php', 'tests/Feature/IncompleteRequisitionDraftTest.php']];
|
||||||
|
}
|
||||||
|
if (in_array('--requisition-cycles-focused', $argv, true)) {
|
||||||
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionBudgetCyclesTest.php']];
|
||||||
}
|
}
|
||||||
if (in_array('--capital-concurrency', $argv, true)) {
|
if (in_array('--capital-concurrency', $argv, true)) {
|
||||||
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
|
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
|
||||||
[PHP_BINARY, 'tests/Concurrency/import-dossier-worker.php', $database, 'race-capital']];
|
[PHP_BINARY, 'tests/Concurrency/import-dossier-worker.php', $database, 'race-capital']];
|
||||||
}
|
}
|
||||||
|
if (in_array('--capital-recovery', $argv, true)) {
|
||||||
|
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
|
||||||
|
[PHP_BINARY, 'tests/Concurrency/budget-distribution-recovery-worker.php', $database, 'capital']];
|
||||||
|
}
|
||||||
if (in_array('--legal-concurrency', $argv, true)) {
|
if (in_array('--legal-concurrency', $argv, true)) {
|
||||||
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
|
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
|
||||||
[PHP_BINARY, 'tests/Concurrency/import-dossier-worker.php', $database, 'race-legal']];
|
[PHP_BINARY, 'tests/Concurrency/import-dossier-worker.php', $database, 'race-legal']];
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ use App\Models\Requisition;
|
|||||||
use App\Models\Supplier;
|
use App\Models\Supplier;
|
||||||
use App\Models\SupplyRecord;
|
use App\Models\SupplyRecord;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
|
use App\Services\CapitalAssignments;
|
||||||
|
use App\Services\CapitalRegister;
|
||||||
use App\Services\CommonBudget;
|
use App\Services\CommonBudget;
|
||||||
use App\Services\ImportBankSupport;
|
use App\Services\ImportBankSupport;
|
||||||
use App\Services\ImportCostDocumentHealth;
|
use App\Services\ImportCostDocumentHealth;
|
||||||
@@ -45,7 +47,8 @@ require_once __DIR__.'/../Support/ImportLegalQaFixture.php';
|
|||||||
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
|
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
|
||||||
$orderPartsAmendment = ($argv[2] ?? '') === 'order-parts-amendment';
|
$orderPartsAmendment = ($argv[2] ?? '') === 'order-parts-amendment';
|
||||||
$orderParts = $orderPartsAmendment || ($argv[2] ?? '') === 'order-parts';
|
$orderParts = $orderPartsAmendment || ($argv[2] ?? '') === 'order-parts';
|
||||||
$legalAmounts = ($argv[2] ?? '') === 'import-legal-amount';
|
$capitalRestore = ($argv[2] ?? '') === 'capital';
|
||||||
|
$legalAmounts = $capitalRestore || ($argv[2] ?? '') === 'import-legal-amount';
|
||||||
$legalRules = $legalAmounts || ($argv[2] ?? '') === 'import-legal';
|
$legalRules = $legalAmounts || ($argv[2] ?? '') === 'import-legal';
|
||||||
$bankSupport = $legalRules || ($argv[2] ?? '') === 'import-bank-support';
|
$bankSupport = $legalRules || ($argv[2] ?? '') === 'import-bank-support';
|
||||||
$importEstimates = $bankSupport || ($argv[2] ?? '') === 'import-estimates';
|
$importEstimates = $bankSupport || ($argv[2] ?? '') === 'import-estimates';
|
||||||
@@ -231,6 +234,10 @@ if ($landedCosts) {
|
|||||||
config(['import-estimates.qa_enabled' => true]);
|
config(['import-estimates.qa_enabled' => true]);
|
||||||
$legalPlanRequest = $f['r']->replicate();
|
$legalPlanRequest = $f['r']->replicate();
|
||||||
$legalPlanRequest->fill(['number' => 'LEGAL-RECOVERY-'.Str::random(10), 'status' => 'draft']);
|
$legalPlanRequest->fill(['number' => 'LEGAL-RECOVERY-'.Str::random(10), 'status' => 'draft']);
|
||||||
|
if ($capitalRestore) {
|
||||||
|
$legalPlanRequest->requester_id = $partyBuyer->id;
|
||||||
|
supplyGrant($partyBuyer, ['requester']);
|
||||||
|
}
|
||||||
$legalPlanRequest->save();
|
$legalPlanRequest->save();
|
||||||
$legalPlanItem = $f['r']->items()->sole()->replicate();
|
$legalPlanItem = $f['r']->items()->sole()->replicate();
|
||||||
$legalPlanItem->requisition_id = $legalPlanRequest->id;
|
$legalPlanItem->requisition_id = $legalPlanRequest->id;
|
||||||
@@ -246,6 +253,18 @@ if ($landedCosts) {
|
|||||||
'subtotal_minor' => $kind === 'duty' ? 750 : null, 'tax_minor' => $kind === 'duty' ? 0 : null,
|
'subtotal_minor' => $kind === 'duty' ? 750 : null, 'tax_minor' => $kind === 'duty' ? 0 : null,
|
||||||
'total_minor' => $kind === 'duty' ? 750 : null], BudgetImportEstimate::KINDS)];
|
'total_minor' => $kind === 'duty' ? 750 : null], BudgetImportEstimate::KINDS)];
|
||||||
$legalNativePlan = app(ImportEstimates::class)->save($partyBuyer, $legalPlanRequest, $legalNativeInput);
|
$legalNativePlan = app(ImportEstimates::class)->save($partyBuyer, $legalPlanRequest, $legalNativeInput);
|
||||||
|
if ($capitalRestore) {
|
||||||
|
config(['capital-register.qa_enabled' => true]);
|
||||||
|
$capitalInput = ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0,
|
||||||
|
'type' => 'project', 'code' => 'RECOVERY-QA', 'name' => 'Projecto sintético antes da revisão', 'department_id' => $f['department']->id,
|
||||||
|
'equipment_id' => null, 'reference' => 'Documento sintético para recuperação', 'state' => 'active', 'reason' => 'Cadastro próprio de Compras no ensaio de recuperação'];
|
||||||
|
$capitalFirst = app(CapitalRegister::class)->save($partyBuyer, $capitalInput);
|
||||||
|
$capitalAssignmentInput = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'item_id' => $legalPlanItem->id,
|
||||||
|
'capital_id' => $capitalFirst->id, 'reason' => 'Destino sintético preservado na recuperação do cadastro'];
|
||||||
|
$capitalAssignment = app(CapitalAssignments::class)->save($partyBuyer, $legalPlanRequest, $capitalAssignmentInput);
|
||||||
|
$capitalArchive = app(CapitalRegister::class)->save($partyBuyer, [...$capitalInput, 'operation_key' => (string) Str::uuid(),
|
||||||
|
'record_key' => $capitalFirst->record_key, 'version' => 1, 'state' => 'archived', 'name' => 'Designação sintética posterior']);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
$evidenceManifest = [];
|
$evidenceManifest = [];
|
||||||
@@ -391,6 +410,20 @@ try {
|
|||||||
echo json_encode(['legal_amount_minor_restored' => 750, 'legal_amount_replay_without_effects' => true,
|
echo json_encode(['legal_amount_minor_restored' => 750, 'legal_amount_replay_without_effects' => true,
|
||||||
'native_legal_plan_total_minor' => 10750, 'native_legal_plan_source_restored' => true,
|
'native_legal_plan_total_minor' => 10750, 'native_legal_plan_source_restored' => true,
|
||||||
'native_legal_plan_replay_without_effects' => true], JSON_THROW_ON_ERROR).PHP_EOL;
|
'native_legal_plan_replay_without_effects' => true], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||||
|
if ($capitalRestore) {
|
||||||
|
$capitalService = app(CapitalRegister::class);
|
||||||
|
$capitalReplay = $capitalService->save($restoredBuyer, $capitalInput);
|
||||||
|
$assignmentReplay = app(CapitalAssignments::class)->save($restoredBuyer, $restoredRequest, $capitalAssignmentInput);
|
||||||
|
$capitalFrozen = app(CapitalAssignments::class)->freezeForItems($restoredBuyer, [$legalPlanItem->id]);
|
||||||
|
$capitalHead = app(SupplyPlanning::class)->latest('capital_register')->where('record_key', $capitalFirst->record_key)->firstOrFail();
|
||||||
|
if ($capitalReplay->id !== $capitalFirst->id || $assignmentReplay->id !== $capitalAssignment->id
|
||||||
|
|| $capitalHead->id !== $capitalArchive->id || $capitalHead->state !== 'archived'
|
||||||
|
|| $capitalFrozen[$legalPlanItem->id]['snapshot']['source']['id'] !== $capitalFirst->id) {
|
||||||
|
throw new RuntimeException('Capital identity versions, archival, frozen assignment or operation replay differs after recovery.');
|
||||||
|
}
|
||||||
|
echo json_encode(['capital_register_versions_restored' => 2, 'capital_assignment_source_version_restored' => 1,
|
||||||
|
'capital_archived_head_preserved' => true, 'capital_replay_without_effects' => true], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
$readFingerprint = $fingerprint($restored, $afterColumns);
|
$readFingerprint = $fingerprint($restored, $afterColumns);
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ use Inertia\Testing\AssertableInertia as Assert;
|
|||||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||||
|
|
||||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||||
|
require_once __DIR__.'/../Support/SupplyFixture.php';
|
||||||
|
|
||||||
beforeEach(function () {
|
beforeEach(function () {
|
||||||
config(['capital-register.qa_enabled' => true]);
|
config(['capital-register.qa_enabled' => true]);
|
||||||
@@ -133,3 +134,34 @@ test('submitted requisitions reject new line destinations and stale versions do
|
|||||||
expect(fn () => $service->freezeForItems($this->f['issuer'], [$item->id]))->toThrow(HttpException::class);
|
expect(fn () => $service->freezeForItems($this->f['issuer'], [$item->id]))->toThrow(HttpException::class);
|
||||||
expect(SupplyRecord::query()->where('kind', 'capital_assignment')->count())->toBe(1);
|
expect(SupplyRecord::query()->where('kind', 'capital_assignment')->count())->toBe(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('revoked requester retains only native historical visibility without new catalogue choices or commands', function () {
|
||||||
|
supplyGrant($this->f['issuer'], ['procurement', 'requester']);
|
||||||
|
$source = app(CapitalRegister::class)->save($this->f['issuer'], $this->input);
|
||||||
|
$this->f['r']->update(['status' => 'draft']);
|
||||||
|
$item = $this->f['r']->items()->sole();
|
||||||
|
$input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'item_id' => $item->id, 'capital_id' => $source->id,
|
||||||
|
'reason' => 'Escolha sintética antes da revogação dos acessos'];
|
||||||
|
$service = app(CapitalAssignments::class);
|
||||||
|
$service->save($this->f['issuer'], $this->f['r'], $input);
|
||||||
|
DB::table('organization_memberships')->where('user_id', $this->f['issuer']->id)->delete();
|
||||||
|
$workspace = $service->workspace($this->f['issuer'], $this->f['r']);
|
||||||
|
expect($workspace['canWrite'])->toBeFalse()->and($workspace['choices']->total())->toBe(0)->and($workspace['current'])->toHaveCount(1);
|
||||||
|
expect(fn () => $service->save($this->f['issuer'], $this->f['r'], [...$input, 'operation_key' => (string) Str::uuid(), 'version' => 1]))->toThrow(HttpException::class);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('classified machinery cannot submit without a capital destination or create approvals and reservations', function () {
|
||||||
|
$this->f['r']->update(['status' => 'draft']);
|
||||||
|
$item = $this->f['r']->items()->sole();
|
||||||
|
$item->update(['purchase_type' => 'equipment', 'production_area' => 'Área sintética',
|
||||||
|
'category_context' => ['version' => 1, 'category' => 'capital_equipment', 'reason' => 'Justificação sintética de investimento']]);
|
||||||
|
$this->postJson('/requisicoes/'.$this->f['r']->id.'/submeter', ['operation_key' => (string) Str::uuid(), 'process_version' => $this->f['r']->process_version])
|
||||||
|
->assertUnprocessable()->assertJsonValidationErrors('capital_assignment');
|
||||||
|
expect($this->f['r']->fresh()->status)->toBe('draft')->and(DB::table('budget_entries')->count())->toBe(0)
|
||||||
|
->and($this->f['r']->steps()->count())->toBe(0);
|
||||||
|
$source = app(CapitalRegister::class)->save($this->f['issuer'], $this->input);
|
||||||
|
app(CapitalAssignments::class)->save($this->f['issuer'], $this->f['r'], ['operation_key' => (string) Str::uuid(), 'version' => 0,
|
||||||
|
'item_id' => $item->id, 'capital_id' => $source->id, 'reason' => 'Destino sintético para maquinaria classificada']);
|
||||||
|
app(CapitalAssignments::class)->assertSubmission($this->f['issuer'], $this->f['r']);
|
||||||
|
expect(DB::table('budget_entries')->count())->toBe(0)->and($this->f['r']->steps()->count())->toBe(0);
|
||||||
|
});
|
||||||
|
|||||||
@@ -1969,6 +1969,14 @@ test('native consolidated order retains both origins and consumes a single invoi
|
|||||||
expect(PurchaseOrder::query()->visibleTo($this->owner)->whereKey($order->id)->exists())->toBeTrue();
|
expect(PurchaseOrder::query()->visibleTo($this->owner)->whereKey($order->id)->exists())->toBeTrue();
|
||||||
$request->forceFill(['requester_id' => $this->head->id])->save();
|
$request->forceFill(['requester_id' => $this->head->id])->save();
|
||||||
expect(PurchaseOrder::query()->visibleTo($this->owner)->whereKey($order->id)->exists())->toBeFalse();
|
expect(PurchaseOrder::query()->visibleTo($this->owner)->whereKey($order->id)->exists())->toBeFalse();
|
||||||
|
// The search must respect every consolidated origin after a current department change,
|
||||||
|
// while keeping the native company-wide warehouse reader's receipt access.
|
||||||
|
$otherDepartment = Department::query()->create(['tenant_id' => $this->tenant->id, 'name' => 'Outro departamento sintético']);
|
||||||
|
$request->forceFill(['department_id' => $otherDepartment->id])->save();
|
||||||
|
$this->actingAs($this->head)->get('/compras/pesquisa?q=GR-CONSOL-QA')->assertOk()
|
||||||
|
->assertInertia(fn (Assert $page) => $page->where('groups.4.key', 'receipts')->where('groups.4.records.total', 0));
|
||||||
|
$this->actingAs($receiver)->get('/compras/pesquisa?q=GR-CONSOL-QA')->assertOk()
|
||||||
|
->assertInertia(fn (Assert $page) => $page->where('groups.4.key', 'receipts')->where('groups.4.records.total', 1));
|
||||||
});
|
});
|
||||||
|
|
||||||
test('native partial-order cancellation uses independent Finance and preserves the unissued reservation and requisition', function () {
|
test('native partial-order cancellation uses independent Finance and preserves the unissued reservation and requisition', function () {
|
||||||
|
|||||||
@@ -0,0 +1,220 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Enums\PurchasingRole;
|
||||||
|
use App\Models\Budget;
|
||||||
|
use App\Models\Invoice;
|
||||||
|
use App\Models\Requisition;
|
||||||
|
use App\Models\SupplyRecord;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\CommonBudget;
|
||||||
|
use App\Services\RequisitionBudgetDistributions;
|
||||||
|
use App\Services\RequisitionExpiry;
|
||||||
|
use App\Services\RequisitionWorkflow;
|
||||||
|
use App\Services\WorkflowNotices;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Inertia\Testing\AssertableInertia as Assert;
|
||||||
|
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||||
|
use Tempo\Finance\Budget\BudgetControl;
|
||||||
|
use Tempo\Finance\Budget\BudgetFailure;
|
||||||
|
use Tempo\Finance\Budget\BudgetImportEstimate;
|
||||||
|
use Tempo\Purchasing\Internal\InternalRequisitions;
|
||||||
|
|
||||||
|
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||||
|
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
|
||||||
|
|
||||||
|
beforeEach(function () {
|
||||||
|
if (! method_exists(BudgetControl::class, 'beginRequisitionCycle')) {
|
||||||
|
$this->markTestSkipped('The optional cycle contract uses the explicitly authorised common QA source, never the installed kernel.');
|
||||||
|
}
|
||||||
|
$this->f = receiptFixture();
|
||||||
|
$this->actingAs($this->f['issuer']);
|
||||||
|
$this->reviewer = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||||
|
$this->budget = Budget::query()->create(['tenant_id' => $this->f['tenant']->id, 'cost_center_id' => $this->f['r']->cost_center_id,
|
||||||
|
'year' => now()->year, 'kind' => 'operating', 'amount_minor' => 100000, 'includes_tax' => true,
|
||||||
|
'reason' => 'Dotação aprovada estritamente sintética para ciclos', 'created_by' => $this->f['issuer']->id, 'approved_by' => $this->reviewer->id]);
|
||||||
|
budgetDistributionFixtureSchema();
|
||||||
|
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
|
||||||
|
(require __DIR__.'/../../database/qa-migrations/2026_11_27_000001_add_requisition_cycles.php')->up();
|
||||||
|
config(['requisition-expiry.qa_enabled' => true]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('ordinary budget cycles release and reserve a revised amount without replaying or rewriting the original cycle', function () {
|
||||||
|
$origin = $this->f['r']->id;
|
||||||
|
$service = app(CommonBudget::class);
|
||||||
|
$first = $service->for($this->f['issuer'], [$origin => 1]);
|
||||||
|
$open = (string) Str::uuid();
|
||||||
|
$first->beginRequisitionCycle($origin, 1, $open);
|
||||||
|
$first->record($origin, $this->f['r']->cost_center_id, 'operating', 'reserve', 10000, 10000);
|
||||||
|
expect(fn () => $first->closeRequisitionCycle($origin, 1, (string) Str::uuid()))->toThrow(BudgetFailure::class);
|
||||||
|
$first->record($origin, $this->f['r']->cost_center_id, 'operating', 'release');
|
||||||
|
$close = (string) Str::uuid();
|
||||||
|
$first->closeRequisitionCycle($origin, 1, $close);
|
||||||
|
$old = DB::table('budget_entries')->where('requisition_cycle', 1)->orderBy('id')->get()->toJson();
|
||||||
|
expect($first->closeRequisitionCycle($origin, 1, $close)['replayed'])->toBeTrue();
|
||||||
|
$second = $service->for($this->f['issuer'], [$origin => 2]);
|
||||||
|
$second->beginRequisitionCycle($origin, 2, (string) Str::uuid());
|
||||||
|
$second->record($origin, $this->f['r']->cost_center_id, 'operating', 'reserve', 12000, 12000);
|
||||||
|
$second->record($origin, $this->f['r']->cost_center_id, 'operating', 'reserve', 12000, 12000);
|
||||||
|
expect(DB::table('budget_entries')->where('requisition_cycle', 1)->orderBy('id')->get()->toJson())->toBe($old)
|
||||||
|
->and(DB::table('budget_entries')->where('requisition_cycle', 2)->count())->toBe(1)
|
||||||
|
->and((int) DB::table('budget_entries')->sum('reserved_minor'))->toBe(12000);
|
||||||
|
$this->actingAs($this->reviewer);
|
||||||
|
expect($service->for($this->reviewer)->balance($this->budget->id)['available_minor'])->toBe(88000);
|
||||||
|
$this->actingAs($this->f['issuer']);
|
||||||
|
expect(fn () => $service->for($this->f['issuer'])->record($origin, $this->f['r']->cost_center_id, 'operating', 'release'))->toThrow(BudgetFailure::class);
|
||||||
|
$second->record($origin, $this->f['r']->cost_center_id, 'operating', 'release');
|
||||||
|
expect((int) DB::table('budget_entries')->sum('reserved_minor'))->toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a current committed cycle cannot expire or open another cycle and malformed operations cannot establish identity', function () {
|
||||||
|
$origin = $this->f['r']->id;
|
||||||
|
$engine = app(CommonBudget::class)->for($this->f['issuer'], [$origin => 1]);
|
||||||
|
expect(fn () => $engine->beginRequisitionCycle($origin, 1, str_repeat('-', 36)))->toThrow(BudgetFailure::class);
|
||||||
|
$engine->beginRequisitionCycle($origin, 1, (string) Str::uuid());
|
||||||
|
$engine->record($origin, $this->f['r']->cost_center_id, 'operating', 'reserve', 10000, 10000);
|
||||||
|
$engine->record($origin, $this->f['r']->cost_center_id, 'operating', 'commit', 10000, 10000);
|
||||||
|
expect(fn () => $engine->closeRequisitionCycle($origin, 1, (string) Str::uuid()))->toThrow(BudgetFailure::class);
|
||||||
|
expect(fn () => app(CommonBudget::class)->for($this->f['issuer'], [$origin => 2])->beginRequisitionCycle($origin, 2, (string) Str::uuid()))->toThrow(BudgetFailure::class);
|
||||||
|
expect(DB::table('budget_requisition_cycles')->count())->toBe(1)
|
||||||
|
->and((int) DB::table('budget_entries')->sum('committed_minor'))->toBe(10000);
|
||||||
|
$invoice = Invoice::query()->create(['tenant_id' => $this->f['tenant']->id, 'purchase_order_id' => $this->f['order']->id,
|
||||||
|
'supplier_id' => $this->f['order']->supplier_id, 'created_by' => $this->f['issuer']->id, 'number' => 'CYCLE-CONSUMPTION-QA',
|
||||||
|
'issued_on' => today(), 'status' => 'validated', 'subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000, 'snapshot' => ['synthetic' => true]]);
|
||||||
|
$this->actingAs($this->reviewer);
|
||||||
|
app(CommonBudget::class)->for($this->reviewer, [$origin => 1])->consume($origin, $invoice->id, 10000, 10000);
|
||||||
|
$this->actingAs($this->f['issuer']);
|
||||||
|
expect((int) DB::table('budget_entries')->sum('committed_minor'))->toBe(0);
|
||||||
|
expect(fn () => $engine->closeRequisitionCycle($origin, 1, (string) Str::uuid()))->toThrow(BudgetFailure::class);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('current approval relations select the new cycle during eager loading and keep all original decisions addressable', function () {
|
||||||
|
$request = $this->f['r']->fresh();
|
||||||
|
$old = $request->allSteps()->create(['tenant_id' => $request->tenant_id, 'approval_cycle' => 1, 'position' => 1,
|
||||||
|
'role' => 'department_head', 'decision' => 'approved', 'approver_id' => $this->reviewer->id, 'decided_at' => now()]);
|
||||||
|
$request->setAttribute('approval_cycle', 2);
|
||||||
|
$request->setAttribute('status', 'pending');
|
||||||
|
$request->save();
|
||||||
|
expect((int) DB::table('requisitions')->where('id', $request->id)->value('approval_cycle'))->toBe(2);
|
||||||
|
$current = $request->allSteps()->create(['tenant_id' => $request->tenant_id, 'approval_cycle' => 2, 'position' => 1,
|
||||||
|
'role' => 'department_head', 'decision' => 'pending']);
|
||||||
|
$loaded = Requisition::query()->with('steps')->whereKey($request->id)->firstOrFail();
|
||||||
|
expect($loaded->steps->pluck('id')->all())->toBe([$current->id])
|
||||||
|
->and($loaded->allSteps()->count())->toBe(2)->and($old->fresh()->decision)->toBe('approved')
|
||||||
|
->and(InternalRequisitions::nextStep($loaded->toArray(), $this->reviewer->id)['id'])->toBe($current->id);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('distributed reservations use a fresh cycle header and preserve the released original allocations', function () {
|
||||||
|
$origin = $this->f['r']->id;
|
||||||
|
$line = $this->f['r']->items()->sole();
|
||||||
|
$allocations = [['allocation_key' => 'A', 'line_id' => $line->id, 'centre_id' => $this->f['r']->cost_center_id, 'subtotal_minor' => 10000, 'total_minor' => 10000]];
|
||||||
|
$lines = [$line->id => ['subtotal_minor' => 10000, 'total_minor' => 10000, 'required_kind' => 'operating']];
|
||||||
|
$revision = hash('sha256', 'synthetic cycle-one native source');
|
||||||
|
$first = app(CommonBudget::class)->for($this->f['issuer'], [$origin => 1]);
|
||||||
|
$first->beginRequisitionCycle($origin, 1, (string) Str::uuid());
|
||||||
|
$first->recordDistribution($origin, 'reserve', $allocations, $lines, $revision, (string) Str::uuid());
|
||||||
|
$first->recordDistribution($origin, 'release', $allocations, $lines, $revision, (string) Str::uuid());
|
||||||
|
$first->closeRequisitionCycle($origin, 1, (string) Str::uuid());
|
||||||
|
$old = DB::table('budget_distributions')->where('requisition_cycle', 1)->sole();
|
||||||
|
$this->f['r']->setAttribute('approval_cycle', 2);
|
||||||
|
$this->f['r']->save();
|
||||||
|
$line->update(['unit_price_minor' => 12000, 'subtotal_minor' => 12000, 'total_minor' => 12000]);
|
||||||
|
$this->f['r']->update(['subtotal_minor' => 12000, 'total_minor' => 12000]);
|
||||||
|
$allocations[0]['subtotal_minor'] = $allocations[0]['total_minor'] = 12000;
|
||||||
|
$lines[$line->id]['subtotal_minor'] = $lines[$line->id]['total_minor'] = 12000;
|
||||||
|
$second = app(CommonBudget::class)->for($this->f['issuer'], [$origin => 2]);
|
||||||
|
$second->beginRequisitionCycle($origin, 2, (string) Str::uuid());
|
||||||
|
$second->recordDistribution($origin, 'reserve', $allocations, $lines, hash('sha256', 'synthetic cycle-two native source'), (string) Str::uuid());
|
||||||
|
expect(DB::table('budget_distributions')->where('id', $old->id)->sole())->toEqual($old)
|
||||||
|
->and(DB::table('budget_distributions')->where('requisition_id', $origin)->count())->toBe(2)
|
||||||
|
->and((int) DB::table('budget_distribution_entries')->sum('reserved_minor'))->toBe(12000)
|
||||||
|
->and(app(RequisitionBudgetDistributions::class)->source($this->f['r'])->requisition_cycle)->toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('import assumptions release in the old cycle before a separately identified new plan can reserve', function () {
|
||||||
|
$origin = $this->f['r']->id;
|
||||||
|
$first = app(CommonBudget::class)->for($this->f['issuer'], [$origin => 1]);
|
||||||
|
$first->beginRequisitionCycle($origin, 1, (string) Str::uuid());
|
||||||
|
$goods = ['subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000];
|
||||||
|
$components = array_map(fn ($kind) => ['key' => $kind, 'kind' => $kind, 'status' => $kind === 'duty' ? 'known' : 'not_applicable',
|
||||||
|
'basis' => 'Explicit synthetic assumption; not a real import or exemption', 'subtotal_minor' => $kind === 'duty' ? 1000 : null,
|
||||||
|
'tax_minor' => $kind === 'duty' ? 0 : null, 'total_minor' => $kind === 'duty' ? 1000 : null], BudgetImportEstimate::KINDS);
|
||||||
|
$plan = (string) Str::uuid();
|
||||||
|
$first->reserveImportEstimate($plan, 1, $this->budget->id, $origin, $goods, $components, (string) Str::uuid());
|
||||||
|
expect(fn () => $first->closeRequisitionCycle($origin, 1, (string) Str::uuid()))->toThrow(BudgetFailure::class);
|
||||||
|
$hash = BudgetImportEstimate::reconcile($goods, $components, true)['fingerprint'];
|
||||||
|
$first->releaseImportEstimate($plan, 1, $hash, (string) Str::uuid());
|
||||||
|
$first->closeRequisitionCycle($origin, 1, (string) Str::uuid());
|
||||||
|
$old = DB::table('budget_landed_entries')->orderBy('id')->get()->toJson();
|
||||||
|
$second = app(CommonBudget::class)->for($this->f['issuer'], [$origin => 2]);
|
||||||
|
$second->beginRequisitionCycle($origin, 2, (string) Str::uuid());
|
||||||
|
foreach ($components as &$component) {
|
||||||
|
if ($component['kind'] === 'duty') {
|
||||||
|
$component['subtotal_minor'] = $component['total_minor'] = 1500;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
unset($component);
|
||||||
|
$second->reserveImportEstimate((string) Str::uuid(), 1, $this->budget->id, $origin, $goods, $components, (string) Str::uuid());
|
||||||
|
expect((int) DB::table('budget_landed_entries')->sum('reserved_minor'))->toBe(1500)
|
||||||
|
->and(DB::table('budget_landed_entries')->orderBy('id')->limit(2)->get()->toJson())->toBe($old);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('native expiry returns the same request and preserves the approved stage before a fresh revised submission and reservation', function () {
|
||||||
|
$admin = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Admin]);
|
||||||
|
$head = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
|
||||||
|
$buyer = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Procurement]);
|
||||||
|
$this->f['tenant']->update(['first_limit_minor' => 5000, 'second_limit_minor' => 20000]);
|
||||||
|
$expiry = app(RequisitionExpiry::class);
|
||||||
|
$this->actingAs($admin);
|
||||||
|
$expiry->savePolicy($admin, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true,
|
||||||
|
'levels' => array_map(fn ($role) => ['role' => $role, 'expire_minutes' => 30, 'reminder_minutes' => 10, 'escalation_minutes' => null, 'profile_ids' => []], ['department_head', 'procurement']),
|
||||||
|
'reason' => 'Prazos corridos expressamente sintéticos deste teste de expiração']);
|
||||||
|
$owner = $this->f['issuer'];
|
||||||
|
$this->actingAs($owner);
|
||||||
|
$workflow = app(RequisitionWorkflow::class);
|
||||||
|
$input = ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $this->f['r']->cost_center_id, 'priority' => 'normal',
|
||||||
|
'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Requisição sintética para duas submissões independentes',
|
||||||
|
'items' => [['description' => 'Bem de ensaio', 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '1.000', 'unit' => 'un', 'unit_price' => '100.00', 'tax_rate' => '0.00']]];
|
||||||
|
$request = $workflow->save($owner, $input);
|
||||||
|
$workflow->submit($owner, $request, (string) Str::uuid(), $request->process_version);
|
||||||
|
$request->refresh();
|
||||||
|
$this->actingAs($head);
|
||||||
|
$workflow->decide($head, $request, 'approved', 'Conferência sintética do primeiro nível', (string) Str::uuid(), $request->process_version);
|
||||||
|
$request->refresh();
|
||||||
|
$approved = $request->steps()->where('decision', 'approved')->sole()->toArray();
|
||||||
|
$this->travel(31)->minutes();
|
||||||
|
$deadline = $expiry->deadline($request);
|
||||||
|
expect($deadline['state'])->toBe('expired');
|
||||||
|
$this->actingAs($buyer);
|
||||||
|
expect(fn () => $workflow->decide($buyer, $request, 'approved', 'Aprovação fora do prazo', (string) Str::uuid(), $request->process_version))->toThrow(HttpException::class);
|
||||||
|
$this->actingAs($owner);
|
||||||
|
$operation = (string) Str::uuid();
|
||||||
|
$version = $request->process_version;
|
||||||
|
$this->withoutVite();
|
||||||
|
$body = ['basis_hash' => $deadline['basis_hash'], 'operation_key' => $operation, 'process_version' => $version];
|
||||||
|
$this->postJson('/requisicoes/'.$request->id.'/expiracao', $body)->assertRedirect();
|
||||||
|
$this->postJson('/requisicoes/'.$request->id.'/expiracao', $body)->assertRedirect();
|
||||||
|
$request->refresh();
|
||||||
|
expect($request->status)->toBe('draft')->and($request->approval_cycle)->toBe(2)->and($request->steps()->count())->toBe(0)
|
||||||
|
->and($request->allSteps()->whereKey($approved['id'])->firstOrFail()->toArray())->toBe($approved)
|
||||||
|
->and($request->allSteps()->where('decision', 'expired')->count())->toBe(1)
|
||||||
|
->and((int) DB::table('budget_entries')->where('requisition_id', $request->id)->sum('reserved_minor'))->toBe(0)
|
||||||
|
->and(SupplyRecord::query()->where('kind', 'req_expiration')->count())->toBe(1);
|
||||||
|
$this->get('/requisicoes/'.$request->id.'/prazos')->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')
|
||||||
|
->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true)
|
||||||
|
->assertInertia(fn (Assert $page) => $page->component('requisitions/expiry')->where('requisition.approval_cycle', 2)->where('canEdit', true)->has('history.data', 1));
|
||||||
|
$input['operation_key'] = (string) Str::uuid();
|
||||||
|
$input['process_version'] = $request->process_version;
|
||||||
|
$input['items'][0]['unit_price'] = '120.00';
|
||||||
|
$request = $workflow->save($owner, $input, $request);
|
||||||
|
$workflow->submit($owner, $request, (string) Str::uuid(), $request->process_version);
|
||||||
|
$request->refresh();
|
||||||
|
expect($request->status)->toBe('pending')->and($request->steps()->count())->toBe(2)
|
||||||
|
->and($request->steps()->where('decision', 'approved')->count())->toBe(0)->and($request->allSteps()->count())->toBe(4)
|
||||||
|
->and((int) DB::table('budget_entries')->where('requisition_id', $request->id)->where('requisition_cycle', 2)->sum('reserved_minor'))->toBe(12000)
|
||||||
|
->and(SupplyRecord::query()->where('kind', 'req_expiration')->sole()->snapshot['request']['total_minor'])->toBe(10000);
|
||||||
|
$notices = app(WorkflowNotices::class)->visible($owner);
|
||||||
|
expect(array_column($notices, 'outcome'))->toContain('expired')
|
||||||
|
->and(DB::table('workflow_notices')->where('requisition_id', $request->id)->where('recipient_id', $owner->id)->count())->toBe(1);
|
||||||
|
$this->travelBack();
|
||||||
|
});
|
||||||
@@ -24,6 +24,14 @@ function landedQaReceiptsVerified(array $command, string $output): bool
|
|||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
$mode = ($command[1] ?? '') === 'vendor/bin/pest' ? 'pest' : ($command[3] ?? '');
|
$mode = ($command[1] ?? '') === 'vendor/bin/pest' ? 'pest' : ($command[3] ?? '');
|
||||||
|
if ($mode === 'capital') {
|
||||||
|
if (! $contains(fn ($row) => ($row['capital_register_versions_restored'] ?? null) === 2
|
||||||
|
&& ($row['capital_assignment_source_version_restored'] ?? null) === 1 && ($row['capital_archived_head_preserved'] ?? false) === true
|
||||||
|
&& ($row['capital_replay_without_effects'] ?? false) === true)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
$mode = 'import-legal-amount';
|
||||||
|
}
|
||||||
if ($mode === 'migrate') {
|
if ($mode === 'migrate') {
|
||||||
return $contains(fn ($row) => ($row['isolated_schema_prepared'] ?? false) === true);
|
return $contains(fn ($row) => ($row['isolated_schema_prepared'] ?? false) === true);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -195,4 +195,12 @@ test('legal amount receipts require both contention cases and recovery of the ex
|
|||||||
expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeTrue();
|
expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeTrue();
|
||||||
$rows[1]['native_legal_plan_total_minor'] = 10751;
|
$rows[1]['native_legal_plan_total_minor'] = 10751;
|
||||||
expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeFalse();
|
expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeFalse();
|
||||||
|
$command[3] = 'capital';
|
||||||
|
$rows[1]['native_legal_plan_total_minor'] = 10750;
|
||||||
|
expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeFalse();
|
||||||
|
$rows[] = ['capital_register_versions_restored' => 2, 'capital_assignment_source_version_restored' => 1,
|
||||||
|
'capital_archived_head_preserved' => true, 'capital_replay_without_effects' => true];
|
||||||
|
expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeTrue();
|
||||||
|
$rows[2]['capital_assignment_source_version_restored'] = 2;
|
||||||
|
expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeFalse();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -87,3 +87,46 @@ test('approved requisitions display the preserved source independently of availa
|
|||||||
expect(frozen).toContain('<script>QA</script>');
|
expect(frozen).toContain('<script>QA</script>');
|
||||||
expect(renderToStaticMarkup(<CapitalAssignmentSummary />)).toBe('');
|
expect(renderToStaticMarkup(<CapitalAssignmentSummary />)).toBe('');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('capital lineage distinguishes the original receipt from current returns and reversal', () => {
|
||||||
|
const html = render(CapitalRegister, {
|
||||||
|
records: page([source]),
|
||||||
|
history: page([source]),
|
||||||
|
departments: [],
|
||||||
|
equipment: [],
|
||||||
|
canManage: false,
|
||||||
|
actorId: 1,
|
||||||
|
tenantId: 1,
|
||||||
|
trace: {
|
||||||
|
orders: page([
|
||||||
|
{
|
||||||
|
id: 7,
|
||||||
|
description: 'Synthetic item',
|
||||||
|
quantity: '2.000',
|
||||||
|
unit: 'un',
|
||||||
|
order_id: 8,
|
||||||
|
order_number: 'OC-QA',
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
receipts: page([
|
||||||
|
{
|
||||||
|
id: 9,
|
||||||
|
description: 'Synthetic item',
|
||||||
|
unit: 'un',
|
||||||
|
receipt_id: 10,
|
||||||
|
order_id: 8,
|
||||||
|
received_on: '2026-11-27',
|
||||||
|
quality_status: 'compliant',
|
||||||
|
accepted_quantity: '2.000',
|
||||||
|
reversed: true,
|
||||||
|
returned_quantity: '1.000',
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(html).toContain('Aceite no original: 2.000');
|
||||||
|
expect(html).toContain('Devolução ao fornecedor: 1.000');
|
||||||
|
expect(html).toContain('Recepção estornada');
|
||||||
|
expect(html).toContain('/ordens/8');
|
||||||
|
expect(html).not.toContain('<form');
|
||||||
|
});
|
||||||
|
|||||||
@@ -0,0 +1,249 @@
|
|||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { App } from '@inertiajs/react';
|
||||||
|
import { renderToStaticMarkup } from 'react-dom/server';
|
||||||
|
import { expect, test } from 'vitest';
|
||||||
|
import {
|
||||||
|
ActionBar,
|
||||||
|
FormErrors,
|
||||||
|
PageTitle,
|
||||||
|
Panel,
|
||||||
|
TableViewport,
|
||||||
|
} from '@/components/procurement';
|
||||||
|
import RequisitionForm from '@/pages/requisitions/form';
|
||||||
|
import SupplierEdit from '@/pages/suppliers/edit';
|
||||||
|
import ProcurementReports from '@/pages/reports/procurement';
|
||||||
|
import type { Supplier } from '@/types/procurement';
|
||||||
|
|
||||||
|
function render(
|
||||||
|
component: Parameters<typeof App>[0]['initialComponent'],
|
||||||
|
props: object,
|
||||||
|
) {
|
||||||
|
const html = renderToStaticMarkup(
|
||||||
|
<App
|
||||||
|
initialComponent={component}
|
||||||
|
initialPage={{
|
||||||
|
component: 'qa',
|
||||||
|
url: '/qa',
|
||||||
|
version: 'presentation',
|
||||||
|
clearHistory: false,
|
||||||
|
encryptHistory: true,
|
||||||
|
props: { errors: {}, ...props },
|
||||||
|
}}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
if (process.env.SGC_PRESENTATION_PREVIEW) {
|
||||||
|
const root = path.resolve(process.env.SGC_PRESENTATION_PREVIEW);
|
||||||
|
const allowed = path.resolve('storage/framework/testing') + path.sep;
|
||||||
|
if (!root.startsWith(allowed))
|
||||||
|
throw Error('Private preview path required');
|
||||||
|
fs.mkdirSync(root, { recursive: true });
|
||||||
|
const name =
|
||||||
|
component === RequisitionForm
|
||||||
|
? 'requisition'
|
||||||
|
: component === SupplierEdit
|
||||||
|
? 'supplier'
|
||||||
|
: 'report';
|
||||||
|
fs.writeFileSync(
|
||||||
|
path.join(root, name + '.html'),
|
||||||
|
'<!doctype html><html lang="pt-MZ"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>SGC - ' +
|
||||||
|
name +
|
||||||
|
' - dados sinteticos</title><link rel="stylesheet" href="/preview.css"><body><aside style="padding:12px;background:#fef3c7">Pre-visualizacao estatica isolada com dados sinteticos; sem gravacao.</aside>' +
|
||||||
|
html +
|
||||||
|
'</body></html>',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return html;
|
||||||
|
}
|
||||||
|
|
||||||
|
test('shared panels have distinct accessible titles and preserve their own content', () => {
|
||||||
|
const html = renderToStaticMarkup(
|
||||||
|
<>
|
||||||
|
<Panel title="Dados gerais">
|
||||||
|
<input name="reference" defaultValue="SINTETICO" />
|
||||||
|
</Panel>
|
||||||
|
<Panel title="Historico">
|
||||||
|
<p>Versao original</p>
|
||||||
|
</Panel>
|
||||||
|
</>,
|
||||||
|
);
|
||||||
|
const headings = [...html.matchAll(/<h2 id="([^"]+)"/g)].map(
|
||||||
|
(match) => match[1],
|
||||||
|
);
|
||||||
|
expect(new Set(headings).size).toBe(2);
|
||||||
|
for (const id of headings)
|
||||||
|
expect(html).toContain(`aria-labelledby="${id}"`);
|
||||||
|
expect(html).toContain('name="reference"');
|
||||||
|
expect(html).toContain('Versao original');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('shared actions preserve submission and disabled semantics without adding commands', () => {
|
||||||
|
const html = renderToStaticMarkup(
|
||||||
|
<form>
|
||||||
|
<ActionBar align="end">
|
||||||
|
<a href="/requisicoes">Cancelar</a>
|
||||||
|
<button type="submit" disabled>
|
||||||
|
Guardar rascunho
|
||||||
|
</button>
|
||||||
|
</ActionBar>
|
||||||
|
</form>,
|
||||||
|
);
|
||||||
|
expect(html).toContain('role="group"');
|
||||||
|
expect(html).toContain('href="/requisicoes"');
|
||||||
|
expect(html).toContain('type="submit" disabled');
|
||||||
|
expect(html.match(/<button/g)).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('wide result viewport preserves table headers, cells and escaped user text', () => {
|
||||||
|
const html = renderToStaticMarkup(
|
||||||
|
<TableViewport label="Resultados autorizados">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Referencia</th>
|
||||||
|
<th>Valor</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr>
|
||||||
|
<td>{'<script>synthetic</script>'}</td>
|
||||||
|
<td>100,00 MZN</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</TableViewport>,
|
||||||
|
);
|
||||||
|
expect(html).toContain('tabindex="0"');
|
||||||
|
expect(html).toContain('aria-label="Resultados autorizados"');
|
||||||
|
expect(html).toContain('<script>synthetic</script>');
|
||||||
|
expect(html).toContain('<td>100,00 MZN</td>');
|
||||||
|
expect(html.match(/<th>/g)).toHaveLength(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('title keeps the single page heading without inserting an empty action area', () => {
|
||||||
|
const html = renderToStaticMarkup(
|
||||||
|
<PageTitle
|
||||||
|
eyebrow="Compras"
|
||||||
|
title="Nova requisicao"
|
||||||
|
description="Preparacao sintetica"
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
expect(html.match(/<h1 /g)).toHaveLength(1);
|
||||||
|
expect(html).not.toContain('sgc-page-actions');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('shared validation keeps every error and the existing help action', () => {
|
||||||
|
const html = renderToStaticMarkup(
|
||||||
|
<FormErrors
|
||||||
|
errors={{
|
||||||
|
'items.0.quantity': 'Quantidade invalida',
|
||||||
|
currency: 'Moeda por indicar',
|
||||||
|
}}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
expect(html).toContain('role="alert"');
|
||||||
|
expect(html).toContain('Quantidade invalida');
|
||||||
|
expect(html).toContain('Moeda por indicar');
|
||||||
|
expect(html).toContain('type="button"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test.each([false, true])(
|
||||||
|
'requisition preserves existing save guard with incomplete drafts %s',
|
||||||
|
(incompleteDraftsAvailable) => {
|
||||||
|
const html = render(RequisitionForm, {
|
||||||
|
costCenters: [],
|
||||||
|
requisition: null,
|
||||||
|
incompleteDraftsAvailable,
|
||||||
|
});
|
||||||
|
expect(html).toContain('Guardar rascunho');
|
||||||
|
expect(html).toContain('sgc-action-bar');
|
||||||
|
const save = html.slice(
|
||||||
|
html.lastIndexOf('<button'),
|
||||||
|
html.lastIndexOf('</button>'),
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
/\sdisabled(?:=|[ >])/.test(save.slice(0, save.indexOf('>') + 1)),
|
||||||
|
).toBe(!incompleteDraftsAvailable);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
test('supplier editing keeps the financial revalidation warning and cancellation destination', () => {
|
||||||
|
const supplier = {
|
||||||
|
id: 7,
|
||||||
|
name: 'Fornecedor SINTETICO',
|
||||||
|
nuit: '',
|
||||||
|
contact: '',
|
||||||
|
email: '',
|
||||||
|
phone: '',
|
||||||
|
address: '',
|
||||||
|
category: '',
|
||||||
|
beneficiaries: '',
|
||||||
|
document_references: '',
|
||||||
|
diligence_notes: '',
|
||||||
|
next_review: '2026-12-01',
|
||||||
|
blocked: false,
|
||||||
|
version: 3,
|
||||||
|
} as Supplier;
|
||||||
|
const html = render(SupplierEdit, { supplier });
|
||||||
|
expect(html).toContain('/fornecedores/7');
|
||||||
|
expect(html).toContain('Guardar alterações');
|
||||||
|
expect(html).toContain('retiram a validação actual');
|
||||||
|
expect(html).toContain('sgc-action-bar');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('procurement report retains applied export filters, result scope and both pagination destinations', () => {
|
||||||
|
const html = render(ProcurementReports, {
|
||||||
|
records: {
|
||||||
|
data: [],
|
||||||
|
total: 0,
|
||||||
|
current_page: 2,
|
||||||
|
last_page: 3,
|
||||||
|
prev_page_url: '/relatorios?status=approved&page=1',
|
||||||
|
next_page_url: '/relatorios?status=approved&page=3',
|
||||||
|
},
|
||||||
|
filters: { status: 'approved', department_id: 9 },
|
||||||
|
departments: [{ id: 9, name: 'Departamento SINTETICO' }],
|
||||||
|
counts: {},
|
||||||
|
generatedAt: '2026-11-27T12:00:00Z',
|
||||||
|
});
|
||||||
|
expect(html).toContain(
|
||||||
|
'/relatorios/compras.csv?status=approved&department_id=9',
|
||||||
|
);
|
||||||
|
expect(html).toContain('/relatorios?status=approved&page=1');
|
||||||
|
expect(html).toContain('/relatorios?status=approved&page=3');
|
||||||
|
expect(html).toContain('âmbito autorizado');
|
||||||
|
expect(html).toContain('sgc-table-viewport');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('populated report keeps every authorised row and its process/report actions', () => {
|
||||||
|
const records = {
|
||||||
|
data: Array.from({ length: 25 }, (_, i) => ({
|
||||||
|
id: 100 + i,
|
||||||
|
number: `REQ-SINTETICA-${i + 1}`,
|
||||||
|
status: 'approved',
|
||||||
|
created_at: '2026-11-27T12:00:00Z',
|
||||||
|
needed_by: '2026-12-01',
|
||||||
|
department: 'Departamento sintetico de aprovisionamento',
|
||||||
|
requester: 'Utilizador sintetico',
|
||||||
|
total_minor: '10000',
|
||||||
|
quotations_count: 3,
|
||||||
|
order_number: null,
|
||||||
|
})),
|
||||||
|
total: 75,
|
||||||
|
current_page: 2,
|
||||||
|
last_page: 3,
|
||||||
|
prev_page_url: '/relatorios?page=1',
|
||||||
|
next_page_url: '/relatorios?page=3',
|
||||||
|
};
|
||||||
|
const html = render(ProcurementReports, {
|
||||||
|
records,
|
||||||
|
filters: {},
|
||||||
|
departments: [],
|
||||||
|
counts: {},
|
||||||
|
generatedAt: '2026-11-27T12:00:00Z',
|
||||||
|
});
|
||||||
|
expect(html.match(/Acompanhar processo/g)).toHaveLength(25);
|
||||||
|
expect(html.match(/Gerar relatório de conferência/g)).toHaveLength(25);
|
||||||
|
expect(html).toContain('REQ-SINTETICA-25');
|
||||||
|
expect(html).toContain('/requisicoes/124/relatorio');
|
||||||
|
});
|
||||||
@@ -0,0 +1,251 @@
|
|||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { App } from '@inertiajs/react';
|
||||||
|
import { renderToStaticMarkup } from 'react-dom/server';
|
||||||
|
import { expect, test } from 'vitest';
|
||||||
|
import ReviewReport from '@/pages/purchases/review-report';
|
||||||
|
import Improvements from '@/pages/reports/supplier-improvements';
|
||||||
|
import PeopleReports from '@/pages/people/reports';
|
||||||
|
import WarehouseRequests from '@/pages/stock/requests';
|
||||||
|
import BankSupport from '@/pages/supply/import-bank-support';
|
||||||
|
|
||||||
|
const stamp = '2026-11-27T12:00:00Z';
|
||||||
|
const page = <T,>(data: T[]) => ({
|
||||||
|
data,
|
||||||
|
from: data.length ? 1 : null,
|
||||||
|
to: data.length || null,
|
||||||
|
total: data.length,
|
||||||
|
current_page: 1,
|
||||||
|
last_page: 1,
|
||||||
|
prev_page_url: null,
|
||||||
|
next_page_url: null,
|
||||||
|
});
|
||||||
|
function render(
|
||||||
|
component: Parameters<typeof App>[0]['initialComponent'],
|
||||||
|
props: object,
|
||||||
|
name: string,
|
||||||
|
) {
|
||||||
|
const html = renderToStaticMarkup(
|
||||||
|
<App
|
||||||
|
initialComponent={component}
|
||||||
|
initialPage={{
|
||||||
|
component: 'qa',
|
||||||
|
url: '/qa',
|
||||||
|
version: 'screen-review',
|
||||||
|
clearHistory: false,
|
||||||
|
encryptHistory: true,
|
||||||
|
props: { errors: {}, ...props },
|
||||||
|
}}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
const folder = process.env.SGC_REVIEW_PREVIEW;
|
||||||
|
if (folder) {
|
||||||
|
const root = path.resolve(folder);
|
||||||
|
if (
|
||||||
|
!root.startsWith(
|
||||||
|
path.resolve('storage/framework/testing') + path.sep,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
throw Error('Private preview required');
|
||||||
|
fs.mkdirSync(root, { recursive: true });
|
||||||
|
fs.writeFileSync(
|
||||||
|
path.join(root, name + '.html'),
|
||||||
|
'<!doctype html><html lang="pt-MZ"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>SGC QA ' +
|
||||||
|
name +
|
||||||
|
'</title><link rel="stylesheet" href="/preview.css"><body><aside class="print:hidden" style="padding:12px;background:#fef3c7">Pre-visualizacao isolada; dados sinteticos; sem gravacao.</aside>' +
|
||||||
|
html +
|
||||||
|
'</body></html>',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return html;
|
||||||
|
}
|
||||||
|
const policy = {
|
||||||
|
revision: 1,
|
||||||
|
configured: true,
|
||||||
|
minimum_proposals: 3,
|
||||||
|
minimum_evaluators: 2,
|
||||||
|
weights: { price: 40, quality: 20, delivery: 20, history: 10, payment: 10 },
|
||||||
|
};
|
||||||
|
test('long review report preserves all proposals, original amounts and finance visibility restriction', () => {
|
||||||
|
const rows = Array.from({ length: 30 }, (_, i) => ({
|
||||||
|
id: i + 1,
|
||||||
|
reference: 'QA-PROPOSTA-' + String(i + 1).padStart(3, '0'),
|
||||||
|
supplier: 'Fornecedor SINTETICO ' + (i + 1),
|
||||||
|
currency: 'MZN',
|
||||||
|
subtotal_minor: 10000,
|
||||||
|
tax_minor: 1600,
|
||||||
|
total_minor: 11600,
|
||||||
|
delivery_days: 15,
|
||||||
|
valid_until: '2026-12-31',
|
||||||
|
evaluation_count: 2,
|
||||||
|
score_minor: null,
|
||||||
|
eligible: false,
|
||||||
|
ineligibility_reasons: [
|
||||||
|
'Condicao sintetica por completar; nenhuma adjudicacao automatica.',
|
||||||
|
],
|
||||||
|
is_top: false,
|
||||||
|
weights: policy.weights,
|
||||||
|
}));
|
||||||
|
const report = {
|
||||||
|
generated_at: stamp,
|
||||||
|
generated_by: 'Operador SINTETICO',
|
||||||
|
company: 'Empresa SINTETICA',
|
||||||
|
requisition: {
|
||||||
|
id: 42,
|
||||||
|
number: 'REQ-SINTETICA-42',
|
||||||
|
status: 'approved',
|
||||||
|
justification:
|
||||||
|
'Necessidade sintetica para ensaio de impressao; sem operacao.',
|
||||||
|
department: 'Departamento SINTETICO',
|
||||||
|
requester: 'Requisitante SINTETICO',
|
||||||
|
},
|
||||||
|
comparison: { ready: false, top_count: 0, rows, policy },
|
||||||
|
recommendation: null,
|
||||||
|
admission: null,
|
||||||
|
qualification: null,
|
||||||
|
opening: null,
|
||||||
|
award: null,
|
||||||
|
order: null,
|
||||||
|
fulfilment: {
|
||||||
|
receipts: [],
|
||||||
|
finance_visible: false,
|
||||||
|
invoices: null,
|
||||||
|
payments: null,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const html = render(ReviewReport, { report }, 'review');
|
||||||
|
for (const row of rows) expect(html).toContain(row.reference);
|
||||||
|
expect(html).toContain('report-fulfilment');
|
||||||
|
expect(html).not.toContain('QA-FACTURA-PRIVADA');
|
||||||
|
});
|
||||||
|
test('improvement report preserves details on every visible row without changing their disclosure state', () => {
|
||||||
|
const rows = Array.from({ length: 30 }, (_, i) => ({
|
||||||
|
id: i + 1,
|
||||||
|
evaluation_id: 50 + i,
|
||||||
|
revision: 1,
|
||||||
|
supplier: 'Fornecedor SINTETICO ' + (i + 1),
|
||||||
|
responsible: 'Responsavel SINTETICO',
|
||||||
|
title: 'QA-MEDIDA-' + String(i + 1).padStart(3, '0'),
|
||||||
|
description:
|
||||||
|
'Descricao sintetica da medida de melhoria e acompanhamento da entrega com verificacao independente.',
|
||||||
|
due_on: '2026-12-01',
|
||||||
|
status: 'open',
|
||||||
|
version: 1,
|
||||||
|
overdue: false,
|
||||||
|
result: 'QA-RESULTADO-' + String(i + 1).padStart(3, '0'),
|
||||||
|
evidence: 'QA-EVIDENCIA-' + String(i + 1).padStart(3, '0'),
|
||||||
|
review_reason: 'Conferencia sintetica preservada.',
|
||||||
|
}));
|
||||||
|
const html = render(
|
||||||
|
Improvements,
|
||||||
|
{
|
||||||
|
records: page(rows),
|
||||||
|
filters: {},
|
||||||
|
counts: { open: 30 },
|
||||||
|
overdue: 0,
|
||||||
|
suppliers: [],
|
||||||
|
responsibles: [],
|
||||||
|
today: '2026-11-27',
|
||||||
|
generatedAt: stamp,
|
||||||
|
},
|
||||||
|
'improvements',
|
||||||
|
);
|
||||||
|
for (const row of rows) {
|
||||||
|
expect(html).toContain(row.title);
|
||||||
|
expect(html).toContain(row.evidence);
|
||||||
|
}
|
||||||
|
expect(html).not.toContain('<details open');
|
||||||
|
});
|
||||||
|
test('people deadline report retains all tasks and preserves visibility of unknown deadlines', () => {
|
||||||
|
const items = Array.from({ length: 35 }, (_, i) => ({
|
||||||
|
id: 'task-' + i,
|
||||||
|
reference: 'QA-PESSOAS-' + String(i + 1).padStart(3, '0'),
|
||||||
|
title: 'Processo SINTETICO ' + (i + 1),
|
||||||
|
category: 'task',
|
||||||
|
label: 'Conferencia sintetica',
|
||||||
|
responsibility: 'Responsavel SINTETICO',
|
||||||
|
due_on: null,
|
||||||
|
days_overdue: null,
|
||||||
|
href: '/pessoas/' + (i + 1),
|
||||||
|
}));
|
||||||
|
const html = render(
|
||||||
|
PeopleReports,
|
||||||
|
{
|
||||||
|
deadlineReport: {
|
||||||
|
as_of: '2026-11-27',
|
||||||
|
window: 'all',
|
||||||
|
total_items: 35,
|
||||||
|
matching_processes: 35,
|
||||||
|
processes_considered: 35,
|
||||||
|
tasks: 35,
|
||||||
|
approvals: 0,
|
||||||
|
alerts: 0,
|
||||||
|
without_deadline: 35,
|
||||||
|
overdue_items: 0,
|
||||||
|
items,
|
||||||
|
pagination: page([]),
|
||||||
|
},
|
||||||
|
selectionMetrics: {},
|
||||||
|
applicationMetrics: {},
|
||||||
|
filters: { view: 'deadlines' },
|
||||||
|
kinds: ['staff', 'service'],
|
||||||
|
generatedAt: stamp,
|
||||||
|
summary: [],
|
||||||
|
processes: page([]),
|
||||||
|
},
|
||||||
|
'people',
|
||||||
|
);
|
||||||
|
for (const item of items) expect(html).toContain(item.reference);
|
||||||
|
expect(html).toContain('Sem prazo');
|
||||||
|
});
|
||||||
|
test.each([true, false])(
|
||||||
|
'warehouse preparation remains conditional on its existing permission (%s)',
|
||||||
|
(canPrepare) => {
|
||||||
|
const html = render(
|
||||||
|
WarehouseRequests,
|
||||||
|
{
|
||||||
|
filters: {
|
||||||
|
view: 'all',
|
||||||
|
state: '',
|
||||||
|
search: '',
|
||||||
|
warehouse_id: null,
|
||||||
|
},
|
||||||
|
views: [],
|
||||||
|
states: {},
|
||||||
|
checkedAt: stamp,
|
||||||
|
ready: true,
|
||||||
|
canPrepare,
|
||||||
|
items: [],
|
||||||
|
warehouses: [],
|
||||||
|
costCenters: [],
|
||||||
|
equipment: [],
|
||||||
|
records: page([]),
|
||||||
|
},
|
||||||
|
canPrepare ? 'warehouse' : 'warehouse-read',
|
||||||
|
);
|
||||||
|
expect(html.includes('Preparar rascunho')).toBe(canPrepare);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
test.each([true, false])(
|
||||||
|
'bank documentary editing remains conditional on its existing permission (%s)',
|
||||||
|
(canWrite) => {
|
||||||
|
const html = render(
|
||||||
|
BankSupport,
|
||||||
|
{
|
||||||
|
importRecord: { id: 5, record_key: 'synthetic', version: 1 },
|
||||||
|
order: { id: 2, number: 'OC-SINTETICA' },
|
||||||
|
current: page([]),
|
||||||
|
history: page([]),
|
||||||
|
documents: page([]),
|
||||||
|
types: { commitment: 'Termo sintetico' },
|
||||||
|
canWrite,
|
||||||
|
actorId: 1,
|
||||||
|
tenantId: 1,
|
||||||
|
today: '2026-11-27',
|
||||||
|
},
|
||||||
|
canWrite ? 'bank' : 'bank-read',
|
||||||
|
);
|
||||||
|
expect(html).toContain('Suporte documental bancário');
|
||||||
|
expect(html.includes('<form')).toBe(canWrite);
|
||||||
|
},
|
||||||
|
);
|
||||||
Reference in New Issue
Block a user