@@ -0,0 +1,39 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use App\Services\RequisitionExpiry;
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
|
final class RequisitionExpiryTick extends Command
|
||||||
|
{
|
||||||
|
protected $signature = 'sgc:approval-deadlines-tick';
|
||||||
|
|
||||||
|
protected $description = 'Conferir prazos configurados, avisos e devoluções de requisições';
|
||||||
|
|
||||||
|
public function handle(RequisitionExpiry $service): int
|
||||||
|
{
|
||||||
|
if (! $service->ready()) {
|
||||||
|
$this->warn('Extensão de prazos indisponível nesta composição.');
|
||||||
|
|
||||||
|
return self::FAILURE;
|
||||||
|
}
|
||||||
|
$checked = $failed = 0;
|
||||||
|
DB::table('requisitions')->where('status', 'pending')->whereNotNull('approval_snapshot->approval_expiry')->orderBy('id')->chunkById(100,
|
||||||
|
function ($requests) use ($service, &$checked, &$failed) {
|
||||||
|
foreach ($requests as $request) {
|
||||||
|
try {
|
||||||
|
$service->scheduled($request->id);
|
||||||
|
$checked++;
|
||||||
|
} catch (\Throwable $error) {
|
||||||
|
report($error);
|
||||||
|
$failed++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
$this->info('Prazos: '.$checked.' pedidos conferidos; '.$failed.' pendentes de recuperação.');
|
||||||
|
|
||||||
|
return $failed === 0 ? self::SUCCESS : self::FAILURE;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -59,4 +59,13 @@ final class RequisitionExpiryController extends Controller
|
|||||||
|
|
||||||
return back()->with('success', 'Pedido devolvido ao requisitante; decisões e reservas anteriores preservadas no histórico.');
|
return back()->with('success', 'Pedido devolvido ao requisitante; decisões e reservas anteriores preservadas no histórico.');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function check(Request $request, Requisition $requisition, RequisitionExpiry $service): Response
|
||||||
|
{
|
||||||
|
$result = $service->check($this->actor($request), $requisition, $request->all());
|
||||||
|
|
||||||
|
return back()->with('success', $result['action'] === 'returned'
|
||||||
|
? 'Prazo terminado: pedido devolvido ao requisitante.'
|
||||||
|
: 'Prazos conferidos; avisos devidos registados sem duplicação.');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ class WorkflowNoticeController extends Controller
|
|||||||
$unread = $visible->whereNull('read_at')->count();
|
$unread = $visible->whereNull('read_at')->count();
|
||||||
$items = ($filter['view'] ?? 'all') === 'unread' ? $visible->whereNull('read_at')->values() : $visible;
|
$items = ($filter['view'] ?? 'all') === 'unread' ? $visible->whereNull('read_at')->values() : $visible;
|
||||||
if (in_array($filter['view'] ?? '', ['tasks', 'outcomes'], true)) {
|
if (in_array($filter['view'] ?? '', ['tasks', 'outcomes'], true)) {
|
||||||
$items = $visible->where('kind', $filter['view'] === 'tasks' ? 'task' : 'outcome')->values();
|
$items = $filter['view'] === 'tasks' ? $visible->whereIn('kind', ['task', 'reminder'])->values() : $visible->where('kind', 'outcome')->values();
|
||||||
}
|
}
|
||||||
$search = trim($filter['search'] ?? '');
|
$search = trim($filter['search'] ?? '');
|
||||||
if ($search !== '') {
|
if ($search !== '') {
|
||||||
|
|||||||
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
namespace App\Models\Concerns;
|
namespace App\Models\Concerns;
|
||||||
|
|
||||||
|
use App\Services\ReplenishmentRun;
|
||||||
|
use App\Services\RequisitionExpiryRun;
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
|
|
||||||
trait BelongsToTenant
|
trait BelongsToTenant
|
||||||
@@ -9,7 +11,8 @@ trait BelongsToTenant
|
|||||||
protected static function bootBelongsToTenant(): void
|
protected static function bootBelongsToTenant(): void
|
||||||
{
|
{
|
||||||
static::addGlobalScope('tenant', function (Builder $query) {
|
static::addGlobalScope('tenant', function (Builder $query) {
|
||||||
$tenantId = auth()->check() ? auth()->user()->tenant_id : app(\App\Services\ReplenishmentRun::class)->tenantId();
|
$tenantId = auth()->check() ? auth()->user()->tenant_id : (app(ReplenishmentRun::class)->tenantId()
|
||||||
|
?? app(RequisitionExpiryRun::class)->tenantId());
|
||||||
$query->where($query->getModel()->qualifyColumn('tenant_id'), $tenantId ?? 0);
|
$query->where($query->getModel()->qualifyColumn('tenant_id'), $tenantId ?? 0);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ use App\Services\AdministrativeGeography;
|
|||||||
use App\Services\BudgetDistributionArtifact;
|
use App\Services\BudgetDistributionArtifact;
|
||||||
use App\Services\FinanceBundle;
|
use App\Services\FinanceBundle;
|
||||||
use App\Services\ReplenishmentRun;
|
use App\Services\ReplenishmentRun;
|
||||||
|
use App\Services\RequisitionExpiryRun;
|
||||||
use Carbon\CarbonImmutable;
|
use Carbon\CarbonImmutable;
|
||||||
use Illuminate\Support\Facades\Date;
|
use Illuminate\Support\Facades\Date;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
@@ -20,6 +21,7 @@ class AppServiceProvider extends ServiceProvider
|
|||||||
public function register(): void
|
public function register(): void
|
||||||
{
|
{
|
||||||
$this->app->singleton(ReplenishmentRun::class);
|
$this->app->singleton(ReplenishmentRun::class);
|
||||||
|
$this->app->singleton(RequisitionExpiryRun::class);
|
||||||
$this->app->scoped(AdministrativeGeography::class);
|
$this->app->scoped(AdministrativeGeography::class);
|
||||||
require_once base_path('packages/purchasing/bootstrap.php');
|
require_once base_path('packages/purchasing/bootstrap.php');
|
||||||
$package = config('common-budget.path');
|
$package = config('common-budget.path');
|
||||||
|
|||||||
@@ -12,7 +12,12 @@ class BudgetWorkflow
|
|||||||
/** @return array<string,mixed>|null */
|
/** @return array<string,mixed>|null */
|
||||||
public function record(User $user, Requisition $request, string $kind, int $amount = 0, ?int $subtotal = null, ?Quotation $quote = null): ?array
|
public function record(User $user, Requisition $request, string $kind, int $amount = 0, ?int $subtotal = null, ?Quotation $quote = null): ?array
|
||||||
{
|
{
|
||||||
abort_unless(auth()->id() === $user->id && $user->tenant_id !== null && $request->tenant_id === $user->tenant_id, 403);
|
$scheduled = app(RequisitionExpiryRun::class)->isActor($user);
|
||||||
|
abort_unless((auth()->id() === $user->id || $scheduled) && $user->tenant_id !== null && $request->tenant_id === $user->tenant_id, 403);
|
||||||
|
if ($scheduled) {
|
||||||
|
app(RequisitionExpiryRun::class)->assertRequest($request->id);
|
||||||
|
abort_unless($kind === 'release', 403);
|
||||||
|
}
|
||||||
if (DB::connection()->transactionLevel() === 0) {
|
if (DB::connection()->transactionLevel() === 0) {
|
||||||
throw new \LogicException('Movimentos de orçamento exigem transacção.');
|
throw new \LogicException('Movimentos de orçamento exigem transacção.');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,7 +28,14 @@ final class CommonBudget
|
|||||||
/** @param array<int,int> $cycles */
|
/** @param array<int,int> $cycles */
|
||||||
public function for(User $user, array $cycles = []): BudgetControl
|
public function for(User $user, array $cycles = []): BudgetControl
|
||||||
{
|
{
|
||||||
abort_unless(auth()->id() === $user->id && $user->tenant_id !== null, 403);
|
$deadlineRun = app(RequisitionExpiryRun::class);
|
||||||
|
abort_unless((auth()->id() === $user->id || $deadlineRun->isActor($user)) && $user->tenant_id !== null, 403);
|
||||||
|
if ($deadlineRun->tenantId() !== null) {
|
||||||
|
abort_unless($cycles !== [], 403);
|
||||||
|
foreach (array_keys($cycles) as $origin) {
|
||||||
|
$deadlineRun->assertRequest($origin);
|
||||||
|
}
|
||||||
|
}
|
||||||
$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;
|
$cycleRuntime = $runtime->hasConstant('REQUISITION_CYCLES_VERSION') && $runtime->getConstant('REQUISITION_CYCLES_VERSION') === self::REQUISITION_CYCLES_CONTRACT;
|
||||||
if (! $cycleRuntime) {
|
if (! $cycleRuntime) {
|
||||||
@@ -78,6 +85,9 @@ final class CommonBudget
|
|||||||
|
|
||||||
return new BudgetControl(DB::connection(), $context, '',
|
return new BudgetControl(DB::connection(), $context, '',
|
||||||
function (string $action) use ($user): void {
|
function (string $action) use ($user): void {
|
||||||
|
if (app(RequisitionExpiryRun::class)->tenantId() !== null) {
|
||||||
|
abort_unless(in_array($action, ['record', 'estimate.release'], true), 403);
|
||||||
|
}
|
||||||
app(ConflictGuard::class)->lockCompany($user);
|
app(ConflictGuard::class)->lockCompany($user);
|
||||||
abort_unless(DB::table('tenants')->where('id', $user->tenant_id)->value('currency') === 'MZN', 422, 'Moeda da organização incompatível com esta entrega.');
|
abort_unless(DB::table('tenants')->where('id', $user->tenant_id)->value('currency') === 'MZN', 422, 'Moeda da organização incompatível com esta entrega.');
|
||||||
$roles = in_array($action, ['create', 'approve', 'reinforcement.propose', 'reinforcement.review', 'view'], true)
|
$roles = in_array($action, ['create', 'approve', 'reinforcement.propose', 'reinforcement.review', 'view'], true)
|
||||||
|
|||||||
@@ -13,6 +13,11 @@ class CurrentActor
|
|||||||
*/
|
*/
|
||||||
public function lock(User $actor, ?array $roles = null): User
|
public function lock(User $actor, ?array $roles = null): User
|
||||||
{
|
{
|
||||||
|
if (app(RequisitionExpiryRun::class)->tenantId() !== null) {
|
||||||
|
abort_unless($roles === null, 403);
|
||||||
|
|
||||||
|
return app(RequisitionExpiryRun::class)->lock($actor);
|
||||||
|
}
|
||||||
abort_unless(auth()->id() === $actor->id && $actor->tenant_id !== null, 403);
|
abort_unless(auth()->id() === $actor->id && $actor->tenant_id !== null, 403);
|
||||||
if (DB::connection()->transactionLevel() === 0) {
|
if (DB::connection()->transactionLevel() === 0) {
|
||||||
throw new \LogicException('Revalidar o operador dentro da transacção.');
|
throw new \LogicException('Revalidar o operador dentro da transacção.');
|
||||||
|
|||||||
@@ -359,7 +359,7 @@ final class ImportLandedCosts
|
|||||||
abort_unless($this->equivalentPreparation($this->preview($actor, $current, $plan->data), $plan->snapshot['plan']), 409, 'As origens documentais mudaram. Prepare e confira uma nova versão.');
|
abort_unless($this->equivalentPreparation($this->preview($actor, $current, $plan->data), $plan->snapshot['plan']), 409, 'As origens documentais mudaram. Prepare e confira uma nova versão.');
|
||||||
}
|
}
|
||||||
$adapter = app(CommonBudget::class);
|
$adapter = app(CommonBudget::class);
|
||||||
$engine = $adapter->for($actor);
|
$engine = $adapter->for($actor, RequisitionExpiry::orderCycles($order));
|
||||||
$state = $adapter->execute(fn () => (new \ReflectionMethod($engine, 'landedCostState'))->invoke($engine, $plan->record_key));
|
$state = $adapter->execute(fn () => (new \ReflectionMethod($engine, 'landedCostState'))->invoke($engine, $plan->record_key));
|
||||||
abort_unless($data['financial_revision'] === (is_array($state) ? $state['result']['revision'] : 0), 409, 'A posição orçamental mudou; conserve a preparação e actualize antes de continuar.');
|
abort_unless($data['financial_revision'] === (is_array($state) ? $state['result']['revision'] : 0), 409, 'A posição orçamental mudou; conserve a preparação e actualize antes de continuar.');
|
||||||
abort_unless(! in_array($data['action'], ['reserve', 'amend'], true) || $data['sources'] === [], 422, 'A reserva e a reafectação usam a preparação conferida completa.');
|
abort_unless(! in_array($data['action'], ['reserve', 'amend'], true) || $data['sources'] === [], 422, 'A reserva e a reafectação usam a preparação conferida completa.');
|
||||||
|
|||||||
@@ -49,6 +49,10 @@ final class InternalRequisitionPort implements ExpiryRequisitionPort
|
|||||||
|
|
||||||
public function authorize(string $action, ?array $record): void
|
public function authorize(string $action, ?array $record): void
|
||||||
{
|
{
|
||||||
|
if (app(RequisitionExpiryRun::class)->tenantId() !== null) {
|
||||||
|
abort_unless(in_array($action, ['expire', 'view'], true) && $record !== null, 403);
|
||||||
|
app(RequisitionExpiryRun::class)->assertRequest($record['id']);
|
||||||
|
}
|
||||||
if ($this->automaticRule !== null) {
|
if ($this->automaticRule !== null) {
|
||||||
abort_unless($action === 'save' && $record === null, 403);
|
abort_unless($action === 'save' && $record === null, 403);
|
||||||
app(AutomaticPurchases::class)->requester($this->actor, $this->automaticRule);
|
app(AutomaticPurchases::class)->requester($this->actor, $this->automaticRule);
|
||||||
|
|||||||
@@ -34,6 +34,7 @@ final class RequisitionExpiry
|
|||||||
&& constant(BudgetControl::class.'::REQUISITION_CYCLES_VERSION') === CommonBudget::REQUISITION_CYCLES_CONTRACT
|
&& constant(BudgetControl::class.'::REQUISITION_CYCLES_VERSION') === CommonBudget::REQUISITION_CYCLES_CONTRACT
|
||||||
&& Schema::hasTable('budget_requisition_cycles') && Schema::hasColumn('requisitions', 'approval_cycle')
|
&& Schema::hasTable('budget_requisition_cycles') && Schema::hasColumn('requisitions', 'approval_cycle')
|
||||||
&& Schema::hasTable('workflow_notices') && Schema::hasTable('requisition_commands') && Schema::hasColumn('requisitions', 'process_version')
|
&& Schema::hasTable('workflow_notices') && Schema::hasTable('requisition_commands') && Schema::hasColumn('requisitions', 'process_version')
|
||||||
|
&& Schema::hasColumn('workflow_notices', 'event_kind')
|
||||||
&& Schema::hasColumn('approval_steps', 'approval_cycle') && Schema::hasColumn('budget_entries', 'requisition_cycle');
|
&& Schema::hasColumn('approval_steps', 'approval_cycle') && Schema::hasColumn('budget_entries', 'requisition_cycle');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -114,6 +115,7 @@ final class RequisitionExpiry
|
|||||||
return ['requisition' => [...$request->only(['id', 'number', 'status', 'process_version', 'requester_id']),
|
return ['requisition' => [...$request->only(['id', 'number', 'status', 'process_version', 'requester_id']),
|
||||||
'approval_cycle' => $request->getAttribute('approval_cycle') ?? 1], 'deadline' => $deadline, 'history' => $history,
|
'approval_cycle' => $request->getAttribute('approval_cycle') ?? 1], 'deadline' => $deadline, 'history' => $history,
|
||||||
'canExpire' => $deadline['state'] === 'expired' && ! app(ConflictGuard::class)->participationBlocked($actor, $request),
|
'canExpire' => $deadline['state'] === 'expired' && ! app(ConflictGuard::class)->participationBlocked($actor, $request),
|
||||||
|
'canCheck' => in_array($deadline['state'], ['running', 'expired'], true) && ! app(ConflictGuard::class)->participationBlocked($actor, $request),
|
||||||
'canEdit' => $request->status === 'draft' && (int) ($request->getAttribute('approval_cycle') ?? 1) > 1
|
'canEdit' => $request->status === 'draft' && (int) ($request->getAttribute('approval_cycle') ?? 1) > 1
|
||||||
&& $request->requester_id === $actor->id && app(OrganizationAccess::class)->canRequest($actor),
|
&& $request->requester_id === $actor->id && app(OrganizationAccess::class)->canRequest($actor),
|
||||||
'actorId' => $actor->id, 'tenantId' => $actor->tenant_id];
|
'actorId' => $actor->id, 'tenantId' => $actor->tenant_id];
|
||||||
@@ -312,4 +314,123 @@ final class RequisitionExpiry
|
|||||||
app(RequisitionWorkflow::class)->audit($actor, 'requisition.expired_returned', $request, $before,
|
app(RequisitionWorkflow::class)->audit($actor, 'requisition.expired_returned', $request, $before,
|
||||||
['status' => 'draft', 'cycle' => $cycle + 1, 'expiration_record_id' => $record->id, 'reason' => $proof['reason']]);
|
['status' => 'draft', 'cycle' => $cycle + 1, 'expiration_record_id' => $record->id, 'reason' => $proof['reason']]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Escalation is a recorded alert to configured, currently authorised viewers; it grants no decision authority.
|
||||||
|
* @param list<int> $profileIds
|
||||||
|
* @return list<User>
|
||||||
|
*/
|
||||||
|
public function escalationRecipients(Requisition $request, array $profileIds): array
|
||||||
|
{
|
||||||
|
if ($profileIds === [] || ! app(OrganizationAccess::class)->active($request->tenant_id)) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
$members = DB::table('organization_memberships as m')->join('organization_profiles as p', 'p.id', '=', 'm.profile_id')
|
||||||
|
->where('m.tenant_id', $request->tenant_id)->where('p.tenant_id', $request->tenant_id)->whereIn('p.id', $profileIds)
|
||||||
|
->where('m.maintenance', false)->where(fn ($q) => $q->whereNull('m.expires_at')->orWhere('m.expires_at', '>', now()))->select('m.user_id');
|
||||||
|
$result = [];
|
||||||
|
foreach (User::query()->where('tenant_id', $request->tenant_id)->where('id', '!=', $request->requester_id)->whereIn('id', $members)->orderBy('id')->get() as $person) {
|
||||||
|
if (app(WorkContext::class)->enforced($person) && ! DB::table('organization_memberships as m')->join('organization_profiles as p', 'p.id', '=', 'm.profile_id')
|
||||||
|
->where('m.tenant_id', $request->tenant_id)->where('p.tenant_id', $request->tenant_id)->where('m.user_id', $person->id)
|
||||||
|
->whereIn('p.id', $profileIds)->where('m.maintenance', false)->where(fn ($q) => $q->whereNull('m.expires_at')->orWhere('m.expires_at', '>', now()))
|
||||||
|
->whereJsonContains('p.work_contexts', 'procurement.internal')->exists()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (! app(OrganizationAccess::class)->maintenanceOnly($person) && app(OrganizationAccess::class)->permissions($person) !== []
|
||||||
|
&& Requisition::query()->visibleTo($person)->whereKey($request->id)->exists()) {
|
||||||
|
$result[] = $person;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array<string,mixed> $input
|
||||||
|
* @return array<string,mixed>
|
||||||
|
*/
|
||||||
|
public function check(User $actor, Requisition $request, array $input): array
|
||||||
|
{
|
||||||
|
abort_unless($this->ready(), 503);
|
||||||
|
$data = Validator::make($input, ['operation_key' => 'required|uuid', 'process_version' => 'required|integer|min:1'])->validate();
|
||||||
|
$data = ['operation_key' => strtolower($data['operation_key']), 'process_version' => (int) $data['process_version']];
|
||||||
|
$hash = hash('sha256', json_encode([$request->id, $data], JSON_THROW_ON_ERROR));
|
||||||
|
|
||||||
|
return DB::transaction(function () use ($actor, $request, $data, $hash) {
|
||||||
|
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)->lockForUpdate()->whereKey($request->id)->firstOrFail();
|
||||||
|
app(ConflictGuard::class)->assertParticipation($actor, $request);
|
||||||
|
$retry = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
|
||||||
|
if ($retry !== null) {
|
||||||
|
abort_unless($retry->kind === 'req_timeout_check' && $retry->created_by === $actor->id && hash_equals($retry->input_hash, $hash), 409);
|
||||||
|
|
||||||
|
return $retry->snapshot['result'];
|
||||||
|
}
|
||||||
|
abort_unless((int) $request->getAttribute('process_version') === $data['process_version'], 409, 'O pedido mudou. Reveja a etapa actual.');
|
||||||
|
$deadline = $this->deadline($request);
|
||||||
|
$result = ['action' => 'no_pending_deadline', 'notices_created' => 0];
|
||||||
|
if ($deadline['state'] === 'expired') {
|
||||||
|
$childOperation = (string) Str::uuid();
|
||||||
|
app(RequisitionWorkflow::class)->expire($actor, $request, $deadline['basis_hash'], $childOperation, $data['process_version']);
|
||||||
|
$result = ['action' => 'returned', 'notices_created' => 0, 'expiry_operation' => $childOperation];
|
||||||
|
} elseif ($deadline['state'] === 'running') {
|
||||||
|
$step = $request->steps()->whereKey($deadline['step_id'])->firstOrFail();
|
||||||
|
$created = 0;
|
||||||
|
if ($deadline['reminder_at'] !== null && now()->greaterThanOrEqualTo(CarbonImmutable::parse($deadline['reminder_at']))) {
|
||||||
|
$routing = app(ApprovalRouting::class)->current($request, $actor);
|
||||||
|
foreach ($routing['people'] as $person) {
|
||||||
|
$created += DB::table('workflow_notices')->insertOrIgnore(['tenant_id' => $request->tenant_id, 'requisition_id' => $request->id,
|
||||||
|
'approval_step_id' => $step->id, 'recipient_id' => $person['id'], 'reference' => $request->number,
|
||||||
|
'role' => $step->role, 'event_kind' => 'reminder', 'created_at' => now()]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$escalationEligible = null;
|
||||||
|
if ($deadline['escalation_at'] !== null && now()->greaterThanOrEqualTo(CarbonImmutable::parse($deadline['escalation_at']))) {
|
||||||
|
$people = $this->escalationRecipients($request, $deadline['profile_ids']);
|
||||||
|
$escalationEligible = count($people);
|
||||||
|
foreach ($people as $person) {
|
||||||
|
$created += DB::table('workflow_notices')->insertOrIgnore(['tenant_id' => $request->tenant_id, 'requisition_id' => $request->id,
|
||||||
|
'approval_step_id' => $step->id, 'recipient_id' => $person->id, 'reference' => $request->number,
|
||||||
|
'role' => $step->role, 'event_kind' => 'escalation', 'created_at' => now()]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$result = ['action' => 'deadline_checked', 'notices_created' => $created, 'escalation_eligible' => $escalationEligible];
|
||||||
|
}
|
||||||
|
$receipt = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'req_timeout_check', 'record_key' => (string) Str::uuid(),
|
||||||
|
'version' => 1, 'state' => 'checked', 'created_by' => $actor->id,
|
||||||
|
'data' => ['requisition_id' => $request->id, 'process_version' => $data['process_version']],
|
||||||
|
'snapshot' => ['result' => $result, 'deadline' => $deadline], 'reason' => 'Verificação dos prazos preservados na submissão.',
|
||||||
|
'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'created_at' => now()]);
|
||||||
|
app(RequisitionWorkflow::class)->audit($actor, 'requisition.timeout_checked', $request, null, ['receipt_id' => $receipt->id, 'result' => $result]);
|
||||||
|
|
||||||
|
return $result;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Execute only due work, so periodic checks do not accumulate empty receipts.
|
||||||
|
* @return array<string,mixed>
|
||||||
|
*/
|
||||||
|
public function scheduled(int $id): array
|
||||||
|
{
|
||||||
|
return app(RequisitionExpiryRun::class)->execute($id, function () use ($id) {
|
||||||
|
$request = Requisition::query()->whereKey($id)->firstOrFail();
|
||||||
|
$deadline = $this->deadline($request);
|
||||||
|
$due = $deadline['state'] === 'expired';
|
||||||
|
if ($deadline['state'] === 'running') {
|
||||||
|
foreach (['reminder' => 'reminder_at', 'escalation' => 'escalation_at'] as $kind => $field) {
|
||||||
|
if ($deadline[$field] !== null && now()->greaterThanOrEqualTo(CarbonImmutable::parse($deadline[$field]))
|
||||||
|
&& ! DB::table('workflow_notices')->where('tenant_id', $request->tenant_id)->where('approval_step_id', $deadline['step_id'])->where('event_kind', $kind)->exists()) {
|
||||||
|
$due = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (! $due) {
|
||||||
|
return ['action' => 'nothing_due'];
|
||||||
|
}
|
||||||
|
$actor = User::query()->whereKey($request->requester_id)->firstOrFail();
|
||||||
|
|
||||||
|
return $this->check($actor, $request, ['operation_key' => (string) Str::uuid(), 'process_version' => $request->getAttribute('process_version')]);
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services;
|
||||||
|
|
||||||
|
use App\Models\User;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
|
/** Narrow scheduled deadline execution, never a login or authority to approve. */
|
||||||
|
final class RequisitionExpiryRun
|
||||||
|
{
|
||||||
|
private ?int $tenant = null;
|
||||||
|
|
||||||
|
private ?int $request = null;
|
||||||
|
|
||||||
|
private ?int $owner = null;
|
||||||
|
|
||||||
|
public function tenantId(): ?int
|
||||||
|
{
|
||||||
|
return $this->tenant;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function isActor(User $actor): bool
|
||||||
|
{
|
||||||
|
return $this->tenant !== null && ! auth()->check() && $actor->tenant_id === $this->tenant && $actor->id === $this->owner;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function assertRequest(int $id): void
|
||||||
|
{
|
||||||
|
abort_unless($this->request === $id, 403);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function lock(User $actor): User
|
||||||
|
{
|
||||||
|
abort_unless($this->isActor($actor) && DB::transactionLevel() > 0, 403);
|
||||||
|
$source = DB::table('requisitions')->where('tenant_id', $this->tenant)->where('id', $this->request)->lockForUpdate()->firstOrFail();
|
||||||
|
abort_unless($source->requester_id === $this->owner, 403);
|
||||||
|
|
||||||
|
return User::query()->where('tenant_id', $this->tenant)->whereKey($this->owner)->lockForUpdate()->firstOrFail();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string,mixed> */
|
||||||
|
public function evidence(): array
|
||||||
|
{
|
||||||
|
return ['mode' => 'scheduled_approval_deadline', 'tenant_id' => $this->tenant, 'requisition_id' => $this->request,
|
||||||
|
'requester_id' => $this->owner, 'attribution' => 'request_owner_for_context_only; not_an_interactive_action'];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function execute(int $id, callable $callback): mixed
|
||||||
|
{
|
||||||
|
abort_unless(app(RequisitionExpiry::class)->ready() && app()->runningInConsole() && ! auth()->check()
|
||||||
|
&& ! request()->hasSession() && $this->tenant === null && app(ReplenishmentRun::class)->tenantId() === null, 403);
|
||||||
|
$source = DB::table('requisitions')->where('id', $id)->where('status', 'pending')->firstOrFail();
|
||||||
|
$this->tenant = $source->tenant_id;
|
||||||
|
$this->request = $source->id;
|
||||||
|
$this->owner = $source->requester_id;
|
||||||
|
try {
|
||||||
|
return $callback();
|
||||||
|
} finally {
|
||||||
|
$this->tenant = $this->request = $this->owner = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -183,10 +183,13 @@ class RequisitionWorkflow
|
|||||||
*/
|
*/
|
||||||
public function audit(User $user, string $action, ?Requisition $requisition, ?array $before, array $after): void
|
public function audit(User $user, string $action, ?Requisition $requisition, ?array $before, array $after): void
|
||||||
{
|
{
|
||||||
|
if (app(RequisitionExpiryRun::class)->tenantId() !== null) {
|
||||||
|
$after += ['execution' => app(RequisitionExpiryRun::class)->evidence()];
|
||||||
|
}
|
||||||
AuditLog::query()->create([
|
AuditLog::query()->create([
|
||||||
'tenant_id' => $user->tenant_id, 'user_id' => $user->id,
|
'tenant_id' => $user->tenant_id, 'user_id' => $user->id,
|
||||||
'requisition_id' => $requisition?->id, 'action' => $action,
|
'requisition_id' => $requisition?->id, 'action' => $action,
|
||||||
'ip_address' => app(ReplenishmentRun::class)->tenantId() === null ? request()->ip() : null, 'before' => $before, 'after' => $after + (app(ReplenishmentRun::class)->tenantId() === null ? [] : ['execution' => app(ReplenishmentRun::class)->evidence()]),
|
'ip_address' => app(ReplenishmentRun::class)->tenantId() === null && app(RequisitionExpiryRun::class)->tenantId() === null ? request()->ip() : null, 'before' => $before, 'after' => $after + (app(ReplenishmentRun::class)->tenantId() === null ? [] : ['execution' => app(ReplenishmentRun::class)->evidence()]),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -111,12 +111,20 @@ class WorkflowNotices
|
|||||||
}
|
}
|
||||||
$step = $request->steps->firstWhere('id', $notice->approval_step_id)
|
$step = $request->steps->firstWhere('id', $notice->approval_step_id)
|
||||||
?? $request->allSteps()->whereKey($notice->approval_step_id)->first();
|
?? $request->allSteps()->whereKey($notice->approval_step_id)->first();
|
||||||
|
$event = $notice->event_kind ?? 'task';
|
||||||
|
if ($event === 'escalation') {
|
||||||
|
$deadline = app(RequisitionExpiry::class)->deadline($request);
|
||||||
|
if ($deadline['state'] !== 'running' || $deadline['step_id'] !== $notice->approval_step_id
|
||||||
|
|| ! collect(app(RequisitionExpiry::class)->escalationRecipients($request, $deadline['profile_ids']))->contains('id', $actor->id)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
$outcome = $request->requester_id === $actor->id && $step !== null && in_array($step->decision, ['approved', 'rejected', 'expired'], true);
|
$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 ($event !== 'escalation' && ! $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' : ($event === 'task' ? 'task' : $event), 'outcome' => $outcome ? $step->decision : null, 'current_status' => $request->status,
|
||||||
'created_at' => $notice->created_at, 'read_at' => $notice->read_at, 'href' => '/requisicoes/'.$request->id.($outcome && $step->decision === 'expired' ? '/prazos' : '')];
|
'created_at' => $notice->created_at, 'read_at' => $notice->read_at, 'href' => '/requisicoes/'.$request->id.($outcome && $step->decision === 'expired' ? '/prazos' : '')];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ return new class extends Migration
|
|||||||
}
|
}
|
||||||
$schema = $db->getSchemaBuilder();
|
$schema = $db->getSchemaBuilder();
|
||||||
if ($schema->hasTable('budget_requisition_cycles') || $schema->hasColumn('requisitions', 'approval_cycle')
|
if ($schema->hasTable('budget_requisition_cycles') || $schema->hasColumn('requisitions', 'approval_cycle')
|
||||||
|| $schema->hasColumn('budget_entries', 'requisition_cycle')) {
|
|| $schema->hasColumn('budget_entries', 'requisition_cycle') || $schema->hasColumn('workflow_notices', 'event_kind')) {
|
||||||
throw new LogicException('Do not reinstall or repair partial cycle structures automatically.');
|
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('requisitions', fn (Blueprint $table) => $table->unsignedInteger('approval_cycle')->default(1));
|
||||||
@@ -31,6 +31,11 @@ return new class extends Migration
|
|||||||
$table->dropUnique(['requisition_id', 'kind']);
|
$table->dropUnique(['requisition_id', 'kind']);
|
||||||
$table->unique(['requisition_id', 'requisition_cycle', 'kind'], 'budget_entry_cycle_kind');
|
$table->unique(['requisition_id', 'requisition_cycle', 'kind'], 'budget_entry_cycle_kind');
|
||||||
});
|
});
|
||||||
|
$schema->table('workflow_notices', function (Blueprint $table) {
|
||||||
|
$table->string('event_kind', 20)->default('task');
|
||||||
|
$table->dropUnique(['approval_step_id', 'recipient_id']);
|
||||||
|
$table->unique(['approval_step_id', 'recipient_id', 'event_kind'], 'workflow_notice_event_recipient');
|
||||||
|
});
|
||||||
if ($schema->hasTable('budget_distributions')) {
|
if ($schema->hasTable('budget_distributions')) {
|
||||||
$schema->table('budget_distributions', function (Blueprint $table) {
|
$schema->table('budget_distributions', function (Blueprint $table) {
|
||||||
$table->unsignedInteger('requisition_cycle')->default(1);
|
$table->unsignedInteger('requisition_cycle')->default(1);
|
||||||
|
|||||||
@@ -1,5 +1,15 @@
|
|||||||
# Desenvolvimento do SGC
|
# Desenvolvimento do SGC
|
||||||
|
|
||||||
|
## Conferência adicional e impressão multipágina — 27/11/2026
|
||||||
|
|
||||||
|
Conferidos em apresentação isolada os formulários de armazém e suporte documental bancário (edição/consulta), relatórios de Pessoas, melhorias de fornecedores e conferência. Dados inteiramente sintéticos; a390px não foi observado transbordo da página; apresentação de melhorias também observada a1280px. Não demonstra gravações nativas ou validação de servidor nesses cenários.
|
||||||
|
|
||||||
|
Corrigida omissão confirmada de resultados/evidências na impressão quando os detalhes estavam fechados: `PrintableDetails` conserva os detalhes fechados no ecrã e apresenta o mesmo conteúdo autorizado numa vista exclusiva de impressão. Três relatórios largos usam página A4 horizontal, tabelas a9pt, espaçamento compacto e navegação de ecrã oculta na impressão. O relatório de conferência usa fluxo de impressão em bloco e conserva a secção final com a sua nota financeira. Sem alteração de campos, handlers de negócio, regras, dados ou permissões.
|
||||||
|
|
||||||
|
PDFs reais gerados pelo navegador, extraídos com pypdf/pdfplumber e páginas rasterizadas/inspeccionadas: melhorias9páginas/30medidas/30resultados/30evidências (antes, zero evidências impressas); conferência10páginas/30propostas; Pessoas3páginas/35ocorrências. Sem linhas em falta ou palavras fora dos limites; cabeçalhos repetidos nas páginas das tabelas. Dados complementares do relatório de conferência não são tratados como linhas repetidas da tabela. Prova `proofs/screen-print-review-qa.json`; exemplares sintéticos em `output/pdf/sgc-*-after.pdf`.
|
||||||
|
|
||||||
|
Verificação dirigida17testes e regressão da conferência10testes aprovadas (sobrepostas); tipos, formato/lint e build privado aprovados. Bateria geral199/200: falha de ajuda contextual nas páginas paralelas `organization/approval-timeouts` e `requisitions/expiry`, já presentes antes deste bloco e não alteradas pela conferência. Não enfraquecido o teste nem declarada aprovação geral. Servidor privado encerrado, separadores temporários fechados e viewport reposto. `public/build` mantém a data22/11; nenhuma publicação em `compras.tempo.co.mz`. A validação nativa integral e a publicação controlada permanecem etapas distintas.
|
||||||
|
|
||||||
## Uniformização dos formulários e relatórios — 27/11/2026
|
## 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.
|
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.
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
# Matriz reconciliada do SGC — 03/11/2026
|
# Matriz reconciliada do SGC — 03/11/2026
|
||||||
|
|
||||||
|
**Delta de impressão e conferência — 27/11/2026:** provas adicionais de armazém/importação documental e relatórios (Pessoas/melhorias/conferência), em pré-visualização sintética. Impressão real do navegador verificada em9/10/3páginas, sem linhas em falta ou texto fora das páginas; resultados/evidências anteriormente omitidos agora presentes, estado de expansão do ecrã conservado. Relatórios largos emA4horizontal e navegação de ecrã excluída da impressão.17testes dirigidos aprovados; bateria geral199/200 devido às guias ausentes de `organization/approval-timeouts` e `requisitions/expiry` do trabalho paralelo. Tipos/lint/build privado aprovados. Isto reduz a pendência multipágina nestes três relatórios, não declara revisão nativa integral ou publicação. `proofs/screen-print-review-qa.json`.
|
||||||
|
|
||||||
**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.
|
**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.
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
# Continuidade do desenvolvimento do SGC
|
# Continuidade do desenvolvimento do SGC
|
||||||
|
|
||||||
|
**27/11/2026 — conferência adicional/impressão:** armazém e suporte bancário (edição/consulta), Pessoas, melhorias e conferência revistos com dados sintéticos. Corrigida a omissão de resultados/evidências fechados no ecrã; PDFs de9/10/3páginas preservam30medidas/30propostas/35ocorrências, com cabeçalhos e limites conferidos. A4horizontal para relatórios largos, paginação de ecrã oculta e nota final agrupada. Prova `proofs/screen-print-review-qa.json`. Dirigidos aprovados, tipos/lint/build privado aprovados; bateria geral199/200 por falta de ajuda das duas páginas de expiração do trabalho paralelo. Não repetir tentativas do mesmo erro sem actualizar essas guias; não alterar fluxos financeiros para o resolver. Sem gravações de negócio, assets operacionais actualizados ou publicação. Conferência nativa integral e implantação do domínio ainda pendentes de âmbito próprio.
|
||||||
|
|
||||||
**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.
|
**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.
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# Preparação de publicação das correcções de apresentação
|
||||||
|
|
||||||
|
27/11/2026 — preparado, sem publicação ou alteração operacional.
|
||||||
|
|
||||||
|
Pacote privado: `storage/app/private/screen-publication-20261127.zip`.
|
||||||
|
SHA-256: `1516aecb24798df8e86d785fc64b45e1e636add1cdcb0360ac5f417c963b5ba3`.
|
||||||
|
Patch SHA-256: `6b9f64331fa3732927d0344eb9a72d89fd5164c2a119f0f6955494e684a69ba5`.
|
||||||
|
|
||||||
|
O pacote contém README com procedimento e recuperação, manifesto por ficheiro, verificador de integridade, patch delimitado e as duas provas anteriores. Inclui 33 fontes de apresentação e dois testes. Sem backend, rotas, migrações, configuração, dados, acessos, módulos financeiros ou conector. As adições paralelas de expiração em dois ficheiros partilhados foram excluídas; os 35 conteúdos seleccionados correspondem exactamente aos hashes das provas aceites. O trabalho original foi preservado.
|
||||||
|
|
||||||
|
Aplicação, verificação dos hashes, reversão exacta e reaplicação ensaiadas numa cópia local dos ficheiros de base, sem base de dados. Este ensaio não simula uma release integral nem a troca do link operacional. Provas anteriores de apresentação continuam válidas para esses conteúdos; não se repetiu a bateria da árvore mista.
|
||||||
|
|
||||||
|
Base técnica do delta: `930064269e48fbc0d1a814a6dacbcdbfc5d211d3`; não se afirma que corresponda à versão actualmente instalada em compras.tempo.co.mz. O destino histórico `/var/www/compras-deploy/current` e o seu commit/manifesto precisam de confirmação em leitura antes da decisão de instalação. O publicador existente que recolhe toda a main não é adequado para este recorte.
|
||||||
|
|
||||||
|
Não foram incluídos builds da árvore mista. Antes de autorizar publicação é necessário reproduzir a release activa, verificar os hashes anteriores sem forçar conflitos, compilar e validar o build delimitado nessa reprodução e ensaiar a recuperação dos assets/release. A reversão de código/assets não é reversão de dados; este pacote não altera schema/dados e não prevê migrate:rollback ou restauro automático da base.
|
||||||
|
|
||||||
|
Procedimento detalhado no README privado do pacote. Domínio, public/build local, configurações, dados, permissões e SGF não foram alterados nesta preparação. A próxima etapa recomendada é identificar em leitura a release instalada e fechar a compatibilidade e o artefacto compilado, antes da autorização de publicação.
|
||||||
|
|
||||||
|
## Tentativa de confirmação da release activa — 27/11/2026
|
||||||
|
|
||||||
|
O utilizador autorizou consultar a versão activa e compilar/validar uma reprodução isolada, mantendo a publicação excluída. A consulta SSH em leitura pelo domínio terminou com timeout na porta 22. A ligação ao endereço já presente em known_hosts chegou ao servidor, mas a identidade mario não foi autenticada (`Permission denied (publickey,password)`). Não foram tentadas outras contas nem alterados acessos.
|
||||||
|
|
||||||
|
Estado: bloqueado na identificação da release activa; nenhum comando remoto foi executado com sucesso. Os dados históricos da release não constituem confirmação actual. A compilação sobre a reprodução dessa release não foi executada, pois não existe ainda uma origem confirmada. O pacote anterior permanece intacto, com o SHA-256 acima conferido novamente. Não houve publicação, cópia de dados reais, alteração de configuração, base, direitos ou assets operacionais.
|
||||||
|
|
||||||
|
Para retomar: indicar a ligação administrativa já autorizada (host/alias, utilizador e porta, com autenticação existente), sem enviar segredos no chat; em alternativa fornecer uma exportação apenas do código da release activa, incluindo commit e hashes do manifesto/ficheiros abrangidos, excluindo .env, storage privado e dados reais. Após acesso confirmado, retomar a reprodução isolada e as verificações previstas, sem repetir as tentativas falhadas sem mudança de condição.
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
{
|
||||||
|
"date": "2026-11-27",
|
||||||
|
"status": "implemented_in_isolated_qa_integration_and_acceptance_in_progress",
|
||||||
|
"authorization": "requisition-expiry-contract-authorization.json",
|
||||||
|
"behaviour_verified": [
|
||||||
|
"Same requisition returned to requester draft; prior approved decisions and item amounts preserved",
|
||||||
|
"Old cycle reservation released by the existing financial writer; revised submission reserves independently",
|
||||||
|
"Current-cycle eager approval relation and immutable history remain distinct",
|
||||||
|
"Ordinary, distributed and import-estimate reservations retain separate cycle identities",
|
||||||
|
"Company-defined elapsed-minute policy frozen on submission; later policy changes do not rewrite it",
|
||||||
|
"Native HTTP expiry and due-action checks replay without duplicate effects",
|
||||||
|
"Reminder receipts are unique per current step and recipient",
|
||||||
|
"Escalation alert recipients require currently valid configured membership and native visibility; no approval grant",
|
||||||
|
"Partial native orders commit forty then sixty in both first and second cycles",
|
||||||
|
"Old installed financial runtime refuses balances with status 503 after a new cycle"
|
||||||
|
],
|
||||||
|
"verification": {
|
||||||
|
"focused_postgresql": {"tests": 7, "assertions": 78, "passed": true},
|
||||||
|
"submission_budget_regression": {"tests": 40, "assertions": 723, "passed": true, "note": "Before the added seventh escalation test; not additive with focused tests"},
|
||||||
|
"import_regression": {"tests": 24, "assertions": 189, "passed": true},
|
||||||
|
"order_regression": {"tests": 8, "assertions": 268, "passed": true},
|
||||||
|
"partial_order_two_cycles": {"tests": 2, "assertions": 60, "passed": true, "note": "Covered by order regression"},
|
||||||
|
"frontend": {"tests": 2, "passed": true},
|
||||||
|
"concurrency": {
|
||||||
|
"same_operation": {"statuses": [200, 200], "blocked_writers": 2},
|
||||||
|
"different_operations": {"statuses": [200, 409], "blocked_writers": 2},
|
||||||
|
"late_decision": {"statuses": [200, 409], "blocked_writers": 2},
|
||||||
|
"each_scenario": {"returns": 1, "reserve_minor": 0, "late_approvals": 0},
|
||||||
|
"old_runtime": {"status": 503, "before_balance_or_effects": true},
|
||||||
|
"disposable_database_removed": true
|
||||||
|
},
|
||||||
|
"phpstan": "passed before final contention-helper changes",
|
||||||
|
"typescript": "passed",
|
||||||
|
"pint": "passed on edited host files; shared-source final check pending",
|
||||||
|
"oversized_regression_attempt": "No result claimed: exceeded 180 seconds; replaced with independently isolated focused groups"
|
||||||
|
},
|
||||||
|
"remaining": [
|
||||||
|
"Verified pre/post extension backup and restoration of complete cycle data",
|
||||||
|
"Private portable artifact and native administrator/requester visual review",
|
||||||
|
"Scheduled execution with narrow documented identity and tenant context, without impersonation",
|
||||||
|
"Final shared-source checks and final delta review",
|
||||||
|
"Remaining application requirements in the existing matrix"
|
||||||
|
],
|
||||||
|
"operational_installation": false,
|
||||||
|
"pilot_migration_or_activation": false,
|
||||||
|
"sgf_operational_changes": false,
|
||||||
|
"real_data_or_permission_changes": false
|
||||||
|
}
|
||||||
@@ -0,0 +1,221 @@
|
|||||||
|
{
|
||||||
|
"date": "2026-11-27",
|
||||||
|
"scope": "isolated synthetic presentation and multi-page browser PDF verification",
|
||||||
|
"screen_review": {
|
||||||
|
"widths": [
|
||||||
|
390,
|
||||||
|
1280
|
||||||
|
],
|
||||||
|
"warehouse_prepare_and_read": true,
|
||||||
|
"bank_prepare_and_read": true,
|
||||||
|
"people_report": true,
|
||||||
|
"comparison_report": true,
|
||||||
|
"supplier_improvements": true,
|
||||||
|
"full_native_business_interaction": false
|
||||||
|
},
|
||||||
|
"fixes": [
|
||||||
|
"Print authorised result/evidence even when on-screen details remain collapsed",
|
||||||
|
"A4 landscape and compact table spacing for wide reports",
|
||||||
|
"Hide screen navigation in printed wide reports",
|
||||||
|
"Group the fulfilment section with its final finance visibility note"
|
||||||
|
],
|
||||||
|
"baseline": {
|
||||||
|
"improvement_pages": 4,
|
||||||
|
"measure_rows": 30,
|
||||||
|
"printed_evidence": 0
|
||||||
|
},
|
||||||
|
"final_pdfs": {
|
||||||
|
"improvements": {
|
||||||
|
"pages": 9,
|
||||||
|
"rows": 30,
|
||||||
|
"missing_rows": [],
|
||||||
|
"table_pages": [
|
||||||
|
2,
|
||||||
|
3,
|
||||||
|
4,
|
||||||
|
5,
|
||||||
|
6,
|
||||||
|
7,
|
||||||
|
8,
|
||||||
|
9
|
||||||
|
],
|
||||||
|
"missing_headers": [],
|
||||||
|
"outside_page": [
|
||||||
|
{
|
||||||
|
"page": 1,
|
||||||
|
"count": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"page": 2,
|
||||||
|
"count": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"page": 3,
|
||||||
|
"count": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"page": 4,
|
||||||
|
"count": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"page": 5,
|
||||||
|
"count": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"page": 6,
|
||||||
|
"count": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"page": 7,
|
||||||
|
"count": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"page": 8,
|
||||||
|
"count": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"page": 9,
|
||||||
|
"count": 0
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"review": {
|
||||||
|
"pages": 10,
|
||||||
|
"rows": 30,
|
||||||
|
"missing_rows": [],
|
||||||
|
"table_pages": [
|
||||||
|
2,
|
||||||
|
3,
|
||||||
|
4,
|
||||||
|
5,
|
||||||
|
6
|
||||||
|
],
|
||||||
|
"missing_headers": [],
|
||||||
|
"outside_page": [
|
||||||
|
{
|
||||||
|
"page": 1,
|
||||||
|
"count": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"page": 2,
|
||||||
|
"count": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"page": 3,
|
||||||
|
"count": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"page": 4,
|
||||||
|
"count": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"page": 5,
|
||||||
|
"count": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"page": 6,
|
||||||
|
"count": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"page": 7,
|
||||||
|
"count": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"page": 8,
|
||||||
|
"count": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"page": 9,
|
||||||
|
"count": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"page": 10,
|
||||||
|
"count": 0
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"people": {
|
||||||
|
"pages": 3,
|
||||||
|
"rows": 35,
|
||||||
|
"missing_rows": [],
|
||||||
|
"table_pages": [
|
||||||
|
1,
|
||||||
|
2,
|
||||||
|
3
|
||||||
|
],
|
||||||
|
"missing_headers": [],
|
||||||
|
"outside_page": [
|
||||||
|
{
|
||||||
|
"page": 1,
|
||||||
|
"count": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"page": 2,
|
||||||
|
"count": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"page": 3,
|
||||||
|
"count": 0
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"validation": {
|
||||||
|
"directed_tests": 17,
|
||||||
|
"directed_passed": true,
|
||||||
|
"report_regression_tests": 10,
|
||||||
|
"report_regression_passed": true,
|
||||||
|
"counts_overlap": true,
|
||||||
|
"full_frontend_tests": 200,
|
||||||
|
"full_frontend_passed": 199,
|
||||||
|
"full_frontend_failed": 1,
|
||||||
|
"failure": "journey-help: missing guides for organization/approval-timeouts and requisitions/expiry from parallel work, present before this task; not changed or suppressed",
|
||||||
|
"typescript": "passed",
|
||||||
|
"scoped_format_lint": "passed",
|
||||||
|
"private_build": "passed"
|
||||||
|
},
|
||||||
|
"private_build": "storage/framework/testing/sgc-screen-review-20261127/assets",
|
||||||
|
"private_build_manifest_sha256": "5cdbb3bdd27379ba55a32c676ebf791fd90c0a3e89f5c384fea3ea7b98084cd7",
|
||||||
|
"visual": {
|
||||||
|
"pdf_pages_rendered_with": "Poppler",
|
||||||
|
"text_and_bounds_checked_with": [
|
||||||
|
"pypdf",
|
||||||
|
"pdfplumber"
|
||||||
|
],
|
||||||
|
"contact_sheets_inspected": true,
|
||||||
|
"final_finance_section_page_inspected": true
|
||||||
|
},
|
||||||
|
"preserved": {
|
||||||
|
"business_data": true,
|
||||||
|
"permissions": true,
|
||||||
|
"operational_migrations": false,
|
||||||
|
"connector_activation": false,
|
||||||
|
"pilot_public_build_updated": false,
|
||||||
|
"domain_published": false,
|
||||||
|
"parallel_work": true
|
||||||
|
},
|
||||||
|
"cleanup": {
|
||||||
|
"preview_server_stopped": true,
|
||||||
|
"temporary_browser_tabs_closed": true,
|
||||||
|
"viewport_reset": true
|
||||||
|
},
|
||||||
|
"artifacts": {
|
||||||
|
"output/pdf/sgc-improvements-after.pdf": "9cacc9d41db96d83a6e870240296ca8c5b2e2a1532d026f444463b72c8d5ae32",
|
||||||
|
"output/pdf/sgc-review-after.pdf": "b17fda913fb0431dbdad8c8216a27c9426e520764aeae1e5d734afaf7e797899",
|
||||||
|
"output/pdf/sgc-people-after.pdf": "8d349187cde738e44cc1fc97c79637444a6925b7d6ee532fdfd37f5649cf0e28"
|
||||||
|
},
|
||||||
|
"source_hashes": {
|
||||||
|
"resources/css/app.css": "52ca693f9162c040ac77a529d4886a0166a292947d5faa05f2462b3c5b0fe0a5",
|
||||||
|
"resources/js/components/procurement.tsx": "3a81c1b791ef8036d7ebb1044c4c3d6319ca7428dedd7cc2489b4e48e23791cb",
|
||||||
|
"resources/js/pages/purchases/review-report.tsx": "d2cc4adb194fe5064026304a88c1e1ec9d5671a69c02dff041f72e768fbd1517",
|
||||||
|
"resources/js/pages/reports/supplier-improvements.tsx": "9901f8d41d8a81267d22a25154fd5c9ee07215773190b3e21c88715e22fbeca7",
|
||||||
|
"resources/js/pages/reports/procurement.tsx": "e115c96877d907c7265eb0c5a5c168e5ed9c401e04fe512b853f13f0a2065876",
|
||||||
|
"resources/js/pages/people/reports.tsx": "583249241cc6c2535384ece670900318e2b6e466e21aa197f8fb3bf3d5cc0867",
|
||||||
|
"tests/frontend/screen-review.test.tsx": "c850b1c72c06f295a5c22caa44075ccbeefe747833360d535a33b008c1b50374"
|
||||||
|
},
|
||||||
|
"remaining": [
|
||||||
|
"Native end-to-end validation across all remaining screens",
|
||||||
|
"Contextual help in parallel expiry work",
|
||||||
|
"Prepare and separately authorise deployment excluding unrelated changes"
|
||||||
|
]
|
||||||
|
}
|
||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -206,3 +206,28 @@
|
|||||||
overflow-wrap: anywhere;
|
overflow-wrap: anywhere;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@page sgc-wide-report {
|
||||||
|
size: A4 landscape;
|
||||||
|
margin: 12mm;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media print {
|
||||||
|
.sgc-wide-report {
|
||||||
|
page: sgc-wide-report;
|
||||||
|
max-width: none;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sgc-wide-report table {
|
||||||
|
font-size: 9pt;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sgc-wide-report :is(th, td) {
|
||||||
|
padding: 6px 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sgc-wide-report nav {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -126,7 +126,7 @@ export default function Reports(props: Props) {
|
|||||||
'@media print { .people-report-tools { display: none !important; } }'
|
'@media print { .people-report-tools { display: none !important; } }'
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
<div className="space-y-6 p-6">
|
<div className="sgc-wide-report space-y-6 p-6">
|
||||||
<PageTitle
|
<PageTitle
|
||||||
eyebrow="Pessoas e contratações"
|
eyebrow="Pessoas e contratações"
|
||||||
title="Relatórios"
|
title="Relatórios"
|
||||||
|
|||||||
@@ -191,7 +191,7 @@ export default function ReviewReport({
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Head title={`Relatório de conferência · ${r.number}`} />
|
<Head title={`Relatório de conferência · ${r.number}`} />
|
||||||
<style>{`@media print { @page { size: A4 landscape; margin: 14mm; } .review-report { max-width: none; padding: 0; font-size: 11px; gap: 18px; } .review-report section { box-shadow: none; } .review-report table { font-size: 10px; table-layout: fixed; width: 100%; } .review-report th, .review-report td { overflow-wrap: anywhere; } .review-report thead { display: table-header-group; } .review-report tr { break-inside: avoid; } .review-report h2, .review-report h3 { break-after: avoid; } }`}</style>
|
<style>{`@media print { @page { size: A4 landscape; margin: 14mm; } .review-report { display: block; max-width: none; padding: 0; font-size: 11px; } .review-report > * + * { margin-top: 18px; } .review-report section { box-shadow: none; } .review-report #report-fulfilment { break-inside: avoid; } .review-report table { font-size: 10px; table-layout: fixed; width: 100%; } .review-report th, .review-report td { overflow-wrap: anywhere; } .review-report thead { display: table-header-group; } .review-report tr { break-inside: avoid; } .review-report h2, .review-report h3 { break-after: avoid; } }`}</style>
|
||||||
<div className="review-report mx-auto flex max-w-7xl flex-col gap-6 p-5 lg:p-8">
|
<div className="review-report mx-auto flex max-w-7xl flex-col gap-6 p-5 lg:p-8">
|
||||||
<header className="hidden border-b-2 border-[#ed1c24] pb-3 print:block">
|
<header className="hidden border-b-2 border-[#ed1c24] pb-3 print:block">
|
||||||
<p className="font-semibold">
|
<p className="font-semibold">
|
||||||
|
|||||||
@@ -94,7 +94,7 @@ export default function ProcurementReports({
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Head title="Relatórios de compras" />
|
<Head title="Relatórios de compras" />
|
||||||
<div className="mx-auto max-w-7xl space-y-6 px-5 py-8 lg:px-8">
|
<div className="sgc-wide-report mx-auto max-w-7xl space-y-6 px-5 py-8 lg:px-8">
|
||||||
<PageTitle
|
<PageTitle
|
||||||
eyebrow="Consulta e relatórios"
|
eyebrow="Consulta e relatórios"
|
||||||
title="Relatórios de compras"
|
title="Relatórios de compras"
|
||||||
|
|||||||
@@ -98,7 +98,7 @@ export default function SupplierImprovementReport({
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Head title="Medidas de melhoria de fornecedores" />
|
<Head title="Medidas de melhoria de fornecedores" />
|
||||||
<div className="mx-auto max-w-7xl space-y-6 px-5 py-8 lg:px-8">
|
<div className="sgc-wide-report mx-auto max-w-7xl space-y-6 px-5 py-8 lg:px-8">
|
||||||
<PageTitle
|
<PageTitle
|
||||||
eyebrow="Relatórios · Fornecedores"
|
eyebrow="Relatórios · Fornecedores"
|
||||||
title="Medidas de melhoria"
|
title="Medidas de melhoria"
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
import { Head, Link, router, useForm } from '@inertiajs/react';
|
import { Head, Link, router, useForm } from "@inertiajs/react";
|
||||||
import { useEffect, useRef } from 'react';
|
import { useEffect, useRef } from "react";
|
||||||
import {
|
import {
|
||||||
FormErrors,
|
FormErrors,
|
||||||
PageTitle,
|
PageTitle,
|
||||||
Panel,
|
Panel,
|
||||||
controlClass,
|
controlClass,
|
||||||
} from '@/components/procurement';
|
} from "@/components/procurement";
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from "@/components/ui/button";
|
||||||
|
|
||||||
type Deadline = {
|
type Deadline = {
|
||||||
state: string;
|
state: string;
|
||||||
@@ -27,6 +27,7 @@ type Props = {
|
|||||||
};
|
};
|
||||||
deadline: Deadline;
|
deadline: Deadline;
|
||||||
canExpire: boolean;
|
canExpire: boolean;
|
||||||
|
canCheck: boolean;
|
||||||
canEdit: boolean;
|
canEdit: boolean;
|
||||||
actorId: number;
|
actorId: number;
|
||||||
tenantId: number;
|
tenantId: number;
|
||||||
@@ -48,36 +49,40 @@ type Props = {
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
const labels: Record<string, string> = {
|
const labels: Record<string, string> = {
|
||||||
inactive: 'Sem etapa pendente',
|
inactive: "Sem etapa pendente",
|
||||||
unconfigured: 'Sem prazo configurado',
|
unconfigured: "Sem prazo configurado",
|
||||||
unverified: 'Datas por conferir',
|
unverified: "Datas por conferir",
|
||||||
running: 'Em prazo',
|
running: "Em prazo",
|
||||||
expired: 'Prazo terminado',
|
expired: "Prazo terminado",
|
||||||
};
|
};
|
||||||
const time = (value?: string | null) =>
|
const time = (value?: string | null) =>
|
||||||
value ? new Date(value).toLocaleString('pt-MZ') : 'Por indicar';
|
value ? new Date(value).toLocaleString("pt-MZ") : "Por indicar";
|
||||||
export default function Expiry(props: Props) {
|
export default function Expiry(props: Props) {
|
||||||
const r = props.requisition;
|
const r = props.requisition;
|
||||||
const form = useForm(`expiry:${props.tenantId}:${props.actorId}:${r.id}`, {
|
const check = useForm({
|
||||||
operation_key: '',
|
operation_key: "",
|
||||||
process_version: r.process_version,
|
process_version: r.process_version,
|
||||||
basis_hash: props.deadline.basis_hash || '',
|
});
|
||||||
comment: '',
|
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 =
|
const current =
|
||||||
form.data.process_version === r.process_version &&
|
form.data.process_version === r.process_version &&
|
||||||
form.data.basis_hash === (props.deadline.basis_hash || '');
|
form.data.basis_hash === (props.deadline.basis_hash || "");
|
||||||
const ref = useRef<HTMLFormElement>(null);
|
const ref = useRef<HTMLFormElement>(null);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const node = ref.current;
|
const node = ref.current;
|
||||||
window.dispatchEvent(
|
window.dispatchEvent(
|
||||||
new CustomEvent('sgc:context-dirty', {
|
new CustomEvent("sgc:context-dirty", {
|
||||||
detail: { form: node, dirty: form.isDirty },
|
detail: { form: node, dirty: form.isDirty },
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
return () => {
|
return () => {
|
||||||
window.dispatchEvent(
|
window.dispatchEvent(
|
||||||
new CustomEvent('sgc:context-dirty', {
|
new CustomEvent("sgc:context-dirty", {
|
||||||
detail: { form: node, dirty: false },
|
detail: { form: node, dirty: false },
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -95,7 +100,7 @@ export default function Expiry(props: Props) {
|
|||||||
Voltar à requisição
|
Voltar à requisição
|
||||||
</Link>
|
</Link>
|
||||||
<Panel
|
<Panel
|
||||||
title={`${labels[props.deadline.state] || 'Por conferir'} · ciclo ${r.approval_cycle}`}
|
title={`${labels[props.deadline.state] || "Por conferir"} · ciclo ${r.approval_cycle}`}
|
||||||
>
|
>
|
||||||
<dl className="grid gap-3 text-sm">
|
<dl className="grid gap-3 text-sm">
|
||||||
<div>
|
<div>
|
||||||
@@ -131,6 +136,37 @@ export default function Expiry(props: Props) {
|
|||||||
>
|
>
|
||||||
Actualizar conferência do prazo
|
Actualizar conferência do prazo
|
||||||
</Button>
|
</Button>
|
||||||
|
{props.canCheck && (
|
||||||
|
<form
|
||||||
|
className="mt-3"
|
||||||
|
onSubmit={(event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
const operation =
|
||||||
|
check.data.operation_key || crypto.randomUUID();
|
||||||
|
check.setData("operation_key", operation);
|
||||||
|
check.transform(() => ({
|
||||||
|
operation_key: operation,
|
||||||
|
process_version: r.process_version,
|
||||||
|
}));
|
||||||
|
check.post(
|
||||||
|
`/requisicoes/${r.id}/prazos/verificar`,
|
||||||
|
{
|
||||||
|
preserveScroll: true,
|
||||||
|
onSuccess: () => check.reset(),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<FormErrors errors={check.errors} />
|
||||||
|
<Button variant="outline" disabled={check.processing}>
|
||||||
|
Verificar e executar acções devidas
|
||||||
|
</Button>
|
||||||
|
<p className="mt-2 text-sm text-muted-foreground">
|
||||||
|
Regista os lembretes e alertas configurados; se o
|
||||||
|
prazo terminou, devolve o pedido ao requisitante.
|
||||||
|
</p>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
</Panel>
|
</Panel>
|
||||||
{props.canExpire && (
|
{props.canExpire && (
|
||||||
<Panel
|
<Panel
|
||||||
@@ -144,7 +180,7 @@ export default function Expiry(props: Props) {
|
|||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
const operation =
|
const operation =
|
||||||
form.data.operation_key || crypto.randomUUID();
|
form.data.operation_key || crypto.randomUUID();
|
||||||
form.setData('operation_key', operation);
|
form.setData("operation_key", operation);
|
||||||
form.transform((data) => ({
|
form.transform((data) => ({
|
||||||
...data,
|
...data,
|
||||||
operation_key: operation,
|
operation_key: operation,
|
||||||
@@ -173,8 +209,8 @@ export default function Expiry(props: Props) {
|
|||||||
...data,
|
...data,
|
||||||
process_version: r.process_version,
|
process_version: r.process_version,
|
||||||
basis_hash:
|
basis_hash:
|
||||||
props.deadline.basis_hash || '',
|
props.deadline.basis_hash || "",
|
||||||
operation_key: '',
|
operation_key: "",
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
@@ -189,7 +225,7 @@ export default function Expiry(props: Props) {
|
|||||||
maxLength={2000}
|
maxLength={2000}
|
||||||
value={form.data.comment}
|
value={form.data.comment}
|
||||||
onChange={(event) =>
|
onChange={(event) =>
|
||||||
form.setData('comment', event.target.value)
|
form.setData("comment", event.target.value)
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
@@ -223,17 +259,17 @@ export default function Expiry(props: Props) {
|
|||||||
className="space-y-2 border-b py-4 break-words"
|
className="space-y-2 border-b py-4 break-words"
|
||||||
>
|
>
|
||||||
<h3 className="font-semibold">
|
<h3 className="font-semibold">
|
||||||
Ciclo {row.data.cycle} · devolvido para o ciclo{' '}
|
Ciclo {row.data.cycle} · devolvido para o ciclo{" "}
|
||||||
{row.data.next_cycle}
|
{row.data.next_cycle}
|
||||||
</h3>
|
</h3>
|
||||||
<p>{row.reason}</p>
|
<p>{row.reason}</p>
|
||||||
<ul>
|
<ul>
|
||||||
{row.steps.map((step) => (
|
{row.steps.map((step) => (
|
||||||
<li key={step.id}>
|
<li key={step.id}>
|
||||||
Etapa {step.position}:{' '}
|
Etapa {step.position}:{" "}
|
||||||
{step.decision === 'approved'
|
{step.decision === "approved"
|
||||||
? 'Aprovação preservada'
|
? "Aprovação preservada"
|
||||||
: 'Etapa pendente no momento da devolução'}
|
: "Etapa pendente no momento da devolução"}
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Head, Link, router, useForm } from '@inertiajs/react';
|
import { Head, Link, router, useForm } from "@inertiajs/react";
|
||||||
import { PageTitle, Panel, controlClass } from '@/components/procurement';
|
import { PageTitle, Panel, controlClass } from "@/components/procurement";
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from "@/components/ui/button";
|
||||||
import { roleLabels, statusLabels } from '@/types/procurement';
|
import { roleLabels, statusLabels } from "@/types/procurement";
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
ready: boolean;
|
ready: boolean;
|
||||||
@@ -61,13 +61,13 @@ export default function Notices({
|
|||||||
</div>
|
</div>
|
||||||
<Panel
|
<Panel
|
||||||
title={
|
title={
|
||||||
view === 'unread'
|
view === "unread"
|
||||||
? 'Por ler'
|
? "Por ler"
|
||||||
: view === 'outcomes'
|
: view === "outcomes"
|
||||||
? 'Resultados dos meus pedidos'
|
? "Resultados dos meus pedidos"
|
||||||
: view === 'tasks'
|
: view === "tasks"
|
||||||
? 'Intervenções pendentes'
|
? "Intervenções pendentes"
|
||||||
: 'Avisos internos'
|
: "Avisos internos"
|
||||||
}
|
}
|
||||||
description="Intervenções concluídas deixam a fila pendente. Resultados registados mantêm-se visíveis ao requisitante com acesso actual. Não são criados avisos retroactivos para decisões antigas."
|
description="Intervenções concluídas deixam a fila pendente. Resultados registados mantêm-se visíveis ao requisitante com acesso actual. Não são criados avisos retroactivos para decisões antigas."
|
||||||
>
|
>
|
||||||
@@ -86,7 +86,7 @@ export default function Notices({
|
|||||||
...data,
|
...data,
|
||||||
view,
|
view,
|
||||||
}));
|
}));
|
||||||
form.get('/requisicoes/avisos', {
|
form.get("/requisicoes/avisos", {
|
||||||
preserveState: true,
|
preserveState: true,
|
||||||
});
|
});
|
||||||
}}
|
}}
|
||||||
@@ -99,7 +99,7 @@ export default function Notices({
|
|||||||
value={form.data.search}
|
value={form.data.search}
|
||||||
onChange={(event) =>
|
onChange={(event) =>
|
||||||
form.setData(
|
form.setData(
|
||||||
'search',
|
"search",
|
||||||
event.target.value,
|
event.target.value,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -118,7 +118,7 @@ export default function Notices({
|
|||||||
</form>
|
</form>
|
||||||
</details>
|
</details>
|
||||||
<p className="mb-3 text-sm text-muted-foreground">
|
<p className="mb-3 text-sm text-muted-foreground">
|
||||||
{notices.total} aviso(s) nesta consulta · Página{' '}
|
{notices.total} aviso(s) nesta consulta · Página{" "}
|
||||||
{notices.current_page}
|
{notices.current_page}
|
||||||
</p>
|
</p>
|
||||||
{!ready ? (
|
{!ready ? (
|
||||||
@@ -135,28 +135,40 @@ export default function Notices({
|
|||||||
className="font-medium underline"
|
className="font-medium underline"
|
||||||
href={notice.href}
|
href={notice.href}
|
||||||
>
|
>
|
||||||
{notice.reference} ·{' '}
|
{notice.reference} ·{" "}
|
||||||
{notice.role_label ??
|
{notice.role_label ??
|
||||||
roleLabels[notice.role] ??
|
roleLabels[notice.role] ??
|
||||||
notice.role}
|
notice.role}
|
||||||
</Link>
|
</Link>
|
||||||
{notice.kind === 'outcome' && (
|
{notice.kind === "outcome" && (
|
||||||
<p className="mt-2 text-sm">
|
<p className="mt-2 text-sm">
|
||||||
Resultado registado:{' '}
|
Resultado registado:{" "}
|
||||||
{notice.outcome === 'approved'
|
{notice.outcome === "approved"
|
||||||
? 'requisição aprovada'
|
? "requisição aprovada"
|
||||||
: notice.outcome === 'expired'
|
: notice.outcome === "expired"
|
||||||
? 'pedido devolvido por expiração'
|
? "pedido devolvido por expiração"
|
||||||
: 'requisição rejeitada'}
|
: "requisição rejeitada"}
|
||||||
. Estado actual:{' '}
|
. Estado actual:{" "}
|
||||||
{statusLabels[notice.current_status] ??
|
{statusLabels[notice.current_status] ??
|
||||||
notice.current_status}
|
notice.current_status}
|
||||||
. Consulte o processo para conhecer o
|
. Consulte o processo para conhecer o
|
||||||
fundamento e os passos seguintes.
|
fundamento e os passos seguintes.
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
|
{notice.kind === "reminder" && (
|
||||||
<p className="mt-2 text-sm">
|
<p className="mt-2 text-sm">
|
||||||
{notice.read_at ? 'Lido' : 'Por ler'} ·
|
Lembrete da etapa de aprovação pendente.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{notice.kind === "escalation" && (
|
||||||
|
<p className="mt-2 text-sm">
|
||||||
|
Alerta de escalamento da etapa pendente.
|
||||||
|
Consulte o processo e os responsáveis
|
||||||
|
actuais.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<p className="mt-2 text-sm">
|
||||||
|
{notice.read_at ? "Lido" : "Por ler"} ·
|
||||||
Criado em {notice.created_at}
|
Criado em {notice.created_at}
|
||||||
</p>
|
</p>
|
||||||
{!notice.read_at && (
|
{!notice.read_at && (
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ use Illuminate\Support\Facades\Artisan;
|
|||||||
use Illuminate\Support\Facades\Schedule;
|
use Illuminate\Support\Facades\Schedule;
|
||||||
|
|
||||||
Schedule::command('sgc:replenishment-tick')->everyMinute()->withoutOverlapping(10);
|
Schedule::command('sgc:replenishment-tick')->everyMinute()->withoutOverlapping(10);
|
||||||
|
Schedule::command('sgc:approval-deadlines-tick')->everyMinute()->withoutOverlapping(10);
|
||||||
|
|
||||||
Artisan::command('inspire', function () {
|
Artisan::command('inspire', function () {
|
||||||
$this->comment(Inspiring::quote());
|
$this->comment(Inspiring::quote());
|
||||||
|
|||||||
@@ -374,6 +374,7 @@ Route::middleware(['auth', 'verified', EnsureOrganizationAccess::class])->group(
|
|||||||
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::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}/expiracao', [RequisitionExpiryController::class, 'expire'])->name('requisitions.expire');
|
||||||
|
Route::post('requisicoes/{requisition}/prazos/verificar', [RequisitionExpiryController::class, 'check'])->name('requisitions.expiry.check');
|
||||||
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');
|
||||||
|
|||||||
@@ -105,6 +105,29 @@ try {
|
|||||||
if (in_array('--requisition-cycles-focused', $argv, true)) {
|
if (in_array('--requisition-cycles-focused', $argv, true)) {
|
||||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionBudgetCyclesTest.php']];
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionBudgetCyclesTest.php']];
|
||||||
}
|
}
|
||||||
|
if (in_array('--requisition-cycles-regression', $argv, true)) {
|
||||||
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionBudgetCyclesTest.php',
|
||||||
|
'tests/Feature/InternalRequisitionCandidateTest.php', 'tests/Feature/BudgetTest.php']];
|
||||||
|
}
|
||||||
|
if (in_array('--requisition-cycles-import-regression', $argv, true)) {
|
||||||
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ImportEstimatesTest.php', 'tests/Feature/ImportLandedCostsTest.php']];
|
||||||
|
}
|
||||||
|
if (in_array('--requisition-cycles-order-regression', $argv, true)) {
|
||||||
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/PurchaseAwardOrderTest.php',
|
||||||
|
'--filter=award starts a new approval cycle|distributed approved synthetic|native partial-order issuance|native partial-order receipts|native consolidated order retains|native partial-order cancellation']];
|
||||||
|
}
|
||||||
|
if (in_array('--requisition-cycles-orders', $argv, true)) {
|
||||||
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/PurchaseAwardOrderTest.php',
|
||||||
|
'--filter=native partial-order issuance commits only forty']];
|
||||||
|
}
|
||||||
|
if (in_array('--requisition-cycles-concurrency', $argv, true)) {
|
||||||
|
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
|
||||||
|
[PHP_BINARY, 'tests/Concurrency/requisition-cycle-worker.php', $database, 'race-cycles']];
|
||||||
|
}
|
||||||
|
if (in_array('--requisition-cycles-recovery', $argv, true)) {
|
||||||
|
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
|
||||||
|
[PHP_BINARY, 'tests/Concurrency/requisition-cycle-recovery-worker.php', $database, 'recover-cycles']];
|
||||||
|
}
|
||||||
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']];
|
||||||
|
|||||||
@@ -0,0 +1,122 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Models\Requisition;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\RequisitionWorkflow;
|
||||||
|
use Illuminate\Contracts\Console\Kernel;
|
||||||
|
use Illuminate\Database\Connection;
|
||||||
|
use Illuminate\Support\Carbon;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\File;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Symfony\Component\Process\Process;
|
||||||
|
|
||||||
|
require __DIR__.'/../../vendor/autoload.php';
|
||||||
|
$app = require __DIR__.'/../../bootstrap/app.php';
|
||||||
|
$app->make(Kernel::class)->bootstrap();
|
||||||
|
$database = $argv[1] ?? '';
|
||||||
|
$db = DB::connection();
|
||||||
|
if (! $app->environment('testing') || $db->getDriverName() !== 'pgsql' || $db->getDatabaseName() !== $database
|
||||||
|
|| $db->getConfig('host') !== '127.0.0.1' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database)) {
|
||||||
|
throw new LogicException('Cycle recovery requires disposable local PostgreSQL QA.');
|
||||||
|
}
|
||||||
|
config(['requisition-expiry.qa_enabled' => true]);
|
||||||
|
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||||
|
receiptFixture();
|
||||||
|
$fingerprint = static function (Connection $connection): array {
|
||||||
|
$result = [];
|
||||||
|
foreach ($connection->select("select tablename from pg_tables where schemaname='public' order by tablename") as $row) {
|
||||||
|
$table = str_replace('"', '""', $row->tablename);
|
||||||
|
$rows = $connection->select('select row_to_json(t)::text as row from "'.$table.'" t order by row_to_json(t)::text');
|
||||||
|
$result[$row->tablename] = hash('sha256', json_encode([$connection->getSchemaBuilder()->getColumnListing($row->tablename), array_column($rows, 'row')], JSON_THROW_ON_ERROR));
|
||||||
|
}
|
||||||
|
|
||||||
|
return $result;
|
||||||
|
};
|
||||||
|
$before = $fingerprint($db);
|
||||||
|
$connectionConfig = $db->getConfig();
|
||||||
|
unset($connectionConfig['name']);
|
||||||
|
$directory = storage_path('framework/testing/cycle-recovery-'.$database);
|
||||||
|
File::ensureDirectoryExists($directory, 0700);
|
||||||
|
$pg = static function (string $binary, array $arguments) use ($connectionConfig): void {
|
||||||
|
$process = new Process(['C:/Program Files/PostgreSQL/17/bin/'.$binary.'.exe', ...$arguments], null,
|
||||||
|
['PGHOST' => $connectionConfig['host'], 'PGPORT' => (string) $connectionConfig['port'], 'PGUSER' => $connectionConfig['username'], 'PGPASSWORD' => $connectionConfig['password']], timeout: 60);
|
||||||
|
$process->run();
|
||||||
|
if (! $process->isSuccessful()) {
|
||||||
|
throw new RuntimeException('Synthetic cycle backup/restore failed.');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
$preDump = $directory.'/before.dump';
|
||||||
|
$postDump = $directory.'/after.dump';
|
||||||
|
$pg('pg_dump', ['--format=custom', '--file='.$preDump, '--dbname='.$database]);
|
||||||
|
$prepare = new Process([PHP_BINARY, __DIR__.'/requisition-cycle-worker.php', $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
|
||||||
|
$prepare->mustRun();
|
||||||
|
$input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
|
||||||
|
Carbon::setTestNow($input['clock']);
|
||||||
|
$owner = User::query()->findOrFail($input['owner']);
|
||||||
|
auth()->guard()->setUser($owner);
|
||||||
|
$request = Requisition::query()->findOrFail($input['request']);
|
||||||
|
$workflow = app(RequisitionWorkflow::class);
|
||||||
|
$workflow->expire($owner, $request, $input['basis'], $input['operation'], $input['version']);
|
||||||
|
$request->refresh();
|
||||||
|
$request = $workflow->save($owner, ['operation_key' => (string) Str::uuid(), 'process_version' => $request->process_version,
|
||||||
|
'cost_center_id' => $request->cost_center_id, 'priority' => 'normal', 'needed_by' => today()->addWeek()->toDateString(),
|
||||||
|
'justification' => 'Synthetic revised request retained through recovery',
|
||||||
|
'items' => [['description' => 'Synthetic revised item', 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '1.000', 'unit' => 'un', 'unit_price' => '120.00', 'tax_rate' => '0.00']]], $request);
|
||||||
|
$submission = (string) Str::uuid();
|
||||||
|
$version = $request->process_version;
|
||||||
|
$workflow->submit($owner, $request, $submission, $version);
|
||||||
|
$after = $fingerprint($db);
|
||||||
|
$pg('pg_dump', ['--format=custom', '--file='.$postDump, '--dbname='.$database]);
|
||||||
|
$restore = 'compras_receipts_test_'.bin2hex(random_bytes(6));
|
||||||
|
$originalDefault = DB::getDefaultConnection();
|
||||||
|
config(['database.connections.cycle_recovery_admin' => [...$connectionConfig, 'database' => 'postgres'],
|
||||||
|
'database.connections.cycle_recovery_restore' => [...$connectionConfig, 'database' => $restore]]);
|
||||||
|
$admin = DB::connection('cycle_recovery_admin');
|
||||||
|
$created = false;
|
||||||
|
try {
|
||||||
|
$admin->statement('CREATE DATABASE "'.$restore.'"');
|
||||||
|
$created = true;
|
||||||
|
$pg('pg_restore', ['--no-owner', '--no-privileges', '--exit-on-error', '--dbname='.$restore, $postDump]);
|
||||||
|
$restored = DB::connection('cycle_recovery_restore');
|
||||||
|
if ($fingerprint($restored) !== $after) {
|
||||||
|
throw new RuntimeException('Restored cycle schema or complete table contents differ.');
|
||||||
|
}
|
||||||
|
DB::setDefaultConnection('cycle_recovery_restore');
|
||||||
|
$owner = User::query()->findOrFail($input['owner']);
|
||||||
|
auth()->guard()->setUser($owner);
|
||||||
|
$request = Requisition::query()->findOrFail($input['request']);
|
||||||
|
$workflow->expire($owner, $request, $input['basis'], $input['operation'], $input['version']);
|
||||||
|
$workflow->submit($owner, $request, $submission, $version);
|
||||||
|
if ($fingerprint($restored) !== $after || $request->fresh()->approval_cycle !== 2
|
||||||
|
|| (int) $restored->table('budget_entries')->where('requisition_id', $request->id)->sum('reserved_minor') !== 12000
|
||||||
|
|| $restored->table('approval_steps')->where('requisition_id', $request->id)->where('decision', 'expired')->count() !== 1) {
|
||||||
|
throw new RuntimeException('Restored native expiry/submission replay changed history or reservation.');
|
||||||
|
}
|
||||||
|
DB::setDefaultConnection($originalDefault);
|
||||||
|
DB::purge('cycle_recovery_restore');
|
||||||
|
$admin->statement('DROP DATABASE "'.$restore.'" WITH (FORCE)');
|
||||||
|
$created = false;
|
||||||
|
$admin->statement('CREATE DATABASE "'.$restore.'"');
|
||||||
|
$created = true;
|
||||||
|
$pg('pg_restore', ['--no-owner', '--no-privileges', '--exit-on-error', '--dbname='.$restore, $preDump]);
|
||||||
|
$restored = DB::connection('cycle_recovery_restore');
|
||||||
|
if ($fingerprint($restored) !== $before || $restored->getSchemaBuilder()->hasTable('budget_requisition_cycles')) {
|
||||||
|
throw new RuntimeException('Pre-extension restore did not preserve its exact original schema and records.');
|
||||||
|
}
|
||||||
|
echo json_encode(['cycle_post_extension_all_tables_equal' => true, 'cycle_native_replays_without_effects' => true,
|
||||||
|
'cycle_history_and_reserve_restored' => true, 'cycle_reserved_minor' => 12000,
|
||||||
|
'cycle_pre_extension_all_tables_equal' => true, 'pre_extension_tables' => count($before), 'post_extension_tables' => count($after)], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||||
|
} finally {
|
||||||
|
DB::setDefaultConnection($originalDefault);
|
||||||
|
DB::purge('cycle_recovery_restore');
|
||||||
|
if ($created) {
|
||||||
|
$admin->statement('DROP DATABASE "'.$restore.'" WITH (FORCE)');
|
||||||
|
}
|
||||||
|
echo json_encode(['restore_database' => $restore, 'isolated_restore_removed' => true], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||||
|
$resolved = realpath($directory);
|
||||||
|
$testingRoot = realpath(storage_path('framework/testing'));
|
||||||
|
if ($resolved !== false && $testingRoot !== false && str_starts_with($resolved, $testingRoot.DIRECTORY_SEPARATOR)) {
|
||||||
|
File::deleteDirectory($resolved);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,210 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Enums\PurchasingRole;
|
||||||
|
use App\Models\Budget;
|
||||||
|
use App\Models\Requisition;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\CommonBudget;
|
||||||
|
use App\Services\RequisitionExpiry;
|
||||||
|
use App\Services\RequisitionExpiryRun;
|
||||||
|
use App\Services\RequisitionWorkflow;
|
||||||
|
use Illuminate\Contracts\Console\Kernel;
|
||||||
|
use Illuminate\Support\Carbon;
|
||||||
|
use Illuminate\Support\Facades\Artisan;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||||
|
use Symfony\Component\Process\Process;
|
||||||
|
|
||||||
|
require __DIR__.'/../../vendor/autoload.php';
|
||||||
|
$app = require __DIR__.'/../../bootstrap/app.php';
|
||||||
|
$app->make(Kernel::class)->bootstrap();
|
||||||
|
$database = $argv[1] ?? '';
|
||||||
|
$mode = $argv[2] ?? '';
|
||||||
|
$db = DB::connection();
|
||||||
|
if (! $app->environment('testing') || $db->getDriverName() !== 'pgsql' || $db->getDatabaseName() !== $database
|
||||||
|
|| $db->getConfig('host') !== '127.0.0.1' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database)) {
|
||||||
|
throw new LogicException('Cycle contention requires disposable local PostgreSQL QA.');
|
||||||
|
}
|
||||||
|
config(['requisition-expiry.qa_enabled' => true]);
|
||||||
|
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||||
|
|
||||||
|
if ($mode === 'scheduled-cycle') {
|
||||||
|
$input = json_decode($argv[3], true, 32, JSON_THROW_ON_ERROR);
|
||||||
|
Carbon::setTestNow($input['clock']);
|
||||||
|
if (auth()->check() || request()->hasSession()) {
|
||||||
|
throw new RuntimeException('Scheduled proof must run without an authenticated session.');
|
||||||
|
}
|
||||||
|
if (Artisan::call('sgc:approval-deadlines-tick') !== 0) {
|
||||||
|
throw new RuntimeException('Scheduled deadline tick failed: '.Artisan::output());
|
||||||
|
}
|
||||||
|
$request = $db->table('requisitions')->where('id', $input['request'])->sole();
|
||||||
|
$count = $db->table('supply_records')->count();
|
||||||
|
$audits = $db->table('audit_logs')->count();
|
||||||
|
if (Artisan::call('sgc:approval-deadlines-tick') !== 0 || $db->table('supply_records')->count() !== $count || $db->table('audit_logs')->count() !== $audits
|
||||||
|
|| $request->status !== 'draft' || $request->approval_cycle !== 2 || auth()->check()
|
||||||
|
|| app(RequisitionExpiryRun::class)->tenantId() !== null
|
||||||
|
|| (int) $db->table('budget_entries')->where('requisition_id', $input['request'])->sum('reserved_minor') !== 0) {
|
||||||
|
throw new RuntimeException('Scheduled expiry must close the scope and replay without effects.');
|
||||||
|
}
|
||||||
|
$audit = $db->table('audit_logs')->where('requisition_id', $input['request'])->where('action', 'requisition.expired_returned')->sole();
|
||||||
|
$data = json_decode($audit->after, true, 32, JSON_THROW_ON_ERROR);
|
||||||
|
if (($data['execution']['mode'] ?? null) !== 'scheduled_approval_deadline' || $audit->ip_address !== null) {
|
||||||
|
throw new RuntimeException('Scheduled audit must distinguish automatic execution from an interactive act.');
|
||||||
|
}
|
||||||
|
echo json_encode(['scheduled_expiry_without_session' => true, 'scheduled_scope_closed' => true, 'scheduled_repeat_without_effects' => true,
|
||||||
|
'scheduled_audit_explicit' => true], JSON_THROW_ON_ERROR);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
if ($mode === 'legacy-cycles') {
|
||||||
|
$actor = User::query()->findOrFail((int) $argv[3]);
|
||||||
|
auth()->guard()->setUser($actor);
|
||||||
|
try {
|
||||||
|
app(CommonBudget::class)->for($actor)->balance((int) $argv[4]);
|
||||||
|
throw new RuntimeException('Old runtime unexpectedly exposed a balance after a new cycle.');
|
||||||
|
} catch (HttpExceptionInterface $error) {
|
||||||
|
if ($error->getStatusCode() !== 503) {
|
||||||
|
throw $error;
|
||||||
|
}
|
||||||
|
echo json_encode(['old_cycle_runtime_rejected_before_balance' => true, 'status' => 503]);
|
||||||
|
}
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($mode === 'prepare') {
|
||||||
|
if (! $db->getSchemaBuilder()->hasTable('budget_requisition_cycles')) {
|
||||||
|
(require __DIR__.'/../../database/qa-migrations/2026_11_27_000001_add_requisition_cycles.php')->up();
|
||||||
|
}
|
||||||
|
$f = receiptFixture();
|
||||||
|
$owner = $f['issuer'];
|
||||||
|
$admin = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::Admin]);
|
||||||
|
$head = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
|
||||||
|
$finance = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||||
|
auth()->guard()->setUser($admin);
|
||||||
|
Budget::query()->create(['tenant_id' => $owner->tenant_id, 'cost_center_id' => $f['r']->cost_center_id, 'year' => now()->year, 'kind' => 'operating',
|
||||||
|
'amount_minor' => 100000, 'includes_tax' => true, 'reason' => 'Synthetic concurrent cycle budget', 'created_by' => $admin->id, 'approved_by' => $finance->id]);
|
||||||
|
app(RequisitionExpiry::class)->savePolicy($admin, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true,
|
||||||
|
'levels' => [['role' => 'department_head', 'expire_minutes' => 30, 'reminder_minutes' => null, 'escalation_minutes' => null, 'profile_ids' => []]],
|
||||||
|
'reason' => 'Explicit synthetic concurrent expiry policy']);
|
||||||
|
auth()->guard()->setUser($owner);
|
||||||
|
$workflow = app(RequisitionWorkflow::class);
|
||||||
|
$request = $workflow->save($owner, ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $f['r']->cost_center_id, 'priority' => 'normal',
|
||||||
|
'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Synthetic simultaneous expiry and decision',
|
||||||
|
'items' => [['description' => 'Synthetic item', 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '1.000', 'unit' => 'un', 'unit_price' => '100.00', 'tax_rate' => '0.00']]]);
|
||||||
|
$workflow->submit($owner, $request, (string) Str::uuid(), $request->process_version);
|
||||||
|
$request->refresh();
|
||||||
|
Carbon::setTestNow(now()->addMinutes(31));
|
||||||
|
echo json_encode(['tenant' => $owner->tenant_id, 'owner' => $owner->id, 'head' => $head->id, 'request' => $request->id,
|
||||||
|
'version' => $request->process_version, 'clock' => now()->toIso8601String(),
|
||||||
|
'basis' => app(RequisitionExpiry::class)->deadline($request)['basis_hash'], 'operation' => (string) Str::uuid()], JSON_THROW_ON_ERROR);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Re-enter the native submission route before checking an older installed composition.
|
||||||
|
$verifyLegacy = function (array $input) use ($db, $database): void {
|
||||||
|
$owner = User::query()->findOrFail($input['owner']);
|
||||||
|
auth()->guard()->setUser($owner);
|
||||||
|
$request = Requisition::query()->findOrFail($input['request']);
|
||||||
|
app(RequisitionWorkflow::class)->submit($owner, $request, (string) Str::uuid(), $request->process_version);
|
||||||
|
$before = $db->table('budget_entries')->where('requisition_id', $request->id)->orderBy('id')->get()->toJson();
|
||||||
|
$budget = $db->table('budgets')->where('tenant_id', $owner->tenant_id)->where('cost_center_id', $request->cost_center_id)->sole();
|
||||||
|
$legacy = new Process([PHP_BINARY, __FILE__, $database, 'legacy-cycles', (string) $owner->id, (string) $budget->id],
|
||||||
|
dirname(__DIR__, 2), ['COMMON_BUDGET_PATH' => base_path('packages/budget-control')], timeout: 30);
|
||||||
|
$legacy->mustRun();
|
||||||
|
$receipt = json_decode($legacy->getOutput(), true, 32, JSON_THROW_ON_ERROR);
|
||||||
|
if (($receipt['old_cycle_runtime_rejected_before_balance'] ?? false) !== true
|
||||||
|
|| $before !== $db->table('budget_entries')->where('requisition_id', $request->id)->orderBy('id')->get()->toJson()) {
|
||||||
|
throw new RuntimeException('Legacy cycle refusal must precede all balance exposure and financial writes.');
|
||||||
|
}
|
||||||
|
echo $legacy->getOutput().PHP_EOL;
|
||||||
|
};
|
||||||
|
|
||||||
|
if ($mode === 'write') {
|
||||||
|
$input = json_decode($argv[3], true, 32, JSON_THROW_ON_ERROR);
|
||||||
|
Carbon::setTestNow($input['clock']);
|
||||||
|
$db->select('select set_config(?, ?, false)', ['application_name', 'sgc_cycle_write_'.getmypid()]);
|
||||||
|
$actor = User::query()->findOrFail($input['decision'] ? $input['head'] : $input['owner']);
|
||||||
|
auth()->guard()->setUser($actor);
|
||||||
|
try {
|
||||||
|
$request = Requisition::query()->findOrFail($input['request']);
|
||||||
|
$workflow = app(RequisitionWorkflow::class);
|
||||||
|
if ($input['decision']) {
|
||||||
|
$workflow->decide($actor, $request, 'approved', 'Synthetic decision after configured deadline', $input['operation'], $input['version']);
|
||||||
|
} else {
|
||||||
|
$workflow->expire($actor, $request, $input['basis'], $input['operation'], $input['version']);
|
||||||
|
}
|
||||||
|
echo json_encode(['status' => 200]);
|
||||||
|
} catch (HttpExceptionInterface $error) {
|
||||||
|
echo json_encode(['status' => $error->getStatusCode()]);
|
||||||
|
}
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
if ($mode !== 'race-cycles') {
|
||||||
|
throw new InvalidArgumentException('Unknown cycle worker mode.');
|
||||||
|
}
|
||||||
|
foreach (['same_operation', 'different_operations', 'late_decision'] as $scenario) {
|
||||||
|
$prepare = new Process([PHP_BINARY, __FILE__, $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
|
||||||
|
$prepare->mustRun();
|
||||||
|
$input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
|
||||||
|
$workers = [];
|
||||||
|
$db->beginTransaction();
|
||||||
|
try {
|
||||||
|
$db->table('tenants')->where('id', $input['tenant'])->lockForUpdate()->firstOrFail();
|
||||||
|
for ($index = 0; $index < 2; $index++) {
|
||||||
|
$payload = $input + ['decision' => $scenario === 'late_decision' && $index === 1];
|
||||||
|
if ($scenario !== 'same_operation' && $index === 1) {
|
||||||
|
$payload['operation'] = (string) Str::uuid();
|
||||||
|
}
|
||||||
|
$worker = new Process([PHP_BINARY, __FILE__, $database, 'write', json_encode($payload, JSON_THROW_ON_ERROR)], dirname(__DIR__, 2), timeout: 30);
|
||||||
|
$workers[] = $worker;
|
||||||
|
$worker->start();
|
||||||
|
}
|
||||||
|
$deadline = microtime(true) + 10;
|
||||||
|
do {
|
||||||
|
$db->select('select pg_stat_clear_snapshot()');
|
||||||
|
$blocked = (int) $db->selectOne("select count(*) as n from pg_stat_activity where datname=? and application_name like 'sgc_cycle_write_%' and wait_event_type='Lock'", [$database])->n;
|
||||||
|
if ($blocked >= 2) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
usleep(50000);
|
||||||
|
} while (microtime(true) < $deadline);
|
||||||
|
if ($blocked < 2) {
|
||||||
|
throw new RuntimeException('Both cycle writers must demonstrably wait on the company lock.');
|
||||||
|
}
|
||||||
|
$db->commit();
|
||||||
|
$statuses = [];
|
||||||
|
foreach ($workers as $worker) {
|
||||||
|
$worker->wait();
|
||||||
|
if (! $worker->isSuccessful()) {
|
||||||
|
throw new RuntimeException($worker->getErrorOutput());
|
||||||
|
}
|
||||||
|
$statuses[] = json_decode($worker->getOutput(), true, 32, JSON_THROW_ON_ERROR)['status'];
|
||||||
|
}
|
||||||
|
sort($statuses);
|
||||||
|
$request = $db->table('requisitions')->where('id', $input['request'])->sole();
|
||||||
|
$returns = $db->table('supply_records')->where('tenant_id', $input['tenant'])->where('kind', 'req_expiration')->count();
|
||||||
|
$reserve = (int) $db->table('budget_entries')->where('requisition_id', $input['request'])->sum('reserved_minor');
|
||||||
|
$approved = $db->table('approval_steps')->where('requisition_id', $input['request'])->where('decision', 'approved')->count();
|
||||||
|
if ($statuses !== ($scenario === 'same_operation' ? [200, 200] : [200, 409]) || $returns !== 1 || $reserve !== 0
|
||||||
|
|| $request->status !== 'draft' || $request->approval_cycle !== 2 || $approved !== 0) {
|
||||||
|
throw new RuntimeException('Concurrent expiry must preserve one return, zero reserve and no late approval: '.json_encode($statuses));
|
||||||
|
}
|
||||||
|
echo json_encode(['scenario' => $scenario, 'statuses' => $statuses, 'blocked_writers_observed' => $blocked,
|
||||||
|
'returns' => $returns, 'reserve_minor' => $reserve, 'late_approvals' => $approved], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||||
|
} finally {
|
||||||
|
if ($db->transactionLevel() > 0) {
|
||||||
|
$db->rollBack();
|
||||||
|
}
|
||||||
|
foreach ($workers as $worker) {
|
||||||
|
if ($worker->isRunning()) {
|
||||||
|
$worker->stop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$verifyLegacy($input);
|
||||||
|
$prepare = new Process([PHP_BINARY, __FILE__, $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
|
||||||
|
$prepare->mustRun();
|
||||||
|
$scheduled = new Process([PHP_BINARY, __FILE__, $database, 'scheduled-cycle', $prepare->getOutput()], dirname(__DIR__, 2), timeout: 30);
|
||||||
|
$scheduled->mustRun();
|
||||||
|
echo $scheduled->getOutput().PHP_EOL;
|
||||||
@@ -1794,12 +1794,32 @@ test('native partial-order Finance amendment exposes a recoverable form and pres
|
|||||||
$this->post('/ordens/'.$order->id.'/reafectacao', $data)->assertConflict();
|
$this->post('/ordens/'.$order->id.'/reafectacao', $data)->assertConflict();
|
||||||
});
|
});
|
||||||
|
|
||||||
test('native partial-order issuance commits only forty then sixty and preserves replay and quantity caps', function () {
|
test('native partial-order issuance commits only forty then sixty and preserves replay and quantity caps', function (int $cycle) {
|
||||||
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
|
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
|
||||||
$this->markTestSkipped('Explicit unpublished common source required.');
|
$this->markTestSkipped('Explicit unpublished common source required.');
|
||||||
}
|
}
|
||||||
(new PurchaseOrder)->fill(['number' => 'Unpersisted legacy metadata warmup']);
|
(new PurchaseOrder)->fill(['number' => 'Unpersisted legacy metadata warmup']);
|
||||||
(new PurchaseOrderItem)->fill(['description' => 'Unpersisted legacy metadata warmup']);
|
(new PurchaseOrderItem)->fill(['description' => 'Unpersisted legacy metadata warmup']);
|
||||||
|
if ($cycle === 2) {
|
||||||
|
if (! method_exists(BudgetControl::class, 'beginRequisitionCycle')) {
|
||||||
|
$this->markTestSkipped('Explicit cycle-capable common QA source required.');
|
||||||
|
}
|
||||||
|
budgetDistributionFixtureSchema();
|
||||||
|
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php')->up();
|
||||||
|
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000008_create_purchase_order_sources.php')->up();
|
||||||
|
(require __DIR__.'/../../database/qa-migrations/2026_11_27_000001_add_requisition_cycles.php')->up();
|
||||||
|
config(['requisition-expiry.qa_enabled' => true]);
|
||||||
|
$engine = app(CommonBudget::class)->for($this->buyer, [$this->r->id => 1]);
|
||||||
|
$engine->beginRequisitionCycle($this->r->id, 1, (string) Str::uuid());
|
||||||
|
$engine->closeRequisitionCycle($this->r->id, 1, (string) Str::uuid());
|
||||||
|
$this->r->setAttribute('approval_cycle', 2);
|
||||||
|
$this->r->save();
|
||||||
|
$step = $this->r->steps()->make(['tenant_id' => $this->tenant->id, 'position' => 1, 'role' => 'department_head',
|
||||||
|
'decision' => 'approved', 'approver_id' => $this->head->id, 'decided_at' => now()]);
|
||||||
|
$step->setAttribute('approval_cycle', 2);
|
||||||
|
$step->save();
|
||||||
|
app(CommonBudget::class)->for($this->buyer, [$this->r->id => 2])->beginRequisitionCycle($this->r->id, 2, (string) Str::uuid());
|
||||||
|
}
|
||||||
$award = nativeOrderPartsAward($this);
|
$award = nativeOrderPartsAward($this);
|
||||||
$input = nativeOrderPartsInput($this, $award, '0.400', 0);
|
$input = nativeOrderPartsInput($this, $award, '0.400', 0);
|
||||||
$workflow = app(OrderPartsWorkflow::class);
|
$workflow = app(OrderPartsWorkflow::class);
|
||||||
@@ -1824,7 +1844,7 @@ test('native partial-order issuance commits only forty then sixty and preserves
|
|||||||
$this->withoutVite();
|
$this->withoutVite();
|
||||||
$this->get('/ordens/preparar')->assertOk()->assertViewHas('page', fn (array $page) => $page['props']['candidates']['data'] === []);
|
$this->get('/ordens/preparar')->assertOk()->assertViewHas('page', fn (array $page) => $page['props']['candidates']['data'] === []);
|
||||||
$this->post('/adjudicacoes/'.$award->id.'/emitir')->assertConflict();
|
$this->post('/adjudicacoes/'.$award->id.'/emitir')->assertConflict();
|
||||||
});
|
})->with([1, 2]);
|
||||||
|
|
||||||
test('native partial-order issuance rolls back the document and all financial effects when its audit fails', function () {
|
test('native partial-order issuance rolls back the document and all financial effects when its audit fails', function () {
|
||||||
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
|
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
|
||||||
|
|||||||
@@ -159,6 +159,40 @@ test('import assumptions release in the old cycle before a separately identified
|
|||||||
->and(DB::table('budget_landed_entries')->orderBy('id')->limit(2)->get()->toJson())->toBe($old);
|
->and(DB::table('budget_landed_entries')->orderBy('id')->limit(2)->get()->toJson())->toBe($old);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('configured escalation alerts respect current membership and never delegate the pending approval', function () {
|
||||||
|
$owner = $this->f['issuer'];
|
||||||
|
$head = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::Configured]);
|
||||||
|
$viewer = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::Configured]);
|
||||||
|
$profiles = [];
|
||||||
|
foreach ([[$owner, ['admin', 'requester']], [$head, ['department_head']], [$viewer, ['procurement']]] as [$person, $permissions]) {
|
||||||
|
$profile = DB::table('organization_profiles')->insertGetId(['tenant_id' => $owner->tenant_id, 'name' => 'Synthetic profile '.$person->id,
|
||||||
|
'permissions' => json_encode($permissions), 'work_contexts' => json_encode(['procurement.internal']), 'version' => 1]);
|
||||||
|
DB::table('organization_memberships')->insert(['tenant_id' => $owner->tenant_id, 'user_id' => $person->id, 'profile_id' => $profile, 'maintenance' => false]);
|
||||||
|
$profiles[$person->id] = $profile;
|
||||||
|
}
|
||||||
|
DB::table('organization_access')->insert(['tenant_id' => $owner->tenant_id, 'active' => true, 'version' => 1]);
|
||||||
|
$this->actingAs($owner);
|
||||||
|
$expiry = app(RequisitionExpiry::class);
|
||||||
|
$expiry->savePolicy($owner, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true,
|
||||||
|
'levels' => [['role' => 'department_head', 'expire_minutes' => 30, 'reminder_minutes' => 10, 'escalation_minutes' => 20, 'profile_ids' => [$profiles[$viewer->id]]]],
|
||||||
|
'reason' => 'Explicit synthetic escalation to an existing viewer profile']);
|
||||||
|
$workflow = app(RequisitionWorkflow::class);
|
||||||
|
$request = $workflow->save($owner, ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $this->f['r']->cost_center_id,
|
||||||
|
'priority' => 'normal', 'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Synthetic configured deadline and notification recipients',
|
||||||
|
'items' => [['description' => 'Synthetic item', 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '1.000', 'unit' => 'un', 'unit_price' => '100.00', 'tax_rate' => '0.00']]]);
|
||||||
|
$workflow->submit($owner, $request, (string) Str::uuid(), $request->process_version);
|
||||||
|
$request->refresh();
|
||||||
|
$this->travel(20)->minutes();
|
||||||
|
$result = $expiry->check($owner, $request, ['operation_key' => (string) Str::uuid(), 'process_version' => $request->process_version]);
|
||||||
|
expect($result['escalation_eligible'])->toBe(1)->and($result['notices_created'])->toBe(2);
|
||||||
|
$this->actingAs($viewer);
|
||||||
|
expect(array_column(app(WorkflowNotices::class)->visible($viewer), 'kind'))->toContain('escalation')
|
||||||
|
->and($request->canDecide($viewer))->toBeFalse();
|
||||||
|
DB::table('organization_memberships')->where('user_id', $viewer->id)->update(['expires_at' => now()->subSecond()]);
|
||||||
|
expect(app(WorkflowNotices::class)->visible($viewer))->toBe([]);
|
||||||
|
$this->travelBack();
|
||||||
|
});
|
||||||
|
|
||||||
test('native expiry returns the same request and preserves the approved stage before a fresh revised submission and reservation', function () {
|
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]);
|
$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]);
|
$head = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
|
||||||
@@ -179,6 +213,13 @@ test('native expiry returns the same request and preserves the approved stage be
|
|||||||
$workflow->submit($owner, $request, (string) Str::uuid(), $request->process_version);
|
$workflow->submit($owner, $request, (string) Str::uuid(), $request->process_version);
|
||||||
$request->refresh();
|
$request->refresh();
|
||||||
$this->actingAs($head);
|
$this->actingAs($head);
|
||||||
|
$this->travel(10)->minutes();
|
||||||
|
$check = ['operation_key' => (string) Str::uuid(), 'process_version' => $request->process_version];
|
||||||
|
$firstCheck = $expiry->check($head, $request, $check);
|
||||||
|
expect($firstCheck['notices_created'])->toBe(1)
|
||||||
|
->and($expiry->check($head, $request, $check))->toBe($firstCheck)
|
||||||
|
->and($expiry->check($head, $request, ['operation_key' => (string) Str::uuid(), 'process_version' => $request->process_version])['notices_created'])->toBe(0)
|
||||||
|
->and(array_column(app(WorkflowNotices::class)->visible($head), 'kind'))->toContain('reminder');
|
||||||
$workflow->decide($head, $request, 'approved', 'Conferência sintética do primeiro nível', (string) Str::uuid(), $request->process_version);
|
$workflow->decide($head, $request, 'approved', 'Conferência sintética do primeiro nível', (string) Str::uuid(), $request->process_version);
|
||||||
$request->refresh();
|
$request->refresh();
|
||||||
$approved = $request->steps()->where('decision', 'approved')->sole()->toArray();
|
$approved = $request->steps()->where('decision', 'approved')->sole()->toArray();
|
||||||
@@ -216,5 +257,13 @@ test('native expiry returns the same request and preserves the approved stage be
|
|||||||
$notices = app(WorkflowNotices::class)->visible($owner);
|
$notices = app(WorkflowNotices::class)->visible($owner);
|
||||||
expect(array_column($notices, 'outcome'))->toContain('expired')
|
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);
|
->and(DB::table('workflow_notices')->where('requisition_id', $request->id)->where('recipient_id', $owner->id)->count())->toBe(1);
|
||||||
|
$this->travel(31)->minutes();
|
||||||
|
$check = ['operation_key' => (string) Str::uuid(), 'process_version' => $request->process_version];
|
||||||
|
$this->postJson('/requisicoes/'.$request->id.'/prazos/verificar', $check)->assertRedirect();
|
||||||
|
$this->postJson('/requisicoes/'.$request->id.'/prazos/verificar', $check)->assertRedirect();
|
||||||
|
$request->refresh();
|
||||||
|
expect($request->status)->toBe('draft')->and($request->approval_cycle)->toBe(3)
|
||||||
|
->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(2);
|
||||||
$this->travelBack();
|
$this->travelBack();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -24,6 +24,25 @@ 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 === 'recover-cycles') {
|
||||||
|
return $contains(fn ($row) => ($row['cycle_post_extension_all_tables_equal'] ?? false) === true
|
||||||
|
&& ($row['cycle_native_replays_without_effects'] ?? false) === true && ($row['cycle_history_and_reserve_restored'] ?? false) === true
|
||||||
|
&& ($row['cycle_reserved_minor'] ?? null) === 12000 && ($row['cycle_pre_extension_all_tables_equal'] ?? false) === true)
|
||||||
|
&& $contains(fn ($row) => ($row['isolated_restore_removed'] ?? false) === true);
|
||||||
|
}
|
||||||
|
if ($mode === 'race-cycles') {
|
||||||
|
foreach (['same_operation', 'different_operations', 'late_decision'] as $scenario) {
|
||||||
|
$matches = array_values(array_filter($records, fn ($row) => ($row['scenario'] ?? null) === $scenario));
|
||||||
|
if (count($matches) !== 1 || ($matches[0]['blocked_writers_observed'] ?? 0) < 2
|
||||||
|
|| ($matches[0]['returns'] ?? null) !== 1 || ($matches[0]['reserve_minor'] ?? null) !== 0
|
||||||
|
|| ($matches[0]['late_approvals'] ?? null) !== 0
|
||||||
|
|| ($matches[0]['statuses'] ?? null) !== ($scenario === 'same_operation' ? [200, 200] : [200, 409])) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $contains(fn ($row) => ($row['old_cycle_runtime_rejected_before_balance'] ?? false) === true && ($row['status'] ?? null) === 503);
|
||||||
|
}
|
||||||
if ($mode === 'capital') {
|
if ($mode === 'capital') {
|
||||||
if (! $contains(fn ($row) => ($row['capital_register_versions_restored'] ?? null) === 2
|
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_assignment_source_version_restored'] ?? null) === 1 && ($row['capital_archived_head_preserved'] ?? false) === true
|
||||||
|
|||||||
@@ -1,5 +1,22 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
|
test('cycle contention requires all three real lock and single-effect receipts', function () {
|
||||||
|
$command = ['php', 'worker.php', 'compras_receipts_test_000000000001', 'race-cycles'];
|
||||||
|
$rows = [];
|
||||||
|
foreach (['same_operation' => [200, 200], 'different_operations' => [200, 409], 'late_decision' => [200, 409]] as $scenario => $statuses) {
|
||||||
|
$rows[] = ['scenario' => $scenario, 'statuses' => $statuses, 'blocked_writers_observed' => 2, 'returns' => 1, 'reserve_minor' => 0, 'late_approvals' => 0];
|
||||||
|
}
|
||||||
|
$rows[] = ['old_cycle_runtime_rejected_before_balance' => true, 'status' => 503];
|
||||||
|
$output = function () use (&$rows) {
|
||||||
|
return implode("\n", array_map(fn ($row) => json_encode($row, JSON_THROW_ON_ERROR), $rows));
|
||||||
|
};
|
||||||
|
expect(landedQaReceiptsVerified($command, $output()))->toBeTrue();
|
||||||
|
$rows[2]['late_approvals'] = 1;
|
||||||
|
expect(landedQaReceiptsVerified($command, $output()))->toBeFalse();
|
||||||
|
array_pop($rows);
|
||||||
|
expect(landedQaReceiptsVerified($command, $output()))->toBeFalse();
|
||||||
|
});
|
||||||
|
|
||||||
test('capital register contention requires both actual lock receipts and one immutable version per scenario', function () {
|
test('capital register contention requires both actual lock receipts and one immutable version per scenario', function () {
|
||||||
$command = ['php', 'worker.php', 'compras_receipts_test_000000000001', 'race-capital'];
|
$command = ['php', 'worker.php', 'compras_receipts_test_000000000001', 'race-capital'];
|
||||||
$rows = [];
|
$rows = [];
|
||||||
|
|||||||
@@ -0,0 +1,85 @@
|
|||||||
|
import { App } from "@inertiajs/react";
|
||||||
|
import { renderToStaticMarkup } from "react-dom/server";
|
||||||
|
import { expect, test } from "vitest";
|
||||||
|
import Expiry from "../../resources/js/pages/requisitions/expiry";
|
||||||
|
|
||||||
|
function render(extra: object) {
|
||||||
|
return renderToStaticMarkup(
|
||||||
|
<App
|
||||||
|
initialComponent={Expiry}
|
||||||
|
initialPage={{
|
||||||
|
component: "requisitions/expiry",
|
||||||
|
url: "/requisicoes/1/prazos",
|
||||||
|
version: null,
|
||||||
|
clearHistory: false,
|
||||||
|
encryptHistory: true,
|
||||||
|
props: {
|
||||||
|
errors: {},
|
||||||
|
requisition: {
|
||||||
|
id: 1,
|
||||||
|
number: "REQ-QA",
|
||||||
|
status: "draft",
|
||||||
|
process_version: 4,
|
||||||
|
approval_cycle: 2,
|
||||||
|
},
|
||||||
|
deadline: {
|
||||||
|
state: "inactive",
|
||||||
|
step_id: null,
|
||||||
|
expires_at: null,
|
||||||
|
basis_hash: null,
|
||||||
|
},
|
||||||
|
canExpire: false,
|
||||||
|
canCheck: false,
|
||||||
|
canEdit: true,
|
||||||
|
actorId: 1,
|
||||||
|
tenantId: 1,
|
||||||
|
history: {
|
||||||
|
data: [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
data: { cycle: 1, next_cycle: 2 },
|
||||||
|
reason: "<script>synthetic</script>",
|
||||||
|
request: { number: "REQ-QA" },
|
||||||
|
steps: [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
position: 1,
|
||||||
|
role: "department_head",
|
||||||
|
decision: "approved",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
prev_page_url: null,
|
||||||
|
next_page_url: null,
|
||||||
|
},
|
||||||
|
...extra,
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
test("returned owner sees the same draft and preserved approval without expiry controls", () => {
|
||||||
|
const html = render({});
|
||||||
|
expect(html).toContain("/requisicoes/1/editar");
|
||||||
|
expect(html).toContain("Aprovação preservada");
|
||||||
|
expect(html).toContain("<script>synthetic</script>");
|
||||||
|
expect(html).not.toContain("<form");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a pending configured deadline exposes due actions only when allowed", () => {
|
||||||
|
const html = render({
|
||||||
|
canEdit: false,
|
||||||
|
canCheck: true,
|
||||||
|
deadline: {
|
||||||
|
state: "running",
|
||||||
|
step_id: 2,
|
||||||
|
expires_at: "2026-11-27T12:30:00Z",
|
||||||
|
basis_hash: "a".repeat(64),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(html).toContain("Verificar e executar acções devidas");
|
||||||
|
expect(html).not.toContain("Rever rascunho");
|
||||||
|
expect(html).not.toContain("Devolver ao requisitante</button>");
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user