@@ -3,9 +3,11 @@
|
|||||||
namespace App\Http\Controllers;
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
use App\Models\ConflictDeclaration;
|
use App\Models\ConflictDeclaration;
|
||||||
|
use App\Models\ConflictRelease;
|
||||||
use App\Models\Requisition;
|
use App\Models\Requisition;
|
||||||
use App\Models\Supplier;
|
use App\Models\Supplier;
|
||||||
use App\Services\ConflictGuard;
|
use App\Services\ConflictGuard;
|
||||||
|
use App\Services\ConflictReleases;
|
||||||
use App\Services\RequisitionWorkflow;
|
use App\Services\RequisitionWorkflow;
|
||||||
use Illuminate\Http\RedirectResponse;
|
use Illuminate\Http\RedirectResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
@@ -70,12 +72,23 @@ class ConflictDeclarationController extends Controller
|
|||||||
$latest = $history->last();
|
$latest = $history->last();
|
||||||
|
|
||||||
Inertia::encryptHistory();
|
Inertia::encryptHistory();
|
||||||
$response = Inertia::render('conflicts/show', ['history' => $history, 'canCorrect' => $latest?->user_id === $this->staffIdentity($request)->id])->toResponse($request);
|
$releases = app(ConflictReleases::class);
|
||||||
|
$release = $releases->ready() ? ConflictRelease::query()->where('root_id', $rootId)->first() : null;
|
||||||
|
$response = Inertia::render('conflicts/show', ['history' => $history, 'canCorrect' => $latest?->user_id === $this->staffIdentity($request)->id,
|
||||||
|
'release' => $release, 'canAuthoriseRelease' => $release === null && $latest?->has_conflict === true && $releases->canAuthorise($this->staffIdentity($request)),
|
||||||
|
])->toResponse($request);
|
||||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
return $response;
|
return $response;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function authoriseRelease(Request $request, ConflictDeclaration $declaration, ConflictReleases $releases): RedirectResponse
|
||||||
|
{
|
||||||
|
$releases->authorise($this->staffIdentity($request), $declaration, $request->only(['operation_key', 'reason']));
|
||||||
|
|
||||||
|
return to_route('conflicts.show', $declaration);
|
||||||
|
}
|
||||||
|
|
||||||
public function update(Request $request, ConflictDeclaration $declaration, ConflictGuard $guard, RequisitionWorkflow $workflow): RedirectResponse
|
public function update(Request $request, ConflictDeclaration $declaration, ConflictGuard $guard, RequisitionWorkflow $workflow): RedirectResponse
|
||||||
{
|
{
|
||||||
abort_unless($declaration->user_id === $this->staffIdentity($request)->id, 403);
|
abort_unless($declaration->user_id === $this->staffIdentity($request)->id, 403);
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\Requisition;
|
||||||
|
use App\Services\OperationalOrders;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
final class OperationalOrdersController extends Controller
|
||||||
|
{
|
||||||
|
public function index(Request $request, OperationalOrders $orders, ?Requisition $requisition = null): Response
|
||||||
|
{
|
||||||
|
$request->validate(['page' => 'nullable|integer|min:1|max:1000000']);
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('requisitions/operational-orders', $orders->workspace($this->staffIdentity($request), $requisition))->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function configure(Request $request, OperationalOrders $orders): Response
|
||||||
|
{
|
||||||
|
$orders->configure($this->staffIdentity($request), $request->all());
|
||||||
|
|
||||||
|
return back()->with('success', 'Origem das novas ordens configurada.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function store(Request $request, OperationalOrders $orders): Response
|
||||||
|
{
|
||||||
|
$orders->save($this->staffIdentity($request), $request->all());
|
||||||
|
|
||||||
|
return back()->with('success', 'Ordem registada e original preservado.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function link(Request $request, Requisition $requisition, OperationalOrders $orders): Response
|
||||||
|
{
|
||||||
|
$orders->link($this->staffIdentity($request), $requisition, $request->all());
|
||||||
|
|
||||||
|
return back()->with('success', 'Ordem ligada à linha da requisição.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -15,6 +15,7 @@ use App\Services\OrganizationConfiguration;
|
|||||||
use App\Services\RequisitionApprovalLevels;
|
use App\Services\RequisitionApprovalLevels;
|
||||||
use App\Services\RequisitionCategories;
|
use App\Services\RequisitionCategories;
|
||||||
use App\Services\RequisitionExpiry;
|
use App\Services\RequisitionExpiry;
|
||||||
|
use App\Services\UrgentQuotationBasis;
|
||||||
use App\Services\WorkContext;
|
use App\Services\WorkContext;
|
||||||
use App\Services\WorkflowTasks;
|
use App\Services\WorkflowTasks;
|
||||||
use Brick\Math\BigDecimal;
|
use Brick\Math\BigDecimal;
|
||||||
@@ -52,6 +53,7 @@ class OrganizationConfigurationController extends Controller
|
|||||||
'companyDetails' => Tenant::query()->findOrFail($actor->tenant_id)->company_details,
|
'companyDetails' => Tenant::query()->findOrFail($actor->tenant_id)->company_details,
|
||||||
'companyRules' => $this->companyRules((int) $actor->tenant_id),
|
'companyRules' => $this->companyRules((int) $actor->tenant_id),
|
||||||
'comparisonPolicy' => app(ComparisonPolicy::class)->company(Tenant::query()->findOrFail($actor->tenant_id)),
|
'comparisonPolicy' => app(ComparisonPolicy::class)->company(Tenant::query()->findOrFail($actor->tenant_id)),
|
||||||
|
'urgentQuotationReady' => app(UrgentQuotationBasis::class)->ready(),
|
||||||
'intelligencePolicy' => app(IntelligencePolicy::class)->company(Tenant::query()->findOrFail($actor->tenant_id)),
|
'intelligencePolicy' => app(IntelligencePolicy::class)->company(Tenant::query()->findOrFail($actor->tenant_id)),
|
||||||
'intelligenceReady' => Schema::hasColumn('tenants', 'intelligence_policy'),
|
'intelligenceReady' => Schema::hasColumn('tenants', 'intelligence_policy'),
|
||||||
'aiPlan' => app(AiPreparationPlan::class)->company(Tenant::query()->findOrFail($actor->tenant_id)),
|
'aiPlan' => app(AiPreparationPlan::class)->company(Tenant::query()->findOrFail($actor->tenant_id)),
|
||||||
@@ -98,6 +100,7 @@ class OrganizationConfigurationController extends Controller
|
|||||||
$rules += ['first_limit' => ['required', 'string', 'regex:/^\d{1,12}(\.\d{1,2})?$/D'], 'second_limit' => ['required', 'string', 'regex:/^\d{1,12}(\.\d{1,2})?$/D'], 'includes_tax' => 'required|boolean', 'reason' => 'required|string|min:10|max:4000'];
|
$rules += ['first_limit' => ['required', 'string', 'regex:/^\d{1,12}(\.\d{1,2})?$/D'], 'second_limit' => ['required', 'string', 'regex:/^\d{1,12}(\.\d{1,2})?$/D'], 'includes_tax' => 'required|boolean', 'reason' => 'required|string|min:10|max:4000'];
|
||||||
} elseif ($command === 'comparison') {
|
} elseif ($command === 'comparison') {
|
||||||
$rules += ['minimum_proposals' => 'required|integer|between:1,100', 'minimum_evaluators' => 'required|integer|between:1,100',
|
$rules += ['minimum_proposals' => 'required|integer|between:1,100', 'minimum_evaluators' => 'required|integer|between:1,100',
|
||||||
|
'urgent_minimum_proposals' => 'sometimes|nullable|integer|between:1,100',
|
||||||
'weights' => 'required|array:price,quality,delivery,history,payment', 'reason' => 'required|string|min:10|max:4000'];
|
'weights' => 'required|array:price,quality,delivery,history,payment', 'reason' => 'required|string|min:10|max:4000'];
|
||||||
foreach (array_keys(ComparisonPolicy::DEFAULTS['weights']) as $criterion) {
|
foreach (array_keys(ComparisonPolicy::DEFAULTS['weights']) as $criterion) {
|
||||||
$rules['weights.'.$criterion] = 'required|integer|between:0,100';
|
$rules['weights.'.$criterion] = 'required|integer|between:0,100';
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\PrivateAuditExport;
|
||||||
|
use App\Services\PrivateAuditAccess;
|
||||||
|
use App\Services\PrivateAuditExporter;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\Storage;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
final class PrivateAuditController extends Controller
|
||||||
|
{
|
||||||
|
public function index(Request $request, PrivateAuditAccess $access): Response
|
||||||
|
{
|
||||||
|
$scope = $access->current($this->staffIdentity($request));
|
||||||
|
$request->validate(['page' => 'nullable|integer|min:1|max:1000000']);
|
||||||
|
$exports = PrivateAuditExport::query()->where('created_by', $scope['actor']->id)->where('work_context', $scope['context'])->latest('id')->paginate(20)
|
||||||
|
->through(fn (PrivateAuditExport $export) => ['id' => $export->id, 'families' => $export->families,
|
||||||
|
'created_at' => $export->created_at, 'size' => $export->size, 'sha256' => $export->sha256,
|
||||||
|
'download_url' => '/auditoria/privada/'.$export->id.'/download']);
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('audit/private', ['families' => collect($scope['granted'])->map(fn (string $key) => ['key' => $key, 'label' => PrivateAuditAccess::FAMILIES[$key]['label']])->values(), 'exports' => $exports])->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function store(Request $request, PrivateAuditExporter $service): Response
|
||||||
|
{
|
||||||
|
$service->generate($this->staffIdentity($request), $request->all());
|
||||||
|
|
||||||
|
return redirect('/auditoria/privada')->with('success', 'Pacote privado preparado e verificado.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function download(Request $request, PrivateAuditExport $export, PrivateAuditExporter $service): Response
|
||||||
|
{
|
||||||
|
$actor = $this->staffIdentity($request);
|
||||||
|
$service->verifiedPath($actor, $export);
|
||||||
|
// Snapshot the verified bytes before any response: a later file change cannot alter the download.
|
||||||
|
$copy = tmpfile();
|
||||||
|
abort_unless(is_resource($copy), 503);
|
||||||
|
try {
|
||||||
|
$source = Storage::disk('local')->readStream($export->path);
|
||||||
|
abort_unless(is_resource($source), 409);
|
||||||
|
try {
|
||||||
|
$size = stream_copy_to_stream($source, $copy);
|
||||||
|
} finally {
|
||||||
|
fclose($source);
|
||||||
|
}
|
||||||
|
rewind($copy);
|
||||||
|
$hash = hash_init('sha256');
|
||||||
|
hash_update_stream($hash, $copy);
|
||||||
|
abort_unless($size === $export->size && hash_equals($export->sha256, hash_final($hash)), 409);
|
||||||
|
$service->verifiedPath($actor, $export);
|
||||||
|
rewind($copy);
|
||||||
|
|
||||||
|
return response()->streamDownload(function () use ($copy): void {
|
||||||
|
try {
|
||||||
|
fpassthru($copy);
|
||||||
|
} finally {
|
||||||
|
fclose($copy);
|
||||||
|
}
|
||||||
|
}, 'auditoria-'.$export->id.'.zip', ['Content-Type' => 'application/zip', 'Content-Length' => (string) $export->size,
|
||||||
|
'Cache-Control' => 'private, no-store, max-age=0', 'X-Content-Type-Options' => 'nosniff']);
|
||||||
|
} catch (\Throwable $error) {
|
||||||
|
fclose($copy);
|
||||||
|
throw $error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -18,6 +18,7 @@ use App\Services\QuotationExchange;
|
|||||||
use App\Services\QuotationParticipation;
|
use App\Services\QuotationParticipation;
|
||||||
use App\Services\QuotationPricing;
|
use App\Services\QuotationPricing;
|
||||||
use App\Services\RequisitionWorkflow;
|
use App\Services\RequisitionWorkflow;
|
||||||
|
use App\Services\UrgentQuotationBasis;
|
||||||
use Brick\Math\BigDecimal;
|
use Brick\Math\BigDecimal;
|
||||||
use Brick\Math\RoundingMode;
|
use Brick\Math\RoundingMode;
|
||||||
use Illuminate\Http\RedirectResponse;
|
use Illuminate\Http\RedirectResponse;
|
||||||
@@ -72,6 +73,7 @@ class QuotationController extends Controller
|
|||||||
'ready' => $result['ready'],
|
'ready' => $result['ready'],
|
||||||
'topIds' => $result['top_ids'],
|
'topIds' => $result['top_ids'],
|
||||||
'comparisonPolicy' => $result['policy'],
|
'comparisonPolicy' => $result['policy'],
|
||||||
|
'urgentQuotationReady' => app(UrgentQuotationBasis::class)->ready(),
|
||||||
'exchangeRates' => app(QuotationExchange::class)->rates($requisition),
|
'exchangeRates' => app(QuotationExchange::class)->rates($requisition),
|
||||||
'exchangeAvailable' => app(QuotationExchange::class)->ready(),
|
'exchangeAvailable' => app(QuotationExchange::class)->ready(),
|
||||||
'canRecordExchange' => $actor->hasFunctions([PurchasingRole::Finance]) && ! app(OrganizationAccess::class)->maintenanceOnly($actor)
|
'canRecordExchange' => $actor->hasFunctions([PurchasingRole::Finance]) && ! app(OrganizationAccess::class)->maintenanceOnly($actor)
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ use App\Services\EquipmentWorkflow;
|
|||||||
use App\Services\ImportEstimates;
|
use App\Services\ImportEstimates;
|
||||||
use App\Services\ImportTariffCodes;
|
use App\Services\ImportTariffCodes;
|
||||||
use App\Services\InternalSupplyTrace;
|
use App\Services\InternalSupplyTrace;
|
||||||
|
use App\Services\OperationalOrders;
|
||||||
use App\Services\OrganizationAccess;
|
use App\Services\OrganizationAccess;
|
||||||
use App\Services\RequisitionAuditTrail;
|
use App\Services\RequisitionAuditTrail;
|
||||||
use App\Services\RequisitionBudgetDistributions;
|
use App\Services\RequisitionBudgetDistributions;
|
||||||
@@ -135,6 +136,7 @@ class RequisitionController extends Controller
|
|||||||
'importTariffsReady' => app(ImportTariffCodes::class)->ready(),
|
'importTariffsReady' => app(ImportTariffCodes::class)->ready(),
|
||||||
'importEstimatesReady' => app(ImportEstimates::class)->ready(),
|
'importEstimatesReady' => app(ImportEstimates::class)->ready(),
|
||||||
'capitalRegisterReady' => app(CapitalRegister::class)->ready(),
|
'capitalRegisterReady' => app(CapitalRegister::class)->ready(),
|
||||||
|
'operationalOrdersReady' => app(OperationalOrders::class)->ready(),
|
||||||
'accountsReady' => app(RequisitionLedgerAccounts::class)->ready(),
|
'accountsReady' => app(RequisitionLedgerAccounts::class)->ready(),
|
||||||
'expiryReady' => app(RequisitionExpiry::class)->ready(),
|
'expiryReady' => app(RequisitionExpiry::class)->ready(),
|
||||||
'canDecide' => $requisition->canDecide($this->actor($request)),
|
'canDecide' => $requisition->canDecide($this->actor($request)),
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\Requisition;
|
||||||
|
use App\Services\UrgentQuotationBasis;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
final class UrgentQuotationController extends Controller
|
||||||
|
{
|
||||||
|
public function show(Request $request, Requisition $requisition, UrgentQuotationBasis $service): Response
|
||||||
|
{
|
||||||
|
$request->validate(['page' => 'nullable|integer|min:1|max:1000000']);
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('requisitions/urgent-stock', $service->workspace($this->staffIdentity($request), $requisition))->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function store(Request $request, Requisition $requisition, UrgentQuotationBasis $service): Response
|
||||||
|
{
|
||||||
|
$service->record($this->staffIdentity($request), $requisition, $request->all());
|
||||||
|
|
||||||
|
return back()->with('success', 'Stock mínimo documentado para esta linha e ciclo.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
namespace App\Http\Middleware;
|
namespace App\Http\Middleware;
|
||||||
|
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
|
use App\Services\OperationalOrders;
|
||||||
use App\Services\OrganizationAccess;
|
use App\Services\OrganizationAccess;
|
||||||
use App\Services\SupplierPayables;
|
use App\Services\SupplierPayables;
|
||||||
use App\Services\WorkContext;
|
use App\Services\WorkContext;
|
||||||
@@ -64,6 +65,8 @@ class HandleInertiaRequests extends Middleware
|
|||||||
],
|
],
|
||||||
'payablesAvailable' => $actor !== null && app(SupplierPayables::class)->can($actor, 'view'),
|
'payablesAvailable' => $actor !== null && app(SupplierPayables::class)->can($actor, 'view'),
|
||||||
'orderCancellationAvailable' => $actor !== null && (bool) config('order_cancellation.enabled') && Schema::hasTable('order_cancellations'),
|
'orderCancellationAvailable' => $actor !== null && (bool) config('order_cancellation.enabled') && Schema::hasTable('order_cancellations'),
|
||||||
|
'operationalOrdersAvailable' => $actor !== null && app(OperationalOrders::class)->ready(),
|
||||||
|
'privateAuditAvailable' => $actor !== null && app(\App\Services\PrivateAuditAccess::class)->ready(),
|
||||||
'sidebarOpen' => ! $request->hasCookie('sidebar_state') || $request->cookie('sidebar_state') === 'true',
|
'sidebarOpen' => ! $request->hasCookie('sidebar_state') || $request->cookie('sidebar_state') === 'true',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ namespace App\Models;
|
|||||||
|
|
||||||
use App\Enums\PurchasingRole;
|
use App\Enums\PurchasingRole;
|
||||||
use App\Models\Concerns\BelongsToTenant;
|
use App\Models\Concerns\BelongsToTenant;
|
||||||
|
use App\Services\ConflictReleases;
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
@@ -41,7 +42,7 @@ class ConflictDeclaration extends Model
|
|||||||
/** @param Builder<ConflictDeclaration> $query */
|
/** @param Builder<ConflictDeclaration> $query */
|
||||||
public function scopeVisibleTo(Builder $query, User $user): void
|
public function scopeVisibleTo(Builder $query, User $user): void
|
||||||
{
|
{
|
||||||
if (! $user->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance])) {
|
if (! $user->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance]) && ! app(ConflictReleases::class)->canAuthorise($user)) {
|
||||||
$query->where('user_id', $user->id);
|
$query->where('user_id', $user->id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use App\Models\Concerns\BelongsToTenant;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use LogicException;
|
||||||
|
|
||||||
|
class ConflictRelease extends Model
|
||||||
|
{
|
||||||
|
use BelongsToTenant;
|
||||||
|
|
||||||
|
public $timestamps = false;
|
||||||
|
|
||||||
|
protected $guarded = ['id'];
|
||||||
|
|
||||||
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return ['snapshot' => 'array', 'authorised_at' => 'datetime'];
|
||||||
|
}
|
||||||
|
|
||||||
|
protected static function booted(): void
|
||||||
|
{
|
||||||
|
static::updating(fn () => throw new LogicException('Preservar a autorização da direcção.'));
|
||||||
|
static::deleting(fn () => throw new LogicException('Preservar o histórico do levantamento.'));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use App\Models\Concerns\BelongsToTenant;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use LogicException;
|
||||||
|
|
||||||
|
/** @property list<string> $families */
|
||||||
|
class PrivateAuditExport extends Model
|
||||||
|
{
|
||||||
|
use BelongsToTenant;
|
||||||
|
|
||||||
|
public $timestamps = false;
|
||||||
|
|
||||||
|
protected $guarded = ['id'];
|
||||||
|
|
||||||
|
protected $hidden = ['path', 'input_hash'];
|
||||||
|
|
||||||
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return ['families' => 'array', 'manifest' => 'array', 'created_at' => 'datetime', 'size' => 'integer'];
|
||||||
|
}
|
||||||
|
|
||||||
|
protected static function booted(): void
|
||||||
|
{
|
||||||
|
static::updating(fn () => throw new LogicException('Preservar o pacote e o manifesto originais da auditoria.'));
|
||||||
|
static::deleting(fn () => throw new LogicException('Preservar o histórico da exportação privada.'));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -12,25 +12,26 @@ class ComparisonPolicy
|
|||||||
public const DEFAULTS = ['revision' => 0, 'configured' => false, 'minimum_proposals' => 3, 'minimum_evaluators' => 2,
|
public const DEFAULTS = ['revision' => 0, 'configured' => false, 'minimum_proposals' => 3, 'minimum_evaluators' => 2,
|
||||||
'weights' => ['price' => 40, 'quality' => 20, 'delivery' => 15, 'history' => 15, 'payment' => 10]];
|
'weights' => ['price' => 40, 'quality' => 20, 'delivery' => 15, 'history' => 15, 'payment' => 10]];
|
||||||
|
|
||||||
/** @return array{revision: int, configured: bool, minimum_proposals: int, minimum_evaluators: int, weights: array<string,int>} */
|
/** @return array{revision: int, configured: bool, minimum_proposals: int, minimum_evaluators: int, weights: array<string,int>, urgent_minimum_proposals?: int, normal_minimum_proposals?: int} */
|
||||||
public function company(Tenant $tenant): array
|
public function company(Tenant $tenant): array
|
||||||
{
|
{
|
||||||
return $tenant->comparison_policy === null ? self::DEFAULTS : $this->checked($tenant->comparison_policy);
|
return $tenant->comparison_policy === null ? self::DEFAULTS : $this->checked($tenant->comparison_policy);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return array{revision: int, configured: bool, minimum_proposals: int, minimum_evaluators: int, weights: array<string,int>} */
|
/** @return array{revision: int, configured: bool, minimum_proposals: int, minimum_evaluators: int, weights: array<string,int>, urgent_minimum_proposals?: int, normal_minimum_proposals?: int} */
|
||||||
public function forRequest(Requisition $request): array
|
public function forRequest(Requisition $request): array
|
||||||
{
|
{
|
||||||
return $request->comparison_policy === null ? self::DEFAULTS : $this->checked($request->comparison_policy);
|
return $request->comparison_policy === null ? self::DEFAULTS : $this->checked($request->comparison_policy);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @param array<string,mixed> $data
|
/** @param array<string,mixed> $data
|
||||||
* @return array{revision: int, configured: bool, minimum_proposals: int, minimum_evaluators: int, weights: array<string,int>}
|
* @return array{revision: int, configured: bool, minimum_proposals: int, minimum_evaluators: int, weights: array<string,int>, urgent_minimum_proposals?: int, normal_minimum_proposals?: int}
|
||||||
*/
|
*/
|
||||||
public function checked(array $data): array
|
public function checked(array $data): array
|
||||||
{
|
{
|
||||||
$rules = ['revision' => 'required|integer|min:0', 'configured' => 'required|boolean',
|
$rules = ['revision' => 'required|integer|min:0', 'configured' => 'required|boolean',
|
||||||
'minimum_proposals' => 'required|integer|between:1,100', 'minimum_evaluators' => 'required|integer|between:1,100',
|
'minimum_proposals' => 'required|integer|between:1,100', 'minimum_evaluators' => 'required|integer|between:1,100',
|
||||||
|
'urgent_minimum_proposals' => 'sometimes|nullable|integer|between:1,100',
|
||||||
'weights' => 'required|array:price,quality,delivery,history,payment'];
|
'weights' => 'required|array:price,quality,delivery,history,payment'];
|
||||||
foreach (array_keys(self::DEFAULTS['weights']) as $key) {
|
foreach (array_keys(self::DEFAULTS['weights']) as $key) {
|
||||||
$rules['weights.'.$key] = 'required|integer|between:0,100';
|
$rules['weights.'.$key] = 'required|integer|between:0,100';
|
||||||
@@ -43,8 +44,15 @@ class ComparisonPolicy
|
|||||||
if (array_sum($weights) !== 100) {
|
if (array_sum($weights) !== 100) {
|
||||||
throw ValidationException::withMessages(['weights' => 'A soma das ponderações deve ser exactamente 100%.']);
|
throw ValidationException::withMessages(['weights' => 'A soma das ponderações deve ser exactamente 100%.']);
|
||||||
}
|
}
|
||||||
|
$urgent = [];
|
||||||
|
if (isset($valid['urgent_minimum_proposals'])) {
|
||||||
|
if ((int) $valid['urgent_minimum_proposals'] >= (int) $valid['minimum_proposals']) {
|
||||||
|
throw ValidationException::withMessages(['urgent_minimum_proposals' => 'A redução urgente deve ser inferior ao mínimo normal. Deixe vazio para não permitir redução.']);
|
||||||
|
}
|
||||||
|
$urgent = ['urgent_minimum_proposals' => (int) $valid['urgent_minimum_proposals']];
|
||||||
|
}
|
||||||
|
|
||||||
return ['revision' => (int) $valid['revision'], 'configured' => (bool) $valid['configured'],
|
return ['revision' => (int) $valid['revision'], 'configured' => (bool) $valid['configured'],
|
||||||
'minimum_proposals' => (int) $valid['minimum_proposals'], 'minimum_evaluators' => (int) $valid['minimum_evaluators'], 'weights' => $weights];
|
'minimum_proposals' => (int) $valid['minimum_proposals'], 'minimum_evaluators' => (int) $valid['minimum_evaluators'], 'weights' => $weights, ...$urgent];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,6 +24,10 @@ class ConflictGuard
|
|||||||
public function hasConflict(int $userId, ?int $supplierId, ?int $requisitionId): bool
|
public function hasConflict(int $userId, ?int $supplierId, ?int $requisitionId): bool
|
||||||
{
|
{
|
||||||
return ConflictDeclaration::query()->where('user_id', $userId)->where('has_conflict', true)
|
return ConflictDeclaration::query()->where('user_id', $userId)->where('has_conflict', true)
|
||||||
|
->when(app(ConflictReleases::class)->ready(), fn ($query) => $query->whereNotExists(fn ($release) => $release
|
||||||
|
->selectRaw('1')->from('conflict_releases')
|
||||||
|
->whereColumn('conflict_releases.tenant_id', 'conflict_declarations.tenant_id')
|
||||||
|
->whereRaw('conflict_releases.root_id = COALESCE(conflict_declarations.root_id, conflict_declarations.id)')))
|
||||||
->where(function ($scopes) use ($supplierId, $requisitionId) {
|
->where(function ($scopes) use ($supplierId, $requisitionId) {
|
||||||
// Supplier-wide statements apply only once that supplier is known.
|
// Supplier-wide statements apply only once that supplier is known.
|
||||||
$scopes->where(function ($supplierScope) use ($supplierId) {
|
$scopes->where(function ($supplierScope) use ($supplierId) {
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services;
|
||||||
|
|
||||||
|
use App\Models\ConflictDeclaration;
|
||||||
|
use App\Models\ConflictRelease;
|
||||||
|
use App\Models\User;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
use Illuminate\Support\Facades\Validator;
|
||||||
|
|
||||||
|
/** Explicit direction authority; no legacy Admin/Finance fallback or automatic expiry. */
|
||||||
|
final class ConflictReleases
|
||||||
|
{
|
||||||
|
public function ready(): bool
|
||||||
|
{
|
||||||
|
$db = DB::connection();
|
||||||
|
|
||||||
|
return config('conflict-releases.qa_enabled') === true && app()->environment('testing')
|
||||||
|
&& (($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|
||||||
|
|| ($db->getDriverName() === 'pgsql' && $db->getConfig('host') === '127.0.0.1'
|
||||||
|
&& preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName())))
|
||||||
|
&& Schema::hasTable('conflict_releases');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function canAuthorise(User $actor): bool
|
||||||
|
{
|
||||||
|
if (! $this->ready() || auth()->id() !== $actor->id || $actor->tenant_id === null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
$actor = User::query()->where('tenant_id', $actor->tenant_id)->find($actor->id);
|
||||||
|
|
||||||
|
return $actor !== null && app(OrganizationAccess::class)->allows($actor, ['conflict_release_authorise'])
|
||||||
|
&& ! app(OrganizationAccess::class)->maintenanceOnly($actor);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array<string,mixed> $input */
|
||||||
|
public function authorise(User $actor, ConflictDeclaration $declaration, array $input): ConflictRelease
|
||||||
|
{
|
||||||
|
abort_unless($this->ready(), 503);
|
||||||
|
$data = Validator::make($input, ['operation_key' => 'required|uuid', 'reason' => 'required|string|min:10|max:5000'])->validate();
|
||||||
|
$data['operation_key'] = strtolower($data['operation_key']);
|
||||||
|
|
||||||
|
return DB::transaction(function () use ($actor, $declaration, $data) {
|
||||||
|
app(ConflictGuard::class)->lockCompany($actor);
|
||||||
|
$actor = app(CurrentActor::class)->lock($actor);
|
||||||
|
abort_unless($this->canAuthorise($actor), 403);
|
||||||
|
$declaration = ConflictDeclaration::query()->lockForUpdate()->findOrFail($declaration->id);
|
||||||
|
$rootId = $declaration->root_id ?? $declaration->id;
|
||||||
|
$retry = ConflictRelease::query()->where('operation_key', $data['operation_key'])->first();
|
||||||
|
if ($retry !== null) {
|
||||||
|
abort_unless($retry->declaration_id === $declaration->id && $retry->authorised_by === $actor->id
|
||||||
|
&& $retry->reason === $data['reason'], 409);
|
||||||
|
|
||||||
|
return $retry;
|
||||||
|
}
|
||||||
|
abort_unless($declaration->has_conflict && ! $declaration->successor()->exists(), 409, 'Reabra a declaração mais recente.');
|
||||||
|
abort_if(ConflictRelease::query()->where('root_id', $rootId)->exists(), 409, 'Este impedimento já foi levantado.');
|
||||||
|
$release = ConflictRelease::query()->create(['tenant_id' => $actor->tenant_id, 'root_id' => $rootId,
|
||||||
|
'declaration_id' => $declaration->id, 'authorised_by' => $actor->id, 'operation_key' => $data['operation_key'],
|
||||||
|
'reason' => $data['reason'], 'snapshot' => $declaration->toArray(), 'authorised_at' => now()]);
|
||||||
|
app(RequisitionWorkflow::class)->audit($actor, 'conflict.release_authorised', null, null, $release->toArray());
|
||||||
|
|
||||||
|
return $release;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services;
|
||||||
|
|
||||||
|
use App\Models\SupplyRecord;
|
||||||
|
|
||||||
|
/** Documentary transcription of a specific supplied edition, never a consolidated/current tariff claim. */
|
||||||
|
final class ImportLegalReferenceDrafts
|
||||||
|
{
|
||||||
|
public const EDITION_SHA256 = 'a0110696253715567af39c159a21bacfebc32f944fa43a4efd18070d36959e50';
|
||||||
|
|
||||||
|
/** Page 2180-(4), Annex to Law 8/2025: exact codes and general rates, not preferential rates. */
|
||||||
|
private const ROWS = [
|
||||||
|
['3506.91.10', 'Adesivos à base de polímeros ou borracha', '20'],
|
||||||
|
['3506.91.20', 'Silicone para selagem de painéis solares', '20'],
|
||||||
|
['3810.90.10', 'Fluxo de soldadura de painéis solares', '7.5'],
|
||||||
|
['3810.90.90', 'Outros produtos da subposição 3810.90', '7.5'],
|
||||||
|
['3920.49.10', 'Telas EVA para aderência de componentes de painéis solares', '7.5'],
|
||||||
|
['3920.49.90', 'Outros produtos da subposição 3920.49', '7.5'],
|
||||||
|
['7007.19.10', 'Vidro temperado para produção de painéis solares', '7.5'],
|
||||||
|
['7007.19.90', 'Outros produtos da subposição 7007.19', '7.5'],
|
||||||
|
['7408.29.10', 'Tira metálica para soldadura de painéis solares', '7.5'],
|
||||||
|
['7408.29.90', 'Outros fios de cobre da subposição 7408.29', '7.5'],
|
||||||
|
['7604.10.10', 'Kit de perfis de alumínio para emolduração de painéis solares', '7.5'],
|
||||||
|
];
|
||||||
|
|
||||||
|
/** @return list<array<string,mixed>> */
|
||||||
|
public function forSource(SupplyRecord $source): array
|
||||||
|
{
|
||||||
|
if ($source->kind !== 'import_legal_source' || ($source->snapshot['evidence']['sha256'] ?? null) !== self::EDITION_SHA256) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
// Reuse native original verification; a remembered hash alone cannot vouch for changed bytes.
|
||||||
|
app(ImportEvidence::class)->bytes($source);
|
||||||
|
$drafts = [];
|
||||||
|
foreach (self::ROWS as [$code, $description, $rate]) {
|
||||||
|
$citation = 'Lei 8/2025, de 29 de Dezembro, artigo 2 e anexo, BR I Série 248, suplemento, página 2180-(4), código '.$code.'; início de vigência: artigo 4.';
|
||||||
|
$drafts[] = ['source_id' => $source->id, 'source_sha256' => self::EDITION_SHA256,
|
||||||
|
'code' => $code, 'description' => $description, 'rate_percent' => $rate,
|
||||||
|
'title' => 'Taxa geral documental — '.$code,
|
||||||
|
'official_reference' => $source->data['official_reference'], 'official_url' => $source->data['official_url'] ?? null,
|
||||||
|
'citation' => $citation, 'valid_from' => '2026-01-01',
|
||||||
|
'obligations' => 'Confirmar a descrição completa e as condições no exemplar. Esta preparação transcreve apenas a taxa geral da página 2180-(4); não determina preferência de origem, isenção, ICE, IVA, sobretaxa ou alterações posteriores. Documentar o regime e a base de tributação antes de utilizar uma estimativa.',
|
||||||
|
'charges' => [['key' => 'general_duty', 'kind' => 'duty', 'label' => 'Direitos aduaneiros — taxa geral do exemplar',
|
||||||
|
'method' => 'ad_valorem', 'rate_percent' => $rate, 'specific_minor' => null, 'quantity_unit' => null, 'basis_reference' => $citation]]];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $drafts;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -44,10 +44,27 @@ final class ImportLegalRules
|
|||||||
$rules = app(SupplyPlanning::class)->latest('import_legal_rule')->latest('id')
|
$rules = app(SupplyPlanning::class)->latest('import_legal_rule')->latest('id')
|
||||||
->paginate(15, ['id', 'record_key', 'version', 'state', 'data', 'snapshot', 'reason'], 'rules_page')->withQueryString();
|
->paginate(15, ['id', 'record_key', 'version', 'state', 'data', 'snapshot', 'reason'], 'rules_page')->withQueryString();
|
||||||
$rules->through(fn ($rule) => [...$rule->toArray(), 'source_url' => '/requisicoes/'.$request->id.'/base-legal/fontes/'.$rule->snapshot['source_id']]);
|
$rules->through(fn ($rule) => [...$rule->toArray(), 'source_url' => '/requisicoes/'.$request->id.'/base-legal/fontes/'.$rule->snapshot['source_id']]);
|
||||||
|
$sources = SupplyRecord::query()->where('kind', 'import_legal_source')->latest('id')
|
||||||
|
->paginate(15, ['id', 'tenant_id', 'record_key', 'version', 'kind', 'data', 'snapshot', 'created_at'], 'legal_sources_page')->withQueryString();
|
||||||
|
$referenceDrafts = [];
|
||||||
|
$referenceDraftWarnings = [];
|
||||||
|
if ($actor->hasFunctions(['import_customs'])) {
|
||||||
|
foreach ($sources as $source) {
|
||||||
|
try {
|
||||||
|
array_push($referenceDrafts, ...app(ImportLegalReferenceDrafts::class)->forSource($source));
|
||||||
|
} catch (HttpExceptionInterface $error) {
|
||||||
|
if ($error->getStatusCode() !== 409) {
|
||||||
|
throw $error;
|
||||||
|
}
|
||||||
|
$referenceDraftWarnings[] = ['source_id' => $source->id, 'message' => 'O original da fonte não pôde ser conferido; as suas propostas documentais estão indisponíveis.'];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The UI receives source metadata and drafts, never native private paths.
|
||||||
|
$sources->through(fn ($source) => $source->only(['id', 'data', 'created_at']));
|
||||||
|
|
||||||
return ['requisition' => $request->only(['id', 'number']), 'rules' => $rules,
|
return ['requisition' => $request->only(['id', 'number']), 'rules' => $rules,
|
||||||
'sources' => SupplyRecord::query()->where('kind', 'import_legal_source')->latest('id')
|
'sources' => $sources, 'referenceDrafts' => $referenceDrafts, 'referenceDraftWarnings' => $referenceDraftWarnings,
|
||||||
->paginate(15, ['id', 'data', 'created_at'], 'legal_sources_page')->withQueryString(),
|
|
||||||
'items' => $request->items()->orderBy('id')->get(['id', 'description']),
|
'items' => $request->items()->orderBy('id')->get(['id', 'description']),
|
||||||
'classifications' => app(SupplyPlanning::class)->latest('import_tariff')->where('data->requisition_id', $request->id)->get(['version', 'data']),
|
'classifications' => app(SupplyPlanning::class)->latest('import_tariff')->where('data->requisition_id', $request->id)->get(['version', 'data']),
|
||||||
'canPropose' => $actor->hasFunctions([PurchasingRole::Procurement]),
|
'canPropose' => $actor->hasFunctions([PurchasingRole::Procurement]),
|
||||||
|
|||||||
@@ -129,6 +129,7 @@ final class InternalRequisitionPort implements ExpiryRequisitionPort
|
|||||||
app(EquipmentWorkflow::class)->line($item->toArray(), $r->department_id, $r->priority);
|
app(EquipmentWorkflow::class)->line($item->toArray(), $r->department_id, $r->priority);
|
||||||
}
|
}
|
||||||
app(CapitalAssignments::class)->assertSubmission($this->actor, $r);
|
app(CapitalAssignments::class)->assertSubmission($this->actor, $r);
|
||||||
|
app(OperationalOrders::class)->assertSubmission($this->actor, $r);
|
||||||
app(RequisitionAccountAssignments::class)->assertSubmission($this->actor, $r);
|
app(RequisitionAccountAssignments::class)->assertSubmission($this->actor, $r);
|
||||||
app(EquipmentWorkflow::class)->assertTechnical($r);
|
app(EquipmentWorkflow::class)->assertTechnical($r);
|
||||||
if ($r->needed_by < today()) {
|
if ($r->needed_by < today()) {
|
||||||
|
|||||||
@@ -0,0 +1,253 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services;
|
||||||
|
|
||||||
|
use App\Models\Department;
|
||||||
|
use App\Models\Requisition;
|
||||||
|
use App\Models\RequisitionItem;
|
||||||
|
use App\Models\SupplyRecord;
|
||||||
|
use App\Models\User;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
use Illuminate\Support\Facades\Validator;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Illuminate\Validation\ValidationException;
|
||||||
|
|
||||||
|
/** Documentary production/maintenance orders owned by Compras; no production scheduling or SGF writes. */
|
||||||
|
final class OperationalOrders
|
||||||
|
{
|
||||||
|
public function ready(): bool
|
||||||
|
{
|
||||||
|
$db = DB::connection();
|
||||||
|
|
||||||
|
return config('operational-orders.qa_enabled') === true && app()->environment('testing')
|
||||||
|
&& (($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|
||||||
|
|| ($db->getDriverName() === 'pgsql' && $db->getConfig('host') === '127.0.0.1'
|
||||||
|
&& preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName())))
|
||||||
|
&& Schema::hasTable('supply_records');
|
||||||
|
}
|
||||||
|
|
||||||
|
private function actor(User $actor): User
|
||||||
|
{
|
||||||
|
abort_unless($this->ready(), 503);
|
||||||
|
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);
|
||||||
|
|
||||||
|
return $actor;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function policy(): ?SupplyRecord
|
||||||
|
{
|
||||||
|
return app(SupplyPlanning::class)->latest('op_order_policy')->first();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return list<string> */
|
||||||
|
private function types(User $actor, ?SupplyRecord $policy): array
|
||||||
|
{
|
||||||
|
if ($policy === null) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
if ($policy->data['mode'] === 'procurement') {
|
||||||
|
return $actor->hasFunctions(['procurement']) ? ['production', 'maintenance'] : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
return array_values(array_filter(['production', 'maintenance'], fn ($type) => $actor->hasFunctions([$type.'_order_prepare'])));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string,mixed> */
|
||||||
|
public function workspace(User $actor, ?Requisition $request = null): array
|
||||||
|
{
|
||||||
|
return DB::transaction(function () use ($actor, $request) {
|
||||||
|
$actor = $this->actor($actor);
|
||||||
|
$policy = $this->policy();
|
||||||
|
if ($request !== null) {
|
||||||
|
$request = Requisition::query()->visibleTo($actor)->findOrFail($request->id);
|
||||||
|
} else {
|
||||||
|
abort_unless($actor->hasFunctions(['admin', 'procurement', 'requester', 'production_order_prepare', 'maintenance_order_prepare']), 403);
|
||||||
|
}
|
||||||
|
$canLink = $request !== null && $request->status === 'draft' && $request->requester_id === $actor->id
|
||||||
|
&& app(OrganizationAccess::class)->canRequest($actor) && ! app(ConflictGuard::class)->participationBlocked($actor, $request);
|
||||||
|
$links = $request === null ? collect() : app(SupplyPlanning::class)->latest('op_order_link')->where('data->requisition_id', $request->id)->get();
|
||||||
|
$linkedIds = [];
|
||||||
|
foreach ($links as $link) {
|
||||||
|
$linkedIds[] = $link->data['order_id'];
|
||||||
|
}
|
||||||
|
$allDepartments = $actor->hasFunctions(['admin', 'procurement']);
|
||||||
|
$orders = app(SupplyPlanning::class)->latest('op_order')
|
||||||
|
->when($request !== null && ! $canLink, fn ($q) => $q->whereIn('id', $linkedIds))
|
||||||
|
->when($request !== null, fn ($q) => $q->where('data->department_id', $request->department_id))
|
||||||
|
->when($request === null && ! $allDepartments, fn ($q) => $q->where('data->department_id', $actor->department_id));
|
||||||
|
|
||||||
|
return ['actorId' => $actor->id, 'tenantId' => $actor->tenant_id, 'policy' => $policy,
|
||||||
|
'canConfigure' => $actor->hasFunctions(['admin']), 'allowedTypes' => $this->types($actor, $policy),
|
||||||
|
'departments' => Department::query()->when(! $allDepartments, fn ($q) => $q->whereKey($actor->department_id))->orderBy('name')->get(['id', 'name']),
|
||||||
|
'orders' => $orders->latest('id')->paginate(15)->withQueryString(),
|
||||||
|
'requisition' => $request?->only(['id', 'number', 'status']),
|
||||||
|
'items' => $request?->items()->get(['id', 'description']) ?? [],
|
||||||
|
'links' => $links, 'canLink' => $canLink,
|
||||||
|
];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array<string,mixed> $input */
|
||||||
|
public function configure(User $actor, array $input): SupplyRecord
|
||||||
|
{
|
||||||
|
$data = Validator::make($input, ['version' => 'required|integer|min:0', 'mode' => 'required|in:utilisation,procurement',
|
||||||
|
'reason' => 'required|string|min:10|max:4000', 'operation_key' => 'required|uuid'])->validate();
|
||||||
|
|
||||||
|
return DB::transaction(function () use ($actor, $data) {
|
||||||
|
$actor = $this->actor($actor);
|
||||||
|
abort_unless($actor->hasFunctions(['admin']), 403);
|
||||||
|
$retry = $this->retry($actor, 'op_order_policy', $data);
|
||||||
|
if ($retry !== null) {
|
||||||
|
return $retry;
|
||||||
|
}
|
||||||
|
$old = $this->policy();
|
||||||
|
abort_unless((int) $data['version'] === ($old->version ?? 0), 409);
|
||||||
|
|
||||||
|
return $this->record($actor, 'op_order_policy', $data, ['mode' => $data['mode']], [], $old);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array<string,mixed> $input */
|
||||||
|
public function save(User $actor, array $input): SupplyRecord
|
||||||
|
{
|
||||||
|
$data = Validator::make($input, ['type' => 'required|in:production,maintenance', 'reference' => 'required|string|min:3|max:120',
|
||||||
|
'department_id' => 'required|integer|min:1', 'utilisation_location' => 'required|string|min:3|max:300',
|
||||||
|
'description' => 'required|string|min:10|max:4000', 'reason' => 'required|string|min:10|max:4000',
|
||||||
|
'policy_version' => 'required|integer|min:1', 'operation_key' => 'required|uuid'])->validate();
|
||||||
|
|
||||||
|
return DB::transaction(function () use ($actor, $data) {
|
||||||
|
$actor = $this->actor($actor);
|
||||||
|
$policy = $this->policy();
|
||||||
|
abort_unless(in_array($data['type'], $this->types($actor, $policy), true), 403);
|
||||||
|
$retry = $this->retry($actor, 'op_order', $data);
|
||||||
|
if ($retry !== null) {
|
||||||
|
return $retry;
|
||||||
|
}
|
||||||
|
abort_unless((int) $data['policy_version'] === $policy?->version, 409, 'A origem das ordens mudou. Reveja a configuração.');
|
||||||
|
$department = Department::query()->whereKey($data['department_id'])
|
||||||
|
->when($policy->data['mode'] === 'utilisation', fn ($q) => $q->whereKey($actor->department_id))->firstOrFail();
|
||||||
|
abort_if(SupplyRecord::query()->where('kind', 'op_order')->where('data->type', $data['type'])
|
||||||
|
->where('data->department_id', $department->id)->where('data->reference', trim($data['reference']))->exists(), 409, 'Esta referência já está registada neste departamento.');
|
||||||
|
|
||||||
|
return $this->record($actor, 'op_order', $data, ['type' => $data['type'], 'reference' => trim($data['reference']),
|
||||||
|
'department_id' => $department->id, 'utilisation_location' => $data['utilisation_location'], 'description' => $data['description']],
|
||||||
|
['policy' => $policy->only(['id', 'version', 'data']), 'author' => $actor->only(['id', 'name']), 'department' => $department->only(['id', 'name'])]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array<string,mixed> $input */
|
||||||
|
public function link(User $actor, Requisition $request, array $input): SupplyRecord
|
||||||
|
{
|
||||||
|
$data = Validator::make($input, ['item_id' => 'required|integer|min:1', 'order_id' => 'required|integer|min:1',
|
||||||
|
'version' => 'required|integer|min:0', 'reason' => 'required|string|min:10|max:4000', 'operation_key' => 'required|uuid'])->validate();
|
||||||
|
$data['requisition_id'] = $request->id;
|
||||||
|
|
||||||
|
return DB::transaction(function () use ($actor, $request, $data) {
|
||||||
|
$actor = $this->actor($actor);
|
||||||
|
$request = Requisition::query()->visibleTo($actor)->lockForUpdate()->findOrFail($request->id);
|
||||||
|
abort_unless($request->requester_id === $actor->id && app(OrganizationAccess::class)->canRequest($actor), 403);
|
||||||
|
app(ConflictGuard::class)->assertParticipation($actor, $request);
|
||||||
|
$retry = $this->retry($actor, 'op_order_link', $data);
|
||||||
|
if ($retry !== null) {
|
||||||
|
return $retry;
|
||||||
|
}
|
||||||
|
abort_unless($request->status === 'draft', 409);
|
||||||
|
$item = $request->items()->whereKey($data['item_id'])->firstOrFail();
|
||||||
|
$order = app(SupplyPlanning::class)->latest('op_order')->whereKey($data['order_id'])->where('data->department_id', $request->department_id)->firstOrFail();
|
||||||
|
$old = app(SupplyPlanning::class)->latest('op_order_link')->where('data->requisition_item_id', $item->id)->first();
|
||||||
|
abort_unless((int) $data['version'] === ($old->version ?? 0), 409);
|
||||||
|
|
||||||
|
return $this->record($actor, 'op_order_link', $data, ['requisition_id' => $request->id, 'requisition_item_id' => $item->id, 'order_id' => $order->id],
|
||||||
|
['item' => $this->item($item), 'source' => $order->toArray()], $old, $request);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string,mixed> */
|
||||||
|
private function item(RequisitionItem $item): array
|
||||||
|
{
|
||||||
|
return $item->only(['id', 'description', 'quantity', 'unit', 'equipment_id', 'spare_part_id', 'category_context']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function assertSubmission(User $actor, Requisition $request): void
|
||||||
|
{
|
||||||
|
$items = $request->items()->get();
|
||||||
|
$ids = [];
|
||||||
|
foreach ($items as $item) {
|
||||||
|
$ids[] = $item->id;
|
||||||
|
}
|
||||||
|
$frozen = $this->freezeForItems($actor, $ids);
|
||||||
|
if (! $this->ready() || $this->policy() === null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
foreach ($items as $item) {
|
||||||
|
$expected = match ($item->category_context['category'] ?? null) {
|
||||||
|
'production_input' => 'production', 'spare_part' => 'maintenance', default => null,
|
||||||
|
};
|
||||||
|
if ($expected !== null && ($frozen[$item->id]['snapshot']['source']['data']['type'] ?? null) !== $expected) {
|
||||||
|
throw ValidationException::withMessages(['op_order' => 'Ligue cada insumo de produção ou peça à ordem de produção/manutenção correspondente antes de submeter. Não foram criadas reservas ou aprovações.']);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param list<int> $ids
|
||||||
|
* @return array<int,array<string,mixed>>
|
||||||
|
*/
|
||||||
|
public function freezeForItems(User $actor, array $ids): array
|
||||||
|
{
|
||||||
|
if (! Schema::hasTable('supply_records')) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
$links = app(SupplyPlanning::class)->latest('op_order_link')->whereIn('data->requisition_item_id', $ids)->get();
|
||||||
|
if ($links->isEmpty()) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
abort_unless($this->ready() && auth()->id() === $actor->id, 503);
|
||||||
|
$result = [];
|
||||||
|
foreach ($links as $link) {
|
||||||
|
$item = RequisitionItem::query()->whereKey($link->data['requisition_item_id'])->firstOrFail();
|
||||||
|
Requisition::query()->visibleTo($actor)->findOrFail($item->requisition_id);
|
||||||
|
abort_unless($link->snapshot['item'] === $this->item($item), 409, 'A linha mudou. Reveja a ordem de origem.');
|
||||||
|
$result[$item->id] = $link->only(['id', 'version', 'data', 'snapshot', 'reason']);
|
||||||
|
}
|
||||||
|
ksort($result, SORT_NUMERIC);
|
||||||
|
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array<string,mixed> $input */
|
||||||
|
private function retry(User $actor, string $kind, array $input): ?SupplyRecord
|
||||||
|
{
|
||||||
|
$record = SupplyRecord::query()->where('operation_key', strtolower($input['operation_key']))->first();
|
||||||
|
if ($record !== null) {
|
||||||
|
abort_unless($record->kind === $kind && $record->created_by === $actor->id && hash_equals($record->input_hash, $this->hash($input)), 409);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $record;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array<string,mixed> $input */
|
||||||
|
private function hash(array $input): string
|
||||||
|
{
|
||||||
|
$input['operation_key'] = strtolower($input['operation_key']);
|
||||||
|
|
||||||
|
return hash('sha256', json_encode($input, JSON_THROW_ON_ERROR));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array<string,mixed> $input
|
||||||
|
* @param array<string,mixed> $data
|
||||||
|
* @param array<string,mixed> $snapshot
|
||||||
|
*/
|
||||||
|
private function record(User $actor, string $kind, array $input, array $data, array $snapshot, ?SupplyRecord $old = null, ?Requisition $request = null): SupplyRecord
|
||||||
|
{
|
||||||
|
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => $kind, 'record_key' => $old->record_key ?? (string) Str::uuid(),
|
||||||
|
'version' => ($old->version ?? 0) + 1, 'state' => 'recorded', 'data' => $data, 'snapshot' => $snapshot,
|
||||||
|
'created_by' => $actor->id, 'created_at' => now(), 'reason' => $input['reason'], 'operation_key' => strtolower($input['operation_key']), 'input_hash' => $this->hash($input)]);
|
||||||
|
app(RequisitionWorkflow::class)->audit($actor, $kind.'.recorded', $request, $old?->toArray(), ['record' => $record->toArray()]);
|
||||||
|
|
||||||
|
return $record;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -196,7 +196,7 @@ final class OrderPartsWorkflow
|
|||||||
$prepared = app(OrderPartsPreparation::class)->prepare($actor, $selection);
|
$prepared = app(OrderPartsPreparation::class)->prepare($actor, $selection);
|
||||||
abort_unless(hash_equals($prepared['fingerprint'], $data['fingerprint']), 409, 'A preparação mudou; consulte as origens actuais.');
|
abort_unless(hash_equals($prepared['fingerprint'], $data['fingerprint']), 409, 'A preparação mudou; consulte as origens actuais.');
|
||||||
$this->checkAllocations($actor, $prepared['sources'], $budgetSources);
|
$this->checkAllocations($actor, $prepared['sources'], $budgetSources);
|
||||||
$frames = $requests = $lines = $catalogue = $tariffs = $capital = $accounts = [];
|
$frames = $requests = $lines = $catalogue = $tariffs = $capital = $accounts = $operational = [];
|
||||||
$firstQuote = null;
|
$firstQuote = null;
|
||||||
foreach ($prepared['sources'] as $source) {
|
foreach ($prepared['sources'] as $source) {
|
||||||
$request = Requisition::query()->whereKey($source['requisition_id'])->firstOrFail();
|
$request = Requisition::query()->whereKey($source['requisition_id'])->firstOrFail();
|
||||||
@@ -210,6 +210,7 @@ final class OrderPartsWorkflow
|
|||||||
$requested = $request->items()->get()->keyBy('id');
|
$requested = $request->items()->get()->keyBy('id');
|
||||||
$tariffs += app(ImportTariffCodes::class)->freezeForItems($actor, array_column($source['items'], 'requisition_item_id'));
|
$tariffs += app(ImportTariffCodes::class)->freezeForItems($actor, array_column($source['items'], 'requisition_item_id'));
|
||||||
$capital += app(CapitalAssignments::class)->freezeForItems($actor, array_column($source['items'], 'requisition_item_id'));
|
$capital += app(CapitalAssignments::class)->freezeForItems($actor, array_column($source['items'], 'requisition_item_id'));
|
||||||
|
$operational += app(OperationalOrders::class)->freezeForItems($actor, array_column($source['items'], 'requisition_item_id'));
|
||||||
$accounts += app(RequisitionAccountAssignments::class)->freezeForItems($actor, array_column($source['items'], 'requisition_item_id'));
|
$accounts += app(RequisitionAccountAssignments::class)->freezeForItems($actor, array_column($source['items'], 'requisition_item_id'));
|
||||||
foreach ($source['items'] as $item) {
|
foreach ($source['items'] as $item) {
|
||||||
$native = $requested->get($item['requisition_item_id']);
|
$native = $requested->get($item['requisition_item_id']);
|
||||||
@@ -229,7 +230,8 @@ final class OrderPartsWorkflow
|
|||||||
'award' => [...$source['award_terms'], 'id' => $award->id], 'approval_rules' => $award->approval_snapshot,
|
'award' => [...$source['award_terms'], 'id' => $award->id], 'approval_rules' => $award->approval_snapshot,
|
||||||
'investment_rules' => $award->investment_snapshot, 'admission' => $award->admission_snapshot, 'recommendation' => $award->recommendation_snapshot,
|
'investment_rules' => $award->investment_snapshot, 'admission' => $award->admission_snapshot, 'recommendation' => $award->recommendation_snapshot,
|
||||||
'estimate_approvals' => $request->steps()->get()->toArray(), 'final_approvals' => $award->approvals()->get()->toArray(),
|
'estimate_approvals' => $request->steps()->get()->toArray(), 'final_approvals' => $award->approvals()->get()->toArray(),
|
||||||
'decision_matrix' => $award->decision_matrix, 'comparison_policy' => app(ComparisonPolicy::class)->forRequest($request),
|
'decision_matrix' => $award->decision_matrix, 'comparison_policy' => app(ProposalComparison::class)->inspect($request)['policy'],
|
||||||
|
...(app(UrgentQuotationBasis::class)->eligible($request) === [] ? [] : ['urgent_quotation_basis' => app(UrgentQuotationBasis::class)->eligible($request)]),
|
||||||
'native_preparation' => $source];
|
'native_preparation' => $source];
|
||||||
}
|
}
|
||||||
$first = $prepared['sources'][0];
|
$first = $prepared['sources'][0];
|
||||||
@@ -244,6 +246,7 @@ final class OrderPartsWorkflow
|
|||||||
'exchange_sources' => array_map(fn ($s) => ['requisition_id' => $s['requisition_id'], 'exchange_basis' => $s['exchange_basis']], $prepared['sources']),
|
'exchange_sources' => array_map(fn ($s) => ['requisition_id' => $s['requisition_id'], 'exchange_basis' => $s['exchange_basis']], $prepared['sources']),
|
||||||
'reference_amounts' => app(OrderPartsExchange::class)->sum(array_column($prepared['sources'], 'reference_amounts'))] : [];
|
'reference_amounts' => app(OrderPartsExchange::class)->sum(array_column($prepared['sources'], 'reference_amounts'))] : [];
|
||||||
$snapshot = [...$frames[0], ...$limits, ...$exchange, ...($tariffs === [] ? [] : ['import_tariffs' => $tariffs]), ...($capital === [] ? [] : ['capital_assignments' => $capital]), ...($accounts === [] ? [] : ['account_assignments' => $accounts]), 'company' => Tenant::query()->whereKey($actor->tenant_id)->firstOrFail()->only(['id', 'name']),
|
$snapshot = [...$frames[0], ...$limits, ...$exchange, ...($tariffs === [] ? [] : ['import_tariffs' => $tariffs]), ...($capital === [] ? [] : ['capital_assignments' => $capital]), ...($accounts === [] ? [] : ['account_assignments' => $accounts]), 'company' => Tenant::query()->whereKey($actor->tenant_id)->firstOrFail()->only(['id', 'name']),
|
||||||
|
...($operational === [] ? [] : ['operational_orders' => $operational]),
|
||||||
'supplier' => $firstQuote->supplier?->only(['id', 'name', 'nuit', 'contact', 'email', 'phone', 'address']),
|
'supplier' => $firstQuote->supplier?->only(['id', 'name', 'nuit', 'contact', 'email', 'phone', 'address']),
|
||||||
'issuer' => $actor->only(['id', 'name']), 'items' => $lines, 'catalogue_sources' => $catalogue,
|
'issuer' => $actor->only(['id', 'name']), 'items' => $lines, 'catalogue_sources' => $catalogue,
|
||||||
'budget_control' => $commit, 'development_only' => true, 'budget_checked' => true,
|
'budget_control' => $commit, 'development_only' => true, 'budget_checked' => true,
|
||||||
|
|||||||
@@ -10,6 +10,13 @@ use Illuminate\Support\Facades\Schema;
|
|||||||
class OrganizationAccess
|
class OrganizationAccess
|
||||||
{
|
{
|
||||||
public const PERMISSIONS = [
|
public const PERMISSIONS = [
|
||||||
|
'audit_private_purchasing_read' => 'Auditoria privada: exportar compras e origens, sem cadastro bancário completo nem Pessoas',
|
||||||
|
'audit_private_stock_read' => 'Auditoria privada: exportar recepções, stock e movimentos físicos',
|
||||||
|
'audit_private_finance_read' => 'Auditoria privada: exportar orçamento, facturas e pagamentos, sem identificadores bancários completos',
|
||||||
|
'audit_private_configuration_read' => 'Auditoria privada: exportar regras, perfis e alterações de configuração, sem segredos',
|
||||||
|
'production_order_prepare' => 'Responsável da produção: registar ordens nos locais de utilização abrangidos',
|
||||||
|
'maintenance_order_prepare' => 'Chefe de oficina: registar ordens de manutenção nos locais abrangidos',
|
||||||
|
'conflict_release_authorise' => 'Direcção: consultar declarações e autorizar o levantamento de impedimentos por conflito de interesses',
|
||||||
'audit_metadata_read' => 'Consultar e exportar metadados de eventos de todos os módulos da empresa, sem conteúdos privados',
|
'audit_metadata_read' => 'Consultar e exportar metadados de eventos de todos os módulos da empresa, sem conteúdos privados',
|
||||||
'warehouse_return_read' => 'Consultar devoluções de excedentes de entregas internas',
|
'warehouse_return_read' => 'Consultar devoluções de excedentes de entregas internas',
|
||||||
'warehouse_return_prepare' => 'Declarar excedente não consumido de entrega interna própria',
|
'warehouse_return_prepare' => 'Declarar excedente não consumido de entrega interna própria',
|
||||||
|
|||||||
@@ -0,0 +1,75 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services;
|
||||||
|
|
||||||
|
use App\Models\User;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
/** Separate private read authority approved by the owner; never a Finance/Admin/metadata fallback. */
|
||||||
|
final class PrivateAuditAccess
|
||||||
|
{
|
||||||
|
public const FAMILIES = [
|
||||||
|
'purchasing' => ['permission' => 'audit_private_purchasing_read', 'label' => 'Compras e documentos de origem'],
|
||||||
|
'stock' => ['permission' => 'audit_private_stock_read', 'label' => 'Recepções, stock e movimentos físicos'],
|
||||||
|
'finance' => ['permission' => 'audit_private_finance_read', 'label' => 'Orçamento, facturas e pagamentos registados'],
|
||||||
|
'configuration' => ['permission' => 'audit_private_configuration_read', 'label' => 'Regras, perfis e alterações da configuração'],
|
||||||
|
];
|
||||||
|
|
||||||
|
public function ready(): bool
|
||||||
|
{
|
||||||
|
$db = DB::connection();
|
||||||
|
|
||||||
|
return config('private-audit.qa_enabled') === true && app()->environment('testing')
|
||||||
|
&& (($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|
||||||
|
|| ($db->getDriverName() === 'pgsql' && $db->getConfig('host') === '127.0.0.1'
|
||||||
|
&& preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName())))
|
||||||
|
&& Schema::hasTable('private_audit_exports');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array{actor:User,context:string,granted:list<string>} */
|
||||||
|
public function current(User $candidate): array
|
||||||
|
{
|
||||||
|
abort_unless($this->ready(), 503);
|
||||||
|
abort_unless(auth()->id() === $candidate->id && $candidate->tenant_id !== null && auth()->user()?->tenant_id === $candidate->tenant_id, 403);
|
||||||
|
$actor = User::query()->where('tenant_id', $candidate->tenant_id)->whereKey($candidate->id)->firstOrFail();
|
||||||
|
$access = app(OrganizationAccess::class);
|
||||||
|
abort_if($access->maintenanceOnly($actor), 403);
|
||||||
|
$contexts = app(WorkContext::class);
|
||||||
|
$context = 'legacy';
|
||||||
|
if ($contexts->enforced($actor)) {
|
||||||
|
abort_unless(app()->bound('request') && request()->hasSession() && $contexts->active(request()) === 'procurement.internal', 403);
|
||||||
|
$context = 'procurement.internal';
|
||||||
|
}
|
||||||
|
$permissions = $access->permissions($actor, $context === 'legacy' ? null : $context);
|
||||||
|
$granted = [];
|
||||||
|
foreach (self::FAMILIES as $key => $definition) {
|
||||||
|
if (in_array($definition['permission'], $permissions, true)) {
|
||||||
|
$granted[] = $key;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
abort_unless($granted !== [], 403);
|
||||||
|
|
||||||
|
return ['actor' => $actor, 'context' => $context, 'granted' => $granted];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Untrusted family selection from the export request is validated before producing a typed scope.
|
||||||
|
* @param array<array-key,mixed> $families
|
||||||
|
* @return array{actor:User,context:string,families:list<string>}
|
||||||
|
*/
|
||||||
|
public function authorise(User $candidate, array $families): array
|
||||||
|
{
|
||||||
|
$state = $this->current($candidate);
|
||||||
|
abort_unless($families !== [] && count($families) <= count(self::FAMILIES) && array_is_list($families), 422);
|
||||||
|
$selected = [];
|
||||||
|
foreach ($families as $family) {
|
||||||
|
abort_unless(is_string($family) && isset(self::FAMILIES[$family]), 422);
|
||||||
|
abort_unless(in_array($family, $state['granted'], true), 403);
|
||||||
|
$selected[] = $family;
|
||||||
|
}
|
||||||
|
$selected = array_values(array_unique($selected));
|
||||||
|
sort($selected);
|
||||||
|
|
||||||
|
return ['actor' => $state['actor'], 'context' => $state['context'], 'families' => $selected];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,205 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services;
|
||||||
|
|
||||||
|
/** Fixed positive column registry derived from the isolated checked schema, not runtime discovery. */
|
||||||
|
final class PrivateAuditCatalogue
|
||||||
|
{
|
||||||
|
/** @var array<string,array<string,string>> */
|
||||||
|
public const TABLES = [
|
||||||
|
'purchasing' => [
|
||||||
|
'admission_adoptions' => 'id tenant_id requisition_id admission_policy_id created_by revision snapshot reason created_at',
|
||||||
|
'admission_decisions' => 'id tenant_id admission_adoption_id qualification_set_id quotation_id created_by revision outcome basis_hash snapshot reason created_at',
|
||||||
|
'admission_policies' => 'id tenant_id created_by revision enabled roles required_count reason created_at',
|
||||||
|
'admission_reviews' => 'id tenant_id admission_decision_id reviewed_by verdict reason snapshot created_at',
|
||||||
|
'approval_steps' => 'id tenant_id requisition_id position role decision approver_id comment decided_at routing approval_cycle',
|
||||||
|
'award_cancellations' => 'id tenant_id purchase_award_id purchase_control_policy_id created_by reviewed_by status basis_hash reason review_reason snapshot reviewed_at created_at updated_at',
|
||||||
|
'conflict_declarations' => 'id tenant_id user_id supplier_id requisition_id has_conflict known_since reason declared_at root_id previous_id',
|
||||||
|
'conflict_releases' => 'id tenant_id root_id declaration_id authorised_by operation_key reason snapshot authorised_at',
|
||||||
|
'criticality_levels' => 'id tenant_id created_by code name criteria is_critical created_at',
|
||||||
|
'investment_policies' => 'id tenant_id created_by revision status mode scope currency ceiling_minor includes_tax valid_from valid_until reason decided_at created_at updated_at',
|
||||||
|
'investment_policy_reviews' => 'id tenant_id investment_policy_id reviewed_by decision reason created_at',
|
||||||
|
'order_cancellation_policies' => 'id tenant_id created_by revision status mode enabled valid_from valid_until reason decided_at created_at updated_at',
|
||||||
|
'order_cancellation_policy_reviews' => 'id tenant_id purchase_control_policy_id reviewed_by decision reason created_at',
|
||||||
|
'order_cancellations' => 'id tenant_id purchase_order_id policy_id created_by operation_key input_hash basis_hash snapshot status reason evidence reviewed_by review_reason reviewed_at revised_requisition_id created_at updated_at',
|
||||||
|
'proposal_evaluations' => 'id tenant_id quotation_id evaluator_id quality history payment comment no_conflict created_at updated_at',
|
||||||
|
'proposal_openings' => 'id tenant_id requisition_id created_by revision opened_at timezone submission_deadline reference location reason notes participants annexes snapshot basis_hash created_at',
|
||||||
|
'purchase_award_approvals' => 'id tenant_id purchase_award_id position role decision approver_id comment decided_at',
|
||||||
|
'purchase_awards' => 'id tenant_id requisition_id quotation_id created_by justification delivery_date delivery_location status subtotal_minor tax_minor total_minor approval_snapshot decision_matrix comparison_hash created_at updated_at investment_snapshot admission_snapshot recommendation_snapshot',
|
||||||
|
'purchase_control_policies' => 'id tenant_id created_by revision status mode enabled valid_from valid_until reason decided_at created_at updated_at',
|
||||||
|
'purchase_control_reviews' => 'id tenant_id purchase_control_policy_id reviewed_by decision reason created_at',
|
||||||
|
'purchase_order_items' => 'id tenant_id purchase_order_id requisition_item_id description category purchase_type unit quantity unit_price_minor tax_rate subtotal_minor tax_minor total_minor equipment_id spare_part_id quotation_item_id quantity_offset_milli',
|
||||||
|
'purchase_order_sources' => 'id tenant_id purchase_order_id requisition_id purchase_award_id quotation_id snapshot',
|
||||||
|
'purchase_orders' => 'id tenant_id requisition_id purchase_award_id supplier_id issued_by number status currency subtotal_minor tax_minor total_minor snapshot issued_at order_key order_payload_hash order_source_count',
|
||||||
|
'purchase_plan_items' => 'id tenant_id department_id requisition_id created_by responsible_id title nature version created_at updated_at',
|
||||||
|
'purchase_plan_milestones' => 'id tenant_id purchase_plan_item_id created_by label planned_on actual_on version created_at updated_at',
|
||||||
|
'purchase_revisions' => 'id tenant_id award_cancellation_id source_requisition_id requisition_id created_by created_at',
|
||||||
|
'qualification_assessments' => 'id tenant_id qualification_set_id quotation_id analyst_id revision answers snapshot reason created_at',
|
||||||
|
'qualification_sets' => 'id tenant_id requisition_id created_by revision criteria snapshot basis_hash reason created_at',
|
||||||
|
'quotation_exchange_rates' => 'id tenant_id requisition_id recorded_by currency rate quoted_on source operation_id payload_hash created_at',
|
||||||
|
'quotation_items' => 'id tenant_id quotation_id requisition_item_id description quantity unit_price_minor tax_rate subtotal_minor tax_minor total_minor created_at updated_at',
|
||||||
|
'quotations' => 'id tenant_id requisition_id supplier_id created_by reference delivery_days valid_until payment_terms subtotal_minor tax_minor total_minor currency weights created_at updated_at commercial_terms exchange_basis',
|
||||||
|
'recommendation_adoptions' => 'id tenant_id requisition_id recommendation_policy_id created_by revision snapshot reason created_at',
|
||||||
|
'recommendation_attempts' => 'id tenant_id recommendation_adoption_id quotation_id created_by revision basis_hash snapshot reason created_at',
|
||||||
|
'recommendation_policies' => 'id tenant_id created_by revision enabled roles required_count reason created_at',
|
||||||
|
'recommendation_reviews' => 'id tenant_id recommendation_attempt_id reviewed_by verdict reason snapshot created_at',
|
||||||
|
'requisition_catalogue' => 'id tenant_id stock_item_id category purchase_type source_snapshot published version created_at updated_at',
|
||||||
|
'requisition_commands' => 'id tenant_id actor_id operation_key request_hash result created_at',
|
||||||
|
'requisition_items' => 'id tenant_id requisition_id description category purchase_type quantity unit unit_price_minor tax_rate subtotal_minor tax_minor total_minor equipment_id spare_part_id production_area downtime_started_at catalogue_entry_id catalogue_snapshot category_context',
|
||||||
|
'requisitions' => 'id tenant_id number requester_id department_id cost_center_id priority needed_by justification status currency subtotal_minor tax_minor total_minor approval_snapshot submitted_at created_at updated_at comparison_policy work_context_key process_version draft_input budget_distribution_preparation approval_cycle',
|
||||||
|
'supplier_documents' => 'id tenant_id supplier_id uploaded_by document_type original_name mime_type size sha256 created_at updated_at',
|
||||||
|
'supplier_evaluations' => 'id tenant_id supplier_id department_id created_by submitted_by reviewed_by previous_id operation_key creation_hash revision version status contributors supplier_snapshot payload review_reason reviewed_at created_at updated_at',
|
||||||
|
'supplier_improvements' => 'id tenant_id supplier_evaluation_id created_by responsible_id operation_key creation_hash title description due_on version status contributors result evidence reviewed_by review_reason reviewed_at created_at updated_at',
|
||||||
|
'supplier_responses' => 'id tenant_id supplier_evaluation_id created_by operation_key creation_hash version status payload contributors decision reviewed_by review_reason reviewed_at created_at updated_at',
|
||||||
|
'suppliers' => 'id tenant_id created_by name nuit contact email phone address category beneficiaries document_references diligence_notes blocked status next_review reviewed_by review_comment created_at updated_at last_changed_by version geography_reference',
|
||||||
|
'technical_reviews' => 'id tenant_id requisition_id reviewed_by basis_hash decision reason snapshot reviewed_at',
|
||||||
|
'workflow_notices' => 'id tenant_id requisition_id approval_step_id recipient_id reference role created_at read_at event_kind',
|
||||||
|
],
|
||||||
|
'stock' => [
|
||||||
|
'equipment' => 'id tenant_id created_by department_id stock_item_id criticality_level_id code description area serial_number status version created_at updated_at geography_reference',
|
||||||
|
'equipment_spare_parts' => 'id tenant_id equipment_id spare_part_id created_by created_at',
|
||||||
|
'goods_receipt_items' => 'id tenant_id goods_receipt_id purchase_order_item_id stock_item_id received_milli accepted_milli rejected_milli quality_status notes snapshot',
|
||||||
|
'goods_receipts' => 'id tenant_id purchase_order_id received_by warehouse_id number idempotency_key payload_hash delivery_note received_on status snapshot confirmed_at',
|
||||||
|
'inventory_lot_allocations' => 'id tenant_id stock_item_id warehouse_id lot_id stock_movement_id setup_record_id quantity_milli created_at',
|
||||||
|
'receipt_documents' => 'id tenant_id goods_receipt_id uploaded_by document_type original_name mime_type size sha256 created_at',
|
||||||
|
'replenishment_work' => 'id tenant_id stock_item_id warehouse_id responsible_id generation processed_generation attempts failures last_outcome last_error due_at last_run_at created_at updated_at',
|
||||||
|
'spare_parts' => 'id tenant_id created_by stock_item_id criticality_level_id minimum_milli version created_at updated_at',
|
||||||
|
'stock_items' => 'id tenant_id created_by code name unit created_at updated_at',
|
||||||
|
'stock_movements' => 'id tenant_id goods_receipt_item_id stock_item_id warehouse_id moved_by movement_type quantity_milli snapshot moved_at stock_operation_id equipment_id spare_part_id',
|
||||||
|
'stock_operations' => 'id tenant_id created_by responsible_id warehouse_id destination_warehouse_id stock_item_id count_id kind reference idempotency_key payload_hash destination reason quantity_milli theoretical_milli ledger_version snapshot recorded_at equipment_id spare_part_id',
|
||||||
|
'warehouse_request_events' => 'id tenant_id warehouse_request_id actor_id version operation_key input_hash action data reason created_at',
|
||||||
|
'warehouse_requests' => 'id tenant_id created_by warehouse_id cost_center_id work_context_key operation_key input_hash status snapshot created_at',
|
||||||
|
'warehouse_reservations' => 'id tenant_id warehouse_request_id line_index stock_item_id warehouse_id authorization_event_id actor_id command_key kind quantity_milli created_at',
|
||||||
|
'warehouses' => 'id tenant_id created_by code name created_at updated_at geography_reference',
|
||||||
|
],
|
||||||
|
'finance' => [
|
||||||
|
'budget_consumptions' => 'id tenant_id budget_id invoice_id created_by amount_minor created_at',
|
||||||
|
'budget_distribution_consumptions' => 'id tenant_id distribution_id allocation_key budget_id invoice_id amount_minor subtotal_minor total_minor created_by created_at',
|
||||||
|
'budget_distribution_entries' => 'id tenant_id distribution_id allocation_key budget_id kind reserved_minor committed_minor created_by created_at',
|
||||||
|
'budget_distribution_events' => 'id tenant_id distribution_id kind operation_key payload_hash result snapshot created_by created_at',
|
||||||
|
'budget_distributions' => 'id tenant_id requisition_id phase snapshot created_by created_at updated_at requisition_cycle',
|
||||||
|
'budget_entries' => 'id tenant_id budget_id requisition_id created_by kind reserved_minor committed_minor created_at requisition_cycle',
|
||||||
|
'budget_landed_commands' => 'id tenant_id created_by operation_key plan_key plan_version plan_hash kind payload_hash snapshot created_at',
|
||||||
|
'budget_landed_entries' => 'id tenant_id command_id budget_id source_key source_kind source_id source_version source_revision source_snapshot reserved_minor committed_minor consumed_minor',
|
||||||
|
'budget_order_allocations' => 'id tenant_id command_id distribution_id order_key allocation_key budget_id subtotal_minor total_minor amount_minor kind',
|
||||||
|
'budget_order_bindings' => 'id tenant_id command_id distribution_id source_version',
|
||||||
|
'budget_order_commands' => 'id tenant_id kind document_key operation_key payload_hash result snapshot created_by created_at',
|
||||||
|
'budget_order_consumptions' => 'id tenant_id command_id distribution_id order_key allocation_key budget_id subtotal_minor total_minor amount_minor invoice_id',
|
||||||
|
'budget_reinforcements' => 'id tenant_id budget_id created_by reviewed_by reference payload_hash amount_minor reason status review_reason reviewed_at created_at updated_at',
|
||||||
|
'budget_requisition_cycles' => 'id tenant_id requisition_id cycle state open_operation opened_by opened_at close_operation closed_by closed_at',
|
||||||
|
'budgets' => 'id tenant_id cost_center_id year amount_minor includes_tax reason created_by approved_by approved_at created_at updated_at kind',
|
||||||
|
'external_payments' => 'id tenant_id invoice_id supplier_bank_detail_id created_by reviewed_by status amount_minor currency paid_on external_reference reference_hash payload_hash evidence_reference review_reason reviewed_at created_at updated_at',
|
||||||
|
'gl_accounts' => 'id tenant_id company_id unit_id code label is_movement currency',
|
||||||
|
'gl_commands' => 'id tenant_id company_id unit_id actor_id command_key request_hash result created_at',
|
||||||
|
'gl_events' => 'id tenant_id company_id unit_id actor_id person kind entity_id reason previous subsequent created_at',
|
||||||
|
'gl_journals' => 'id tenant_id company_id unit_id effect_key obligation_id proposal_id review_id source_revision journal_on currency debit_minor credit_minor snapshot posted_by posted_person reason created_at',
|
||||||
|
'gl_lines' => 'id tenant_id company_id unit_id journal_id line_no account_id debit_minor credit_minor',
|
||||||
|
'gl_periods' => 'id tenant_id company_id unit_id period_key version starts_on ends_on status created_by reason created_at',
|
||||||
|
'gl_proposals' => 'id tenant_id company_id unit_id effect_key obligation_id capture_version revision snapshot prepared_by prepared_person reason created_at',
|
||||||
|
'gl_reviews' => 'id tenant_id company_id unit_id proposal_id revision decision reviewed_by reviewed_person reason created_at',
|
||||||
|
'gl_rules' => 'id tenant_id company_id unit_id rule_key version policy effect_type currency valid_from valid_to debit_account_id credit_account_id created_by reason created_at',
|
||||||
|
'invoice_items' => 'id tenant_id invoice_id purchase_order_item_id quantity_milli subtotal_minor tax_minor snapshot',
|
||||||
|
'invoices' => 'id tenant_id purchase_order_id supplier_id created_by validated_by number issued_on status subtotal_minor tax_minor total_minor snapshot validated_at created_at updated_at',
|
||||||
|
'pa_commands' => 'id tenant_id company_id unit_id actor_id command_key request_hash result created_at',
|
||||||
|
'pa_events' => 'id tenant_id company_id unit_id source_id actor_id kind payload created_at',
|
||||||
|
'pa_history_imports' => 'id tenant_id company_id unit_id obligation_id source_id source_key history_hash confirmed_minor pending_minor rejected_minor snapshot imported_by created_at',
|
||||||
|
'pa_imported_payments' => 'id tenant_id company_id unit_id obligation_id source_id payment_key legacy_payment_id amount_minor status snapshot created_at',
|
||||||
|
'pa_obligations' => 'id tenant_id company_id unit_id source_id proposal_id source_revision principal_minor currency due_on recognised_by recognised_person reason created_at',
|
||||||
|
'pa_outbox' => 'event_id state',
|
||||||
|
'pa_payment_decisions' => 'id tenant_id company_id unit_id obligation_id imported_payment_id sequence previous_hash history_hash payment_snapshot actor_id created_at',
|
||||||
|
'pa_proposals' => 'id tenant_id company_id unit_id source_id source_revision capture_version snapshot missing prepared_by prepared_person reason created_at',
|
||||||
|
'pa_sources' => 'id tenant_id company_id unit_id source_key local_source_id created_at',
|
||||||
|
'sgf_invoice_dispatch_events' => 'id dispatch_id tenant_id version actor_id action reason before_state after_state created_at',
|
||||||
|
'sgf_invoice_dispatches' => 'id tenant_id supplier_id reference number connection_id mapping_id mapping_snapshot mapping_hash document reason source_version version phase ever_sending approval_hash preview_actor_id source_context_hash operation_key lease_until receipt created_by created_at updated_at',
|
||||||
|
],
|
||||||
|
'configuration' => [
|
||||||
|
'cost_centers' => 'id tenant_id department_id code name created_at updated_at',
|
||||||
|
'departments' => 'id tenant_id name created_at updated_at',
|
||||||
|
'organization_access' => 'id tenant_id active version created_at updated_at',
|
||||||
|
'organization_memberships' => 'id tenant_id user_id profile_id maintenance expires_at reason created_at updated_at',
|
||||||
|
'organization_profiles' => 'id tenant_id name permissions version created_at updated_at work_contexts',
|
||||||
|
'pa_access' => 'id tenant_id company_id unit_id user_id person action',
|
||||||
|
'private_audit_exports' => 'id tenant_id created_by operation_key work_context families size sha256 manifest_sha256 created_at',
|
||||||
|
'procurement_saved_searches' => 'id tenant_id user_id name term active_name_key version archived_at created_at updated_at',
|
||||||
|
'tenants' => 'id name currency first_limit_minor second_limit_minor approval_includes_tax rules_provisional created_at updated_at default_tax_rate comparison_policy intelligence_policy work_context_policy geography_reference company_details requisition_approval_policy',
|
||||||
|
'users' => 'id name email email_verified_at created_at updated_at tenant_id department_id purchasing_role two_factor_confirmed_at',
|
||||||
|
],
|
||||||
|
];
|
||||||
|
|
||||||
|
/** JSON columns are explicit for SQLite as well as native PostgreSQL JSON types. */
|
||||||
|
public const JSON_COLUMNS = [
|
||||||
|
'admission_adoptions' => ['snapshot'],
|
||||||
|
'admission_decisions' => ['snapshot'],
|
||||||
|
'admission_policies' => ['roles'],
|
||||||
|
'admission_reviews' => ['snapshot'],
|
||||||
|
'audit_logs' => ['after', 'before'],
|
||||||
|
'award_cancellations' => ['snapshot'],
|
||||||
|
'candidate_events' => ['metadata'],
|
||||||
|
'candidate_profile_versions' => ['data'],
|
||||||
|
'candidate_submissions' => ['snapshot'],
|
||||||
|
'conflict_releases' => ['snapshot'],
|
||||||
|
'goods_receipt_items' => ['snapshot'],
|
||||||
|
'goods_receipts' => ['snapshot'],
|
||||||
|
'invoice_items' => ['snapshot'],
|
||||||
|
'invoices' => ['snapshot'],
|
||||||
|
'order_cancellations' => ['snapshot'],
|
||||||
|
'organization_profiles' => ['permissions', 'work_contexts'],
|
||||||
|
'pa_commands' => ['result'],
|
||||||
|
'pa_events' => ['payload'],
|
||||||
|
'pa_history_imports' => ['snapshot'],
|
||||||
|
'pa_imported_payments' => ['snapshot'],
|
||||||
|
'pa_payment_decisions' => ['payment_snapshot'],
|
||||||
|
'pa_proposals' => ['missing', 'snapshot'],
|
||||||
|
'people_applications' => ['person_snapshot'],
|
||||||
|
'people_clarifications' => ['decisions', 'responses'],
|
||||||
|
'people_process_access' => ['scopes'],
|
||||||
|
'people_processes' => ['contract', 'rules', 'selection'],
|
||||||
|
'people_reviews' => ['answers'],
|
||||||
|
'private_audit_exports' => ['families', 'manifest'],
|
||||||
|
'proposal_openings' => ['annexes', 'participants', 'snapshot'],
|
||||||
|
'ps_allocation_aliases' => ['payload', 'result'],
|
||||||
|
'ps_allocation_decisions' => ['payload', 'result'],
|
||||||
|
'ps_allocations' => ['payload', 'result'],
|
||||||
|
'ps_commands' => ['payload', 'result'],
|
||||||
|
'ps_events' => ['payload'],
|
||||||
|
'ps_payment_decisions' => ['payload', 'plan', 'result'],
|
||||||
|
'ps_payments' => ['payload', 'plan', 'result', 'snapshot'],
|
||||||
|
'ps_proposals' => ['payload', 'plan', 'result'],
|
||||||
|
'purchase_awards' => ['approval_snapshot', 'decision_matrix'],
|
||||||
|
'purchase_orders' => ['snapshot'],
|
||||||
|
'qualification_assessments' => ['answers', 'snapshot'],
|
||||||
|
'qualification_sets' => ['criteria', 'snapshot'],
|
||||||
|
'quotations' => ['exchange_basis', 'weights'],
|
||||||
|
'recommendation_adoptions' => ['snapshot'],
|
||||||
|
'recommendation_attempts' => ['snapshot'],
|
||||||
|
'recommendation_policies' => ['roles'],
|
||||||
|
'recommendation_reviews' => ['snapshot'],
|
||||||
|
'requisition_catalogue' => ['source_snapshot'],
|
||||||
|
'requisition_commands' => ['result'],
|
||||||
|
'requisition_items' => ['catalogue_snapshot'],
|
||||||
|
'requisitions' => ['approval_snapshot', 'draft_input', 'result'],
|
||||||
|
'sgf_invoice_dispatch_events' => ['after_state', 'before_state'],
|
||||||
|
'sgf_invoice_dispatches' => ['document', 'mapping_snapshot', 'receipt'],
|
||||||
|
'stock_items' => ['source_snapshot'],
|
||||||
|
'stock_movements' => ['snapshot'],
|
||||||
|
'stock_operations' => ['snapshot'],
|
||||||
|
'submission_forms' => ['definition'],
|
||||||
|
'supplier_evaluations' => ['contributors', 'payload', 'supplier_snapshot'],
|
||||||
|
'supplier_improvements' => ['contributors'],
|
||||||
|
'supplier_responses' => ['contributors', 'decision', 'payload'],
|
||||||
|
'technical_reviews' => ['snapshot'],
|
||||||
|
'tenants' => ['company_details', 'intelligence_policy', 'work_context_policy'],
|
||||||
|
'warehouse_request_events' => ['data'],
|
||||||
|
'warehouse_requests' => ['snapshot'],
|
||||||
|
];
|
||||||
|
|
||||||
|
public const SUPPLY_COLUMNS = 'id tenant_id kind record_key version state stock_item_id warehouse_id supplier_id purchase_order_id created_by data snapshot reason operation_key input_hash created_at';
|
||||||
|
|
||||||
|
/** Banking and People families have no table, source or permission in this approved contract. */
|
||||||
|
public const SUPPLY_KINDS = [
|
||||||
|
'purchasing' => ['agreement', 'contract', 'import', 'capital_register', 'capital_assignment', 'import_party', 'import_document', 'import_legal_source', 'import_legal_rule', 'import_tariff', 'stock_tariff', 'op_order', 'op_order_link', 'op_order_policy', 'urgent_stock_basis', 'urgent_review', 'urgent_review_policy', 'req_expiration', 'req_expiry_policy', 'req_timeout_check'],
|
||||||
|
'stock' => ['auto_need', 'auto_rule', 'lot', 'lot_setup', 'lot_state', 'stock_event', 'stock_reversal', 'reservation', 'delivery', 'issue', 'alternative', 'suggestion', 'history', 'warehouse_return', 'workshop_return'],
|
||||||
|
'finance' => ['expense_allocation', 'req_account', 'import_bank_support', 'import_cost_doc', 'import_cost_event', 'import_cost_plan', 'import_estimate', 'import_legal_amount'],
|
||||||
|
'configuration' => [],
|
||||||
|
];
|
||||||
|
}
|
||||||
@@ -0,0 +1,164 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services;
|
||||||
|
|
||||||
|
use App\Models\PrivateAuditExport;
|
||||||
|
use App\Models\User;
|
||||||
|
use Generator;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Storage;
|
||||||
|
use Illuminate\Support\Facades\Validator;
|
||||||
|
use RuntimeException;
|
||||||
|
use ZipArchive;
|
||||||
|
|
||||||
|
final class PrivateAuditExporter
|
||||||
|
{
|
||||||
|
/** @param array<string,mixed> $input */
|
||||||
|
public function generate(User $candidate, array $input): PrivateAuditExport
|
||||||
|
{
|
||||||
|
$data = Validator::make($input, ['operation_key' => 'required|uuid', 'families' => 'required|array|min:1|max:4', 'purpose' => 'nullable|string|max:500'])->validate();
|
||||||
|
$scope = app(PrivateAuditAccess::class)->authorise($candidate, $data['families']);
|
||||||
|
$actor = $scope['actor'];
|
||||||
|
$operation = strtolower($data['operation_key']);
|
||||||
|
$purpose = trim($data['purpose'] ?? '');
|
||||||
|
$inputHash = hash('sha256', json_encode(['schema' => 'compras.private-audit.v1', 'tenant' => $actor->tenant_id,
|
||||||
|
'actor' => $actor->id, 'context' => $scope['context'], 'families' => $scope['families'], 'purpose' => $purpose], JSON_THROW_ON_ERROR));
|
||||||
|
$existing = PrivateAuditExport::query()->where('created_by', $actor->id)->where('operation_key', $operation)->first();
|
||||||
|
if ($existing !== null) {
|
||||||
|
abort_unless(hash_equals($existing->input_hash, $inputHash), 409, 'A operação já corresponde a outra selecção.');
|
||||||
|
$this->verifiedPath($actor, $existing);
|
||||||
|
|
||||||
|
return $existing;
|
||||||
|
}
|
||||||
|
abort_unless(class_exists(ZipArchive::class), 503, 'Preparação ZIP indisponível nesta instalação.');
|
||||||
|
$files = new PrivateAuditFiles($actor);
|
||||||
|
$archivePath = null;
|
||||||
|
$keep = [];
|
||||||
|
try {
|
||||||
|
$manifest = DB::transaction(function () use ($actor, $scope, $purpose, $files): array {
|
||||||
|
if (DB::getDriverName() === 'pgsql') {
|
||||||
|
abort_unless(DB::transactionLevel() === 1, 503, 'A auditoria requer a sua própria leitura consistente.');
|
||||||
|
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||||
|
}
|
||||||
|
$manifest = ['schema' => 'compras.private-audit.v1', 'generated_at' => now()->toIso8601String(),
|
||||||
|
'tenant_id' => $actor->tenant_id, 'actor_id' => $actor->id, 'work_context' => $scope['context'], 'families' => $scope['families'], 'purpose' => $purpose,
|
||||||
|
'source_semantics' => 'Stored source facts and curated history; no new balance calculations or business commands.',
|
||||||
|
'excluded' => ['complete_bank_registers', 'bank_specific_import_documents', 'private_people_data_and_documents', 'credentials', 'arbitrary_audit_payloads', 'native_storage_paths'],
|
||||||
|
'original_semantics' => 'Business originals retain their verified bytes; files are not rewritten or certified by this export.',
|
||||||
|
'datasets' => [], 'originals' => []];
|
||||||
|
foreach (app(PrivateAuditSourceReader::class)->datasets($actor, $scope['families']) as $dataset) {
|
||||||
|
$entry = array_intersect_key($dataset, array_flip(['family', 'source', 'state', 'columns', 'missing_columns']));
|
||||||
|
if ($dataset['rows'] === null) {
|
||||||
|
$manifest['datasets'][] = [...$entry, 'records' => null];
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$count = 0;
|
||||||
|
$content = static function () use ($dataset, &$count): Generator {
|
||||||
|
foreach ($dataset['rows'] as $row) {
|
||||||
|
$count++;
|
||||||
|
yield json_encode($row, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)."\n";
|
||||||
|
}
|
||||||
|
};
|
||||||
|
$written = $files->write($dataset['file'], $content());
|
||||||
|
$manifest['datasets'][] = [...$entry, 'records' => $count, ...array_intersect_key($written, array_flip(['file', 'size', 'sha256']))];
|
||||||
|
}
|
||||||
|
foreach (app(PrivateAuditOriginals::class)->files($actor, $scope['families']) as $original) {
|
||||||
|
$written = $files->write($original['file'], $original['bytes']);
|
||||||
|
abort_unless($written['size'] === $original['size'] && hash_equals($original['sha256'], $written['sha256']), 409, 'A cópia do original não coincide com os bytes verificados.');
|
||||||
|
$manifest['originals'][] = array_intersect_key($original, array_flip(['family', 'source', 'source_id', 'original_name', 'mime_type', 'file', 'size', 'sha256']));
|
||||||
|
}
|
||||||
|
|
||||||
|
return $manifest;
|
||||||
|
});
|
||||||
|
// Revalidate after the snapshot, so a concurrent revocation is not hidden by repeatable read.
|
||||||
|
$fresh = app(PrivateAuditAccess::class)->authorise($actor, $scope['families']);
|
||||||
|
abort_unless($fresh['context'] === $scope['context'], 409, 'O contexto mudou; prepare uma nova exportação.');
|
||||||
|
$manifestBytes = json_encode($manifest, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)."\n";
|
||||||
|
$manifestFile = $files->write('manifesto.json', $manifestBytes);
|
||||||
|
$archivePath = $files->path('auditoria.zip');
|
||||||
|
$zip = new ZipArchive;
|
||||||
|
if ($zip->open($archivePath, ZipArchive::CREATE | ZipArchive::EXCL) !== true) {
|
||||||
|
throw new RuntimeException('Não foi possível preparar o arquivo ZIP.');
|
||||||
|
}
|
||||||
|
$members = [...array_column($manifest['datasets'], 'file'), ...array_column($manifest['originals'], 'file'), 'manifesto.json'];
|
||||||
|
try {
|
||||||
|
foreach ($members as $member) {
|
||||||
|
$path = $member === 'manifesto.json' ? $manifestFile['path'] : Storage::disk('local')->path($files->relative.'/'.$member);
|
||||||
|
if (! $zip->addFile($path, $member)) {
|
||||||
|
throw new RuntimeException('Não foi possível incluir um membro do pacote.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
$closed = $zip->close();
|
||||||
|
if (is_file($archivePath)) {
|
||||||
|
$files->created($archivePath);
|
||||||
|
}
|
||||||
|
if (! $closed) {
|
||||||
|
throw new RuntimeException('Não foi possível concluir o pacote privado.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$sha = hash_file('sha256', $archivePath);
|
||||||
|
$size = filesize($archivePath);
|
||||||
|
if ($sha === false || $size === false || $size < 1) {
|
||||||
|
throw new RuntimeException('Não foi possível verificar o pacote privado.');
|
||||||
|
}
|
||||||
|
$export = DB::transaction(function () use ($actor, $scope, $operation, $inputHash, $files, $size, $sha, $manifestBytes, $manifest) {
|
||||||
|
app(ConflictGuard::class)->lockCompany($actor);
|
||||||
|
$actor = app(CurrentActor::class)->lock($actor);
|
||||||
|
$current = app(PrivateAuditAccess::class)->authorise($actor, $scope['families']);
|
||||||
|
abort_unless($current['context'] === $scope['context'], 409);
|
||||||
|
$retry = PrivateAuditExport::query()->where('created_by', $actor->id)->where('operation_key', $operation)->first();
|
||||||
|
if ($retry !== null) {
|
||||||
|
abort_unless(hash_equals($retry->input_hash, $inputHash), 409);
|
||||||
|
|
||||||
|
return $retry;
|
||||||
|
}
|
||||||
|
$export = PrivateAuditExport::query()->create(['tenant_id' => $actor->tenant_id, 'created_by' => $actor->id,
|
||||||
|
'operation_key' => $operation, 'input_hash' => $inputHash, 'work_context' => $scope['context'], 'families' => $scope['families'],
|
||||||
|
'path' => $files->relative.'/auditoria.zip', 'size' => $size, 'sha256' => $sha,
|
||||||
|
'manifest_sha256' => hash('sha256', $manifestBytes), 'manifest' => $manifest, 'created_at' => now()]);
|
||||||
|
app(RequisitionWorkflow::class)->audit($actor, 'audit.private_export_generated', null, null,
|
||||||
|
['export_id' => $export->id, 'families' => $scope['families'], 'sha256' => $sha, 'manifest_sha256' => $export->manifest_sha256]);
|
||||||
|
|
||||||
|
return $export;
|
||||||
|
});
|
||||||
|
if ($export->path === $files->relative.'/auditoria.zip') {
|
||||||
|
$keep = [$archivePath];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $export;
|
||||||
|
} finally {
|
||||||
|
$files->cleanup($keep);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Validate both current family authority and the immutable private package before download/replay. */
|
||||||
|
public function verifiedPath(User $candidate, PrivateAuditExport $export): string
|
||||||
|
{
|
||||||
|
$scope = app(PrivateAuditAccess::class)->authorise($candidate, $export->families);
|
||||||
|
$actor = $scope['actor'];
|
||||||
|
abort_unless($export->tenant_id === $actor->tenant_id && $export->created_by === $actor->id, 404);
|
||||||
|
abort_unless($scope['context'] === $export->work_context, 409, 'Seleccione o contexto original da exportação.');
|
||||||
|
$prefix = 'audit-exports/'.$actor->tenant_id.'/'.$actor->id.'/';
|
||||||
|
abort_unless(preg_match('/^'.preg_quote($prefix, '/').'[a-f0-9-]{36}\/auditoria\.zip$/D', $export->path) === 1, 409);
|
||||||
|
$disk = Storage::disk('local');
|
||||||
|
$root = realpath($disk->path(''));
|
||||||
|
$path = realpath($disk->path($export->path));
|
||||||
|
$expected = $root === false ? '' : str_replace('\\', '/', $root).'/'.$prefix;
|
||||||
|
$normal = $path === false ? '' : str_replace('\\', '/', $path);
|
||||||
|
$within = PHP_OS_FAMILY === 'Windows' ? str_starts_with(strtolower($normal), strtolower($expected)) : str_starts_with($normal, $expected);
|
||||||
|
abort_unless($root !== false && $path !== false && $within && is_file($path) && ! is_link($disk->path($export->path))
|
||||||
|
&& filesize($path) === $export->size && hash_equals($export->sha256, hash_file('sha256', $path) ?: ''), 409, 'O pacote original está indisponível ou alterado.');
|
||||||
|
$zip = new ZipArchive;
|
||||||
|
abort_unless($zip->open($path, ZipArchive::RDONLY) === true, 409, 'O pacote original não pôde ser verificado.');
|
||||||
|
try {
|
||||||
|
$bytes = $zip->getFromName('manifesto.json');
|
||||||
|
abort_unless(is_string($bytes) && hash_equals($export->manifest_sha256, hash('sha256', $bytes)), 409, 'O manifesto do pacote mudou.');
|
||||||
|
} finally {
|
||||||
|
$zip->close();
|
||||||
|
}
|
||||||
|
|
||||||
|
return $path;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services;
|
||||||
|
|
||||||
|
use App\Models\User;
|
||||||
|
use Illuminate\Support\Facades\Storage;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use LogicException;
|
||||||
|
use RuntimeException;
|
||||||
|
|
||||||
|
/** Only new, individually tracked files in an owned QA workspace; never recursive deletion. */
|
||||||
|
final class PrivateAuditFiles
|
||||||
|
{
|
||||||
|
public readonly string $relative;
|
||||||
|
|
||||||
|
private string $root;
|
||||||
|
|
||||||
|
/** @var list<string> */
|
||||||
|
private array $createdFiles = [];
|
||||||
|
|
||||||
|
/** @var list<string> */
|
||||||
|
private array $createdDirectories = [];
|
||||||
|
|
||||||
|
public function __construct(User $actor)
|
||||||
|
{
|
||||||
|
$disk = Storage::disk('local');
|
||||||
|
$boundary = realpath(base_path('storage/framework/testing'));
|
||||||
|
$storageRoot = realpath($disk->path(''));
|
||||||
|
abort_unless($actor->id === auth()->id() && $actor->tenant_id !== null && $boundary !== false && $storageRoot !== false
|
||||||
|
&& $this->within($storageRoot, $boundary), 503, 'A exportação requer armazenamento QA isolado.');
|
||||||
|
$public = realpath(public_path());
|
||||||
|
abort_if($public !== false && $this->within($storageRoot, $public), 503, 'O pacote de auditoria não pode usar armazenamento público.');
|
||||||
|
$this->relative = 'audit-exports/'.$actor->tenant_id.'/'.$actor->id.'/'.Str::uuid();
|
||||||
|
$this->root = $disk->path($this->relative);
|
||||||
|
$parent = $storageRoot;
|
||||||
|
foreach (['audit-exports', (string) $actor->tenant_id, (string) $actor->id] as $component) {
|
||||||
|
$parent .= DIRECTORY_SEPARATOR.$component;
|
||||||
|
abort_if(is_link($parent), 409, 'Preserve o armazenamento privado sem ligações externas.');
|
||||||
|
if (! file_exists($parent) && ! mkdir($parent, 0700)) {
|
||||||
|
throw new RuntimeException('Não foi possível preparar o armazenamento privado.');
|
||||||
|
}
|
||||||
|
$resolved = realpath($parent);
|
||||||
|
abort_unless($resolved !== false && is_dir($resolved) && $this->within($resolved, $storageRoot), 409);
|
||||||
|
}
|
||||||
|
abort_if(file_exists($this->root) || is_link($this->root), 409);
|
||||||
|
if (! mkdir($this->root, 0700)) {
|
||||||
|
throw new RuntimeException('Não foi possível preparar o directório privado.');
|
||||||
|
}
|
||||||
|
$this->createdDirectories[] = $this->root;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function within(string $path, string $boundary): bool
|
||||||
|
{
|
||||||
|
$path = str_replace('\\', '/', $path);
|
||||||
|
$boundary = rtrim(str_replace('\\', '/', $boundary), '/').'/';
|
||||||
|
|
||||||
|
return PHP_OS_FAMILY === 'Windows' ? str_starts_with(strtolower($path), strtolower($boundary)) : str_starts_with($path, $boundary);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function path(string $member): string
|
||||||
|
{
|
||||||
|
if (! preg_match('/\A[a-z0-9_\/.\-]+\z/D', $member) || str_starts_with($member, '/') || str_contains($member, '..') || str_contains($member, '//')) {
|
||||||
|
throw new LogicException('Nome interno do pacote inválido.');
|
||||||
|
}
|
||||||
|
$directory = $this->root;
|
||||||
|
$parts = explode('/', $member);
|
||||||
|
array_pop($parts);
|
||||||
|
foreach ($parts as $part) {
|
||||||
|
$directory .= DIRECTORY_SEPARATOR.$part;
|
||||||
|
if (! file_exists($directory)) {
|
||||||
|
if (! mkdir($directory, 0700)) {
|
||||||
|
throw new RuntimeException('Não foi possível preparar um membro do pacote.');
|
||||||
|
}
|
||||||
|
$this->createdDirectories[] = $directory;
|
||||||
|
}
|
||||||
|
if (is_link($directory) || ! is_dir($directory)) {
|
||||||
|
throw new LogicException('Preserve o directório privado de preparação.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$target = $this->root.DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $member);
|
||||||
|
if (file_exists($target) || is_link($target)) {
|
||||||
|
throw new LogicException('Não substituir um membro já preparado.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $target;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Register only a file that this operation has successfully created. */
|
||||||
|
public function created(string $path): void
|
||||||
|
{
|
||||||
|
$resolved = realpath($path);
|
||||||
|
$root = realpath($this->root);
|
||||||
|
if ($resolved === false || $root === false || ! $this->within($resolved, $root) || is_link($path) || ! is_file($resolved)) {
|
||||||
|
throw new LogicException('Ficheiro fora do pacote privado.');
|
||||||
|
}
|
||||||
|
$this->createdFiles[] = $path;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param iterable<string>|string $content
|
||||||
|
* @return array{file:string,path:string,size:int,sha256:string}
|
||||||
|
*/
|
||||||
|
public function write(string $member, iterable|string $content): array
|
||||||
|
{
|
||||||
|
$path = $this->path($member);
|
||||||
|
$stream = fopen($path, 'xb');
|
||||||
|
if ($stream === false) {
|
||||||
|
throw new RuntimeException('Não foi possível escrever o pacote privado.');
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
$this->created($path);
|
||||||
|
foreach (is_string($content) ? [$content] : $content as $chunk) {
|
||||||
|
if (fwrite($stream, $chunk) !== strlen($chunk)) {
|
||||||
|
throw new RuntimeException('Escrita incompleta do pacote privado.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
fclose($stream);
|
||||||
|
}
|
||||||
|
$size = filesize($path);
|
||||||
|
$sha = hash_file('sha256', $path);
|
||||||
|
if ($size === false || $sha === false) {
|
||||||
|
throw new RuntimeException('Não foi possível verificar o membro preparado.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return ['file' => $member, 'path' => $path, 'size' => $size, 'sha256' => $sha];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param list<string> $keep Absolute paths created by this instance only. */
|
||||||
|
public function cleanup(array $keep = []): void
|
||||||
|
{
|
||||||
|
$root = realpath($this->root);
|
||||||
|
if ($root === false || is_link($this->root)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
foreach (array_reverse($this->createdFiles) as $path) {
|
||||||
|
$resolved = realpath($path);
|
||||||
|
if (! in_array($path, $keep, true) && $resolved !== false && $this->within($resolved, $root) && ! is_link($path) && is_file($resolved)) {
|
||||||
|
unlink($path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
foreach (array_reverse($this->createdDirectories) as $directory) {
|
||||||
|
$resolved = realpath($directory);
|
||||||
|
if ($resolved !== false && ($resolved === $root || $this->within($resolved, $root)) && ! is_link($directory) && is_dir($directory)) {
|
||||||
|
// Unknown/untracked files are deliberately preserved, not removed recursively.
|
||||||
|
if (count(scandir($directory) ?: []) === 2) {
|
||||||
|
rmdir($directory);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services;
|
||||||
|
|
||||||
|
use App\Models\SupplyRecord;
|
||||||
|
use App\Models\User;
|
||||||
|
use Generator;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
use Illuminate\Support\Facades\Storage;
|
||||||
|
use League\Flysystem\FilesystemException;
|
||||||
|
use LogicException;
|
||||||
|
|
||||||
|
/** Verified original bytes; bank-specific imports and all People stores are outside this contract. */
|
||||||
|
final class PrivateAuditOriginals
|
||||||
|
{
|
||||||
|
/** @param list<string> $families
|
||||||
|
* @return Generator<int,array<string,mixed>>
|
||||||
|
*/
|
||||||
|
public function files(User $actor, array $families): Generator
|
||||||
|
{
|
||||||
|
$scope = app(PrivateAuditAccess::class)->authorise($actor, $families);
|
||||||
|
$actor = $scope['actor'];
|
||||||
|
if (DB::transactionLevel() < 1 || (DB::getDriverName() === 'pgsql'
|
||||||
|
&& (DB::selectOne('SHOW transaction_read_only')->transaction_read_only ?? null) !== 'on')) {
|
||||||
|
throw new LogicException('Recolher originais na transacção de leitura consistente.');
|
||||||
|
}
|
||||||
|
foreach (['purchasing' => ['supplier_documents', 'supplier_id', 'suppliers'], 'stock' => ['receipt_documents', 'goods_receipt_id', 'goods_receipts']] as $family => [$table, $parentColumn, $parent]) {
|
||||||
|
if (! in_array($family, $scope['families'], true) || ! Schema::hasTable($table)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
foreach (DB::table($table)->where('tenant_id', $actor->tenant_id)->orderBy('id')->lazy(100) as $document) {
|
||||||
|
$parentId = $document->{$parentColumn};
|
||||||
|
abort_unless(DB::table($parent)->where('tenant_id', $actor->tenant_id)->where('id', $parentId)->exists(), 409, 'Preserve a ligação do documento à sua origem.');
|
||||||
|
$prefix = $actor->tenant_id.'/'.$parentId.'/';
|
||||||
|
$bytes = $this->bounded($table, $document->path, $prefix, (int) $document->size, $document->sha256);
|
||||||
|
yield $this->entry($family, $table, (int) $document->id, $document->original_name, $document->mime_type, $bytes);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$kinds = [];
|
||||||
|
if (in_array('purchasing', $scope['families'], true)) {
|
||||||
|
$kinds = ['import_document', 'import_legal_source'];
|
||||||
|
}
|
||||||
|
if (in_array('finance', $scope['families'], true)) {
|
||||||
|
$kinds[] = 'import_cost_doc';
|
||||||
|
}
|
||||||
|
if ($kinds === [] || ! Schema::hasTable('supply_records')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
foreach (SupplyRecord::query()->where('tenant_id', $actor->tenant_id)->whereIn('kind', $kinds)->orderBy('id')->lazy(100) as $record) {
|
||||||
|
if ($record->kind === 'import_document' && in_array($record->data['type'] ?? null, ['bank_commitment', 'bank_support'], true)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if ($record->kind !== 'import_legal_source') {
|
||||||
|
abort_unless(DB::table('purchase_orders')->where('tenant_id', $actor->tenant_id)->where('id', $record->purchase_order_id)->exists(), 409, 'Preserve a origem do documento de importação.');
|
||||||
|
}
|
||||||
|
$evidence = $record->snapshot['evidence'] ?? [];
|
||||||
|
$bytes = app(ImportEvidence::class)->bytes($record);
|
||||||
|
$family = $record->kind === 'import_cost_doc' ? 'finance' : 'purchasing';
|
||||||
|
yield $this->entry($family, $record->kind, $record->id, $evidence['original_name'] ?? $evidence['name'] ?? null,
|
||||||
|
$evidence['mime'] ?? $evidence['mime_type'] ?? null, $bytes);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private function bounded(string $diskName, string $path, string $prefix, int $size, string $sha): string
|
||||||
|
{
|
||||||
|
abort_unless(str_starts_with($path, $prefix) && preg_match('/\A[A-Za-z0-9_-]+\.[A-Za-z0-9]+\z/D', substr($path, strlen($prefix)))
|
||||||
|
&& $size > 0 && $size <= 2097152 && preg_match('/^[a-f0-9]{64}$/D', $sha), 409, 'Original sem referência verificável.');
|
||||||
|
$disk = Storage::disk($diskName);
|
||||||
|
try {
|
||||||
|
$root = realpath($disk->path(''));
|
||||||
|
$resolved = realpath($disk->path($path));
|
||||||
|
$expected = $root === false ? '' : str_replace('\\', '/', $root).'/'.$prefix;
|
||||||
|
$normal = $resolved === false ? '' : str_replace('\\', '/', $resolved);
|
||||||
|
$within = PHP_OS_FAMILY === 'Windows' ? str_starts_with(strtolower($normal), strtolower($expected)) : str_starts_with($normal, $expected);
|
||||||
|
abort_unless($root !== false && $resolved !== false && $within && is_file($resolved) && ! is_link($disk->path($path)), 409, 'Original indisponível no local autorizado.');
|
||||||
|
$stream = $disk->readStream($path);
|
||||||
|
abort_unless(is_resource($stream), 409, 'Original indisponível.');
|
||||||
|
try {
|
||||||
|
$bytes = stream_get_contents($stream, 2097153);
|
||||||
|
} finally {
|
||||||
|
fclose($stream);
|
||||||
|
}
|
||||||
|
} catch (FilesystemException) {
|
||||||
|
abort(409, 'Original indisponível ou alterado.');
|
||||||
|
}
|
||||||
|
abort_unless(is_string($bytes) && strlen($bytes) === $size && hash_equals($sha, hash('sha256', $bytes)), 409, 'Original indisponível ou alterado.');
|
||||||
|
|
||||||
|
return $bytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string,mixed> */
|
||||||
|
private function entry(string $family, string $source, int $id, ?string $name, ?string $mime, string $bytes): array
|
||||||
|
{
|
||||||
|
$extension = match ($mime) {
|
||||||
|
'application/pdf' => 'pdf', 'image/jpeg' => 'jpg', 'image/png' => 'png', default => 'bin',
|
||||||
|
};
|
||||||
|
|
||||||
|
return ['family' => $family, 'source' => $source, 'source_id' => $id, 'original_name' => $name, 'mime_type' => $mime,
|
||||||
|
'file' => 'originais/'.$family.'/'.$source.'/'.$id.'.'.$extension, 'size' => strlen($bytes), 'sha256' => hash('sha256', $bytes), 'bytes' => $bytes];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services;
|
||||||
|
|
||||||
|
/** Structured bank coordinates, credentials and storage locations are outside the approved export. */
|
||||||
|
final class PrivateAuditRedaction
|
||||||
|
{
|
||||||
|
public function scrub(mixed $value): mixed
|
||||||
|
{
|
||||||
|
if (! is_array($value)) {
|
||||||
|
return $value;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->fields($value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array<array-key,mixed> $value
|
||||||
|
* @return array<array-key,mixed>
|
||||||
|
*/
|
||||||
|
public function fields(array $value): array
|
||||||
|
{
|
||||||
|
$result = [];
|
||||||
|
foreach ($value as $key => $item) {
|
||||||
|
if (is_string($key) && $this->excluded($key)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$result[$key] = $this->scrub($item);
|
||||||
|
}
|
||||||
|
|
||||||
|
return array_is_list($value) ? array_values($result) : $result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function excluded(string $key): bool
|
||||||
|
{
|
||||||
|
$key = strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $key) ?? '');
|
||||||
|
|
||||||
|
return in_array($key, ['bank', 'banks', 'bankaccounts', 'bankaccount', 'banksnapshot', 'bankdetails', 'accountidentifier',
|
||||||
|
'accountnumber', 'accountholder', 'beneficiary', 'iban', 'nib', 'nuib', 'swift', 'bic', 'swiftbic', 'bankcoordinates',
|
||||||
|
'password', 'passwordconfirmation', 'passwordhash', 'remembertoken', 'twofactorsecret', 'twofactorrecoverycodes',
|
||||||
|
'secret', 'apikey', 'token', 'bearertoken', 'accesstoken', 'refreshtoken', 'credentials', 'stateciphertext', 'privatekey',
|
||||||
|
'path', 'filepath', 'storagepath', 'peopledata', 'candidatedata', 'candidateprofile', 'curriculumvitae'], true)
|
||||||
|
|| str_ends_with($key, 'password') || str_ends_with($key, 'secret') || str_ends_with($key, 'credentials') || str_ends_with($key, 'token');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A positive projection of known configuration change payloads, never an arbitrary event dump. */
|
||||||
|
public function configurationEvent(mixed $value): mixed
|
||||||
|
{
|
||||||
|
if (! is_array($value)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
$keys = ['id', 'name', 'email', 'department_id', 'user_id', 'profile_id', 'profile_ids', 'permissions', 'work_contexts',
|
||||||
|
'memberships', 'maintenance', 'expires_at', 'reason', 'scope', 'effect', 'active', 'version', 'ready',
|
||||||
|
'company', 'users', 'administrators', 'profile', 'department', 'center', 'cost_center', 'code',
|
||||||
|
'first_limit_minor', 'second_limit_minor', 'approval_includes_tax', 'rules_provisional', 'default_tax_rate',
|
||||||
|
'comparison_policy', 'company_details', 'intelligence_policy', 'work_context_policy', 'requisition_approval_policy',
|
||||||
|
'geography_reference'];
|
||||||
|
|
||||||
|
return $this->scrub(array_intersect_key($value, array_flip($keys)));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,168 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services;
|
||||||
|
|
||||||
|
use App\Models\ExternalPayment;
|
||||||
|
use App\Models\User;
|
||||||
|
use DateTimeInterface;
|
||||||
|
use Generator;
|
||||||
|
use Illuminate\Database\Query\Builder;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
use LogicException;
|
||||||
|
|
||||||
|
/** Immutable source facts only: no financial calculations, role impersonation or business commands. */
|
||||||
|
final class PrivateAuditSourceReader
|
||||||
|
{
|
||||||
|
/** @param list<string> $families
|
||||||
|
* @return Generator<int,array<string,mixed>>
|
||||||
|
*/
|
||||||
|
public function datasets(User $actor, array $families): Generator
|
||||||
|
{
|
||||||
|
$scope = app(PrivateAuditAccess::class)->authorise($actor, $families);
|
||||||
|
$actor = $scope['actor'];
|
||||||
|
if (DB::transactionLevel() < 1 || (DB::getDriverName() === 'pgsql'
|
||||||
|
&& (DB::selectOne('SHOW transaction_read_only')->transaction_read_only ?? null) !== 'on')) {
|
||||||
|
throw new LogicException('Recolher fontes apenas numa transacção de leitura consistente.');
|
||||||
|
}
|
||||||
|
foreach ($scope['families'] as $family) {
|
||||||
|
foreach (PrivateAuditCatalogue::TABLES[$family] ?? throw new LogicException('Família sem catálogo de fontes.') as $table => $columns) {
|
||||||
|
yield $this->dataset($actor, $family, $table, explode(' ', $columns));
|
||||||
|
}
|
||||||
|
$kinds = PrivateAuditCatalogue::SUPPLY_KINDS[$family];
|
||||||
|
if ($kinds !== []) {
|
||||||
|
yield $this->dataset($actor, $family, 'supply_records', explode(' ', PrivateAuditCatalogue::SUPPLY_COLUMNS), $kinds);
|
||||||
|
}
|
||||||
|
yield $this->events($actor, $family);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param list<string> $columns
|
||||||
|
* @param list<string>|null $kinds
|
||||||
|
* @return array<string,mixed>
|
||||||
|
*/
|
||||||
|
private function dataset(User $actor, string $family, string $table, array $columns, ?array $kinds = null): array
|
||||||
|
{
|
||||||
|
$base = ['family' => $family, 'source' => $table, 'file' => 'dados/'.$family.'/'.$table.'.ndjson'];
|
||||||
|
if (! Schema::hasTable($table)) {
|
||||||
|
return [...$base, 'state' => 'not_installed', 'columns' => [], 'missing_columns' => $columns, 'rows' => null];
|
||||||
|
}
|
||||||
|
$available = Schema::getColumnListing($table);
|
||||||
|
$included = array_values(array_intersect($columns, $available));
|
||||||
|
$missing = array_values(array_diff($columns, $available));
|
||||||
|
$query = $this->query($actor, $table, $available);
|
||||||
|
if ($kinds !== null) {
|
||||||
|
$query->whereIn($table.'.kind', $kinds);
|
||||||
|
$query->where(function ($records) {
|
||||||
|
$records->where('kind', '!=', 'import_document')->orWhere(function ($documents) {
|
||||||
|
$documents->whereNull('data->type')->orWhereNotIn('data->type', ['bank_commitment', 'bank_support']);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if ($table === 'workflow_notices') {
|
||||||
|
$query->whereNotNull('requisition_id');
|
||||||
|
}
|
||||||
|
$json = $table === 'supply_records' ? ['data', 'snapshot'] : (PrivateAuditCatalogue::JSON_COLUMNS[$table] ?? []);
|
||||||
|
foreach (Schema::getColumns($table) as $definition) {
|
||||||
|
if (in_array($definition['type_name'], ['json', 'jsonb'], true)) {
|
||||||
|
$json[] = $definition['name'];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return [...$base, 'state' => $missing === [] ? 'available' : 'legacy_columns', 'columns' => $included, 'missing_columns' => $missing,
|
||||||
|
'rows' => $this->rows($query, $table, $included, array_values(array_unique($json)))];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param list<string> $available */
|
||||||
|
private function query(User $actor, string $table, array $available): Builder
|
||||||
|
{
|
||||||
|
$query = DB::table($table);
|
||||||
|
if ($table === 'tenants') {
|
||||||
|
return $query->where('id', $actor->tenant_id);
|
||||||
|
}
|
||||||
|
if ($table === 'pa_outbox') {
|
||||||
|
return $query->join('pa_events', 'pa_events.id', '=', 'pa_outbox.event_id')
|
||||||
|
->where('pa_events.tenant_id', $actor->tenant_id)->where('pa_events.company_id', 0)->where('pa_events.unit_id', 0);
|
||||||
|
}
|
||||||
|
if (! in_array('tenant_id', $available, true)) {
|
||||||
|
throw new LogicException('Fonte sem âmbito de empresa explícito.');
|
||||||
|
}
|
||||||
|
$query->where($table.'.tenant_id', $actor->tenant_id);
|
||||||
|
if (str_starts_with($table, 'pa_') || str_starts_with($table, 'gl_')) {
|
||||||
|
// The standalone Compras adapters explicitly use company/unit zero inside the current tenant.
|
||||||
|
if (! in_array('company_id', $available, true) || ! in_array('unit_id', $available, true)) {
|
||||||
|
throw new LogicException('Preserve o âmbito do núcleo financeiro comum.');
|
||||||
|
}
|
||||||
|
$query->where($table.'.company_id', 0)->where($table.'.unit_id', 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $query;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param list<string> $columns
|
||||||
|
* @param list<string> $jsonColumns
|
||||||
|
* @return Generator<int,array<string,mixed>>
|
||||||
|
*/
|
||||||
|
private function rows(Builder $query, string $table, array $columns, array $jsonColumns): Generator
|
||||||
|
{
|
||||||
|
if ($columns === []) {
|
||||||
|
throw new LogicException('Fonte instalada sem campos conhecidos.');
|
||||||
|
}
|
||||||
|
$key = in_array('id', $columns, true) ? 'id' : ($table === 'pa_outbox' ? 'event_id' : 'tenant_id');
|
||||||
|
if ($table === 'external_payments') {
|
||||||
|
foreach (ExternalPayment::query()->select($columns)->orderBy('id')->lazy(100) as $payment) {
|
||||||
|
$row = [];
|
||||||
|
foreach ($columns as $column) {
|
||||||
|
$value = $payment->getAttribute($column);
|
||||||
|
$row[$column] = $value instanceof DateTimeInterface ? $value->format('Y-m-d\TH:i:s.uP') : $value;
|
||||||
|
}
|
||||||
|
yield app(PrivateAuditRedaction::class)->fields($row);
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
foreach ($query->select(array_map(fn ($column) => $table.'.'.$column, $columns))->orderBy($table.'.'.$key)->lazy(100) as $record) {
|
||||||
|
$row = get_object_vars($record);
|
||||||
|
foreach ($jsonColumns as $column) {
|
||||||
|
if (isset($row[$column]) && is_string($row[$column])) {
|
||||||
|
$row[$column] = json_decode($row[$column], true, 512, JSON_THROW_ON_ERROR | JSON_BIGINT_AS_STRING);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
yield app(PrivateAuditRedaction::class)->fields($row);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string,mixed> */
|
||||||
|
private function events(User $actor, string $family): array
|
||||||
|
{
|
||||||
|
$prefixes = match ($family) {
|
||||||
|
'configuration' => ['organization.', 'company.', 'audit.private_'],
|
||||||
|
'finance' => ['budget.', 'invoice.', 'payment.', 'expense.', 'payables.', 'ledger.', 'sgf_invoice.'],
|
||||||
|
'stock' => ['stock.', 'receipt.', 'warehouse.', 'inventory.', 'warehouse_request.', 'replenishment.', 'supply.policy.', 'supply.reservation.', 'supply.delivery.', 'supply.issue.', 'supply.alternative.', 'supply.history.', 'supply.suggestion.'],
|
||||||
|
'purchasing' => ['requisition.', 'approval.', 'quotation.', 'award.', 'purchase_order.', 'opening.', 'qualification.', 'admission.', 'recommendation.', 'capital.', 'conflict.', 'equipment.', 'investment.', 'urgent.', 'op_order.', 'op_order_policy.', 'op_order_link.', 'import.', 'supply.agreement.', 'supply.contract.', 'supply.import.'],
|
||||||
|
default => throw new LogicException('Família de eventos desconhecida.'),
|
||||||
|
};
|
||||||
|
$columns = ['id', 'tenant_id', 'user_id', 'requisition_id', 'action', 'created_at'];
|
||||||
|
$query = DB::table('audit_logs')->where('tenant_id', $actor->tenant_id)->where(function ($events) use ($prefixes) {
|
||||||
|
foreach ($prefixes as $prefix) {
|
||||||
|
$events->orWhereRaw('substr(action, 1, ?) = ?', [strlen($prefix), $prefix]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
$rows = function () use ($query, $columns, $family): Generator {
|
||||||
|
foreach ($query->select([...$columns, ...($family === 'configuration' ? ['before', 'after'] : [])])->orderBy('id')->lazy(100) as $event) {
|
||||||
|
$row = get_object_vars($event);
|
||||||
|
if ($family === 'configuration') {
|
||||||
|
foreach (['before', 'after'] as $field) {
|
||||||
|
$value = $row[$field] === null ? null : json_decode($row[$field], true, 512, JSON_THROW_ON_ERROR | JSON_BIGINT_AS_STRING);
|
||||||
|
$row[$field.'_projected'] = app(PrivateAuditRedaction::class)->configurationEvent($value);
|
||||||
|
unset($row[$field]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
yield $row;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return ['family' => $family, 'source' => 'audit_logs', 'file' => 'dados/'.$family.'/eventos.ndjson', 'state' => 'available',
|
||||||
|
'columns' => [...$columns, ...($family === 'configuration' ? ['before_projected', 'after_projected'] : [])], 'missing_columns' => [], 'rows' => $rows()];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -16,13 +16,17 @@ use Tempo\Purchasing\Economic\ProposalScoring;
|
|||||||
|
|
||||||
class ProposalComparison
|
class ProposalComparison
|
||||||
{
|
{
|
||||||
/** @return array{rows: list<array<string, mixed>>, ready: bool, top_ids: list<int>, fingerprint: string, policy: array{revision: int, configured: bool, minimum_proposals: int, minimum_evaluators: int, weights: array<string,int>}} */
|
/** @return array{rows: list<array<string, mixed>>, ready: bool, top_ids: list<int>, fingerprint: string, policy: array{revision: int, configured: bool, minimum_proposals: int, minimum_evaluators: int, weights: array<string,int>, urgent_minimum_proposals?: int, normal_minimum_proposals?: int}} */
|
||||||
public function inspect(Requisition $requisition): array
|
public function inspect(Requisition $requisition): array
|
||||||
{
|
{
|
||||||
$quotes = Quotation::query()->where('requisition_id', $requisition->id)
|
$quotes = Quotation::query()->where('requisition_id', $requisition->id)
|
||||||
->with(['supplier', 'items' => fn ($q) => $q->orderBy('id'), 'evaluations' => fn ($q) => $q->orderBy('id')])->orderBy('id')->get();
|
->with(['supplier', 'items' => fn ($q) => $q->orderBy('id'), 'evaluations' => fn ($q) => $q->orderBy('id')])->orderBy('id')->get();
|
||||||
$guard = app(ConflictGuard::class);
|
$guard = app(ConflictGuard::class);
|
||||||
$policy = app(ComparisonPolicy::class)->forRequest($requisition);
|
$policy = app(ComparisonPolicy::class)->forRequest($requisition);
|
||||||
|
$urgentBasis = app(UrgentQuotationBasis::class)->eligible($requisition);
|
||||||
|
if ($urgentBasis !== [] && isset($policy['urgent_minimum_proposals'])) {
|
||||||
|
$policy = [...$policy, 'normal_minimum_proposals' => $policy['minimum_proposals'], 'minimum_proposals' => $policy['urgent_minimum_proposals']];
|
||||||
|
}
|
||||||
$referenceWeights = $requisition->comparison_policy === null ? $quotes->first()?->weights : $policy['weights'];
|
$referenceWeights = $requisition->comparison_policy === null ? $quotes->first()?->weights : $policy['weights'];
|
||||||
$adopted = app(FormalAdmission::class)->adoption($requisition) !== null;
|
$adopted = app(FormalAdmission::class)->adoption($requisition) !== null;
|
||||||
$rows = [];
|
$rows = [];
|
||||||
@@ -88,6 +92,9 @@ class ProposalComparison
|
|||||||
if ($requisition->comparison_policy !== null) {
|
if ($requisition->comparison_policy !== null) {
|
||||||
$basis['comparison_policy'] = $policy;
|
$basis['comparison_policy'] = $policy;
|
||||||
}
|
}
|
||||||
|
if ($urgentBasis !== []) {
|
||||||
|
$basis['urgent_stock_basis'] = $urgentBasis;
|
||||||
|
}
|
||||||
$ready = count($eligible) >= $policy['minimum_proposals'] && count(array_unique(array_column($eligible, 'supplier_id'))) >= $policy['minimum_proposals'];
|
$ready = count($eligible) >= $policy['minimum_proposals'] && count(array_unique(array_column($eligible, 'supplier_id'))) >= $policy['minimum_proposals'];
|
||||||
foreach ($eligible as $row) {
|
foreach ($eligible as $row) {
|
||||||
$ready = $ready && $row['evaluation_count'] >= $policy['minimum_evaluators'];
|
$ready = $ready && $row['evaluation_count'] >= $policy['minimum_evaluators'];
|
||||||
|
|||||||
@@ -172,10 +172,14 @@ class PurchaseWorkflow
|
|||||||
}
|
}
|
||||||
$tariffs = app(ImportTariffCodes::class)->freezeForItems($user, array_column($lines, 'requisition_item_id'));
|
$tariffs = app(ImportTariffCodes::class)->freezeForItems($user, array_column($lines, 'requisition_item_id'));
|
||||||
$capital = app(CapitalAssignments::class)->freezeForItems($user, array_column($lines, 'requisition_item_id'));
|
$capital = app(CapitalAssignments::class)->freezeForItems($user, array_column($lines, 'requisition_item_id'));
|
||||||
|
$operational = app(OperationalOrders::class)->freezeForItems($user, array_column($lines, 'requisition_item_id'));
|
||||||
$accounts = app(RequisitionAccountAssignments::class)->freezeForItems($user, array_column($lines, 'requisition_item_id'));
|
$accounts = app(RequisitionAccountAssignments::class)->freezeForItems($user, array_column($lines, 'requisition_item_id'));
|
||||||
|
$comparisonDocument = $this->comparison->inspect($requisition);
|
||||||
|
$urgentDocument = app(UrgentQuotationBasis::class)->eligible($requisition);
|
||||||
$snapshot = [
|
$snapshot = [
|
||||||
...($accounts === [] ? [] : ['account_assignments' => $accounts]),
|
...($accounts === [] ? [] : ['account_assignments' => $accounts]),
|
||||||
...($capital === [] ? [] : ['capital_assignments' => $capital]),
|
...($capital === [] ? [] : ['capital_assignments' => $capital]),
|
||||||
|
...($operational === [] ? [] : ['operational_orders' => $operational]),
|
||||||
...($tariffs === [] ? [] : ['import_tariffs' => $tariffs]),
|
...($tariffs === [] ? [] : ['import_tariffs' => $tariffs]),
|
||||||
...app(AgreementOrderLimits::class)->freeze($user, $quote, $requisition, $lines, $agreementBindings),
|
...app(AgreementOrderLimits::class)->freeze($user, $quote, $requisition, $lines, $agreementBindings),
|
||||||
...($quote->exchange_basis === null ? [] : ['exchange_basis' => $quote->exchange_basis, 'reference_amounts' => app(QuotationExchange::class)->amounts($quote)]),
|
...($quote->exchange_basis === null ? [] : ['exchange_basis' => $quote->exchange_basis, 'reference_amounts' => app(QuotationExchange::class)->amounts($quote)]),
|
||||||
@@ -197,8 +201,9 @@ class PurchaseWorkflow
|
|||||||
'recommendation' => $award->recommendation_snapshot,
|
'recommendation' => $award->recommendation_snapshot,
|
||||||
'estimate_approvals' => $requisition->steps()->get()->toArray(),
|
'estimate_approvals' => $requisition->steps()->get()->toArray(),
|
||||||
'final_approvals' => $award->approvals()->get()->toArray(),
|
'final_approvals' => $award->approvals()->get()->toArray(),
|
||||||
'decision_matrix' => $this->comparison->inspect($requisition)['rows'], 'items' => $lines,
|
'decision_matrix' => $comparisonDocument['rows'], 'items' => $lines,
|
||||||
'comparison_policy' => app(ComparisonPolicy::class)->forRequest($requisition),
|
'comparison_policy' => $comparisonDocument['policy'],
|
||||||
|
...($urgentDocument === [] ? [] : ['urgent_quotation_basis' => $urgentDocument]),
|
||||||
'equipment_context' => $requisition->items()->whereNotNull('equipment_id')->get()->map(fn ($line) => ['requisition_item_id' => $line->id, 'equipment' => Equipment::query()->findOrFail($line->equipment_id)->toArray(), 'spare_part' => SparePart::query()->findOrFail($line->spare_part_id)->toArray(), 'downtime_started_at' => $line->downtime_started_at])->all(),
|
'equipment_context' => $requisition->items()->whereNotNull('equipment_id')->get()->map(fn ($line) => ['requisition_item_id' => $line->id, 'equipment' => Equipment::query()->findOrFail($line->equipment_id)->toArray(), 'spare_part' => SparePart::query()->findOrFail($line->spare_part_id)->toArray(), 'downtime_started_at' => $line->downtime_started_at])->all(),
|
||||||
];
|
];
|
||||||
$order = PurchaseOrder::query()->create([
|
$order = PurchaseOrder::query()->create([
|
||||||
|
|||||||
@@ -258,6 +258,7 @@ class SupplyPlanning
|
|||||||
'target_milli' => 'required|integer|min:0|max:1000000000', 'maximum_milli' => 'required|integer|min:0|max:1000000000',
|
'target_milli' => 'required|integer|min:0|max:1000000000', 'maximum_milli' => 'required|integer|min:0|max:1000000000',
|
||||||
'daily_milli' => 'nullable|integer|min:0|max:1000000000', 'lead_days' => 'required|integer|min:0|max:3650', 'approval_days' => 'required|integer|min:0|max:365',
|
'daily_milli' => 'nullable|integer|min:0|max:1000000000', 'lead_days' => 'required|integer|min:0|max:3650', 'approval_days' => 'required|integer|min:0|max:365',
|
||||||
'horizon_days' => 'required|integer|min:1|max:366', 'minimum_milli' => 'required|integer|min:0|max:1000000000', 'pack_milli' => 'required|integer|min:1|max:1000000000',
|
'horizon_days' => 'required|integer|min:1|max:366', 'minimum_milli' => 'required|integer|min:0|max:1000000000', 'pack_milli' => 'required|integer|min:1|max:1000000000',
|
||||||
|
'usage_context' => 'sometimes|nullable|string|max:500',
|
||||||
'basis' => 'required|string|min:5|max:2000'],
|
'basis' => 'required|string|min:5|max:2000'],
|
||||||
'contract' => ['supplier_id' => 'required|integer|min:1', 'reference' => 'required|string|max:200',
|
'contract' => ['supplier_id' => 'required|integer|min:1', 'reference' => 'required|string|max:200',
|
||||||
'currency' => 'required|regex:/^[A-Z]{3}$/', 'valid_from' => 'required|date_format:Y-m-d', 'valid_until' => 'required|date_format:Y-m-d|after_or_equal:valid_from',
|
'currency' => 'required|regex:/^[A-Z]{3}$/', 'valid_from' => 'required|date_format:Y-m-d', 'valid_until' => 'required|date_format:Y-m-d|after_or_equal:valid_from',
|
||||||
|
|||||||
@@ -0,0 +1,143 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services;
|
||||||
|
|
||||||
|
use App\Models\Requisition;
|
||||||
|
use App\Models\RequisitionItem;
|
||||||
|
use App\Models\StockItem;
|
||||||
|
use App\Models\SupplyRecord;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Models\Warehouse;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Validator;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Illuminate\Validation\ValidationException;
|
||||||
|
|
||||||
|
/** Evidence of reaching a company-defined minimum; never a budget or approval waiver. */
|
||||||
|
final class UrgentQuotationBasis
|
||||||
|
{
|
||||||
|
public function ready(): bool
|
||||||
|
{
|
||||||
|
$db = DB::connection();
|
||||||
|
|
||||||
|
return config('urgent-quotations.qa_enabled') === true && app()->environment('testing')
|
||||||
|
&& (($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|
||||||
|
|| ($db->getDriverName() === 'pgsql' && $db->getConfig('host') === '127.0.0.1'
|
||||||
|
&& preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName())));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string,mixed> */
|
||||||
|
private function line(RequisitionItem $item): array
|
||||||
|
{
|
||||||
|
return $item->only(['id', 'description', 'quantity', 'unit', 'catalogue_entry_id', 'catalogue_snapshot', 'category_context']);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function cycle(Requisition $request): int
|
||||||
|
{
|
||||||
|
return max(1, (int) ($request->getAttribute('approval_cycle') ?? 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string,mixed> */
|
||||||
|
public function workspace(User $actor, Requisition $request): array
|
||||||
|
{
|
||||||
|
abort_unless($this->ready(), 503);
|
||||||
|
abort_unless(auth()->id() === $actor->id && $actor->tenant_id !== null, 403);
|
||||||
|
$actor = User::query()->where('tenant_id', $actor->tenant_id)->whereKey($actor->id)->firstOrFail();
|
||||||
|
Requisition::query()->visibleTo($actor)->whereKey($request->id)->firstOrFail();
|
||||||
|
abort_unless($actor->hasFunctions(['admin', 'procurement', 'finance', 'department_head']) && ! app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||||
|
$canRecord = app(QuotationParticipation::class)->canPrepare($actor, $request);
|
||||||
|
$items = $request->items()->orderBy('id')->get();
|
||||||
|
$stockIds = [];
|
||||||
|
foreach ($items as $item) {
|
||||||
|
if (isset($item->catalogue_snapshot['stock_item_id'])) {
|
||||||
|
$stockIds[] = $item->catalogue_snapshot['stock_item_id'];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ['requisition' => $request->only(['id', 'number', 'priority', 'justification']), 'cycle' => $this->cycle($request), 'items' => $items->map(fn ($item) => $this->line($item)),
|
||||||
|
'comparisonPolicy' => app(ComparisonPolicy::class)->forRequest($request), 'canRecord' => $canRecord,
|
||||||
|
'policies' => app(SupplyPlanning::class)->latest('policy')->where('state', 'approved')->whereIn('stock_item_id', $canRecord ? $stockIds : [])->orderBy('id')
|
||||||
|
->paginate(15, ['id', 'version', 'stock_item_id', 'warehouse_id', 'data', 'snapshot'])->through(fn ($policy) => [
|
||||||
|
'id' => $policy->id, 'version' => $policy->version, 'stock_item_id' => $policy->stock_item_id,
|
||||||
|
'item' => $policy->snapshot['item'], 'warehouse' => $policy->snapshot['warehouse'],
|
||||||
|
'minimum_stock_milli' => $policy->data['minimum_stock_milli'], 'usage_context' => $policy->data['usage_context'] ?? null,
|
||||||
|
])->withQueryString(),
|
||||||
|
'evidence' => app(SupplyPlanning::class)->latest('urgent_stock_basis')->where('data->requisition_id', $request->id)->where('data->cycle', $this->cycle($request))
|
||||||
|
->get(['id', 'version', 'data', 'snapshot', 'reason', 'created_at']),
|
||||||
|
'eligible' => $this->eligible($request),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array<string,mixed> $input */
|
||||||
|
public function record(User $actor, Requisition $request, array $input): SupplyRecord
|
||||||
|
{
|
||||||
|
abort_unless($this->ready(), 503);
|
||||||
|
$data = Validator::make($input, ['item_id' => 'required|integer|min:1', 'policy_id' => 'required|integer|min:1', 'version' => 'required|integer|min:0',
|
||||||
|
'reason' => 'required|string|min:10|max:4000', 'operation_key' => 'required|uuid'])->validate();
|
||||||
|
$data['operation_key'] = strtolower($data['operation_key']);
|
||||||
|
|
||||||
|
return DB::transaction(function () use ($actor, $request, $data) {
|
||||||
|
app(ConflictGuard::class)->lockCompany($actor);
|
||||||
|
$actor = app(CurrentActor::class)->lock($actor);
|
||||||
|
$request = Requisition::query()->visibleTo($actor)->whereKey($request->id)->lockForUpdate()->firstOrFail();
|
||||||
|
app(QuotationParticipation::class)->assertPrepare($actor, $request);
|
||||||
|
$policy = app(ComparisonPolicy::class)->forRequest($request);
|
||||||
|
abort_unless($request->priority === 'urgent' && isset($policy['urgent_minimum_proposals']) && mb_strlen(trim($request->justification ?? '')) >= 10, 422,
|
||||||
|
'É necessária uma requisição urgente justificada com redução expressamente configurada.');
|
||||||
|
$hash = hash('sha256', json_encode([$request->id, $this->cycle($request), $data], JSON_THROW_ON_ERROR));
|
||||||
|
$retry = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
|
||||||
|
if ($retry !== null) {
|
||||||
|
abort_unless($retry->kind === 'urgent_stock_basis' && $retry->created_by === $actor->id && hash_equals($retry->input_hash, $hash), 409);
|
||||||
|
|
||||||
|
return $retry;
|
||||||
|
}
|
||||||
|
$item = $request->items()->whereKey($data['item_id'])->firstOrFail();
|
||||||
|
$source = app(SupplyPlanning::class)->latest('policy')->where('state', 'approved')->whereKey($data['policy_id'])
|
||||||
|
->where('stock_item_id', $item->catalogue_snapshot['stock_item_id'] ?? 0)->firstOrFail();
|
||||||
|
$stock = StockItem::query()->whereKey($source->stock_item_id)->lockForUpdate()->firstOrFail();
|
||||||
|
$warehouse = Warehouse::query()->whereKey($source->warehouse_id)->firstOrFail();
|
||||||
|
$availability = app(WarehouseAvailability::class)->row($stock, $warehouse, true);
|
||||||
|
if (! $availability['at_minimum'] || $source->snapshot['item'] !== $stock->only(['id', 'code', 'name', 'unit'])) {
|
||||||
|
throw ValidationException::withMessages(['policy_id' => 'O mínimo aplicável não foi atingido ou a fonte mudou. Mantém-se o número normal de cotações.']);
|
||||||
|
}
|
||||||
|
$old = app(SupplyPlanning::class)->latest('urgent_stock_basis')->where('data->requisition_item_id', $item->id)->where('data->cycle', $this->cycle($request))->first();
|
||||||
|
abort_unless((int) $data['version'] === ($old->version ?? 0), 409);
|
||||||
|
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'urgent_stock_basis',
|
||||||
|
'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1, 'state' => 'recorded',
|
||||||
|
'data' => ['requisition_id' => $request->id, 'requisition_item_id' => $item->id, 'cycle' => $this->cycle($request)],
|
||||||
|
'snapshot' => ['item' => $this->line($item), 'stock_policy' => ['id' => $source->id, 'version' => $source->version,
|
||||||
|
'minimum_stock_milli' => $source->data['minimum_stock_milli'], 'usage_context' => $source->data['usage_context'] ?? null,
|
||||||
|
'warehouse' => $source->snapshot['warehouse']], 'availability' => $availability,
|
||||||
|
'comparison_policy' => $policy, 'author' => $actor->only(['id', 'name'])],
|
||||||
|
'created_by' => $actor->id, 'created_at' => now(), 'reason' => $data['reason'], 'operation_key' => $data['operation_key'], 'input_hash' => $hash]);
|
||||||
|
app(RequisitionWorkflow::class)->audit($actor, 'urgent.stock_minimum_recorded', $request, $old?->toArray(), ['record' => $record->toArray()]);
|
||||||
|
|
||||||
|
return $record;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The historical threshold event is preserved; no automatic expiry or stock movement is invented.
|
||||||
|
* @return list<array<string,mixed>>
|
||||||
|
*/
|
||||||
|
public function eligible(Requisition $request): array
|
||||||
|
{
|
||||||
|
if (! $this->ready() || $request->status !== 'approved' || $request->priority !== 'urgent' || mb_strlen(trim($request->justification ?? '')) < 10) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
$policy = app(ComparisonPolicy::class)->forRequest($request);
|
||||||
|
if (! isset($policy['urgent_minimum_proposals'])) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
$records = app(SupplyPlanning::class)->latest('urgent_stock_basis')->where('data->requisition_id', $request->id)->where('data->cycle', $this->cycle($request))->get();
|
||||||
|
$result = [];
|
||||||
|
foreach ($request->items()->orderBy('id')->get() as $item) {
|
||||||
|
$record = $records->first(fn ($record) => $record->data['requisition_item_id'] === $item->id);
|
||||||
|
if ($record === null || $record->snapshot['item'] !== $this->line($item) || $record->snapshot['comparison_policy'] !== $policy) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
$result[] = $record->only(['id', 'version', 'data', 'snapshot', 'reason', 'created_at']);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
return ['qa_enabled' => false];
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
return ['qa_enabled' => false];
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
return ['qa_enabled' => false];
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
return ['qa_enabled' => false];
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::create('conflict_releases', function (Blueprint $table) {
|
||||||
|
$table->id();
|
||||||
|
$table->foreignId('tenant_id')->constrained()->restrictOnDelete();
|
||||||
|
$table->foreignId('root_id')->unique()->constrained('conflict_declarations')->restrictOnDelete();
|
||||||
|
$table->foreignId('declaration_id')->constrained('conflict_declarations')->restrictOnDelete();
|
||||||
|
$table->foreignId('authorised_by')->constrained('users')->restrictOnDelete();
|
||||||
|
$table->uuid('operation_key')->unique();
|
||||||
|
$table->text('reason');
|
||||||
|
$table->json('snapshot');
|
||||||
|
$table->timestamp('authorised_at');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::dropIfExists('conflict_releases');
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::create('private_audit_exports', function (Blueprint $table) {
|
||||||
|
$table->id();
|
||||||
|
$table->foreignId('tenant_id')->constrained()->restrictOnDelete();
|
||||||
|
$table->foreignId('created_by')->constrained('users')->restrictOnDelete();
|
||||||
|
$table->uuid('operation_key');
|
||||||
|
$table->string('input_hash', 64);
|
||||||
|
$table->string('work_context', 80);
|
||||||
|
$table->json('families');
|
||||||
|
$table->string('path');
|
||||||
|
$table->unsignedBigInteger('size');
|
||||||
|
$table->string('sha256', 64);
|
||||||
|
$table->string('manifest_sha256', 64);
|
||||||
|
$table->json('manifest');
|
||||||
|
$table->timestamp('created_at');
|
||||||
|
$table->unique(['tenant_id', 'created_by', 'operation_key'], 'private_audit_operation_unique');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::dropIfExists('private_audit_exports');
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -1,5 +1,17 @@
|
|||||||
# Desenvolvimento do SGC
|
# Desenvolvimento do SGC
|
||||||
|
|
||||||
|
28/11/2026 — exportação privada de auditoria implementada em QA para Compras, stock, finanças e configuração, conforme decisão expressa. Quatro competências próprias independentes, sem herança de Admin/Finanças/metadados; bancos completos e Pessoas separados. ZIP privado imutável com manifesto, fontes/contagens/colunas ausentes, NDJSON integral e originais verificados; snapshot readonly, UUID idempotente, hashes, descarga autenticada dos bytes conferidos e limpeza só de ficheiros próprios. SQLite15/493, PG15/493 (base removida), frontend24/2ficheiros, tipos/PHPStan0/check/Pint/build aprovados. HTTP nativo270/quatro sessões/20assets,138tabelas intactas no intervalo de consultas; geração/repetição/ZIP conferidos após esse intervalo, recursos removidos. Manifesto fa87e37a3626ef75d22b5248dce9a0af2bad68c967e6f99bb64bc426a68f6aaf,183entradas. Prova: `proofs/audit-export-scope-proposal.json`. Substitui a pendência histórica de escolha das famílias/exportador abaixo; não voltar a perguntar o âmbito. Sem concessões reais, instalação/activação, alteração do piloto/SGF ou aceitação visual/integral. Originais mantêm bytes; não se afirma anonimização de texto livre ou certificação.
|
||||||
|
|
||||||
|
28/11/2026: corrigido erro de acesso introduzido no novo cadastro: apenas metadados nao permitem consultar ordens; leitores autorizados do processo recebem so as origens ligadas. Regressao SQLite1/24 e PostgreSQL1/24, base removida; PHPStan0 e HTTP final234/três sessoes/19assets/137tabelas intactas, sem comandos. Log storage/logs/operational-urgent-http-final-20261128.log; fonte/manifesto privado b712f509 preservados.
|
||||||
|
|
||||||
|
28/11/2026 — urgência e mínimo por natureza/utilização: `UrgentQuotationBasis` guarda evidência histórica do mínimo nativo atingido por linha/ciclo, com política/local de uso escolhidos, sem movimentar stock ou dispensar orçamento/contas/aprovações. Mínimo de propostas urgente opcional, positivo e inferior ao normal, parametrizado na interface e congelado na criação da requisição. A regra normal prevalece sem todas as evidências compatíveis. Autoridade de preparação/consulta reutiliza `QuotationParticipation` e visibilidade nativas; intervenientes de aprovação consultam a origem sem obter gravação. Comparação/ordens normais e parciais preservam regra efectiva e evidências em consulta/impressão. Testes PG6/139 incluem uma proposta elegível versus mínimo normal3/urgente explícito1, duas avaliações, recusa de adjudicação sem prova e de emissão sem aprovação, ordens sintéticas100/40MZN; base removida. SQLite5/122 e1saltado por pacote antigo sem parcelas; frontend46/4ficheiros, tipos/PHPStan0/check9/Pint/build aprovados. HTTP somente leitura234/três sessões/19assets/137tabelas intactas, novas páginas e recusas incluídas, recursos removidos. Build privado182entradas, manifestob712f509fb0ff1179fc9d007abbef0a3c2d5f97f575b558cbc49f47d06dc9894. Prova `proofs/requisition-expiry-qa.json`. Sem piloto, SGF, concessões, activação operacional ou prova visual. Erros das novas fixtures corrigidos, sem relaxar regras. Explicação e proposta das famílias de auditoria privada acrescentadas ao ficheiro já aberto no IDE; escolha concreta ainda necessária.
|
||||||
|
|
||||||
|
28/11/2026 — cadastro de ordens de origem entregue em QA. `OperationalOrders` e controlador/página próprios permitem à empresa escolher registo nos locais de utilização (responsável da produção/chefe de oficina com competências expressas) ou pelo procurement. Ordens originais append-only, autoria real e modo congelados; ligações por linha/versionamento/repetição/concorrência optimista e guarda na submissão. Snapshot de emissão normal e por parcelas conserva a origem; consulta e impressão apresentam o mesmo original após mudança da configuração. Sem novos efeitos financeiros/stock ou cadastro SGF. Natureza/utilização considerada no mínimo de stock passam a poder ser documentadas na política nativa versionada; valor continua parametrizado por artigo/local. SQLite12/136, PG6/115 com emissão normal/parcial e stockPG1/5 passaram, bases removidas. Frontend36/3ficheiros, tipos, PHPStan0, check/Pint e build privado aprovados; manifesto6b0126100bf6ad8ee88565c580c87ae724e259505f8bbb3c395312fc07cf9564/181entradas sem faltas. Prova e erro próprio de comprimento do kind corrigido em `proofs/rq01-account-assignment-qa.json`. Flag false, piloto/SGF e manifesto operacional preservados. Sem nova prova HTTP/visual; redução urgente e exportação privada ainda têm implementação própria a concluir.
|
||||||
|
|
||||||
|
28/11/2026 — RF-AF-01: decisão expressa «autorização da direcção da empresa» traduzida em `ConflictReleases`, `ConflictRelease`, rota POST explícita e formulário no histórico. Uma nova competência configurável identifica a direcção, sem assumir que Admin/Finanças a representam. Migração `2026_11_28_000001_create_conflict_releases.php` testada exclusivamente em bases descartáveis. Guarda exige flag explícita/testing/base QA; desactivada por defeito. Autorização ligada à cadeia e à última declaração imutável, fundamento, autor, data, UUID e auditoria única. Ausência declarada não retira impedimento; nova declaração independente continua a impedir. Nenhum estado anterior de compra é reaberto nem há efeito financeiro automático. SQLite e PostgreSQL46/418 cada, frontend5, tipos/PHPStan0/check/Pint/diff/build privado aprovados. PostgreSQL descartável removido. Manifesto privado8ac97298e6d8efbcde4b22b3dd2cfc4df76b0bbff9403d2b091a5e394089194e,180entradas sem faltas; log `storage/logs/conflict-direction-build-20261128.log`. Sem nova prova HTTP/visual, instalação, activação ou concessão real. Restantes decisões de28/11 registadas na continuidade e proposta de auditoria; famílias privadas perguntadas, implantação preservada.
|
||||||
|
|
||||||
|
28/11/2026: preparações empresariais recuperadas por actor/empresa/contexto/permissões/versão/fonte: arranque/equipa, perfis separados entre novo/edição, atribuições por pessoa, activação, regras/IVA/comparação, dados bancários/locais, opções contratadas, inteligência/plano IA e alçadas. Palavras-passe excluídas pelo Inertia instalado; omissão não gera falso aviso nem input indefinido. Referência geográfica original congelada, sem a actualizar mantendo edição antiga. Frontend38em7ficheiros, nativos71/764, tipos/PHPStan/check/Pint/diff/build aprovados. Candidata `sgc-company-preparation-final-qa-20261128`, manifestodf4e07d422af16897581371283d9730f41076ad2888d1e4911bdd7cadbb92c5f,180entradas sem faltas; runner fixado. HTTP final213verificações/três sessões/17assets/136tabelas intactas, ambientes removidos. Falha inicial era transporte do verificador Node (!paused): corpos agora consumidos antes de devolver clone; regressão Node1passou com2MiB/fecho sem comprimento, cookies/204/redireccionamento. Runtime interrompido c218afc04aae removido sob guardas; b3antigo preservado. Prova `company_preparation_delta_20261128` em `proofs/requisition-history.json`. Recuperação não executa concessões/activações; piloto/SGF intactos. Reconciliar agora formulários nucleares restantes, sem repetir baterias sem delta; visual/decisões pendentes, aplicação integral activa.
|
||||||
|
|
||||||
28/11/2026: contraditório, medidas de melhoria e validação da ficha conservam preparações por actor/empresa/contexto/competência/avaliação/registo/versão/modo de relatório. UUID de criação recuperável entre tentativas; sucesso limpa apenas a preparação concluída e preserva estado dos outros registos, que reconstituem a versão nativa quando muda. Conferência em formulário não submetido automaticamente, botões explícitos. Validação separada do upload; nenhum File adicionado ao histórico. Frontend14em3ficheiros, percursos nativos32/360, tipos/check/diff/build aprovados. Build privado `sgc-supplier-followup-preparation-qa-20261128`, manifesto46a86de9590ceb084b8a9b04abc7782404780044a38cc0982b399dad9bdc88c2,180entradas sem faltas, anteriores preservados. Prova `supplier_followup_preparation_delta_20261128` em `proofs/requisition-history.json`; runner permanece43fc8077/provaHTTP200, sem nova prova HTTP/visual deste build. Próxima frente delimitada: preparações da configuração empresarial, preservando versões, confirmações, perfis e nenhuma concessão por recuperação. Piloto/SGF preservados; aplicação integral activa.
|
28/11/2026: contraditório, medidas de melhoria e validação da ficha conservam preparações por actor/empresa/contexto/competência/avaliação/registo/versão/modo de relatório. UUID de criação recuperável entre tentativas; sucesso limpa apenas a preparação concluída e preserva estado dos outros registos, que reconstituem a versão nativa quando muda. Conferência em formulário não submetido automaticamente, botões explícitos. Validação separada do upload; nenhum File adicionado ao histórico. Frontend14em3ficheiros, percursos nativos32/360, tipos/check/diff/build aprovados. Build privado `sgc-supplier-followup-preparation-qa-20261128`, manifesto46a86de9590ceb084b8a9b04abc7782404780044a38cc0982b399dad9bdc88c2,180entradas sem faltas, anteriores preservados. Prova `supplier_followup_preparation_delta_20261128` em `proofs/requisition-history.json`; runner permanece43fc8077/provaHTTP200, sem nova prova HTTP/visual deste build. Próxima frente delimitada: preparações da configuração empresarial, preservando versões, confirmações, perfis e nenhuma concessão por recuperação. Piloto/SGF preservados; aplicação integral activa.
|
||||||
|
|
||||||
28/11/2026: preparações de taxa cambial documental e pedido de cancelamento recuperadas por actor/empresa/contexto/permissões/processo/versão/competência nativa. UUIDs preservados para repetição, ignorados no aviso e renovados no sucesso; sem congelar taxas ou cancelar automaticamente. Payloads/rotas/motores preservados. Frontend15em4ficheiros, tipos/check/diff/build aprovados. Build privado `sgc-document-command-preparation-qa-20261128`, manifesto652c3190f1897155641ebc50c6e3ce0454b96244dc4f603d96ffc3e61b69b529,179entradas sem faltas, anteriores preservados; `document_command_preparation_delta_20261128` em `proofs/requisition-history.json`. Runner permanece43fc8077/provaHTTP200; não atribuir HTTP/visual novo a este build. Próxima frente delimitada: preparações de contraditório/medidas de melhoria do fornecedor e revisão da ficha, preservando versões, UUIDs de criação e ficheiros fora da memória do histórico. Piloto/SGF preservados; aplicação integral activa.
|
28/11/2026: preparações de taxa cambial documental e pedido de cancelamento recuperadas por actor/empresa/contexto/permissões/processo/versão/competência nativa. UUIDs preservados para repetição, ignorados no aviso e renovados no sucesso; sem congelar taxas ou cancelar automaticamente. Payloads/rotas/motores preservados. Frontend15em4ficheiros, tipos/check/diff/build aprovados. Build privado `sgc-document-command-preparation-qa-20261128`, manifesto652c3190f1897155641ebc50c6e3ce0454b96244dc4f603d96ffc3e61b69b529,179entradas sem faltas, anteriores preservados; `document_command_preparation_delta_20261128` em `proofs/requisition-history.json`. Runner permanece43fc8077/provaHTTP200; não atribuir HTTP/visual novo a este build. Próxima frente delimitada: preparações de contraditório/medidas de melhoria do fornecedor e revisão da ficha, preservando versões, UUIDs de criação e ficheiros fora da memória do histórico. Piloto/SGF preservados; aplicação integral activa.
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
# Matriz reconciliada do SGC — 03/11/2026
|
# Matriz reconciliada do SGC — 03/11/2026
|
||||||
|
|
||||||
|
28/11/2026: preparações empresariais recuperadas por actor/empresa/contexto/permissões/versão/fonte: arranque/equipa, perfis separados entre novo/edição, atribuições por pessoa, activação, regras/IVA/comparação, dados bancários/locais, opções contratadas, inteligência/plano IA e alçadas. Palavras-passe excluídas pelo Inertia instalado; omissão não gera falso aviso nem input indefinido. Referência geográfica original congelada, sem a actualizar mantendo edição antiga. Frontend38em7ficheiros, nativos71/764, tipos/PHPStan/check/Pint/diff/build aprovados. Candidata `sgc-company-preparation-final-qa-20261128`, manifestodf4e07d422af16897581371283d9730f41076ad2888d1e4911bdd7cadbb92c5f,180entradas sem faltas; runner fixado. HTTP final213verificações/três sessões/17assets/136tabelas intactas, ambientes removidos. Falha inicial era transporte do verificador Node (!paused): corpos agora consumidos antes de devolver clone; regressão Node1passou com2MiB/fecho sem comprimento, cookies/204/redireccionamento. Runtime interrompido c218afc04aae removido sob guardas; b3antigo preservado. Prova `company_preparation_delta_20261128` em `proofs/requisition-history.json`. Recuperação não executa concessões/activações; piloto/SGF intactos. Reconciliar agora formulários nucleares restantes, sem repetir baterias sem delta; visual/decisões pendentes, aplicação integral activa.
|
||||||
|
|
||||||
28/11/2026: contraditório, medidas de melhoria e validação da ficha conservam preparações por actor/empresa/contexto/competência/avaliação/registo/versão/modo de relatório. UUID de criação recuperável entre tentativas; sucesso limpa apenas a preparação concluída e preserva estado dos outros registos, que reconstituem a versão nativa quando muda. Conferência em formulário não submetido automaticamente, botões explícitos. Validação separada do upload; nenhum File adicionado ao histórico. Frontend14em3ficheiros, percursos nativos32/360, tipos/check/diff/build aprovados. Build privado `sgc-supplier-followup-preparation-qa-20261128`, manifesto46a86de9590ceb084b8a9b04abc7782404780044a38cc0982b399dad9bdc88c2,180entradas sem faltas, anteriores preservados. Prova `supplier_followup_preparation_delta_20261128` em `proofs/requisition-history.json`; runner permanece43fc8077/provaHTTP200, sem nova prova HTTP/visual deste build. Próxima frente delimitada: preparações da configuração empresarial, preservando versões, confirmações, perfis e nenhuma concessão por recuperação. Piloto/SGF preservados; aplicação integral activa.
|
28/11/2026: contraditório, medidas de melhoria e validação da ficha conservam preparações por actor/empresa/contexto/competência/avaliação/registo/versão/modo de relatório. UUID de criação recuperável entre tentativas; sucesso limpa apenas a preparação concluída e preserva estado dos outros registos, que reconstituem a versão nativa quando muda. Conferência em formulário não submetido automaticamente, botões explícitos. Validação separada do upload; nenhum File adicionado ao histórico. Frontend14em3ficheiros, percursos nativos32/360, tipos/check/diff/build aprovados. Build privado `sgc-supplier-followup-preparation-qa-20261128`, manifesto46a86de9590ceb084b8a9b04abc7782404780044a38cc0982b399dad9bdc88c2,180entradas sem faltas, anteriores preservados. Prova `supplier_followup_preparation_delta_20261128` em `proofs/requisition-history.json`; runner permanece43fc8077/provaHTTP200, sem nova prova HTTP/visual deste build. Próxima frente delimitada: preparações da configuração empresarial, preservando versões, confirmações, perfis e nenhuma concessão por recuperação. Piloto/SGF preservados; aplicação integral activa.
|
||||||
|
|
||||||
28/11/2026: preparações de taxa cambial documental e pedido de cancelamento recuperadas por actor/empresa/contexto/permissões/processo/versão/competência nativa. UUIDs preservados para repetição, ignorados no aviso e renovados no sucesso; sem congelar taxas ou cancelar automaticamente. Payloads/rotas/motores preservados. Frontend15em4ficheiros, tipos/check/diff/build aprovados. Build privado `sgc-document-command-preparation-qa-20261128`, manifesto652c3190f1897155641ebc50c6e3ce0454b96244dc4f603d96ffc3e61b69b529,179entradas sem faltas, anteriores preservados; `document_command_preparation_delta_20261128` em `proofs/requisition-history.json`. Runner permanece43fc8077/provaHTTP200; não atribuir HTTP/visual novo a este build. Próxima frente delimitada: preparações de contraditório/medidas de melhoria do fornecedor e revisão da ficha, preservando versões, UUIDs de criação e ficheiros fora da memória do histórico. Piloto/SGF preservados; aplicação integral activa.
|
28/11/2026: preparações de taxa cambial documental e pedido de cancelamento recuperadas por actor/empresa/contexto/permissões/processo/versão/competência nativa. UUIDs preservados para repetição, ignorados no aviso e renovados no sucesso; sem congelar taxas ou cancelar automaticamente. Payloads/rotas/motores preservados. Frontend15em4ficheiros, tipos/check/diff/build aprovados. Build privado `sgc-document-command-preparation-qa-20261128`, manifesto652c3190f1897155641ebc50c6e3ce0454b96244dc4f603d96ffc3e61b69b529,179entradas sem faltas, anteriores preservados; `document_command_preparation_delta_20261128` em `proofs/requisition-history.json`. Runner permanece43fc8077/provaHTTP200; não atribuir HTTP/visual novo a este build. Próxima frente delimitada: preparações de contraditório/medidas de melhoria do fornecedor e revisão da ficha, preservando versões, UUIDs de criação e ficheiros fora da memória do histórico. Piloto/SGF preservados; aplicação integral activa.
|
||||||
@@ -188,13 +190,13 @@ Fonte: `A requisção de insumos de produção.docx`, secções 1–9; exemplar/
|
|||||||
| --- | --- |
|
| --- | --- |
|
||||||
| Compra e interna, numeração própria | REQ e RA existentes, com motores e origens preservados; não fundir compra com documento de saída interna. |
|
| Compra e interna, numeração própria | REQ e RA existentes, com motores e origens preservados; não fundir compra com documento de saída interna. |
|
||||||
| Insumos, peças, maquinaria e escritório | Classificação explícita e regras condicionais verificadas em QA, incluindo critérios opcionais de aprovação; não instaladas no piloto. Ver `rq01-categories.json`; MRP e restantes requisitos não são inferidos desta entrega. |
|
| Insumos, peças, maquinaria e escritório | Classificação explícita e regras condicionais verificadas em QA, incluindo critérios opcionais de aprovação; não instaladas no piloto. Ver `rq01-categories.json`; MRP e restantes requisitos não são inferidos desta entrega. |
|
||||||
| Insumos para produção | Primeiro incremento disponível em QA: destino próprio, referência declarada opcional, catálogo de stock obrigatório nativo, entrega/evento/operação única, impressão/CSV e origem da reposição. `production-destination.json`. Não afirma validação de ordem externa ou MRP. |
|
| Insumos para produção | Destino próprio, catálogo de stock, entrega e reposição preservados (`production-destination.json`). Em28/11, cadastro próprio de ordens de produção/manutenção e ligação versionada por linha implementados em QA: origem nos locais abrangidos, com competências de responsável da produção/chefe de oficina, ou registo pelo procurement, conforme configuração expressa. Emissão normal/parcial/consolidada conserva a origem em snapshot, consulta e impressão. `rq01-account-assignment-qa.json`. Não é integração de ordens externas, planeamento MRP ou activação no piloto. |
|
||||||
| Compatibilidade do feed de armazém | Produção é representada como uso interno no contrato v1 existente; o detalhe de produção fica preservado no SGC. Regressão valida o feed com o consumidor actual. Não foi alterado nem activado o SGF; transportar metadados adicionais exige evolução explícita do contrato. |
|
| Compatibilidade do feed de armazém | Produção é representada como uso interno no contrato v1 existente; o detalhe de produção fica preservado no SGC. Regressão valida o feed com o consumidor actual. Não foi alterado nem activado o SGF; transportar metadados adicionais exige evolução explícita do contrato. |
|
||||||
| Atribuição de conta por linha e distribuições | Distribuições V1 por linha/centro instaladas no piloto autorizado, com escritor comum único; não repetir instalação. Cadastro próprio de projectos/imobilizado e ligação explícita por artigo/rastreio implementados em QA (`capital-register-qa.json`). Contas de movimento do plano comum na base própria, imputação por linha/parcelas exactas, submissão, versões e congelamento em ordens normais/parciais/consolidadas verificados (`rq01-account-assignment-qa.json`,9/158, concorrência e restauro124tabelas). Sem segundo plano ou lançamentos novos. Aplicabilidade dos restantes destinos e revisão visual final continuam por demonstrar. |
|
| Atribuição de conta por linha e distribuições | Distribuições V1 por linha/centro instaladas no piloto autorizado, com escritor comum único; não repetir instalação. Cadastro próprio de projectos/imobilizado e ligação explícita por artigo/rastreio implementados em QA (`capital-register-qa.json`). Contas de movimento do plano comum na base própria, imputação por linha/parcelas exactas, submissão, versões e congelamento em ordens normais/parciais/consolidadas verificados (`rq01-account-assignment-qa.json`,9/158, concorrência e restauro124tabelas). Sem segundo plano ou lançamentos novos. Aplicabilidade dos restantes destinos e revisão visual final continuam por demonstrar. |
|
||||||
| Aprovação por valor/categoria/centro, até oito níveis | Implementado, testado e capacidade instalada no piloto: controlos base mais até cinco níveis condicionais por perfis, máximo oito, um elegível por nível. Versão/encaminhamento congelados, sem concessões automáticas. Provas `configured-requisition-levels.json` e `approval-search-pilot-installation.json`. Configuração pela empresa, revisão visual restante e aceitação pendentes; não repetir instalação. |
|
| Aprovação por valor/categoria/centro, até oito níveis | Implementado, testado e capacidade instalada no piloto: controlos base mais até cinco níveis condicionais por perfis, máximo oito, um elegível por nível. Versão/encaminhamento congelados, sem concessões automáticas. Provas `configured-requisition-levels.json` e `approval-search-pilot-installation.json`. Configuração pela empresa, revisão visual restante e aceitação pendentes; não repetir instalação. |
|
||||||
| Auto-aprovação | Continua proibida. A opção proposta não é activada sem limite e decisão/configuração concreta; nenhum valor ilustrativo é parametrização da empresa. |
|
| Auto-aprovação | Continua proibida. A opção proposta não é activada sem limite e decisão/configuração concreta; nenhum valor ilustrativo é parametrização da empresa. |
|
||||||
| Orçamento e compromisso | Preservar o núcleo comum e a regra vigente. Não alterar política financeira ou activar regra em dados reais pela importação do documento. |
|
| Orçamento e compromisso | Preservar o núcleo comum e a regra vigente. Não alterar política financeira ou activar regra em dados reais pela importação do documento. |
|
||||||
| Urgência e peça crítica | Metadados/validação técnica, prazos reduzidos explicitamente configuráveis e revisão posterior por ciclo implementados em QA (`requisition-expiry-qa.json`). Revisão fica disponível após decisão final, incluindo rejeição e expiração, conforme decisão expressa da Tempo. Configuração real da empresa e momento de conferir o limite da redução de cotações continuam próprios; não dispensar cotações ou orçamento por inferência. |
|
| Urgência e peça crítica | Metadados, prazos reduzidos explicitamente configurados e revisão posterior por ciclo preservados (`requisition-expiry-qa.json`). Revisão após decisão final, incluindo rejeição/expiração. Em28/11, mínimo de stock parametrizável por artigo/local/natureza/utilização e número reduzido de propostas expressamente configurado, sem valor universal. A evidência do evento é escolhida e conferida por linha/ciclo; sem todas as fontes compatíveis mantém-se o mínimo normal. Orçamento, conta, avaliações e aprovações independentes mantêm-se. PG6/139, frontend46, tipos/PHPStan/check/build privado aprovados; consulta HTTP final234/três sessões/19assets/137tabelas intactas, sem comandos de negócio ou prova visual. Flag false no piloto. |
|
||||||
| Maquinaria | Percurso nativo integrado demonstrado em QA até recepção, cadastro físico/ligação ao imobilizado e liquidação, com técnica, dotação de investimento e direcção expressa por níveis existentes (`rq01-account-assignment-qa.json`, delta maquinaria de27/11). Origem v1 preservada após ligação física v2; sem lançamento contabilístico. Configuração empresarial, apresentação e aceitação operacional permanecem pendentes; não duplicar os motores SGF. |
|
| Maquinaria | Percurso nativo integrado demonstrado em QA até recepção, cadastro físico/ligação ao imobilizado e liquidação, com técnica, dotação de investimento e direcção expressa por níveis existentes (`rq01-account-assignment-qa.json`, delta maquinaria de27/11). Origem v1 preservada após ligação física v2; sem lançamento contabilístico. Configuração empresarial, apresentação e aceitação operacional permanecem pendentes; não duplicar os motores SGF. |
|
||||||
| Lembretes, escalamento e expiração | Política empresarial configurável/fixada por ciclo, lembretes e alertas a perfis expressos, expiração com devolução/libertação e nova submissão implementados em QA autorizada (`requisition-expiry-qa.json`). Agendador sem sessão, recusa de operações alheias, concorrência e recuperação verificados. Alertar não delega aprovação. Revisão visual e disponibilização operacional pendentes; nenhum prazo ilustrativo activado no piloto. |
|
| Lembretes, escalamento e expiração | Política empresarial configurável/fixada por ciclo, lembretes e alertas a perfis expressos, expiração com devolução/libertação e nova submissão implementados em QA autorizada (`requisition-expiry-qa.json`). Agendador sem sessão, recusa de operações alheias, concorrência e recuperação verificados. Alertar não delega aprovação. Revisão visual e disponibilização operacional pendentes; nenhum prazo ilustrativo activado no piloto. |
|
||||||
| Divisão/consolidação e conversão | Emissão documental, visibilidade entre origens, recepção/factura, câmbio por origem e reafectação financeira implementados e verificados em QA; deltas e provas no início desta matriz. Emissão parcial também verificada no segundo ciclo de reserva. Revisão visual restante e disponibilização operacional mantêm requisitos próprios; V1 instalado preservado. |
|
| Divisão/consolidação e conversão | Emissão documental, visibilidade entre origens, recepção/factura, câmbio por origem e reafectação financeira implementados e verificados em QA; deltas e provas no início desta matriz. Emissão parcial também verificada no segundo ciclo de reserva. Revisão visual restante e disponibilização operacional mantêm requisitos próprios; V1 instalado preservado. |
|
||||||
@@ -290,7 +292,7 @@ O relatório de conferência já tinha impressão; acrescentada exportação CSV
|
|||||||
|
|
||||||
Verificação: 278 testes integrados/3378 asserções em SQLite e um teste dirigido adicional de cancelamento/20 asserções; 30 testes dirigidos/197 asserções em PostgreSQL, seis verificações do CSV e dois cenários com contenção real entre escritores. Bases descartáveis removidas. Sete testes frontend, tipos, análise estática dirigida, formatação/lint dos dez ficheiros frontend alterados e compilação privada aprovados. Provas locais: `storage/logs/exchange-final-integration.txt`, `exchange-cancellation-tests.txt`, `exchange-release-postgres.txt`, `exchange-release-phpstan.txt`, `exchange-frontend-tests.txt` e `exchange-private-build.txt`. As baterias sobrepõem-se e não devem ser somadas.
|
Verificação: 278 testes integrados/3378 asserções em SQLite e um teste dirigido adicional de cancelamento/20 asserções; 30 testes dirigidos/197 asserções em PostgreSQL, seis verificações do CSV e dois cenários com contenção real entre escritores. Bases descartáveis removidas. Sete testes frontend, tipos, análise estática dirigida, formatação/lint dos dez ficheiros frontend alterados e compilação privada aprovados. Provas locais: `storage/logs/exchange-final-integration.txt`, `exchange-cancellation-tests.txt`, `exchange-release-postgres.txt`, `exchange-release-phpstan.txt`, `exchange-frontend-tests.txt` e `exchange-private-build.txt`. As baterias sobrepõem-se e não devem ser somadas.
|
||||||
|
|
||||||
Isto sucede à lacuna de propostas exclusivamente em MZN nas linhas históricas abaixo. Não declara o produto completo: conversões gerais de unidades, restantes lacunas dos documentos base, formalização/execução de Pessoas, verificações globais de qualidade, revisão visual, instalação e aceitação mantêm critérios próprios. A pergunta de critério para formalização documental de Pessoas permanece pendente de resposta nesta sessão.
|
Isto sucede à lacuna de propostas exclusivamente em MZN nas linhas históricas abaixo. A extensão de conversões de inventário já tem entrega QA documentada na actualização de 21/11 acima; não a reabrir como ausência de implementação. A formalização de Pessoas permanece adiada por decisão expressa «Manter a formalização pendente», registada em `orientacoes-continuidade.md`, e não por falta de resposta. Restantes lacunas dos documentos base, verificações globais de qualidade, revisão visual, instalação e aceitação mantêm critérios próprios. Nenhuma destas entregas autoriza activar conversões ou formalização no piloto.
|
||||||
|
|
||||||
Esta revisão confronta a matriz histórica de `compatibilidade.md` com código e provas posteriores. É uma reconciliação documental e de código, não uma nova execução de todos os testes, revisão visual ou aceitação comercial. As provas citadas conservam a data, composição e limites originais; os seus números não se somam.
|
Esta revisão confronta a matriz histórica de `compatibilidade.md` com código e provas posteriores. É uma reconciliação documental e de código, não uma nova execução de todos os testes, revisão visual ou aceitação comercial. As provas citadas conservam a data, composição e limites originais; os seus números não se somam.
|
||||||
|
|
||||||
@@ -305,10 +307,10 @@ O âmbito é o SGC autónomo em `C:/laragon/www/compras`, com o piloto sintétic
|
|||||||
| Requisições e aprovações | `RequisitionWorkflow`; `InternalRequisitionCandidateTest`; `proofs/pilot-approval-activation.json` | Circuito versionado e recibos de comandos implementados; aprovação sintética aplicada uma vez. Valores e segregação continuam a pertencer à configuração da empresa. Não significa aceitação empresarial nem autorização de adjudicação. |
|
| Requisições e aprovações | `RequisitionWorkflow`; `InternalRequisitionCandidateTest`; `proofs/pilot-approval-activation.json` | Circuito versionado e recibos de comandos implementados; aprovação sintética aplicada uma vez. Valores e segregação continuam a pertencer à configuração da empresa. Não significa aceitação empresarial nem autorização de adjudicação. |
|
||||||
| Fornecedores | `SupplierParticipation`, `SupplierBankWorkflow`, `SupplierEvaluationWorkflow`; provas históricas e actualização de 21/11 abaixo | Cadastro, validação, avaliação qualitativa, contraditório e tarefas preservados. Múltiplas contas independentes implementadas e verificadas em QA em 21/11, com migração ainda não instalada no piloto. Verificação bancária externa não é inferida do cadastro. |
|
| Fornecedores | `SupplierParticipation`, `SupplierBankWorkflow`, `SupplierEvaluationWorkflow`; provas históricas e actualização de 21/11 abaixo | Cadastro, validação, avaliação qualitativa, contraditório e tarefas preservados. Múltiplas contas independentes implementadas e verificadas em QA em 21/11, com migração ainda não instalada no piloto. Verificação bancária externa não é inferida do cadastro. |
|
||||||
| Cotações | `QuotationController`, `QuotationPricing`, `QuotationExchange`; actualização de 21/11 acima | Preços/descontos reutilizam núcleo comum. Multimoeda implementada e verificada em QA com moeda original e taxa explícita para MZN, data/fonte congeladas, conforme aprovação do proprietário. Migração ainda não instalada no piloto; não confundir esta entrega com taxa automática, câmbio bancário ou autorização de propostas reais. |
|
| Cotações | `QuotationController`, `QuotationPricing`, `QuotationExchange`; actualização de 21/11 acima | Preços/descontos reutilizam núcleo comum. Multimoeda implementada e verificada em QA com moeda original e taxa explícita para MZN, data/fonte congeladas, conforme aprovação do proprietário. Migração ainda não instalada no piloto; não confundir esta entrega com taxa automática, câmbio bancário ou autorização de propostas reais. |
|
||||||
| Conflitos RF-AF-01 | `ConflictGuard`; `compatibilidade.md` | Há controlo no servidor. Não foi comprovado nesta revisão o ciclo completo de periodicidade/validade/levantamento; manter pendente, sem desactivar impedimentos. |
|
| Conflitos RF-AF-01 | `ConflictGuard`, `ConflictReleases`; `compatibilidade.md` | Levantamento por autorização da direcção decidido em 28/11 e implementado em QA, com competência própria configurável, fundamento, autoria, fonte congelada e histórico imutável. Sem herança automática de Admin/Finanças, caducidade ou retirada pela declaração de ausência. Correcções da mesma declaração partilham a decisão; outra declaração continua a bloquear. SQLite e PostgreSQL: 46 testes/418 asserções em cada motor; frontend 5 testes, tipos/PHPStan/check/Pint/build privado aprovados. Migração e capacidade desligadas no piloto. Periodicidade/validade e aceitação operacional mantêm cobertura própria. |
|
||||||
| Adjudicação e ordens | `PurchaseAwardOrderTest`; `cancelamento-ordens-emitidas.md`; `proofs/issued-order-cancellation.json` | C2 autorizado para desenvolvimento,implementado com política própria e decisão independente de Finanças,sem recepção/factura/pagamento. Original imutável,reversão canónica auditada única e revisão ligada. Desligado e sem migração/políticas/cancelamentos no piloto;antes da emissão e estornos físicos mantêm circuitos separados. |
|
| Adjudicação e ordens | `PurchaseAwardOrderTest`; `cancelamento-ordens-emitidas.md`; `proofs/issued-order-cancellation.json` | C2 autorizado para desenvolvimento,implementado com política própria e decisão independente de Finanças,sem recepção/factura/pagamento. Original imutável,reversão canónica auditada única e revisão ligada. Desligado e sem migração/políticas/cancelamentos no piloto;antes da emissão e estornos físicos mantêm circuitos separados. |
|
||||||
| Recepção | `ReceiptWorkflow`; provas de recepção e `proofs/inventory-corrections.json`; `recepcao-documental.md` | Recepção e correcções físicas implementadas; anexos privados R1 instalados com autorização, backup/restauro e consulta por perfis confirmados (`proofs/receipt-block-installation.json`). R2 acrescenta reprodução imprimível com referências dos estornos e anexos. Substituições e aceitação operacional integral mantêm cobertura própria; correcção física não equivale a nota de crédito. |
|
| Recepção | `ReceiptWorkflow`; provas de recepção e `proofs/inventory-corrections.json`; `recepcao-documental.md` | Recepção e correcções físicas implementadas; anexos privados R1 instalados com autorização, backup/restauro e consulta por perfis confirmados (`proofs/receipt-block-installation.json`). R2 acrescenta reprodução imprimível com referências dos estornos e anexos. Substituições e aceitação operacional integral mantêm cobertura própria; correcção física não equivale a nota de crédito. |
|
||||||
| Stock | `StockWorkflow`, `InventoryLots`, `InventoryReversals`, `InventoryDispositions`; `proofs/inventory-task-integration.json` | Lotes, qualidade, correcções e tarefas já existem; «estornos ausentes» seria uma conclusão incorrecta para stock. Conversões gerais de unidade e revisão visual não foram encerradas. |
|
| Stock | `StockWorkflow`, `InventoryLots`, `InventoryReversals`, `InventoryDispositions`, `ReceiptQuantityConversion`; `proofs/inventory-task-integration.json`; actualização de conversões de 21/11 acima | Lotes, qualidade, correcções e tarefas já existem; «estornos ausentes» seria uma conclusão incorrecta para stock. Conversão documental/física, parcelas, lotes, devolução e estorno têm entrega QA própria; fonte/factor/versão congelados, sem arredondamento de quantidades. A guarda actual exige configuração explícita e ambiente testing. Instalação, activação e revisão visual continuam separadas. |
|
||||||
| Requisições internas | `WarehouseRequests`, `WarehouseReservations`, `WarehouseFulfilment`; `proofs/warehouse-task-pilot-status-http.json` | Autorização, reserva e entrega usam a requisição como documento de saída, sem factura. Venda a terceiros pertence à composição SGF; não desenvolver facturação paralela no SGC. |
|
| Requisições internas | `WarehouseRequests`, `WarehouseReservations`, `WarehouseFulfilment`; `proofs/warehouse-task-pilot-status-http.json` | Autorização, reserva e entrega usam a requisição como documento de saída, sem factura. Venda a terceiros pertence à composição SGF; não desenvolver facturação paralela no SGC. |
|
||||||
| Devolução interna de excedente | `WarehouseReturns`; `warehouse-unused-return.md` | Implementação sintética própria, desactivada por defeito. Não confundir existência de código/prova com funcionalidade activa no piloto; não habilitar por esta revisão. |
|
| Devolução interna de excedente | `WarehouseReturns`; `warehouse-unused-return.md` | Implementação sintética própria, desactivada por defeito. Não confundir existência de código/prova com funcionalidade activa no piloto; não habilitar por esta revisão. |
|
||||||
| Equipamentos e peças | `EquipmentWorkflow`; `EquipmentSparePartsTest`, `InvestmentPolicyTest`; `equipamentos-acompanhamento.md` | E1 liga ficha do equipamento às compras visíveis e movimentos físicos,com paginação independente e operação única da entrega interna (`proofs/equipment-integration.json`). Configuração empresarial,agregação por projecto e fraccionamento continuam separados,sem encerramento por esta ficha. |
|
| Equipamentos e peças | `EquipmentWorkflow`; `EquipmentSparePartsTest`, `InvestmentPolicyTest`; `equipamentos-acompanhamento.md` | E1 liga ficha do equipamento às compras visíveis e movimentos físicos,com paginação independente e operação única da entrega interna (`proofs/equipment-integration.json`). Configuração empresarial,agregação por projecto e fraccionamento continuam separados,sem encerramento por esta ficha. |
|
||||||
@@ -317,7 +319,7 @@ O âmbito é o SGC autónomo em `C:/laragon/www/compras`, com o piloto sintétic
|
|||||||
| Planeamento e formalização | `PurchasePlanningWorkflow`, `ProposalOpeningWorkflow`, `FormalAdmission`, `FormalRecommendation`; `validacao-tecnica.md` | Preservar adopções e políticas independentes. Não há prova nesta revisão de assinaturas digitais verificadas, propostas seladas ou aprovação financeira de planos. |
|
| Planeamento e formalização | `PurchasePlanningWorkflow`, `ProposalOpeningWorkflow`, `FormalAdmission`, `FormalRecommendation`; `validacao-tecnica.md` | Preservar adopções e políticas independentes. Não há prova nesta revisão de assinaturas digitais verificadas, propostas seladas ou aprovação financeira de planos. |
|
||||||
| Pessoas e contratações | `PeopleHiring`, `PeopleRegistry`, `PeopleReportController`; `reutilizacao-dados.md` e `PeopleHiringTest` | Cadastro reutilizável, relatórios e caixa de tarefas são distintos dos de Compras. Uma referência antiga a «sem relatórios» não descreve o código actual. Aceitação visual e cobertura empresarial continuam separadas. |
|
| Pessoas e contratações | `PeopleHiring`, `PeopleRegistry`, `PeopleReportController`; `reutilizacao-dados.md` e `PeopleHiringTest` | Cadastro reutilizável, relatórios e caixa de tarefas são distintos dos de Compras. Uma referência antiga a «sem relatórios» não descreve o código actual. Aceitação visual e cobertura empresarial continuam separadas. |
|
||||||
| Navegação e relatórios | Páginas `workflow/tasks`, `workflow/notices`, `supply/coordination`; `proofs/task-deadlines.json`, `proofs/notice-consultation.json`, `proofs/coordination-export.json` | Filtros, prazos e CSV de acompanhamento entregues. Isto não encerra revisão visual, impressão ou todos os relatórios exigidos pelo produto. |
|
| Navegação e relatórios | Páginas `workflow/tasks`, `workflow/notices`, `supply/coordination`; `proofs/task-deadlines.json`, `proofs/notice-consultation.json`, `proofs/coordination-export.json` | Filtros, prazos e CSV de acompanhamento entregues. Isto não encerra revisão visual, impressão ou todos os relatórios exigidos pelo produto. |
|
||||||
| Auditoria | `AuditLog`, auditoria dos comandos e relatórios por processo | Conservação integral sem eliminação automática aprovada em22/11, com bloqueios de edição/eliminação no modelo. Consulta/CSV de metadados e histórico por processo existem; ciclos anteriores passam a apresentar documento/regras e decisões preservadas (`requisition-expiry-qa.json`). Não reabrir prazo de conservação nem converter garantia absoluta contra administradorSQL em exigência adicional. Exportação integral e aceitação transversal ainda por demonstrar. |
|
| Auditoria | `AuditLog`, auditoria nativa e `PrivateAuditExporter` | 28/11/2026 — exportação privada de auditoria implementada em QA para Compras, stock, finanças e configuração, conforme decisão expressa. Quatro competências próprias independentes, sem herança de Admin/Finanças/metadados; bancos completos e Pessoas separados. ZIP privado imutável com manifesto, fontes/contagens/colunas ausentes, NDJSON integral e originais verificados; snapshot readonly, UUID idempotente, hashes, descarga autenticada dos bytes conferidos e limpeza só de ficheiros próprios. SQLite15/493, PG15/493 (base removida), frontend24/2ficheiros, tipos/PHPStan0/check/Pint/build aprovados. HTTP nativo270/quatro sessões/20assets,138tabelas intactas no intervalo de consultas; geração/repetição/ZIP conferidos após esse intervalo, recursos removidos. Manifesto fa87e37a3626ef75d22b5248dce9a0af2bad68c967e6f99bb64bc426a68f6aaf,183entradas. Consulta/CSV de metadados e retenção integral sem eliminação automática preservados. Prova `audit-export-scope-proposal.json`; sem concessões reais, activação ou aceitação visual/integral. |
|
||||||
| Reposição periódica | `AutomaticPurchases`, `ReplenishmentQueue`, `ReplenishmentProcessLock`; `proofs/replenishment-process-lock.json`, `operacao-reposicao.md` | Recuperação durável, reavaliação temporal e exclusão local existem. A pendência deixou de ser «implementar reposição»: é instalar/conferir operação comercial após reinício e validar capacidade. O bloqueio local não prova exclusão distribuída. |
|
| Reposição periódica | `AutomaticPurchases`, `ReplenishmentQueue`, `ReplenishmentProcessLock`; `proofs/replenishment-process-lock.json`, `operacao-reposicao.md` | Recuperação durável, reavaliação temporal e exclusão local existem. A pendência deixou de ser «implementar reposição»: é instalar/conferir operação comercial após reinício e validar capacidade. O bloqueio local não prova exclusão distribuída. |
|
||||||
|
|
||||||
## Lacuna escolhida nesta revisão
|
## Lacuna escolhida nesta revisão
|
||||||
|
|||||||
@@ -1,5 +1,19 @@
|
|||||||
# Continuidade do desenvolvimento do SGC
|
# Continuidade do desenvolvimento do SGC
|
||||||
|
|
||||||
|
28/11/2026 — exportação privada de auditoria implementada em QA para Compras, stock, finanças e configuração, conforme decisão expressa. Quatro competências próprias independentes, sem herança de Admin/Finanças/metadados; bancos completos e Pessoas separados. ZIP privado imutável com manifesto, fontes/contagens/colunas ausentes, NDJSON integral e originais verificados; snapshot readonly, UUID idempotente, hashes, descarga autenticada dos bytes conferidos e limpeza só de ficheiros próprios. SQLite15/493, PG15/493 (base removida), frontend24/2ficheiros, tipos/PHPStan0/check/Pint/build aprovados. HTTP nativo270/quatro sessões/20assets,138tabelas intactas no intervalo de consultas; geração/repetição/ZIP conferidos após esse intervalo, recursos removidos. Manifesto fa87e37a3626ef75d22b5248dce9a0af2bad68c967e6f99bb64bc426a68f6aaf,183entradas. Prova: `proofs/audit-export-scope-proposal.json`. Substitui a pendência histórica de escolha das famílias/exportador abaixo; não voltar a perguntar o âmbito. Sem concessões reais, instalação/activação, alteração do piloto/SGF ou aceitação visual/integral. Originais mantêm bytes; não se afirma anonimização de texto livre ou certificação.
|
||||||
|
|
||||||
|
28/11/2026: corrigido erro de acesso introduzido no novo cadastro: apenas metadados nao permitem consultar ordens; leitores autorizados do processo recebem so as origens ligadas. Regressao SQLite1/24 e PostgreSQL1/24, base removida; PHPStan0 e HTTP final234/três sessoes/19assets/137tabelas intactas, sem comandos. Log storage/logs/operational-urgent-http-final-20261128.log; fonte/manifesto privado b712f509 preservados.
|
||||||
|
|
||||||
|
28/11/2026 — redução urgente após stock mínimo implementada em QA: número reduzido opcional/expresso na comparação da empresa, sem valor universal, preservado apenas em novas requisições. Compras selecciona política aprovada por artigo/local e documenta o evento de mínimo atingido, contexto de uso, stock nativo, linha, autor/data/ciclo. Todas as linhas precisam de evidência compatível; falta/alteração conserva mínimo normal. Não inventar novo limite monetário: trecho urgente do Word confirma eventual dispensa da segunda cotação e preserva orçamento/conta/aprovador independente. Leitura pelos intervenientes nativos da comparação; gravação só com preparação actual de cotações. Fingerprint e snapshots normal/parcial/consolidado, ecrã e impressão preservam a origem. PG6/139, SQLite5passaram/122+1saltado (parcial indisponível no pacote antigo, provado no PG privado), frontend46/4ficheiros, tipos/PHPStan0/check9/Pint/build passaram. Candidata `sgc-urgent-stock-qa-20261128`, manifestob712f509fb0ff1179fc9d007abbef0a3c2d5f97f575b558cbc49f47d06dc9894,182entradas sem faltas; runner fixado. HTTP234verificações/três sessões/19assets/137tabelas intactas nas consultas; páginas de ordens e mínimo privado conferidas, recusas do requisitante, nenhum comando de negócio, recursos próprios removidos. Prova `urgent_stock_quotation_delta_20261128` em `proofs/requisition-expiry-qa.json`. Flag `urgent-quotations.qa_enabled` false; router habilita só no próprio QA guardado. Piloto/SGF intactos. Auditorias existentes e famílias privadas explicadas ao proprietário na proposta aberta no IDE; pergunta concreta de âmbito apresentada, não repetir a escolha já dada de autoridade própria. Visual/aceitação integral pendentes.
|
||||||
|
|
||||||
|
28/11/2026 — ordens de produção/manutenção: proprietário confirmou cadastro próprio e dois modos, origem nos locais abrangidos ou registo pelo agente de procurement nos restantes. Implementado `OperationalOrders`, página privada/cadastro/configuração, competências próprias de produção/oficina sem concessões, originais imutáveis e ligações versionadas por linha. Ordem nativa normal/parcial/consolidada conserva origem/autor/modo em snapshot, ecrã e impressão. Flag `operational-orders.qa_enabled` false; apenas testing/base QA, sem migração. Primeiro PG detectou erro próprio: kind de política maior que varchar20; corrigidos identificadores para op_order_policy/op_order/op_order_link, regressão de comprimento e asserções HTTP de sucesso reforçadas. SQLite12/136 (cadastro+fornecimento), PG6/115 (inclui emissão parcial) e delta stock1/5 passaram; bases removidas. Frontend36/3ficheiros, PHPStan0/check/Pint/build privado aprovados. Candidata `sgc-operational-orders-qa-20261128`, manifesto6b0126100bf6ad8ee88565c580c87ae724e259505f8bbb3c395312fc07cf9564,181entradas sem faltas. Contexto opcional de natureza/utilização preservado na política de mínimo, sem valor universal. Prova `operational_orders_and_stock_use_delta_20261128` em `proofs/rq01-account-assignment-qa.json`; sem nova prova HTTP/visual ou activação, runner anterior preservado. Próxima frente: redução urgente de cotações com mínimo de stock documentado e número explicitamente configurado, sem inventar limite monetário (o trecho de urgência do Word não o estabelece). Auditorias existentes explicadas: eventos/CSV de metadados, históricos documentais autorizados e relatórios de conferência; exportação privada própria ainda por implementar, nenhuma família sensível presumida.
|
||||||
|
|
||||||
|
28/11/2026 — decisões recebidas: limite urgente de cotações após atingir o stock mínimo; origem das ordens de produção no responsável da produção e das ordens de manutenção no chefe de oficina; exportação com autoridade de auditoria própria para conteúdo privado adicional; levantamento de impedimentos autorizado pela direcção. Não voltar a perguntar estas escolhas. A exportação exige delimitação das famílias privadas, já perguntada, sem inferir dados bancários/Pessoas ou concessões reais. Responsáveis não identificam por si um sistema externo; não criar integração SGF. Urgência não dispensa orçamento/aprovações, nem esta resposta fixa números de propostas ou montantes.
|
||||||
|
|
||||||
|
28/11/2026 — levantamento de conflitos implementado em QA: `ConflictReleases`, tabela própria append-only, competência `conflict_release_authorise` sem atribuição automática. Autor actual revalidado após bloqueio da empresa, referência à última correcção, fundamento, UUID recuperável/repetição única e fonte congelada. Levanta apenas a cadeia seleccionada; outra declaração continua a bloquear. Original não muda; sem prazos/caducidade, reaprovação ou efeitos financeiros automáticos. Interface conserva preparação e decisão no histórico. SQLite46/418 e PostgreSQL46/418 aprovados; base `compras_receipts_test_b6955b03c4ba` removida. Frontend5, tipos, PHPStan0, check/Pint/diff aprovados. Build privado `sgc-conflict-direction-qa-20261128`, manifesto8ac97298e6d8efbcde4b22b3dd2cfc4df76b0bbff9403d2b091a5e394089194e,180entradas sem faltas. Primeira invocação Node falhou antes do build por aspas PowerShell; execução por stdin passou. Runner HTTP permanece na candidata empresarial anterior: não atribuir HTTP213 ou visual a esta candidata. Migração apenas ensaiada em QA, capacidade false, piloto/SGF intactos. Continuar stock mínimo/ordens/auditoria; aplicação integral não concluída.
|
||||||
|
|
||||||
|
28/11/2026: preparações empresariais recuperadas por actor/empresa/contexto/permissões/versão/fonte: arranque/equipa, perfis separados entre novo/edição, atribuições por pessoa, activação, regras/IVA/comparação, dados bancários/locais, opções contratadas, inteligência/plano IA e alçadas. Palavras-passe excluídas pelo Inertia instalado; omissão não gera falso aviso nem input indefinido. Referência geográfica original congelada, sem a actualizar mantendo edição antiga. Frontend38em7ficheiros, nativos71/764, tipos/PHPStan/check/Pint/diff/build aprovados. Candidata `sgc-company-preparation-final-qa-20261128`, manifestodf4e07d422af16897581371283d9730f41076ad2888d1e4911bdd7cadbb92c5f,180entradas sem faltas; runner fixado. HTTP final213verificações/três sessões/17assets/136tabelas intactas, ambientes removidos. Falha inicial era transporte do verificador Node (!paused): corpos agora consumidos antes de devolver clone; regressão Node1passou com2MiB/fecho sem comprimento, cookies/204/redireccionamento. Runtime interrompido c218afc04aae removido sob guardas; b3antigo preservado. Prova `company_preparation_delta_20261128` em `proofs/requisition-history.json`. Recuperação não executa concessões/activações; piloto/SGF intactos. Reconciliar agora formulários nucleares restantes, sem repetir baterias sem delta; visual/decisões pendentes, aplicação integral activa.
|
||||||
|
|
||||||
28/11/2026: contraditório, medidas de melhoria e validação da ficha conservam preparações por actor/empresa/contexto/competência/avaliação/registo/versão/modo de relatório. UUID de criação recuperável entre tentativas; sucesso limpa apenas a preparação concluída e preserva estado dos outros registos, que reconstituem a versão nativa quando muda. Conferência em formulário não submetido automaticamente, botões explícitos. Validação separada do upload; nenhum File adicionado ao histórico. Frontend14em3ficheiros, percursos nativos32/360, tipos/check/diff/build aprovados. Build privado `sgc-supplier-followup-preparation-qa-20261128`, manifesto46a86de9590ceb084b8a9b04abc7782404780044a38cc0982b399dad9bdc88c2,180entradas sem faltas, anteriores preservados. Prova `supplier_followup_preparation_delta_20261128` em `proofs/requisition-history.json`; runner permanece43fc8077/provaHTTP200, sem nova prova HTTP/visual deste build. Próxima frente delimitada: preparações da configuração empresarial, preservando versões, confirmações, perfis e nenhuma concessão por recuperação. Piloto/SGF preservados; aplicação integral activa.
|
28/11/2026: contraditório, medidas de melhoria e validação da ficha conservam preparações por actor/empresa/contexto/competência/avaliação/registo/versão/modo de relatório. UUID de criação recuperável entre tentativas; sucesso limpa apenas a preparação concluída e preserva estado dos outros registos, que reconstituem a versão nativa quando muda. Conferência em formulário não submetido automaticamente, botões explícitos. Validação separada do upload; nenhum File adicionado ao histórico. Frontend14em3ficheiros, percursos nativos32/360, tipos/check/diff/build aprovados. Build privado `sgc-supplier-followup-preparation-qa-20261128`, manifesto46a86de9590ceb084b8a9b04abc7782404780044a38cc0982b399dad9bdc88c2,180entradas sem faltas, anteriores preservados. Prova `supplier_followup_preparation_delta_20261128` em `proofs/requisition-history.json`; runner permanece43fc8077/provaHTTP200, sem nova prova HTTP/visual deste build. Próxima frente delimitada: preparações da configuração empresarial, preservando versões, confirmações, perfis e nenhuma concessão por recuperação. Piloto/SGF preservados; aplicação integral activa.
|
||||||
|
|
||||||
28/11/2026: preparações de taxa cambial documental e pedido de cancelamento recuperadas por actor/empresa/contexto/permissões/processo/versão/competência nativa. UUIDs preservados para repetição, ignorados no aviso e renovados no sucesso; sem congelar taxas ou cancelar automaticamente. Payloads/rotas/motores preservados. Frontend15em4ficheiros, tipos/check/diff/build aprovados. Build privado `sgc-document-command-preparation-qa-20261128`, manifesto652c3190f1897155641ebc50c6e3ce0454b96244dc4f603d96ffc3e61b69b529,179entradas sem faltas, anteriores preservados; `document_command_preparation_delta_20261128` em `proofs/requisition-history.json`. Runner permanece43fc8077/provaHTTP200; não atribuir HTTP/visual novo a este build. Próxima frente delimitada: preparações de contraditório/medidas de melhoria do fornecedor e revisão da ficha, preservando versões, UUIDs de criação e ficheiros fora da memória do histórico. Piloto/SGF preservados; aplicação integral activa.
|
28/11/2026: preparações de taxa cambial documental e pedido de cancelamento recuperadas por actor/empresa/contexto/permissões/processo/versão/competência nativa. UUIDs preservados para repetição, ignorados no aviso e renovados no sucesso; sem congelar taxas ou cancelar automaticamente. Payloads/rotas/motores preservados. Frontend15em4ficheiros, tipos/check/diff/build aprovados. Build privado `sgc-document-command-preparation-qa-20261128`, manifesto652c3190f1897155641ebc50c6e3ce0454b96244dc4f603d96ffc3e61b69b529,179entradas sem faltas, anteriores preservados; `document_command_preparation_delta_20261128` em `proofs/requisition-history.json`. Runner permanece43fc8077/provaHTTP200; não atribuir HTTP/visual novo a este build. Próxima frente delimitada: preparações de contraditório/medidas de melhoria do fornecedor e revisão da ficha, preservando versões, UUIDs de criação e ficheiros fora da memória do histórico. Piloto/SGF preservados; aplicação integral activa.
|
||||||
|
|||||||
@@ -1,7 +1,44 @@
|
|||||||
{
|
{
|
||||||
"date": "2026-11-27",
|
"date": "2026-11-27",
|
||||||
"status": "pending_owner_scope_definition",
|
"status": "implemented_in_qa_functional_verification_passed_operational_activation_and_visual_pending",
|
||||||
|
"owner_private_family_decision_20261128": {
|
||||||
|
"exact_reply": "Compras, stock, finanças e configuração; bancos completos e Pessoas ficam separados",
|
||||||
|
"included": [
|
||||||
|
"purchasing",
|
||||||
|
"stock",
|
||||||
|
"finance",
|
||||||
|
"configuration"
|
||||||
|
],
|
||||||
|
"not_included": [
|
||||||
|
"complete_bank_identifiers",
|
||||||
|
"private_people_data_and_documents"
|
||||||
|
],
|
||||||
|
"effect": "Implement the dedicated private audit export for the four included families in QA. Complete bank identifiers stay masked/excluded; People private data/documents are outside this scope. No actual grants, operational export, installation or activation. Do not ask this scope again."
|
||||||
|
},
|
||||||
|
"owner_decision_20261128": {
|
||||||
|
"selected_choice": "dedicated_audit_scope",
|
||||||
|
"exact_reply": "Autoridade de auditoria própria para consultar conteúdo privado adicional",
|
||||||
|
"effect": "Implement a separate configurable audit authority; the existing metadata permission remains unchanged. No real user/profile grant, pilot installation or private data export is authorised by development.",
|
||||||
|
"remaining_configuration": "Private source families and designated audit profiles must be explicit in the company configuration; no implicit Admin/Finance/private-bank/personnel access."
|
||||||
|
},
|
||||||
"purpose": "Define the intended private-content scope of the matrix's integral audit export before extending a permission explicitly limited to metadata.",
|
"purpose": "Define the intended private-content scope of the matrix's integral audit export before extending a permission explicitly limited to metadata.",
|
||||||
|
"available_audits_explained_20261128": {
|
||||||
|
"current_event_audit": "Implemented: company event ID/date/action/actor ID, filters and complete CSV; includes events from purchasing, stock, People and configuration, but no private before/after payload or document bytes.",
|
||||||
|
"current_process_evidence": "Implemented through native process permissions: request history and cycles, frozen rules, decisions, quotations/evaluations, orders and linked documents. This is not a separate private auditor authority.",
|
||||||
|
"current_reconciliation_reports": "Implemented native operational/financial reports for purchasing, receipt/stock, budgets, invoices, confirmed external payments and explicit category attribution. No bank transfer execution or external audit certification is implied.",
|
||||||
|
"new_private_export": "Implemented in isolated synthetic QA for the four owner-selected families. Dedicated configurable per-family authority; no actual operational grants or activation."
|
||||||
|
},
|
||||||
|
"concrete_private_family_options_20261128": {
|
||||||
|
"base_purchasing_stock_finance_configuration": {
|
||||||
|
"purchasing": "Original/versioned requests, approval cycles and rules, production/maintenance origins, quotations, evaluations, awards, orders and authorised original documents.",
|
||||||
|
"stock": "Receipts, quantities, lots, quality, reservations, deliveries, returns and reversals with their native source links.",
|
||||||
|
"finance": "Budget allocations/reservations/commitments/consumption, invoices, outstanding amounts, confirmed external payments and explicit category allocations; bank identifiers remain masked unless the separate bank family is approved.",
|
||||||
|
"configuration": "Versioned business rules, profiles, memberships, delegations and recorded changes; passwords, tokens and secrets are excluded."
|
||||||
|
},
|
||||||
|
"optional_bank_identifiers": "Complete supplier bank identifiers and their independent verification history, as a separately configurable audit family.",
|
||||||
|
"optional_people_documents": "Private data and originals of the existing People/candidate/selection processes in their own work context. Does not invent formal employment contracts, payroll or the deferred formalisation workflow.",
|
||||||
|
"common_limits": "Company-configurable, separate audit permissions; no automatic Admin/Finance grant or operational installation. QA implementation/tests only, with synthetic data. Each included file is checked and covered by the export manifest; no blind AuditLog before/after dump."
|
||||||
|
},
|
||||||
"existing_authority": {
|
"existing_authority": {
|
||||||
"permission": "audit_metadata_read",
|
"permission": "audit_metadata_read",
|
||||||
"declared_scope": "Company-wide event ID, recorded date, action and user ID; no private payloads",
|
"declared_scope": "Company-wide event ID, recorded date, action and user ID; no private payloads",
|
||||||
@@ -37,5 +74,72 @@
|
|||||||
"Bypassing a native reader, broadening metadata authority silently or exporting real private data",
|
"Bypassing a native reader, broadening metadata authority silently or exporting real private data",
|
||||||
"Automatic disclosure, email, publication, destructive source cleanup or changing the two products' independence"
|
"Automatic disclosure, email, publication, destructive source cleanup or changing the two products' independence"
|
||||||
],
|
],
|
||||||
"existing_pilot_access_proposal": "audit-access-proposal.json remains a separate unapplied grant proposal; this scope question does not replace or approve it."
|
"existing_pilot_access_proposal": "audit-access-proposal.json remains a separate unapplied grant proposal; this scope question does not replace or approve it.",
|
||||||
|
"implementation_qa_20261128": {
|
||||||
|
"authority": "Four independent explicit private audit permissions; no Admin, Finance or metadata fallback; current actor, tenant, work context, expiry and maintenance revalidated.",
|
||||||
|
"source_contract": "109 fixed allowlisted tables plus curated events and explicit SupplyRecord kinds; standalone financial rows scoped to tenant/company0/unit0. Optional absent sources explicitly not_installed, records null; legacy missing columns identified. No new balance calculations.",
|
||||||
|
"package": "Immutable private ZIP and manifest; NDJSON all-page stable source snapshot; original source hashes verified; SHA256 and exact size; operation UUID bound to actor/context/scope/purpose; replay preserved; partial owned files cleaned individually.",
|
||||||
|
"excluded": [
|
||||||
|
"complete bank registers and structured bank coordinates",
|
||||||
|
"bank-specific import originals",
|
||||||
|
"private People data and originals",
|
||||||
|
"credentials",
|
||||||
|
"arbitrary event payloads",
|
||||||
|
"native storage paths"
|
||||||
|
],
|
||||||
|
"original_semantics": "Ordinary authorised business originals retain exact bytes; no claim to redact arbitrary free text or certify documents.",
|
||||||
|
"sqlite": {
|
||||||
|
"tests": 15,
|
||||||
|
"passed": 15,
|
||||||
|
"assertions": 493
|
||||||
|
},
|
||||||
|
"postgresql": {
|
||||||
|
"tests": 15,
|
||||||
|
"passed": 15,
|
||||||
|
"assertions": 493,
|
||||||
|
"database": "compras_receipts_test_3c9809d21aab",
|
||||||
|
"removed": true
|
||||||
|
},
|
||||||
|
"frontend": {
|
||||||
|
"tests": 24,
|
||||||
|
"files": 2,
|
||||||
|
"passed": 24
|
||||||
|
},
|
||||||
|
"native_http": {
|
||||||
|
"checks": 270,
|
||||||
|
"fortify_sessions": 4,
|
||||||
|
"readonly_tables_equal": 138,
|
||||||
|
"verified_assets": 20,
|
||||||
|
"audit_export_posts_including_replay": 2,
|
||||||
|
"business_commands": 0,
|
||||||
|
"zip_download_sha256_verified": true,
|
||||||
|
"isolated_database_and_role_removed": true
|
||||||
|
},
|
||||||
|
"static": "PHPStan zero errors; types, targeted frontend check, Pint and private build passed. Final Files parent containment hardening followed by SQLite13/482 and PHPStan0.",
|
||||||
|
"build": {
|
||||||
|
"path": "storage/framework/testing/sgc-private-audit-help-qa-20261128",
|
||||||
|
"manifest_sha256": "fa87e37a3626ef75d22b5248dce9a0af2bad68c967e6f99bb64bc426a68f6aaf",
|
||||||
|
"entries": 183,
|
||||||
|
"missing_files_or_imports": 0
|
||||||
|
},
|
||||||
|
"limits": "QA only; no pilot migration, actual grants, activation, SGF writes or visual/mobile/physical print acceptance. People formalisation remains deferred.",
|
||||||
|
"help_delta": {
|
||||||
|
"frontend_tests": 10,
|
||||||
|
"files": 2,
|
||||||
|
"all_operational_pages_have_specific_help": true,
|
||||||
|
"pages": [
|
||||||
|
"audit/private",
|
||||||
|
"requisitions/operational-orders",
|
||||||
|
"requisitions/urgent-stock"
|
||||||
|
],
|
||||||
|
"types_and_targeted_check": "passed"
|
||||||
|
},
|
||||||
|
"corrections_and_regressions": [
|
||||||
|
"Import document metadata kind added to the allowlist; ordinary documentary versions preserved, typed banking documents still excluded.",
|
||||||
|
"SupplyRecord JSON explicitly decoded on SQLite as well as PostgreSQL before recursive redaction; nested native paths cannot escape as raw JSON strings.",
|
||||||
|
"Same-company fully authorised auditors cannot read another creator package.",
|
||||||
|
"Output parent components reject symlinks and must remain within the owned private QA storage."
|
||||||
|
],
|
||||||
|
"pilot_manifest_sha256": "1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,21 @@
|
|||||||
{
|
{
|
||||||
|
"urgent_stock_quotation_delta_20261128": {
|
||||||
|
"owner_decisions": "Urgent quotation condition after reaching minimum stock; minimum configurable according to item nature and use. No numeric minimum quotation count was supplied: company configuration is explicit and optional.",
|
||||||
|
"source_check": "Re-read the urgent paragraph in the approved RQ-01 Word: possibility of dispensing with the second quotation; budget verification, account assignment and an independent approver remain. No additional monetary cap was invented from that paragraph.",
|
||||||
|
"implementation": "Optional lower urgent_minimum_proposals in native versioned company comparison policy, frozen only for newly created requests. UrgentQuotationBasis privately records the applicable approved item/warehouse minimum policy, use context, native free/usable stock at the threshold event, original line, actor, date and current cycle. All lines need matching evidence; otherwise ordinary quotation counts remain. Changed line/cycle/policy does not reuse evidence. Native comparison fingerprint and normal/partial/consolidated order snapshots preserve the selected evidence. Stock evidence is a historical threshold event, not an automatic stock movement, expiry or business approval.",
|
||||||
|
"authority": "Current native quotation preparation authority to record; current native process/quotation readers may consult the projected evidence without gaining recording rights. Revocation, hidden requests and closed awards remain guarded. QA-only and disabled by default.",
|
||||||
|
"verification": {
|
||||||
|
"postgres": { "tests": 6, "assertions": 139, "passed": true, "normal_and_partial_issue": true, "independent_evaluators": 2, "eligible_suppliers": 1, "ordinary_minimum": 3, "explicit_urgent_minimum": 1, "synthetic_normal_order_mzn": 100, "synthetic_partial_order_mzn": 40, "database_removed": "compras_receipts_test_61471f295692" },
|
||||||
|
"sqlite": { "tests": 6, "passed": 5, "skipped": 1, "assertions": 122, "skip_reason": "Published legacy budget runtime lacks partial-order capability; actual partial issuance passed with the pinned private composition on PostgreSQL." },
|
||||||
|
"frontend": { "tests": 46, "files": 4, "passed": true },
|
||||||
|
"typescript": "passed", "phpstan_errors": 0, "frontend_format_lint": "9 files passed", "pint": "passed",
|
||||||
|
"private_build": "storage/framework/testing/sgc-urgent-stock-qa-20261128", "manifest_sha256": "b712f509fb0ff1179fc9d007abbef0a3c2d5f97f575b558cbc49f47d06dc9894", "manifest_entries": 182, "missing_assets_or_imports": 0,
|
||||||
|
"native_readonly_http": { "checks": 234, "prior_same_asset_run_checks": 233, "fortify_sessions": 3, "verified_page_assets": 19, "unchanged_tables_in_read_window": 137, "operational_order_and_urgent_stock_pages": true, "requester_refusals": true, "metadata_order_register_refused": true, "business_commands_sent": 0, "owned_database_and_role_removed": true, "browser_visual_acceptance": false, "log": "storage/logs/operational-urgent-http-final-20261128.log" },
|
||||||
|
"operational_access_regression": { "sqlite_tests": 1, "sqlite_assertions": 24, "postgres_tests": 1, "postgres_assertions": 24, "passed": true, "database_removed": "compras_receipts_test_26a90e083ce1", "correction": "Own new register originally accepted any nonempty permission list. Explicit register authority now excludes metadata-only actors. Authorised process readers receive only linked order origins, never unrelated register rows. PHPStan passed again without suppressions." },
|
||||||
|
"own_test_corrections": "Used the actual receiptPayload helper and the existing native 404 for a warehouse actor without process visibility; an authorised Finance reader separately proved 403 for recording and read-only evidence access. Added the omitted explicit normal/partial dataset. No application access was relaxed to satisfy those assertions."
|
||||||
|
},
|
||||||
|
"limits": "Pilot/SGF, real accounts/grants and operational deployment untouched. New HTTP run is read-only and does not replace the separate native financial command journey or physical browser/print acceptance. Metadata audit scope unchanged; private export scope remains a separate owner choice."
|
||||||
|
},
|
||||||
"date": "2026-11-27",
|
"date": "2026-11-27",
|
||||||
"status": "implemented_in_isolated_qa_integration_and_acceptance_in_progress",
|
"status": "implemented_in_isolated_qa_integration_and_acceptance_in_progress",
|
||||||
"authorization": "requisition-expiry-contract-authorization.json",
|
"authorization": "requisition-expiry-contract-authorization.json",
|
||||||
|
|||||||
@@ -847,5 +847,80 @@
|
|||||||
},
|
},
|
||||||
"native_http_runner": "Still pinned to equipment candidate43fc8077 with dated200 read checks. Native supplier workflow tests above are a separate proof; no new HTTP/browser claim for this build.",
|
"native_http_runner": "Still pinned to equipment candidate43fc8077 with dated200 read checks. Native supplier workflow tests above are a separate proof; no new HTTP/browser claim for this build.",
|
||||||
"remaining": "Physical browser multi-form post/back/forward/context/mobile/print, company configuration and other approved forms, and existing concrete owner decisions remain open. No policy publication, supplier command in operational data, bank/SGF action or full application acceptance."
|
"remaining": "Physical browser multi-form post/back/forward/context/mobile/print, company configuration and other approved forms, and existing concrete owner decisions remain open. No policy publication, supplier command in operational data, bank/SGF action or full application acceptance."
|
||||||
|
},
|
||||||
|
"company_preparation_delta_20261128": {
|
||||||
|
"status": "verified in isolated synthetic QA; physical and operational acceptance pending",
|
||||||
|
"scope": [
|
||||||
|
"Company bootstrap and legacy team/departments/cost centres",
|
||||||
|
"Version-bound profile creation/edit and person-bound access assignment",
|
||||||
|
"Company activation, approval/value/tax/comparison configuration",
|
||||||
|
"Company details/banks/establishments, licensed work contexts, local intelligence and draft AI plan",
|
||||||
|
"Approval plan revision and original company geography reference"
|
||||||
|
],
|
||||||
|
"identity": "Actor/company/work context/permissions, ready/active/configuration version and source-specific profile/person/plan/reference. Selected profile editor separate from new profile. Recovered input never posts, assigns, activates or publishes by itself. Native payloads, authority, version checks and confirmations preserved.",
|
||||||
|
"credentials": "Installed Inertia dontRemember excludes password and confirmation fields. Explicit successful resets remember metadata only. Missing excluded fields are normalised to empty controls/defaults for semantic dirty comparison, with regression tests; no password or File object added to remembered history.",
|
||||||
|
"geography_correction": "Company location is keyed by the exact original reference; removed the effect that refreshed expected_reference while retaining an older edited reference. Native original-reference concurrency contract preserved.",
|
||||||
|
"frontend": {
|
||||||
|
"tests": 38,
|
||||||
|
"files": 7,
|
||||||
|
"passed": true,
|
||||||
|
"tests_files": [
|
||||||
|
"tests/frontend/company-preparation.test.tsx",
|
||||||
|
"tests/frontend/company-policy-preparation.test.tsx"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"native": {
|
||||||
|
"tests": 71,
|
||||||
|
"assertions": 764,
|
||||||
|
"passed": true,
|
||||||
|
"log": "storage/logs/company-preparation-native-sqlite-20261128.log"
|
||||||
|
},
|
||||||
|
"types_phpstan_format_lint_diff": true,
|
||||||
|
"build": {
|
||||||
|
"root": "storage/framework/testing/sgc-company-preparation-final-qa-20261128",
|
||||||
|
"manifest_sha256": "df4e07d422af16897581371283d9730f41076ad2888d1e4911bdd7cadbb92c5f",
|
||||||
|
"entries": 180,
|
||||||
|
"missing_files_or_imports": 0,
|
||||||
|
"log": "storage/logs/company-preparation-final-build-20261128.log",
|
||||||
|
"previous_build_preserved": true
|
||||||
|
},
|
||||||
|
"native_http": {
|
||||||
|
"private_native_http_verified": true,
|
||||||
|
"checks": 213,
|
||||||
|
"fortify_sessions": 3,
|
||||||
|
"missing_csrf_refused": true,
|
||||||
|
"stale_inertia_version_refused": true,
|
||||||
|
"supply_views": 9,
|
||||||
|
"purchase_control_views": 2,
|
||||||
|
"requester_scope_verified": true,
|
||||||
|
"encrypted_history_verified": true,
|
||||||
|
"budget_view_verified": true,
|
||||||
|
"conflict_index_verified": true,
|
||||||
|
"stock_views_verified": 2,
|
||||||
|
"equipment_view_verified": true,
|
||||||
|
"investment_view_verified": true,
|
||||||
|
"company_configuration_verified": true,
|
||||||
|
"metadata_scope_isolation_verified": true,
|
||||||
|
"readonly_tables_equal": 136,
|
||||||
|
"private_asset_verified": true,
|
||||||
|
"private_assets_verified": 17,
|
||||||
|
"business_commands_sent": 0,
|
||||||
|
"browser_visual_acceptance": false,
|
||||||
|
"private_manifest_sha256": "df4e07d422af16897581371283d9730f41076ad2888d1e4911bdd7cadbb92c5f"
|
||||||
|
},
|
||||||
|
"http_log": "storage/logs/company-preparation-http-final-20261128.log",
|
||||||
|
"server_database_role_cluster_private_root_removed": true,
|
||||||
|
"own_harness_correction": {
|
||||||
|
"initial_log": "storage/logs/company-preparation-http-20261128.log",
|
||||||
|
"failure": "Node 24 Undici Parser.finish asserted !paused on a closed response. Checker status/header-only requests and readiness probes left transport bodies unread.",
|
||||||
|
"fix": "Owned HTTP client now drains the original network response and returns a readable clone; readiness responses are drained too. No application access rule or writer changed.",
|
||||||
|
"regression": "node --test tests/Support/native-inertia-client.test.mjs",
|
||||||
|
"passed_tests": 1,
|
||||||
|
"regression_scope": "2 MiB close-delimited response with neither Content-Length nor Transfer-Encoding; unread returned bodies, readable JSON, URL, cookies, 204 and manual redirects preserved, foreign destination refused.",
|
||||||
|
"aborted_runtime": "rq01-ledger-qa-c218afc04aae",
|
||||||
|
"recovery": "Verified exact cluster name/data directory and allowed database list with the private owner credential, then removed only that database/role/cluster/root. No secret printed. Older b3ba8de533e2 root untouched; final rerun cleaned normally."
|
||||||
|
},
|
||||||
|
"pilot_manifest_unchanged": "1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e",
|
||||||
|
"remaining": "Physical multi-form post/back/forward/context/mobile/print, remaining approved forms and concrete owner decisions still open. No operational account/grant/policy/schema/install/SGF change or whole application acceptance."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,24 @@
|
|||||||
{
|
{
|
||||||
|
"operational_orders_and_stock_use_delta_20261128": {
|
||||||
|
"owner_decision": "Own order register; origin at utilisation sites when the application covers them, otherwise the procurement agent records the order. Production responsibility and workshop responsibility remain distinct. Stock minimum is configurable by item nature and use.",
|
||||||
|
"implementation": "OperationalOrders, private register/workspace, company-selected origin mode, separate production_order_prepare and maintenance_order_prepare capabilities without grants. Immutable original orders and versioned per-line links; source preserved in ordinary and partial/consolidated native order snapshots, screen and print. Guarded QA-only, disabled by default, using existing supply_records without schema extension.",
|
||||||
|
"stock_use": "Existing item/warehouse minimum remains company-defined. Optional usage_context explains nature/use in the versioned stock policy; no universal value or automatic calculation was imposed.",
|
||||||
|
"verification": {
|
||||||
|
"sqlite_register_and_supply": { "tests": 12, "assertions": 136, "passed": true },
|
||||||
|
"postgres_register_and_native_orders": { "tests": 6, "assertions": 115, "passed": true, "partial_issue_included": true, "database_removed": "compras_receipts_test_f2d7b42d73c1" },
|
||||||
|
"postgres_stock_use": { "tests": 1, "assertions": 5, "passed": true, "database_removed": "compras_receipts_test_b3d1427bd9f8" },
|
||||||
|
"frontend": { "tests": 36, "files": 3, "passed": true },
|
||||||
|
"phpstan_errors": 0,
|
||||||
|
"format_and_lint": "9 frontend files passed; PHP Pint passed",
|
||||||
|
"private_build": "storage/framework/testing/sgc-operational-orders-qa-20261128",
|
||||||
|
"manifest_sha256": "6b0126100bf6ad8ee88565c580c87ae724e259505f8bbb3c395312fc07cf9564",
|
||||||
|
"manifest_entries": 181,
|
||||||
|
"missing_assets_or_imports": 0,
|
||||||
|
"pilot_manifest_unchanged": "1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e",
|
||||||
|
"own_error_corrected": "Initial internal policy kind exceeded the existing varchar(20) contract. Renamed own new kinds to op_order_policy/op_order/op_order_link, added length regression and required successful HTTP redirects. Failed PG fixture database removed; no schema weakening."
|
||||||
|
},
|
||||||
|
"limits": "No operational installation, grants, activation, SGF writes or new native HTTP/browser/physical acceptance. This minimum-policy delivery alone does not implement the urgent quotation reduction. Current HTTP runner remains pinned to the earlier company candidate."
|
||||||
|
},
|
||||||
"date": "2026-11-27",
|
"date": "2026-11-27",
|
||||||
"status": "implemented_in_isolated_qa_native_visual_and_operational_acceptance_pending",
|
"status": "implemented_in_isolated_qa_native_visual_and_operational_acceptance_pending",
|
||||||
"decision": "rq01-account-origin-decision.json",
|
"decision": "rq01-account-origin-decision.json",
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ export type ComparisonPolicy = {
|
|||||||
configured: boolean;
|
configured: boolean;
|
||||||
minimum_proposals: number;
|
minimum_proposals: number;
|
||||||
minimum_evaluators: number;
|
minimum_evaluators: number;
|
||||||
|
urgent_minimum_proposals?: number;
|
||||||
|
normal_minimum_proposals?: number;
|
||||||
weights: Record<
|
weights: Record<
|
||||||
'price' | 'quality' | 'delivery' | 'history' | 'payment',
|
'price' | 'quality' | 'delivery' | 'history' | 'payment',
|
||||||
number
|
number
|
||||||
@@ -32,6 +34,21 @@ export function ComparisonPolicySummary({
|
|||||||
fornecedores distintos e {policy.minimum_evaluators} avaliações
|
fornecedores distintos e {policy.minimum_evaluators} avaliações
|
||||||
independentes por proposta.
|
independentes por proposta.
|
||||||
</p>
|
</p>
|
||||||
|
{policy.normal_minimum_proposals !== undefined ? (
|
||||||
|
<p>
|
||||||
|
Redução urgente aplicada após conferência documentada do
|
||||||
|
stock mínimo. O mínimo normal é{' '}
|
||||||
|
{policy.normal_minimum_proposals}; as avaliações e
|
||||||
|
aprovações mantêm-se.
|
||||||
|
</p>
|
||||||
|
) : policy.urgent_minimum_proposals !== undefined ? (
|
||||||
|
<p>
|
||||||
|
A empresa permite reduzir para{' '}
|
||||||
|
{policy.urgent_minimum_proposals} propostas numa urgência
|
||||||
|
justificada, após documentar o stock mínimo aplicável a
|
||||||
|
todas as linhas.
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
<p>
|
<p>
|
||||||
{Object.entries(comparisonCriteria)
|
{Object.entries(comparisonCriteria)
|
||||||
.map(
|
.map(
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import { Panel } from '@/components/procurement';
|
||||||
|
|
||||||
|
export type FrozenOperationalOrder = {
|
||||||
|
id: number;
|
||||||
|
snapshot: {
|
||||||
|
item: { description: string };
|
||||||
|
source: {
|
||||||
|
data: {
|
||||||
|
type: string;
|
||||||
|
reference: string;
|
||||||
|
utilisation_location: string;
|
||||||
|
description: string;
|
||||||
|
};
|
||||||
|
snapshot: {
|
||||||
|
author: { name: string };
|
||||||
|
department: { name: string };
|
||||||
|
policy: { data: { mode: string } };
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
export default function OperationalOrderSummary({
|
||||||
|
records,
|
||||||
|
}: {
|
||||||
|
records?: Record<number, FrozenOperationalOrder>;
|
||||||
|
}) {
|
||||||
|
const rows = Object.values(records ?? {});
|
||||||
|
if (rows.length === 0) return null;
|
||||||
|
return (
|
||||||
|
<Panel
|
||||||
|
title="Ordens de origem"
|
||||||
|
description="Produção e manutenção: documentos preservados na emissão desta ordem de compra."
|
||||||
|
>
|
||||||
|
<ul className="space-y-4">
|
||||||
|
{rows.map((record) => {
|
||||||
|
const source = record.snapshot.source;
|
||||||
|
return (
|
||||||
|
<li key={record.id}>
|
||||||
|
<p className="font-semibold">
|
||||||
|
{record.snapshot.item.description} ·{' '}
|
||||||
|
{source.data.reference} ·{' '}
|
||||||
|
{source.data.type === 'production'
|
||||||
|
? 'Produção'
|
||||||
|
: 'Manutenção'}
|
||||||
|
</p>
|
||||||
|
<p className="text-sm">
|
||||||
|
{source.snapshot.department.name} ·{' '}
|
||||||
|
{source.data.utilisation_location} ·{' '}
|
||||||
|
{source.snapshot.author.name} ·{' '}
|
||||||
|
{source.snapshot.policy.data.mode ===
|
||||||
|
'utilisation'
|
||||||
|
? 'Origem no local de utilização'
|
||||||
|
: 'Registada pelo procurement'}
|
||||||
|
</p>
|
||||||
|
<p className="mt-2 text-sm whitespace-pre-wrap">
|
||||||
|
{source.data.description}
|
||||||
|
</p>
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
</Panel>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,8 +1,12 @@
|
|||||||
import { Link } from '@inertiajs/react';
|
import { Link } from '@inertiajs/react';
|
||||||
import { Panel } from '@/components/procurement';
|
import { Panel } from '@/components/procurement';
|
||||||
import { money, roleLabels } from '@/types/procurement';
|
import { money, roleLabels } from '@/types/procurement';
|
||||||
|
import UrgentQuotationSummary, {
|
||||||
|
type FrozenUrgentBasis,
|
||||||
|
} from '@/components/urgent-quotation-summary';
|
||||||
|
|
||||||
export type OrderPartFrame = {
|
export type OrderPartFrame = {
|
||||||
|
urgent_quotation_basis?: FrozenUrgentBasis[];
|
||||||
requisition: { id: number; number: string };
|
requisition: { id: number; number: string };
|
||||||
department: { name: string };
|
department: { name: string };
|
||||||
cost_center: { code: string; name: string };
|
cost_center: { code: string; name: string };
|
||||||
@@ -66,6 +70,9 @@ export function OrderPartsSummary({ sources }: { sources: OrderPartFrame[] }) {
|
|||||||
{source.requisition.number}
|
{source.requisition.number}
|
||||||
</Link>
|
</Link>
|
||||||
</h3>
|
</h3>
|
||||||
|
<UrgentQuotationSummary
|
||||||
|
records={source.urgent_quotation_basis}
|
||||||
|
/>
|
||||||
<p className="break-words">
|
<p className="break-words">
|
||||||
{source.department.name} · {source.cost_center.code}{' '}
|
{source.department.name} · {source.cost_center.code}{' '}
|
||||||
· {source.cost_center.name}
|
· {source.cost_center.name}
|
||||||
|
|||||||
@@ -53,6 +53,8 @@ export function SgcWorkspaceShell({ children }: { children: ReactNode }) {
|
|||||||
page.props.payablesAvailable === true,
|
page.props.payablesAvailable === true,
|
||||||
undefined,
|
undefined,
|
||||||
page.props.orderCancellationAvailable === true,
|
page.props.orderCancellationAvailable === true,
|
||||||
|
page.props.operationalOrdersAvailable === true,
|
||||||
|
page.props.privateAuditAvailable === true,
|
||||||
).flatMap((group) => group.entries.map((entry) => entry.id)),
|
).flatMap((group) => group.entries.map((entry) => entry.id)),
|
||||||
);
|
);
|
||||||
const groups = procurementNavigation(
|
const groups = procurementNavigation(
|
||||||
@@ -60,6 +62,8 @@ export function SgcWorkspaceShell({ children }: { children: ReactNode }) {
|
|||||||
page.props.payablesAvailable === true,
|
page.props.payablesAvailable === true,
|
||||||
publicNavigation?.paths,
|
publicNavigation?.paths,
|
||||||
page.props.orderCancellationAvailable === true,
|
page.props.orderCancellationAvailable === true,
|
||||||
|
page.props.operationalOrdersAvailable === true,
|
||||||
|
page.props.privateAuditAvailable === true,
|
||||||
)
|
)
|
||||||
.map((group) => ({
|
.map((group) => ({
|
||||||
...group,
|
...group,
|
||||||
|
|||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import { Panel } from '@/components/procurement';
|
||||||
|
import { date } from '@/types/procurement';
|
||||||
|
|
||||||
|
export type FrozenUrgentBasis = {
|
||||||
|
id: number;
|
||||||
|
created_at: string;
|
||||||
|
reason: string;
|
||||||
|
snapshot: {
|
||||||
|
item: { description: string };
|
||||||
|
author: { name: string };
|
||||||
|
stock_policy: {
|
||||||
|
minimum_stock_milli: number;
|
||||||
|
usage_context: string | null;
|
||||||
|
warehouse: { name: string };
|
||||||
|
};
|
||||||
|
availability: { free_milli: number | null };
|
||||||
|
};
|
||||||
|
};
|
||||||
|
export default function UrgentQuotationSummary({
|
||||||
|
records,
|
||||||
|
}: {
|
||||||
|
records?: FrozenUrgentBasis[];
|
||||||
|
}) {
|
||||||
|
if (!records?.length) return null;
|
||||||
|
return (
|
||||||
|
<Panel
|
||||||
|
title="Fundamento da redução urgente de cotações"
|
||||||
|
description="Conferências preservadas do momento em que o mínimo parametrizado foi atingido. Orçamento e aprovações mantêm-se."
|
||||||
|
>
|
||||||
|
<ul className="space-y-3">
|
||||||
|
{records.map((record) => (
|
||||||
|
<li key={record.id} className="text-sm">
|
||||||
|
<p className="font-semibold">
|
||||||
|
{record.snapshot.item.description} ·{' '}
|
||||||
|
{record.snapshot.stock_policy.warehouse.name}
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
Mínimo:{' '}
|
||||||
|
{record.snapshot.stock_policy.minimum_stock_milli /
|
||||||
|
1000}
|
||||||
|
; stock livre no momento:{' '}
|
||||||
|
{record.snapshot.availability.free_milli === null
|
||||||
|
? 'Indeterminado'
|
||||||
|
: record.snapshot.availability.free_milli /
|
||||||
|
1000}
|
||||||
|
.
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
{record.snapshot.author.name} ·{' '}
|
||||||
|
{date(record.created_at)}
|
||||||
|
</p>
|
||||||
|
{record.snapshot.stock_policy.usage_context && (
|
||||||
|
<p>{record.snapshot.stock_policy.usage_context}</p>
|
||||||
|
)}
|
||||||
|
<p className="whitespace-pre-wrap">{record.reason}</p>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</Panel>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -37,6 +37,61 @@ function topic(
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const journeyHelp: JourneyHelp[] = [
|
export const journeyHelp: JourneyHelp[] = [
|
||||||
|
topic(
|
||||||
|
'private-audit',
|
||||||
|
'Preparar uma exportação privada de auditoria',
|
||||||
|
['audit/private'],
|
||||||
|
'Conservar um pacote verificável das famílias autorizadas da empresa.',
|
||||||
|
[
|
||||||
|
'Seleccione Compras, stock, finanças ou configuração entre as famílias que pode consultar e indique a finalidade quando necessário.',
|
||||||
|
'Prepare o pacote por acção explícita. Recuperar um formulário não inicia a exportação.',
|
||||||
|
'Descarregue o ZIP na lista dos seus pacotes. Confira no manifesto as fontes, contagens, hashes e eventuais colunas ou componentes indisponíveis.',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'A autoridade privada é própria: Administração, Finanças ou leitura de metadados não a substituem.',
|
||||||
|
'Bancos completos, documentos bancários específicos, conteúdo privado de Pessoas e credenciais ficam separados.',
|
||||||
|
'Fonte não instalada não significa saldo ou contagem zero. O pacote conserva factos registados, sem recalcular saldos.',
|
||||||
|
'Os originais incluídos conservam os bytes verificados; a exportação não certifica os documentos nem altera os processos.',
|
||||||
|
],
|
||||||
|
'Se a operação for interrompida, confira primeiro os seus pacotes; repetir a mesma preparação conserva o pacote original. Um ficheiro alterado ou acesso revogado impede a descarga; não substitua o original para contornar a recusa.',
|
||||||
|
'Conserve o ZIP e o manifesto no destino autorizado para a auditoria.',
|
||||||
|
),
|
||||||
|
topic(
|
||||||
|
'operational-orders',
|
||||||
|
'Registar ordens de produção e manutenção',
|
||||||
|
['requisitions/operational-orders'],
|
||||||
|
'Identificar a origem operacional das linhas da requisição e preservar a ordem utilizada.',
|
||||||
|
[
|
||||||
|
'Confira se a empresa definiu registo nos locais de utilização ou pelo procurement.',
|
||||||
|
'Registe tipo, referência, departamento, local, trabalho e fundamento com a competência atribuída.',
|
||||||
|
'Na requisição em rascunho, ligue cada linha aplicável à ordem correspondente e confira a origem antes de submeter.',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'No local de utilização, as competências de produção e manutenção são atribuídas aos respectivos responsáveis; o modo procurement usa o agente autorizado.',
|
||||||
|
'Administração pode configurar sem obter por isso competência para criar ordens.',
|
||||||
|
'A ligação não substitui orçamento, aprovação ou recepção. Ordens emitidas conservam a origem usada, mesmo após nova configuração.',
|
||||||
|
],
|
||||||
|
'Se não houver ordens elegíveis, confira o modo, a competência, o departamento e o tipo exigido pela linha. Uma alteração posterior da linha exige conferir novamente a ligação.',
|
||||||
|
'Volte à requisição e confirme as origens antes da submissão.',
|
||||||
|
),
|
||||||
|
topic(
|
||||||
|
'urgent-stock',
|
||||||
|
'Conferir o stock mínimo de uma requisição urgente',
|
||||||
|
['requisitions/urgent-stock'],
|
||||||
|
'Documentar quando o mínimo parametrizado foi atingido para aplicar a regra urgente preservada no pedido.',
|
||||||
|
[
|
||||||
|
'Confira a justificação urgente e a regra de comparação preservada na requisição.',
|
||||||
|
'Para cada linha, escolha a política aprovada do artigo e armazém, considerando a natureza e utilização documentadas.',
|
||||||
|
'Registe a conferência com fundamento. O servidor verifica a disponibilidade nativa e preserva autor, data, política, linha e ciclo.',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'Não existe mínimo universal: a empresa parametriza o valor por artigo e local.',
|
||||||
|
'A redução só se aplica com regra urgente expressa e evidência compatível para todas as linhas. Sem essa cobertura mantém-se o número normal.',
|
||||||
|
'A conferência não movimenta stock nem dispensa contas, orçamento, avaliações ou aprovações independentes.',
|
||||||
|
],
|
||||||
|
'Se o mínimo não tiver sido atingido ou a linha, regra ou ciclo tiver mudado, confira a origem e mantenha o percurso normal enquanto não existir evidência válida.',
|
||||||
|
'Volte às cotações para conferir a comparação e prosseguir pelas aprovações existentes.',
|
||||||
|
),
|
||||||
topic(
|
topic(
|
||||||
'urgent-review-policy',
|
'urgent-review-policy',
|
||||||
'Designar a revisão posterior das urgências',
|
'Designar a revisão posterior das urgências',
|
||||||
|
|||||||
@@ -33,6 +33,8 @@ export function procurementNavigation(
|
|||||||
payables: boolean,
|
payables: boolean,
|
||||||
publicPaths?: string[],
|
publicPaths?: string[],
|
||||||
orderCancellation = false,
|
orderCancellation = false,
|
||||||
|
operationalOrders = false,
|
||||||
|
privateAudit = false,
|
||||||
): ProcurementGroup[] {
|
): ProcurementGroup[] {
|
||||||
const groups: ProcurementGroup[] = [
|
const groups: ProcurementGroup[] = [
|
||||||
{
|
{
|
||||||
@@ -71,6 +73,18 @@ export function procurementNavigation(
|
|||||||
path: '/requisicoes?view=all',
|
path: '/requisicoes?view=all',
|
||||||
},
|
},
|
||||||
{ id: 'planning', label: 'Planeamento', path: '/planeamento' },
|
{ id: 'planning', label: 'Planeamento', path: '/planeamento' },
|
||||||
|
{
|
||||||
|
id: 'operational_orders',
|
||||||
|
label: 'Ordens de produção e manutenção',
|
||||||
|
path: '/ordens-operacionais',
|
||||||
|
roles: [
|
||||||
|
'admin',
|
||||||
|
'procurement',
|
||||||
|
'requester',
|
||||||
|
'production_order_prepare',
|
||||||
|
'maintenance_order_prepare',
|
||||||
|
],
|
||||||
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -501,6 +515,17 @@ export function procurementNavigation(
|
|||||||
path: '/auditoria/eventos',
|
path: '/auditoria/eventos',
|
||||||
roles: ['audit_metadata_read'],
|
roles: ['audit_metadata_read'],
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
id: 'audit_private',
|
||||||
|
label: 'Exportação privada',
|
||||||
|
path: '/auditoria/privada',
|
||||||
|
roles: [
|
||||||
|
'audit_private_purchasing_read',
|
||||||
|
'audit_private_stock_read',
|
||||||
|
'audit_private_finance_read',
|
||||||
|
'audit_private_configuration_read',
|
||||||
|
],
|
||||||
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -568,6 +593,9 @@ export function procurementNavigation(
|
|||||||
)
|
)
|
||||||
: (entry.id !== 'issued_order_cancellations' ||
|
: (entry.id !== 'issued_order_cancellations' ||
|
||||||
orderCancellation) &&
|
orderCancellation) &&
|
||||||
|
(entry.id !== 'audit_private' || privateAudit) &&
|
||||||
|
(entry.id !== 'operational_orders' ||
|
||||||
|
operationalOrders) &&
|
||||||
(entry.id !== 'new_request' ||
|
(entry.id !== 'new_request' ||
|
||||||
!Array.isArray(role) ||
|
!Array.isArray(role) ||
|
||||||
role.includes('requester')) &&
|
role.includes('requester')) &&
|
||||||
|
|||||||
@@ -0,0 +1,188 @@
|
|||||||
|
import { Head, Link, useForm } from '@inertiajs/react';
|
||||||
|
import {
|
||||||
|
Panel,
|
||||||
|
PageTitle,
|
||||||
|
FormErrors,
|
||||||
|
controlClass,
|
||||||
|
} from '@/components/procurement';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { useProcurementPreparationIdentity } from '@/hooks/use-procurement-preparation-identity';
|
||||||
|
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
families: { key: string; label: string }[];
|
||||||
|
exports: {
|
||||||
|
data: {
|
||||||
|
id: number;
|
||||||
|
families: string[];
|
||||||
|
created_at: string;
|
||||||
|
size: number;
|
||||||
|
sha256: string;
|
||||||
|
download_url: string;
|
||||||
|
}[];
|
||||||
|
prev_page_url: string | null;
|
||||||
|
next_page_url: string | null;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function PrivateAudit(props: Props) {
|
||||||
|
const identity = useProcurementPreparationIdentity(
|
||||||
|
`private-audit:${props.families.map((family) => family.key).join(',')}`,
|
||||||
|
);
|
||||||
|
const form = useForm(identity, {
|
||||||
|
operation_key: crypto.randomUUID(),
|
||||||
|
families: [] as string[],
|
||||||
|
purpose: '',
|
||||||
|
});
|
||||||
|
const formRef = usePreparationDirty(form.isDirty);
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Head title="Exportação privada de auditoria" />
|
||||||
|
<div className="mx-auto flex w-full max-w-5xl flex-col gap-6 p-5 lg:p-8">
|
||||||
|
<PageTitle
|
||||||
|
eyebrow="Auditoria"
|
||||||
|
title="Exportação privada de auditoria"
|
||||||
|
description="Seleccione os dados abrangidos pela sua autoridade. O pacote inclui um manifesto com fontes, contagens e hashes e os originais verificáveis aplicáveis."
|
||||||
|
/>
|
||||||
|
<Panel title="Preparar pacote">
|
||||||
|
<p className="mb-4 text-sm">
|
||||||
|
Bancos completos, documentos bancários específicos,
|
||||||
|
conteúdo privado de Pessoas e credenciais ficam fora
|
||||||
|
deste pacote. Os dados representam os registos
|
||||||
|
existentes; não recalculam saldos nem certificam os
|
||||||
|
documentos.
|
||||||
|
</p>
|
||||||
|
<form
|
||||||
|
ref={formRef}
|
||||||
|
className="space-y-4"
|
||||||
|
onSubmit={(event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
form.post('/auditoria/privada', {
|
||||||
|
onSuccess: () => {
|
||||||
|
const clean = {
|
||||||
|
operation_key: crypto.randomUUID(),
|
||||||
|
families: [] as string[],
|
||||||
|
purpose: '',
|
||||||
|
};
|
||||||
|
form.setDefaults(clean);
|
||||||
|
form.setData(clean);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<FormErrors errors={form.errors} />
|
||||||
|
<fieldset className="space-y-2">
|
||||||
|
<legend className="font-medium">Conteúdo</legend>
|
||||||
|
{props.families.map((family) => (
|
||||||
|
<label
|
||||||
|
key={family.key}
|
||||||
|
className="flex items-center gap-2"
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={form.data.families.includes(
|
||||||
|
family.key,
|
||||||
|
)}
|
||||||
|
onChange={(event) =>
|
||||||
|
form.setData(
|
||||||
|
'families',
|
||||||
|
event.target.checked
|
||||||
|
? [
|
||||||
|
...form.data.families,
|
||||||
|
family.key,
|
||||||
|
]
|
||||||
|
: form.data.families.filter(
|
||||||
|
(key) =>
|
||||||
|
key !==
|
||||||
|
family.key,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
{family.label}
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</fieldset>
|
||||||
|
<label className="block">
|
||||||
|
Finalidade (opcional)
|
||||||
|
<textarea
|
||||||
|
className={controlClass}
|
||||||
|
maxLength={500}
|
||||||
|
value={form.data.purpose}
|
||||||
|
onChange={(event) =>
|
||||||
|
form.setData('purpose', event.target.value)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
disabled={
|
||||||
|
form.processing ||
|
||||||
|
form.data.families.length === 0
|
||||||
|
}
|
||||||
|
>
|
||||||
|
Preparar exportação privada
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
</Panel>
|
||||||
|
<Panel title="Os seus pacotes preparados">
|
||||||
|
{props.exports.data.length === 0 && (
|
||||||
|
<p>Ainda não preparou um pacote neste contexto.</p>
|
||||||
|
)}
|
||||||
|
<ul className="space-y-4">
|
||||||
|
{props.exports.data.map((item) => (
|
||||||
|
<li
|
||||||
|
key={item.id}
|
||||||
|
className="space-y-1 border-b pb-4"
|
||||||
|
>
|
||||||
|
<p>
|
||||||
|
Pacote {item.id} —{' '}
|
||||||
|
{new Date(item.created_at).toLocaleString(
|
||||||
|
'pt-MZ',
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
<p className="text-sm">
|
||||||
|
{item.families
|
||||||
|
.map(
|
||||||
|
(key) =>
|
||||||
|
props.families.find(
|
||||||
|
(family) =>
|
||||||
|
family.key === key,
|
||||||
|
)?.label ?? key,
|
||||||
|
)
|
||||||
|
.join('; ')}{' '}
|
||||||
|
· {item.size.toLocaleString('pt-MZ')} bytes
|
||||||
|
</p>
|
||||||
|
<p className="font-mono text-xs break-all">
|
||||||
|
SHA-256: {item.sha256}
|
||||||
|
</p>
|
||||||
|
<a
|
||||||
|
className="underline"
|
||||||
|
href={item.download_url}
|
||||||
|
>
|
||||||
|
Descarregar ZIP verificado
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
<div className="mt-4 flex gap-4">
|
||||||
|
{props.exports.prev_page_url && (
|
||||||
|
<Link href={props.exports.prev_page_url}>
|
||||||
|
Anterior
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
{props.exports.next_page_url && (
|
||||||
|
<Link href={props.exports.next_page_url}>
|
||||||
|
Seguinte
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</Panel>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
PrivateAudit.layout = {
|
||||||
|
breadcrumbs: [{ title: 'Auditoria privada', href: '/auditoria/privada' }],
|
||||||
|
};
|
||||||
@@ -219,6 +219,7 @@ function ParameterFields({
|
|||||||
notice,
|
notice,
|
||||||
companyRules,
|
companyRules,
|
||||||
comparisonPolicy,
|
comparisonPolicy,
|
||||||
|
urgentQuotationReady = false,
|
||||||
intelligencePolicy,
|
intelligencePolicy,
|
||||||
intelligenceReady = false,
|
intelligenceReady = false,
|
||||||
aiPlan,
|
aiPlan,
|
||||||
@@ -239,6 +240,7 @@ function ParameterFields({
|
|||||||
geographyEnabled?: boolean;
|
geographyEnabled?: boolean;
|
||||||
geography?: GeographyDescription;
|
geography?: GeographyDescription;
|
||||||
comparisonPolicy: ComparisonPolicy;
|
comparisonPolicy: ComparisonPolicy;
|
||||||
|
urgentQuotationReady?: boolean;
|
||||||
intelligencePolicy?: IntelligencePolicy;
|
intelligencePolicy?: IntelligencePolicy;
|
||||||
intelligenceReady?: boolean;
|
intelligenceReady?: boolean;
|
||||||
aiPlan?: AiPlan;
|
aiPlan?: AiPlan;
|
||||||
@@ -370,14 +372,16 @@ function ParameterFields({
|
|||||||
version,
|
version,
|
||||||
minimum_proposals: comparisonPolicy.minimum_proposals,
|
minimum_proposals: comparisonPolicy.minimum_proposals,
|
||||||
minimum_evaluators: comparisonPolicy.minimum_evaluators,
|
minimum_evaluators: comparisonPolicy.minimum_evaluators,
|
||||||
|
urgent_minimum_proposals:
|
||||||
|
comparisonPolicy.urgent_minimum_proposals?.toString() ?? '',
|
||||||
weights: { ...comparisonPolicy.weights },
|
weights: { ...comparisonPolicy.weights },
|
||||||
reason: '',
|
reason: '',
|
||||||
};
|
};
|
||||||
const comparison = useForm(`${identity}:comparison`, initialComparison);
|
const comparison = useForm(`${identity}:comparison`, initialComparison);
|
||||||
const comparisonDirty = hasPreparationChanges(
|
const comparisonDirty = hasPreparationChanges(initialComparison, {
|
||||||
initialComparison,
|
...initialComparison,
|
||||||
comparison.data,
|
...comparison.data,
|
||||||
);
|
});
|
||||||
const comparisonRef = usePreparationDirty(comparisonDirty);
|
const comparisonRef = usePreparationDirty(comparisonDirty);
|
||||||
const clearComparison = () => {
|
const clearComparison = () => {
|
||||||
comparison.setData(initialComparison);
|
comparison.setData(initialComparison);
|
||||||
@@ -581,6 +585,36 @@ function ParameterFields({
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<FormErrors errors={comparison.errors} />
|
<FormErrors errors={comparison.errors} />
|
||||||
|
{urgentQuotationReady && (
|
||||||
|
<label className="block space-y-1">
|
||||||
|
Mínimo de propostas numa urgência com
|
||||||
|
stock mínimo documentado (opcional)
|
||||||
|
<input
|
||||||
|
className={controlClass}
|
||||||
|
type="number"
|
||||||
|
min="1"
|
||||||
|
max="100"
|
||||||
|
step="1"
|
||||||
|
value={
|
||||||
|
comparison.data
|
||||||
|
.urgent_minimum_proposals ??
|
||||||
|
''
|
||||||
|
}
|
||||||
|
onChange={(event) =>
|
||||||
|
comparison.setData(
|
||||||
|
'urgent_minimum_proposals',
|
||||||
|
event.target.value,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<span className="text-sm text-muted-foreground">
|
||||||
|
Vazio conserva o mínimo normal. Só
|
||||||
|
novas requisições recebem esta
|
||||||
|
configuração; orçamento e aprovações
|
||||||
|
não são dispensados.
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
<div className="grid gap-4 md:grid-cols-2">
|
<div className="grid gap-4 md:grid-cols-2">
|
||||||
<label className="block space-y-1">
|
<label className="block space-y-1">
|
||||||
Mínimo de fornecedores com proposta
|
Mínimo de fornecedores com proposta
|
||||||
|
|||||||
@@ -18,6 +18,13 @@ import { date } from '@/types/procurement';
|
|||||||
export default function DeclarationHistory(props: {
|
export default function DeclarationHistory(props: {
|
||||||
history: ConflictDeclaration[];
|
history: ConflictDeclaration[];
|
||||||
canCorrect: boolean;
|
canCorrect: boolean;
|
||||||
|
canAuthoriseRelease?: boolean;
|
||||||
|
release?: {
|
||||||
|
id: number;
|
||||||
|
authorised_by: number;
|
||||||
|
authorised_at: string;
|
||||||
|
reason: string;
|
||||||
|
} | null;
|
||||||
}) {
|
}) {
|
||||||
const current = props.history[props.history.length - 1];
|
const current = props.history[props.history.length - 1];
|
||||||
const identity = `${useConflictPreparationIdentity()}:correction:${current.id}:${current.declared_at}:${props.canCorrect}`;
|
const identity = `${useConflictPreparationIdentity()}:correction:${current.id}:${current.declared_at}:${props.canCorrect}`;
|
||||||
@@ -27,10 +34,19 @@ function HistoryFields({
|
|||||||
history,
|
history,
|
||||||
canCorrect,
|
canCorrect,
|
||||||
identity,
|
identity,
|
||||||
|
canAuthoriseRelease,
|
||||||
|
release,
|
||||||
}: {
|
}: {
|
||||||
identity: string;
|
identity: string;
|
||||||
history: ConflictDeclaration[];
|
history: ConflictDeclaration[];
|
||||||
canCorrect: boolean;
|
canCorrect: boolean;
|
||||||
|
canAuthoriseRelease?: boolean;
|
||||||
|
release?: {
|
||||||
|
id: number;
|
||||||
|
authorised_by: number;
|
||||||
|
authorised_at: string;
|
||||||
|
reason: string;
|
||||||
|
} | null;
|
||||||
}) {
|
}) {
|
||||||
const current = history[history.length - 1];
|
const current = history[history.length - 1];
|
||||||
const initial = {
|
const initial = {
|
||||||
@@ -56,7 +72,9 @@ function HistoryFields({
|
|||||||
/>
|
/>
|
||||||
<Panel
|
<Panel
|
||||||
title={
|
title={
|
||||||
current.has_conflict
|
release
|
||||||
|
? 'Impedimento levantado pela direcção'
|
||||||
|
: current.has_conflict
|
||||||
? 'Conflito registado com impedimento'
|
? 'Conflito registado com impedimento'
|
||||||
: 'Ausência de conflito declarada'
|
: 'Ausência de conflito declarada'
|
||||||
}
|
}
|
||||||
@@ -87,6 +105,22 @@ function HistoryFields({
|
|||||||
))}
|
))}
|
||||||
</ol>
|
</ol>
|
||||||
</Panel>
|
</Panel>
|
||||||
|
{release && (
|
||||||
|
<Panel
|
||||||
|
title="Autorização da direcção"
|
||||||
|
description={`Autorizada por #${release.authorised_by} em ${date(release.authorised_at)}. Aplica-se apenas a esta declaração e às suas correcções.`}
|
||||||
|
>
|
||||||
|
<p className="text-sm whitespace-pre-wrap">
|
||||||
|
{release.reason}
|
||||||
|
</p>
|
||||||
|
</Panel>
|
||||||
|
)}
|
||||||
|
{canAuthoriseRelease && (
|
||||||
|
<ReleaseForm
|
||||||
|
identity={identity}
|
||||||
|
declarationId={current.id}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
{canCorrect && (
|
{canCorrect && (
|
||||||
<Panel
|
<Panel
|
||||||
title="Corrigir fundamento ou data de conhecimento"
|
title="Corrigir fundamento ou data de conhecimento"
|
||||||
@@ -159,6 +193,70 @@ function HistoryFields({
|
|||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
function ReleaseForm({
|
||||||
|
identity,
|
||||||
|
declarationId,
|
||||||
|
}: {
|
||||||
|
identity: string;
|
||||||
|
declarationId: number;
|
||||||
|
}) {
|
||||||
|
const form = useForm(`${identity}:release`, {
|
||||||
|
reason: '',
|
||||||
|
operation_key: crypto.randomUUID(),
|
||||||
|
});
|
||||||
|
const dirty = form.data.reason.trim() !== '';
|
||||||
|
const ref = usePreparationDirty(dirty, true);
|
||||||
|
return (
|
||||||
|
<Panel
|
||||||
|
title="Autorizar levantamento do impedimento"
|
||||||
|
description="Decisão expressa da direcção. A declaração original permanece no histórico; outros conflitos continuam a impedir a participação."
|
||||||
|
>
|
||||||
|
<form
|
||||||
|
ref={ref}
|
||||||
|
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||||
|
className="space-y-4"
|
||||||
|
onSubmit={(event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
form.post(`/conflitos/${declarationId}/levantamento`, {
|
||||||
|
preserveScroll: true,
|
||||||
|
onSuccess: () => {
|
||||||
|
const initial = {
|
||||||
|
reason: '',
|
||||||
|
operation_key: crypto.randomUUID(),
|
||||||
|
};
|
||||||
|
form.setData(initial);
|
||||||
|
form.clearErrors();
|
||||||
|
router.remember(
|
||||||
|
initial,
|
||||||
|
`${identity}:release:data`,
|
||||||
|
);
|
||||||
|
router.remember({}, `${identity}:release:errors`);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<FormErrors errors={form.errors} />
|
||||||
|
<Label htmlFor="release-reason">
|
||||||
|
Fundamento da autorização
|
||||||
|
</Label>
|
||||||
|
<textarea
|
||||||
|
id="release-reason"
|
||||||
|
required
|
||||||
|
minLength={10}
|
||||||
|
maxLength={5000}
|
||||||
|
className={`${controlClass} h-28 py-3`}
|
||||||
|
value={form.data.reason}
|
||||||
|
onChange={(event) =>
|
||||||
|
form.setData('reason', event.target.value)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Button disabled={form.processing}>
|
||||||
|
Autorizar levantamento
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
</Panel>
|
||||||
|
);
|
||||||
|
}
|
||||||
DeclarationHistory.layout = {
|
DeclarationHistory.layout = {
|
||||||
breadcrumbs: [
|
breadcrumbs: [
|
||||||
{ title: 'Conflitos de interesses', href: '/conflitos' },
|
{ title: 'Conflitos de interesses', href: '/conflitos' },
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ import { ExchangeSummary } from '@/components/quotation-exchange-panel';
|
|||||||
import type { PurchaseOrder } from '@/types/purchase';
|
import type { PurchaseOrder } from '@/types/purchase';
|
||||||
import ImportTariffSummary from '@/components/import-tariff-summary';
|
import ImportTariffSummary from '@/components/import-tariff-summary';
|
||||||
import CapitalAssignmentSummary from '@/components/capital-assignment-summary';
|
import CapitalAssignmentSummary from '@/components/capital-assignment-summary';
|
||||||
|
import OperationalOrderSummary from '@/components/operational-order-summary';
|
||||||
|
import UrgentQuotationSummary from '@/components/urgent-quotation-summary';
|
||||||
import RequisitionAccountSummary from '@/components/requisition-account-summary';
|
import RequisitionAccountSummary from '@/components/requisition-account-summary';
|
||||||
import OrderCancellationRequest, {
|
import OrderCancellationRequest, {
|
||||||
type OrderCancellationState,
|
type OrderCancellationState,
|
||||||
@@ -176,6 +178,14 @@ export default function OrderShow({
|
|||||||
<CapitalAssignmentSummary
|
<CapitalAssignmentSummary
|
||||||
records={snapshot.capital_assignments}
|
records={snapshot.capital_assignments}
|
||||||
/>
|
/>
|
||||||
|
<OperationalOrderSummary
|
||||||
|
records={snapshot.operational_orders}
|
||||||
|
/>
|
||||||
|
{orderPartsSources.length === 0 && (
|
||||||
|
<UrgentQuotationSummary
|
||||||
|
records={snapshot.urgent_quotation_basis}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
<RequisitionAccountSummary
|
<RequisitionAccountSummary
|
||||||
records={snapshot.account_assignments}
|
records={snapshot.account_assignments}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -79,6 +79,7 @@ function ComparisonContent({
|
|||||||
exchangeRates = [],
|
exchangeRates = [],
|
||||||
exchangeAvailable = false,
|
exchangeAvailable = false,
|
||||||
canRecordExchange = false,
|
canRecordExchange = false,
|
||||||
|
urgentQuotationReady = false,
|
||||||
}: {
|
}: {
|
||||||
requisition: {
|
requisition: {
|
||||||
id: number;
|
id: number;
|
||||||
@@ -99,6 +100,7 @@ function ComparisonContent({
|
|||||||
exchangeRates?: ExchangeBasis[];
|
exchangeRates?: ExchangeBasis[];
|
||||||
exchangeAvailable?: boolean;
|
exchangeAvailable?: boolean;
|
||||||
canRecordExchange?: boolean;
|
canRecordExchange?: boolean;
|
||||||
|
urgentQuotationReady?: boolean;
|
||||||
}) {
|
}) {
|
||||||
const actor = usePage().props.auth?.user;
|
const actor = usePage().props.auth?.user;
|
||||||
const historyKey = `quotation-preparation:${actor?.tenant_id}:${actor?.id}:${requisition.id}:${requisition.process_version ?? 0}`;
|
const historyKey = `quotation-preparation:${actor?.tenant_id}:${actor?.id}:${requisition.id}:${requisition.process_version ?? 0}`;
|
||||||
@@ -192,6 +194,15 @@ function ComparisonContent({
|
|||||||
<Link className="text-sm text-teal-700" href="/conflitos">
|
<Link className="text-sm text-teal-700" href="/conflitos">
|
||||||
Registar ou consultar a minha declaração de conflito
|
Registar ou consultar a minha declaração de conflito
|
||||||
</Link>
|
</Link>
|
||||||
|
{urgentQuotationReady &&
|
||||||
|
comparisonPolicy.urgent_minimum_proposals !== undefined && (
|
||||||
|
<Link
|
||||||
|
className="text-sm text-teal-700"
|
||||||
|
href={`/requisicoes/${requisition.id}/urgencia-stock`}
|
||||||
|
>
|
||||||
|
Stock mínimo das cotações urgentes
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
<div
|
<div
|
||||||
className={`rounded-xl border p-5 text-sm ${ready ? 'border-teal-200 bg-teal-50 text-teal-900' : 'border-amber-200 bg-amber-50 text-amber-900'}`}
|
className={`rounded-xl border p-5 text-sm ${ready ? 'border-teal-200 bg-teal-50 text-teal-900' : 'border-amber-200 bg-amber-50 text-amber-900'}`}
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -0,0 +1,416 @@
|
|||||||
|
import { Head, Link, router, useForm } from '@inertiajs/react';
|
||||||
|
import {
|
||||||
|
PageTitle,
|
||||||
|
Panel,
|
||||||
|
FormErrors,
|
||||||
|
controlClass,
|
||||||
|
} from '@/components/procurement';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { useProcurementPreparationIdentity } from '@/hooks/use-procurement-preparation-identity';
|
||||||
|
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||||
|
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||||
|
|
||||||
|
type Order = {
|
||||||
|
id: number;
|
||||||
|
version: number;
|
||||||
|
created_at: string;
|
||||||
|
reason: string;
|
||||||
|
data: {
|
||||||
|
type: string;
|
||||||
|
reference: string;
|
||||||
|
utilisation_location: string;
|
||||||
|
description: string;
|
||||||
|
department_id: number;
|
||||||
|
};
|
||||||
|
snapshot: {
|
||||||
|
author: { name: string };
|
||||||
|
department: { name: string };
|
||||||
|
policy: { data: { mode: string } };
|
||||||
|
};
|
||||||
|
};
|
||||||
|
type LinkRecord = {
|
||||||
|
id: number;
|
||||||
|
version: number;
|
||||||
|
data: { requisition_item_id: number };
|
||||||
|
snapshot: { source: Order };
|
||||||
|
};
|
||||||
|
type Props = {
|
||||||
|
policy: { id: number; version: number; data: { mode: string } } | null;
|
||||||
|
canConfigure: boolean;
|
||||||
|
allowedTypes: string[];
|
||||||
|
departments: { id: number; name: string }[];
|
||||||
|
orders: {
|
||||||
|
data: Order[];
|
||||||
|
prev_page_url: string | null;
|
||||||
|
next_page_url: string | null;
|
||||||
|
};
|
||||||
|
requisition: { id: number; number: string; status: string } | null;
|
||||||
|
items: { id: number; description: string }[];
|
||||||
|
links: LinkRecord[];
|
||||||
|
canLink: boolean;
|
||||||
|
};
|
||||||
|
const labels: Record<string, string> = {
|
||||||
|
production: 'Produção',
|
||||||
|
maintenance: 'Manutenção',
|
||||||
|
};
|
||||||
|
type Field = {
|
||||||
|
name: string;
|
||||||
|
label: string;
|
||||||
|
choices?: { value: string; label: string }[];
|
||||||
|
long?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function OperationalOrders(props: Props) {
|
||||||
|
const identity = useProcurementPreparationIdentity(
|
||||||
|
`operational-orders:${props.policy?.id ?? 0}:${props.policy?.version ?? 0}:${props.allowedTypes.join(',')}:${props.canConfigure}:${props.requisition?.id ?? 0}:${props.canLink}`,
|
||||||
|
);
|
||||||
|
return <Workspace key={identity} {...props} identity={identity} />;
|
||||||
|
}
|
||||||
|
function Workspace(props: Props & { identity: string }) {
|
||||||
|
const base = '/ordens-operacionais';
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Head title="Ordens de produção e manutenção" />
|
||||||
|
<div className="mx-auto flex w-full max-w-6xl flex-col gap-6 p-5 lg:p-8">
|
||||||
|
<PageTitle
|
||||||
|
eyebrow="Compras"
|
||||||
|
title="Ordens de produção e manutenção"
|
||||||
|
description="Registe a necessidade no local de utilização ou através do procurement, conforme a configuração da empresa. A ordem de origem acompanha a compra."
|
||||||
|
/>
|
||||||
|
{props.requisition && (
|
||||||
|
<p>
|
||||||
|
<Link
|
||||||
|
className="underline"
|
||||||
|
href={`/requisicoes/${props.requisition.id}`}
|
||||||
|
>
|
||||||
|
Voltar à {props.requisition.number}
|
||||||
|
</Link>{' '}
|
||||||
|
·{' '}
|
||||||
|
<Link className="underline" href={base}>
|
||||||
|
Cadastro das ordens
|
||||||
|
</Link>
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<Panel
|
||||||
|
title="Origem das ordens"
|
||||||
|
description="A configuração altera quem pode registar novas ordens. Preserva as ordens existentes e não atribui competências a pessoas."
|
||||||
|
>
|
||||||
|
<p className="mb-4 text-sm">
|
||||||
|
{!props.policy
|
||||||
|
? 'A empresa ainda não definiu a origem das ordens.'
|
||||||
|
: props.policy.data.mode === 'utilisation'
|
||||||
|
? 'Nos locais de utilização: responsável da produção ou chefe de oficina, com competência atribuída pela empresa.'
|
||||||
|
: 'No procurement: o agente regista as ordens para os locais ainda não abrangidos pela aplicação.'}
|
||||||
|
</p>
|
||||||
|
{props.canConfigure && (
|
||||||
|
<DraftForm
|
||||||
|
identity={`${props.identity}:policy`}
|
||||||
|
url={`${base}/configuracao`}
|
||||||
|
initial={{
|
||||||
|
version: String(props.policy?.version ?? 0),
|
||||||
|
mode: props.policy?.data.mode ?? '',
|
||||||
|
reason: '',
|
||||||
|
}}
|
||||||
|
fields={[
|
||||||
|
{
|
||||||
|
name: 'mode',
|
||||||
|
label: 'Modo de registo',
|
||||||
|
choices: [
|
||||||
|
{
|
||||||
|
value: 'utilisation',
|
||||||
|
label: 'Nos locais de utilização',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
value: 'procurement',
|
||||||
|
label: 'Pelo agente de procurement',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'reason',
|
||||||
|
label: 'Fundamento da configuração',
|
||||||
|
long: true,
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
submit="Guardar origem das novas ordens"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</Panel>
|
||||||
|
{props.allowedTypes.length > 0 && (
|
||||||
|
<Panel
|
||||||
|
title="Registar ordem"
|
||||||
|
description="O autor e o modo de origem são registados automaticamente. O documento original permanece no histórico."
|
||||||
|
>
|
||||||
|
<DraftForm
|
||||||
|
identity={`${props.identity}:new`}
|
||||||
|
url={base}
|
||||||
|
initial={{
|
||||||
|
type:
|
||||||
|
props.allowedTypes.length === 1
|
||||||
|
? props.allowedTypes[0]
|
||||||
|
: '',
|
||||||
|
reference: '',
|
||||||
|
department_id:
|
||||||
|
props.departments.length === 1
|
||||||
|
? String(props.departments[0].id)
|
||||||
|
: '',
|
||||||
|
utilisation_location: '',
|
||||||
|
description: '',
|
||||||
|
reason: '',
|
||||||
|
policy_version: String(
|
||||||
|
props.policy?.version ?? 0,
|
||||||
|
),
|
||||||
|
}}
|
||||||
|
fields={[
|
||||||
|
{
|
||||||
|
name: 'type',
|
||||||
|
label: 'Tipo de ordem',
|
||||||
|
choices: props.allowedTypes.map((type) => ({
|
||||||
|
value: type,
|
||||||
|
label: labels[type],
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'reference',
|
||||||
|
label: 'Referência da ordem',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'department_id',
|
||||||
|
label: 'Departamento de utilização',
|
||||||
|
choices: props.departments.map(
|
||||||
|
(department) => ({
|
||||||
|
value: String(department.id),
|
||||||
|
label: department.name,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'utilisation_location',
|
||||||
|
label: 'Local de utilização',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'description',
|
||||||
|
label: 'Trabalho ou produção a executar',
|
||||||
|
long: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'reason',
|
||||||
|
label: 'Fundamento do registo',
|
||||||
|
long: true,
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
submit="Registar ordem"
|
||||||
|
/>
|
||||||
|
</Panel>
|
||||||
|
)}
|
||||||
|
<Panel
|
||||||
|
title="Ordens registadas"
|
||||||
|
description="A lista respeita a empresa e o departamento aplicável. Uma ligação utiliza a versão original seleccionada."
|
||||||
|
>
|
||||||
|
{props.orders.data.length === 0 && (
|
||||||
|
<p>Não há ordens disponíveis neste âmbito.</p>
|
||||||
|
)}
|
||||||
|
<ul className="space-y-4">
|
||||||
|
{props.orders.data.map((order) => (
|
||||||
|
<li className="rounded border p-4" key={order.id}>
|
||||||
|
<p className="font-semibold">
|
||||||
|
{labels[order.data.type]} ·{' '}
|
||||||
|
{order.data.reference}
|
||||||
|
</p>
|
||||||
|
<p className="text-sm">
|
||||||
|
{order.snapshot.department.name} ·{' '}
|
||||||
|
{order.data.utilisation_location} ·{' '}
|
||||||
|
{order.snapshot.author.name}
|
||||||
|
</p>
|
||||||
|
<p className="mt-2 text-sm whitespace-pre-wrap">
|
||||||
|
{order.data.description}
|
||||||
|
</p>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
<div className="mt-4 flex gap-4">
|
||||||
|
{props.orders.prev_page_url && (
|
||||||
|
<Link
|
||||||
|
preserveState
|
||||||
|
preserveScroll
|
||||||
|
href={props.orders.prev_page_url}
|
||||||
|
>
|
||||||
|
Anterior
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
{props.orders.next_page_url && (
|
||||||
|
<Link
|
||||||
|
preserveState
|
||||||
|
preserveScroll
|
||||||
|
href={props.orders.next_page_url}
|
||||||
|
>
|
||||||
|
Seguinte
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</Panel>
|
||||||
|
{props.requisition &&
|
||||||
|
props.items.map((item) => {
|
||||||
|
const link = props.links.find(
|
||||||
|
(link) => link.data.requisition_item_id === item.id,
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
<Panel
|
||||||
|
key={item.id}
|
||||||
|
title={item.description}
|
||||||
|
description={
|
||||||
|
link
|
||||||
|
? `Ordem ligada: ${link.snapshot.source.data.reference} · ${labels[link.snapshot.source.data.type]}`
|
||||||
|
: 'Sem ordem de origem ligada.'
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{props.canLink && (
|
||||||
|
<DraftForm
|
||||||
|
key={`${item.id}:${link?.version ?? 0}`}
|
||||||
|
identity={`${props.identity}:link:${item.id}:${link?.version ?? 0}`}
|
||||||
|
url={`/requisicoes/${props.requisition?.id}/ordens-operacionais`}
|
||||||
|
initial={{
|
||||||
|
item_id: String(item.id),
|
||||||
|
order_id: '',
|
||||||
|
version: String(link?.version ?? 0),
|
||||||
|
reason: '',
|
||||||
|
}}
|
||||||
|
fields={[
|
||||||
|
{
|
||||||
|
name: 'order_id',
|
||||||
|
label: 'Ordem de origem',
|
||||||
|
choices: props.orders.data.map(
|
||||||
|
(order) => ({
|
||||||
|
value: String(order.id),
|
||||||
|
label: `${labels[order.data.type]} · ${order.data.reference} · ${order.data.utilisation_location}`,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'reason',
|
||||||
|
label: 'Fundamento da ligação',
|
||||||
|
long: true,
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
submit="Ligar ordem à linha"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</Panel>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
function DraftForm({
|
||||||
|
identity,
|
||||||
|
url,
|
||||||
|
initial,
|
||||||
|
fields,
|
||||||
|
submit,
|
||||||
|
}: {
|
||||||
|
identity: string;
|
||||||
|
url: string;
|
||||||
|
initial: Record<string, string>;
|
||||||
|
fields: Field[];
|
||||||
|
submit: string;
|
||||||
|
}) {
|
||||||
|
const form = useForm<Record<string, string>>(`${identity}:form`, {
|
||||||
|
...initial,
|
||||||
|
operation_key: crypto.randomUUID(),
|
||||||
|
});
|
||||||
|
const dirty = hasPreparationChanges(
|
||||||
|
{ ...initial, operation_key: '' },
|
||||||
|
{ ...form.data, operation_key: '' },
|
||||||
|
);
|
||||||
|
const ref = usePreparationDirty(dirty);
|
||||||
|
return (
|
||||||
|
<form
|
||||||
|
ref={ref}
|
||||||
|
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||||
|
className="space-y-4"
|
||||||
|
onSubmit={(event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
form.post(url, {
|
||||||
|
preserveScroll: true,
|
||||||
|
preserveState: true,
|
||||||
|
onSuccess: () => {
|
||||||
|
const cleared = {
|
||||||
|
...initial,
|
||||||
|
operation_key: crypto.randomUUID(),
|
||||||
|
};
|
||||||
|
form.setData(cleared);
|
||||||
|
form.clearErrors();
|
||||||
|
router.remember(cleared, `${identity}:form:data`);
|
||||||
|
router.remember({}, `${identity}:form:errors`);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<FormErrors errors={form.errors} />
|
||||||
|
{fields.map((field) => (
|
||||||
|
<label key={field.name} className="block space-y-1 text-sm">
|
||||||
|
{field.label}
|
||||||
|
{field.choices ? (
|
||||||
|
<select
|
||||||
|
className={controlClass}
|
||||||
|
required
|
||||||
|
value={form.data[field.name] ?? ''}
|
||||||
|
onChange={(event) =>
|
||||||
|
form.setData(field.name, event.target.value)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<option value="">Seleccione</option>
|
||||||
|
{form.data[field.name] &&
|
||||||
|
!field.choices.some(
|
||||||
|
(choice) =>
|
||||||
|
choice.value === form.data[field.name],
|
||||||
|
) && (
|
||||||
|
<option value={form.data[field.name]}>
|
||||||
|
Selecção preservada de outra página —
|
||||||
|
confira a ordem antes de submeter
|
||||||
|
</option>
|
||||||
|
)}
|
||||||
|
{field.choices.map((choice) => (
|
||||||
|
<option key={choice.value} value={choice.value}>
|
||||||
|
{choice.label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
) : field.long ? (
|
||||||
|
<textarea
|
||||||
|
className={`${controlClass} h-24 py-3`}
|
||||||
|
required
|
||||||
|
minLength={10}
|
||||||
|
maxLength={4000}
|
||||||
|
value={form.data[field.name] ?? ''}
|
||||||
|
onChange={(event) =>
|
||||||
|
form.setData(field.name, event.target.value)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<input
|
||||||
|
className={controlClass}
|
||||||
|
required
|
||||||
|
minLength={3}
|
||||||
|
maxLength={field.name === 'reference' ? 120 : 300}
|
||||||
|
value={form.data[field.name] ?? ''}
|
||||||
|
onChange={(event) =>
|
||||||
|
form.setData(field.name, event.target.value)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
<Button disabled={form.processing}>{submit}</Button>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
OperationalOrders.layout = {
|
||||||
|
breadcrumbs: [
|
||||||
|
{
|
||||||
|
title: 'Ordens de produção e manutenção',
|
||||||
|
href: '/ordens-operacionais',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
@@ -67,6 +67,7 @@ export default function Show({
|
|||||||
importTariffsReady = false,
|
importTariffsReady = false,
|
||||||
importEstimatesReady = false,
|
importEstimatesReady = false,
|
||||||
capitalRegisterReady = false,
|
capitalRegisterReady = false,
|
||||||
|
operationalOrdersReady = false,
|
||||||
expiryReady = false,
|
expiryReady = false,
|
||||||
accountsReady = false,
|
accountsReady = false,
|
||||||
duplicateHints = null,
|
duplicateHints = null,
|
||||||
@@ -81,6 +82,7 @@ export default function Show({
|
|||||||
} | null;
|
} | null;
|
||||||
importEstimatesReady?: boolean;
|
importEstimatesReady?: boolean;
|
||||||
capitalRegisterReady?: boolean;
|
capitalRegisterReady?: boolean;
|
||||||
|
operationalOrdersReady?: boolean;
|
||||||
expiryReady?: boolean;
|
expiryReady?: boolean;
|
||||||
accountsReady?: boolean;
|
accountsReady?: boolean;
|
||||||
importTariffsReady?: boolean;
|
importTariffsReady?: boolean;
|
||||||
@@ -195,6 +197,14 @@ export default function Show({
|
|||||||
</Link>
|
</Link>
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
|
{operationalOrdersReady && (
|
||||||
|
<Link
|
||||||
|
className="underline"
|
||||||
|
href={`/requisicoes/${r.id}/ordens-operacionais`}
|
||||||
|
>
|
||||||
|
Ligar artigos a ordens de produção ou manutenção
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
{accountsReady && (
|
{accountsReady && (
|
||||||
<Button asChild variant="outline">
|
<Button asChild variant="outline">
|
||||||
<Link href={`/requisicoes/${r.id}/contas`}>
|
<Link href={`/requisicoes/${r.id}/contas`}>
|
||||||
|
|||||||
@@ -0,0 +1,290 @@
|
|||||||
|
import { Head, Link, router, useForm } from '@inertiajs/react';
|
||||||
|
import {
|
||||||
|
Panel,
|
||||||
|
PageTitle,
|
||||||
|
FormErrors,
|
||||||
|
controlClass,
|
||||||
|
} from '@/components/procurement';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import {
|
||||||
|
ComparisonPolicySummary,
|
||||||
|
type ComparisonPolicy,
|
||||||
|
} from '@/components/comparison-policy-summary';
|
||||||
|
import { useProcurementPreparationIdentity } from '@/hooks/use-procurement-preparation-identity';
|
||||||
|
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
|
||||||
|
import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||||
|
|
||||||
|
type Item = {
|
||||||
|
id: number;
|
||||||
|
description: string;
|
||||||
|
catalogue_snapshot?: { stock_item_id?: number } | null;
|
||||||
|
};
|
||||||
|
type Policy = {
|
||||||
|
id: number;
|
||||||
|
version: number;
|
||||||
|
stock_item_id: number;
|
||||||
|
item: { name: string; unit: string };
|
||||||
|
warehouse: { name: string };
|
||||||
|
minimum_stock_milli: number;
|
||||||
|
usage_context: string | null;
|
||||||
|
};
|
||||||
|
type Evidence = {
|
||||||
|
id: number;
|
||||||
|
version: number;
|
||||||
|
reason: string;
|
||||||
|
data: { requisition_item_id: number };
|
||||||
|
snapshot: {
|
||||||
|
stock_policy: {
|
||||||
|
minimum_stock_milli: number;
|
||||||
|
usage_context: string | null;
|
||||||
|
warehouse: { name: string };
|
||||||
|
};
|
||||||
|
availability: { free_milli: number | null };
|
||||||
|
author: { name: string };
|
||||||
|
};
|
||||||
|
};
|
||||||
|
type Props = {
|
||||||
|
requisition: {
|
||||||
|
id: number;
|
||||||
|
number: string;
|
||||||
|
priority: string;
|
||||||
|
justification: string;
|
||||||
|
};
|
||||||
|
cycle: number;
|
||||||
|
canRecord: boolean;
|
||||||
|
items: Item[];
|
||||||
|
comparisonPolicy: ComparisonPolicy;
|
||||||
|
policies: {
|
||||||
|
data: Policy[];
|
||||||
|
prev_page_url: string | null;
|
||||||
|
next_page_url: string | null;
|
||||||
|
};
|
||||||
|
evidence: Evidence[];
|
||||||
|
eligible: Evidence[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function UrgentStock(props: Props) {
|
||||||
|
const identity = useProcurementPreparationIdentity(
|
||||||
|
`urgent-stock:${props.requisition.id}:${props.cycle}:${props.comparisonPolicy.revision}`,
|
||||||
|
);
|
||||||
|
const enabled =
|
||||||
|
props.requisition.priority === 'urgent' &&
|
||||||
|
props.comparisonPolicy.urgent_minimum_proposals !== undefined;
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Head title="Stock mínimo e cotações urgentes" />
|
||||||
|
<div className="mx-auto flex w-full max-w-5xl flex-col gap-6 p-5 lg:p-8">
|
||||||
|
<PageTitle
|
||||||
|
eyebrow={props.requisition.number}
|
||||||
|
title="Stock mínimo e cotações urgentes"
|
||||||
|
description="Documente a política de stock aplicável ao artigo e ao local de utilização. O servidor confere se o mínimo foi atingido; orçamento, avaliações e aprovações mantêm-se."
|
||||||
|
/>
|
||||||
|
<Link
|
||||||
|
className="underline"
|
||||||
|
href={`/requisicoes/${props.requisition.id}/cotacoes`}
|
||||||
|
>
|
||||||
|
Voltar às cotações
|
||||||
|
</Link>
|
||||||
|
<Panel title="Regra preservada na requisição">
|
||||||
|
<ComparisonPolicySummary policy={props.comparisonPolicy} />
|
||||||
|
<p className="mt-3 text-sm">
|
||||||
|
{!enabled
|
||||||
|
? 'Esta requisição não permite redução urgente de cotações.'
|
||||||
|
: props.eligible.length > 0
|
||||||
|
? 'Stock mínimo documentado para todas as linhas deste ciclo. A comparação pode aplicar o número urgente configurado.'
|
||||||
|
: 'Mantém-se o número normal de propostas enquanto faltar a conferência válida de alguma linha.'}
|
||||||
|
</p>
|
||||||
|
</Panel>
|
||||||
|
{props.items.map((item) => {
|
||||||
|
const previous = props.evidence.find(
|
||||||
|
(record) => record.data.requisition_item_id === item.id,
|
||||||
|
);
|
||||||
|
const policies = props.policies.data.filter(
|
||||||
|
(policy) =>
|
||||||
|
policy.stock_item_id ===
|
||||||
|
item.catalogue_snapshot?.stock_item_id,
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
<Panel title={item.description} key={item.id}>
|
||||||
|
{previous && (
|
||||||
|
<div className="mb-4 space-y-1 text-sm">
|
||||||
|
<p>
|
||||||
|
Conferência #{previous.id} ·{' '}
|
||||||
|
{previous.snapshot.author.name} ·{' '}
|
||||||
|
{
|
||||||
|
previous.snapshot.stock_policy
|
||||||
|
.warehouse.name
|
||||||
|
}
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
Mínimo documentado:{' '}
|
||||||
|
{previous.snapshot.stock_policy
|
||||||
|
.minimum_stock_milli / 1000}
|
||||||
|
; stock livre no momento:{' '}
|
||||||
|
{previous.snapshot.availability
|
||||||
|
.free_milli === null
|
||||||
|
? 'Indeterminado'
|
||||||
|
: previous.snapshot.availability
|
||||||
|
.free_milli / 1000}
|
||||||
|
.
|
||||||
|
</p>
|
||||||
|
{previous.snapshot.stock_policy
|
||||||
|
.usage_context && (
|
||||||
|
<p>
|
||||||
|
{
|
||||||
|
previous.snapshot.stock_policy
|
||||||
|
.usage_context
|
||||||
|
}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<p>{previous.reason}</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{enabled && props.canRecord && (
|
||||||
|
<EvidenceForm
|
||||||
|
key={`${identity}:${item.id}:${previous?.version ?? 0}`}
|
||||||
|
identity={`${identity}:${item.id}:${previous?.version ?? 0}`}
|
||||||
|
requestId={props.requisition.id}
|
||||||
|
itemId={item.id}
|
||||||
|
version={previous?.version ?? 0}
|
||||||
|
policies={policies}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</Panel>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
<div className="flex gap-4">
|
||||||
|
{props.policies.prev_page_url && (
|
||||||
|
<Link
|
||||||
|
preserveState
|
||||||
|
preserveScroll
|
||||||
|
href={props.policies.prev_page_url}
|
||||||
|
>
|
||||||
|
Políticas anteriores
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
{props.policies.next_page_url && (
|
||||||
|
<Link
|
||||||
|
preserveState
|
||||||
|
preserveScroll
|
||||||
|
href={props.policies.next_page_url}
|
||||||
|
>
|
||||||
|
Mais políticas
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
function EvidenceForm({
|
||||||
|
identity,
|
||||||
|
requestId,
|
||||||
|
itemId,
|
||||||
|
version,
|
||||||
|
policies,
|
||||||
|
}: {
|
||||||
|
identity: string;
|
||||||
|
requestId: number;
|
||||||
|
itemId: number;
|
||||||
|
version: number;
|
||||||
|
policies: Policy[];
|
||||||
|
}) {
|
||||||
|
const initial = {
|
||||||
|
item_id: itemId,
|
||||||
|
policy_id: policies.length === 1 ? String(policies[0].id) : '',
|
||||||
|
version,
|
||||||
|
reason: '',
|
||||||
|
};
|
||||||
|
const form = useForm(`${identity}:form`, {
|
||||||
|
...initial,
|
||||||
|
operation_key: crypto.randomUUID(),
|
||||||
|
});
|
||||||
|
const dirty = hasPreparationChanges(
|
||||||
|
{ ...initial, operation_key: '' },
|
||||||
|
{ ...form.data, operation_key: '' },
|
||||||
|
);
|
||||||
|
const ref = usePreparationDirty(dirty);
|
||||||
|
return (
|
||||||
|
<form
|
||||||
|
ref={ref}
|
||||||
|
data-preparation-dirty={dirty ? 'true' : 'false'}
|
||||||
|
className="space-y-4"
|
||||||
|
onSubmit={(event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
form.post(`/requisicoes/${requestId}/urgencia-stock`, {
|
||||||
|
preserveScroll: true,
|
||||||
|
preserveState: true,
|
||||||
|
onSuccess: () => {
|
||||||
|
const cleared = {
|
||||||
|
...initial,
|
||||||
|
operation_key: crypto.randomUUID(),
|
||||||
|
};
|
||||||
|
form.setData(cleared);
|
||||||
|
form.clearErrors();
|
||||||
|
router.remember(cleared, `${identity}:form:data`);
|
||||||
|
router.remember({}, `${identity}:form:errors`);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<FormErrors errors={form.errors} />
|
||||||
|
<label className="block space-y-1 text-sm">
|
||||||
|
Política de mínimo aplicável ao artigo/local
|
||||||
|
<select
|
||||||
|
className={controlClass}
|
||||||
|
required
|
||||||
|
value={form.data.policy_id}
|
||||||
|
onChange={(event) =>
|
||||||
|
form.setData('policy_id', event.target.value)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<option value="">Seleccione a política aprovada</option>
|
||||||
|
{form.data.policy_id &&
|
||||||
|
!policies.some(
|
||||||
|
(policy) =>
|
||||||
|
String(policy.id) === form.data.policy_id,
|
||||||
|
) && (
|
||||||
|
<option value={form.data.policy_id}>
|
||||||
|
Política preservada de outra página — confira a
|
||||||
|
fonte
|
||||||
|
</option>
|
||||||
|
)}
|
||||||
|
{policies.map((policy) => (
|
||||||
|
<option key={policy.id} value={policy.id}>
|
||||||
|
{policy.warehouse.name} · mínimo{' '}
|
||||||
|
{policy.minimum_stock_milli / 1000}{' '}
|
||||||
|
{policy.item.unit} ·{' '}
|
||||||
|
{policy.usage_context ?? policy.item.name} · versão{' '}
|
||||||
|
{policy.version}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label className="block space-y-1 text-sm">
|
||||||
|
Fundamento da urgência e da utilização desta política
|
||||||
|
<textarea
|
||||||
|
className={`${controlClass} h-24 py-3`}
|
||||||
|
required
|
||||||
|
minLength={10}
|
||||||
|
maxLength={4000}
|
||||||
|
value={form.data.reason}
|
||||||
|
onChange={(event) =>
|
||||||
|
form.setData('reason', event.target.value)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<Button
|
||||||
|
disabled={
|
||||||
|
form.processing ||
|
||||||
|
(!form.data.policy_id && policies.length === 0)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
Conferir stock mínimo
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
UrgentStock.layout = {
|
||||||
|
breadcrumbs: [{ title: 'Stock mínimo e cotações urgentes', href: '#' }],
|
||||||
|
};
|
||||||
@@ -46,6 +46,20 @@ type Page<T> = {
|
|||||||
next_page_url: string | null;
|
next_page_url: string | null;
|
||||||
};
|
};
|
||||||
type Props = {
|
type Props = {
|
||||||
|
referenceDraftWarnings?: { source_id: number; message: string }[];
|
||||||
|
referenceDrafts?: {
|
||||||
|
source_id: number;
|
||||||
|
code: string;
|
||||||
|
description: string;
|
||||||
|
rate_percent: string;
|
||||||
|
title: string;
|
||||||
|
official_reference: string;
|
||||||
|
official_url: string | null;
|
||||||
|
citation: string;
|
||||||
|
valid_from: string;
|
||||||
|
obligations: string;
|
||||||
|
charges: LegalCharge[];
|
||||||
|
}[];
|
||||||
sources?: Page<{
|
sources?: Page<{
|
||||||
id: number;
|
id: number;
|
||||||
data: { official_reference: string; official_url: string | null };
|
data: { official_reference: string; official_url: string | null };
|
||||||
@@ -864,6 +878,87 @@ export default function ImportLegal(props: Props) {
|
|||||||
: 'Preparar uma regra documentada'
|
: 'Preparar uma regra documentada'
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
|
{props.referenceDraftWarnings?.map((warning) => (
|
||||||
|
<p
|
||||||
|
key={warning.source_id}
|
||||||
|
role="status"
|
||||||
|
className="mb-3 text-sm"
|
||||||
|
>
|
||||||
|
Fonte #{warning.source_id}: {warning.message}
|
||||||
|
</p>
|
||||||
|
))}
|
||||||
|
{(props.referenceDrafts?.length ?? 0) > 0 && (
|
||||||
|
<div className="mb-5 space-y-3 rounded border p-3">
|
||||||
|
<h3 className="font-medium">
|
||||||
|
Preparar a partir do exemplar oficial
|
||||||
|
</h3>
|
||||||
|
<p className="text-sm">
|
||||||
|
Transcrição da página 2180-(4) da Lei 8/2025,
|
||||||
|
com início em 01/01/2026. Inclui apenas a taxa
|
||||||
|
geral dessa edição; não é uma pauta consolidada
|
||||||
|
nem determina isenções, preferências ou outras
|
||||||
|
imposições. A preparação continua editável e
|
||||||
|
exige gravação e decisão expressas.
|
||||||
|
</p>
|
||||||
|
{form.isDirty && (
|
||||||
|
<p className="text-sm">
|
||||||
|
Conclua ou limpe a preparação actual antes
|
||||||
|
de escolher outro código. O preenchimento
|
||||||
|
existente será conservado.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<div className="grid gap-2">
|
||||||
|
{props.referenceDrafts?.map((draft) => (
|
||||||
|
<Button
|
||||||
|
key={`${draft.source_id}:${draft.code}`}
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
className="h-auto justify-start text-left whitespace-normal"
|
||||||
|
disabled={
|
||||||
|
form.isDirty ||
|
||||||
|
form.processing ||
|
||||||
|
form.data.record_key !== null
|
||||||
|
}
|
||||||
|
onClick={() => {
|
||||||
|
form.setData({
|
||||||
|
...form.data,
|
||||||
|
operation_key: '',
|
||||||
|
record_key: null,
|
||||||
|
version: 0,
|
||||||
|
action: 'save',
|
||||||
|
title: draft.title,
|
||||||
|
official_reference:
|
||||||
|
draft.official_reference,
|
||||||
|
official_url:
|
||||||
|
draft.official_url ?? '',
|
||||||
|
citation: draft.citation,
|
||||||
|
valid_from: draft.valid_from,
|
||||||
|
valid_until: '',
|
||||||
|
match_code: draft.code,
|
||||||
|
suggested_code: draft.code,
|
||||||
|
origin_country: '',
|
||||||
|
sector: '',
|
||||||
|
obligations: draft.obligations,
|
||||||
|
document_types: [],
|
||||||
|
reason: '',
|
||||||
|
file: null,
|
||||||
|
source_id: String(
|
||||||
|
draft.source_id,
|
||||||
|
),
|
||||||
|
charges: chargeDrafts(
|
||||||
|
draft.charges,
|
||||||
|
),
|
||||||
|
});
|
||||||
|
form.clearErrors();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{draft.code} — {draft.description} —
|
||||||
|
taxa geral {draft.rate_percent}%
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
<form
|
<form
|
||||||
ref={ref}
|
ref={ref}
|
||||||
className="space-y-4"
|
className="space-y-4"
|
||||||
|
|||||||
@@ -155,6 +155,7 @@ const labels: Record<string, string> = {
|
|||||||
origin: 'Origem do fornecimento',
|
origin: 'Origem do fornecimento',
|
||||||
safety_milli: 'Stock de segurança',
|
safety_milli: 'Stock de segurança',
|
||||||
minimum_stock_milli: 'Stock mínimo',
|
minimum_stock_milli: 'Stock mínimo',
|
||||||
|
usage_context: 'Natureza do artigo e utilização considerada',
|
||||||
target_milli: 'Stock alvo',
|
target_milli: 'Stock alvo',
|
||||||
maximum_milli: 'Stock máximo',
|
maximum_milli: 'Stock máximo',
|
||||||
daily_milli: 'Procura diária',
|
daily_milli: 'Procura diária',
|
||||||
@@ -1077,6 +1078,12 @@ function PreparationForm({
|
|||||||
</label>
|
</label>
|
||||||
{field('safety', 'Stock de segurança', 'number')}
|
{field('safety', 'Stock de segurança', 'number')}
|
||||||
{field('minimum_stock', 'Stock mínimo', 'number')}
|
{field('minimum_stock', 'Stock mínimo', 'number')}
|
||||||
|
{field(
|
||||||
|
'usage_context',
|
||||||
|
'Natureza do artigo e utilização considerada no mínimo',
|
||||||
|
'text',
|
||||||
|
true,
|
||||||
|
)}
|
||||||
{field('target', 'Stock alvo', 'number')}
|
{field('target', 'Stock alvo', 'number')}
|
||||||
{field('maximum', 'Stock máximo', 'number')}
|
{field('maximum', 'Stock máximo', 'number')}
|
||||||
{form.data.data.forecast_method !== 'historical' &&
|
{form.data.data.forecast_method !== 'historical' &&
|
||||||
@@ -1097,7 +1104,10 @@ function PreparationForm({
|
|||||||
'Antecedência de aprovação interna em dias corridos',
|
'Antecedência de aprovação interna em dias corridos',
|
||||||
'number',
|
'number',
|
||||||
)}
|
)}
|
||||||
{field('basis', 'Fonte da procura e do prazo')}
|
{field(
|
||||||
|
'basis',
|
||||||
|
'Fundamento do mínimo, da procura e do prazo',
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
{props.kind === 'import' && (
|
{props.kind === 'import' && (
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ import type { ComparisonPolicy } from '@/components/comparison-policy-summary';
|
|||||||
import type { ExchangeBasis } from '@/components/quotation-exchange-panel';
|
import type { ExchangeBasis } from '@/components/quotation-exchange-panel';
|
||||||
import type { FrozenImportTariff } from '@/components/import-tariff-summary';
|
import type { FrozenImportTariff } from '@/components/import-tariff-summary';
|
||||||
import type { FrozenCapitalAssignment } from '@/components/capital-assignment-summary';
|
import type { FrozenCapitalAssignment } from '@/components/capital-assignment-summary';
|
||||||
|
import type { FrozenOperationalOrder } from '@/components/operational-order-summary';
|
||||||
|
import type { FrozenUrgentBasis } from '@/components/urgent-quotation-summary';
|
||||||
|
|
||||||
export type MatrixRow = {
|
export type MatrixRow = {
|
||||||
currency?: string;
|
currency?: string;
|
||||||
@@ -101,6 +103,8 @@ export type PurchaseOrder = {
|
|||||||
items: OrderItem[];
|
items: OrderItem[];
|
||||||
snapshot: {
|
snapshot: {
|
||||||
capital_assignments?: Record<number, FrozenCapitalAssignment>;
|
capital_assignments?: Record<number, FrozenCapitalAssignment>;
|
||||||
|
operational_orders?: Record<number, FrozenOperationalOrder>;
|
||||||
|
urgent_quotation_basis?: FrozenUrgentBasis[];
|
||||||
account_assignments?: Record<
|
account_assignments?: Record<
|
||||||
string,
|
string,
|
||||||
import('@/components/requisition-account-summary').FrozenAccountAssignment
|
import('@/components/requisition-account-summary').FrozenAccountAssignment
|
||||||
|
|||||||
@@ -48,6 +48,7 @@
|
|||||||
<p>Cada origem conserva as condições e aprovações registadas. Os valores das parcelas usam o arredondamento cumulativo da origem.</p>
|
<p>Cada origem conserva as condições e aprovações registadas. Os valores das parcelas usam o arredondamento cumulativo da origem.</p>
|
||||||
@foreach($snapshot['order_parts']['frames'] as $frame)
|
@foreach($snapshot['order_parts']['frames'] as $frame)
|
||||||
<section><h3>{{ $frame['requisition']['number'] }}</h3><p>{{ $frame['department']['name'] }} · {{ $frame['cost_center']['code'] }} · {{ $frame['cost_center']['name'] }}<br>Proposta {{ $frame['quotation']['reference'] }} · Pagamento: {{ $frame['quotation']['payment_terms'] }}<br>Entrega: {{ $frame['award']['delivery_date'] }} · <span class="pre">{{ $frame['award']['delivery_location'] }}</span></p></section>
|
<section><h3>{{ $frame['requisition']['number'] }}</h3><p>{{ $frame['department']['name'] }} · {{ $frame['cost_center']['code'] }} · {{ $frame['cost_center']['name'] }}<br>Proposta {{ $frame['quotation']['reference'] }} · Pagamento: {{ $frame['quotation']['payment_terms'] }}<br>Entrega: {{ $frame['award']['delivery_date'] }} · <span class="pre">{{ $frame['award']['delivery_location'] }}</span></p></section>
|
||||||
|
@include('purchases.urgent-quotation-basis', ['urgentBasis' => $frame['urgent_quotation_basis'] ?? []])
|
||||||
@if(!empty($frame['native_preparation']['exchange_basis']))
|
@if(!empty($frame['native_preparation']['exchange_basis']))
|
||||||
@include('purchases.exchange-basis', ['basis' => $frame['native_preparation']['exchange_basis'], 'reference' => $frame['requisition']['number'], 'referenceAmounts' => $frame['native_preparation']['reference_amounts']])
|
@include('purchases.exchange-basis', ['basis' => $frame['native_preparation']['exchange_basis'], 'reference' => $frame['requisition']['number'], 'referenceAmounts' => $frame['native_preparation']['reference_amounts']])
|
||||||
@endif
|
@endif
|
||||||
@@ -95,6 +96,17 @@
|
|||||||
{{ $assignment['snapshot']['source']['data']['reference'] }}<br>{{ $assignment['reason'] }}</p>
|
{{ $assignment['snapshot']['source']['data']['reference'] }}<br>{{ $assignment['reason'] }}</p>
|
||||||
@endforeach
|
@endforeach
|
||||||
@endif
|
@endif
|
||||||
|
@if(!empty($snapshot['operational_orders']))
|
||||||
|
<h2>Ordens de produção e manutenção de origem</h2>
|
||||||
|
@foreach($snapshot['operational_orders'] as $origin)
|
||||||
|
@php($source = $origin['snapshot']['source'])
|
||||||
|
<p class="pre"><strong>{{ $origin['snapshot']['item']['description'] }}</strong><br>
|
||||||
|
{{ $source['data']['type'] === 'production' ? 'Produção' : 'Manutenção' }} · {{ $source['data']['reference'] }}<br>
|
||||||
|
{{ $source['snapshot']['department']['name'] }} · {{ $source['data']['utilisation_location'] }} · {{ $source['snapshot']['author']['name'] }}<br>
|
||||||
|
{{ $source['snapshot']['policy']['data']['mode'] === 'utilisation' ? 'Origem no local de utilização' : 'Registada pelo procurement' }}<br>
|
||||||
|
{{ $source['data']['description'] }}</p>
|
||||||
|
@endforeach
|
||||||
|
@endif
|
||||||
@if(!empty($snapshot['account_assignments']))
|
@if(!empty($snapshot['account_assignments']))
|
||||||
<h2>Contas da necessidade original</h2>
|
<h2>Contas da necessidade original</h2>
|
||||||
<p>Imputação da requisição conservada na emissão. Parcelas originais; não são valores contabilizados nem rateio desta ordem parcial.</p>
|
<p>Imputação da requisição conservada na emissão. Parcelas originais; não são valores contabilizados nem rateio desta ordem parcial.</p>
|
||||||
@@ -121,6 +133,9 @@
|
|||||||
@if(!empty($snapshot['comparison_policy']))
|
@if(!empty($snapshot['comparison_policy']))
|
||||||
<p class="small">Regra de comparação preservada: revisão {{ $snapshot['comparison_policy']['revision'] }} · mínimo de {{ $snapshot['comparison_policy']['minimum_proposals'] }} fornecedores com propostas elegíveis e {{ $snapshot['comparison_policy']['minimum_evaluators'] }} avaliações independentes por proposta.</p>
|
<p class="small">Regra de comparação preservada: revisão {{ $snapshot['comparison_policy']['revision'] }} · mínimo de {{ $snapshot['comparison_policy']['minimum_proposals'] }} fornecedores com propostas elegíveis e {{ $snapshot['comparison_policy']['minimum_evaluators'] }} avaliações independentes por proposta.</p>
|
||||||
@endif
|
@endif
|
||||||
|
@if(empty($snapshot['order_parts']['frames']))
|
||||||
|
@include('purchases.urgent-quotation-basis', ['urgentBasis' => $snapshot['urgent_quotation_basis'] ?? []])
|
||||||
|
@endif
|
||||||
<table><thead><tr><th>Fornecedor / proposta</th><th>Total com IVA</th><th>Avaliações elegíveis</th><th>Pontuação</th></tr></thead><tbody>
|
<table><thead><tr><th>Fornecedor / proposta</th><th>Total com IVA</th><th>Avaliações elegíveis</th><th>Pontuação</th></tr></thead><tbody>
|
||||||
@foreach($snapshot['decision_matrix'] as $row)
|
@foreach($snapshot['decision_matrix'] as $row)
|
||||||
<tr><td>{{ $row['supplier']['name'] }} · {{ $row['reference'] }}<br>@foreach($row['evaluations'] as $evaluation)<span class="small">Avaliador #{{ $evaluation['evaluator_id'] }}: qualidade {{ $evaluation['quality'] }}, histórico {{ $evaluation['history'] }}, pagamento {{ $evaluation['payment'] }}. {{ $evaluation['comment'] }}</span><br>@endforeach</td><td>{{ $money($row['total_minor'], $row['currency']) }}</td><td>{{ $row['evaluation_count'] }}</td><td>{{ $row['score'] === null ? 'Não elegível / incompleta' : number_format($row['score'], 2, ',', '.') . ' / 10' }}</td></tr>
|
<tr><td>{{ $row['supplier']['name'] }} · {{ $row['reference'] }}<br>@foreach($row['evaluations'] as $evaluation)<span class="small">Avaliador #{{ $evaluation['evaluator_id'] }}: qualidade {{ $evaluation['quality'] }}, histórico {{ $evaluation['history'] }}, pagamento {{ $evaluation['payment'] }}. {{ $evaluation['comment'] }}</span><br>@endforeach</td><td>{{ $money($row['total_minor'], $row['currency']) }}</td><td>{{ $row['evaluation_count'] }}</td><td>{{ $row['score'] === null ? 'Não elegível / incompleta' : number_format($row['score'], 2, ',', '.') . ' / 10' }}</td></tr>
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
@if(!empty($urgentBasis))
|
||||||
|
<h3>Fundamento da redução urgente de cotações</h3>
|
||||||
|
<p>Conferências do mínimo parametrizado atingido; orçamento e aprovações mantêm-se.</p>
|
||||||
|
@foreach($urgentBasis as $proof)
|
||||||
|
<p class="pre"><strong>{{ $proof['snapshot']['item']['description'] }}</strong> · {{ $proof['snapshot']['stock_policy']['warehouse']['name'] }}<br>
|
||||||
|
Mínimo: {{ $proof['snapshot']['stock_policy']['minimum_stock_milli'] / 1000 }};
|
||||||
|
stock livre no momento: {{ $proof['snapshot']['availability']['free_milli'] === null ? 'Indeterminado' : $proof['snapshot']['availability']['free_milli'] / 1000 }}.<br>
|
||||||
|
{{ $proof['snapshot']['author']['name'] }} · {{ $proof['created_at'] }}<br>
|
||||||
|
{{ $proof['snapshot']['stock_policy']['usage_context'] ?? '' }}<br>{{ $proof['reason'] }}</p>
|
||||||
|
@endforeach
|
||||||
|
@endif
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
use App\Http\Controllers\AdministrativeGeographyController;
|
use App\Http\Controllers\AdministrativeGeographyController;
|
||||||
use App\Http\Controllers\AgreementFollowupController;
|
use App\Http\Controllers\AgreementFollowupController;
|
||||||
use App\Http\Controllers\AuditMetadataController;
|
use App\Http\Controllers\AuditMetadataController;
|
||||||
|
use App\Http\Controllers\PrivateAuditController;
|
||||||
use App\Http\Controllers\AutomaticPurchaseController;
|
use App\Http\Controllers\AutomaticPurchaseController;
|
||||||
use App\Http\Controllers\BudgetController;
|
use App\Http\Controllers\BudgetController;
|
||||||
use App\Http\Controllers\BudgetReinforcementController;
|
use App\Http\Controllers\BudgetReinforcementController;
|
||||||
@@ -31,6 +32,7 @@ use App\Http\Controllers\InventoryLotController;
|
|||||||
use App\Http\Controllers\InventoryReversalController;
|
use App\Http\Controllers\InventoryReversalController;
|
||||||
use App\Http\Controllers\InvestmentPolicyController;
|
use App\Http\Controllers\InvestmentPolicyController;
|
||||||
use App\Http\Controllers\InvoiceController;
|
use App\Http\Controllers\InvoiceController;
|
||||||
|
use App\Http\Controllers\OperationalOrdersController;
|
||||||
use App\Http\Controllers\OrderCancellationController;
|
use App\Http\Controllers\OrderCancellationController;
|
||||||
use App\Http\Controllers\OrderPartsController;
|
use App\Http\Controllers\OrderPartsController;
|
||||||
use App\Http\Controllers\OrganizationConfigurationController;
|
use App\Http\Controllers\OrganizationConfigurationController;
|
||||||
@@ -68,6 +70,7 @@ use App\Http\Controllers\SupplierPaymentsController;
|
|||||||
use App\Http\Controllers\SupplierResponseController;
|
use App\Http\Controllers\SupplierResponseController;
|
||||||
use App\Http\Controllers\SupplyCoordinationReportController;
|
use App\Http\Controllers\SupplyCoordinationReportController;
|
||||||
use App\Http\Controllers\SupplyPlanningController;
|
use App\Http\Controllers\SupplyPlanningController;
|
||||||
|
use App\Http\Controllers\UrgentQuotationController;
|
||||||
use App\Http\Controllers\UrgentRequisitionReviewController;
|
use App\Http\Controllers\UrgentRequisitionReviewController;
|
||||||
use App\Http\Controllers\WarehouseAvailabilityController;
|
use App\Http\Controllers\WarehouseAvailabilityController;
|
||||||
use App\Http\Controllers\WarehouseExchangeController;
|
use App\Http\Controllers\WarehouseExchangeController;
|
||||||
@@ -220,6 +223,9 @@ Route::middleware(['auth', 'verified', EnsureOrganizationAccess::class])->group(
|
|||||||
Route::get('pessoas/{process}', [PeopleHiringController::class, 'show'])->whereNumber('process');
|
Route::get('pessoas/{process}', [PeopleHiringController::class, 'show'])->whereNumber('process');
|
||||||
Route::get('auditoria/eventos', [AuditMetadataController::class, 'index']);
|
Route::get('auditoria/eventos', [AuditMetadataController::class, 'index']);
|
||||||
Route::get('auditoria/eventos.csv', [AuditMetadataController::class, 'csv']);
|
Route::get('auditoria/eventos.csv', [AuditMetadataController::class, 'csv']);
|
||||||
|
Route::get('auditoria/privada', [PrivateAuditController::class, 'index']);
|
||||||
|
Route::post('auditoria/privada', [PrivateAuditController::class, 'store']);
|
||||||
|
Route::get('auditoria/privada/{export}/download', [PrivateAuditController::class, 'download']);
|
||||||
Route::get('pessoas/{process}/dossier.json', [PeopleHiringController::class, 'dossier'])->whereNumber('process');
|
Route::get('pessoas/{process}/dossier.json', [PeopleHiringController::class, 'dossier'])->whereNumber('process');
|
||||||
Route::post('pessoas/{process}/{command}', [PeopleHiringController::class, 'command'])->whereNumber('process')->whereIn('command', ['open', 'apply', 'close', 'evaluate', 'select', 'confirm', 'contract']);
|
Route::post('pessoas/{process}/{command}', [PeopleHiringController::class, 'command'])->whereNumber('process')->whereIn('command', ['open', 'apply', 'close', 'evaluate', 'select', 'confirm', 'contract']);
|
||||||
Route::get('administracao/parametrizacao', [OrganizationConfigurationController::class, 'index'])->name('organization.parameters');
|
Route::get('administracao/parametrizacao', [OrganizationConfigurationController::class, 'index'])->name('organization.parameters');
|
||||||
@@ -311,6 +317,13 @@ Route::middleware(['auth', 'verified', EnsureOrganizationAccess::class])->group(
|
|||||||
Route::post('orcamentos/{budget}/aprovar', [BudgetController::class, 'approve'])->name('budgets.approve');
|
Route::post('orcamentos/{budget}/aprovar', [BudgetController::class, 'approve'])->name('budgets.approve');
|
||||||
Route::get('equipamentos', [EquipmentController::class, 'index'])->name('equipment.index');
|
Route::get('equipamentos', [EquipmentController::class, 'index'])->name('equipment.index');
|
||||||
Route::get('projectos-imobilizado', [CapitalRegisterController::class, 'index'])->name('capital-register.index');
|
Route::get('projectos-imobilizado', [CapitalRegisterController::class, 'index'])->name('capital-register.index');
|
||||||
|
Route::get('ordens-operacionais', [OperationalOrdersController::class, 'index'])->name('operational-orders.index');
|
||||||
|
Route::post('ordens-operacionais/configuracao', [OperationalOrdersController::class, 'configure']);
|
||||||
|
Route::post('ordens-operacionais', [OperationalOrdersController::class, 'store']);
|
||||||
|
Route::get('requisicoes/{requisition}/ordens-operacionais', [OperationalOrdersController::class, 'index']);
|
||||||
|
Route::post('requisicoes/{requisition}/ordens-operacionais', [OperationalOrdersController::class, 'link']);
|
||||||
|
Route::get('requisicoes/{requisition}/urgencia-stock', [UrgentQuotationController::class, 'show']);
|
||||||
|
Route::post('requisicoes/{requisition}/urgencia-stock', [UrgentQuotationController::class, 'store']);
|
||||||
Route::get('administracao/prazos-aprovacao', [RequisitionExpiryController::class, 'settings'])->name('approval-timeouts.index');
|
Route::get('administracao/prazos-aprovacao', [RequisitionExpiryController::class, 'settings'])->name('approval-timeouts.index');
|
||||||
Route::get('administracao/revisao-urgencias', [UrgentRequisitionReviewController::class, 'settings'])->name('urgent-reviews.settings');
|
Route::get('administracao/revisao-urgencias', [UrgentRequisitionReviewController::class, 'settings'])->name('urgent-reviews.settings');
|
||||||
Route::post('administracao/revisao-urgencias', [UrgentRequisitionReviewController::class, 'saveSettings'])->name('urgent-reviews.settings.store');
|
Route::post('administracao/revisao-urgencias', [UrgentRequisitionReviewController::class, 'saveSettings'])->name('urgent-reviews.settings.store');
|
||||||
@@ -359,6 +372,7 @@ Route::middleware(['auth', 'verified', EnsureOrganizationAccess::class])->group(
|
|||||||
Route::post('conflitos', [ConflictDeclarationController::class, 'store'])->name('conflicts.store');
|
Route::post('conflitos', [ConflictDeclarationController::class, 'store'])->name('conflicts.store');
|
||||||
Route::get('conflitos/{declaration}', [ConflictDeclarationController::class, 'show'])->name('conflicts.show');
|
Route::get('conflitos/{declaration}', [ConflictDeclarationController::class, 'show'])->name('conflicts.show');
|
||||||
Route::put('conflitos/{declaration}', [ConflictDeclarationController::class, 'update'])->name('conflicts.update');
|
Route::put('conflitos/{declaration}', [ConflictDeclarationController::class, 'update'])->name('conflicts.update');
|
||||||
|
Route::post('conflitos/{declaration}/levantamento', [ConflictDeclarationController::class, 'authoriseRelease'])->name('conflicts.release');
|
||||||
Route::get('fornecedores', [SupplierController::class, 'index'])->name('suppliers.index');
|
Route::get('fornecedores', [SupplierController::class, 'index'])->name('suppliers.index');
|
||||||
Route::post('fornecedores', [SupplierController::class, 'store'])->name('suppliers.store');
|
Route::post('fornecedores', [SupplierController::class, 'store'])->name('suppliers.store');
|
||||||
Route::get('fornecedores/{supplier}', [SupplierController::class, 'show'])->name('suppliers.show');
|
Route::get('fornecedores/{supplier}', [SupplierController::class, 'show'])->name('suppliers.show');
|
||||||
|
|||||||
@@ -90,6 +90,9 @@ try {
|
|||||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ImportLegalRulesTest.php', 'tests/Feature/ImportTariffCodesTest.php',
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ImportLegalRulesTest.php', 'tests/Feature/ImportTariffCodesTest.php',
|
||||||
'tests/Feature/ImportReadinessTest.php', 'tests/Feature/ImportBankSupportTest.php', 'tests/Feature/OperationalHealthTest.php', 'tests/Feature/ImportDossierTest.php']];
|
'tests/Feature/ImportReadinessTest.php', 'tests/Feature/ImportBankSupportTest.php', 'tests/Feature/OperationalHealthTest.php', 'tests/Feature/ImportDossierTest.php']];
|
||||||
}
|
}
|
||||||
|
if (in_array('--legal-reference-focused', $argv, true)) {
|
||||||
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ImportLegalReferenceDraftsTest.php', 'tests/Feature/ImportLegalRulesTest.php']];
|
||||||
|
}
|
||||||
if (in_array('--legal-amounts-focused', $argv, true)) {
|
if (in_array('--legal-amounts-focused', $argv, true)) {
|
||||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ImportLegalEstimatesTest.php', 'tests/Feature/ImportLegalRulesTest.php',
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ImportLegalEstimatesTest.php', 'tests/Feature/ImportLegalRulesTest.php',
|
||||||
'tests/Feature/ImportEstimatesTest.php', 'tests/Feature/ImportEstimatePlanTest.php', 'tests/Feature/InternalRequisitionCandidateTest.php', 'tests/Feature/RequisitionApprovalLevelsTest.php']];
|
'tests/Feature/ImportEstimatesTest.php', 'tests/Feature/ImportEstimatePlanTest.php', 'tests/Feature/InternalRequisitionCandidateTest.php', 'tests/Feature/RequisitionApprovalLevelsTest.php']];
|
||||||
@@ -123,6 +126,9 @@ try {
|
|||||||
if (in_array('--urgent-review-focused', $argv, true)) {
|
if (in_array('--urgent-review-focused', $argv, true)) {
|
||||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionBudgetCyclesTest.php', '--filter=posterior urgent review|urgent review keeps indeterminate']];
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionBudgetCyclesTest.php', '--filter=posterior urgent review|urgent review keeps indeterminate']];
|
||||||
}
|
}
|
||||||
|
if (in_array('--conflict-release-focused', $argv, true)) {
|
||||||
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ConflictDeclarationTest.php']];
|
||||||
|
}
|
||||||
if (in_array('--cycle-history-focused', $argv, true)) {
|
if (in_array('--cycle-history-focused', $argv, true)) {
|
||||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionBudgetCyclesTest.php', 'tests/Feature/ImportEstimatesTest.php',
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionBudgetCyclesTest.php', 'tests/Feature/ImportEstimatesTest.php',
|
||||||
'--filter=native expiry returns the same request|expired import cycle preserves']];
|
'--filter=native expiry returns the same request|expired import cycle preserves']];
|
||||||
@@ -152,6 +158,24 @@ try {
|
|||||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionBudgetCyclesTest.php',
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionBudgetCyclesTest.php',
|
||||||
'tests/Feature/InternalRequisitionCandidateTest.php', 'tests/Feature/BudgetTest.php']];
|
'tests/Feature/InternalRequisitionCandidateTest.php', 'tests/Feature/BudgetTest.php']];
|
||||||
}
|
}
|
||||||
|
if (in_array('--operational-orders-focused', $argv, true)) {
|
||||||
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/OperationalOrdersTest.php', 'tests/Feature/PurchaseAwardOrderTest.php',
|
||||||
|
'--filter=operational register|utilisation mode|request links preserve|policy versions and company department|native orders freeze their production origin|metadata authority never opens']];
|
||||||
|
}
|
||||||
|
if (in_array('--operational-orders-access-only', $argv, true)) {
|
||||||
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/OperationalOrdersTest.php', '--filter=metadata authority never opens']];
|
||||||
|
}
|
||||||
|
if (in_array('--stock-use-minimum-focused', $argv, true)) {
|
||||||
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/SupplyPlanningTest.php',
|
||||||
|
'--filter=minimum stock is explicitly configured']];
|
||||||
|
}
|
||||||
|
if (in_array('--urgent-quotation-focused', $argv, true)) {
|
||||||
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/UrgentQuotationBasisTest.php', 'tests/Feature/PurchaseAwardOrderTest.php', 'tests/Feature/OrganizationConfigurationTest.php',
|
||||||
|
'--filter=urgent reduction|unmet minimum|urgent minimum is|native urgent order|comparison policy requires valid weights']];
|
||||||
|
}
|
||||||
|
if (in_array('--private-audit-focused', $argv, true)) {
|
||||||
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/PrivateAuditExporterTest.php', 'tests/Feature/PrivateAuditSourcesTest.php', 'tests/Feature/PrivateAuditAccessTest.php']];
|
||||||
|
}
|
||||||
if (in_array('--requisition-cycles-import-regression', $argv, true)) {
|
if (in_array('--requisition-cycles-import-regression', $argv, true)) {
|
||||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ImportEstimatesTest.php', 'tests/Feature/ImportLandedCostsTest.php']];
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ImportEstimatesTest.php', 'tests/Feature/ImportLandedCostsTest.php']];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -117,10 +117,11 @@ try {
|
|||||||
}
|
}
|
||||||
const raceOnly = process.argv.includes('--race-only');
|
const raceOnly = process.argv.includes('--race-only');
|
||||||
const recoveryOnly = process.argv.includes('--recovery-only');
|
const recoveryOnly = process.argv.includes('--recovery-only');
|
||||||
|
const nativeAuditSchemaOnly = process.argv.includes('--audit-schema-only');
|
||||||
const nativeFixtureOnly = process.argv.includes('--native-review-fixture-only');
|
const nativeFixtureOnly = process.argv.includes('--native-review-fixture-only');
|
||||||
const nativeHttpOnly = process.argv.includes('--native-review-http-only');
|
const nativeHttpOnly = process.argv.includes('--native-review-http-only');
|
||||||
const nativeOfficeOnly = process.argv.includes('--native-office-http-only');
|
const nativeOfficeOnly = process.argv.includes('--native-office-http-only');
|
||||||
const nativeReview = process.argv.includes('--native-review') || nativeFixtureOnly || nativeHttpOnly || nativeOfficeOnly;
|
const nativeReview = process.argv.includes('--native-review') || nativeFixtureOnly || nativeHttpOnly || nativeOfficeOnly || nativeAuditSchemaOnly;
|
||||||
const setupOnly = raceOnly || recoveryOnly || nativeReview;
|
const setupOnly = raceOnly || recoveryOnly || nativeReview;
|
||||||
const args = setupOnly ? ['artisan', 'migrate', '--force', '--no-interaction'] : process.argv.includes('--integrated-release-journeys') ? ['vendor/bin/pest', '--compact', 'tests/Feature/RequisitionLedgerAccountsTest.php', 'tests/Feature/RequisitionBudgetCyclesTest.php', 'tests/Feature/PurchaseAwardOrderTest.php', 'tests/Feature/ImportLandedCostsTest.php', '--filter=RequisitionBudgetCyclesTest|ImportLandedCostsTest|native office purchase|native partial-order|native consolidated order|native delivery analysis'] : process.argv.includes('--integrated-import-costs-only') ? ['vendor/bin/pest', '--compact', 'tests/Feature/ImportLandedCostsTest.php'] : process.argv.includes('--integrated-orders-only') ? ['vendor/bin/pest', '--compact', 'tests/Feature/PurchaseAwardOrderTest.php', '--filter=native partial-order|native consolidated order|native delivery analysis'] : process.argv.includes('--integrated-cycles-only') ? ['vendor/bin/pest', '--compact', 'tests/Feature/RequisitionBudgetCyclesTest.php'] : process.argv.includes('--office-process-only') ? ['vendor/bin/pest', '--compact', 'tests/Feature/RequisitionLedgerAccountsTest.php', '--filter=native office purchase'] : ['vendor/bin/pest', '--compact', 'tests/Feature/RequisitionLedgerAccountsTest.php', 'tests/Feature/PurchaseAwardOrderTest.php',
|
const args = setupOnly ? ['artisan', 'migrate', '--force', '--no-interaction'] : process.argv.includes('--integrated-release-journeys') ? ['vendor/bin/pest', '--compact', 'tests/Feature/RequisitionLedgerAccountsTest.php', 'tests/Feature/RequisitionBudgetCyclesTest.php', 'tests/Feature/PurchaseAwardOrderTest.php', 'tests/Feature/ImportLandedCostsTest.php', '--filter=RequisitionBudgetCyclesTest|ImportLandedCostsTest|native office purchase|native partial-order|native consolidated order|native delivery analysis'] : process.argv.includes('--integrated-import-costs-only') ? ['vendor/bin/pest', '--compact', 'tests/Feature/ImportLandedCostsTest.php'] : process.argv.includes('--integrated-orders-only') ? ['vendor/bin/pest', '--compact', 'tests/Feature/PurchaseAwardOrderTest.php', '--filter=native partial-order|native consolidated order|native delivery analysis'] : process.argv.includes('--integrated-cycles-only') ? ['vendor/bin/pest', '--compact', 'tests/Feature/RequisitionBudgetCyclesTest.php'] : process.argv.includes('--office-process-only') ? ['vendor/bin/pest', '--compact', 'tests/Feature/RequisitionLedgerAccountsTest.php', '--filter=native office purchase'] : ['vendor/bin/pest', '--compact', 'tests/Feature/RequisitionLedgerAccountsTest.php', 'tests/Feature/PurchaseAwardOrderTest.php',
|
||||||
'--filter=minimal purchasing catalogue|chart references reject|native line account assignment|classified line requires|native submission requires account|zero monetary line retains|native order preserves common ledger|native office purchase'];
|
'--filter=minimal purchasing catalogue|chart references reject|native line account assignment|classified line requires|native submission requires account|zero monetary line retains|native order preserves common ledger|native office purchase'];
|
||||||
@@ -190,15 +191,29 @@ try {
|
|||||||
if (seed.status !== 0) throw Error('Native review fixture failed: '+(seed.stderr || seed.stdout || '').replaceAll(password, '[private]'));
|
if (seed.status !== 0) throw Error('Native review fixture failed: '+(seed.stderr || seed.stdout || '').replaceAll(password, '[private]'));
|
||||||
const fixture = JSON.parse(seed.stdout);
|
const fixture = JSON.parse(seed.stdout);
|
||||||
fs.writeFileSync(path.join(root, 'native-review.json'), JSON.stringify(fixture));
|
fs.writeFileSync(path.join(root, 'native-review.json'), JSON.stringify(fixture));
|
||||||
const assets = path.join(privateParent, 'sgc-company-preparation-final-qa-20261128');
|
const assets = path.join(privateParent, 'sgc-private-audit-help-qa-20261128');
|
||||||
const manifest = fs.readFileSync(path.join(assets, 'manifest.json'));
|
const manifest = fs.readFileSync(path.join(assets, 'manifest.json'));
|
||||||
const manifestHash = crypto.createHash('sha256').update(manifest).digest('hex');
|
const manifestHash = crypto.createHash('sha256').update(manifest).digest('hex');
|
||||||
if (manifestHash !== 'df4e07d422af16897581371283d9730f41076ad2888d1e4911bdd7cadbb92c5f') throw Error('Unexpected private review manifest');
|
if (manifestHash !== 'fa87e37a3626ef75d22b5248dce9a0af2bad68c967e6f99bb64bc426a68f6aaf') throw Error('Unexpected private review manifest');
|
||||||
for (const entry of Object.values(JSON.parse(manifest))) {
|
for (const entry of Object.values(JSON.parse(manifest))) {
|
||||||
if (!fs.existsSync(path.join(assets, entry.file))) throw Error('Private review asset missing');
|
if (!fs.existsSync(path.join(assets, entry.file))) throw Error('Private review asset missing');
|
||||||
}
|
}
|
||||||
fs.cpSync(assets, path.join(root, 'public/build'), { recursive: true });
|
fs.cpSync(assets, path.join(root, 'public/build'), { recursive: true });
|
||||||
if (nativeFixtureOnly) {
|
if (nativeAuditSchemaOnly) {
|
||||||
|
if (!frozenRuntime || !process.argv.includes('--integrated-schema')) throw Error('Audit schema inventory requires the pinned private composition');
|
||||||
|
const schema = spawnSync('php', ['tests/Concurrency/requisition-account-worker.php', database, 'describe-private-audit-schema'], {
|
||||||
|
cwd: workspace, windowsHide: true, encoding: 'utf8', maxBuffer: 4 * 1024 * 1024,
|
||||||
|
env: { ...environment, SGC_REQUISITION_QA_ROOT: root },
|
||||||
|
});
|
||||||
|
if (schema.status !== 0) throw Error('Private audit schema inventory failed');
|
||||||
|
const inventory = JSON.parse(schema.stdout);
|
||||||
|
if (inventory.schema_only !== true || inventory.no_business_values !== true) throw Error('Schema-only contract refused');
|
||||||
|
const target = path.join(privateParent, 'private-audit-source-schema-20261128.json');
|
||||||
|
const bytes = JSON.stringify(inventory, null, 2)+'\n';
|
||||||
|
if (fs.existsSync(target) && fs.readFileSync(target, 'utf8') !== bytes) throw Error('Preserve the previous private schema inventory before replacing it');
|
||||||
|
fs.writeFileSync(target, bytes);
|
||||||
|
console.log(JSON.stringify({ private_audit_schema_inventory: true, tables: Object.keys(inventory.tables).length, business_values_exported: false, target }));
|
||||||
|
} else if (nativeFixtureOnly) {
|
||||||
console.log(JSON.stringify({ private_native_fixture_verified: true, ...fixture, private_manifest_sha256: manifestHash }));
|
console.log(JSON.stringify({ private_native_fixture_verified: true, ...fixture, private_manifest_sha256: manifestHash }));
|
||||||
} else {
|
} else {
|
||||||
const port = await new Promise((resolve, reject) => {
|
const port = await new Promise((resolve, reject) => {
|
||||||
@@ -243,7 +258,7 @@ try {
|
|||||||
console.log(JSON.stringify({ private_native_office_http_verified: true, ...result, private_manifest_sha256: manifestHash }));
|
console.log(JSON.stringify({ private_native_office_http_verified: true, ...result, private_manifest_sha256: manifestHash }));
|
||||||
} else if (nativeHttpOnly) {
|
} else if (nativeHttpOnly) {
|
||||||
const { verifyNativeReviewHttp } = await import('./requisition-native-http-check.mjs');
|
const { verifyNativeReviewHttp } = await import('./requisition-native-http-check.mjs');
|
||||||
const pageAssets = ['resources/js/pages/supply/index.tsx', 'resources/js/pages/purchase-controls/index.tsx', 'resources/js/pages/purchase-controls/orders.tsx', 'resources/js/pages/budgets/index.tsx', 'resources/js/pages/conflicts/index.tsx', 'resources/js/pages/conflicts/show.tsx', 'resources/js/pages/payments/index.tsx', 'resources/js/pages/stock/index.tsx', 'resources/js/pages/stock/operations.tsx', 'resources/js/pages/stock/lots.tsx', 'resources/js/pages/stock/reversals.tsx', 'resources/js/pages/stock/dispositions.tsx', 'resources/js/pages/equipment/index.tsx', 'resources/js/pages/investment/index.tsx', 'resources/js/pages/company/parameters.tsx', 'resources/js/pages/company/index.tsx', 'resources/js/pages/company/setup.tsx']
|
const pageAssets = ['resources/js/pages/audit/private.tsx', 'resources/js/pages/supply/index.tsx', 'resources/js/pages/purchase-controls/index.tsx', 'resources/js/pages/purchase-controls/orders.tsx', 'resources/js/pages/budgets/index.tsx', 'resources/js/pages/conflicts/index.tsx', 'resources/js/pages/conflicts/show.tsx', 'resources/js/pages/payments/index.tsx', 'resources/js/pages/stock/index.tsx', 'resources/js/pages/stock/operations.tsx', 'resources/js/pages/stock/lots.tsx', 'resources/js/pages/stock/reversals.tsx', 'resources/js/pages/stock/dispositions.tsx', 'resources/js/pages/equipment/index.tsx', 'resources/js/pages/investment/index.tsx', 'resources/js/pages/company/parameters.tsx', 'resources/js/pages/company/index.tsx', 'resources/js/pages/company/setup.tsx', 'resources/js/pages/requisitions/operational-orders.tsx', 'resources/js/pages/requisitions/urgent-stock.tsx']
|
||||||
.map(key => JSON.parse(manifest)[key]);
|
.map(key => JSON.parse(manifest)[key]);
|
||||||
const result = await verifyNativeReviewHttp(url, fixture, {
|
const result = await verifyNativeReviewHttp(url, fixture, {
|
||||||
assets: pageAssets.map(entry => ({ file: entry.file, sha256: crypto.createHash('sha256').update(fs.readFileSync(path.join(assets, entry.file))).digest('hex') })),
|
assets: pageAssets.map(entry => ({ file: entry.file, sha256: crypto.createHash('sha256').update(fs.readFileSync(path.join(assets, entry.file))).digest('hex') })),
|
||||||
|
|||||||
@@ -19,11 +19,25 @@ export async function verifyNativeReviewHttp(origin, fixture, { assets, snapshot
|
|||||||
const reviewer = client();
|
const reviewer = client();
|
||||||
const auditor = client();
|
const auditor = client();
|
||||||
const requester = client();
|
const requester = client();
|
||||||
|
const privateAuditor = client();
|
||||||
await reviewer.login(fixture.synthetic_login);
|
await reviewer.login(fixture.synthetic_login);
|
||||||
await auditor.login(fixture.synthetic_metadata_login);
|
await auditor.login(fixture.synthetic_metadata_login);
|
||||||
await requester.login(fixture.synthetic_requester_login);
|
await requester.login(fixture.synthetic_requester_login);
|
||||||
|
await privateAuditor.login(fixture.synthetic_private_audit_login);
|
||||||
// Login/logout may legitimately rotate native authentication fields. Compare the read window only.
|
// Login/logout may legitimately rotate native authentication fields. Compare the read window only.
|
||||||
const before = await snapshot();
|
const before = await snapshot();
|
||||||
|
const privateAudit = await privateAuditor.page('/auditoria/privada', 'audit/private');
|
||||||
|
check(privateAudit.props.families.length === 4 && privateAudit.props.exports.data.length === 0, 'dedicated private authority opens approved families without generating a package');
|
||||||
|
for (const actor of [reviewer, auditor, requester]) check((await actor.request('/auditoria/privada')).status === 403, 'other authorities cannot open private audit');
|
||||||
|
check((await privateAuditor.request('/orcamentos')).status === 403, 'private audit never grants native financial workspace');
|
||||||
|
const operationalOrders = await reviewer.page('/ordens-operacionais', 'requisitions/operational-orders');
|
||||||
|
check((await auditor.request('/ordens-operacionais')).status === 403, 'metadata authority never grants operational order register access');
|
||||||
|
check(operationalOrders.props.canConfigure === true && operationalOrders.props.policy === null, 'native admin can configure origin but a GET does not select an origin');
|
||||||
|
const ownOperationalOrders = await requester.page('/ordens-operacionais', 'requisitions/operational-orders');
|
||||||
|
check(ownOperationalOrders.props.canConfigure === false && ownOperationalOrders.props.allowedTypes.length === 0, 'requester receives no production workshop or procurement order creation grant');
|
||||||
|
const urgentStock = await reviewer.page(`/requisicoes/${fixture.historical_decision_request}/urgencia-stock`, 'requisitions/urgent-stock');
|
||||||
|
check(urgentStock.props.eligible.length === 0, 'ordinary historical source receives no implicit urgent reduction');
|
||||||
|
check((await requester.request(`/requisicoes/${fixture.historical_decision_request}/urgencia-stock`)).status === 403, 'request ownership does not grant stock threshold preparation or quotation oversight');
|
||||||
const budgets = await reviewer.page('/orcamentos', 'budgets/index');
|
const budgets = await reviewer.page('/orcamentos', 'budgets/index');
|
||||||
check(budgets.props.budgets.length > 0, 'native synthetic budget is visible to its authorised reader');
|
check(budgets.props.budgets.length > 0, 'native synthetic budget is visible to its authorised reader');
|
||||||
const budgetHeaders = await reviewer.request('/orcamentos');
|
const budgetHeaders = await reviewer.request('/orcamentos');
|
||||||
@@ -93,10 +107,24 @@ export async function verifyNativeReviewHttp(origin, fixture, { assets, snapshot
|
|||||||
check(await csv(reviewer) === await csv(auditor), 'both metadata grants export the same scoped metadata without private context');
|
check(await csv(reviewer) === await csv(auditor), 'both metadata grants export the same scoped metadata without private context');
|
||||||
const after = await snapshot();
|
const after = await snapshot();
|
||||||
check(JSON.stringify(before) === JSON.stringify(after), 'all native table rows and columns unchanged during read window');
|
check(JSON.stringify(before) === JSON.stringify(after), 'all native table rows and columns unchanged during read window');
|
||||||
|
const auditInput = {operation_key: crypto.randomUUID(), families: ['purchasing', 'stock', 'finance', 'configuration'], purpose: 'Owned synthetic native QA export'};
|
||||||
|
await privateAuditor.post('/auditoria/privada', auditInput);
|
||||||
|
const prepared = await privateAuditor.page('/auditoria/privada', 'audit/private');
|
||||||
|
check(prepared.props.exports.data.length === 1, 'one private package prepared after the unchanged read window');
|
||||||
|
const packageRow = prepared.props.exports.data[0];
|
||||||
|
const download = await privateAuditor.request(packageRow.download_url);
|
||||||
|
check(download.status === 200 && download.headers.get('Cache-Control')?.includes('no-store'), 'authenticated private package download');
|
||||||
|
const bytes = Buffer.from(await download.arrayBuffer());
|
||||||
|
check(bytes.length === packageRow.size && crypto.createHash('sha256').update(bytes).digest('hex') === packageRow.sha256, 'native download bytes match immutable package size and SHA256');
|
||||||
|
await privateAuditor.post('/auditoria/privada', auditInput);
|
||||||
|
const replay = await privateAuditor.page('/auditoria/privada', 'audit/private');
|
||||||
|
check(replay.props.exports.data.length === 1 && replay.props.exports.data[0].sha256 === packageRow.sha256, 'replay preserves the same archive');
|
||||||
|
check((await auditor.request(packageRow.download_url)).status === 403, 'metadata cannot download private package');
|
||||||
await reviewer.logout();
|
await reviewer.logout();
|
||||||
await auditor.logout();
|
await auditor.logout();
|
||||||
await requester.logout();
|
await requester.logout();
|
||||||
return { checks, fortify_sessions: 3, missing_csrf_refused: true, stale_inertia_version_refused: true, supply_views: 9, purchase_control_views: 2, requester_scope_verified: true, encrypted_history_verified: true,
|
await privateAuditor.logout();
|
||||||
budget_view_verified: true, conflict_index_verified: true, stock_views_verified: 2, equipment_view_verified: true, investment_view_verified: true, company_configuration_verified: true, metadata_scope_isolation_verified: true, readonly_tables_equal: Object.keys(before).length,
|
return { checks, fortify_sessions: 4, missing_csrf_refused: true, stale_inertia_version_refused: true, supply_views: 9, purchase_control_views: 2, requester_scope_verified: true, encrypted_history_verified: true,
|
||||||
private_asset_verified: true, private_assets_verified: assets.length, business_commands_sent: 0, browser_visual_acceptance: false };
|
budget_view_verified: true, conflict_index_verified: true, stock_views_verified: 2, equipment_view_verified: true, investment_view_verified: true, company_configuration_verified: true, operational_orders_verified: true, urgent_stock_verified: true, metadata_scope_isolation_verified: true, readonly_tables_equal: Object.keys(before).length,
|
||||||
|
private_asset_verified: true, private_assets_verified: assets.length, business_commands_sent: 0, audit_export_commands_sent: 2, private_audit_download_verified: true, browser_visual_acceptance: false };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ use Tempo\Finance\GeneralLedger\LedgerSchema;
|
|||||||
|
|
||||||
require __DIR__.'/../../vendor/autoload.php';
|
require __DIR__.'/../../vendor/autoload.php';
|
||||||
$app = require __DIR__.'/../../bootstrap/app.php';
|
$app = require __DIR__.'/../../bootstrap/app.php';
|
||||||
if (in_array($argv[2] ?? '', ['prepare-native-review', 'read-office-purchase'], true)) {
|
if (in_array($argv[2] ?? '', ['prepare-native-review', 'read-office-purchase', 'describe-private-audit-schema'], true)) {
|
||||||
$privateRoot = realpath(getenv('SGC_REQUISITION_QA_ROOT') ?: '');
|
$privateRoot = realpath(getenv('SGC_REQUISITION_QA_ROOT') ?: '');
|
||||||
$boundary = realpath(__DIR__.'/../../storage/framework/testing');
|
$boundary = realpath(__DIR__.'/../../storage/framework/testing');
|
||||||
$databaseName = getenv('DB_DATABASE') ?: '';
|
$databaseName = getenv('DB_DATABASE') ?: '';
|
||||||
@@ -42,6 +42,21 @@ if ($mode === 'prepare-native-review') {
|
|||||||
echo json_encode(requisitionAccountsNativeReviewFixture(getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') === '1', getenv('RQ01_NATIVE_OFFICE_JOURNEY') === '1'), JSON_THROW_ON_ERROR);
|
echo json_encode(requisitionAccountsNativeReviewFixture(getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') === '1', getenv('RQ01_NATIVE_OFFICE_JOURNEY') === '1'), JSON_THROW_ON_ERROR);
|
||||||
exit;
|
exit;
|
||||||
}
|
}
|
||||||
|
if ($mode === 'describe-private-audit-schema') {
|
||||||
|
$columns = DB::transaction(function () {
|
||||||
|
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||||
|
$schema = DB::getSchemaBuilder();
|
||||||
|
$result = [];
|
||||||
|
foreach ($schema->getTableListing() as $table) {
|
||||||
|
$result[$table] = $schema->getColumnListing($table);
|
||||||
|
}
|
||||||
|
ksort($result);
|
||||||
|
|
||||||
|
return $result;
|
||||||
|
});
|
||||||
|
echo json_encode(['schema_only' => true, 'no_business_values' => true, 'tables' => $columns], JSON_THROW_ON_ERROR);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
if ($mode === 'read-office-purchase') {
|
if ($mode === 'read-office-purchase') {
|
||||||
if (getenv('RQ01_NATIVE_OFFICE_JOURNEY') !== '1') {
|
if (getenv('RQ01_NATIVE_OFFICE_JOURNEY') !== '1') {
|
||||||
throw new LogicException('Office HTTP assertions require their explicit synthetic composition.');
|
throw new LogicException('Office HTTP assertions require their explicit synthetic composition.');
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
use App\Enums\PurchasingRole;
|
use App\Enums\PurchasingRole;
|
||||||
use App\Models\AuditLog;
|
use App\Models\AuditLog;
|
||||||
use App\Models\ConflictDeclaration;
|
use App\Models\ConflictDeclaration;
|
||||||
|
use App\Models\ConflictRelease;
|
||||||
use App\Models\CostCenter;
|
use App\Models\CostCenter;
|
||||||
use App\Models\Department;
|
use App\Models\Department;
|
||||||
use App\Models\ProposalEvaluation;
|
use App\Models\ProposalEvaluation;
|
||||||
@@ -13,6 +14,8 @@ use App\Models\Tenant;
|
|||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Services\ConflictGuard;
|
use App\Services\ConflictGuard;
|
||||||
use App\Services\RequisitionWorkflow;
|
use App\Services\RequisitionWorkflow;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
use Inertia\Testing\AssertableInertia as Assert;
|
use Inertia\Testing\AssertableInertia as Assert;
|
||||||
|
|
||||||
function personalConflict(int $supplierId, ?int $requisitionId = null, bool $hasConflict = true): array
|
function personalConflict(int $supplierId, ?int $requisitionId = null, bool $hasConflict = true): array
|
||||||
@@ -20,6 +23,76 @@ function personalConflict(int $supplierId, ?int $requisitionId = null, bool $has
|
|||||||
return ['scope' => $requisitionId ? 'process_supplier' : 'supplier', 'supplier_id' => $supplierId, 'requisition_id' => $requisitionId, 'has_conflict' => $hasConflict, 'known_since' => now()->subYears(3)->format('Y-m-d'), 'reason' => 'Relação pessoal relevante declarada para efeitos de transparência.'];
|
return ['scope' => $requisitionId ? 'process_supplier' : 'supplier', 'supplier_id' => $supplierId, 'requisition_id' => $requisitionId, 'has_conflict' => $hasConflict, 'known_since' => now()->subYears(3)->format('Y-m-d'), 'reason' => 'Relação pessoal relevante declarada para efeitos de transparência.'];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function configureConflictDirection(User $user): int
|
||||||
|
{
|
||||||
|
$db = DB::class;
|
||||||
|
$db::table('organization_access')->insert(['tenant_id' => $user->tenant_id, 'active' => true, 'version' => 1, 'created_at' => now(), 'updated_at' => now()]);
|
||||||
|
$profile = $db::table('organization_profiles')->insertGetId(['tenant_id' => $user->tenant_id, 'name' => 'Direcção da empresa', 'permissions' => json_encode(['conflict_release_authorise']), 'version' => 1, 'created_at' => now(), 'updated_at' => now()]);
|
||||||
|
|
||||||
|
return $db::table('organization_memberships')->insertGetId(['tenant_id' => $user->tenant_id, 'user_id' => $user->id, 'profile_id' => $profile, 'maintenance' => false, 'created_at' => now(), 'updated_at' => now()]);
|
||||||
|
}
|
||||||
|
|
||||||
|
test('direction release preserves declarations applies to the complete correction chain and replays once', function () {
|
||||||
|
config(['conflict-releases.qa_enabled' => true]);
|
||||||
|
$this->post('/conflitos', personalConflict($this->supplier->id))->assertSessionHasNoErrors();
|
||||||
|
$root = ConflictDeclaration::query()->firstOrFail();
|
||||||
|
$this->put('/conflitos/'.$root->id, ['reason' => 'Fundamento corrigido antes da decisão da direcção.', 'known_since' => now()->format('Y-m-d')])->assertSessionHasNoErrors();
|
||||||
|
$latest = ConflictDeclaration::query()->latest('id')->firstOrFail();
|
||||||
|
$before = ConflictDeclaration::query()->get()->toArray();
|
||||||
|
$input = ['operation_key' => (string) Str::uuid(), 'reason' => 'Direcção autoriza expressamente o levantamento deste impedimento.'];
|
||||||
|
$guard = app(ConflictGuard::class);
|
||||||
|
expect($guard->hasConflict($this->buyer->id, $this->supplier->id, $this->r->id))->toBeTrue();
|
||||||
|
$this->actingAs($this->admin)->post('/conflitos/'.$latest->id.'/levantamento', $input)->assertForbidden();
|
||||||
|
configureConflictDirection($this->admin);
|
||||||
|
$this->post('/conflitos/'.$root->id.'/levantamento', $input)->assertConflict();
|
||||||
|
$this->get('/conflitos/'.$root->id)->assertInertia(fn (Assert $page) => $page->where('canAuthoriseRelease', true));
|
||||||
|
$this->post('/conflitos/'.$latest->id.'/levantamento', $input)->assertSessionHasNoErrors()->assertRedirect();
|
||||||
|
$this->post('/conflitos/'.$latest->id.'/levantamento', $input)->assertSessionHasNoErrors()->assertRedirect();
|
||||||
|
expect($guard->hasConflict($this->buyer->id, $this->supplier->id, $this->r->id))->toBeFalse()
|
||||||
|
->and(ConflictDeclaration::query()->get()->toArray())->toBe($before)
|
||||||
|
->and(ConflictRelease::query()->count())->toBe(1)
|
||||||
|
->and(AuditLog::query()->where('action', 'conflict.release_authorised')->count())->toBe(1);
|
||||||
|
$this->get('/conflitos/'.$root->id)->assertInertia(fn (Assert $page) => $page->where('canAuthoriseRelease', false)->where('release.declaration_id', $latest->id));
|
||||||
|
$this->post('/conflitos/'.$latest->id.'/levantamento', [...$input, 'reason' => 'Alteração indevida do fundamento após decisão.'])->assertConflict();
|
||||||
|
ConflictDeclaration::query()->create([...$root->only(['tenant_id', 'user_id', 'supplier_id', 'requisition_id', 'has_conflict', 'known_since', 'reason']), 'declared_at' => now()]);
|
||||||
|
expect($guard->hasConflict($this->buyer->id, $this->supplier->id, $this->r->id))->toBeTrue();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('direction authority is current scoped and never inherited from admin or finance', function () {
|
||||||
|
config(['conflict-releases.qa_enabled' => true]);
|
||||||
|
$this->post('/conflitos', personalConflict($this->supplier->id))->assertSessionHasNoErrors();
|
||||||
|
$root = ConflictDeclaration::query()->firstOrFail();
|
||||||
|
$input = ['operation_key' => (string) Str::uuid(), 'reason' => 'Autorização expressa da direcção para este conflito.'];
|
||||||
|
$url = '/conflitos/'.$root->id.'/levantamento';
|
||||||
|
$this->actingAs($this->finance)->post($url, $input)->assertForbidden();
|
||||||
|
$membership = configureConflictDirection($this->admin);
|
||||||
|
$this->actingAs($this->admin);
|
||||||
|
DB::table('organization_memberships')->where('id', $membership)->update(['expires_at' => now()->subMinute()]);
|
||||||
|
$this->post($url, $input)->assertForbidden();
|
||||||
|
DB::table('organization_memberships')->where('id', $membership)->update(['expires_at' => null, 'maintenance' => true]);
|
||||||
|
$this->post($url, $input)->assertForbidden();
|
||||||
|
DB::table('organization_memberships')->where('id', $membership)->update(['maintenance' => false]);
|
||||||
|
$this->post($url, [...$input, 'reason' => 'curto'])->assertSessionHasErrors('reason');
|
||||||
|
$other = Tenant::query()->create(['name' => 'Outra empresa sintética']);
|
||||||
|
$foreign = User::factory()->create(['tenant_id' => $other->id, 'purchasing_role' => PurchasingRole::Configured]);
|
||||||
|
configureConflictDirection($foreign);
|
||||||
|
$this->actingAs($foreign)->post($url, $input)->assertNotFound();
|
||||||
|
expect(ConflictRelease::query()->withoutGlobalScopes()->count())->toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('release capability remains disabled by default and release evidence is append only', function () {
|
||||||
|
$this->post('/conflitos', personalConflict($this->supplier->id))->assertSessionHasNoErrors();
|
||||||
|
$root = ConflictDeclaration::query()->firstOrFail();
|
||||||
|
configureConflictDirection($this->admin);
|
||||||
|
$input = ['operation_key' => (string) Str::uuid(), 'reason' => 'Direcção autoriza o levantamento com fundamento registado.'];
|
||||||
|
$this->actingAs($this->admin)->post('/conflitos/'.$root->id.'/levantamento', $input)->assertStatus(503);
|
||||||
|
config(['conflict-releases.qa_enabled' => true]);
|
||||||
|
$this->post('/conflitos/'.$root->id.'/levantamento', $input)->assertSessionHasNoErrors();
|
||||||
|
$release = ConflictRelease::query()->firstOrFail();
|
||||||
|
expect(fn () => $release->update(['reason' => 'Outro fundamento']))->toThrow(LogicException::class);
|
||||||
|
expect(fn () => $release->delete())->toThrow(LogicException::class);
|
||||||
|
});
|
||||||
|
|
||||||
beforeEach(function () {
|
beforeEach(function () {
|
||||||
$this->tenant = Tenant::query()->create(['name' => 'Conflitos A']);
|
$this->tenant = Tenant::query()->create(['name' => 'Conflitos A']);
|
||||||
$this->department = Department::query()->create(['tenant_id' => $this->tenant->id, 'name' => 'Operações']);
|
$this->department = Department::query()->create(['tenant_id' => $this->tenant->id, 'name' => 'Operações']);
|
||||||
|
|||||||
@@ -0,0 +1,65 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Models\SupplyRecord;
|
||||||
|
use App\Services\ImportLegalReferenceDrafts;
|
||||||
|
use App\Services\ImportLegalRules;
|
||||||
|
use Illuminate\Http\UploadedFile;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Storage;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
|
||||||
|
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||||
|
require_once __DIR__.'/../Support/SupplyFixture.php';
|
||||||
|
|
||||||
|
beforeEach(function () {
|
||||||
|
config(['import-tariffs.qa_enabled' => true, 'import-legal.qa_enabled' => true]);
|
||||||
|
Storage::fake('local');
|
||||||
|
$this->f = receiptFixture();
|
||||||
|
supplyGrant($this->f['issuer'], ['procurement', 'import_customs']);
|
||||||
|
$this->actingAs($this->f['issuer']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a supplied official edition offers exact documentary drafts without publishing rules or changing financial facts', function () {
|
||||||
|
$path = 'C:/Mac/Home/Documents/TEMPO/Portal Tempo/Legislacao/novas/BR_248_I_SERIE_SUPLEMENTO_2025.pdf';
|
||||||
|
if (! is_file($path)) {
|
||||||
|
test()->markTestSkipped('The owner supplied original is required for this real-source integration.');
|
||||||
|
}
|
||||||
|
expect(hash_file('sha256', $path))->toBe(ImportLegalReferenceDrafts::EDITION_SHA256);
|
||||||
|
$before = [];
|
||||||
|
foreach (['budget_entries', 'stock_movements', 'purchase_orders', 'invoices'] as $table) {
|
||||||
|
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
|
||||||
|
}
|
||||||
|
$service = app(ImportLegalRules::class);
|
||||||
|
$source = $service->save($this->f['issuer'], ['operation_key' => (string) Str::uuid(), 'action' => 'source', 'version' => 0,
|
||||||
|
'official_reference' => 'BR I Série 248, suplemento, 29/12/2025; Lei 8/2025',
|
||||||
|
'reason' => 'Actual supplied official original copied only to synthetic isolated QA; no rule publication.'],
|
||||||
|
new UploadedFile($path, basename($path), 'application/pdf', UPLOAD_ERR_OK, true));
|
||||||
|
$workspace = $service->workspace($this->f['issuer'], $this->f['r']);
|
||||||
|
$drafts = $workspace['referenceDrafts'];
|
||||||
|
expect($drafts)->toHaveCount(11)
|
||||||
|
->and(array_column($drafts, 'code'))->toContain('3506.91.20', '7604.10.10')
|
||||||
|
->and($drafts[0]['rate_percent'])->toBe('20')
|
||||||
|
->and($drafts[2]['rate_percent'])->toBe('7.5')
|
||||||
|
->and($drafts[0]['valid_from'])->toBe('2026-01-01')
|
||||||
|
->and($drafts[0]['citation'])->toContain('2180-(4)')
|
||||||
|
->and($drafts[0]['source_id'])->toBe($source->id)
|
||||||
|
->and($drafts[0]['charges'][0]['kind'])->toBe('duty')
|
||||||
|
->and($workspace['referenceDraftWarnings'])->toBe([])
|
||||||
|
->and(SupplyRecord::query()->where('kind', 'import_legal_rule')->count())->toBe(0)
|
||||||
|
->and(json_encode($workspace['sources'], JSON_THROW_ON_ERROR))->not->toContain('import-legal/');
|
||||||
|
foreach ($before as $table => $rows) {
|
||||||
|
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
|
||||||
|
}
|
||||||
|
Storage::disk('local')->put($source->snapshot['evidence']['path'], 'ALTERED-SYNTHETIC-COPY');
|
||||||
|
$workspace = $service->workspace($this->f['issuer'], $this->f['r']);
|
||||||
|
expect($workspace['referenceDrafts'])->toBe([])
|
||||||
|
->and($workspace['referenceDraftWarnings'])->toHaveCount(1)
|
||||||
|
->and($workspace['referenceDraftWarnings'][0]['source_id'])->toBe($source->id)
|
||||||
|
->and(hash_file('sha256', $path))->toBe(ImportLegalReferenceDrafts::EDITION_SHA256);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an unknown edition never inherits parameters from its title or citation', function () {
|
||||||
|
$source = new SupplyRecord(['kind' => 'import_legal_source', 'data' => ['official_reference' => 'Lei 8/2025'],
|
||||||
|
'snapshot' => ['evidence' => ['sha256' => hash('sha256', 'different edition')]]]);
|
||||||
|
expect(app(ImportLegalReferenceDrafts::class)->forSource($source))->toBe([]);
|
||||||
|
});
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Enums\PurchasingRole;
|
||||||
|
use App\Models\Department;
|
||||||
|
use App\Models\SupplyRecord;
|
||||||
|
use App\Models\Tenant;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\OperationalOrders;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Illuminate\Validation\ValidationException;
|
||||||
|
use Inertia\Testing\AssertableInertia as Assert;
|
||||||
|
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||||
|
|
||||||
|
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||||
|
require_once __DIR__.'/../Support/SupplyFixture.php';
|
||||||
|
|
||||||
|
beforeEach(function () {
|
||||||
|
$this->withoutVite();
|
||||||
|
$this->f = receiptFixture();
|
||||||
|
$this->admin = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Admin]);
|
||||||
|
$this->policy = ['version' => 0, 'mode' => 'procurement', 'reason' => 'Locais ainda não abrangidos pela aplicação de compras.', 'operation_key' => (string) Str::uuid()];
|
||||||
|
$this->input = ['type' => 'production', 'reference' => 'OP-SYNTHETIC-001', 'department_id' => $this->f['department']->id,
|
||||||
|
'utilisation_location' => 'Linha de produção exclusivamente sintética', 'description' => 'Produção fictícia para comprovar a ordem de origem.',
|
||||||
|
'reason' => 'Registo sintético pelo agente de procurement.', 'policy_version' => 1, 'operation_key' => (string) Str::uuid()];
|
||||||
|
$this->actingAs($this->admin);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('operational register requires explicit origin mode preserves sources and has no financial or stock effects', function () {
|
||||||
|
$this->get('/ordens-operacionais')->assertStatus(503);
|
||||||
|
config(['operational-orders.qa_enabled' => true]);
|
||||||
|
$before = [];
|
||||||
|
foreach (['budget_entries', 'stock_movements', 'invoices', 'purchase_orders'] as $table) {
|
||||||
|
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
|
||||||
|
}
|
||||||
|
$this->actingAs($this->f['issuer'])->post('/ordens-operacionais', $this->input)->assertForbidden();
|
||||||
|
$this->actingAs($this->admin)->post('/ordens-operacionais/configuracao', $this->policy)->assertSessionHasNoErrors()->assertRedirect();
|
||||||
|
$this->post('/ordens-operacionais', $this->input)->assertForbidden();
|
||||||
|
$this->actingAs($this->f['issuer'])->post('/ordens-operacionais', $this->input)->assertSessionHasNoErrors()->assertRedirect();
|
||||||
|
$this->post('/ordens-operacionais', $this->input)->assertSessionHasNoErrors()->assertRedirect();
|
||||||
|
$order = SupplyRecord::query()->where('kind', 'op_order')->firstOrFail();
|
||||||
|
expect($order->snapshot['author']['id'])->toBe($this->f['issuer']->id)
|
||||||
|
->and($order->snapshot['policy']['data']['mode'])->toBe('procurement')
|
||||||
|
->and(SupplyRecord::query()->where('kind', 'op_order')->count())->toBe(1);
|
||||||
|
foreach (SupplyRecord::query()->pluck('kind') as $kind) {
|
||||||
|
expect(strlen($kind))->toBeLessThanOrEqual(20);
|
||||||
|
}
|
||||||
|
$this->post('/ordens-operacionais', [...$this->input, 'description' => 'Payload alterado na mesma operação.'])->assertConflict();
|
||||||
|
$this->post('/ordens-operacionais', [...$this->input, 'operation_key' => (string) Str::uuid()])->assertConflict();
|
||||||
|
$response = $this->get('/ordens-operacionais')->assertOk()->assertInertia(fn (Assert $page) => $page->component('requisitions/operational-orders')->has('orders.data', 1));
|
||||||
|
$response->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true);
|
||||||
|
expect($response->headers->get('Cache-Control'))->toContain('private')->toContain('no-store');
|
||||||
|
foreach ($before as $table => $rows) {
|
||||||
|
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('utilisation mode uses explicit production and workshop responsibilities without a procurement fallback', function () {
|
||||||
|
config(['operational-orders.qa_enabled' => true]);
|
||||||
|
$this->post('/ordens-operacionais/configuracao', [...$this->policy, 'mode' => 'utilisation'])->assertSessionHasNoErrors()->assertRedirect();
|
||||||
|
$this->actingAs($this->f['issuer'])->post('/ordens-operacionais', $this->input)->assertForbidden();
|
||||||
|
DB::table('organization_access')->insert(['tenant_id' => $this->f['tenant']->id, 'active' => true, 'version' => 1, 'created_at' => now(), 'updated_at' => now()]);
|
||||||
|
foreach (['production', 'maintenance'] as $type) {
|
||||||
|
$person = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Configured]);
|
||||||
|
$profile = DB::table('organization_profiles')->insertGetId(['tenant_id' => $person->tenant_id, 'name' => $type, 'permissions' => json_encode([$type.'_order_prepare']), 'version' => 1, 'created_at' => now(), 'updated_at' => now()]);
|
||||||
|
$membership = DB::table('organization_memberships')->insertGetId(['tenant_id' => $person->tenant_id, 'user_id' => $person->id, 'profile_id' => $profile, 'maintenance' => false, 'created_at' => now(), 'updated_at' => now()]);
|
||||||
|
$input = [...$this->input, 'type' => $type, 'reference' => 'SYNTHETIC-'.$type, 'operation_key' => (string) Str::uuid()];
|
||||||
|
$this->actingAs($person)->post('/ordens-operacionais', $input)->assertSessionHasNoErrors()->assertRedirect();
|
||||||
|
$this->post('/ordens-operacionais', [...$input, 'type' => $type === 'production' ? 'maintenance' : 'production', 'operation_key' => (string) Str::uuid()])->assertForbidden();
|
||||||
|
DB::table('organization_memberships')->where('id', $membership)->update(['expires_at' => now()->subMinute()]);
|
||||||
|
$this->post('/ordens-operacionais', $input)->assertForbidden();
|
||||||
|
}
|
||||||
|
expect(SupplyRecord::query()->where('kind', 'op_order')->count())->toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('request links preserve original order and line basis reject stale changes and cannot be changed after submission', function () {
|
||||||
|
config(['operational-orders.qa_enabled' => true]);
|
||||||
|
$this->post('/ordens-operacionais/configuracao', $this->policy)->assertSessionHasNoErrors()->assertRedirect();
|
||||||
|
$this->actingAs($this->f['issuer'])->post('/ordens-operacionais', $this->input)->assertSessionHasNoErrors()->assertRedirect();
|
||||||
|
$source = SupplyRecord::query()->where('kind', 'op_order')->firstOrFail();
|
||||||
|
$request = $this->f['r'];
|
||||||
|
$request->update(['status' => 'draft']);
|
||||||
|
$item = $request->items()->firstOrFail();
|
||||||
|
$item->update(['category_context' => ['version' => 1, 'category' => 'production_input', 'reason' => null]]);
|
||||||
|
$service = app(OperationalOrders::class);
|
||||||
|
expect(fn () => $service->assertSubmission($this->f['issuer'], $request))->toThrow(ValidationException::class);
|
||||||
|
$input = ['item_id' => $item->id, 'order_id' => $source->id, 'version' => 0, 'reason' => 'Ligação documental à produção solicitada.', 'operation_key' => (string) Str::uuid()];
|
||||||
|
$url = '/requisicoes/'.$request->id.'/ordens-operacionais';
|
||||||
|
$this->post($url, $input)->assertSessionHasNoErrors()->assertRedirect();
|
||||||
|
$this->post($url, $input)->assertSessionHasNoErrors()->assertRedirect();
|
||||||
|
$service->assertSubmission($this->f['issuer'], $request);
|
||||||
|
$frozen = $service->freezeForItems($this->f['issuer'], [$item->id]);
|
||||||
|
expect($frozen[$item->id]['snapshot']['source']['id'])->toBe($source->id)
|
||||||
|
->and($frozen[$item->id]['snapshot']['source']['snapshot']['author']['id'])->toBe($this->f['issuer']->id);
|
||||||
|
$this->post($url, [...$input, 'operation_key' => (string) Str::uuid()])->assertConflict();
|
||||||
|
$item->update(['description' => 'Alteração posterior exige nova ligação.']);
|
||||||
|
expect(fn () => $service->freezeForItems($this->f['issuer'], [$item->id]))->toThrow(HttpException::class);
|
||||||
|
$this->post($url, [...$input, 'version' => 1, 'operation_key' => (string) Str::uuid()])->assertSessionHasNoErrors()->assertRedirect();
|
||||||
|
$request->update(['status' => 'pending']);
|
||||||
|
$this->post($url, [...$input, 'version' => 2, 'operation_key' => (string) Str::uuid()])->assertConflict();
|
||||||
|
expect(SupplyRecord::query()->where('kind', 'op_order_link')->count())->toBe(2);
|
||||||
|
config(['operational-orders.qa_enabled' => false]);
|
||||||
|
expect(fn () => $service->freezeForItems($this->f['issuer'], [$item->id]))->toThrow(HttpException::class);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('policy versions and company department isolation are enforced on original orders', function () {
|
||||||
|
config(['operational-orders.qa_enabled' => true]);
|
||||||
|
$this->post('/ordens-operacionais/configuracao', $this->policy)->assertSessionHasNoErrors()->assertRedirect();
|
||||||
|
$this->post('/ordens-operacionais/configuracao', [...$this->policy, 'operation_key' => (string) Str::uuid()])->assertConflict();
|
||||||
|
$this->actingAs($this->f['issuer'])->post('/ordens-operacionais', [...$this->input, 'policy_version' => 2])->assertConflict();
|
||||||
|
$other = Tenant::query()->create(['name' => 'Outra empresa sintética']);
|
||||||
|
$department = Department::query()->create(['tenant_id' => $other->id, 'name' => 'Outra produção']);
|
||||||
|
$this->post('/ordens-operacionais', [...$this->input, 'department_id' => $department->id])->assertNotFound();
|
||||||
|
$foreign = User::factory()->create(['tenant_id' => $other->id, 'department_id' => $department->id, 'purchasing_role' => PurchasingRole::Procurement]);
|
||||||
|
$this->actingAs($foreign)->get('/requisicoes/'.$this->f['r']->id.'/ordens-operacionais')->assertNotFound();
|
||||||
|
expect(SupplyRecord::query()->withoutGlobalScopes()->where('kind', 'op_order')->count())->toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('metadata authority never opens the order register and process readers receive only linked origins', function () {
|
||||||
|
config(['operational-orders.qa_enabled' => true]);
|
||||||
|
$this->post('/ordens-operacionais/configuracao', $this->policy)->assertSessionHasNoErrors()->assertRedirect();
|
||||||
|
$this->actingAs($this->f['issuer'])->post('/ordens-operacionais', $this->input)->assertSessionHasNoErrors()->assertRedirect();
|
||||||
|
$order = SupplyRecord::query()->where('kind', 'op_order')->firstOrFail();
|
||||||
|
$request = $this->f['r'];
|
||||||
|
$request->update(['status' => 'draft']);
|
||||||
|
app(OperationalOrders::class)->link($this->f['issuer'], $request, ['item_id' => $request->items()->sole()->id, 'order_id' => $order->id,
|
||||||
|
'version' => 0, 'reason' => 'Origem sintética ligada para a consulta limitada.', 'operation_key' => (string) Str::uuid()]);
|
||||||
|
$this->post('/ordens-operacionais', [...$this->input, 'reference' => 'UNLINKED-PRIVATE-ORDER', 'operation_key' => (string) Str::uuid()])->assertSessionHasNoErrors()->assertRedirect();
|
||||||
|
$request->update(['status' => 'approved']);
|
||||||
|
$metadata = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Configured]);
|
||||||
|
$finance = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Configured]);
|
||||||
|
supplyGrant($metadata, ['audit_metadata_read']);
|
||||||
|
supplyGrant($finance, ['finance']);
|
||||||
|
$this->actingAs($metadata)->get('/ordens-operacionais')->assertForbidden();
|
||||||
|
$this->get('/requisicoes/'.$request->id.'/ordens-operacionais')->assertNotFound();
|
||||||
|
$this->actingAs($finance)->get('/ordens-operacionais')->assertForbidden();
|
||||||
|
$this->get('/requisicoes/'.$request->id.'/ordens-operacionais')->assertOk()->assertInertia(fn (Assert $page) => $page
|
||||||
|
->where('canLink', false)->has('orders.data', 1)->where('orders.data.0.id', $order->id)->has('links', 1));
|
||||||
|
});
|
||||||
@@ -160,13 +160,16 @@ test('tax configuration is versioned tenant scoped and never rewrites existing p
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('comparison policy requires valid weights authority and current version without rewriting existing processes', function () {
|
test('comparison policy requires valid weights authority and current version without rewriting existing processes', function () {
|
||||||
$body = ['version' => 1, 'minimum_proposals' => 2, 'minimum_evaluators' => 1, 'weights' => ['price' => 50, 'quality' => 20, 'delivery' => 10, 'history' => 10, 'payment' => 10], 'reason' => 'Regra comercial aprovada para novos processos.'];
|
$body = ['version' => 1, 'minimum_proposals' => 2, 'minimum_evaluators' => 1, 'urgent_minimum_proposals' => 1, 'weights' => ['price' => 50, 'quality' => 20, 'delivery' => 10, 'history' => 10, 'payment' => 10], 'reason' => 'Regra comercial aprovada para novos processos.'];
|
||||||
$this->postJson($this->base.'/comparison', [...$body, 'weights' => [...$body['weights'], 'price' => 49]])->assertUnprocessable();
|
$this->postJson($this->base.'/comparison', [...$body, 'weights' => [...$body['weights'], 'price' => 49]])->assertUnprocessable();
|
||||||
expect($this->f['tenant']->fresh()->comparison_policy)->toBeNull();
|
expect($this->f['tenant']->fresh()->comparison_policy)->toBeNull();
|
||||||
$this->postJson($this->base.'/comparison', [...$body, 'minimum_evaluators' => 0])->assertUnprocessable();
|
$this->postJson($this->base.'/comparison', [...$body, 'minimum_evaluators' => 0])->assertUnprocessable();
|
||||||
|
$this->postJson($this->base.'/comparison', [...$body, 'urgent_minimum_proposals' => 0])->assertUnprocessable();
|
||||||
|
$this->postJson($this->base.'/comparison', [...$body, 'urgent_minimum_proposals' => 2])->assertUnprocessable();
|
||||||
$this->postJson($this->base.'/comparison', [...$body, 'weights' => [...$body['weights'], 'other' => 0]])->assertUnprocessable();
|
$this->postJson($this->base.'/comparison', [...$body, 'weights' => [...$body['weights'], 'other' => 0]])->assertUnprocessable();
|
||||||
$this->postJson($this->base.'/comparison', $body)->assertRedirect();
|
$this->postJson($this->base.'/comparison', $body)->assertRedirect();
|
||||||
expect($this->f['tenant']->fresh()->comparison_policy['revision'])->toBe(1)->and($this->f['r']->fresh()->comparison_policy)->toBeNull();
|
expect($this->f['tenant']->fresh()->comparison_policy['revision'])->toBe(1)->and($this->f['r']->fresh()->comparison_policy)->toBeNull();
|
||||||
|
expect($this->f['tenant']->fresh()->comparison_policy['urgent_minimum_proposals'])->toBe(1);
|
||||||
$this->postJson($this->base.'/comparison', $body)->assertUnprocessable();
|
$this->postJson($this->base.'/comparison', $body)->assertUnprocessable();
|
||||||
$this->get($this->base)->assertInertia(fn (Assert $page) => $page->where('comparisonPolicy.minimum_proposals', 2));
|
$this->get($this->base)->assertInertia(fn (Assert $page) => $page->where('comparisonPolicy.minimum_proposals', 2));
|
||||||
expect(AuditLog::query()->where('action', 'organization.comparison')->count())->toBe(1);
|
expect(AuditLog::query()->where('action', 'organization.comparison')->count())->toBe(1);
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Enums\PurchasingRole;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\PrivateAuditAccess;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||||
|
|
||||||
|
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||||
|
require_once __DIR__.'/../Support/SupplyFixture.php';
|
||||||
|
|
||||||
|
beforeEach(function () {
|
||||||
|
$this->f = receiptFixture();
|
||||||
|
$this->actor = $this->f['issuer'];
|
||||||
|
$this->actingAs($this->actor);
|
||||||
|
$this->access = app(PrivateAuditAccess::class);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('private audit requires its explicit family authority and never inherits metadata finance or administration', function (string $permission) {
|
||||||
|
config(['private-audit.qa_enabled' => true]);
|
||||||
|
supplyGrant($this->actor, [$permission]);
|
||||||
|
expect(fn () => $this->access->authorise($this->actor, ['finance']))->toThrow(HttpException::class);
|
||||||
|
})->with(['audit_metadata_read', 'finance', 'admin']);
|
||||||
|
|
||||||
|
test('private audit family grants remain independent and cannot activate banking people or financial commands', function () {
|
||||||
|
config(['private-audit.qa_enabled' => true]);
|
||||||
|
supplyGrant($this->actor, ['audit_private_finance_read']);
|
||||||
|
$scope = $this->access->authorise($this->actor, ['finance', 'finance']);
|
||||||
|
expect($scope['families'])->toBe(['finance'])->and($scope['context'])->toBe('legacy')
|
||||||
|
->and($this->actor->hasFunctions(['finance', 'admin', 'procurement']))->toBeFalse();
|
||||||
|
expect(fn () => $this->access->authorise($this->actor, ['purchasing']))->toThrow(HttpException::class);
|
||||||
|
expect(fn () => $this->access->authorise($this->actor, ['complete_bank_identifiers']))->toThrow(HttpException::class);
|
||||||
|
expect(fn () => $this->access->authorise($this->actor, ['people']))->toThrow(HttpException::class);
|
||||||
|
$this->get('/auditoria/eventos')->assertForbidden();
|
||||||
|
$this->get('/orcamentos')->assertForbidden();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('private audit revalidates membership expiry revocation and maintenance without updating company rights', function () {
|
||||||
|
config(['private-audit.qa_enabled' => true]);
|
||||||
|
supplyGrant($this->actor, array_column(PrivateAuditAccess::FAMILIES, 'permission'));
|
||||||
|
$before = DB::table('organization_memberships')->orderBy('id')->get()->toJson();
|
||||||
|
expect($this->access->authorise($this->actor, ['stock', 'purchasing', 'finance', 'configuration'])['families'])
|
||||||
|
->toBe(['configuration', 'finance', 'purchasing', 'stock']);
|
||||||
|
expect(DB::table('organization_memberships')->orderBy('id')->get()->toJson())->toBe($before);
|
||||||
|
DB::table('organization_memberships')->where('user_id', $this->actor->id)->update(['expires_at' => now()->subMinute()]);
|
||||||
|
expect(fn () => $this->access->authorise($this->actor, ['stock']))->toThrow(HttpException::class);
|
||||||
|
DB::table('organization_memberships')->where('user_id', $this->actor->id)->update(['expires_at' => null, 'maintenance' => true]);
|
||||||
|
expect(fn () => $this->access->authorise($this->actor, ['stock']))->toThrow(HttpException::class);
|
||||||
|
DB::table('organization_memberships')->where('user_id', $this->actor->id)->delete();
|
||||||
|
expect(fn () => $this->access->authorise($this->actor, ['stock']))->toThrow(HttpException::class);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('private audit capability is disabled by default and the caller cannot select a different actor', function () {
|
||||||
|
supplyGrant($this->actor, ['audit_private_stock_read']);
|
||||||
|
expect(fn () => $this->access->authorise($this->actor, ['stock']))->toThrow(HttpException::class);
|
||||||
|
config(['private-audit.qa_enabled' => true]);
|
||||||
|
$other = User::factory()->create(['tenant_id' => $this->actor->tenant_id, 'purchasing_role' => PurchasingRole::Configured]);
|
||||||
|
expect(fn () => $this->access->authorise($other, ['stock']))->toThrow(HttpException::class);
|
||||||
|
});
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Enums\PurchasingRole;
|
||||||
|
use App\Models\PrivateAuditExport;
|
||||||
|
use App\Models\SupplierDocument;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\PrivateAuditAccess;
|
||||||
|
use App\Services\PrivateAuditExporter;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Storage;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||||
|
|
||||||
|
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||||
|
require_once __DIR__.'/../Support/SupplyFixture.php';
|
||||||
|
|
||||||
|
beforeEach(function () {
|
||||||
|
config(['private-audit.qa_enabled' => true]);
|
||||||
|
Storage::fake('local');
|
||||||
|
Storage::fake('supplier_documents');
|
||||||
|
Storage::fake('receipt_documents');
|
||||||
|
$this->f = receiptFixture();
|
||||||
|
$this->actor = $this->f['issuer'];
|
||||||
|
$this->actingAs($this->actor);
|
||||||
|
supplyGrant($this->actor, array_column(PrivateAuditAccess::FAMILIES, 'permission'));
|
||||||
|
if (DB::getDriverName() === 'pgsql') {
|
||||||
|
if (! app()->environment('testing') || DB::connection()->getConfig('host') !== '127.0.0.1'
|
||||||
|
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 1) {
|
||||||
|
throw new LogicException('Audit fixtures require the owned disposable PostgreSQL database.');
|
||||||
|
}
|
||||||
|
DB::commit();
|
||||||
|
$this->committedAuditFixture = true;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(function () {
|
||||||
|
if ($this->committedAuditFixture ?? false) {
|
||||||
|
if (! app()->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getConfig('host') !== '127.0.0.1'
|
||||||
|
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 0) {
|
||||||
|
throw new LogicException('Audit fixture cleanup requires its disposable PostgreSQL database.');
|
||||||
|
}
|
||||||
|
DB::statement('DROP SCHEMA public CASCADE');
|
||||||
|
DB::statement('CREATE SCHEMA public');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('private audit creates a verified immutable package and replays without duplicating or changing business facts', function () {
|
||||||
|
$before = DB::table('purchase_orders')->orderBy('id')->get()->toJson();
|
||||||
|
$input = ['operation_key' => (string) Str::uuid(), 'families' => ['configuration', 'purchasing', 'stock', 'finance'], 'purpose' => 'Synthetic QA audit'];
|
||||||
|
$service = app(PrivateAuditExporter::class);
|
||||||
|
$export = $service->generate($this->actor, $input);
|
||||||
|
$path = $service->verifiedPath($this->actor, $export);
|
||||||
|
$zip = new ZipArchive;
|
||||||
|
expect($zip->open($path, ZipArchive::RDONLY))->toBeTrue();
|
||||||
|
try {
|
||||||
|
$manifest = json_decode($zip->getFromName('manifesto.json'), true, 512, JSON_THROW_ON_ERROR);
|
||||||
|
expect($manifest['families'])->toHaveCount(4);
|
||||||
|
foreach ($manifest['datasets'] as $dataset) {
|
||||||
|
if ($dataset['state'] === 'not_installed') {
|
||||||
|
expect($dataset['records'])->toBeNull();
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$bytes = $zip->getFromName($dataset['file']);
|
||||||
|
expect($bytes)->toBeString()
|
||||||
|
->and(strlen($bytes))->toBe($dataset['size'])
|
||||||
|
->and(hash('sha256', $bytes))->toBe($dataset['sha256'])
|
||||||
|
->and(substr_count($bytes, "\n"))->toBe($dataset['records']);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
$zip->close();
|
||||||
|
}
|
||||||
|
expect($service->generate($this->actor, $input)->id)->toBe($export->id)
|
||||||
|
->and(PrivateAuditExport::query()->count())->toBe(1)
|
||||||
|
->and(DB::table('audit_logs')->where('action', 'audit.private_export_generated')->count())->toBe(1)
|
||||||
|
->and(DB::table('purchase_orders')->orderBy('id')->get()->toJson())->toBe($before)
|
||||||
|
->and(Storage::disk('local')->allFiles())->toBe([$export->path]);
|
||||||
|
try {
|
||||||
|
$service->generate($this->actor, [...$input, 'purpose' => 'Changed purpose']);
|
||||||
|
test()->fail('A different request must not reuse the operation.');
|
||||||
|
} catch (HttpException $error) {
|
||||||
|
expect($error->getStatusCode())->toBe(409);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('private audit refuses changed package bytes and revoked family authority', function () {
|
||||||
|
$service = app(PrivateAuditExporter::class);
|
||||||
|
$export = $service->generate($this->actor, ['operation_key' => (string) Str::uuid(), 'families' => ['configuration']]);
|
||||||
|
Storage::disk('local')->append($export->path, 'CORRUPTED-SYNTHETIC-QA');
|
||||||
|
try {
|
||||||
|
$service->verifiedPath($this->actor, $export);
|
||||||
|
test()->fail('Changed bytes must be refused.');
|
||||||
|
} catch (HttpException $error) {
|
||||||
|
expect($error->getStatusCode())->toBe(409);
|
||||||
|
}
|
||||||
|
DB::table('organization_memberships')->where('user_id', $this->actor->id)->update(['expires_at' => now()->subMinute()]);
|
||||||
|
try {
|
||||||
|
$service->verifiedPath($this->actor, $export);
|
||||||
|
test()->fail('Revocation must be effective before download.');
|
||||||
|
} catch (HttpException $error) {
|
||||||
|
expect($error->getStatusCode())->toBe(403);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('private audit verifies original bytes and cleans only its own incomplete preparation', function () {
|
||||||
|
$bytes = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl6E4sAAAAASUVORK5CYII=');
|
||||||
|
$supplier = $this->f['order']->supplier_id;
|
||||||
|
$path = $this->actor->tenant_id.'/'.$supplier.'/original.png';
|
||||||
|
Storage::disk('supplier_documents')->put($path, $bytes);
|
||||||
|
$document = SupplierDocument::query()->create(['tenant_id' => $this->actor->tenant_id, 'supplier_id' => $supplier,
|
||||||
|
'uploaded_by' => $this->actor->id, 'document_type' => 'other', 'original_name' => 'original.png', 'path' => $path,
|
||||||
|
'mime_type' => 'image/png', 'size' => strlen($bytes), 'sha256' => hash('sha256', $bytes)]);
|
||||||
|
$service = app(PrivateAuditExporter::class);
|
||||||
|
$export = $service->generate($this->actor, ['operation_key' => (string) Str::uuid(), 'families' => ['purchasing']]);
|
||||||
|
$zip = new ZipArchive;
|
||||||
|
$zip->open($service->verifiedPath($this->actor, $export), ZipArchive::RDONLY);
|
||||||
|
try {
|
||||||
|
expect($zip->getFromName('originais/purchasing/supplier_documents/'.$document->id.'.png'))->toBe($bytes);
|
||||||
|
} finally {
|
||||||
|
$zip->close();
|
||||||
|
}
|
||||||
|
Storage::disk('local')->put('unrelated/keep.txt', 'PRESERVE');
|
||||||
|
$before = Storage::disk('local')->allFiles();
|
||||||
|
Storage::disk('supplier_documents')->put($path, 'ALTERED');
|
||||||
|
try {
|
||||||
|
$service->generate($this->actor, ['operation_key' => (string) Str::uuid(), 'families' => ['purchasing']]);
|
||||||
|
test()->fail('An altered original must prevent a ready package.');
|
||||||
|
} catch (HttpException $error) {
|
||||||
|
expect($error->getStatusCode())->toBe(409);
|
||||||
|
}
|
||||||
|
expect(PrivateAuditExport::query()->count())->toBe(1)
|
||||||
|
->and(Storage::disk('local')->allFiles())->toBe($before)
|
||||||
|
->and(Storage::disk('supplier_documents')->get($path))->toBe('ALTERED');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('private audit HTTP preparation download and private headers preserve verified response bytes', function () {
|
||||||
|
$this->withoutVite();
|
||||||
|
$this->get('/auditoria/privada')->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private');
|
||||||
|
$this->post('/auditoria/privada', ['operation_key' => (string) Str::uuid(), 'families' => ['configuration']])->assertRedirect('/auditoria/privada')->assertSessionHasNoErrors();
|
||||||
|
$export = PrivateAuditExport::query()->sole();
|
||||||
|
$response = $this->get('/auditoria/privada/'.$export->id.'/download')->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private');
|
||||||
|
Storage::disk('local')->append($export->path, 'LATER-CHANGE');
|
||||||
|
expect(hash('sha256', $response->streamedContent()))->toBe($export->sha256);
|
||||||
|
$this->get('/auditoria/privada/'.$export->id.'/download')->assertStatus(409);
|
||||||
|
DB::table('organization_memberships')->where('user_id', $this->actor->id)->update(['expires_at' => now()->subMinute()]);
|
||||||
|
$this->get('/auditoria/privada')->assertForbidden();
|
||||||
|
$this->get('/auditoria/privada/'.$export->id.'/download')->assertForbidden();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('private audit packages remain personal to their creator even within the same authorised company', function () {
|
||||||
|
$service = app(PrivateAuditExporter::class);
|
||||||
|
$export = $service->generate($this->actor, ['operation_key' => (string) Str::uuid(), 'families' => ['configuration']]);
|
||||||
|
$other = User::factory()->create(['tenant_id' => $this->actor->tenant_id, 'department_id' => $this->actor->department_id,
|
||||||
|
'purchasing_role' => PurchasingRole::Configured]);
|
||||||
|
supplyGrant($other, ['audit_private_configuration_read']);
|
||||||
|
$this->actingAs($other)->get('/auditoria/privada/'.$export->id.'/download')->assertNotFound();
|
||||||
|
$this->withoutVite()->get('/auditoria/privada')->assertOk()->assertViewHas('page', fn (array $page) => $page['props']['exports']['data'] === []);
|
||||||
|
expect(PrivateAuditExport::query()->count())->toBe(1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Models\AuditLog;
|
||||||
|
use App\Models\Department;
|
||||||
|
use App\Models\SupplierBankDetail;
|
||||||
|
use App\Models\SupplyRecord;
|
||||||
|
use App\Models\Tenant;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\PrivateAuditAccess;
|
||||||
|
use App\Services\PrivateAuditSourceReader;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
|
||||||
|
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||||
|
require_once __DIR__.'/../Support/SupplyFixture.php';
|
||||||
|
|
||||||
|
beforeEach(function () {
|
||||||
|
config(['private-audit.qa_enabled' => true]);
|
||||||
|
$this->f = receiptFixture();
|
||||||
|
$this->actor = $this->f['issuer'];
|
||||||
|
$this->actingAs($this->actor);
|
||||||
|
supplyGrant($this->actor, array_column(PrivateAuditAccess::FAMILIES, 'permission'));
|
||||||
|
if (DB::getDriverName() === 'pgsql') {
|
||||||
|
if (! app()->environment('testing') || DB::connection()->getConfig('host') !== '127.0.0.1'
|
||||||
|
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 1) {
|
||||||
|
throw new LogicException('Audit source fixtures require the disposable PostgreSQL database.');
|
||||||
|
}
|
||||||
|
DB::commit();
|
||||||
|
$this->committedAuditSourceFixture = true;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(function () {
|
||||||
|
if ($this->committedAuditSourceFixture ?? false) {
|
||||||
|
if (! app()->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getConfig('host') !== '127.0.0.1'
|
||||||
|
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 0) {
|
||||||
|
throw new LogicException('Audit source cleanup requires its disposable PostgreSQL database.');
|
||||||
|
}
|
||||||
|
DB::statement('DROP SCHEMA public CASCADE');
|
||||||
|
DB::statement('CREATE SCHEMA public');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Test collector only; the production packager consumes each generator directly. */
|
||||||
|
function collectedPrivateAuditSources(User $actor, array $families): array
|
||||||
|
{
|
||||||
|
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 0) {
|
||||||
|
return DB::transaction(function () use ($actor, $families) {
|
||||||
|
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||||
|
|
||||||
|
return collectedPrivateAuditSources($actor, $families);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
$result = [];
|
||||||
|
foreach (app(PrivateAuditSourceReader::class)->datasets($actor, $families) as $dataset) {
|
||||||
|
$rows = $dataset['rows'];
|
||||||
|
$result[$dataset['family'].':'.$dataset['source']] = [...$dataset, 'rows' => $rows === null ? null : iterator_to_array($rows, false)];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
|
||||||
|
test('private audit source pagination includes every selected company row and no other company data', function () {
|
||||||
|
for ($index = 0; $index < 131; $index++) {
|
||||||
|
Department::query()->create(['tenant_id' => $this->actor->tenant_id, 'name' => 'AUDIT-DEPARTMENT-'.str_pad((string) $index, 3, '0', STR_PAD_LEFT)]);
|
||||||
|
}
|
||||||
|
$foreign = Tenant::query()->create(['name' => 'FOREIGN-AUDIT-COMPANY']);
|
||||||
|
Department::query()->create(['tenant_id' => $foreign->id, 'name' => 'FOREIGN-AUDIT-DEPARTMENT']);
|
||||||
|
$before = DB::table('departments')->orderBy('id')->get()->toJson();
|
||||||
|
$sources = collectedPrivateAuditSources($this->actor, ['configuration']);
|
||||||
|
$rows = $sources['configuration:departments']['rows'];
|
||||||
|
expect($rows)->toHaveCount(132)
|
||||||
|
->and(array_column($rows, 'name'))->toContain('AUDIT-DEPARTMENT-130')
|
||||||
|
->and(json_encode($sources, JSON_THROW_ON_ERROR))->not->toContain('FOREIGN-AUDIT-DEPARTMENT')->not->toContain('FOREIGN-AUDIT-COMPANY')
|
||||||
|
->and(DB::table('departments')->orderBy('id')->get()->toJson())->toBe($before);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('private audit preserves ordinary data while excluding bank coordinates credentials people payloads and storage paths', function () {
|
||||||
|
$this->f['tenant']->update(['company_details' => ['legal_name' => 'AUDIT-LEGAL-NAME', 'bank_accounts' => [['account_number' => 'BANK-FULL-NEVER-EXPORT']], 'establishments' => [['name' => 'AUDIT-LOCATION']]]]);
|
||||||
|
SupplierBankDetail::query()->create(['tenant_id' => $this->actor->tenant_id, 'supplier_id' => $this->f['order']->supplier_id,
|
||||||
|
'created_by' => $this->actor->id, 'revision' => 1, 'bank_name' => 'PRIVATE-BANK-NOT-IN-SCOPE', 'country' => 'MZ', 'currency' => 'MZN',
|
||||||
|
'beneficiary' => 'PRIVATE-BANK-HOLDER', 'account_identifier' => 'BANK-FULL-NEVER-EXPORT', 'evidence_reference' => 'PRIVATE-BANK-EVIDENCE', 'reason' => 'Synthetic bank record outside the approved audit scope.', 'created_at' => now()]);
|
||||||
|
$snapshot = [...$this->f['order']->snapshot, 'bank_snapshot' => ['account_identifier' => 'BANK-NESTED-NEVER-EXPORT'], 'api_key' => 'API-KEY-NEVER-EXPORT'];
|
||||||
|
// Synthetic exclusion markers only; documentary values and financial amounts remain unchanged.
|
||||||
|
DB::table('purchase_orders')->where('id', $this->f['order']->id)->update(['snapshot' => json_encode($snapshot, JSON_THROW_ON_ERROR)]);
|
||||||
|
AuditLog::query()->create(['tenant_id' => $this->actor->tenant_id, 'user_id' => $this->actor->id, 'action' => 'people.application.created',
|
||||||
|
'after' => ['candidate_document' => 'PEOPLE-PRIVATE-NEVER-EXPORT'], 'created_at' => now()]);
|
||||||
|
AuditLog::query()->create(['tenant_id' => $this->actor->tenant_id, 'user_id' => $this->actor->id, 'action' => 'organization.profile',
|
||||||
|
'before' => null, 'after' => ['name' => 'AUDIT-PROFILE-NAME', 'permissions' => ['procurement'], 'password' => 'PASSWORD-NEVER-EXPORT', 'unmapped_private_payload' => 'UNKNOWN-PRIVATE-NEVER-EXPORT'], 'created_at' => now()]);
|
||||||
|
$sources = collectedPrivateAuditSources($this->actor, ['configuration', 'purchasing', 'stock', 'finance']);
|
||||||
|
$body = json_encode($sources, JSON_THROW_ON_ERROR);
|
||||||
|
expect($body)->toContain('AUDIT-LEGAL-NAME')->toContain('AUDIT-LOCATION')->toContain('AUDIT-PROFILE-NAME')
|
||||||
|
->not->toContain('BANK-FULL-NEVER-EXPORT')->not->toContain('BANK-NESTED-NEVER-EXPORT')
|
||||||
|
->not->toContain('PRIVATE-BANK-NOT-IN-SCOPE')->not->toContain('PRIVATE-BANK-EVIDENCE')
|
||||||
|
->not->toContain('API-KEY-NEVER-EXPORT')->not->toContain('PASSWORD-NEVER-EXPORT')
|
||||||
|
->not->toContain('PEOPLE-PRIVATE-NEVER-EXPORT')->not->toContain('UNKNOWN-PRIVATE-NEVER-EXPORT');
|
||||||
|
foreach ($sources['configuration:users']['rows'] as $user) {
|
||||||
|
expect($user)->not->toHaveKey('password')->not->toHaveKey('two_factor_secret')->not->toHaveKey('remember_token');
|
||||||
|
}
|
||||||
|
$event = collect($sources['configuration:audit_logs']['rows'])->firstWhere('action', 'organization.profile');
|
||||||
|
expect($event)->toHaveKey('after_projected')->not->toHaveKey('after');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('private audit exposes installed empty data separately from uninstalled optional common sources without calculations or writes', function () {
|
||||||
|
$before = [];
|
||||||
|
foreach (['budget_entries', 'stock_movements', 'external_payments', 'invoices', 'purchase_orders', 'audit_logs'] as $table) {
|
||||||
|
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
|
||||||
|
}
|
||||||
|
$sources = collectedPrivateAuditSources($this->actor, ['finance']);
|
||||||
|
expect($sources['finance:external_payments']['state'])->toBe('available')
|
||||||
|
->and($sources['finance:external_payments']['rows'])->toBe([]);
|
||||||
|
if (! DB::getSchemaBuilder()->hasTable('pa_obligations')) {
|
||||||
|
expect($sources['finance:pa_obligations']['state'])->toBe('not_installed')
|
||||||
|
->and($sources['finance:pa_obligations']['rows'])->toBeNull();
|
||||||
|
}
|
||||||
|
foreach ($before as $table => $rows) {
|
||||||
|
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('private audit includes versioned import document metadata but excludes bank specific documents', function () {
|
||||||
|
foreach (['packing_list', 'bank_commitment', 'bank_support'] as $type) {
|
||||||
|
SupplyRecord::query()->create(['tenant_id' => $this->actor->tenant_id, 'kind' => 'import_document',
|
||||||
|
'record_key' => (string) Str::uuid(), 'version' => 1, 'state' => 'recorded',
|
||||||
|
'purchase_order_id' => $this->f['order']->id, 'created_by' => $this->actor->id,
|
||||||
|
'data' => ['type' => $type, 'reference' => 'SYNTHETIC-'.$type],
|
||||||
|
'snapshot' => ['evidence' => ['path' => 'PRIVATE-PATH-NEVER-EXPORT', 'sha256' => hash('sha256', $type)]],
|
||||||
|
'reason' => 'Synthetic metadata scope regression; no document download is requested.',
|
||||||
|
'operation_key' => (string) Str::uuid(), 'input_hash' => hash('sha256', $type), 'created_at' => now()]);
|
||||||
|
}
|
||||||
|
$sources = collectedPrivateAuditSources($this->actor, ['purchasing']);
|
||||||
|
$rows = $sources['purchasing:supply_records']['rows'];
|
||||||
|
expect($rows)->toHaveCount(1)
|
||||||
|
->and($rows[0]['data']['type'])->toBe('packing_list')
|
||||||
|
->and($rows[0]['version'])->toBe(1)
|
||||||
|
->and($rows[0]['purchase_order_id'])->toBe($this->f['order']->id)
|
||||||
|
->and(json_encode($rows, JSON_THROW_ON_ERROR))->not->toContain('bank_commitment')->not->toContain('bank_support')->not->toContain('PRIVATE-PATH-NEVER-EXPORT');
|
||||||
|
});
|
||||||
@@ -41,6 +41,7 @@ use App\Services\EquipmentWorkflow;
|
|||||||
use App\Services\FormalAdmission;
|
use App\Services\FormalAdmission;
|
||||||
use App\Services\ImportTariffCodes;
|
use App\Services\ImportTariffCodes;
|
||||||
use App\Services\InvoiceWorkflow;
|
use App\Services\InvoiceWorkflow;
|
||||||
|
use App\Services\OperationalOrders;
|
||||||
use App\Services\OrderCancellationPolicyWorkflow;
|
use App\Services\OrderCancellationPolicyWorkflow;
|
||||||
use App\Services\OrderCancellationWorkflow;
|
use App\Services\OrderCancellationWorkflow;
|
||||||
use App\Services\OrderPartsAmendments;
|
use App\Services\OrderPartsAmendments;
|
||||||
@@ -62,6 +63,7 @@ use App\Services\RequisitionBudgetDistributions;
|
|||||||
use App\Services\RequisitionCatalogue;
|
use App\Services\RequisitionCatalogue;
|
||||||
use App\Services\RequisitionWorkflow;
|
use App\Services\RequisitionWorkflow;
|
||||||
use App\Services\SupplyPlanning;
|
use App\Services\SupplyPlanning;
|
||||||
|
use App\Services\UrgentQuotationBasis;
|
||||||
use App\Services\WorkflowTaskInbox;
|
use App\Services\WorkflowTaskInbox;
|
||||||
use Brick\Math\BigDecimal;
|
use Brick\Math\BigDecimal;
|
||||||
use Carbon\CarbonImmutable;
|
use Carbon\CarbonImmutable;
|
||||||
@@ -97,6 +99,93 @@ function nativeCapitalAssignment(object $test, string $type = 'project'): array
|
|||||||
return [$source, $assignment, $input];
|
return [$source, $assignment, $input];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
test('native orders freeze their production origin in normal and partial issuance', function (bool $partial) {
|
||||||
|
if ($partial && ! method_exists(BudgetControl::class, 'commitOrderParts')) {
|
||||||
|
$this->markTestSkipped('Select the approved isolated-QA common source for native order parts.');
|
||||||
|
}
|
||||||
|
config(['operational-orders.qa_enabled' => true]);
|
||||||
|
$service = app(OperationalOrders::class);
|
||||||
|
$this->actingAs($this->admin);
|
||||||
|
$service->configure($this->admin, ['version' => 0, 'mode' => 'procurement', 'reason' => 'Origem sintética pelo procurement sem locais abrangidos.', 'operation_key' => (string) Str::uuid()]);
|
||||||
|
$this->actingAs($this->buyer);
|
||||||
|
$source = $service->save($this->buyer, ['type' => 'production', 'reference' => 'PRODUCTION-ORIGIN-QA', 'department_id' => $this->department->id,
|
||||||
|
'utilisation_location' => 'Linha sintética de utilização', 'description' => 'Trabalho fictício preservado na ordem de compra.', 'reason' => 'Registo sintético de produção para teste nativo.', 'policy_version' => 1, 'operation_key' => (string) Str::uuid()]);
|
||||||
|
// Add the source selected while the existing pre-approved synthetic fixture was a draft.
|
||||||
|
$this->r->update(['status' => 'draft']);
|
||||||
|
$this->actingAs($this->owner);
|
||||||
|
$link = $service->link($this->owner, $this->r, ['item_id' => $this->item->id, 'order_id' => $source->id, 'version' => 0, 'reason' => 'Origem documental escolhida pelo requisitante sintético.', 'operation_key' => (string) Str::uuid()]);
|
||||||
|
$this->r->update(['status' => 'approved']);
|
||||||
|
$this->actingAs($this->buyer);
|
||||||
|
if ($partial) {
|
||||||
|
$award = nativeOrderPartsAward($this);
|
||||||
|
$order = app(OrderPartsWorkflow::class)->issue($this->buyer, nativeOrderPartsInput($this, $award, '0.400', 0));
|
||||||
|
} else {
|
||||||
|
$order = issuePurchaseOrder($this, selectPurchaseAward($this));
|
||||||
|
}
|
||||||
|
expect($order->snapshot['operational_orders'][$this->item->id]['id'])->toBe($link->id)
|
||||||
|
->and($order->snapshot['operational_orders'][$this->item->id]['snapshot']['source']['id'])->toBe($source->id)
|
||||||
|
->and($order->total_minor)->toBe($partial ? 4000 : 10000);
|
||||||
|
$this->actingAs($this->admin);
|
||||||
|
$service->configure($this->admin, ['version' => 1, 'mode' => 'utilisation', 'reason' => 'Configuração posterior que conserva a origem anterior.', 'operation_key' => (string) Str::uuid()]);
|
||||||
|
$this->actingAs($this->buyer)->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('PRODUCTION-ORIGIN-QA')->assertSee('Registada pelo procurement')->assertSee('Linha sintética de utilização');
|
||||||
|
expect($order->fresh()->snapshot['operational_orders'][$this->item->id]['snapshot']['source']['snapshot']['policy']['data']['mode'])->toBe('procurement');
|
||||||
|
})->with([false, true]);
|
||||||
|
|
||||||
|
test('native urgent order uses only the configured reduced eligible count and preserves stock evidence with independent approvals', function (bool $partial) {
|
||||||
|
if ($partial && ! method_exists(BudgetControl::class, 'commitOrderParts')) {
|
||||||
|
$this->markTestSkipped('Select the approved isolated-QA common source for native order parts.');
|
||||||
|
}
|
||||||
|
config(['urgent-quotations.qa_enabled' => true]);
|
||||||
|
$this->actingAs($this->admin);
|
||||||
|
$stock = StockItem::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $this->admin->id, 'code' => 'URGENT-STOCK-QA', 'name' => $this->item->description, 'unit' => $this->item->unit]);
|
||||||
|
$warehouse = Warehouse::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $this->admin->id, 'code' => 'URGENT-WH-QA', 'name' => 'Local sintético da urgência']);
|
||||||
|
app(RequisitionCatalogue::class)->save($this->admin, $stock->id, ['version' => 0, 'stock_basis' => app(RequisitionCatalogue::class)->basis($stock),
|
||||||
|
'category' => 'Material', 'purchase_type' => 'consumable', 'published' => true, 'reason' => 'Catálogo sintético antes da redução urgente.']);
|
||||||
|
$entry = DB::table('requisition_catalogue')->where('stock_item_id', $stock->id)->sole();
|
||||||
|
$this->actingAs($this->owner);
|
||||||
|
$resolved = app(RequisitionCatalogue::class)->line($this->owner, ['catalogue_entry_id' => $entry->id, 'catalogue_version' => 1], []);
|
||||||
|
$this->item->update(['catalogue_entry_id' => $entry->id, 'catalogue_snapshot' => $resolved['catalogue_snapshot']]);
|
||||||
|
// The initial approved request/three offers are synthetic fixtures. Only one supplier remains eligible before adjudication.
|
||||||
|
$this->r->update(['priority' => 'urgent', 'justification' => 'Risco sintético de paragem por falta de material no local de utilização.',
|
||||||
|
'comparison_policy' => app(ComparisonPolicy::class)->checked([...ComparisonPolicy::DEFAULTS, 'configured' => true, 'revision' => 1, 'urgent_minimum_proposals' => 1])]);
|
||||||
|
foreach ([$this->suppliers[1], $this->suppliers[2]] as $supplier) {
|
||||||
|
$supplier->update(['status' => 'suspended']);
|
||||||
|
}
|
||||||
|
foreach ([$this->owner, $this->buyer, $this->secondBuyer, $this->head, $this->finance, $this->admin] as $person) {
|
||||||
|
supplyGrant($person, [$person->purchasing_role->value, ...($person->id === $this->buyer->id ? ['supply_prepare'] : []), ...($person->id === $this->finance->id ? ['supply_review'] : [])]);
|
||||||
|
}
|
||||||
|
$this->actingAs($this->buyer);
|
||||||
|
$planning = app(SupplyPlanning::class);
|
||||||
|
$draft = $planning->save($this->buyer, 'policy', supplyInput(supplyPolicy(['stock' => $stock, 'warehouse' => $warehouse])));
|
||||||
|
$this->actingAs($this->finance);
|
||||||
|
$policy = $planning->save($this->finance, 'policy', supplyInput([], 'approve', $draft));
|
||||||
|
$this->actingAs($this->buyer);
|
||||||
|
expect(app(ProposalComparison::class)->inspect($this->r)['ready'])->toBeFalse();
|
||||||
|
$this->post($this->awardUrl, $this->selection)->assertSessionHasErrors('comparison');
|
||||||
|
expect(PurchaseAward::query()->count())->toBe(0);
|
||||||
|
$proof = app(UrgentQuotationBasis::class)->record($this->buyer, $this->r, ['item_id' => $this->item->id, 'policy_id' => $policy->id, 'version' => 0,
|
||||||
|
'reason' => 'URGENT-MINIMUM-NATIVE-QA: mínimo atingido no local sintético.', 'operation_key' => (string) Str::uuid()]);
|
||||||
|
$comparison = app(ProposalComparison::class)->inspect($this->r);
|
||||||
|
expect($comparison['ready'])->toBeTrue()->and(count(array_filter($comparison['rows'], fn ($row) => $row['eligible'])))->toBe(1)
|
||||||
|
->and($comparison['policy']['minimum_evaluators'])->toBe(2);
|
||||||
|
if ($partial) {
|
||||||
|
$award = nativeOrderPartsAward($this);
|
||||||
|
$order = app(OrderPartsWorkflow::class)->issue($this->buyer, nativeOrderPartsInput($this, $award, '0.400', 0));
|
||||||
|
} else {
|
||||||
|
$award = selectPurchaseAward($this);
|
||||||
|
$this->actingAs($this->owner)->post('/adjudicacoes/'.$award->id.'/decidir', ['decision' => 'approved'])->assertForbidden();
|
||||||
|
$this->actingAs($this->buyer);
|
||||||
|
$this->post('/adjudicacoes/'.$award->id.'/emitir')->assertSessionHasErrors('approvals');
|
||||||
|
$order = issuePurchaseOrder($this, $award);
|
||||||
|
}
|
||||||
|
expect($order->snapshot['urgent_quotation_basis'][0]['id'])->toBe($proof->id)
|
||||||
|
->and($order->snapshot['comparison_policy']['minimum_proposals'])->toBe(1)
|
||||||
|
->and($order->snapshot['comparison_policy']['normal_minimum_proposals'])->toBe(3)
|
||||||
|
->and($order->total_minor)->toBe($partial ? 4000 : 10000);
|
||||||
|
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('URGENT-MINIMUM-NATIVE-QA')->assertSee('Local sintético da urgência');
|
||||||
|
expect($award->approvals()->where('decision', 'approved')->count())->toBeGreaterThan(0);
|
||||||
|
})->with([false, true]);
|
||||||
|
|
||||||
test('native order preserves the capital destination and print after the independent register is archived', function () {
|
test('native order preserves the capital destination and print after the independent register is archived', function () {
|
||||||
[$source, $assignment, $input] = nativeCapitalAssignment($this);
|
[$source, $assignment, $input] = nativeCapitalAssignment($this);
|
||||||
$award = selectPurchaseAward($this);
|
$award = selectPurchaseAward($this);
|
||||||
|
|||||||
@@ -12,6 +12,27 @@ require_once __DIR__.'/../Support/ReceiptFixture.php';
|
|||||||
|
|
||||||
require_once __DIR__.'/../Support/SupplyFixture.php';
|
require_once __DIR__.'/../Support/SupplyFixture.php';
|
||||||
|
|
||||||
|
test('minimum stock is explicitly configured for the item and its documented use without a fixed universal value', function () {
|
||||||
|
$f = receiptFixture();
|
||||||
|
supplyGrant($f['issuer'], ['supply_prepare']);
|
||||||
|
supplyGrant($f['receiver'], ['supply_review']);
|
||||||
|
$service = app(SupplyPlanning::class);
|
||||||
|
$this->actingAs($f['issuer']);
|
||||||
|
$input = [...supplyPolicy($f), 'purpose' => 'internal', 'minimum_stock_milli' => 25000,
|
||||||
|
'usage_context' => 'Insumo sintético usado diariamente na linha de produção.', 'basis' => 'Mínimo parametrizado pela natureza do artigo e utilização diária documentada.'];
|
||||||
|
$draft = $service->save($f['issuer'], 'policy', supplyInput($input));
|
||||||
|
$this->actingAs($f['receiver']);
|
||||||
|
$approved = $service->save($f['receiver'], 'policy', supplyInput([], 'approve', $draft));
|
||||||
|
expect($approved->data['minimum_stock_milli'])->toBe(25000)
|
||||||
|
->and($approved->data['usage_context'])->toBe($input['usage_context'])
|
||||||
|
->and($approved->snapshot['item']['id'])->toBe($f['stock']->id);
|
||||||
|
$before = $approved->fresh()->toArray();
|
||||||
|
$this->actingAs($f['issuer']);
|
||||||
|
$alternative = $service->save($f['issuer'], 'policy', supplyInput([...$input, 'minimum_stock_milli' => 35000, 'usage_context' => 'Uso intensivo sintético que exige outro mínimo.']));
|
||||||
|
expect($alternative->data['minimum_stock_milli'])->toBe(35000)
|
||||||
|
->and($approved->fresh()->toArray())->toBe($before);
|
||||||
|
});
|
||||||
|
|
||||||
test('calendar keeps stock risk but withdraws deadlines when the reused agreement expires or supplier changes', function () {
|
test('calendar keeps stock risk but withdraws deadlines when the reused agreement expires or supplier changes', function () {
|
||||||
$f = receiptFixture();
|
$f = receiptFixture();
|
||||||
supplyGrant($f['issuer'], ['supply_prepare']);
|
supplyGrant($f['issuer'], ['supply_prepare']);
|
||||||
|
|||||||
@@ -0,0 +1,125 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Enums\PurchasingRole;
|
||||||
|
use App\Models\Requisition;
|
||||||
|
use App\Models\SupplyRecord;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\ComparisonPolicy;
|
||||||
|
use App\Services\ProposalComparison;
|
||||||
|
use App\Services\ReceiptWorkflow;
|
||||||
|
use App\Services\RequisitionCatalogue;
|
||||||
|
use App\Services\SupplyPlanning;
|
||||||
|
use App\Services\UrgentQuotationBasis;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Illuminate\Validation\ValidationException;
|
||||||
|
use Inertia\Testing\AssertableInertia as Assert;
|
||||||
|
|
||||||
|
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||||
|
require_once __DIR__.'/../Support/SupplyFixture.php';
|
||||||
|
|
||||||
|
beforeEach(function () {
|
||||||
|
$this->withoutVite();
|
||||||
|
$this->f = receiptFixture();
|
||||||
|
$this->actingAs($this->f['receiver']);
|
||||||
|
$catalogue = app(RequisitionCatalogue::class);
|
||||||
|
$catalogue->save($this->f['receiver'], $this->f['stock']->id, ['version' => 0, 'stock_basis' => $catalogue->basis($this->f['stock']),
|
||||||
|
'category' => 'Material', 'purchase_type' => 'consumable', 'published' => true, 'reason' => 'Artigo sintético publicado para prova de mínimo.']);
|
||||||
|
$entry = DB::table('requisition_catalogue')->where('stock_item_id', $this->f['stock']->id)->sole();
|
||||||
|
$this->actingAs($this->f['issuer']);
|
||||||
|
$resolved = $catalogue->line($this->f['issuer'], ['catalogue_entry_id' => $entry->id, 'catalogue_version' => 1], []);
|
||||||
|
$this->request = Requisition::query()->create([...$this->f['r']->only(['tenant_id', 'requester_id', 'department_id', 'cost_center_id', 'needed_by', 'subtotal_minor', 'tax_minor', 'total_minor']),
|
||||||
|
'number' => 'URGENT-STOCK-QA', 'priority' => 'urgent', 'status' => 'approved', 'justification' => 'Risco sintético de paragem da produção por falta de material.',
|
||||||
|
'comparison_policy' => app(ComparisonPolicy::class)->checked([...ComparisonPolicy::DEFAULTS, 'configured' => true, 'revision' => 1, 'urgent_minimum_proposals' => 1])]);
|
||||||
|
$sourceItem = $this->f['r']->items()->sole();
|
||||||
|
$this->item = $this->request->items()->create([...$sourceItem->only(['tenant_id', 'description', 'category', 'purchase_type', 'quantity', 'unit', 'unit_price_minor', 'tax_rate', 'subtotal_minor', 'tax_minor', 'total_minor']),
|
||||||
|
'catalogue_entry_id' => $entry->id, 'catalogue_snapshot' => $resolved['catalogue_snapshot']]);
|
||||||
|
supplyGrant($this->f['issuer'], ['procurement', 'supply_prepare']);
|
||||||
|
supplyGrant($this->f['receiver'], ['warehouse', 'supply_review']);
|
||||||
|
$this->url = '/requisicoes/'.$this->request->id.'/urgencia-stock';
|
||||||
|
$this->withoutPolicy = app(ProposalComparison::class)->inspect($this->request);
|
||||||
|
});
|
||||||
|
|
||||||
|
function urgentApprovedStockPolicy(object $test, int $minimum = 20000): SupplyRecord
|
||||||
|
{
|
||||||
|
$planning = app(SupplyPlanning::class);
|
||||||
|
$test->actingAs($test->f['issuer']);
|
||||||
|
$draft = $planning->save($test->f['issuer'], 'policy', supplyInput([...supplyPolicy($test->f), 'safety_milli' => 0, 'minimum_stock_milli' => $minimum,
|
||||||
|
'usage_context' => 'Insumo sintético de utilização diária na produção.']));
|
||||||
|
$test->actingAs($test->f['receiver']);
|
||||||
|
|
||||||
|
return $planning->save($test->f['receiver'], 'policy', supplyInput([], 'approve', $draft));
|
||||||
|
}
|
||||||
|
|
||||||
|
test('urgent reduction requires an explicit count and actual company stock minimum evidence for every current line', function () {
|
||||||
|
config(['urgent-quotations.qa_enabled' => true]);
|
||||||
|
$policy = urgentApprovedStockPolicy($this);
|
||||||
|
$input = ['item_id' => $this->item->id, 'policy_id' => $policy->id, 'version' => 0, 'reason' => 'Conferência sintética de stock mínimo atingido e risco de paragem.', 'operation_key' => (string) Str::uuid()];
|
||||||
|
$before = [];
|
||||||
|
foreach (['stock_movements', 'budget_entries', 'purchase_orders', 'invoices'] as $table) {
|
||||||
|
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
|
||||||
|
}
|
||||||
|
$this->actingAs($this->f['issuer']);
|
||||||
|
expect(app(ProposalComparison::class)->inspect($this->request)['policy']['minimum_proposals'])->toBe(3);
|
||||||
|
$this->post($this->url, $input)->assertSessionHasNoErrors()->assertRedirect();
|
||||||
|
$this->post($this->url, $input)->assertSessionHasNoErrors()->assertRedirect();
|
||||||
|
$service = app(UrgentQuotationBasis::class);
|
||||||
|
$proof = $service->eligible($this->request);
|
||||||
|
expect($proof)->toHaveCount(1)
|
||||||
|
->and($proof[0]['snapshot']['availability']['at_minimum'])->toBeTrue()
|
||||||
|
->and($proof[0]['snapshot']['stock_policy']['minimum_stock_milli'])->toBe(20000);
|
||||||
|
$comparison = app(ProposalComparison::class)->inspect($this->request);
|
||||||
|
expect($comparison['policy']['minimum_proposals'])->toBe(1)
|
||||||
|
->and($comparison['policy']['normal_minimum_proposals'])->toBe(3)
|
||||||
|
->and($comparison['policy']['minimum_evaluators'])->toBe(2)
|
||||||
|
->and($comparison['fingerprint'])->not->toBe($this->withoutPolicy['fingerprint']);
|
||||||
|
$response = $this->get($this->url)->assertOk()->assertInertia(fn (Assert $page) => $page->component('requisitions/urgent-stock')->has('eligible', 1));
|
||||||
|
$response->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true);
|
||||||
|
expect($response->headers->get('Cache-Control'))->toContain('private')->toContain('no-store');
|
||||||
|
$this->post($this->url, [...$input, 'operation_key' => (string) Str::uuid()])->assertConflict();
|
||||||
|
$reader = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Configured]);
|
||||||
|
supplyGrant($reader, ['finance']);
|
||||||
|
$this->actingAs($reader)->get($this->url)->assertOk()->assertInertia(fn (Assert $page) => $page->where('canRecord', false)->has('policies.data', 0)->has('evidence', 1));
|
||||||
|
$this->actingAs($this->f['issuer']);
|
||||||
|
$this->request->setAttribute('approval_cycle', 2);
|
||||||
|
expect($service->eligible($this->request))->toBe([]);
|
||||||
|
$this->request->setAttribute('approval_cycle', 1);
|
||||||
|
$this->item->update(['description' => 'Linha alterada exige nova conferência de origem.']);
|
||||||
|
expect($service->eligible($this->request))->toBe([])
|
||||||
|
->and(app(ProposalComparison::class)->inspect($this->request)['policy']['minimum_proposals'])->toBe(3);
|
||||||
|
foreach ($before as $table => $rows) {
|
||||||
|
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('unmet minimum and unauthorised actors cannot obtain the urgent quotation reduction', function () {
|
||||||
|
config(['urgent-quotations.qa_enabled' => true]);
|
||||||
|
$policy = urgentApprovedStockPolicy($this, 500);
|
||||||
|
$this->actingAs($this->f['receiver']);
|
||||||
|
app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $this->f['order'], receiptPayload($this->f, '1.000'));
|
||||||
|
$input = ['item_id' => $this->item->id, 'policy_id' => $policy->id, 'version' => 0, 'reason' => 'Tentativa sintética antes de atingir o mínimo.', 'operation_key' => (string) Str::uuid()];
|
||||||
|
$this->actingAs($this->f['issuer'])->post($this->url, $input)->assertSessionHasErrors('policy_id');
|
||||||
|
expect(app(UrgentQuotationBasis::class)->eligible($this->request))->toBe([]);
|
||||||
|
$this->actingAs($this->f['receiver'])->post($this->url, $input)->assertNotFound();
|
||||||
|
$finance = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Configured]);
|
||||||
|
supplyGrant($finance, ['finance']);
|
||||||
|
$this->actingAs($finance)->post($this->url, $input)->assertForbidden();
|
||||||
|
$this->actingAs($this->f['issuer']);
|
||||||
|
$this->request->update(['priority' => 'normal']);
|
||||||
|
$this->post($this->url, $input)->assertStatus(422);
|
||||||
|
config(['urgent-quotations.qa_enabled' => false]);
|
||||||
|
$this->post($this->url, $input)->assertStatus(503);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('urgent minimum is optional strictly positive and lower than the normal company count', function () {
|
||||||
|
$service = app(ComparisonPolicy::class);
|
||||||
|
expect($service->checked(ComparisonPolicy::DEFAULTS))->toBe(ComparisonPolicy::DEFAULTS);
|
||||||
|
foreach ([0, 3, 4] as $value) {
|
||||||
|
expect(fn () => $service->checked([...ComparisonPolicy::DEFAULTS, 'urgent_minimum_proposals' => $value]))->toThrow(ValidationException::class);
|
||||||
|
}
|
||||||
|
config(['urgent-quotations.qa_enabled' => true]);
|
||||||
|
$policy = urgentApprovedStockPolicy($this);
|
||||||
|
$this->request->update(['comparison_policy' => ComparisonPolicy::DEFAULTS]);
|
||||||
|
$this->actingAs($this->f['issuer'])->post($this->url, ['item_id' => $this->item->id, 'policy_id' => $policy->id, 'version' => 0,
|
||||||
|
'reason' => 'Não pode inferir um número urgente não configurado.', 'operation_key' => (string) Str::uuid()])->assertStatus(422);
|
||||||
|
});
|
||||||
@@ -5,6 +5,7 @@ use App\Http\Controllers\AuditMetadataController;
|
|||||||
use App\Models\CostCenter;
|
use App\Models\CostCenter;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Services\CommonBudget;
|
use App\Services\CommonBudget;
|
||||||
|
use App\Services\PrivateAuditAccess;
|
||||||
use App\Services\PurchaseControlPolicyWorkflow;
|
use App\Services\PurchaseControlPolicyWorkflow;
|
||||||
use App\Services\RequisitionAccountAssignments;
|
use App\Services\RequisitionAccountAssignments;
|
||||||
use App\Services\RequisitionExpiry;
|
use App\Services\RequisitionExpiry;
|
||||||
@@ -41,6 +42,7 @@ function requisitionAccountsNativeReviewFixture(bool $integrated = false, bool $
|
|||||||
$profiles = [];
|
$profiles = [];
|
||||||
$functions = ['reviewer' => ['admin', 'procurement', 'requester', 'supply_prepare', 'warehouse_request_prepare', 'audit_metadata_read'], 'requester' => ['requester'],
|
$functions = ['reviewer' => ['admin', 'procurement', 'requester', 'supply_prepare', 'warehouse_request_prepare', 'audit_metadata_read'], 'requester' => ['requester'],
|
||||||
'head' => ['department_head', 'supply_review', 'warehouse_request_review'], 'finance' => ['finance'], 'auditor' => ['audit_metadata_read']];
|
'head' => ['department_head', 'supply_review', 'warehouse_request_review'], 'finance' => ['finance'], 'auditor' => ['audit_metadata_read']];
|
||||||
|
$functions['private_auditor'] = array_column(PrivateAuditAccess::FAMILIES, 'permission');
|
||||||
if ($officeJourney) {
|
if ($officeJourney) {
|
||||||
$functions += ['office_requester' => ['requester'], 'office_finance_reviewer' => ['finance'], 'office_warehouse' => ['warehouse'],
|
$functions += ['office_requester' => ['requester'], 'office_finance_reviewer' => ['finance'], 'office_warehouse' => ['warehouse'],
|
||||||
'office_procurement_reviewer' => ['procurement']];
|
'office_procurement_reviewer' => ['procurement']];
|
||||||
@@ -250,7 +252,7 @@ function requisitionAccountsNativeReviewFixture(bool $integrated = false, bool $
|
|||||||
return ['tenant_id' => $f['tenant']->id, 'synthetic_login' => $people['reviewer']->email,
|
return ['tenant_id' => $f['tenant']->id, 'synthetic_login' => $people['reviewer']->email,
|
||||||
'office_journey' => $office,
|
'office_journey' => $office,
|
||||||
'integrated_optional_schema' => $composition,
|
'integrated_optional_schema' => $composition,
|
||||||
'synthetic_metadata_login' => $people['auditor']->email, 'synthetic_requester_login' => $people['requester']->email,
|
'synthetic_private_audit_login' => $people['private_auditor']->email, 'synthetic_metadata_login' => $people['auditor']->email, 'synthetic_requester_login' => $people['requester']->email,
|
||||||
'audit_request_reference' => $historyRequest->number, 'audit_native_readonly_transactions' => $readonlyTransactions,
|
'audit_request_reference' => $historyRequest->number, 'audit_native_readonly_transactions' => $readonlyTransactions,
|
||||||
'search_agreement' => $agreement->id, 'search_contract' => $contract->id, 'warehouse_search_request' => $internal->id,
|
'search_agreement' => $agreement->id, 'search_contract' => $contract->id, 'warehouse_search_request' => $internal->id,
|
||||||
'historical_decision_request' => $historyRequest->id, 'historical_decision_verified' => true,
|
'historical_decision_request' => $historyRequest->id, 'historical_decision_verified' => true,
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ test('owned native client drains large closed responses while preserving body he
|
|||||||
let cookiesSeen = '';
|
let cookiesSeen = '';
|
||||||
const server = createServer((request, response) => {
|
const server = createServer((request, response) => {
|
||||||
response.setHeader('Connection', 'close');
|
response.setHeader('Connection', 'close');
|
||||||
|
response.useChunkedEncodingByDefault = false;
|
||||||
if (request.url === '/cookies') {
|
if (request.url === '/cookies') {
|
||||||
response.setHeader('Set-Cookie', ['QA_SESSION=first; Path=/', 'QA_CONTEXT=second; Path=/']);
|
response.setHeader('Set-Cookie', ['QA_SESSION=first; Path=/', 'QA_CONTEXT=second; Path=/']);
|
||||||
}
|
}
|
||||||
@@ -15,7 +16,8 @@ test('owned native client drains large closed responses while preserving body he
|
|||||||
if (request.url === '/redirect') { response.writeHead(302, { Location: '/large' }); response.end('Synthetic redirect'); return; }
|
if (request.url === '/redirect') { response.writeHead(302, { Location: '/large' }); response.end('Synthetic redirect'); return; }
|
||||||
cookiesSeen = request.headers.cookie ?? '';
|
cookiesSeen = request.headers.cookie ?? '';
|
||||||
response.writeHead(200, { 'Content-Type': 'application/json' });
|
response.writeHead(200, { 'Content-Type': 'application/json' });
|
||||||
response.end(JSON.stringify(payload));
|
response.write(JSON.stringify(payload));
|
||||||
|
response.end();
|
||||||
});
|
});
|
||||||
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
|
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
|
||||||
try {
|
try {
|
||||||
@@ -26,6 +28,8 @@ test('owned native client drains large closed responses while preserving body he
|
|||||||
assert.equal(first.status, 200);
|
assert.equal(first.status, 200);
|
||||||
assert.equal(first.bodyUsed, false);
|
assert.equal(first.bodyUsed, false);
|
||||||
assert.equal(first.url, origin + '/large');
|
assert.equal(first.url, origin + '/large');
|
||||||
|
assert.equal(first.headers.get('Content-Length'), null);
|
||||||
|
assert.equal(first.headers.get('Transfer-Encoding'), null);
|
||||||
await client.request('/cookies');
|
await client.request('/cookies');
|
||||||
const next = await client.request('/large');
|
const next = await client.request('/large');
|
||||||
assert.match(cookiesSeen, /QA_SESSION=first/);
|
assert.match(cookiesSeen, /QA_SESSION=first/);
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ $app->booted(function () use ($root, $database) {
|
|||||||
CarbonImmutable::setTestNow($fixture['clock']);
|
CarbonImmutable::setTestNow($fixture['clock']);
|
||||||
config(['requisition-expiry.qa_enabled' => true, 'requisition-accounts.qa_enabled' => true, 'urgent-reviews.qa_enabled' => true,
|
config(['requisition-expiry.qa_enabled' => true, 'requisition-accounts.qa_enabled' => true, 'urgent-reviews.qa_enabled' => true,
|
||||||
'order_cancellation.enabled' => true,
|
'order_cancellation.enabled' => true,
|
||||||
|
'operational-orders.qa_enabled' => true, 'urgent-quotations.qa_enabled' => true, 'private-audit.qa_enabled' => true,
|
||||||
'agreement_order_limits.qa_enabled' => true, 'procurement_search.supply_metadata_enabled' => true,
|
'agreement_order_limits.qa_enabled' => true, 'procurement_search.supply_metadata_enabled' => true,
|
||||||
'procurement_search.warehouse_requests_metadata_enabled' => true,
|
'procurement_search.warehouse_requests_metadata_enabled' => true,
|
||||||
'session.driver' => 'file', 'session.files' => $root.'/storage/framework/sessions', 'session.domain' => null,
|
'session.driver' => 'file', 'session.files' => $root.'/storage/framework/sessions', 'session.domain' => null,
|
||||||
|
|||||||
@@ -28,6 +28,13 @@ function render(
|
|||||||
context = 'finance',
|
context = 'finance',
|
||||||
canCorrect = true,
|
canCorrect = true,
|
||||||
sourceId = 3,
|
sourceId = 3,
|
||||||
|
canAuthoriseRelease = false,
|
||||||
|
release: {
|
||||||
|
id: number;
|
||||||
|
authorised_by: number;
|
||||||
|
authorised_at: string;
|
||||||
|
reason: string;
|
||||||
|
} | null = null,
|
||||||
) {
|
) {
|
||||||
return renderToStaticMarkup(
|
return renderToStaticMarkup(
|
||||||
<App
|
<App
|
||||||
@@ -51,6 +58,8 @@ function render(
|
|||||||
organizationAccess: { permissions: ['finance'] },
|
organizationAccess: { permissions: ['finance'] },
|
||||||
history: [{ ...declaration, id: sourceId }],
|
history: [{ ...declaration, id: sourceId }],
|
||||||
canCorrect,
|
canCorrect,
|
||||||
|
canAuthoriseRelease,
|
||||||
|
release,
|
||||||
declarations: {
|
declarations: {
|
||||||
data: [],
|
data: [],
|
||||||
prev_page_url: null,
|
prev_page_url: null,
|
||||||
@@ -63,6 +72,42 @@ function render(
|
|||||||
/>,
|
/>,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
test('direction release preparation requires explicit capability and never submits on recovery', () => {
|
||||||
|
vi.spyOn(router, 'restore').mockImplementation((key) =>
|
||||||
|
key ===
|
||||||
|
`${identity}:correction:3:${declaration.declared_at}:false:release:data`
|
||||||
|
? {
|
||||||
|
reason: 'DIRECTION-RELEASE-DRAFT',
|
||||||
|
operation_key: 'synthetic-operation',
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
);
|
||||||
|
const post = vi.spyOn(router, 'post');
|
||||||
|
const html = render(true, 7, 4, 'finance', false, 3, true);
|
||||||
|
expect(html).toContain('DIRECTION-RELEASE-DRAFT');
|
||||||
|
expect(html).toContain('Autorizar levantamento');
|
||||||
|
expect(html).toContain('data-preparation-dirty="true"');
|
||||||
|
expect(render(true, 8, 4, 'finance', false, 3, true)).not.toContain(
|
||||||
|
'DIRECTION-RELEASE-DRAFT',
|
||||||
|
);
|
||||||
|
expect(render(true, 7, 4, 'finance', false, 3, false)).not.toContain(
|
||||||
|
'Autorizar levantamento',
|
||||||
|
);
|
||||||
|
expect(post).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('released declaration retains its history and shows the direction decision', () => {
|
||||||
|
const html = render(true, 7, 4, 'finance', false, 3, false, {
|
||||||
|
id: 1,
|
||||||
|
authorised_by: 9,
|
||||||
|
authorised_at: '2026-11-28T09:00:00Z',
|
||||||
|
reason: 'DIRECTION-AUTHORISED-QA',
|
||||||
|
});
|
||||||
|
expect(html).toContain('Impedimento levantado pela direcção');
|
||||||
|
expect(html).toContain('Original synthetic conflict');
|
||||||
|
expect(html).toContain('DIRECTION-AUTHORISED-QA');
|
||||||
|
expect(html).not.toContain('Autorizar levantamento</button>');
|
||||||
|
});
|
||||||
test('personal declaration preparation remains private to its actor company and context without submitting', () => {
|
test('personal declaration preparation remains private to its actor company and context without submitting', () => {
|
||||||
vi.spyOn(router, 'restore').mockImplementation((key) =>
|
vi.spyOn(router, 'restore').mockImplementation((key) =>
|
||||||
key === `${identity}:new:data`
|
key === `${identity}:new:data`
|
||||||
|
|||||||
@@ -3,7 +3,12 @@ import { renderToStaticMarkup } from 'react-dom/server';
|
|||||||
import { expect, test } from 'vitest';
|
import { expect, test } from 'vitest';
|
||||||
import Legal from '../../resources/js/pages/supply/import-legal';
|
import Legal from '../../resources/js/pages/supply/import-legal';
|
||||||
|
|
||||||
function renderLegal(canManage: boolean, withRule = true, withCharges = false) {
|
function renderLegal(
|
||||||
|
canManage: boolean,
|
||||||
|
withRule = true,
|
||||||
|
withCharges = false,
|
||||||
|
withReference = false,
|
||||||
|
) {
|
||||||
const data = {
|
const data = {
|
||||||
title: '<script>synthetic rule</script>',
|
title: '<script>synthetic rule</script>',
|
||||||
official_reference: 'Synthetic official edition',
|
official_reference: 'Synthetic official edition',
|
||||||
@@ -58,6 +63,25 @@ function renderLegal(canManage: boolean, withRule = true, withCharges = false) {
|
|||||||
encryptHistory: true,
|
encryptHistory: true,
|
||||||
props: {
|
props: {
|
||||||
errors: {},
|
errors: {},
|
||||||
|
referenceDrafts: withReference
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
source_id: 8,
|
||||||
|
code: '3506.91.20',
|
||||||
|
description:
|
||||||
|
'Silicone para selagem de painéis solares',
|
||||||
|
rate_percent: '20',
|
||||||
|
title: 'Taxa geral documental',
|
||||||
|
official_reference: 'Lei 8/2025',
|
||||||
|
official_url: null,
|
||||||
|
citation: 'Página 2180-(4)',
|
||||||
|
valid_from: '2026-01-01',
|
||||||
|
obligations:
|
||||||
|
'Conferir o exemplar e o regime aplicável',
|
||||||
|
charges: [],
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: [],
|
||||||
requisition: { id: 1, number: 'QA' },
|
requisition: { id: 1, number: 'QA' },
|
||||||
rules: page,
|
rules: page,
|
||||||
history: page,
|
history: page,
|
||||||
@@ -78,6 +102,18 @@ function renderLegal(canManage: boolean, withRule = true, withCharges = false) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
test('official reference preparation is explicit and only available to the customs preparer', () => {
|
||||||
|
const allowed = renderLegal(true, false, false, true);
|
||||||
|
expect(allowed).toContain('Preparar a partir do exemplar oficial');
|
||||||
|
expect(allowed).toContain('3506.91.20');
|
||||||
|
expect(allowed).toContain('taxa geral 20%');
|
||||||
|
expect(allowed).toContain('não é uma pauta consolidada');
|
||||||
|
expect(allowed).toContain('não substituir');
|
||||||
|
const reader = renderLegal(false, false, false, true);
|
||||||
|
expect(reader).not.toContain('Preparar a partir do exemplar oficial');
|
||||||
|
expect(reader).not.toContain('Silicone para selagem');
|
||||||
|
});
|
||||||
|
|
||||||
test('legal consultation escapes titles preserves periods and offers verified-source downloads without management controls', () => {
|
test('legal consultation escapes titles preserves periods and offers verified-source downloads without management controls', () => {
|
||||||
const html = renderLegal(false);
|
const html = renderLegal(false);
|
||||||
expect(html).toContain('<script>synthetic rule</script>');
|
expect(html).toContain('<script>synthetic rule</script>');
|
||||||
|
|||||||
@@ -0,0 +1,142 @@
|
|||||||
|
import { App, router } from '@inertiajs/react';
|
||||||
|
import { renderToStaticMarkup } from 'react-dom/server';
|
||||||
|
import { afterEach, expect, test, vi } from 'vitest';
|
||||||
|
import OperationalOrders from '@/pages/requisitions/operational-orders';
|
||||||
|
import Summary from '@/components/operational-order-summary';
|
||||||
|
import { procurementNavigation } from '@/lib/procurement-navigation';
|
||||||
|
|
||||||
|
afterEach(() => vi.restoreAllMocks());
|
||||||
|
const source = {
|
||||||
|
id: 5,
|
||||||
|
version: 1,
|
||||||
|
created_at: '2026-11-28T10:00:00Z',
|
||||||
|
reason: 'Synthetic source',
|
||||||
|
data: {
|
||||||
|
type: 'production',
|
||||||
|
reference: 'SOURCE-ORDER-QA',
|
||||||
|
utilisation_location: 'Synthetic line',
|
||||||
|
description: '<script>private-test</script>',
|
||||||
|
department_id: 1,
|
||||||
|
},
|
||||||
|
snapshot: {
|
||||||
|
author: { name: 'Synthetic procurement' },
|
||||||
|
department: { name: 'Synthetic department' },
|
||||||
|
policy: { data: { mode: 'procurement' } },
|
||||||
|
},
|
||||||
|
};
|
||||||
|
function render(
|
||||||
|
actor = 7,
|
||||||
|
canConfigure = true,
|
||||||
|
allowedTypes = ['production', 'maintenance'],
|
||||||
|
linked = false,
|
||||||
|
) {
|
||||||
|
return renderToStaticMarkup(
|
||||||
|
<App
|
||||||
|
initialComponent={OperationalOrders}
|
||||||
|
initialPage={{
|
||||||
|
component: 'requisitions/operational-orders',
|
||||||
|
url: '/ordens-operacionais',
|
||||||
|
version: null,
|
||||||
|
clearHistory: false,
|
||||||
|
encryptHistory: true,
|
||||||
|
props: {
|
||||||
|
errors: {},
|
||||||
|
auth: {
|
||||||
|
user: {
|
||||||
|
id: actor,
|
||||||
|
tenant_id: 4,
|
||||||
|
name: 'Synthetic actor',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
workContext: { active: 'procurement.internal' },
|
||||||
|
organizationAccess: {
|
||||||
|
permissions: ['procurement', 'requester'],
|
||||||
|
},
|
||||||
|
policy: {
|
||||||
|
id: 1,
|
||||||
|
version: 1,
|
||||||
|
data: { mode: 'procurement' },
|
||||||
|
},
|
||||||
|
canConfigure,
|
||||||
|
allowedTypes,
|
||||||
|
departments: [{ id: 1, name: 'Synthetic department' }],
|
||||||
|
orders: {
|
||||||
|
data: [source],
|
||||||
|
prev_page_url: null,
|
||||||
|
next_page_url: null,
|
||||||
|
},
|
||||||
|
requisition: linked
|
||||||
|
? { id: 3, number: 'REQ-QA', status: 'draft' }
|
||||||
|
: null,
|
||||||
|
items: linked
|
||||||
|
? [{ id: 8, description: 'Synthetic item' }]
|
||||||
|
: [],
|
||||||
|
links: [],
|
||||||
|
canLink: linked,
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
test('order preparation restores only its actor context and policy without automatic creation', () => {
|
||||||
|
const identity =
|
||||||
|
'procurement-preparations:4:7:procurement.internal:procurement,requester:operational-orders:1:1:production,maintenance:true:0:false';
|
||||||
|
vi.spyOn(router, 'restore').mockImplementation((key) =>
|
||||||
|
key === `${identity}:new:form:data`
|
||||||
|
? {
|
||||||
|
type: 'production',
|
||||||
|
reference: 'RESTORED-ORDER-DRAFT',
|
||||||
|
department_id: '1',
|
||||||
|
utilisation_location: 'Synthetic location',
|
||||||
|
description: 'Synthetic pending work',
|
||||||
|
reason: 'Synthetic pending reason',
|
||||||
|
policy_version: '1',
|
||||||
|
operation_key: '36cb64ea-0867-4be4-90ea-c0e114ec07b1',
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
);
|
||||||
|
const post = vi.spyOn(router, 'post');
|
||||||
|
const html = render();
|
||||||
|
expect(html).toContain('RESTORED-ORDER-DRAFT');
|
||||||
|
expect(html).toContain('data-preparation-dirty="true"');
|
||||||
|
expect(render(8)).not.toContain('RESTORED-ORDER-DRAFT');
|
||||||
|
expect(post).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
test('native capabilities control configuration creation and request linking independently', () => {
|
||||||
|
const html = render(7, false, [], true);
|
||||||
|
expect(html).not.toContain('Guardar origem das novas ordens');
|
||||||
|
expect(html).not.toContain('>Registar ordem</button>');
|
||||||
|
expect(html).toContain('Ligar ordem à linha');
|
||||||
|
expect(html).toContain('SOURCE-ORDER-QA');
|
||||||
|
expect(html).not.toContain('<script>private-test</script>');
|
||||||
|
});
|
||||||
|
test('order origin summary preserves the source responsibility and renders no empty section', () => {
|
||||||
|
expect(renderToStaticMarkup(<Summary />)).toBe('');
|
||||||
|
const html = renderToStaticMarkup(
|
||||||
|
<Summary
|
||||||
|
records={{
|
||||||
|
8: {
|
||||||
|
id: 9,
|
||||||
|
snapshot: {
|
||||||
|
item: { description: 'Synthetic item' },
|
||||||
|
source,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
expect(html).toContain('SOURCE-ORDER-QA');
|
||||||
|
expect(html).toContain('Synthetic procurement');
|
||||||
|
expect(html).toContain('Registada pelo procurement');
|
||||||
|
expect(html).not.toContain('<script>private-test</script>');
|
||||||
|
});
|
||||||
|
test('operational order navigation requires server readiness and an applicable capability', () => {
|
||||||
|
const has = (permissions: string[], ready: boolean) =>
|
||||||
|
procurementNavigation(permissions, false, undefined, false, ready)
|
||||||
|
.flatMap((group) => group.entries)
|
||||||
|
.some((entry) => entry.id === 'operational_orders');
|
||||||
|
expect(has(['production_order_prepare'], true)).toBe(true);
|
||||||
|
expect(has(['maintenance_order_prepare'], true)).toBe(true);
|
||||||
|
expect(has(['procurement'], false)).toBe(false);
|
||||||
|
expect(has(['finance'], true)).toBe(false);
|
||||||
|
});
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import { App, router } from '@inertiajs/react';
|
||||||
|
import { renderToStaticMarkup } from 'react-dom/server';
|
||||||
|
import { afterEach, expect, test, vi } from 'vitest';
|
||||||
|
import PrivateAudit from '@/pages/audit/private';
|
||||||
|
import { procurementNavigation } from '@/lib/procurement-navigation';
|
||||||
|
|
||||||
|
afterEach(() => vi.restoreAllMocks());
|
||||||
|
|
||||||
|
test('private audit preparation shows only granted families and does not submit on opening', () => {
|
||||||
|
const post = vi.spyOn(router, 'post');
|
||||||
|
const html = renderToStaticMarkup(
|
||||||
|
<App
|
||||||
|
initialComponent={PrivateAudit}
|
||||||
|
initialPage={{
|
||||||
|
component: 'audit/private',
|
||||||
|
url: '/auditoria/privada',
|
||||||
|
version: null,
|
||||||
|
clearHistory: false,
|
||||||
|
encryptHistory: true,
|
||||||
|
props: {
|
||||||
|
errors: {},
|
||||||
|
auth: {
|
||||||
|
user: {
|
||||||
|
id: 7,
|
||||||
|
tenant_id: 4,
|
||||||
|
name: 'Synthetic auditor',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
organizationAccess: {
|
||||||
|
permissions: ['audit_private_stock_read'],
|
||||||
|
},
|
||||||
|
families: [{ key: 'stock', label: 'Stock autorizado' }],
|
||||||
|
exports: {
|
||||||
|
data: [],
|
||||||
|
prev_page_url: null,
|
||||||
|
next_page_url: null,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
expect(html).toContain('Stock autorizado');
|
||||||
|
expect(html).not.toContain('value="finance"');
|
||||||
|
expect(html).toContain('disabled');
|
||||||
|
expect(post).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('private audit navigation needs both QA availability and dedicated family authority', () => {
|
||||||
|
const paths = (permissions: string[], available: boolean) =>
|
||||||
|
procurementNavigation(
|
||||||
|
permissions,
|
||||||
|
false,
|
||||||
|
undefined,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
available,
|
||||||
|
).flatMap((group) => group.entries.map((entry) => entry.path));
|
||||||
|
expect(paths(['audit_private_stock_read'], true)).toContain(
|
||||||
|
'/auditoria/privada',
|
||||||
|
);
|
||||||
|
expect(paths(['audit_private_stock_read'], false)).not.toContain(
|
||||||
|
'/auditoria/privada',
|
||||||
|
);
|
||||||
|
for (const permission of ['audit_metadata_read', 'finance', 'admin']) {
|
||||||
|
expect(paths([permission], true)).not.toContain('/auditoria/privada');
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -30,7 +30,22 @@ function render(
|
|||||||
component: 'test',
|
component: 'test',
|
||||||
url: '/teste',
|
url: '/teste',
|
||||||
version: null,
|
version: null,
|
||||||
props: { errors: {}, ...props },
|
props: {
|
||||||
|
errors: {},
|
||||||
|
auth: {
|
||||||
|
user: {
|
||||||
|
id: 12,
|
||||||
|
tenant_id: 4,
|
||||||
|
name: 'Synthetic banking reader',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
workContext: { active: 'procurement.internal' },
|
||||||
|
organizationAccess: {
|
||||||
|
active: true,
|
||||||
|
permissions: props.canManage ? ['finance'] : ['admin'],
|
||||||
|
},
|
||||||
|
...props,
|
||||||
|
},
|
||||||
clearHistory: false,
|
clearHistory: false,
|
||||||
encryptHistory: true,
|
encryptHistory: true,
|
||||||
} satisfies Page;
|
} satisfies Page;
|
||||||
|
|||||||
@@ -0,0 +1,153 @@
|
|||||||
|
import { App, router } from '@inertiajs/react';
|
||||||
|
import { renderToStaticMarkup } from 'react-dom/server';
|
||||||
|
import { afterEach, expect, test, vi } from 'vitest';
|
||||||
|
import UrgentStock from '@/pages/requisitions/urgent-stock';
|
||||||
|
import Summary from '@/components/urgent-quotation-summary';
|
||||||
|
import { ComparisonPolicySummary } from '@/components/comparison-policy-summary';
|
||||||
|
|
||||||
|
afterEach(() => vi.restoreAllMocks());
|
||||||
|
const policy = {
|
||||||
|
revision: 2,
|
||||||
|
configured: true,
|
||||||
|
minimum_proposals: 3,
|
||||||
|
minimum_evaluators: 2,
|
||||||
|
urgent_minimum_proposals: 1,
|
||||||
|
weights: { price: 40, quality: 20, delivery: 15, history: 15, payment: 10 },
|
||||||
|
};
|
||||||
|
const proof = {
|
||||||
|
id: 9,
|
||||||
|
version: 1,
|
||||||
|
created_at: '2026-11-28T10:00:00Z',
|
||||||
|
reason: 'SYNTHETIC-STOCK-PROOF',
|
||||||
|
data: { requisition_item_id: 8 },
|
||||||
|
snapshot: {
|
||||||
|
item: { description: 'Synthetic material' },
|
||||||
|
stock_policy: {
|
||||||
|
minimum_stock_milli: 20000,
|
||||||
|
usage_context: 'Daily synthetic production',
|
||||||
|
warehouse: { name: 'Synthetic warehouse' },
|
||||||
|
},
|
||||||
|
availability: { free_milli: null },
|
||||||
|
author: { name: 'Synthetic procurement' },
|
||||||
|
},
|
||||||
|
};
|
||||||
|
function render(
|
||||||
|
actor = 7,
|
||||||
|
canRecord = true,
|
||||||
|
evidence = false,
|
||||||
|
configured = true,
|
||||||
|
) {
|
||||||
|
return renderToStaticMarkup(
|
||||||
|
<App
|
||||||
|
initialComponent={UrgentStock}
|
||||||
|
initialPage={{
|
||||||
|
component: 'requisitions/urgent-stock',
|
||||||
|
url: '/requisicoes/3/urgencia-stock',
|
||||||
|
version: null,
|
||||||
|
clearHistory: false,
|
||||||
|
encryptHistory: true,
|
||||||
|
props: {
|
||||||
|
errors: {},
|
||||||
|
auth: {
|
||||||
|
user: {
|
||||||
|
id: actor,
|
||||||
|
tenant_id: 4,
|
||||||
|
name: 'Synthetic actor',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
workContext: { active: 'procurement.internal' },
|
||||||
|
organizationAccess: { permissions: ['procurement'] },
|
||||||
|
requisition: {
|
||||||
|
id: 3,
|
||||||
|
number: 'REQ-QA',
|
||||||
|
priority: 'urgent',
|
||||||
|
justification: 'Synthetic risk of stopping production.',
|
||||||
|
},
|
||||||
|
cycle: 1,
|
||||||
|
canRecord,
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
id: 8,
|
||||||
|
description: 'Synthetic material',
|
||||||
|
catalogue_snapshot: { stock_item_id: 1 },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
comparisonPolicy: configured
|
||||||
|
? policy
|
||||||
|
: { ...policy, urgent_minimum_proposals: undefined },
|
||||||
|
policies: {
|
||||||
|
data: [
|
||||||
|
{
|
||||||
|
id: 11,
|
||||||
|
version: 2,
|
||||||
|
stock_item_id: 1,
|
||||||
|
item: {
|
||||||
|
name: 'Synthetic material',
|
||||||
|
unit: 'un',
|
||||||
|
},
|
||||||
|
warehouse: { name: 'Synthetic warehouse' },
|
||||||
|
minimum_stock_milli: 20000,
|
||||||
|
usage_context: 'Daily synthetic production',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
prev_page_url: null,
|
||||||
|
next_page_url: null,
|
||||||
|
},
|
||||||
|
evidence: evidence ? [proof] : [],
|
||||||
|
eligible: evidence ? [proof] : [],
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
test('urgent stock preparation is scoped to actor process cycle and immutable evidence version without automatic submission', () => {
|
||||||
|
const identity =
|
||||||
|
'procurement-preparations:4:7:procurement.internal:procurement:urgent-stock:3:1:2:8:0';
|
||||||
|
vi.spyOn(router, 'restore').mockImplementation((key) =>
|
||||||
|
key === `${identity}:form:data`
|
||||||
|
? {
|
||||||
|
item_id: 8,
|
||||||
|
policy_id: '11',
|
||||||
|
version: 0,
|
||||||
|
reason: 'RESTORED-URGENT-STOCK-DRAFT',
|
||||||
|
operation_key: '117ed627-098c-49a8-a324-d75c4c989473',
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
);
|
||||||
|
const post = vi.spyOn(router, 'post');
|
||||||
|
expect(render()).toContain('RESTORED-URGENT-STOCK-DRAFT');
|
||||||
|
expect(render()).toContain('data-preparation-dirty="true"');
|
||||||
|
expect(render(8)).not.toContain('RESTORED-URGENT-STOCK-DRAFT');
|
||||||
|
expect(render(7, true, true)).not.toContain('RESTORED-URGENT-STOCK-DRAFT');
|
||||||
|
expect(post).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
test('approval readers see the evidence without being granted the preparation command', () => {
|
||||||
|
const html = render(7, false, true);
|
||||||
|
expect(html).toContain('SYNTHETIC-STOCK-PROOF');
|
||||||
|
expect(html).toContain('Indeterminado');
|
||||||
|
expect(html).not.toContain('>Conferir stock mínimo</button>');
|
||||||
|
expect(render(7, true, false, false)).not.toContain(
|
||||||
|
'>Conferir stock mínimo</button>',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
test('comparison distinguishes the ordinary count from an applied urgent count and preserves independent evaluations', () => {
|
||||||
|
const html = renderToStaticMarkup(
|
||||||
|
<ComparisonPolicySummary
|
||||||
|
policy={{
|
||||||
|
...policy,
|
||||||
|
minimum_proposals: 1,
|
||||||
|
normal_minimum_proposals: 3,
|
||||||
|
}}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
expect(html).toContain('mínimo de 1 propostas');
|
||||||
|
expect(html).toContain('mínimo normal é 3');
|
||||||
|
expect(html).toContain('2 avaliações');
|
||||||
|
});
|
||||||
|
test('frozen stock basis summary has no empty section and never represents unknown free stock as zero', () => {
|
||||||
|
expect(renderToStaticMarkup(<Summary />)).toBe('');
|
||||||
|
const html = renderToStaticMarkup(<Summary records={[proof]} />);
|
||||||
|
expect(html).toContain('SYNTHETIC-STOCK-PROOF');
|
||||||
|
expect(html).toContain('Indeterminado');
|
||||||
|
expect(html).toContain('Daily synthetic production');
|
||||||
|
});
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 251 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 226 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 168 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 191 KiB |
Reference in New Issue
Block a user