@@ -13,6 +13,7 @@ use App\Services\OrganizationAccess;
|
||||
use App\Services\OrganizationActivationPreview;
|
||||
use App\Services\OrganizationConfiguration;
|
||||
use App\Services\RequisitionApprovalLevels;
|
||||
use App\Services\RequisitionCategories;
|
||||
use App\Services\WorkContext;
|
||||
use App\Services\WorkflowTasks;
|
||||
use Brick\Math\BigDecimal;
|
||||
@@ -44,6 +45,7 @@ class OrganizationConfigurationController extends Controller
|
||||
'geography' => app(AdministrativeGeography::class)->describe(Tenant::query()->findOrFail($actor->tenant_id)->geography_reference),
|
||||
'companyDetailsReady' => Schema::hasColumn('tenants', 'company_details'),
|
||||
'approvalLevelsReady' => app(RequisitionApprovalLevels::class)->ready(),
|
||||
'requisitionCategoryOptions' => app(RequisitionCategories::class)->available() ? RequisitionCategories::LABELS : [],
|
||||
'approvalLevels' => Tenant::query()->findOrFail($actor->tenant_id)->requisition_approval_policy,
|
||||
'companyDetails' => Tenant::query()->findOrFail($actor->tenant_id)->company_details,
|
||||
'companyRules' => $this->companyRules((int) $actor->tenant_id),
|
||||
|
||||
@@ -13,6 +13,7 @@ use App\Models\Supplier;
|
||||
use App\Models\User;
|
||||
use App\Models\Warehouse;
|
||||
use App\Services\OrganizationAccess;
|
||||
use App\Services\SavedProcurementSearches;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
@@ -29,7 +30,7 @@ class ProcurementSearchController extends Controller
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||
abort_unless(app(OrganizationAccess::class)->permissions($actor) !== [], 403);
|
||||
$request->setUserResolver(fn () => $actor);
|
||||
$data = $request->validate(['q' => 'nullable|string|max:100', 'requests_page' => 'nullable|integer|min:1|max:1000000', 'orders_page' => 'nullable|integer|min:1|max:1000000', 'suppliers_page' => 'nullable|integer|min:1|max:1000000']);
|
||||
$data = $request->validate(['q' => 'nullable|string|max:100', 'archived_page' => 'nullable|integer|min:1|max:1000000', 'requests_page' => 'nullable|integer|min:1|max:1000000', 'orders_page' => 'nullable|integer|min:1|max:1000000', 'suppliers_page' => 'nullable|integer|min:1|max:1000000']);
|
||||
$term = trim($data['q'] ?? '');
|
||||
$request->validate(['invoices_page' => 'nullable|integer|min:1|max:1000000']);
|
||||
$request->validate(['equipment_page' => 'nullable|integer|min:1|max:1000000', 'stock_page' => 'nullable|integer|min:1|max:1000000', 'warehouses_page' => 'nullable|integer|min:1|max:1000000', 'receipts_page' => 'nullable|integer|min:1|max:1000000']);
|
||||
@@ -97,6 +98,7 @@ class ProcurementSearchController extends Controller
|
||||
});
|
||||
Inertia::encryptHistory();
|
||||
$response = Inertia::render('search/procurement', ['term' => $term, 'groups' => $groups,
|
||||
'savedSearches' => app(SavedProcurementSearches::class)->read($actor),
|
||||
'invoiceSearchAvailable' => config('procurement_search.finance_metadata_enabled') === true && $actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance]),
|
||||
])->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
@@ -21,6 +21,7 @@ use App\Services\OrganizationAccess;
|
||||
use App\Services\RequisitionAuditTrail;
|
||||
use App\Services\RequisitionBudgetDistributions;
|
||||
use App\Services\RequisitionCatalogue;
|
||||
use App\Services\RequisitionCategories;
|
||||
use App\Services\RequisitionDraftInput;
|
||||
use App\Services\RequisitionWorkflow;
|
||||
use App\Services\SupplySuggestions;
|
||||
@@ -77,6 +78,7 @@ class RequisitionController extends Controller
|
||||
return Inertia::render('requisitions/form', [
|
||||
'costCenters' => CostCenter::query()->where('department_id', $this->actor($request)->department_id)->orderBy('code')->get(),
|
||||
'requisition' => null,
|
||||
'requisitionCategories' => app(RequisitionCategories::class)->available() ? RequisitionCategories::LABELS : [],
|
||||
'incompleteDraftsAvailable' => app(RequisitionDraftInput::class)->available(),
|
||||
'defaultTaxRate' => (string) (Tenant::query()->findOrFail($this->actor($request)->tenant_id)->default_tax_rate ?? '16.00'),
|
||||
...$this->equipmentOptions($request),
|
||||
@@ -167,6 +169,7 @@ class RequisitionController extends Controller
|
||||
|
||||
return Inertia::render('requisitions/form', [
|
||||
'requisition' => $requisition->load('items'),
|
||||
'requisitionCategories' => app(RequisitionCategories::class)->available() ? RequisitionCategories::LABELS : [],
|
||||
'incompleteDraftsAvailable' => app(RequisitionDraftInput::class)->available(),
|
||||
'defaultTaxRate' => (string) (Tenant::query()->findOrFail($this->actor($request)->tenant_id)->default_tax_rate ?? '16.00'),
|
||||
'costCenters' => CostCenter::query()->where('department_id', $this->actor($request)->department_id)->orderBy('code')->get(),
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\SavedProcurementSearches;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
final class SavedProcurementSearchController extends Controller
|
||||
{
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
return $this->change($request, 'save');
|
||||
}
|
||||
|
||||
public function update(Request $request, int $search): RedirectResponse
|
||||
{
|
||||
return $this->change($request, 'save', $search);
|
||||
}
|
||||
|
||||
public function archive(Request $request, int $search): RedirectResponse
|
||||
{
|
||||
return $this->change($request, 'archive', $search);
|
||||
}
|
||||
|
||||
public function restore(Request $request, int $search): RedirectResponse
|
||||
{
|
||||
return $this->change($request, 'restore', $search);
|
||||
}
|
||||
|
||||
private function change(Request $request, string $action, ?int $id = null): RedirectResponse
|
||||
{
|
||||
$actor = $request->user('web');
|
||||
abort_unless($actor instanceof User, 403);
|
||||
$query = $request->validate(['q' => 'nullable|string|max:100']);
|
||||
app(SavedProcurementSearches::class)->command($actor, $action, $id, $request->all());
|
||||
|
||||
return to_route('procurement.search', ['q' => $query['q'] ?? '']);
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ use Illuminate\Database\Eloquent\Model;
|
||||
* @property int|null $spare_part_id
|
||||
* @property int|null $catalogue_entry_id
|
||||
* @property array<string,mixed>|null $catalogue_snapshot
|
||||
* @property array<string,mixed>|null $category_context
|
||||
*/
|
||||
class RequisitionItem extends Model
|
||||
{
|
||||
@@ -25,6 +26,6 @@ class RequisitionItem extends Model
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['quantity' => 'decimal:3', 'tax_rate' => 'decimal:2', 'catalogue_entry_id' => 'integer', 'catalogue_snapshot' => 'array'];
|
||||
return ['quantity' => 'decimal:3', 'tax_rate' => 'decimal:2', 'catalogue_entry_id' => 'integer', 'catalogue_snapshot' => 'array', 'category_context' => 'array'];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Providers;
|
||||
|
||||
use App\Services\AdministrativeGeography;
|
||||
use App\Services\BudgetDistributionArtifact;
|
||||
use App\Services\FinanceBundle;
|
||||
use App\Services\ReplenishmentRun;
|
||||
use Carbon\CarbonImmutable;
|
||||
@@ -22,6 +23,10 @@ class AppServiceProvider extends ServiceProvider
|
||||
$this->app->scoped(AdministrativeGeography::class);
|
||||
require_once base_path('packages/purchasing/bootstrap.php');
|
||||
$package = config('common-budget.path');
|
||||
if (config('budget-distributions.enabled') === true) {
|
||||
BudgetDistributionArtifact::verify($package,
|
||||
config('budget-distributions.artifact_manifest'), config('budget-distributions.artifact_manifest_sha256'));
|
||||
}
|
||||
require_once $package.'/bootstrap.php';
|
||||
FinanceBundle::configure();
|
||||
$payables = config('common-payables.path');
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
/** Verify the separately selected release before any of its executable PHP is loaded. */
|
||||
final class BudgetDistributionArtifact
|
||||
{
|
||||
private const FILES = ['bootstrap.php', 'src/BudgetContext.php', 'src/BudgetFailure.php', 'src/BudgetControl.php', 'src/BudgetDistributionPlan.php', 'src/BudgetDistributions.php', 'README.md'];
|
||||
|
||||
public static function verify(mixed $directory, mixed $manifest, mixed $pin): void
|
||||
{
|
||||
if (! is_string($directory) || ! is_string($manifest) || ! is_string($pin)
|
||||
|| ! preg_match('/^[a-f0-9]{64}$/D', $pin) || is_link($directory) || is_link($manifest)) {
|
||||
throw new \LogicException('BUDGET_DISTRIBUTION_ARTIFACT_CONFIGURATION');
|
||||
}
|
||||
$root = realpath($directory);
|
||||
$bytes = is_file($manifest) ? file_get_contents($manifest) : false;
|
||||
if ($root === false || ! is_string($bytes) || ! hash_equals($pin, hash('sha256', $bytes))) {
|
||||
throw new \LogicException('BUDGET_DISTRIBUTION_MANIFEST_MISMATCH');
|
||||
}
|
||||
$data = json_decode($bytes, true, 32, JSON_THROW_ON_ERROR);
|
||||
if (! is_array($data) || ! isset($data['files']) || ! is_array($data['files'])
|
||||
|| array_keys($data['files']) !== self::FILES) {
|
||||
throw new \LogicException('BUDGET_DISTRIBUTION_INVENTORY_MISMATCH');
|
||||
}
|
||||
foreach (self::FILES as $file) {
|
||||
$path = $root.'/'.$file;
|
||||
$expected = $data['files'][$file];
|
||||
$resolved = realpath($path);
|
||||
$actual = is_file($path) ? hash_file('sha256', $path) : false;
|
||||
if (! is_string($expected) || ! preg_match('/^[a-f0-9]{64}$/D', $expected)
|
||||
|| $resolved === false || ! str_starts_with(str_replace('\\', '/', $resolved), str_replace('\\', '/', $root).'/')
|
||||
|| is_link($path) || ! is_string($actual) || ! hash_equals($expected, $actual)) {
|
||||
throw new \LogicException('BUDGET_DISTRIBUTION_FILE_MISMATCH:'.$file);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/** One schema definition for guarded QA and explicitly authorised pilot installation. */
|
||||
final class BudgetDistributionSchema
|
||||
{
|
||||
public static function install(): void
|
||||
{
|
||||
$db = DB::connection();
|
||||
$db->transaction(function () use ($db): void {
|
||||
$schema = $db->getSchemaBuilder();
|
||||
$schema->table('requisitions', fn (Blueprint $table) => $table->json('budget_distribution_preparation')->nullable());
|
||||
$schema->create('budget_distributions', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('tenant_id')->constrained()->restrictOnDelete();
|
||||
$table->foreignId('requisition_id')->unique()->constrained()->restrictOnDelete();
|
||||
$table->string('phase');
|
||||
$table->json('snapshot');
|
||||
$table->foreignId('created_by')->constrained('users')->restrictOnDelete();
|
||||
$table->timestamps();
|
||||
});
|
||||
$schema->create('budget_distribution_events', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('tenant_id')->constrained()->restrictOnDelete();
|
||||
$table->foreignId('distribution_id')->constrained('budget_distributions')->restrictOnDelete();
|
||||
$table->string('kind', 50);
|
||||
$table->uuid('operation_key');
|
||||
$table->string('payload_hash', 64);
|
||||
$table->json('result');
|
||||
$table->json('snapshot');
|
||||
$table->foreignId('created_by')->constrained('users')->restrictOnDelete();
|
||||
$table->timestamp('created_at');
|
||||
$table->unique(['tenant_id', 'operation_key']);
|
||||
$table->unique(['distribution_id', 'kind']);
|
||||
});
|
||||
$schema->create('budget_distribution_entries', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('tenant_id')->constrained()->restrictOnDelete();
|
||||
$table->foreignId('distribution_id')->constrained('budget_distributions')->restrictOnDelete();
|
||||
$table->string('allocation_key', 120);
|
||||
$table->foreignId('budget_id')->constrained('budgets')->restrictOnDelete();
|
||||
$table->string('kind', 50);
|
||||
$table->bigInteger('reserved_minor');
|
||||
$table->bigInteger('committed_minor');
|
||||
$table->foreignId('created_by')->constrained('users')->restrictOnDelete();
|
||||
$table->timestamp('created_at');
|
||||
$table->unique(['distribution_id', 'allocation_key', 'kind']);
|
||||
});
|
||||
$schema->create('budget_distribution_consumptions', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('tenant_id')->constrained()->restrictOnDelete();
|
||||
$table->foreignId('distribution_id')->constrained('budget_distributions')->restrictOnDelete();
|
||||
$table->string('allocation_key', 120);
|
||||
$table->foreignId('budget_id')->constrained('budgets')->restrictOnDelete();
|
||||
$table->foreignId('invoice_id')->constrained('invoices')->restrictOnDelete();
|
||||
$table->bigInteger('amount_minor');
|
||||
$table->bigInteger('subtotal_minor');
|
||||
$table->bigInteger('total_minor');
|
||||
$table->foreignId('created_by')->constrained('users')->restrictOnDelete();
|
||||
$table->timestamp('created_at');
|
||||
$table->unique(['invoice_id', 'allocation_key']);
|
||||
});
|
||||
if ($db->getDriverName() === 'pgsql') {
|
||||
$db->unprepared("CREATE OR REPLACE FUNCTION sgc_distribution_history_guard() RETURNS trigger LANGUAGE plpgsql AS 'BEGIN RAISE EXCEPTION ''Distribution history is append only''; END'");
|
||||
foreach (['budget_distribution_events', 'budget_distribution_entries', 'budget_distribution_consumptions'] as $table) {
|
||||
$db->statement('CREATE TRIGGER distribution_history_guard BEFORE UPDATE OR DELETE ON '.$table.' FOR EACH ROW EXECUTE FUNCTION sgc_distribution_history_guard()');
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -17,10 +17,23 @@ final class CommonBudget
|
||||
{
|
||||
public const DISTRIBUTIONS_CONTRACT = 'COMMON-BUDGET-DISTRIBUTION-QA-v1';
|
||||
|
||||
public const ORDER_PARTS_CONTRACT = 'COMMON-BUDGET-ORDER-PARTS-QA-v1';
|
||||
|
||||
public function for(User $user): BudgetControl
|
||||
{
|
||||
abort_unless(auth()->id() === $user->id && $user->tenant_id !== null, 403);
|
||||
$runtime = new \ReflectionClass(BudgetControl::class);
|
||||
$orderTables = ['budget_order_commands', 'budget_order_bindings', 'budget_order_allocations', 'budget_order_consumptions'];
|
||||
$orderPresent = array_values(array_filter($orderTables, fn ($table) => Schema::hasTable($table)));
|
||||
abort_if(count($orderPresent) !== 0 && count($orderPresent) !== count($orderTables), 503,
|
||||
'Estrutura de ordens parciais incompleta; saldo não presumido.');
|
||||
if (! $runtime->hasConstant('ORDER_PARTS_VERSION') || $runtime->getConstant('ORDER_PARTS_VERSION') !== self::ORDER_PARTS_CONTRACT
|
||||
|| ! $runtime->hasMethod('commitOrderParts') || ! $runtime->hasMethod('consumeOrderParts')) {
|
||||
foreach ($orderPresent as $table) {
|
||||
abort_if(DB::table($table)->where('tenant_id', $user->tenant_id)->exists(), 503,
|
||||
'Existem efeitos de ordens parciais; preserve a composição compatível antes de consultar saldos.');
|
||||
}
|
||||
}
|
||||
$distributionsCompatible = $runtime->hasMethod('recordDistribution') && $runtime->hasConstant('DISTRIBUTIONS_VERSION')
|
||||
&& $runtime->getConstant('DISTRIBUTIONS_VERSION') === self::DISTRIBUTIONS_CONTRACT;
|
||||
if (! $distributionsCompatible) {
|
||||
@@ -40,7 +53,8 @@ final class CommonBudget
|
||||
abort_unless(DB::table('tenants')->where('id', $user->tenant_id)->value('currency') === 'MZN', 422, 'Moeda da organização incompatível com esta entrega.');
|
||||
$roles = in_array($action, ['create', 'approve', 'reinforcement.propose', 'reinforcement.review', 'view'], true)
|
||||
? [PurchasingRole::Admin, PurchasingRole::Finance]
|
||||
: (in_array($action, ['consume', 'consume.preview', 'distribution.amend'], true) ? [PurchasingRole::Finance] : null);
|
||||
: (in_array($action, ['consume', 'consume.preview', 'distribution.amend'], true) ? [PurchasingRole::Finance]
|
||||
: (in_array($action, ['orders.commit', 'orders.cancel', 'orders.adopt'], true) ? [PurchasingRole::Procurement] : null));
|
||||
app(CurrentActor::class)->lock($user, $roles);
|
||||
},
|
||||
function (string $action, array $data, ?int $origin) use ($user): void {
|
||||
|
||||
@@ -49,7 +49,17 @@ class EquipmentWorkflow
|
||||
|
||||
public function basis(Requisition $requisition): string
|
||||
{
|
||||
return hash('sha256', json_encode([$requisition->only(['id', 'tenant_id', 'department_id', 'requester_id', 'priority', 'needed_by', 'justification', 'total_minor']), $requisition->items()->orderBy('id')->get()->toArray()], JSON_THROW_ON_ERROR));
|
||||
$items = $requisition->items()->orderBy('id')->get()->map(function ($item) {
|
||||
$row = $item->toArray();
|
||||
// Adding an empty optional classification must not invalidate an accepted review.
|
||||
if (($row['category_context'] ?? null) === null) {
|
||||
unset($row['category_context']);
|
||||
}
|
||||
|
||||
return $row;
|
||||
})->all();
|
||||
|
||||
return hash('sha256', json_encode([$requisition->only(['id', 'tenant_id', 'department_id', 'requester_id', 'priority', 'needed_by', 'justification', 'total_minor']), $items], JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
public function canReview(User $user, Requisition $requisition): bool
|
||||
|
||||
@@ -10,7 +10,6 @@ use App\Models\PurchaseOrder;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\User;
|
||||
use Brick\Math\BigDecimal;
|
||||
use Brick\Math\RoundingMode;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
@@ -77,11 +76,10 @@ class InvoiceWorkflow
|
||||
$this->invalid('Preço, unidade e IVA devem coincidir exactamente com a ordem. Não há tolerância ou excepção configurada.');
|
||||
}
|
||||
// Cumulative rounding ensures partial invoices sum exactly to the frozen order.
|
||||
$subtotal = fn (int $milli) => BigDecimal::of($milli)->multipliedBy($source->unit_price_minor)->dividedBy(1000, 0, RoundingMode::HalfUp)->toInt();
|
||||
$tax = fn (int $minor) => BigDecimal::of($minor)->multipliedBy((string) $source->tax_rate)->dividedBy(100, 0, RoundingMode::HalfUp)->toInt();
|
||||
$before = $subtotal((int) $previous);
|
||||
$after = $subtotal((int) $previous + $quantity);
|
||||
$lines[] = ['tenant_id' => $order->tenant_id, 'purchase_order_item_id' => $source->id, 'quantity_milli' => $quantity, 'subtotal_minor' => $after - $before, 'tax_minor' => $tax($after) - $tax($before), 'snapshot' => $source->only(['description', 'unit', 'unit_price_minor', 'tax_rate'])];
|
||||
$amounts = PurchaseLineAmounts::portion($source->unit_price_minor, (string) $source->tax_rate, (int) $previous, $quantity);
|
||||
$lines[] = ['tenant_id' => $order->tenant_id, 'purchase_order_item_id' => $source->id, 'quantity_milli' => $quantity,
|
||||
'subtotal_minor' => $amounts['subtotal_minor'], 'tax_minor' => $amounts['tax_minor'],
|
||||
'snapshot' => $source->only(['description', 'unit', 'unit_price_minor', 'tax_rate'])];
|
||||
}
|
||||
if ($lines === []) {
|
||||
$this->invalid('Indique pelo menos uma linha.');
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\PurchaseAward;
|
||||
use App\Models\PurchaseOrderItem;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Tempo\Finance\Budget\BudgetControl;
|
||||
|
||||
/** Native approved-source and quantity preflight. Does not issue an order or move a budget. */
|
||||
final class OrderPartsPreparation
|
||||
{
|
||||
public function ready(): bool
|
||||
{
|
||||
$db = DB::connection();
|
||||
$isolated = ($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|
||||
|| ($db->getDriverName() === 'pgsql' && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName()));
|
||||
$runtime = new \ReflectionClass(BudgetControl::class);
|
||||
|
||||
return config('order-parts.qa_enabled') === true && app()->environment('testing') && $isolated
|
||||
&& $runtime->hasMethod('commitOrderParts') && $runtime->hasConstant('ORDER_PARTS_VERSION')
|
||||
&& $runtime->getConstant('ORDER_PARTS_VERSION') === CommonBudget::ORDER_PARTS_CONTRACT;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function prepare(User $actor, array $input): array
|
||||
{
|
||||
abort_unless($this->ready(), 503);
|
||||
$data = Validator::make($input, [
|
||||
'sources' => 'required|array|min:1|max:100',
|
||||
'sources.*' => 'required|array:award_id,items',
|
||||
'sources.*.award_id' => 'required|integer|min:1|distinct',
|
||||
'sources.*.items' => 'required|array|min:1|max:100',
|
||||
'sources.*.items.*' => 'required|array:quotation_item_id,quantity',
|
||||
'sources.*.items.*.quotation_item_id' => 'required|integer|min:1|distinct',
|
||||
'sources.*.items.*.quantity' => ['required', 'string', 'regex:/^\d{1,10}(?:\.\d{1,3})?$/D'],
|
||||
])->validate();
|
||||
|
||||
return DB::transaction(function () use ($actor, $data): array {
|
||||
app(ConflictGuard::class)->lockCompany($actor);
|
||||
$actor = app(CurrentActor::class)->lock($actor, [PurchasingRole::Procurement]);
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||
$sources = $data['sources'];
|
||||
usort($sources, fn ($a, $b) => $a['award_id'] <=> $b['award_id']);
|
||||
$result = [];
|
||||
$compatibility = null;
|
||||
foreach ($sources as $selection) {
|
||||
$award = PurchaseAward::query()->where('id', $selection['award_id'])->firstOrFail();
|
||||
$quote = app(PurchaseWorkflow::class)->approvedSource($actor, $award);
|
||||
$key = [$quote->tenant_id, $quote->supplier_id, $quote->currency];
|
||||
if ($compatibility !== null && $key !== $compatibility) {
|
||||
throw ValidationException::withMessages(['sources' => 'Consolide apenas adjudicações da mesma empresa, fornecedor e moeda documental.']);
|
||||
}
|
||||
$compatibility = $key;
|
||||
$lines = $quote->items()->orderBy('id')->lockForUpdate()->get()->keyBy('id');
|
||||
$prepared = [];
|
||||
foreach ($selection['items'] as $item) {
|
||||
$source = $lines->get($item['quotation_item_id']);
|
||||
abort_unless($source !== null, 422, 'Linha fora da proposta aprovada.');
|
||||
$ordered = PurchaseOrderItem::query()->where('requisition_item_id', $source->requisition_item_id)->orderBy('id')->lockForUpdate()->get();
|
||||
$before = 0;
|
||||
foreach ($ordered as $old) {
|
||||
// Cancelled lines remain used; cancellation never authorizes automatic reissue.
|
||||
$before += ReceiptWorkflow::milli($old->quantity);
|
||||
}
|
||||
$quantity = ReceiptWorkflow::milli($item['quantity']);
|
||||
$full = ReceiptWorkflow::milli($source->quantity);
|
||||
if ($quantity < 1 || $before > $full || $quantity > $full - $before) {
|
||||
throw ValidationException::withMessages(['sources' => 'A parcela ultrapassa a quantidade aprovada ainda não emitida.']);
|
||||
}
|
||||
$amounts = PurchaseLineAmounts::portion($source->unit_price_minor, (string) $source->tax_rate, $before, $quantity);
|
||||
$native = PurchaseLineAmounts::portion($source->unit_price_minor, (string) $source->tax_rate, 0, $full);
|
||||
if ($native['subtotal_minor'] !== $source->subtotal_minor || $native['tax_minor'] !== $source->tax_minor || $native['total_minor'] !== $source->total_minor) {
|
||||
throw ValidationException::withMessages(['sources' => 'A base nativa da linha aprovada está inconsistente.']);
|
||||
}
|
||||
$prepared[] = ['quotation_item_id' => $source->id, 'requisition_item_id' => $source->requisition_item_id,
|
||||
'description' => $source->description, 'quantity_milli' => $quantity, 'quantity_offset_milli' => $before,
|
||||
'unit_price_minor' => $source->unit_price_minor, 'tax_rate' => (string) $source->tax_rate, ...$amounts];
|
||||
}
|
||||
usort($prepared, fn ($a, $b) => $a['quotation_item_id'] <=> $b['quotation_item_id']);
|
||||
$result[] = ['requisition_id' => $award->requisition_id, 'award_id' => $award->id, 'quotation_id' => $quote->id,
|
||||
'supplier_id' => $quote->supplier_id, 'currency' => $quote->currency, 'items' => $prepared,
|
||||
'exchange_basis' => $quote->exchange_basis, 'approved_reference' => app(QuotationExchange::class)->amounts($quote),
|
||||
'explicit_reference_allocation_required' => $quote->currency !== 'MZN',
|
||||
'quotation_terms' => $quote->only(['reference', 'valid_until', 'payment_terms', 'delivery_days']),
|
||||
'award_terms' => $award->only(['delivery_date', 'delivery_location', 'justification']),
|
||||
'approval_snapshot' => $award->approval_snapshot,
|
||||
'approval_fingerprint' => $award->comparison_hash];
|
||||
}
|
||||
$subtotal = array_sum(array_map(fn ($source) => array_sum(array_column($source['items'], 'subtotal_minor')), $result));
|
||||
$tax = array_sum(array_map(fn ($source) => array_sum(array_column($source['items'], 'tax_minor')), $result));
|
||||
|
||||
return ['sources' => $result, 'currency' => $compatibility[2], 'subtotal_minor' => $subtotal, 'tax_minor' => $tax,
|
||||
'total_minor' => $subtotal + $tax, 'fingerprint' => hash('sha256', json_encode($result, JSON_THROW_ON_ERROR)),
|
||||
'issued' => false, 'budget_effects' => false];
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Brick\Math\BigDecimal;
|
||||
use Brick\Math\RoundingMode;
|
||||
|
||||
/** Native cumulative price/VAT calculation shared by order preparation and invoice matching. */
|
||||
final class PurchaseLineAmounts
|
||||
{
|
||||
/** @return array{subtotal_minor:int,tax_minor:int,total_minor:int} */
|
||||
public static function portion(int $unitPrice, string $taxRate, int $beforeMilli, int $quantityMilli): array
|
||||
{
|
||||
if ($unitPrice < 0 || $beforeMilli < 0 || $quantityMilli < 1 || $beforeMilli > PHP_INT_MAX - $quantityMilli
|
||||
|| BigDecimal::of($taxRate)->isNegative()) {
|
||||
throw new \InvalidArgumentException('Base cumulativa da linha inválida.');
|
||||
}
|
||||
$subtotal = fn (int $milli) => BigDecimal::of($milli)->multipliedBy($unitPrice)->dividedBy(1000, 0, RoundingMode::HalfUp)->toInt();
|
||||
$tax = fn (int $minor) => BigDecimal::of($minor)->multipliedBy($taxRate)->dividedBy(100, 0, RoundingMode::HalfUp)->toInt();
|
||||
$before = $subtotal($beforeMilli);
|
||||
$after = $subtotal($beforeMilli + $quantityMilli);
|
||||
$net = $after - $before;
|
||||
$vat = $tax($after) - $tax($before);
|
||||
|
||||
return ['subtotal_minor' => $net, 'tax_minor' => $vat, 'total_minor' => $net + $vat];
|
||||
}
|
||||
}
|
||||
@@ -209,6 +209,26 @@ class PurchaseWorkflow
|
||||
});
|
||||
}
|
||||
|
||||
/** Read-only preflight for optional partial-order preparation; no approval or issuance is inferred. */
|
||||
public function approvedSource(User $user, PurchaseAward $award): Quotation
|
||||
{
|
||||
abort_unless(DB::transactionLevel() > 0 && auth()->id() === $user->id, 403);
|
||||
$this->guard->lockCompany($user);
|
||||
$user = app(CurrentActor::class)->lock($user, [PurchasingRole::Procurement]);
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($user), 403);
|
||||
$requisition = Requisition::query()->visibleTo($user)->lockForUpdate()->findOrFail($award->requisition_id);
|
||||
$award = PurchaseAward::query()->where('requisition_id', $requisition->id)->lockForUpdate()->findOrFail($award->id);
|
||||
abort_unless($award->status === 'approved', 409, 'Conclua as aprovações da adjudicação.');
|
||||
$this->assertNoPendingCancellation($award);
|
||||
$quote = $this->currentBasis($user, $award, $requisition);
|
||||
$this->validateFinalApprovals($award, $requisition);
|
||||
if ($award->delivery_date < today()) {
|
||||
throw ValidationException::withMessages(['delivery_date' => 'A data de entrega aprovada já passou.']);
|
||||
}
|
||||
|
||||
return $quote;
|
||||
}
|
||||
|
||||
private function currentBasis(User $user, PurchaseAward $award, Requisition $requisition): Quotation
|
||||
{
|
||||
$rules = $this->rules($requisition);
|
||||
|
||||
@@ -36,11 +36,13 @@ class RequisitionApprovalLevels
|
||||
/** @return array<string,mixed> */
|
||||
public function rules(User $actor): array
|
||||
{
|
||||
return ['enabled' => 'required|boolean', 'levels' => 'present|array|list|max:5', 'levels.*' => 'array:name,profile_ids,scope,min_amount,categories,cost_center_ids',
|
||||
return ['enabled' => 'required|boolean', 'levels' => 'present|array|list|max:5', 'levels.*' => 'array:name,profile_ids,scope,min_amount,categories,procurement_categories,cost_center_ids',
|
||||
'levels.*.name' => 'required|string|max:120', 'levels.*.profile_ids' => 'required|array|list|min:1|max:50',
|
||||
'levels.*.profile_ids.*' => ['required', 'integer', Rule::exists('organization_profiles', 'id')->where('tenant_id', $actor->tenant_id)],
|
||||
'levels.*.scope' => 'required|in:department,company', 'levels.*.min_amount' => ['present', 'nullable', 'string', 'regex:/^\d{1,12}(\.\d{1,2})?$/D'],
|
||||
'levels.*.categories' => 'present|array|list|max:50', 'levels.*.categories.*' => 'required|string|max:100',
|
||||
'levels.*.procurement_categories' => app(RequisitionCategories::class)->available() ? 'nullable|array|list|max:5' : 'prohibited',
|
||||
'levels.*.procurement_categories.*' => ['required', Rule::in(array_keys(RequisitionCategories::LABELS))],
|
||||
'levels.*.cost_center_ids' => 'present|array|list|max:100',
|
||||
'levels.*.cost_center_ids.*' => ['required', 'integer', Rule::exists('cost_centers', 'id')->where('tenant_id', $actor->tenant_id)],
|
||||
'reason' => 'required|string|min:10|max:4000'];
|
||||
@@ -70,6 +72,7 @@ class RequisitionApprovalLevels
|
||||
'quorum' => 'one_eligible', 'levels' => array_map(fn ($level) => ['name' => $level['name'], 'profile_ids' => array_values(array_unique(array_map('intval', $level['profile_ids']))), 'scope' => $level['scope'],
|
||||
'min_minor' => $level['min_amount'] === null ? null : BigDecimal::of($level['min_amount'])->multipliedBy(100)->toInt(),
|
||||
'categories' => array_values(array_unique(array_map(fn ($name) => mb_strtolower(trim($name)), $level['categories']))),
|
||||
'procurement_categories' => array_values(array_unique($level['procurement_categories'] ?? [])),
|
||||
'cost_center_ids' => array_values(array_unique(array_map('intval', $level['cost_center_ids'])))], $data['levels'])];
|
||||
}
|
||||
|
||||
@@ -81,6 +84,7 @@ class RequisitionApprovalLevels
|
||||
'levels.*.profile_ids.required' => 'Escolha pelo menos um perfil elegível por nível.',
|
||||
'levels.*.profile_ids.*.exists' => 'Escolha perfis da empresa.', 'levels.*.cost_center_ids.*.exists' => 'Escolha centros de custo da empresa.',
|
||||
'levels.*.min_amount.regex' => 'Use um valor MZN não negativo com até duas casas decimais.',
|
||||
'levels.*.procurement_categories.prohibited' => 'A classificação RQ-01 ainda não está instalada. Preserve o plano e conclua a instalação antes de usar esta condição.',
|
||||
'reason.required' => 'Indique o motivo da alteração.', 'reason.min' => 'Descreva o motivo com pelo menos dez caracteres.'];
|
||||
}
|
||||
|
||||
@@ -98,14 +102,21 @@ class RequisitionApprovalLevels
|
||||
throw ValidationException::withMessages(['submission' => 'Complete os montantes antes de determinar os níveis de aprovação.']);
|
||||
}
|
||||
$categories = array_map(fn ($name) => mb_strtolower(trim($name)), $request->items->pluck('category')->all());
|
||||
$groups = $request->items->map(fn ($item) => $item->category_context['category'] ?? null)->filter()->all();
|
||||
$selected = [];
|
||||
foreach ($plan['levels'] as $index => $level) {
|
||||
$groupFilter = $level['procurement_categories'] ?? [];
|
||||
abort_if($groupFilter !== [] && ! app(RequisitionCategories::class)->available(), 503,
|
||||
'O plano exige a classificação RQ-01. Reponha a composição compatível antes de submeter; os níveis não serão ignorados.');
|
||||
if ($level['min_minor'] !== null && $amount < $level['min_minor']) {
|
||||
continue;
|
||||
}
|
||||
if ($level['categories'] !== [] && array_intersect($categories, $level['categories']) === []) {
|
||||
continue;
|
||||
}
|
||||
if ($groupFilter !== [] && array_intersect($groups, $groupFilter) === []) {
|
||||
continue;
|
||||
}
|
||||
if ($level['cost_center_ids'] !== [] && ! in_array($request->cost_center_id, $level['cost_center_ids'], true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -26,9 +26,15 @@ class RequisitionBudgetDistributions
|
||||
$isolated = DB::getDriverName() === 'sqlite' ? DB::connection()->getDatabaseName() === ':memory:'
|
||||
: DB::getDriverName() === 'pgsql' && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName());
|
||||
|
||||
if (config('budget-distributions.qa_enabled') !== true || ! app()->environment('testing') || ! $isolated) {
|
||||
$deployment = config('budget-distributions.enabled') === true;
|
||||
$qa = config('budget-distributions.qa_enabled') === true && app()->environment('testing') && $isolated;
|
||||
if (! $deployment && ! $qa) {
|
||||
return false;
|
||||
}
|
||||
if ($deployment) {
|
||||
BudgetDistributionArtifact::verify(config('common-budget.path'),
|
||||
config('budget-distributions.artifact_manifest'), config('budget-distributions.artifact_manifest_sha256'));
|
||||
}
|
||||
foreach (['budget_distributions', 'budget_distribution_events', 'budget_distribution_entries', 'budget_distribution_consumptions'] as $table) {
|
||||
if (! Schema::hasTable($table)) {
|
||||
return false;
|
||||
@@ -36,6 +42,11 @@ class RequisitionBudgetDistributions
|
||||
}
|
||||
$runtime = new \ReflectionClass(BudgetControl::class);
|
||||
|
||||
$runtimeFile = $runtime->getFileName();
|
||||
if ($deployment && (! is_string($runtimeFile) || realpath($runtimeFile) !== realpath(config('common-budget.path').'/src/BudgetControl.php'))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return Schema::hasColumn('requisitions', 'budget_distribution_preparation')
|
||||
&& $runtime->hasMethod('recordDistribution') && $runtime->hasMethod('consumeDistribution') && $runtime->hasMethod('amendDistribution')
|
||||
&& $runtime->hasMethod('checkDistributionConsumption')
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\RequisitionItem;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/** RQ-01 classification, distinct from the original catalogue category and financial purchase type. */
|
||||
final class RequisitionCategories
|
||||
{
|
||||
public const LABELS = [
|
||||
'production_input' => 'Insumos de produção',
|
||||
'spare_part' => 'Peças sobressalentes',
|
||||
'capital_equipment' => 'Maquinaria',
|
||||
'office_equipment' => 'Equipamento de escritório',
|
||||
'other' => 'Outra categoria',
|
||||
];
|
||||
|
||||
public function available(): bool
|
||||
{
|
||||
return Schema::hasColumn('requisition_items', 'category_context');
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $line */
|
||||
public function incomplete(array $line): bool
|
||||
{
|
||||
$category = $line['procurement_category'] ?? null;
|
||||
$type = $line['purchase_type'] ?? null;
|
||||
|
||||
return (empty($category) && trim($line['category_reason'] ?? '') !== '')
|
||||
|| ($category === 'production_input' && empty($line['catalogue_entry_id']))
|
||||
|| ($category === 'spare_part' && ((empty($line['catalogue_entry_id']) && $type !== 'spare_part') || empty($line['spare_part_id']) || empty($line['equipment_id'])))
|
||||
|| ($category === 'capital_equipment' && $type !== 'equipment')
|
||||
|| (($category === 'capital_equipment' || (in_array($category, ['office_equipment', 'other'], true) && empty($line['catalogue_entry_id'])))
|
||||
&& mb_strlen(trim($line['category_reason'] ?? '')) < 10);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $line
|
||||
* @return array<string,mixed>|null
|
||||
*/
|
||||
public function context(array $line, int $index, ?RequisitionItem $previous = null): ?array
|
||||
{
|
||||
if (! array_key_exists('procurement_category', $line) && ! array_key_exists('category_reason', $line) && $previous?->category_context !== null) {
|
||||
$line['procurement_category'] = $previous->category_context['category'];
|
||||
$line['category_reason'] = $previous->category_context['reason'];
|
||||
}
|
||||
$category = $line['procurement_category'] ?? null;
|
||||
$reason = trim($line['category_reason'] ?? '');
|
||||
if (empty($category) && $reason === '') {
|
||||
// Accepted legacy lines remain unclassified, never inferred from their description.
|
||||
return null;
|
||||
}
|
||||
if (! $this->available()) {
|
||||
abort(503, 'A classificação RQ-01 ainda não está instalada.');
|
||||
}
|
||||
$field = 'items.'.$index.'.procurement_category';
|
||||
if (! is_string($category) || ! array_key_exists($category, self::LABELS)) {
|
||||
throw ValidationException::withMessages([$field => 'Seleccione a categoria da necessidade.']);
|
||||
}
|
||||
$type = $line['purchase_type'];
|
||||
if ($category === 'production_input' && (empty($line['catalogue_snapshot']['stock_item_id'])
|
||||
|| empty($line['catalogue_snapshot']['code']) || ! in_array($type, ['consumable', 'other'], true))) {
|
||||
throw ValidationException::withMessages([$field => 'Insumos de produção: seleccione um material de stock no catálogo publicado.']);
|
||||
}
|
||||
if ($category === 'spare_part' && ($type !== 'spare_part' || empty($line['spare_part_id']) || empty($line['equipment_id']))) {
|
||||
throw ValidationException::withMessages([$field => 'Peças sobressalentes: escolha o tipo Peça e a associação ao equipamento.']);
|
||||
}
|
||||
if ($category === 'capital_equipment' && $type !== 'equipment') {
|
||||
throw ValidationException::withMessages([$field => 'Maquinaria: escolha o tipo Equipamento para conservar a validação técnica e o orçamento de investimento.']);
|
||||
}
|
||||
if (($category === 'capital_equipment' || (in_array($category, ['office_equipment', 'other'], true) && empty($line['catalogue_entry_id'])))
|
||||
&& mb_strlen($reason) < 10) {
|
||||
throw ValidationException::withMessages(['items.'.$index.'.category_reason' => $category === 'capital_equipment'
|
||||
? 'Descreva a justificação do investimento com pelo menos 10 caracteres.'
|
||||
: 'Justifique o uso de texto livre, sem artigo do catálogo, com pelo menos 10 caracteres.']);
|
||||
}
|
||||
|
||||
return ['version' => 1, 'category' => $category, 'reason' => $reason === '' ? null : $reason];
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,9 @@ class RequisitionDraftInput
|
||||
'items.*.catalogue_entry_id' => 'nullable|integer|min:1',
|
||||
'items.*.catalogue_version' => 'nullable|required_with:items.*.catalogue_entry_id|integer|min:1',
|
||||
'items.*.source_line_id' => 'nullable|integer|min:1',
|
||||
'items.*.procurement_category' => $this->categoriesAvailable()
|
||||
? ['nullable', Rule::in(array_keys(RequisitionCategories::LABELS))] : ['prohibited'],
|
||||
'items.*.category_reason' => $this->categoriesAvailable() ? 'nullable|string|max:2000' : 'prohibited',
|
||||
'items.*.description' => ['required_without:items.*.catalogue_entry_id', 'string', 'max:255'],
|
||||
'items.*.category' => ['required_without:items.*.catalogue_entry_id', 'string', 'max:100'],
|
||||
'items.*.purchase_type' => ['required_without:items.*.catalogue_entry_id', Rule::in(['consumable', 'service', 'other', 'equipment', 'spare_part'])],
|
||||
@@ -42,6 +45,11 @@ class RequisitionDraftInput
|
||||
];
|
||||
}
|
||||
|
||||
private function categoriesAvailable(): bool
|
||||
{
|
||||
return app(RequisitionCategories::class)->available();
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function rules(User $user): array
|
||||
{
|
||||
@@ -64,7 +72,16 @@ class RequisitionDraftInput
|
||||
/** @param array<string,mixed> $data */
|
||||
public function complete(User $user, array $data): bool
|
||||
{
|
||||
return Validator::make($data, $this->completeRules($user))->passes();
|
||||
if (! Validator::make($data, $this->completeRules($user))->passes() || ! is_array($data['items'] ?? null)) {
|
||||
return false;
|
||||
}
|
||||
foreach ($data['items'] as $line) {
|
||||
if (! is_array($line) || app(RequisitionCategories::class)->incomplete($line)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $data
|
||||
|
||||
@@ -106,7 +106,7 @@ class RequisitionWorkflow
|
||||
/** @var list<array{description: string, category: string, purchase_type: string, quantity: string, unit: string, unit_price: string, tax_rate: string, equipment_id?: int, spare_part_id?: int, production_area?: string, downtime_started_at?: string|null}> $lines */
|
||||
$lines = $data['items'];
|
||||
$oldLines = $existing ? $requisition->items()->get()->keyBy('id')->all() : [];
|
||||
foreach ($lines as $line) {
|
||||
foreach ($lines as $index => $line) {
|
||||
$line = app(RequisitionCatalogue::class)->line($user, $line, $oldLines);
|
||||
app(EquipmentWorkflow::class)->line($line, (int) $user->department_id, $data['priority']);
|
||||
$calculation = InternalRequisitions::line($line['quantity'], $line['unit_price'], $line['tax_rate']);
|
||||
@@ -115,6 +115,7 @@ class RequisitionWorkflow
|
||||
$lineTax = $calculation['tax_minor'];
|
||||
$items[] = [
|
||||
'tenant_id' => $user->tenant_id,
|
||||
...(app(RequisitionCategories::class)->available() ? ['category_context' => app(RequisitionCategories::class)->context($line, $index, $oldLines[$line['source_line_id'] ?? 0] ?? null)] : []),
|
||||
...(! empty($line['catalogue_entry_id']) ? ['catalogue_entry_id' => $line['catalogue_entry_id'], 'catalogue_snapshot' => $line['catalogue_snapshot']] : []),
|
||||
'description' => $line['description'], 'category' => $line['category'],
|
||||
'purchase_type' => $line['purchase_type'], 'quantity' => $line['quantity'], 'unit' => $line['unit'],
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/** Private criteria only. Opening a saved query always invokes the native live search. */
|
||||
final class SavedProcurementSearches
|
||||
{
|
||||
// Technical UI capacity, independent from company approval policies or financial limits.
|
||||
public const MAX_ACTIVE = 50;
|
||||
|
||||
public function available(): bool
|
||||
{
|
||||
return Schema::hasTable('procurement_saved_searches');
|
||||
}
|
||||
|
||||
/** @return array<string,mixed>|null */
|
||||
public function read(User $actor): ?array
|
||||
{
|
||||
if (! $this->available()) {
|
||||
return null;
|
||||
}
|
||||
abort_unless(auth()->id() === $actor->id, 403);
|
||||
$query = DB::table('procurement_saved_searches')->where('tenant_id', $actor->tenant_id)->where('user_id', $actor->id);
|
||||
$fields = ['id', 'name', 'term', 'version'];
|
||||
$project = fn ($row) => ['id' => $row->id, 'name' => $row->name, 'term' => $row->term, 'version' => $row->version,
|
||||
'href' => '/compras/pesquisa?q='.rawurlencode($row->term)];
|
||||
|
||||
return ['max_active' => self::MAX_ACTIVE, 'active' => (clone $query)->whereNull('archived_at')->orderBy('name')->get($fields)->map($project),
|
||||
'archived' => (clone $query)->whereNotNull('archived_at')->latest('archived_at')->paginate(10, $fields, 'archived_page')->withQueryString()->through($project)];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function command(User $actor, string $action, ?int $id, array $input): void
|
||||
{
|
||||
abort_unless($this->available(), 503);
|
||||
DB::transaction(function () use ($actor, $action, $id, $input): void {
|
||||
app(ConflictGuard::class)->lockCompany($actor);
|
||||
$actor = app(CurrentActor::class)->lock($actor);
|
||||
$access = app(OrganizationAccess::class);
|
||||
abort_unless(! $access->maintenanceOnly($actor) && $access->permissions($actor) !== [], 403);
|
||||
abort_unless(in_array($action, ['save', 'archive', 'restore'], true), 422);
|
||||
$data = Validator::make($input, [
|
||||
'version' => $id === null ? 'nullable|integer|min:1' : 'required|integer|min:1',
|
||||
'name' => $action === 'save' ? 'required|string|max:100' : 'prohibited',
|
||||
'term' => $action === 'save' ? 'required|string|min:2|max:100' : 'prohibited',
|
||||
])->validate();
|
||||
$query = DB::table('procurement_saved_searches')->where('tenant_id', $actor->tenant_id)->where('user_id', $actor->id);
|
||||
$record = $id === null ? null : (clone $query)->where('id', $id)->lockForUpdate()->first();
|
||||
abort_if($id !== null && $record === null, 404);
|
||||
abort_if($record !== null && $record->version !== (int) $data['version'], 409, 'A pesquisa mudou. Actualize a página antes de voltar a editar.');
|
||||
$values = [];
|
||||
if ($action === 'save') {
|
||||
$name = trim($data['name']);
|
||||
$term = trim($data['term']);
|
||||
if ($name === '' || mb_strlen($term) < 2) {
|
||||
throw ValidationException::withMessages(['name' => 'Indique um nome e pelo menos dois caracteres de pesquisa.']);
|
||||
}
|
||||
$values = ['name' => $name, 'term' => $term];
|
||||
} else {
|
||||
abort_unless($record !== null, 404);
|
||||
abort_if(($action === 'archive') === ($record->archived_at !== null), 409);
|
||||
}
|
||||
$active = $action !== 'archive';
|
||||
$nameKey = $active ? hash('sha256', mb_strtolower($values['name'] ?? $record->name)) : null;
|
||||
if ($active) {
|
||||
$duplicate = (clone $query)->where('active_name_key', $nameKey)->when($id !== null, fn ($q) => $q->where('id', '!=', $id))->first();
|
||||
if ($duplicate !== null) {
|
||||
if ($id === null && $duplicate->term === $values['term']) {
|
||||
return; // A repeated create has one private preference, never duplicate results.
|
||||
}
|
||||
throw ValidationException::withMessages(['name' => 'Já existe uma pesquisa activa com este nome. Escolha outro nome.']);
|
||||
}
|
||||
if (($record === null || $record->archived_at !== null) && (clone $query)->whereNull('archived_at')->count() >= self::MAX_ACTIVE) {
|
||||
throw ValidationException::withMessages(['name' => 'Pode manter até '.self::MAX_ACTIVE.' pesquisas activas. Arquive uma antes de acrescentar outra.']);
|
||||
}
|
||||
}
|
||||
$values += ['active_name_key' => $nameKey, 'archived_at' => $active ? null : now(), 'updated_at' => now()];
|
||||
if ($record === null) {
|
||||
$query->insert([...$values, 'tenant_id' => $actor->tenant_id, 'user_id' => $actor->id, 'version' => 1, 'created_at' => now()]);
|
||||
} else {
|
||||
$query->where('id', $id)->update([...$values, 'version' => $record->version + 1]);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,9 @@
|
||||
<?php
|
||||
|
||||
return ['qa_enabled' => env('SGC_BUDGET_DISTRIBUTIONS_QA_ENABLED', false)];
|
||||
return [
|
||||
// Deployment capability; preparing a release never enables it.
|
||||
'enabled' => env('SGC_BUDGET_DISTRIBUTIONS_ENABLED', false),
|
||||
'qa_enabled' => env('SGC_BUDGET_DISTRIBUTIONS_QA_ENABLED', false),
|
||||
'artifact_manifest' => env('SGC_BUDGET_DISTRIBUTIONS_MANIFEST'),
|
||||
'artifact_manifest_sha256' => env('SGC_BUDGET_DISTRIBUTIONS_MANIFEST_SHA256'),
|
||||
];
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
// No operational activation path is included in this authorization.
|
||||
'qa_enabled' => false,
|
||||
];
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
use App\Services\BudgetDistributionSchema;
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
// Deliberately outside automatic migrations. Only the reviewed installer supplies this scope.
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
$db = DB::connection();
|
||||
$scope = config('budget-distributions.schema_installation');
|
||||
if (! app()->runningInConsole() || ! app()->environment(['local', 'testing', 'payable-testing'])
|
||||
|| $db->getDriverName() !== 'pgsql' || $db->getConfig('host') !== '127.0.0.1'
|
||||
|| ! is_array($scope) || ($scope['database'] ?? null) !== $db->getDatabaseName()
|
||||
|| ($scope['username'] ?? null) !== $db->getConfig('username')
|
||||
|| ! preg_match('/^compras_(receipts_test|distribution_restore)_[a-f0-9]{12}$/D', $db->getDatabaseName())) {
|
||||
throw new LogicException('Distribution pilot schema requires the exact authorised installer scope.');
|
||||
}
|
||||
$identity = $db->selectOne('select current_database() as db, current_user as role');
|
||||
if ($identity === null || $identity->db !== $scope['database'] || $identity->role !== $scope['username']) {
|
||||
throw new LogicException('Distribution pilot schema identity mismatch.');
|
||||
}
|
||||
BudgetDistributionSchema::install();
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
throw new LogicException('Preserve distribution history; use reviewed recovery or a compatible forward correction.');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,18 @@
|
||||
<?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::table('requisition_items', fn (Blueprint $table) => $table->json('category_context')->nullable());
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
throw new LogicException('Preserve recorded category context; use reviewed recovery instead of deleting history.');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,30 @@
|
||||
<?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('procurement_saved_searches', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('tenant_id')->constrained()->restrictOnDelete();
|
||||
$table->foreignId('user_id')->constrained()->restrictOnDelete();
|
||||
$table->string('name', 100);
|
||||
$table->string('term', 100);
|
||||
$table->string('active_name_key', 64)->nullable();
|
||||
$table->unsignedInteger('version')->default(1);
|
||||
$table->timestamp('archived_at')->nullable();
|
||||
$table->timestamps();
|
||||
$table->unique(['tenant_id', 'user_id', 'active_name_key'], 'saved_search_active_name_unique');
|
||||
$table->index(['tenant_id', 'user_id', 'archived_at'], 'saved_search_owner_index');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
throw new LogicException('Preserve saved search criteria; no automatic history deletion.');
|
||||
}
|
||||
};
|
||||
@@ -1,7 +1,7 @@
|
||||
<?php
|
||||
|
||||
use App\Services\BudgetDistributionSchema;
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
// Explicit QA path: not discovered by the normal application migration directory.
|
||||
@@ -16,66 +16,7 @@ return new class extends Migration
|
||||
throw new LogicException('Distribution schema requires the guarded disposable QA database.');
|
||||
}
|
||||
|
||||
$db->transaction(function () use ($db): void {
|
||||
$schema = $db->getSchemaBuilder();
|
||||
$schema->table('requisitions', fn (Blueprint $table) => $table->json('budget_distribution_preparation')->nullable());
|
||||
$schema->create('budget_distributions', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('tenant_id')->constrained()->restrictOnDelete();
|
||||
$table->foreignId('requisition_id')->unique()->constrained()->restrictOnDelete();
|
||||
$table->string('phase');
|
||||
$table->json('snapshot');
|
||||
$table->foreignId('created_by')->constrained('users')->restrictOnDelete();
|
||||
$table->timestamps();
|
||||
});
|
||||
$schema->create('budget_distribution_events', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('tenant_id')->constrained()->restrictOnDelete();
|
||||
$table->foreignId('distribution_id')->constrained('budget_distributions')->restrictOnDelete();
|
||||
$table->string('kind', 50);
|
||||
$table->uuid('operation_key');
|
||||
$table->string('payload_hash', 64);
|
||||
$table->json('result');
|
||||
$table->json('snapshot');
|
||||
$table->foreignId('created_by')->constrained('users')->restrictOnDelete();
|
||||
$table->timestamp('created_at');
|
||||
$table->unique(['tenant_id', 'operation_key']);
|
||||
$table->unique(['distribution_id', 'kind']);
|
||||
});
|
||||
$schema->create('budget_distribution_entries', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('tenant_id')->constrained()->restrictOnDelete();
|
||||
$table->foreignId('distribution_id')->constrained('budget_distributions')->restrictOnDelete();
|
||||
$table->string('allocation_key', 120);
|
||||
$table->foreignId('budget_id')->constrained('budgets')->restrictOnDelete();
|
||||
$table->string('kind', 50);
|
||||
$table->bigInteger('reserved_minor');
|
||||
$table->bigInteger('committed_minor');
|
||||
$table->foreignId('created_by')->constrained('users')->restrictOnDelete();
|
||||
$table->timestamp('created_at');
|
||||
$table->unique(['distribution_id', 'allocation_key', 'kind']);
|
||||
});
|
||||
$schema->create('budget_distribution_consumptions', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('tenant_id')->constrained()->restrictOnDelete();
|
||||
$table->foreignId('distribution_id')->constrained('budget_distributions')->restrictOnDelete();
|
||||
$table->string('allocation_key', 120);
|
||||
$table->foreignId('budget_id')->constrained('budgets')->restrictOnDelete();
|
||||
$table->foreignId('invoice_id')->constrained('invoices')->restrictOnDelete();
|
||||
$table->bigInteger('amount_minor');
|
||||
$table->bigInteger('subtotal_minor');
|
||||
$table->bigInteger('total_minor');
|
||||
$table->foreignId('created_by')->constrained('users')->restrictOnDelete();
|
||||
$table->timestamp('created_at');
|
||||
$table->unique(['invoice_id', 'allocation_key']);
|
||||
});
|
||||
if ($db->getDriverName() === 'pgsql') {
|
||||
$db->unprepared("CREATE OR REPLACE FUNCTION sgc_distribution_history_guard() RETURNS trigger LANGUAGE plpgsql AS 'BEGIN RAISE EXCEPTION ''Distribution history is append only''; END'");
|
||||
foreach (['budget_distribution_events', 'budget_distribution_entries', 'budget_distribution_consumptions'] as $table) {
|
||||
$db->statement('CREATE TRIGGER distribution_history_guard BEFORE UPDATE OR DELETE ON '.$table.' FOR EACH ROW EXECUTE FUNCTION sgc_distribution_history_guard()');
|
||||
}
|
||||
}
|
||||
});
|
||||
BudgetDistributionSchema::install();
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
// Optional contract structure. Deliberately outside normal and deployment migrations.
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
$db = DB::connection();
|
||||
$isolated = ($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|
||||
|| ($db->getDriverName() === 'pgsql' && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName()));
|
||||
if (! app()->environment('testing') || ! $isolated) {
|
||||
throw new LogicException('Order parts require the guarded disposable QA database.');
|
||||
}
|
||||
$schema = $db->getSchemaBuilder();
|
||||
$tables = ['budget_order_commands', 'budget_order_bindings', 'budget_order_allocations', 'budget_order_consumptions'];
|
||||
$found = count(array_filter($tables, fn ($table) => $schema->hasTable($table)));
|
||||
if ($found !== 0) {
|
||||
throw new LogicException('Order-parts schema must be installed once into an empty isolated composition.');
|
||||
}
|
||||
if (! $schema->hasTable('budget_distribution_entries')) {
|
||||
throw new LogicException('Install the explicit V1 distribution schema first.');
|
||||
}
|
||||
$db->transaction(function () use ($schema, $db, $tables): void {
|
||||
$schema->create('budget_order_commands', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->foreignId('tenant_id')->constrained()->restrictOnDelete();
|
||||
$table->string('kind', 20);
|
||||
$table->string('document_key', 60);
|
||||
$table->uuid('operation_key');
|
||||
$table->string('payload_hash', 64);
|
||||
$table->json('result');
|
||||
$table->json('snapshot');
|
||||
$table->foreignId('created_by')->constrained('users')->restrictOnDelete();
|
||||
$table->timestamp('created_at');
|
||||
$table->unique(['tenant_id', 'operation_key']);
|
||||
$table->unique(['tenant_id', 'kind', 'document_key']);
|
||||
});
|
||||
$schema->create('budget_order_bindings', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->foreignId('tenant_id')->constrained()->restrictOnDelete();
|
||||
$table->foreignId('command_id')->constrained('budget_order_commands')->restrictOnDelete();
|
||||
$table->foreignId('distribution_id')->constrained('budget_distributions')->restrictOnDelete();
|
||||
$table->unsignedInteger('source_version');
|
||||
$table->unique(['distribution_id', 'source_version']);
|
||||
$table->unique(['command_id', 'distribution_id']);
|
||||
});
|
||||
foreach (['budget_order_allocations', 'budget_order_consumptions'] as $name) {
|
||||
$schema->create($name, function (Blueprint $table) use ($name): void {
|
||||
$table->id();
|
||||
$table->foreignId('tenant_id')->constrained()->restrictOnDelete();
|
||||
$table->foreignId('command_id')->constrained('budget_order_commands')->restrictOnDelete();
|
||||
$table->foreignId('distribution_id')->constrained('budget_distributions')->restrictOnDelete();
|
||||
$table->uuid('order_key');
|
||||
$table->string('allocation_key', 120);
|
||||
$table->foreignId('budget_id')->constrained('budgets')->restrictOnDelete();
|
||||
$table->bigInteger('subtotal_minor');
|
||||
$table->bigInteger('total_minor');
|
||||
$table->bigInteger('amount_minor');
|
||||
if ($name === 'budget_order_consumptions') {
|
||||
$table->foreignId('invoice_id')->constrained()->restrictOnDelete();
|
||||
} else {
|
||||
$table->string('kind', 20);
|
||||
}
|
||||
$table->unique(['command_id', 'distribution_id', 'order_key', 'allocation_key'], $name === 'budget_order_allocations' ? 'order_allocation_binding' : 'order_consumption_binding');
|
||||
});
|
||||
}
|
||||
if ($db->getDriverName() === 'pgsql') {
|
||||
// Existing function always raises; no mutation or deletion of accepted history.
|
||||
foreach ($tables as $table) {
|
||||
$db->statement('CREATE TRIGGER distribution_history_guard BEFORE UPDATE OR DELETE ON '.$table.' FOR EACH ROW EXECUTE FUNCTION sgc_distribution_history_guard()');
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
throw new LogicException('Use a verified pre-extension backup; order-part history is not deleted by downgrade.');
|
||||
}
|
||||
};
|
||||
+35
-1
@@ -1,12 +1,46 @@
|
||||
# Desenvolvimento do SGC
|
||||
|
||||
## Importação directa na especificação actualizada - 22/11/2026
|
||||
|
||||
O proprietário forneceu uma nova versão de `A requisção de insumos de produção.docx`: SHA256 `9646630ac9b7e08cf84f3e93efc6cf1a90657cdc3e59d680621b74238d3a7408`, 567 parágrafos, sem documentos incorporados. A leitura partilhada preservou o original aberto. O exemplar anterior e a sua autorização mantêm-se como histórico; a secção 10 acrescenta requisitos de importação, além dos controlos de conflito da secção 9.
|
||||
|
||||
Já existe preparação logística por ordem, países, regime, Incoterm opcional e marcos trânsito/chegada/retenção/libertação; a chegada não permite stock utilizável. Isto não demonstra a cobertura integral de código pautal por artigo, custo de aterragem/orçamento, despachante/transitário, documentos tipificados/JUE, obrigações documentais bancárias, regras legais versionadas e alertas. Reconciliação detalhada em `proofs/rq01-import-reconciliation.json`. O resumo legislativo do Word é especificação fornecida; não activa taxas, isenções, pagamentos ou submissões externas. Prazos empresariais e destinatários não são inventados. A preservação integral sem eliminação automática continua válida.
|
||||
|
||||
## Ordens parciais e origens múltiplas - QA autorizada em curso
|
||||
|
||||
Autorização específica registada em `proofs/rq01-multi-order-contract-authorization.json`, vinculada ao SHA da proposta; não voltar a pedir esta decisão. Contrato opcional, adopção explícita de reservas antigas sem ordem, compromisso parcial, consumo de uma factura entre origens e cancelamento sem repor capacidade implementados na fonte comum. Preparação reutiliza as aprovações e controlos nativos, conserva termos/câmbio por origem e não emite documentos. Cálculo cumulativo partilhado com a conferência nativa preserva quantidades fraccionadas e IVA.
|
||||
|
||||
SQLite: 48 aprovados/1 caso exclusivo PG; PostgreSQL: 49/312, com base removida. Concorrência real demonstrou uma gravação/auditoria e conflitos 409; runtime V1 recusou saldo com efeitos novos (503). Backup/restauro QA preservou 115 tabelas anteriores, histórico e repetição sem novo efeito. PHPStan zero erros, sintaxe e formatação aprovadas. Prova `proofs/rq01-multi-order-qa.json`.
|
||||
|
||||
Ainda faltam emissão documental nativa, visibilidade integral entre origens, recepção/factura/obrigação integradas, reafectação explícita por Finanças neste contrato, percurso multimoeda completo e revisão dos formulários/móvel/impressão. Trabalho QA já autorizado; isto não é um bloqueio por falta de autorização geral. Piloto, pacote V1 instalado, dados reais e SGF operacional preservados, sem nova activação.
|
||||
|
||||
## Pesquisa guardada e aprovação por grupo em QA - 22/11/2026
|
||||
|
||||
Pesquisas guardadas privadas por empresa/utilizador: criar, editar, arquivar, restaurar e reabrir a consulta com permissões actuais, sem guardar resultados. SQLite e PostgreSQL: 14 testes/354 verificações em cada; percurso nativo Edge 390/1000px concluído em dados sintéticos. Critérios opcionais de aprovação pelos grupos RQ-01 também verificados: 21 testes/173 verificações em cada motor, 13 testes de interface, tipos e análise estática aprovados. Critérios combinam-se com valor/categoria original/centro e conservam o encaminhamento congelado; schema ausente bloqueia sem ignorar níveis. A apresentação dos novos controlos administrativos ainda requer revisão visual.
|
||||
|
||||
Provas: `proofs/saved-procurement-searches.json` e `proofs/rq01-categories.json`. Estas duas migrações e as novas interfaces continuam apenas em QA, sem instalação no piloto. Distribuições V1 já instaladas permanecem preservadas. Pesquisa transversal integral, análises restantes, divisão/consolidação de ordens, ligação a projectos/imobilizado, escalamento/expiração, revisão transversal e aceitação empresarial não estão declarados concluídos.
|
||||
|
||||
## Categorias RQ-01 em QA - 22/11/2026
|
||||
|
||||
Classificação RQ-01 desenvolvida e verificada em QA: quatro grupos explícitos, motivo de investimento/texto livre, ligação aos controlos nativos de catálogo, peça/equipamento e maquinaria; preparação incompleta não submete nem reserva. Categoria original e tipos financeiros preservados, sem classificar históricos por inferência. Revisão Edge390/1000px confirmou ajuda e gravação nativa do motivo, com versão/auditoria e valores conservados. QA removida; piloto conserva a candidata de distribuições já autorizada, sem a nova migração000005 ou assets de categorias. SQLite53aprovados/1exclusão/494verificações, PostgreSQL54/496,11frontend, tipos/PHPStan/lint/build aprovados. Prova `proofs/rq01-categories.json`. Condições de aprovação específicas dos novos grupos e restantes requisitos continuam abertos; não declarar a RQ-01 integral concluída.
|
||||
|
||||
|
||||
## Distribuições instaladas no piloto - 22/11/2026
|
||||
|
||||
Instalação específica autorizada pelo proprietário («autorizo») e aplicada apenas no piloto8005. Nova salvaguarda/restauro sob a mesma identidade:115tabelas conferidas,114tabelas anteriores de negócio e chaves estrangeiras preservadas; quatro tabelas opcionais vazias e preparaçãoJSON inicialmenteNULL. Candidata de manifesto `1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e` e artefacto independente disponibilizados. Somente quatro configurações previstas alteradas,18ficheiros fixados intactos e oito verificaçõesHTTP aprovadas, sem operações de negócio ou alterações de permissões/SGF. A requisição sintética existente está aprovada e a edição foi correctamente recusada; não alterar o estado para facilitar testes.
|
||||
|
||||
Provas: `proofs/rq01-distribution-pilot-authorization.json`, `proofs/rq01-distribution-pilot-installation.json` e `proofs/rq01-distribution-pilot-http.json`. Não repetir autorização, migração ou instalação deste recorte. As referências seguintes ao piloto antigo e à instalação pendente são históricas. A instalação não equivale à aceitação empresarial integral; categorias/regras condicionais e restantes lacunas da matriz continuam abertas.
|
||||
|
||||
|
||||
## RQ-01: estado consolidado de QA - 22/11/2026
|
||||
|
||||
RQ-01: distribuições por linha/centro, adjudicação, compromisso, factura parcial e reafectação explícita por Finanças implementados e verificados em QA isolado. PostgreSQL:77/355 no grupo núcleo/orçamento/facturas e6/131 na adjudicação dirigida; concorrência real e restauro pré/pós aprovados. Artefacto privado independente:17/147; compatibilidade com runtime anterior:41/134. Resultados sobrepostos não devem ser somados. Tipos, análise estática e sintaxe PHP8.4 aprovados. Prova: `proofs/rq01-distribution-qa.json`.
|
||||
|
||||
Revisão nativa Edge concluída para os novos formulários: preparação móvel/desktop, erro recuperável, gravação exacta, selecção de proposta antes das parcelas, reafectação única versionada e regresso à factura conservando a quantidade parcial. Dados exclusivamente sintéticos; não houve factura/adjudicação visual adicional. Servidor/base/configuração QA descartáveis encerrados/removidos. Prova: `proofs/rq01-distribution-visual.json`.
|
||||
|
||||
Candidata privada: manifesto `1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e`; artefacto comum privado em `proofs/rq01-distribution-artifact.json`. Piloto conserva manifesto `c0beadc1302b0e211eaeb18603a4cf7dab863b9e81f5771ddba8bec92bc4568c` e pacote fixado. A extensão continua limitada a QA: a guarda actual recusa ambiente operacional. Falta preparar a disponibilização operacional concreta e obter a sua autorização específica; não confundir com instalação/activação concluída. Restantes requisitos e aceitação empresarial continuam abertos. As referências anteriores contraditórias são históricas; não repetir autorizações ou provas aceites.
|
||||
Candidata privada: manifesto `1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e`; artefacto comum privado em `proofs/rq01-distribution-artifact.json`. Piloto conserva manifesto `c0beadc1302b0e211eaeb18603a4cf7dab863b9e81f5771ddba8bec92bc4568c` e pacote fixado. A utilização continua limitada a QA. A disponibilização operacional está preparada, desligada por defeito e vinculada ao manifesto do artefacto independente; a instalação/activação ainda exige autorização específica. Restantes requisitos e aceitação empresarial continuam abertos. As referências anteriores contraditórias são históricas; não repetir autorizações ou provas aceites.
|
||||
|
||||
Preparação operacional: verificação prévia dos sete ficheiros antes de carregar PHP (8 testes/20 verificações), composição independente18/152 e PostgreSQL24/180. Ensaio sobre cópia do piloto:115tabelas conferidas,114tabelas anteriores de negócio e chaves estrangeiras preservadas, novos campos/tabelas vazios e cópia removida. Sem alteração do piloto. Proposta `proofs/rq01-distribution-pilot-proposal.json`; salvaguarda/restauro em `proofs/rq01-distribution-pilot-preparation.json`. Instalador recusa falta de autorização exacta ou instalação já registada; confirmação HTTP preparada mas ainda não executada. Os restantes cinco grupos de conclusão do produto conservam as suas pendências.
|
||||
|
||||
## 22/11/2026 — posições nativas, CSV e restauro de preparação
|
||||
|
||||
|
||||
@@ -1,18 +1,52 @@
|
||||
# Matriz reconciliada do SGC — 03/11/2026
|
||||
|
||||
## Importação directa na especificação actualizada - 22/11/2026
|
||||
|
||||
O proprietário forneceu uma nova versão de `A requisção de insumos de produção.docx`: SHA256 `9646630ac9b7e08cf84f3e93efc6cf1a90657cdc3e59d680621b74238d3a7408`, 567 parágrafos, sem documentos incorporados. A leitura partilhada preservou o original aberto. O exemplar anterior e a sua autorização mantêm-se como histórico; a secção 10 acrescenta requisitos de importação, além dos controlos de conflito da secção 9.
|
||||
|
||||
Já existe preparação logística por ordem, países, regime, Incoterm opcional e marcos trânsito/chegada/retenção/libertação; a chegada não permite stock utilizável. Isto não demonstra a cobertura integral de código pautal por artigo, custo de aterragem/orçamento, despachante/transitário, documentos tipificados/JUE, obrigações documentais bancárias, regras legais versionadas e alertas. Reconciliação detalhada em `proofs/rq01-import-reconciliation.json`. O resumo legislativo do Word é especificação fornecida; não activa taxas, isenções, pagamentos ou submissões externas. Prazos empresariais e destinatários não são inventados. A preservação integral sem eliminação automática continua válida.
|
||||
|
||||
## Ordens parciais e origens múltiplas - QA autorizada em curso
|
||||
|
||||
Autorização específica registada em `proofs/rq01-multi-order-contract-authorization.json`, vinculada ao SHA da proposta; não voltar a pedir esta decisão. Contrato opcional, adopção explícita de reservas antigas sem ordem, compromisso parcial, consumo de uma factura entre origens e cancelamento sem repor capacidade implementados na fonte comum. Preparação reutiliza as aprovações e controlos nativos, conserva termos/câmbio por origem e não emite documentos. Cálculo cumulativo partilhado com a conferência nativa preserva quantidades fraccionadas e IVA.
|
||||
|
||||
SQLite: 48 aprovados/1 caso exclusivo PG; PostgreSQL: 49/312, com base removida. Concorrência real demonstrou uma gravação/auditoria e conflitos 409; runtime V1 recusou saldo com efeitos novos (503). Backup/restauro QA preservou 115 tabelas anteriores, histórico e repetição sem novo efeito. PHPStan zero erros, sintaxe e formatação aprovadas. Prova `proofs/rq01-multi-order-qa.json`.
|
||||
|
||||
Ainda faltam emissão documental nativa, visibilidade integral entre origens, recepção/factura/obrigação integradas, reafectação explícita por Finanças neste contrato, percurso multimoeda completo e revisão dos formulários/móvel/impressão. Trabalho QA já autorizado; isto não é um bloqueio por falta de autorização geral. Piloto, pacote V1 instalado, dados reais e SGF operacional preservados, sem nova activação.
|
||||
|
||||
## Pesquisa guardada e aprovação por grupo em QA - 22/11/2026
|
||||
|
||||
Pesquisas guardadas privadas por empresa/utilizador: criar, editar, arquivar, restaurar e reabrir a consulta com permissões actuais, sem guardar resultados. SQLite e PostgreSQL: 14 testes/354 verificações em cada; percurso nativo Edge 390/1000px concluído em dados sintéticos. Critérios opcionais de aprovação pelos grupos RQ-01 também verificados: 21 testes/173 verificações em cada motor, 13 testes de interface, tipos e análise estática aprovados. Critérios combinam-se com valor/categoria original/centro e conservam o encaminhamento congelado; schema ausente bloqueia sem ignorar níveis. A apresentação dos novos controlos administrativos ainda requer revisão visual.
|
||||
|
||||
Provas: `proofs/saved-procurement-searches.json` e `proofs/rq01-categories.json`. Estas duas migrações e as novas interfaces continuam apenas em QA, sem instalação no piloto. Distribuições V1 já instaladas permanecem preservadas. Pesquisa transversal integral, análises restantes, divisão/consolidação de ordens, ligação a projectos/imobilizado, escalamento/expiração, revisão transversal e aceitação empresarial não estão declarados concluídos.
|
||||
|
||||
## Categorias RQ-01 em QA - 22/11/2026
|
||||
|
||||
Classificação RQ-01 desenvolvida e verificada em QA: quatro grupos explícitos, motivo de investimento/texto livre, ligação aos controlos nativos de catálogo, peça/equipamento e maquinaria; preparação incompleta não submete nem reserva. Categoria original e tipos financeiros preservados, sem classificar históricos por inferência. Revisão Edge390/1000px confirmou ajuda e gravação nativa do motivo, com versão/auditoria e valores conservados. QA removida; piloto conserva a candidata de distribuições já autorizada, sem a nova migração000005 ou assets de categorias. SQLite53aprovados/1exclusão/494verificações, PostgreSQL54/496,11frontend, tipos/PHPStan/lint/build aprovados. Prova `proofs/rq01-categories.json`. Condições de aprovação específicas dos novos grupos e restantes requisitos continuam abertos; não declarar a RQ-01 integral concluída.
|
||||
|
||||
|
||||
## Distribuições instaladas no piloto - 22/11/2026
|
||||
|
||||
Instalação específica autorizada pelo proprietário («autorizo») e aplicada apenas no piloto8005. Nova salvaguarda/restauro sob a mesma identidade:115tabelas conferidas,114tabelas anteriores de negócio e chaves estrangeiras preservadas; quatro tabelas opcionais vazias e preparaçãoJSON inicialmenteNULL. Candidata de manifesto `1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e` e artefacto independente disponibilizados. Somente quatro configurações previstas alteradas,18ficheiros fixados intactos e oito verificaçõesHTTP aprovadas, sem operações de negócio ou alterações de permissões/SGF. A requisição sintética existente está aprovada e a edição foi correctamente recusada; não alterar o estado para facilitar testes.
|
||||
|
||||
Provas: `proofs/rq01-distribution-pilot-authorization.json`, `proofs/rq01-distribution-pilot-installation.json` e `proofs/rq01-distribution-pilot-http.json`. Não repetir autorização, migração ou instalação deste recorte. As referências seguintes ao piloto antigo e à instalação pendente são históricas. A instalação não equivale à aceitação empresarial integral; categorias/regras condicionais e restantes lacunas da matriz continuam abertas.
|
||||
|
||||
|
||||
## RQ-01: estado consolidado de QA - 22/11/2026
|
||||
|
||||
RQ-01: distribuições por linha/centro, adjudicação, compromisso, factura parcial e reafectação explícita por Finanças implementados e verificados em QA isolado. PostgreSQL:77/355 no grupo núcleo/orçamento/facturas e6/131 na adjudicação dirigida; concorrência real e restauro pré/pós aprovados. Artefacto privado independente:17/147; compatibilidade com runtime anterior:41/134. Resultados sobrepostos não devem ser somados. Tipos, análise estática e sintaxe PHP8.4 aprovados. Prova: `proofs/rq01-distribution-qa.json`.
|
||||
|
||||
Revisão nativa Edge concluída para os novos formulários: preparação móvel/desktop, erro recuperável, gravação exacta, selecção de proposta antes das parcelas, reafectação única versionada e regresso à factura conservando a quantidade parcial. Dados exclusivamente sintéticos; não houve factura/adjudicação visual adicional. Servidor/base/configuração QA descartáveis encerrados/removidos. Prova: `proofs/rq01-distribution-visual.json`.
|
||||
|
||||
Candidata privada: manifesto `1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e`; artefacto comum privado em `proofs/rq01-distribution-artifact.json`. Piloto conserva manifesto `c0beadc1302b0e211eaeb18603a4cf7dab863b9e81f5771ddba8bec92bc4568c` e pacote fixado. A extensão continua limitada a QA: a guarda actual recusa ambiente operacional. Falta preparar a disponibilização operacional concreta e obter a sua autorização específica; não confundir com instalação/activação concluída. Restantes requisitos e aceitação empresarial continuam abertos. As referências anteriores contraditórias são históricas; não repetir autorizações ou provas aceites.
|
||||
Candidata privada: manifesto `1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e`; artefacto comum privado em `proofs/rq01-distribution-artifact.json`. Piloto conserva manifesto `c0beadc1302b0e211eaeb18603a4cf7dab863b9e81f5771ddba8bec92bc4568c` e pacote fixado. A utilização continua limitada a QA. A disponibilização operacional está preparada, desligada por defeito e vinculada ao manifesto do artefacto independente; a instalação/activação ainda exige autorização específica. Restantes requisitos e aceitação empresarial continuam abertos. As referências anteriores contraditórias são históricas; não repetir autorizações ou provas aceites.
|
||||
|
||||
Preparação operacional: verificação prévia dos sete ficheiros antes de carregar PHP (8 testes/20 verificações), composição independente18/152 e PostgreSQL24/180. Ensaio sobre cópia do piloto:115tabelas conferidas,114tabelas anteriores de negócio e chaves estrangeiras preservadas, novos campos/tabelas vazios e cópia removida. Sem alteração do piloto. Proposta `proofs/rq01-distribution-pilot-proposal.json`; salvaguarda/restauro em `proofs/rq01-distribution-pilot-preparation.json`. Instalador recusa falta de autorização exacta ou instalação já registada; confirmação HTTP preparada mas ainda não executada. Os restantes cinco grupos de conclusão do produto conservam as suas pendências.
|
||||
|
||||
### Análises e formulários — continuação de 22/11/2026
|
||||
|
||||
`payable-insights.json`: posição actual das obrigações integrada no relatório e CSV próprio, com fonte financeira nativa única, filtros do pedido, cobertura determinada/por reconhecer/divergente e soma exacta por moeda. Só competências/grants financeiros existentes. Quatro casos finaisSQLite/58 e PostgreSQL/58,137frontend e seisHTTP; tentativa alargada180s não aprovada, delta isolado passou. O indicador de despesa por período não foi inventado; restante análise tem requisitos próprios. `requisition-history.json`: restauro real de preparação observado noEdge sem gravar, isolamento de empresa/actor/pedido/versão e histórico cifrado. Aviso indevido do formulário limpo identificado e corrigido com regressão; confirmação visual final em curso.
|
||||
|
||||
Distribuições por linha continuam dependentes da extensão concreta de contrato comum apresentada em `rq01-distribution-contract-proposal.json`, autorização solicitada para desenvolvimento/QA. O contrato instalado e a fonte coincidem e só aceitam um centro por origem; não há fundamento para criar efeitos paralelos no adaptador. A análise da dependência não implementa nem encerra este requisito.
|
||||
Distribuições por linha/centro e reafectação explícita já estão implementadas e verificadas no recorte autorizado de QA. O pacote fixado permanece antigo; a fonte canónica evoluiu com autorização. Não confundir essa diferença de composição com funcionalidade desaparecida. A preparação operacional é agora uma frente distinta, sem activar a candidata por inferência.
|
||||
|
||||
### Disponibilidade operacional autorizada — 22/11/2026
|
||||
|
||||
@@ -31,17 +65,18 @@ Fonte: `A requisção de insumos de produção.docx`, secções 1–9; exemplar/
|
||||
| Elemento RQ-01 | Estado reconciliado / continuidade |
|
||||
| --- | --- |
|
||||
| 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 | Stock/catálogo e tipos técnicos existentes; classificação transversal das quatro categorias e regras condicionais ainda por completar. |
|
||||
| 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. |
|
||||
| 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 | Centro de custo do pedido existe; distribuições por linha, ordem/projecto/imobilizado e contas precisam de integração pelos mecanismos comuns aprovados. Não criar segundo motor contabilístico. |
|
||||
| Aprovação por valor/categoria/centro, até oito níveis | Implementado e testado em QA isolado: controlos base preservados mais até cinco níveis condicionais por perfis, máximo oito, um elegível por nível. Versão e encaminhamento congelados por processo, sem concessões automáticas; concorrência, revogação, âmbito e auditoria verificados. Prova `configured-requisition-levels.json`. Instalação/configuração operacional, apresentação visual e aceitação pendentes. |
|
||||
| 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. Ligação a ordem/projecto/imobilizado e contas conserva requisitos próprios ainda por concluir. |
|
||||
| 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. |
|
||||
| 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 existentes; fluxo acelerado, limites e dispensas exigem os parâmetros da empresa ainda ausentes. Não dispensar cotações ou orçamento automaticamente. |
|
||||
| Maquinaria | Validação técnica e Finanças existentes; direcção, orçamento de capital e rastreio até imobilizado requerem completar o percurso, sem duplicar os motores SGF. |
|
||||
| Lembretes, escalamento e expiração | Tarefas/avisos existentes não demonstram escalamento hierárquico ou expiração configurável. Prazos concretos ainda não fornecidos. |
|
||||
| Divisão/consolidação e conversão | Ligações requisição → ordem → recepção/factura existentes; divisão/consolidação entre origens ainda não declarada implementada. Preservar identidade/linha/versão de cada origem. |
|
||||
| Divisão/consolidação e conversão | Contrato opcional e preparação nativa verificados em QA; ver `rq01-multi-order-qa.json`. Emissão documental, visibilidade entre origens e percurso completo de recepção/factura ainda em desenvolvimento autorizado. V1 instalado preservado. |
|
||||
| Importação directa | Especificação actualizada, secções 9–10.8, reconciliada em `rq01-import-reconciliation.json`: logística existente; classificação, custo de aterragem, documentos/JUE, intervenientes, regras legais e alertas adicionais ainda por concluir. |
|
||||
|
||||
Primeiro incremento validado: SQLite 50/713 e PostgreSQL 50/713, base removida, 14 frontend dirigidos, tipos/PHPStan/check/build. Preview QA com 150 assets conferidos, manifesto anterior preservado, sem migração, alteração de alçadas ou comandos de negócio no piloto. Móvel/impressão manual, restante RQ-01 e aceitação empresarial continuam pendentes.
|
||||
|
||||
@@ -71,17 +106,17 @@ Pedido do proprietário: iniciar a aplicação agora para evitar confusão e per
|
||||
|
||||
| Tema / comportamento esperado | Estado e evidência existente | Lacuna ou critério por demonstrar |
|
||||
| --- | --- | --- |
|
||||
| Navegação por tarefas, pesquisa e perfis | Aplicada no `sgc-workspace-shell.tsx`; contratos de menu/rotas em `menus-benchmark-20261029.md`. | Resolver corte lateral observado a 390 px; conferir teclado, foco e destaque. Pesquisa do menu não é pesquisa global de documentos. |
|
||||
| Navegação por tarefas, pesquisa e perfis | Aplicada no `sgc-workspace-shell.tsx`; contratos de menu/rotas em `menus-benchmark-20261029.md`. Corte a390px resolvido pela escala100%, sem alteração CSS. | Conferir teclado, foco e destaque restantes. Pesquisa do menu não é pesquisa global de documentos. |
|
||||
| Tarefas e próxima acção | `WorkflowTaskInbox` e ajuda contextual; 41 guias/88 páginas documentados. | Conferir apresentação por perfil; tarefas não equivalem ao conjunto de indicadores analíticos do Command Center. |
|
||||
| Requisição, rascunho e preservação de dados | Formulário e workflow existentes; `form.tsx` sinaliza `sgc:context-dirty`. | Prioridade funcional: critérios 1 e 6 da fonte — guardar incompleto sem submeter e abandonar alterações apenas por escolha explícita. Sinal de formulário alterado não comprova protecção em todas as saídas. Conferir navegação interna, recarga e mudança de contexto. |
|
||||
| Requisição, rascunho e preservação de dados | Rascunho incompleto instalado; histórico nativo cifrado e regresso/avanço confirmados, incluindo correcção do aviso indevido no formulário limpo. Provas `draft-preparation-pilot-*.json` e `requisition-history.json`. | Alargar a cobertura aos restantes formulários e mudanças de contexto; não prometer conservação após recarga deliberada quando o histórico nativo a limpa. |
|
||||
| Aprovações, propostas e multimoeda | Workflow, recibos/versionamento e `QuotationExchange` existentes; taxa explícita/congelada aprovada e estruturas FX instaladas em 22/11. | Reutilizar provas aceites; conferir estados visuais em falta/erro. Não criar decisões de negócio para testar navegação. A antiga pendência genérica de multimoeda está ultrapassada. |
|
||||
| Avaliação de fornecedores e melhoria | Ciclos persistentes, revisão, contraditório e relatórios: provas `supplier-responses*.json` e `supplier-improvement-report*.json`. | Visual/impressão restantes. A indicação histórica «proposta de interface» não descreve o estado actual. |
|
||||
| Ordens, recepções e impressão | Motores e reproduções imprimíveis existentes; ordem e recepção identificadas em `final-review-inventory.json`. | Conferir pré-visualização de `/ordens/1/imprimir` e `/recepcoes/1/imprimir`, paginação, totais e referências, sem imprimir fisicamente. |
|
||||
| Ordens, recepções e impressão | Pré-visualizações de ordem e recepção conferidas, uma página cada; compatibilidade com original antigo incompleto corrigida sem reescrever dados. Prova `product-review-20261122.json`. | Conferir documentos/estados restantes e paginação com várias páginas; preservar a prova aceite. |
|
||||
| Acordos, contratos e catálogo | Vigência/CSV existentes; multiartigo/limites por ordem e conversões físicas verificados em QA. | Não activar limites/conversões no piloto por inferência. Consulta de vigência não comprova renovação/adendas, nem catálogo comprova análise da sua utilização. |
|
||||
| Facturas, orçamento e pagamentos | Núcleos, adaptadores e provas financeiras existentes; âmbitos activo/QA documentados. | Preservar motor único e limites de activação. Registo documental não executa transferências. |
|
||||
| Relatórios e análise | Central, filtros, CSV integral e relatório por processo (`ProcurementReportsTest`, `ProcurementReviewReportTest`). | Reconciliar individualmente despesa por categoria/fornecedor, tempos de aprovação e compras fora de contrato antes de declarar cobertura. Abrir relatório não comprova esses indicadores. |
|
||||
| Administração e organização | Perfis/regras existentes; dados institucionais, várias contas, sede/sucursais implementados em desenvolvimento (`company-details.json`), por pedido directo do proprietário. | Nova migração/artefacto ainda não instalados no piloto; visual e valores reais pendentes. Não atribuir esta decisão ao benchmark. |
|
||||
| Pesquisa global, pesquisas guardadas e análise avançada | Não demonstradas como capacidades integrais por esta reconciliação. | Reconciliar com os requisitos aprovados antes de implementar; não apresentar pesquisa do menu, filtros ou CSV como substitutos. |
|
||||
| Administração e organização | Dados institucionais, várias contas e sede/sucursais implementados; recortes autorizados instalados no piloto, com provas `benchmark-pilot-installation.json` e `commercial-pilot-installation.json`. Consultas dirigidas também revistas visualmente. | Completar revisão restante e configuração real pela empresa; não repetir migrações nem introduzir dados empresariais por inferência. |
|
||||
| Pesquisa global, pesquisas guardadas e análise avançada | Pesquisas guardadas privadas implementadas e verificadas em QA, incluindo percurso nativo; ainda sem instalação no piloto. | Reconciliar cobertura global e análises restantes; ver `saved-procurement-searches.json`. |
|
||||
|
||||
Ordem de execução: primeiro conferir e fechar lacunas de rascunho/preservação de dados; depois concluir móvel/impressão; depois reconciliar os indicadores analíticos com os requisitos aprovados. Estados de código, instalação, prova e aceitação permanecem distintos. Reutilizar provas válidas e preservar os registos históricos, sem repetir testes gerais ou criar regras externas. O SGC integral não fica declarado concluído por esta reconciliação.
|
||||
|
||||
|
||||
@@ -1,12 +1,46 @@
|
||||
# Continuidade do desenvolvimento do SGC
|
||||
|
||||
## Importação directa na especificação actualizada - 22/11/2026
|
||||
|
||||
O proprietário forneceu uma nova versão de `A requisção de insumos de produção.docx`: SHA256 `9646630ac9b7e08cf84f3e93efc6cf1a90657cdc3e59d680621b74238d3a7408`, 567 parágrafos, sem documentos incorporados. A leitura partilhada preservou o original aberto. O exemplar anterior e a sua autorização mantêm-se como histórico; a secção 10 acrescenta requisitos de importação, além dos controlos de conflito da secção 9.
|
||||
|
||||
Já existe preparação logística por ordem, países, regime, Incoterm opcional e marcos trânsito/chegada/retenção/libertação; a chegada não permite stock utilizável. Isto não demonstra a cobertura integral de código pautal por artigo, custo de aterragem/orçamento, despachante/transitário, documentos tipificados/JUE, obrigações documentais bancárias, regras legais versionadas e alertas. Reconciliação detalhada em `proofs/rq01-import-reconciliation.json`. O resumo legislativo do Word é especificação fornecida; não activa taxas, isenções, pagamentos ou submissões externas. Prazos empresariais e destinatários não são inventados. A preservação integral sem eliminação automática continua válida.
|
||||
|
||||
## Ordens parciais e origens múltiplas - QA autorizada em curso
|
||||
|
||||
Autorização específica registada em `proofs/rq01-multi-order-contract-authorization.json`, vinculada ao SHA da proposta; não voltar a pedir esta decisão. Contrato opcional, adopção explícita de reservas antigas sem ordem, compromisso parcial, consumo de uma factura entre origens e cancelamento sem repor capacidade implementados na fonte comum. Preparação reutiliza as aprovações e controlos nativos, conserva termos/câmbio por origem e não emite documentos. Cálculo cumulativo partilhado com a conferência nativa preserva quantidades fraccionadas e IVA.
|
||||
|
||||
SQLite: 48 aprovados/1 caso exclusivo PG; PostgreSQL: 49/312, com base removida. Concorrência real demonstrou uma gravação/auditoria e conflitos 409; runtime V1 recusou saldo com efeitos novos (503). Backup/restauro QA preservou 115 tabelas anteriores, histórico e repetição sem novo efeito. PHPStan zero erros, sintaxe e formatação aprovadas. Prova `proofs/rq01-multi-order-qa.json`.
|
||||
|
||||
Ainda faltam emissão documental nativa, visibilidade integral entre origens, recepção/factura/obrigação integradas, reafectação explícita por Finanças neste contrato, percurso multimoeda completo e revisão dos formulários/móvel/impressão. Trabalho QA já autorizado; isto não é um bloqueio por falta de autorização geral. Piloto, pacote V1 instalado, dados reais e SGF operacional preservados, sem nova activação.
|
||||
|
||||
## Pesquisa guardada e aprovação por grupo em QA - 22/11/2026
|
||||
|
||||
Pesquisas guardadas privadas por empresa/utilizador: criar, editar, arquivar, restaurar e reabrir a consulta com permissões actuais, sem guardar resultados. SQLite e PostgreSQL: 14 testes/354 verificações em cada; percurso nativo Edge 390/1000px concluído em dados sintéticos. Critérios opcionais de aprovação pelos grupos RQ-01 também verificados: 21 testes/173 verificações em cada motor, 13 testes de interface, tipos e análise estática aprovados. Critérios combinam-se com valor/categoria original/centro e conservam o encaminhamento congelado; schema ausente bloqueia sem ignorar níveis. A apresentação dos novos controlos administrativos ainda requer revisão visual.
|
||||
|
||||
Provas: `proofs/saved-procurement-searches.json` e `proofs/rq01-categories.json`. Estas duas migrações e as novas interfaces continuam apenas em QA, sem instalação no piloto. Distribuições V1 já instaladas permanecem preservadas. Pesquisa transversal integral, análises restantes, divisão/consolidação de ordens, ligação a projectos/imobilizado, escalamento/expiração, revisão transversal e aceitação empresarial não estão declarados concluídos.
|
||||
|
||||
## Categorias RQ-01 em QA - 22/11/2026
|
||||
|
||||
Classificação RQ-01 desenvolvida e verificada em QA: quatro grupos explícitos, motivo de investimento/texto livre, ligação aos controlos nativos de catálogo, peça/equipamento e maquinaria; preparação incompleta não submete nem reserva. Categoria original e tipos financeiros preservados, sem classificar históricos por inferência. Revisão Edge390/1000px confirmou ajuda e gravação nativa do motivo, com versão/auditoria e valores conservados. QA removida; piloto conserva a candidata de distribuições já autorizada, sem a nova migração000005 ou assets de categorias. SQLite53aprovados/1exclusão/494verificações, PostgreSQL54/496,11frontend, tipos/PHPStan/lint/build aprovados. Prova `proofs/rq01-categories.json`. Condições de aprovação específicas dos novos grupos e restantes requisitos continuam abertos; não declarar a RQ-01 integral concluída.
|
||||
|
||||
|
||||
## Distribuições instaladas no piloto - 22/11/2026
|
||||
|
||||
Instalação específica autorizada pelo proprietário («autorizo») e aplicada apenas no piloto8005. Nova salvaguarda/restauro sob a mesma identidade:115tabelas conferidas,114tabelas anteriores de negócio e chaves estrangeiras preservadas; quatro tabelas opcionais vazias e preparaçãoJSON inicialmenteNULL. Candidata de manifesto `1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e` e artefacto independente disponibilizados. Somente quatro configurações previstas alteradas,18ficheiros fixados intactos e oito verificaçõesHTTP aprovadas, sem operações de negócio ou alterações de permissões/SGF. A requisição sintética existente está aprovada e a edição foi correctamente recusada; não alterar o estado para facilitar testes.
|
||||
|
||||
Provas: `proofs/rq01-distribution-pilot-authorization.json`, `proofs/rq01-distribution-pilot-installation.json` e `proofs/rq01-distribution-pilot-http.json`. Não repetir autorização, migração ou instalação deste recorte. As referências seguintes ao piloto antigo e à instalação pendente são históricas. A instalação não equivale à aceitação empresarial integral; categorias/regras condicionais e restantes lacunas da matriz continuam abertas.
|
||||
|
||||
|
||||
## RQ-01: estado consolidado de QA - 22/11/2026
|
||||
|
||||
RQ-01: distribuições por linha/centro, adjudicação, compromisso, factura parcial e reafectação explícita por Finanças implementados e verificados em QA isolado. PostgreSQL:77/355 no grupo núcleo/orçamento/facturas e6/131 na adjudicação dirigida; concorrência real e restauro pré/pós aprovados. Artefacto privado independente:17/147; compatibilidade com runtime anterior:41/134. Resultados sobrepostos não devem ser somados. Tipos, análise estática e sintaxe PHP8.4 aprovados. Prova: `proofs/rq01-distribution-qa.json`.
|
||||
|
||||
Revisão nativa Edge concluída para os novos formulários: preparação móvel/desktop, erro recuperável, gravação exacta, selecção de proposta antes das parcelas, reafectação única versionada e regresso à factura conservando a quantidade parcial. Dados exclusivamente sintéticos; não houve factura/adjudicação visual adicional. Servidor/base/configuração QA descartáveis encerrados/removidos. Prova: `proofs/rq01-distribution-visual.json`.
|
||||
|
||||
Candidata privada: manifesto `1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e`; artefacto comum privado em `proofs/rq01-distribution-artifact.json`. Piloto conserva manifesto `c0beadc1302b0e211eaeb18603a4cf7dab863b9e81f5771ddba8bec92bc4568c` e pacote fixado. A extensão continua limitada a QA: a guarda actual recusa ambiente operacional. Falta preparar a disponibilização operacional concreta e obter a sua autorização específica; não confundir com instalação/activação concluída. Restantes requisitos e aceitação empresarial continuam abertos. As referências anteriores contraditórias são históricas; não repetir autorizações ou provas aceites.
|
||||
Candidata privada: manifesto `1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e`; artefacto comum privado em `proofs/rq01-distribution-artifact.json`. Piloto conserva manifesto `c0beadc1302b0e211eaeb18603a4cf7dab863b9e81f5771ddba8bec92bc4568c` e pacote fixado. A utilização continua limitada a QA. A disponibilização operacional está preparada, desligada por defeito e vinculada ao manifesto do artefacto independente; a instalação/activação ainda exige autorização específica. Restantes requisitos e aceitação empresarial continuam abertos. As referências anteriores contraditórias são históricas; não repetir autorizações ou provas aceites.
|
||||
|
||||
Preparação operacional: verificação prévia dos sete ficheiros antes de carregar PHP (8 testes/20 verificações), composição independente18/152 e PostgreSQL24/180. Ensaio sobre cópia do piloto:115tabelas conferidas,114tabelas anteriores de negócio e chaves estrangeiras preservadas, novos campos/tabelas vazios e cópia removida. Sem alteração do piloto. Proposta `proofs/rq01-distribution-pilot-proposal.json`; salvaguarda/restauro em `proofs/rq01-distribution-pilot-preparation.json`. Instalador recusa falta de autorização exacta ou instalação já registada; confirmação HTTP preparada mas ainda não executada. Os restantes cinco grupos de conclusão do produto conservam as suas pendências.
|
||||
|
||||
## Próxima frente contratual e estado actual — 22/11/2026
|
||||
|
||||
|
||||
@@ -1,12 +1,46 @@
|
||||
# Entregas por blocos funcionais do SGC
|
||||
|
||||
## Importação directa na especificação actualizada - 22/11/2026
|
||||
|
||||
O proprietário forneceu uma nova versão de `A requisção de insumos de produção.docx`: SHA256 `9646630ac9b7e08cf84f3e93efc6cf1a90657cdc3e59d680621b74238d3a7408`, 567 parágrafos, sem documentos incorporados. A leitura partilhada preservou o original aberto. O exemplar anterior e a sua autorização mantêm-se como histórico; a secção 10 acrescenta requisitos de importação, além dos controlos de conflito da secção 9.
|
||||
|
||||
Já existe preparação logística por ordem, países, regime, Incoterm opcional e marcos trânsito/chegada/retenção/libertação; a chegada não permite stock utilizável. Isto não demonstra a cobertura integral de código pautal por artigo, custo de aterragem/orçamento, despachante/transitário, documentos tipificados/JUE, obrigações documentais bancárias, regras legais versionadas e alertas. Reconciliação detalhada em `proofs/rq01-import-reconciliation.json`. O resumo legislativo do Word é especificação fornecida; não activa taxas, isenções, pagamentos ou submissões externas. Prazos empresariais e destinatários não são inventados. A preservação integral sem eliminação automática continua válida.
|
||||
|
||||
## Ordens parciais e origens múltiplas - QA autorizada em curso
|
||||
|
||||
Autorização específica registada em `proofs/rq01-multi-order-contract-authorization.json`, vinculada ao SHA da proposta; não voltar a pedir esta decisão. Contrato opcional, adopção explícita de reservas antigas sem ordem, compromisso parcial, consumo de uma factura entre origens e cancelamento sem repor capacidade implementados na fonte comum. Preparação reutiliza as aprovações e controlos nativos, conserva termos/câmbio por origem e não emite documentos. Cálculo cumulativo partilhado com a conferência nativa preserva quantidades fraccionadas e IVA.
|
||||
|
||||
SQLite: 48 aprovados/1 caso exclusivo PG; PostgreSQL: 49/312, com base removida. Concorrência real demonstrou uma gravação/auditoria e conflitos 409; runtime V1 recusou saldo com efeitos novos (503). Backup/restauro QA preservou 115 tabelas anteriores, histórico e repetição sem novo efeito. PHPStan zero erros, sintaxe e formatação aprovadas. Prova `proofs/rq01-multi-order-qa.json`.
|
||||
|
||||
Ainda faltam emissão documental nativa, visibilidade integral entre origens, recepção/factura/obrigação integradas, reafectação explícita por Finanças neste contrato, percurso multimoeda completo e revisão dos formulários/móvel/impressão. Trabalho QA já autorizado; isto não é um bloqueio por falta de autorização geral. Piloto, pacote V1 instalado, dados reais e SGF operacional preservados, sem nova activação.
|
||||
|
||||
## Pesquisa guardada e aprovação por grupo em QA - 22/11/2026
|
||||
|
||||
Pesquisas guardadas privadas por empresa/utilizador: criar, editar, arquivar, restaurar e reabrir a consulta com permissões actuais, sem guardar resultados. SQLite e PostgreSQL: 14 testes/354 verificações em cada; percurso nativo Edge 390/1000px concluído em dados sintéticos. Critérios opcionais de aprovação pelos grupos RQ-01 também verificados: 21 testes/173 verificações em cada motor, 13 testes de interface, tipos e análise estática aprovados. Critérios combinam-se com valor/categoria original/centro e conservam o encaminhamento congelado; schema ausente bloqueia sem ignorar níveis. A apresentação dos novos controlos administrativos ainda requer revisão visual.
|
||||
|
||||
Provas: `proofs/saved-procurement-searches.json` e `proofs/rq01-categories.json`. Estas duas migrações e as novas interfaces continuam apenas em QA, sem instalação no piloto. Distribuições V1 já instaladas permanecem preservadas. Pesquisa transversal integral, análises restantes, divisão/consolidação de ordens, ligação a projectos/imobilizado, escalamento/expiração, revisão transversal e aceitação empresarial não estão declarados concluídos.
|
||||
|
||||
## Categorias RQ-01 em QA - 22/11/2026
|
||||
|
||||
Classificação RQ-01 desenvolvida e verificada em QA: quatro grupos explícitos, motivo de investimento/texto livre, ligação aos controlos nativos de catálogo, peça/equipamento e maquinaria; preparação incompleta não submete nem reserva. Categoria original e tipos financeiros preservados, sem classificar históricos por inferência. Revisão Edge390/1000px confirmou ajuda e gravação nativa do motivo, com versão/auditoria e valores conservados. QA removida; piloto conserva a candidata de distribuições já autorizada, sem a nova migração000005 ou assets de categorias. SQLite53aprovados/1exclusão/494verificações, PostgreSQL54/496,11frontend, tipos/PHPStan/lint/build aprovados. Prova `proofs/rq01-categories.json`. Condições de aprovação específicas dos novos grupos e restantes requisitos continuam abertos; não declarar a RQ-01 integral concluída.
|
||||
|
||||
|
||||
## Distribuições instaladas no piloto - 22/11/2026
|
||||
|
||||
Instalação específica autorizada pelo proprietário («autorizo») e aplicada apenas no piloto8005. Nova salvaguarda/restauro sob a mesma identidade:115tabelas conferidas,114tabelas anteriores de negócio e chaves estrangeiras preservadas; quatro tabelas opcionais vazias e preparaçãoJSON inicialmenteNULL. Candidata de manifesto `1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e` e artefacto independente disponibilizados. Somente quatro configurações previstas alteradas,18ficheiros fixados intactos e oito verificaçõesHTTP aprovadas, sem operações de negócio ou alterações de permissões/SGF. A requisição sintética existente está aprovada e a edição foi correctamente recusada; não alterar o estado para facilitar testes.
|
||||
|
||||
Provas: `proofs/rq01-distribution-pilot-authorization.json`, `proofs/rq01-distribution-pilot-installation.json` e `proofs/rq01-distribution-pilot-http.json`. Não repetir autorização, migração ou instalação deste recorte. As referências seguintes ao piloto antigo e à instalação pendente são históricas. A instalação não equivale à aceitação empresarial integral; categorias/regras condicionais e restantes lacunas da matriz continuam abertas.
|
||||
|
||||
|
||||
## RQ-01: estado consolidado de QA - 22/11/2026
|
||||
|
||||
RQ-01: distribuições por linha/centro, adjudicação, compromisso, factura parcial e reafectação explícita por Finanças implementados e verificados em QA isolado. PostgreSQL:77/355 no grupo núcleo/orçamento/facturas e6/131 na adjudicação dirigida; concorrência real e restauro pré/pós aprovados. Artefacto privado independente:17/147; compatibilidade com runtime anterior:41/134. Resultados sobrepostos não devem ser somados. Tipos, análise estática e sintaxe PHP8.4 aprovados. Prova: `proofs/rq01-distribution-qa.json`.
|
||||
|
||||
Revisão nativa Edge concluída para os novos formulários: preparação móvel/desktop, erro recuperável, gravação exacta, selecção de proposta antes das parcelas, reafectação única versionada e regresso à factura conservando a quantidade parcial. Dados exclusivamente sintéticos; não houve factura/adjudicação visual adicional. Servidor/base/configuração QA descartáveis encerrados/removidos. Prova: `proofs/rq01-distribution-visual.json`.
|
||||
|
||||
Candidata privada: manifesto `1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e`; artefacto comum privado em `proofs/rq01-distribution-artifact.json`. Piloto conserva manifesto `c0beadc1302b0e211eaeb18603a4cf7dab863b9e81f5771ddba8bec92bc4568c` e pacote fixado. A extensão continua limitada a QA: a guarda actual recusa ambiente operacional. Falta preparar a disponibilização operacional concreta e obter a sua autorização específica; não confundir com instalação/activação concluída. Restantes requisitos e aceitação empresarial continuam abertos. As referências anteriores contraditórias são históricas; não repetir autorizações ou provas aceites.
|
||||
Candidata privada: manifesto `1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e`; artefacto comum privado em `proofs/rq01-distribution-artifact.json`. Piloto conserva manifesto `c0beadc1302b0e211eaeb18603a4cf7dab863b9e81f5771ddba8bec92bc4568c` e pacote fixado. A utilização continua limitada a QA. A disponibilização operacional está preparada, desligada por defeito e vinculada ao manifesto do artefacto independente; a instalação/activação ainda exige autorização específica. Restantes requisitos e aceitação empresarial continuam abertos. As referências anteriores contraditórias são históricas; não repetir autorizações ou provas aceites.
|
||||
|
||||
Preparação operacional: verificação prévia dos sete ficheiros antes de carregar PHP (8 testes/20 verificações), composição independente18/152 e PostgreSQL24/180. Ensaio sobre cópia do piloto:115tabelas conferidas,114tabelas anteriores de negócio e chaves estrangeiras preservadas, novos campos/tabelas vazios e cópia removida. Sem alteração do piloto. Proposta `proofs/rq01-distribution-pilot-proposal.json`; salvaguarda/restauro em `proofs/rq01-distribution-pilot-preparation.json`. Instalador recusa falta de autorização exacta ou instalação já registada; confirmação HTTP preparada mas ainda não executada. Os restantes cinco grupos de conclusão do produto conservam as suas pendências.
|
||||
|
||||
## Continuação funcional e dependência concreta RQ-01 — 22/11/2026
|
||||
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
{
|
||||
"date": "2026-11-22",
|
||||
"status": "implemented_and_verified_in_isolated_qa_not_installed_in_pilot",
|
||||
"source": "rq01-source-authorization.json",
|
||||
"scope": [
|
||||
"Explicit additional classification for production inputs, spare parts, machinery and office equipment; other existing categories remain supported",
|
||||
"Original article category, native financial purchase type and published catalogue descriptors remain distinct",
|
||||
"Production inputs require the native published stock catalogue; spare parts retain native equipment/part checks",
|
||||
"Machinery retains equipment technical/Finance/investment controls and records an explicit investment justification",
|
||||
"Office or other classified free-text items require an explicit reason",
|
||||
"Missing classification requirements remain incomplete drafts without reservation or submission",
|
||||
"Native save/version/audit, encrypted history, conditional guidance and saved detail projection",
|
||||
"Optional classification-group approval criteria combined with native amount/article-category/cost-centre criteria; frozen native approval snapshot"
|
||||
],
|
||||
"migration": "database/migrations/2026_11_22_000005_add_requisition_category_context.php",
|
||||
"schema_change": "One nullable JSON column requisition_items.category_context; old records are not classified automatically",
|
||||
"preservation": [
|
||||
"Empty optional context does not invalidate the accepted equipment technical basis",
|
||||
"Older clients preserve existing classification by native source-line identity; explicit clear remains possible",
|
||||
"An older encrypted preparation without the new blank fields does not become falsely dirty"
|
||||
],
|
||||
"verification": {
|
||||
"sqlite": {
|
||||
"passed": 53,
|
||||
"skipped": 1,
|
||||
"assertions": 494,
|
||||
"log": "storage/logs/requisition-categories-tests.txt"
|
||||
},
|
||||
"postgres": {
|
||||
"passed": 54,
|
||||
"assertions": 496,
|
||||
"isolated_database_removed": true,
|
||||
"log": "storage/logs/requisition-categories-pg.txt"
|
||||
},
|
||||
"frontend": {
|
||||
"passed": 11,
|
||||
"files": 4,
|
||||
"log": "storage/logs/requisition-categories-ui.txt"
|
||||
},
|
||||
"types": "passed",
|
||||
"phpstan": "passed_zero_errors",
|
||||
"scoped_frontend_lint_format": "passed_seven_files_no_warnings",
|
||||
"private_build": {
|
||||
"path": "storage/framework/testing/sgc-categories-qa-20261122",
|
||||
"manifest_sha256": "779f11de96fb237fdcfe97268317864688d97fad841ac1d72eabee8edb0b88a4",
|
||||
"installed_in_pilot": false
|
||||
},
|
||||
"native_edge": {
|
||||
"synthetic_only": true,
|
||||
"mobile_width": 390,
|
||||
"desktop_width_observed": 1000,
|
||||
"height": 525,
|
||||
"zoom": "100%",
|
||||
"category_choice_and_inline_guidance": true,
|
||||
"explicit_reason_saved_by_native_form": true,
|
||||
"saved_detail_legible": true,
|
||||
"draft_version": 3,
|
||||
"one_update_audit": true,
|
||||
"original_descriptors_and_totals_preserved": true,
|
||||
"no_reservation_or_invoice": true,
|
||||
"database_verification_log": "storage/logs/requisition-categories-visual-data.txt",
|
||||
"isolated_database_removed": true,
|
||||
"private_server_stopped": true,
|
||||
"private_settings_removed": true,
|
||||
"pilot_finance_context_restored_by_normal_evaluation_flow": true
|
||||
},
|
||||
"classification_approval": {
|
||||
"sqlite": {
|
||||
"passed": 21,
|
||||
"assertions": 173,
|
||||
"log": "storage/logs/rq01-category-approval-regression.txt"
|
||||
},
|
||||
"postgres": {
|
||||
"passed": 21,
|
||||
"assertions": 173,
|
||||
"isolated_database_removed": true,
|
||||
"log": "storage/logs/rq01-category-approval-pg.txt"
|
||||
},
|
||||
"frontend": {
|
||||
"passed": 13,
|
||||
"files": 4,
|
||||
"log": "storage/logs/rq01-category-approval-ui.txt"
|
||||
},
|
||||
"types": "passed",
|
||||
"phpstan": "passed_zero_errors",
|
||||
"missing_schema": "Fails closed without reserving or silently dropping configured levels",
|
||||
"native_admin_visual": "not_yet_reviewed"
|
||||
}
|
||||
},
|
||||
"own_test_corrections": [
|
||||
"Two existing equipment integration fixtures incorrectly modelled a linked existing-asset purchase as a new capital machine. They now use the native associated spare-part purchase, retaining scope and pagination assertions.",
|
||||
"The incomplete-draft PostgreSQL report test now commits only its guarded disposable fixture before the controller's own repeatable read-only transaction; production snapshot protections were not weakened.",
|
||||
"The focused PostgreSQL harness now exits after the category group instead of falling through to unrelated currency concurrency scenarios."
|
||||
],
|
||||
"limits": [
|
||||
"No pilot migration or category asset installation",
|
||||
"No inferred classification of historical lines",
|
||||
"No new approval exemptions, expiry deadlines, urgency limits or company policies",
|
||||
"No claim of MRP, external project/asset linkage or complete RQ-01 delivery"
|
||||
],
|
||||
"remaining": [
|
||||
"Remaining RQ-01 requirements and whole-product acceptance",
|
||||
"Operational rollout in a separately approved release"
|
||||
]
|
||||
}
|
||||
@@ -15,7 +15,7 @@
|
||||
"README.md": "24363f762ba5ba361377ff3807704bf6143c4180919bc1c45ac6cdd54eed3639"
|
||||
},
|
||||
"host_schema": "database/qa-migrations/2026_11_22_000004_create_budget_distributions.php",
|
||||
"host_schema_sha256": "3617dd6dfecc0fb44aae5450d7fc5a26af90974eb0561aef4d1e86ef1af68dca",
|
||||
"host_schema_sha256": "ed16865e01d22eb1014ff50c3ad422860328ebf32911700891ab50ae38d853b9",
|
||||
"installed_financial_packages_changed": false,
|
||||
"pilot_or_sgf_activation": false
|
||||
}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"date": "2026-11-22",
|
||||
"status": "approved",
|
||||
"owner_response": "autorizo",
|
||||
"environment": "http://127.0.0.1:8005",
|
||||
"proposal": "rq01-distribution-pilot-proposal.json",
|
||||
"proposal_sha256": "b9c736bd73618e326c09d199b06cc04e581b8cb699140becef964f713bb70cac",
|
||||
"scope": "Install the empty optional line/cost-centre distribution schema, independently pinned candidate and four delimited settings in the named SGC pilot after fresh backup and same-role restore rehearsal.",
|
||||
"excluded": ["Business operations", "Permission changes", "SGF changes or activation", "Other disabled capabilities", "Production publication", "Enterprise acceptance"]
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
{
|
||||
"environment": "http://127.0.0.1:8005",
|
||||
"result": "passed",
|
||||
"results": [
|
||||
{
|
||||
"role": "requester",
|
||||
"path": "/requisicoes/2",
|
||||
"status": 200,
|
||||
"request_status": "approved",
|
||||
"can_prepare": false,
|
||||
"restricted_preparation_hidden": true
|
||||
},
|
||||
{
|
||||
"role": "requester",
|
||||
"path": "/requisicoes/2/distribuicoes",
|
||||
"status": 403
|
||||
},
|
||||
{
|
||||
"role": "admin",
|
||||
"path": "/requisicoes/2",
|
||||
"status": 200,
|
||||
"request_status": "approved",
|
||||
"can_prepare": false,
|
||||
"restricted_preparation_hidden": true
|
||||
},
|
||||
{
|
||||
"role": "admin",
|
||||
"path": "/requisicoes/2/distribuicoes",
|
||||
"status": 403
|
||||
},
|
||||
{
|
||||
"role": "procurement",
|
||||
"path": "/requisicoes/2",
|
||||
"status": 200,
|
||||
"request_status": "approved",
|
||||
"can_prepare": false,
|
||||
"restricted_preparation_hidden": true
|
||||
},
|
||||
{
|
||||
"role": "procurement",
|
||||
"path": "/requisicoes/2/distribuicoes",
|
||||
"status": 403
|
||||
},
|
||||
{
|
||||
"role": "finance",
|
||||
"path": "/requisicoes/2",
|
||||
"status": 200,
|
||||
"request_status": "approved",
|
||||
"can_prepare": false,
|
||||
"restricted_preparation_hidden": true
|
||||
},
|
||||
{
|
||||
"role": "finance",
|
||||
"path": "/requisicoes/2/distribuicoes",
|
||||
"status": 403
|
||||
}
|
||||
],
|
||||
"business_commands": false,
|
||||
"session_context_only": true,
|
||||
"visual_review": false
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"date": "2026-11-22",
|
||||
"status": "installed_and_capability_enabled_no_business_operations",
|
||||
"environment": "http://127.0.0.1:8005",
|
||||
"pilot_read_only": false,
|
||||
"backup": "C:/laragon/data/sgf-tempo/backups/compras-distribution-preparation-20261122-151517-722fe0/before.dump",
|
||||
"backup_sha256": "5acc087650292b43841e5ea4993f89d56ed755aec02535001241f1e7be19a39b",
|
||||
"same_restore_role": true,
|
||||
"restored_tables_checked": 115,
|
||||
"previous_business_tables_preserved": 114,
|
||||
"previous_foreign_keys_preserved": true,
|
||||
"new_values_empty": true,
|
||||
"optional_tables": 4,
|
||||
"deployment_settings_unchanged": false,
|
||||
"pilot_manifest_sha256": "c0beadc1302b0e211eaeb18603a4cf7dab863b9e81f5771ddba8bec92bc4568c",
|
||||
"migration": "database/deployment-migrations/2026_11_22_000004_create_budget_distributions.php",
|
||||
"migration_sha256": "d398ce65ef0c770fdf23d9ae0eab8eafff07448c0606aa47c8b423bcf876ca21",
|
||||
"schema_definition_sha256": "5d1ffad80ae0e663065396e5f2aa08eee6a790a0a9801ceed5e2c1e3c280ef7a",
|
||||
"artifact_manifest_sha256": "f21dfbc9cc4344abec88953bc3fc2b7f5751fba401ab52f0da950ae0715816e5",
|
||||
"pilot_schema_or_activation_changed": true,
|
||||
"manifest_sha256": "1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e",
|
||||
"release_path": "storage/app/private/releases/budget-distribution-ef60dd86bf71ec79",
|
||||
"business_operations": false,
|
||||
"grants_changed": false,
|
||||
"pinned_packages_changed": false,
|
||||
"restored_database_removed": true,
|
||||
"unrelated_deployment_settings_preserved": true,
|
||||
"changed_settings": [
|
||||
"COMMON_BUDGET_PATH",
|
||||
"SGC_BUDGET_DISTRIBUTIONS_ENABLED",
|
||||
"SGC_BUDGET_DISTRIBUTIONS_MANIFEST",
|
||||
"SGC_BUDGET_DISTRIBUTIONS_MANIFEST_SHA256"
|
||||
],
|
||||
"http_checks": 8,
|
||||
"http_proof": "rq01-distribution-pilot-http.json",
|
||||
"post_install_verifier_correction": "The existing synthetic requisition is approved, not draft. The read-only verifier now checks native current status and ownership without changing the process. All eight checks passed.",
|
||||
"proof_metadata_correction": "Preparation-only booleans replaced with the actual installed state after comparing the private deployment settings with their saved original."
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"date": "2026-11-22",
|
||||
"status": "restored_pilot_rehearsal_passed_not_installed",
|
||||
"environment": "http://127.0.0.1:8005",
|
||||
"pilot_read_only": true,
|
||||
"backup": "C:/laragon/data/sgf-tempo/backups/compras-distribution-preparation-20261122-150244-0fbc0f/before.dump",
|
||||
"backup_sha256": "9488763c88ff5c7ab0010f94f665ba887de2034aaec325e809d682aa15ab86b6",
|
||||
"same_restore_role": true,
|
||||
"restored_tables_checked": 115,
|
||||
"previous_business_tables_preserved": 114,
|
||||
"previous_foreign_keys_preserved": true,
|
||||
"new_values_empty": true,
|
||||
"optional_tables": 4,
|
||||
"deployment_settings_unchanged": true,
|
||||
"pilot_manifest_sha256": "c0beadc1302b0e211eaeb18603a4cf7dab863b9e81f5771ddba8bec92bc4568c",
|
||||
"migration": "database/deployment-migrations/2026_11_22_000004_create_budget_distributions.php",
|
||||
"migration_sha256": "d398ce65ef0c770fdf23d9ae0eab8eafff07448c0606aa47c8b423bcf876ca21",
|
||||
"schema_definition_sha256": "5d1ffad80ae0e663065396e5f2aa08eee6a790a0a9801ceed5e2c1e3c280ef7a",
|
||||
"artifact_manifest_sha256": "f21dfbc9cc4344abec88953bc3fc2b7f5751fba401ab52f0da950ae0715816e5",
|
||||
"pilot_schema_or_activation_changed": false,
|
||||
"restored_database_removed": true
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
{
|
||||
"date": "2026-11-22",
|
||||
"status": "prepared_not_authorised_not_installed",
|
||||
"environment": "http://127.0.0.1:8005",
|
||||
"scope": "Install only the optional line/cost-centre distributions and explicit Finance amendments in the named SGC pilot; no SGF activation or business operations.",
|
||||
"schema": {
|
||||
"migration": "database/deployment-migrations/2026_11_22_000004_create_budget_distributions.php",
|
||||
"migration_sha256": "d398ce65ef0c770fdf23d9ae0eab8eafff07448c0606aa47c8b423bcf876ca21",
|
||||
"nullable_column": "requisitions.budget_distribution_preparation",
|
||||
"new_empty_tables": [
|
||||
"budget_distributions",
|
||||
"budget_distribution_events",
|
||||
"budget_distribution_entries",
|
||||
"budget_distribution_consumptions"
|
||||
]
|
||||
},
|
||||
"release_path": "storage/app/private/releases/budget-distribution-ef60dd86bf71ec79",
|
||||
"artifact_manifest_sha256": "f21dfbc9cc4344abec88953bc3fc2b7f5751fba401ab52f0da950ae0715816e5",
|
||||
"archive_sha256": "40648297cc2dbf755ca68afb06a9ea68cbea42ff50293d37422fb19119062798",
|
||||
"candidate_path": "storage/framework/testing/sgc-distribution-integrated-qa-20261122",
|
||||
"candidate_manifest_sha256": "1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e",
|
||||
"previous_manifest_sha256": "c0beadc1302b0e211eaeb18603a4cf7dab863b9e81f5771ddba8bec92bc4568c",
|
||||
"assets": {
|
||||
"assets/Combination-Cf-uZSDM.js": "cb6de0edf2a5bc431766866135d9c8868a5671cd0bcc7894cfd8d425db1ea41d",
|
||||
"assets/access-BZvfQY6s.js": "22474f22beda79656b852f4bbd2cd5b0c788e3afd6b38a83ad762e4e191d7598",
|
||||
"assets/access-CcapOGga.js": "143a71c5b4be66e0a7f798c8f3f5f08ba8a3faa5f95a64b92e654078346c3857",
|
||||
"assets/administrative-location-BJbMIJqP.js": "da52b578cc746241cda6df38aa088043a0aa5333f4cbd6764b278bbe549d2a2d",
|
||||
"assets/admission-CRd4Gp_t.js": "e64b22708d8db6b8772e27bc6a020584036c8ad7fe89c0d33a10cb2c46e69efd",
|
||||
"assets/admission-DCW-DMKi.js": "15bfb460a10658d38878de1be382571c9e95755347438a16026fafee4d50129f",
|
||||
"assets/admission-policy-Cu2N7UxX.js": "3ca7633bb6cfa80038fdb14c80b8138446b7680a21a01958f4adb27ae5ec52a5",
|
||||
"assets/agreement-followup-BJwY7Q7H.js": "fffc34510c18562b425f29771d254bb0136da9ac95fd8e28672de75f219054ac",
|
||||
"assets/agreement-order-bindings-gflwHvTF.js": "a20b69389c9cf61b39b15f56792a3d1dd2defb91958ff1820476e5244e2821a8",
|
||||
"assets/ai-preparation-preview-BsDt13H6.js": "6a736e4005282bff1b47d4601b01b880fcacc39faf972d9292466d0412a8924a",
|
||||
"assets/app-BYcuaKuR.js": "177fc3f34068262de25d20f894d3d5bcbd3a204c39ba9a994a0316ffe5d4cf05",
|
||||
"assets/app-CPyB0lMZ.css": "a621247b9fe4c69109e1307f5c8d16b291473f013370ddd9e9d037dc30b18a2c",
|
||||
"assets/appearance-8Z9i0cfX.js": "b7ec8f4ccae36e008a184159c8f74984a2e9398c36bda3c51656a1521e79c6d7",
|
||||
"assets/arrow-right-jQM5Ljhm.js": "460657b89c0a22dd8c648c59408ab9b5d89cda0a2f77fdb5aafb5d4cd81ee047",
|
||||
"assets/availability-rTkrhEIP.js": "d9b41675e607ed52578af47af23d4172729a34e49b7608111db9eb8f75389c9e",
|
||||
"assets/award-CLugGRtU.js": "a72d703635e757bdfcf0c4e16e95f09fb5b4614a3c2b976cac7ba37d36bc32a3",
|
||||
"assets/bank-B7zGvR_J.js": "66eff9606017feefe83bd7bcb14804422d35a399b8a520fa301195c5de8040bb",
|
||||
"assets/budget-distribution-fields-D2Aw5hyZ.js": "f998d18fb629d75c0306e39fbc43c4f8ae6b21d198cabcf53a9022c178faaa89",
|
||||
"assets/budgets-BIGhc0Yl.js": "594c5d79345383ffbbe243d14c0b62db101ef2fe7858c17054397005bc4e340f",
|
||||
"assets/button-CSyysFhi.js": "a0c7c2d62ff1c139a6b5e6ff2e4c7cc778682337a935a3eee0e2df5ac36607b9",
|
||||
"assets/candidate-availability-BBYAjwDY.js": "848c1b093b9016d4dbbc7795f44c281eb3776bfebf82b2a84ca943c70f5df1aa",
|
||||
"assets/candidate-documents-DzSJVuya.js": "3f5131f76ab32a1477614e2318e09a5fbe736f5b6fc75fe306fdba5802f28482",
|
||||
"assets/candidate-portal-Bwky2Aqz.js": "7c5e97bfd6fbe7a7fd98a4508f87acda4c1e750c7d5fa35616bc422b6dc80751",
|
||||
"assets/catalogue-jYTAdj6-.js": "2098a1a928c079470e827ed7915070befd1aaec66ced6f5f9584e58eae542742",
|
||||
"assets/check-B0y1oDcN.js": "2b0f7b1e72a08a1106cae81a5910d88a308d1bc92c729def81b0c38b743c7c59",
|
||||
"assets/clock-3-Cy_zSYUr.js": "b8bf146f2a287cd2bf356687ab0dfdcb0bef6f0213bfda494985dd98d97d20a0",
|
||||
"assets/company-fLQDrq7Y.js": "070f6a22094552311fadb5f308888ef152be80d70be8048920e44daceb725f01",
|
||||
"assets/comparison-policy-summary-7M2PXYtp.js": "da46e741c25a8794ba2006a8836758e3217f4aff71a2ac7bff0b09f693399bdc",
|
||||
"assets/confirm-password-bGnDs4RM.js": "ab3838dd09e9394fa42df04c061a81b3b56f88ffa5da2cddfb8c5d24f0b3c2e2",
|
||||
"assets/conflict-aivhJ9_v.js": "810076518c31390dd9399c028084f4c09ecab7b4645da1d798a49ef66f7b612f",
|
||||
"assets/conflicts-BvV9gVce.js": "ccbed06e5540cb76c203408c2d0b71ac368f64514c50ab3f3c00e96a3cbaa5f9",
|
||||
"assets/coordination-D4TbIBI_.js": "63ee0c502e177266e0e82341a23a5673deb267f396e20bafcb494a379f5f051c",
|
||||
"assets/correction-source-search-34VbA_Cg.js": "b7d5ed1fa3d9464c1a71199e8640b14be8abb9e0c9945f97658d7928b7540288",
|
||||
"assets/createLucideIcon-Bl2ij0Zm.js": "88026a98f925baf2a85f5c6091f3dce5d35689ec432417ba87ac3fba450aa326",
|
||||
"assets/dashboard-BLqnPGWz.js": "a3c2a59716a46db1a1dbb8d59a7993cb80f0e27816f02cf2fc50fe5db350dbd9",
|
||||
"assets/dispositions-BpzQGc5N.js": "ef44a725a1b09a7d41646f1438fabd31a67847f31a7ec9577c2d3a091cc4bfd3",
|
||||
"assets/dist-Bm7wFECT.js": "ec7a8f48099bdb15bd706858c566dff3c664ea77420b2973463f9482c5c66aa0",
|
||||
"assets/dist-Cxy2kTRX.js": "7884e24de234f6d592ec16f228c0eaba69ee5adf28fcbedb0d59383d184958c8",
|
||||
"assets/dist-DSfJglKD.js": "7e5239388df8e9e9251bc5d432701c3a1798b8940371f88e42683e6426f0c6f2",
|
||||
"assets/distribution-amendment-DFWmvvZc.js": "1477c6f467d794a7b374d46429e10d344e06b2fd90a95cd3b88800a3bacca12f",
|
||||
"assets/distributions-CuLxicHi.js": "c90154fcc04a5556acd0069f6bc887c271a0c7ca02011bcaa01e59eab0ef4085",
|
||||
"assets/download-d-ik75sA.js": "ac23d0b10fe748b8664965a4ebb479336cbc75e4d08e570577e5f70519bfde1c",
|
||||
"assets/edit-BnPKsMan.js": "0faf4324e698b22e7ce814cdf61f94d0fc9050cc4c275562845e9f4771229edd",
|
||||
"assets/entry-bcaSTEtB.js": "119e5ae40f2c307aea595d5eafd94e496a1ee14be76c62eacc659a6abbedf181",
|
||||
"assets/equipment-DbQkc-Wp.js": "7ef5e2b6660b5f7c22c2509a0e9f18e9f6e9494b571b41a4c096386891ccf149",
|
||||
"assets/evaluation-DEuxqIy9.js": "0df36580076ab8e7996105713beb61b795dbbdcec545853150fa26ac0827a280",
|
||||
"assets/evaluations-BRT9Wk8D.js": "e2cb45cbe35d1ac98c1ebc9d04571edaa6c1112bd98de18b07370d6709b2b445",
|
||||
"assets/eye-BcFYyvf-.js": "eccd97f0bfeab1e54e9d1abdcd96184794449a6b6277d096598489f52f61e9cf",
|
||||
"assets/file-text-BMumQ0Wt.js": "9af4fdf5c0527694f24719af17256ac1ebb7061ddd738e5135fdd411f5b3a3ac",
|
||||
"assets/fonts-C9MNnjVw.css": "3846a9bb60bfad92960eadcccaf0b4e129d74b11d48791506c8d1a827a385cc8",
|
||||
"assets/forgot-password-YVHqh7XD.js": "eea1af7ad0e46dc9d023cf875a127f7b124804ed1ebc8dad9c4d157a5a0ce811",
|
||||
"assets/form-D2Kr5XaT.js": "27d010e46abfc099a0acb0b09d5686fbaff1824244bfbfd96d3c414c94a22e66",
|
||||
"assets/geography-review-C9b6c-7h.js": "65d8c79500acedbee86e2b48c536ba446530503aaade5d7a29338e617a7a87d5",
|
||||
"assets/history-C3tOJ7sJ.js": "67f7a2bca7c6d597aac44ca79d19277868f5b5b8d5064c34a383b16822f4c53c",
|
||||
"assets/home-rrYGeZa3.js": "3d4236e07c1c6d710e7ddf6dca6da11bc6a76b5cefd8bdfb9bd99e345738fac7",
|
||||
"assets/input-error-B1DjHZT7.js": "00286fd9e30543b59027b37606d63c96944efdf4f58339aba7afd0cd08629ace",
|
||||
"assets/instrument-sans-400-normal-D1W7dsQl.woff": "797bd3eaa70edbd4757650ab44dad75fbfbfdf18bacedb4b71022c04621d30ad",
|
||||
"assets/instrument-sans-400-normal-DRC__1Mx.woff2": "9a91efaa3599a6ef01b2f49e9ec670e3a2f39baeef09c73198f1052cf3bb0850",
|
||||
"assets/instrument-sans-500-normal-Dk9ku72i.woff2": "9d3547da16d950d12a677c772a3ff9b69846e60e7dcd1b5efd540993f7286532",
|
||||
"assets/instrument-sans-500-normal-Z6ESRlEs.woff": "bd6a8dc8b0dc0cced0c32d3eda93f0e0e82c58ddefea8b53b3307b0c48da3089",
|
||||
"assets/instrument-sans-600-normal-B7fBEWYG.woff2": "efb770916eda95a0e31d80cccde9651d4e8617010b21220e9f227c4820d675da",
|
||||
"assets/instrument-sans-600-normal-B9e8oLYv.woff": "9b4ce1f2b26be7cb087fd87d6f99a202136292ec820af75bd38ab9e53895cf28",
|
||||
"assets/inventory-BF2HrsoH.js": "fa3e4a56bae767f93e7f7d0202c4efecc8d08583c0ca6761db8560acda64ddc9",
|
||||
"assets/inventory-DpjqZsgf.js": "b453fde1261963b6d699134fffe749b7e5dcb998a69c6066e6f51e5cd390276c",
|
||||
"assets/inventory-correction-filters-B7Bxrtkf.js": "9f8531c1552402f1bdd7ffef09036591ab5d5d0ae658b7a83a04fb05049af0d8",
|
||||
"assets/inventory-demo-CuZI2x3c.js": "93b549548273d7cada0fda194e9d3024265ef21bc9fdc9dd4cce4bdcbb27b760",
|
||||
"assets/inventory-event-actions-CUZg6Ug9.js": "aaa2d5cdbfa6832d44bcacfde60c7ed69a49d56b69d4d53766b34201dfbbf17f",
|
||||
"assets/investment-BBS9Fqtt.js": "7b3b68279223fc44924504ff96b0bd048f6fe59e65255e6cefe9e21e91790c74",
|
||||
"assets/invoices-FmDYT7Rd.js": "53451aca7ad8dff772c2cfc830de20daaae91c639a8ee2ba5275f6c4f1ec1660",
|
||||
"assets/jsx-runtime-Cjjuc_0N.js": "239501f6701a312b0fbef99c9067ea0d62f11aeeb3a8b388ec4c7528b0493500",
|
||||
"assets/label-Dn4U5SHB.js": "d273f9faf668fc6fc998709fa86dbb3d424a23271725cc48a9b88a8b2d8e399c",
|
||||
"assets/loader-circle-YS2_4W2r.js": "4648de3680be9df8d38d808bb954b6cee541cf3b376321926a10c3edddb96345",
|
||||
"assets/login-CEy5D8o9.js": "012f5fc7519b509e218401d007bf7a8971c27c4fab037a0f54a1a688b095098a",
|
||||
"assets/lots-DVzlumgX.js": "ac8fa03e5d27687bbb348482a51f05162786005460a8402b93210910e3d73e36",
|
||||
"assets/metadata-CyzFhq80.js": "57d83cea2f7f90c1eb18bb04a5ddaafb83b9a2cb4decf50fdc761649c5398bff",
|
||||
"assets/notices-Cz8Yr97-.js": "19ce2727acc38524d8c713403b7a4b0279cc01ca8261809aa2bc156e9aeec92a",
|
||||
"assets/opening-D_s15tdl.js": "de7c31b3fbb52ddc958423af43ceefd97f6b335b53a26b7492a6ad33d4721ecb",
|
||||
"assets/operations-7G1snIsP.js": "55ddeff0c70bf5597d382ae458f080acd9e3636ab49c77611b73dff09e24f5ab",
|
||||
"assets/opportunity-Bh4UUPh8.js": "6e2d8a21d33664722f95dfad29dac33c58de2da37077f93c6a1404880b350419",
|
||||
"assets/order-BBHtd5I4.js": "1512c2f696c735be0eae0ccc4b35ac947d8a1139e2989b19530dd13d34a8cf4a",
|
||||
"assets/orders-CWAAV0kF.js": "cb5c87d441513cb2ff9ab668efe038665324872168a2724d2b07d5f281df3a14",
|
||||
"assets/package-check--ZYjz2oi.js": "ce6074fe092e03473ff914cfe088a47acd57852fe4faef54f239fd04ccd6ab83",
|
||||
"assets/parameters-DmXXmGb8.js": "ce94e8bb88b900ed49cdb2d659466daaed316e6b98c1ce26a0e1fa533ef0e07d",
|
||||
"assets/password-DSVT9zkL.js": "e9f8a7ef9b436a3e046d49f9ab56bdb4ca736bc98f69fc89efe36ec0a9bd08aa",
|
||||
"assets/password-input-D4sBYK-V.js": "d69be490d82f406268c95cf1eabd2f6da079068c9a08bd84651dbe6ff0b1e02c",
|
||||
"assets/payments-u4BsdybH.js": "19e059fc7fcc31bda7b09ac0375554eedaf3c9d38a2c869176c010352cafcd38",
|
||||
"assets/pencil--NTa5x5n.js": "ffc5e9c22501ed8196d21f31e016d351f91796821392ec9942716d7a70b9c022",
|
||||
"assets/people-BshN-e0j.js": "5c545496bc8d446c46338ed7fb035a6b13c4b9aa04c6c25812c77e1c3f9d0433",
|
||||
"assets/people-hiring-0ebERuf_.js": "443ff16989484ecbb7576eb060a5339fccd2fc720015d72a2af828e91d12461c",
|
||||
"assets/pilot-CVQYRC4h.js": "7bace70d23debcb56b53d0e8e5f3f8bd991fd2a2fd640942d763e40f27b0d182",
|
||||
"assets/planning-CMKq06j8.js": "d3440a64519d5bfdf1108c3f24656344094246e7a98ab2aa20e3ae4d06fcfbb8",
|
||||
"assets/preview-DNs6WVCS.js": "ceaf281cd2f88ab47a88c06e60de37a05cd837cf4df38268a7a9bab3199ae365",
|
||||
"assets/principal-B628nxG4.js": "857aae7fd217c24da74c07421855b75a15755332aee101d2e6d4136387935efc",
|
||||
"assets/printer-D0Qc0KdJ.js": "6a29144df3944867ae389bb8e8194205099314ffa04c41f0fb054226f27b3566",
|
||||
"assets/process-BhopPGr0.js": "ab921d08e37294575dc9d75bc5c31c287157aef7bcb008b1dea0aa04d1fe7917",
|
||||
"assets/procurement-BqzkA4bz.js": "db61c74eda890b5107f39cb1482eadc7f55bbcaac19fc9843fdfb2d5de62c4bf",
|
||||
"assets/procurement-CUWIEhpG.js": "e4ddacd60afe0b12a947bdf53a7d7cd7a83a8978a84645e41f4f70137f9501d5",
|
||||
"assets/procurement-DS63g1ZI.js": "05f5ee6e2fa928440fe4fe979ea8c6956e92029fe61eb31b84a47e2fa6a02171",
|
||||
"assets/profile-DfwZC1AU.js": "5cb898450486d46553742f82ed8a82bdf33e55302609436e7ad25f7a9b44b905",
|
||||
"assets/profile-XWQpk5s2.js": "18b74edca0e2efb6ce28b0a15aca3b23bf818efce48a059ff76afdba1d16e5ae",
|
||||
"assets/purchase-controls-BzrY4MFa.js": "9db74864e3d5d91e86567df488151b7654d8d8e4d831cfed171a74e170f02405",
|
||||
"assets/purchases-DDjTWPmN.js": "3dd52d41e603d7363f3e7eb010ef0c6f047c8a7f4cbe5da14815e9d077152e12",
|
||||
"assets/qualification-B4IskB9T.js": "bea08b007173c7c53893a941a495f810e0cd026c0134deecdfcc37dd28728df2",
|
||||
"assets/qualification-DxyaMlU7.js": "77484bb2288f0d169c39ecc4eb322912e7bd091e545b4fda48f656d4464e0634",
|
||||
"assets/quotation-exchange-panel-DwxGYRWS.js": "a401f3903941d80c25beea60be58010cb5a1a49d3aee71c8500716ef47062521",
|
||||
"assets/quotations-BHF2mA5i.js": "f79dd6bc2cae5b95fbdee1dac747ec19aaf66e0c6557ae96bfa67cf75fb4c97a",
|
||||
"assets/receipt-CX6COlya.js": "a20578c41e007f6000ff25baf9e53e7c39312d6541432b98edaa66d2355461d8",
|
||||
"assets/receipt-conversion-ByLHpo0x.js": "46005baac92a5710f7ebba13b054b73a7f8518e4a055da7605c41037a29772b5",
|
||||
"assets/receipts-DWJDlufr.js": "d3372c9643323f1e2f96bb9598ab35bf6639d62ba9aa536be3311ea3590d1dea",
|
||||
"assets/recommendation-BD8Tj-iF.js": "aeaaf4b63992d19f1576520b0497ed8f606d6b73fe6443fa2b0bf24bcb70c927",
|
||||
"assets/recommendation-YOpn5O2G.js": "41f5894bbf71e864a949f23b7805c85ab6fd7031d33ce49fac2d901fa3e49220",
|
||||
"assets/recommendation-policy-R5dCw6H9.js": "af9bd64fe6de4f50afa50f041816d5c1c25c54b38e09595d9acb1859bad87e6b",
|
||||
"assets/register-CeKcXWQX.js": "9431e2f790eae51ad02eee8e266e014eb46141c93729d33df6e8c01310108a94",
|
||||
"assets/registry-CiwVVw8N.js": "4d305860350f63a0523fb05bbebb2be467b7c70553f0ac28982881070175bc63",
|
||||
"assets/replenishment-ptVswWoP.js": "2c31f6ea9a3a46b79c6afeb32644a17c8e0ad944207938bb62e03f77413514fa",
|
||||
"assets/reports-1pADuqo8.js": "319fce822a6fc3672ebca1c39dd89352f24719eec19f261280cafa523c388fb4",
|
||||
"assets/request-DR83SKNQ.js": "77190b1df1046a417f0b96e60700584030e9d468a59bae349c6001fe64a1899f",
|
||||
"assets/requests-BUvFusKj.js": "b37f9f214865ec0d455c665723e1fcb55d72db251eefe173d20e991cbe3bf7d9",
|
||||
"assets/requisition-history-BoVkj-pT.js": "5041ae5447c0d257b478783eabc0f3ed2bc5c9d648e913f449bc24aa5f39db28",
|
||||
"assets/requisitions-C1Q5d6Y3.js": "5ceff3d848e67fc0dcb463732f13b0c26f15906ba18ac75d5d070e6ff21c0058",
|
||||
"assets/reset-password-Cx81K609.js": "7a5c9eff408a521692f339b1f97cb4900ae49c3b486325d140eac0e6c9b24a51",
|
||||
"assets/returns-D795f4MQ.js": "00dda52be0555d9d9dc6cd2402283d9180839e35957afaffa2f45fbff227987e",
|
||||
"assets/reversals-5X__iN4U.js": "1556ccfdba041baf4e8bc5ad11042b68f7f480f169a81ede2416bb9fad23ce34",
|
||||
"assets/review-report-B2kJwRhu.js": "5277d041f85354a5b939b2cd3e2e57d7bfddf2c2eac8a2e79162074574a9a565",
|
||||
"assets/rolldown-runtime-WkwZ5CU-.js": "2629f2ad3cb75a57d98de697127f5af7d777ef572bbcdfa6e3ce8f438cd4527e",
|
||||
"assets/security-BHIpDy_9.js": "666c3ec45bc1af447f255cf45f7aca2a64174b3515a5425d44b877bf9373f0b1",
|
||||
"assets/setup-BpYmfxSf.js": "7af93fc9a98b8cfc7ab842d931fec4455b476024524d7f66c9095e6b1ea9d29c",
|
||||
"assets/show-B8yO7sGd.js": "9bd2cdf3174a59b75f97c44dc34206c0d32aeca6451133c8822010ad1783f575",
|
||||
"assets/show-BltLLOkC.js": "81e528a4160bac8e9f10110f95bc655b8a534bc7142b6d1596b2dbbb949c076f",
|
||||
"assets/show-CXPav-RK.js": "ee4721fc7745cc941cc0740d2b3ce9b4bd0bdff346ba1924167693791f799f50",
|
||||
"assets/show-ChinrVqW.js": "e0af6eac731d0f50d44107de4645f506d145f7adf17d927d933cc23ee928de56",
|
||||
"assets/show-CiXHf48Q.js": "5fc6019fb4562e8870281836674dbb02b12ef7ece1714a98375b02b8c853d5bb",
|
||||
"assets/show-D6SELCPO.js": "02258083fdd86d51821bd8aeff30fe2f9148fcd6b43a8f15d91ba81a75ce0adf",
|
||||
"assets/show-DCXaQ86h.js": "d385bff4ab7c5996e447778a4a27d336d5d9ad90341eb19f45135ba3c7ca8a20",
|
||||
"assets/show-eXIFhEhG.js": "3e9bfb47440b6130035ffd8096e867a60b8d7860fb7d898f989e73de75da9f07",
|
||||
"assets/spinner-CpJAdIKb.js": "9c8f8fb08c631cae61ecdf41cd766fbc3e777fd184fa707b6351c3d460eef059",
|
||||
"assets/stock-DCjtnuTZ.js": "916ec71c7144ff0dc3330651766344aff05edb538a2b5d5ff79c5eacf18fa9d9",
|
||||
"assets/submission-forms-BS2qZil6.js": "f641fc725aa19fd2a14b7b8a02706ca9c0f25f6c36867dcdf0d1e079b29c4db5",
|
||||
"assets/submissions-CgF8WuYJ.js": "212040b42a05862f58519dab85ea05ee1d569a123c13d58f49c33ea2bf8497c6",
|
||||
"assets/suggestions-yo6FGV47.js": "5d06098438de18d2ea7e2b0d62abdc2fea953689af97bb7e2da02a7106981137",
|
||||
"assets/supplier-DbZ754P4.js": "5617827f9283736a34edb62fe4ea4e6c8df48961c617dd66f416fb054dd92ab4",
|
||||
"assets/supplier-evaluation-fields-Dq9wuabP.js": "2cb374f1c614d6718e78d5a1ac92c593db69a146896cdb68c80f8f5b63d8f64e",
|
||||
"assets/supplier-improvements-CYbJgiGO.js": "eb4aba74f37f567edd72e65211e056241f06c3e8b0f6b6583c05e69525e6ec80",
|
||||
"assets/suppliers-De7QKmFB.js": "5b2e1a78fc5ab235292e4db9809587a92b4542487e6bd02eb5becba69619fe36",
|
||||
"assets/supply-c0fZaSpY.js": "b50e8941f9ce584c65996a288ede708987b2d090de333e63ee9c2a66918f561b",
|
||||
"assets/supply-pagination-CnzjlbVc.js": "8537e2e4e48a836f41a2b2176f635ced2b1c62734485d1109bc4469168a1cb28",
|
||||
"assets/tasks-DE-7_tTT.js": "9d8a4faa40184fb568f0930e6c86602ac21f5f51b8966e6c097111311066cc20",
|
||||
"assets/territorial-filter-BFhDQ0bx.js": "aec781e84e0ebac885fdbc74fffe75ad673d57964de4ef07c7e54a2e98157ad6",
|
||||
"assets/text-link-CydDNIng.js": "9ddf76c1a4d33cb5d25315e38395f2893250091a23c156adc582bbb2bcad85b9",
|
||||
"assets/two-factor-challenge-BasHB-NT.js": "57c1fb0e652f44cc5229aa1f4ba53f5fb63b2136a538b3c62eb4fae13576f2be",
|
||||
"assets/utils-DJPu_GY6.js": "7b162681baff9e9a115823fd6070404fcaddf53d058b311edbe98be7f2662ef4",
|
||||
"assets/wayfinder-Dp7PqxvV.js": "3d4c90228fda731e37f541f3087fdf5387d9d59433e35b267b64a97196f70781",
|
||||
"assets/welcome-CYJd6CDz.js": "78bee5083771905bb597c8b58ce7f2bb056c82f7a407bc7842a5c2a8e88b3519",
|
||||
"assets/work-context-DEs_zaEM.js": "b70b3e5081ecbcf3b61e5786e199736082521b0a340bd48aa43814b098a9f661"
|
||||
},
|
||||
"reviewed_files": {
|
||||
"scripts/prepare-budget-distribution-pilot.php": "ab44b7f8ad8196c7db5106aeb2ebf0215426379f6261ba14ad782642aa4c0eac",
|
||||
"scripts/budget-distribution-pilot-http.mjs": "5e9eef07cd6b70c3749bb47f87be1fd55e516e807791269013a55c18071fd4a9",
|
||||
"app/Services/BudgetDistributionArtifact.php": "9cd7ba48d3f91ed75fc0cee66b4c65387af2261d338ae7879305cfe0b13cdc8a",
|
||||
"app/Services/BudgetDistributionSchema.php": "5d1ffad80ae0e663065396e5f2aa08eee6a790a0a9801ceed5e2c1e3c280ef7a",
|
||||
"database/deployment-migrations/2026_11_22_000004_create_budget_distributions.php": "d398ce65ef0c770fdf23d9ae0eab8eafff07448c0606aa47c8b423bcf876ca21",
|
||||
"app/Providers/AppServiceProvider.php": "2c068df9ee2c25949e7db1795298922d8af3a157f99b53874b00719735c3f307",
|
||||
"app/Services/RequisitionBudgetDistributions.php": "98420ea9f73af5b8e92f5e56d1b992091e256dd04fe036d3a1ecb2d74af313d6",
|
||||
"app/Services/InvoiceBudgetDistributions.php": "a07781c06233772213b934c188d617066f8c4af07ea7646493403fa9835449e5",
|
||||
"app/Services/CommonBudget.php": "bcfd8a7048746456f1a9403347c9093ca4ea52a433e9b43fc0046896d4f4c773",
|
||||
"app/Services/BudgetWorkflow.php": "f97d649871ae5f70e0bf189608f0c6fb1f56aceda8ce10edd6bfccea9511928c",
|
||||
"app/Services/PurchaseWorkflow.php": "d1a810533a324aea48c6cc7da919de1a5e39657783e726065bfee8a95f06f075",
|
||||
"app/Services/InvoiceWorkflow.php": "c91e55a08af7e12afece7ea5f06c7b4bfe3889a6c4fc6dbbd4751652244d196b",
|
||||
"app/Services/RequisitionWorkflow.php": "272eb6d9aeb1d84c42fe4c30eecdc8fac4e7ac7222c642fe195cfd5bcc64c8b6",
|
||||
"app/Models/Requisition.php": "c78630472d4c3c5a611b7771c8ad6eaf252a627fbf20e221722c5634dc78df77",
|
||||
"app/Http/Controllers/RequisitionController.php": "459110c749a7a6580f1b1dc588f48e3c7254de1ea67e6e8bbe28067982ee05a9",
|
||||
"app/Http/Controllers/PurchaseController.php": "512a3bc6bf911003be5dfebb4f9c1fc0df8fad54eddf78bc075b6cca66ee97fa",
|
||||
"app/Http/Controllers/InvoiceController.php": "0074d72af39afb736adb79d7a3935366ad39ef0d942a5c3a0872bce96e0a92ba",
|
||||
"app/Http/Controllers/PurchaseProcessController.php": "7af5007c5945a29b34728f6f799e18ea33e9ce5a2b4e1a59c6da4f3cdc73e1c6",
|
||||
"config/budget-distributions.php": "f46b83c722d96e98b13dc0fc9823d2b1d89cd4ccb90f3e7570d1889aa6cb1cb5",
|
||||
"config/common-budget.php": "032d8fcfef069857eae2ffa31eb08ccc171d313c1c7dc4afde9c02286c59ddf0",
|
||||
"routes/web.php": "4f75732246504d88acb96f004ed7dc5dceb32103fddd464c36edc85c9f8e7098",
|
||||
"docs/proofs/rq01-distribution-artifact.json": "f21dfbc9cc4344abec88953bc3fc2b7f5751fba401ab52f0da950ae0715816e5",
|
||||
"storage/framework/testing/budget-distribution-qa-ef60dd86bf71ec79/bootstrap.php": "09feb353274c100596a122aaa6251ab042a39ecdc517b23755154fb33b7987d7",
|
||||
"storage/framework/testing/budget-distribution-qa-ef60dd86bf71ec79/src/BudgetContext.php": "200b23fa560cc967bf6c9ccc1387ee9fefd9933f965811f8a4a0ab5f74f12e04",
|
||||
"storage/framework/testing/budget-distribution-qa-ef60dd86bf71ec79/src/BudgetFailure.php": "30ec4c7a5b45e5980ca517d167aa45e89f22a3429c76365fa1c1a94db5f4d8e0",
|
||||
"storage/framework/testing/budget-distribution-qa-ef60dd86bf71ec79/src/BudgetControl.php": "3019358664e21f6ae75b589fec577f4fc16da1f3b2257eefc2840b143ce988c8",
|
||||
"storage/framework/testing/budget-distribution-qa-ef60dd86bf71ec79/src/BudgetDistributionPlan.php": "ed42ce7c3ffb789c9b0deb39a880ddd8bb3e5c63d8a14d9871dba73fe8c00acd",
|
||||
"storage/framework/testing/budget-distribution-qa-ef60dd86bf71ec79/src/BudgetDistributions.php": "7f963593b2d0b45f89261d90fff384805aa24df2132997f97477b6ca7082f21b",
|
||||
"storage/framework/testing/budget-distribution-qa-ef60dd86bf71ec79/README.md": "24363f762ba5ba361377ff3807704bf6143c4180919bc1c45ac6cdd54eed3639"
|
||||
},
|
||||
"private_settings_changes": {
|
||||
"COMMON_BUDGET_PATH": "Selected independent SGC release directory; original pinned package preserved",
|
||||
"SGC_BUDGET_DISTRIBUTIONS_ENABLED": "true",
|
||||
"SGC_BUDGET_DISTRIBUTIONS_MANIFEST": "Frozen manifest inside the selected release",
|
||||
"SGC_BUDGET_DISTRIBUTIONS_MANIFEST_SHA256": "Exact artifact_manifest_sha256 above"
|
||||
},
|
||||
"verification": {
|
||||
"native_visual": "rq01-distribution-visual.json",
|
||||
"financial_qa": "rq01-distribution-qa.json",
|
||||
"same_role_pilot_restore": "rq01-distribution-pilot-preparation.json",
|
||||
"runtime_integrity_log": "storage/logs/budget-distribution-release-integrity.txt",
|
||||
"postgres_schema_and_contract_log": "storage/logs/budget-distribution-deployment-schema-pg.txt"
|
||||
},
|
||||
"execution": [
|
||||
"Exact separate approval bound to this proposal SHA-256",
|
||||
"Fresh consistent backup and same-role restore before applying",
|
||||
"Recheck pilot data and configuration under locks; refuse intervening changes",
|
||||
"Apply only the staged migration, preserve all previous columns/data/FKs",
|
||||
"Verify separately copied release and all asset bytes before switching manifest and four settings",
|
||||
"Confirm named pilot HTTP and effective capability without business commands"
|
||||
],
|
||||
"recovery": [
|
||||
"Before use: previous settings and manifest preserved privately; new empty schema can remain",
|
||||
"After distribution use: retain compatible runtime and append-only history; never select old runtime or restore a backup automatically",
|
||||
"Any restore affecting later operations requires a separate reviewed decision"
|
||||
],
|
||||
"excluded": [
|
||||
"Real business operations, budgets, commitments, invoices, payments or accounting commands",
|
||||
"Changes to roles or grants",
|
||||
"SGF deployment or activation",
|
||||
"Replacing published or pinned financial packages",
|
||||
"MFA, inventory conversions, per-order limits, People formalisation",
|
||||
"Production publication and enterprise acceptance"
|
||||
]
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"date": "2026-11-22",
|
||||
"status": "implemented_and_verified_in_isolated_qa_unpublished",
|
||||
"status": "implemented_qa_verified_and_installed_in_named_pilot",
|
||||
"authorizations": [
|
||||
"rq01-distribution-contract-authorization.json",
|
||||
"rq01-distribution-fx-decision.json"
|
||||
@@ -108,7 +108,8 @@
|
||||
"status": "passed",
|
||||
"path": "storage/framework/testing/sgc-distribution-integrated-qa-20261122",
|
||||
"manifest_sha256": "1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e",
|
||||
"published": false
|
||||
"published": false,
|
||||
"installed_in_named_pilot": true
|
||||
},
|
||||
"broad_postgres_attempt": "Timed out after 180 seconds; not approved. Subsequently split into the two focused groups above without increasing timeout.",
|
||||
"legacy_runtime_recovery_guard": {
|
||||
@@ -116,6 +117,40 @@
|
||||
"assertions": 134,
|
||||
"log": "storage/logs/budget-distribution-legacy-guard-final.txt",
|
||||
"partial_schema_and_orphan_effects_refused": true
|
||||
},
|
||||
"deployment_preparation": {
|
||||
"runtime_integrity": {
|
||||
"passed": 8,
|
||||
"assertions": 20,
|
||||
"log": "storage/logs/budget-distribution-release-integrity.txt"
|
||||
},
|
||||
"standalone_composition": {
|
||||
"passed": 18,
|
||||
"assertions": 152,
|
||||
"log": "storage/logs/budget-distribution-release-composition.txt"
|
||||
},
|
||||
"postgres_schema_and_contract": {
|
||||
"passed": 24,
|
||||
"assertions": 180,
|
||||
"isolated_database_removed": true,
|
||||
"log": "storage/logs/budget-distribution-deployment-schema-pg.txt"
|
||||
},
|
||||
"default_runtime": {
|
||||
"passed": 15,
|
||||
"skipped": 1,
|
||||
"assertions": 49,
|
||||
"log": "storage/logs/budget-distribution-deployment-default.txt"
|
||||
},
|
||||
"pilot_restore_rehearsal": "rq01-distribution-pilot-preparation.json",
|
||||
"proposal": "rq01-distribution-pilot-proposal.json",
|
||||
"capability_enabled": true,
|
||||
"installation_executed": true,
|
||||
"post_install_http": {
|
||||
"passed": 8,
|
||||
"business_commands": false,
|
||||
"proof": "rq01-distribution-pilot-http.json"
|
||||
},
|
||||
"installation_proof": "rq01-distribution-pilot-installation.json"
|
||||
}
|
||||
},
|
||||
"own_corrections": [
|
||||
@@ -129,13 +164,12 @@
|
||||
"An incompatible runtime refuses any partial optional schema or remaining optional effects, including loss of the source table; regression tests passed."
|
||||
],
|
||||
"pending": [
|
||||
"Concrete operational installation/activation proposal and specific authorisation",
|
||||
"Remaining SGC requirements and enterprise acceptance"
|
||||
"Remaining SGC requirements, transverse review, commercial operation and enterprise acceptance"
|
||||
],
|
||||
"limits": [
|
||||
"No pinned financial package edits",
|
||||
"No pilot or SGF activation",
|
||||
"No real data, grants, payments or accounting operations",
|
||||
"No original pinned financial package edits",
|
||||
"Only the specifically authorised SGC pilot installation; no SGF activation",
|
||||
"No business operations, grants, payments or accounting commands",
|
||||
"No claim of complete SGC delivery"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
{
|
||||
"date": "2026-11-22",
|
||||
"status": "updated_owner_specification_reconciled_not_a_complete_import_delivery",
|
||||
"source": "c:\\Mac\\Home\\Documents\\TEMPO\\Portal Tempo\\Servicos Tempo\\Compras\\A requisção de insumos de produção.docx",
|
||||
"source_sha256": "9646630ac9b7e08cf84f3e93efc6cf1a90657cdc3e59d680621b74238d3a7408",
|
||||
"previous_approved_source_sha256": "ba08b3a713f2e62fb274dacad2a8f76618eb8f11d01db2dbe7cf4b521dff1c5b",
|
||||
"paragraphs": 567,
|
||||
"embedded_documents": 0,
|
||||
"read_method": "Shared read-only stream because the source is open in another application; original unchanged",
|
||||
"owner_message": "New SGC functionality includes goods imports described in this attachment",
|
||||
"source_role": "Updated functional specification; legal summaries, proposed roles, alerts, timeframes and external procedures are not executable authorization or verified live integrations",
|
||||
"existing_implementation": {
|
||||
"files": [
|
||||
"app/Services/SupplyPlanning.php",
|
||||
"app/Services/ReceiptWorkflow.php",
|
||||
"resources/js/pages/supply/index.tsx"
|
||||
],
|
||||
"capabilities": [
|
||||
"One versioned import preparation per purchase order",
|
||||
"Purpose, jurisdiction, origin/dispatch countries, optional Incoterm, customs regime and expected usable date",
|
||||
"Transit, arrival, hold and independent release with dated evidence and existing import permissions",
|
||||
"Native receipt remains blocked until recorded customs release; arrival alone is not usable stock"
|
||||
],
|
||||
"test_reference": "tests/Feature/SupplyPlanningTest.php: import tracking cannot bypass permissions create duplicate orders or make arrived goods usable",
|
||||
"verification_this_reconciliation": "Source and code inspected; no new import execution or test run claimed"
|
||||
},
|
||||
"new_requirements": [
|
||||
{
|
||||
"section": "10.1-10.2",
|
||||
"requirement": "Tariff code per imported item in material master/requisition, proposed classification, buyer confirmation or justified deviation",
|
||||
"state": "not covered by existing import metadata"
|
||||
},
|
||||
{
|
||||
"section": "10.1,10.4",
|
||||
"requirement": "Versioned landed-cost estimate with goods, freight, insurance, duties, taxes and customs expenses; native budget/approval basis and explicit actual-cost changes",
|
||||
"state": "requires economic/budget reconciliation; no new financial authority implemented"
|
||||
},
|
||||
{
|
||||
"section": "10.2-10.3",
|
||||
"requirement": "Selected broker/forwarder, written instructions and reusable shipment/customs document dossier linked to purchase and receipt",
|
||||
"state": "existing evidence text does not demonstrate typed document coverage"
|
||||
},
|
||||
{
|
||||
"section": "9,10.4",
|
||||
"requirement": "Related-party/conflict controls for supplier, broker and forwarder; preserve segregation, justified replacement and history",
|
||||
"state": "native supplier/process controls exist; broker/forwarder coverage not demonstrated"
|
||||
},
|
||||
{
|
||||
"section": "10.2-10.4",
|
||||
"requirement": "Record JUE declaration, unique document, customs assessment, documentary payment/release evidence and receipt lineage without duplicate stock movement",
|
||||
"state": "logistical states exist; external JUE integration and full documentary workflow not implemented by this record"
|
||||
},
|
||||
{
|
||||
"section": "10.4,10.7",
|
||||
"requirement": "Foreign-bank documentary commitment and support-document tracking; no inferred bank execution or card policy activation",
|
||||
"state": "new import-specific documentary requirements; rules and financial integration require concrete reconciliation"
|
||||
},
|
||||
{
|
||||
"section": "10.6-10.7",
|
||||
"requirement": "Versioned official tariff/legal/sector/origin/ICE rules, periods, sources, confirmed buyer suggestions and justified deviations",
|
||||
"state": "functional scope recorded; no customs rates, exemptions or legal validity certified from the Word summary"
|
||||
},
|
||||
{
|
||||
"section": "10.8",
|
||||
"requirement": "Contextual missing-code/licence/document, cost/budget, payment-support, arrival/deadline, legal-change and pending-approval alerts",
|
||||
"state": "reconcile with native task/help channels; organization deadlines and recipients must remain explicitly configured"
|
||||
},
|
||||
{
|
||||
"section": "10.4",
|
||||
"requirement": "Preserve customs originals, versions and audit evidence",
|
||||
"state": "existing owner decision of integral preservation without automatic deletion remains in force"
|
||||
}
|
||||
],
|
||||
"preserved": [
|
||||
"No changes to source Word file",
|
||||
"Existing logistics and single native inventory writer",
|
||||
"Frozen exchange-rate decisions and financial/product boundaries",
|
||||
"Installed pilot release, real data and permissions",
|
||||
"No JUE submission, bank payment, legal-rate activation or operational installation"
|
||||
],
|
||||
"tracking": "Existing reconciled matrix and delivery/continuity documents only; no parallel backlog"
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"date": "2026-11-22",
|
||||
"status": "approved_for_development_and_isolated_qa_only",
|
||||
"owner_response": "autorizo",
|
||||
"proposal": "rq01-multi-order-contract-proposal.json",
|
||||
"proposal_sha256": "945feac2a4f5772edb90fb3533f9f782d17aeef3f40c93aef048a6dd1f3a2fe0",
|
||||
"scope": "Optional multi-order and multi-origin common financial contract and SGC host adaptation as specified in the proposal",
|
||||
"excluded": [
|
||||
"Installed/published artifacts",
|
||||
"Pilot or SGF installation/activation",
|
||||
"Real business data, permissions, budgets, payments and accounting postings"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
{
|
||||
"date": "2026-11-22",
|
||||
"status": "prepared_awaiting_specific_qa_contract_authorization",
|
||||
"purpose": "RQ-01 approved requisition line splitting and consolidation into purchase orders, with native budget lineage",
|
||||
"existing_authorization": "rq01-distribution-contract-authorization.json covers explicit line/centre distributions; the installed V1 pilot release remains preserved",
|
||||
"evidence": {
|
||||
"common_source": "C:\\laragon\\www\\sgf-tempo\\packages\\budget-control\\src\\BudgetDistributions.php",
|
||||
"common_source_sha256": "7f963593b2d0b45f89261d90fff384805aa24df2132997f97477b6ca7082f21b",
|
||||
"current_constraint": "recordDistribution commits a whole single-origin plan; purchase_orders uniquely references requisition_id and purchase_award_id; invoices and native budget consumption each reference one purchase order/invoice",
|
||||
"host_schema": [
|
||||
"database/migrations/2026_10_28_000005_create_purchase_awards_and_orders.php",
|
||||
"database/migrations/2026_10_28_000010_create_invoices.php"
|
||||
]
|
||||
},
|
||||
"requested_scope": [
|
||||
"Extend only the canonical common budget source in SGF and the SGC adaptation in isolated development/QA; no second financial engine",
|
||||
"Introduce an optional separately negotiated capability while preserving V1 methods, data and installed artifact",
|
||||
"Track original requisition/line, approved supplier award, issued order part and invoice allocation by stable identity and version",
|
||||
"Commit only issued quantities/amounts; preserve the unissued reservation and cap cumulative quantities and native amounts",
|
||||
"Consolidate compatible approved origins for the same company, supplier and document currency without bypassing award decisions",
|
||||
"Keep one native invoice and one payable principal; atomically consume allocated commitments across authorized origins",
|
||||
"Preserve original explicit frozen exchange rates and native cumulative rounding; use already approved explicit Finance allocation/versioned amendments without automatic compensation",
|
||||
"Keep current document access and cancellation policy; do not duplicate documents, auto-reopen processes or release unrelated balances",
|
||||
"Preserve legacy records and fail closed on unsupported capability; no silent downgrade after new effects exist"
|
||||
],
|
||||
"illustrative_synthetic_acceptance": [
|
||||
{
|
||||
"scenario": "100 MZN requisition split into 40 and 60 MZN orders",
|
||||
"after_first": {
|
||||
"reserved": 60,
|
||||
"committed": 40
|
||||
},
|
||||
"after_second": {
|
||||
"reserved": 0,
|
||||
"committed": 100
|
||||
},
|
||||
"replay": "No duplicate financial effect"
|
||||
},
|
||||
{
|
||||
"scenario": "Approved origins of 100 and 200 MZN consolidated into one 300 MZN order",
|
||||
"invoice": {
|
||||
"principal": 150,
|
||||
"origin_consumptions": [
|
||||
50,
|
||||
100
|
||||
],
|
||||
"remaining_commitment": 150
|
||||
},
|
||||
"failure": "Any invalid source, authorization or balance rejects the entire operation"
|
||||
},
|
||||
{
|
||||
"scenario": "100 USD at frozen rate 64 and 100 USD at frozen rate 65",
|
||||
"document_usd": 200,
|
||||
"original_mzn_references": 12900,
|
||||
"rule": "Preserve both source rates; do not create an averaged exchange rate"
|
||||
}
|
||||
],
|
||||
"required_verification": [
|
||||
"Native end-to-end split/consolidation/receipt/invoice lineage",
|
||||
"Quantity and monetary limits, explicit FX allocation, authorization and isolation failures",
|
||||
"Real isolated PostgreSQL atomicity, concurrency, operation replay and stale versions",
|
||||
"V1 and legacy regression; same-role backup/restore in disposable QA",
|
||||
"Mobile, print and contextual help for affected journeys before any operational proposal"
|
||||
],
|
||||
"excluded": [
|
||||
"Published or installed financial artifacts, including the current V1 pilot release",
|
||||
"Pilot or SGF migration, installation or activation",
|
||||
"Real business data, permissions, budgets, payments or accounting postings",
|
||||
"Automatic Finance reallocations, invented exchange rates or relaxed supplier/approval/cancellation controls"
|
||||
],
|
||||
"later_deployment": "Requires a separate concrete proposal, compatibility evidence, backup/restore and specific target authorization"
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
{
|
||||
"date": "2026-11-22",
|
||||
"status": "financial_contract_and_native_preparation_verified_in_qa_full_journey_in_progress",
|
||||
"authorization": "rq01-multi-order-contract-authorization.json",
|
||||
"authorization_required_for_remaining_qa_work": false,
|
||||
"implementation": {
|
||||
"capability": "COMMON-BUDGET-ORDER-PARTS-QA-v1",
|
||||
"v1_version_and_distribution_capability_preserved": true,
|
||||
"common_source": "C:\\laragon\\www\\sgf-tempo\\packages\\budget-control",
|
||||
"source_files": {
|
||||
"bootstrap.php": "88e4681e21ef315e156a63fd435419b4a6838ecbed552c39e1c65aa856a98dd5",
|
||||
"src/BudgetControl.php": "6c4d043fb505622649e03cca510f7027cdb511e713c43c9a6ac4447661c3f9ee",
|
||||
"src/BudgetDistributions.php": "187235f0804fe8e9602a9cdb3e4d0c945eba873903e5eacee26c1847728c03f4",
|
||||
"src/BudgetOrderParts.php": "13ffdce6dc35790f19132f1f8e3763470b9d7d4b44af64be47693058dad00998",
|
||||
"README.md": "9b5bc14f029d0b41ff787c2446428999e5c72bfe92e0d5acc1578c26bfd759bb"
|
||||
},
|
||||
"common_commands": [
|
||||
"adoptOrderSource",
|
||||
"commitOrderParts",
|
||||
"checkOrderPartsConsumption",
|
||||
"consumeOrderParts",
|
||||
"cancelOrderParts"
|
||||
],
|
||||
"host": [
|
||||
"app/Services/CommonBudget.php",
|
||||
"app/Services/OrderPartsPreparation.php",
|
||||
"app/Services/PurchaseWorkflow.php",
|
||||
"app/Services/PurchaseLineAmounts.php",
|
||||
"app/Services/InvoiceWorkflow.php"
|
||||
],
|
||||
"qa_schema": "database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php",
|
||||
"schema_installation": "Only guarded in-memory SQLite or disposable local PostgreSQL QA; outside normal/deployment migrations",
|
||||
"native_preparation": "Reuses native award approvals, comparison, conflicts, supplier and visibility checks; preserves source terms, currency and frozen rate separately; validates quantities and original cumulative price/VAT offsets; emits no order, reserve or audit",
|
||||
"technical_envelope_limits": {
|
||||
"origin": "implementation_choice_for_bounded_command_payloads_not_company_policy",
|
||||
"sources": 100,
|
||||
"allocations_per_source": 500
|
||||
}
|
||||
},
|
||||
"verification": {
|
||||
"sqlite_integrated": {
|
||||
"passed": 48,
|
||||
"skipped": 1,
|
||||
"assertions": 296,
|
||||
"skip": "PostgreSQL immutable-history trigger case is executed in PostgreSQL",
|
||||
"log": "storage/logs/order-parts-native-sqlite.txt"
|
||||
},
|
||||
"postgres_integrated": {
|
||||
"passed": 49,
|
||||
"assertions": 312,
|
||||
"log": "storage/logs/order-parts-native-pg.txt",
|
||||
"isolated_database_removed": true
|
||||
},
|
||||
"v1_legacy_regression_before_final_new_only_additions": {
|
||||
"passed": 70,
|
||||
"assertions": 380,
|
||||
"engines": [
|
||||
"SQLite",
|
||||
"PostgreSQL"
|
||||
],
|
||||
"logs": [
|
||||
"storage/logs/budget-order-parts-regression.txt",
|
||||
"storage/logs/budget-order-parts-pg.txt"
|
||||
],
|
||||
"note": "The later PostgreSQL regression log contains 74/418 after adoption/schema cases; counts overlap and must not be added"
|
||||
},
|
||||
"concurrency": {
|
||||
"same_operation_statuses": [
|
||||
200,
|
||||
200
|
||||
],
|
||||
"conflicting_version_statuses": [
|
||||
200,
|
||||
409
|
||||
],
|
||||
"one_command_and_audit": true,
|
||||
"two_blocked_writers_observed": true,
|
||||
"old_runtime_rejected_before_balance": 503,
|
||||
"log": "storage/logs/budget-order-parts-concurrency.txt",
|
||||
"isolated_database_removed": true
|
||||
},
|
||||
"recovery": {
|
||||
"previous_tables_preserved": 115,
|
||||
"optional_tables": 8,
|
||||
"post_extension_all_tables_equal": true,
|
||||
"recovered_command_replay_no_effects": true,
|
||||
"pre_extension_schema_data_balance_restored": true,
|
||||
"before_dump_sha256": "69f1ba31e8699cf6fd291b401edd3fcc15503374dd65938f2dbae3b1e798dd97",
|
||||
"after_dump_sha256": "ba9d4019f6b68e477c77cd39caef29824273a807b6b8cd7e0456e86e7f9cd129",
|
||||
"log": "storage/logs/budget-order-parts-recovery.txt",
|
||||
"source_and_restore_databases_removed": true
|
||||
},
|
||||
"phpstan": "passed_zero_errors",
|
||||
"php_syntax": "Four modified common PHP files passed through the documented SGF wrapper",
|
||||
"format_and_diff": "Scoped Pint and whitespace checks passed",
|
||||
"native_visual": "Not claimed for the new order-parts journey"
|
||||
},
|
||||
"own_fixture_correction": "Financial-source fixtures now create a separate unissued requisition with an actual matching line and consistent totals instead of reusing a reception fixture already linked to an order; adoption regression asserts that no native order exists. Contract-only invoice placeholders remain explicitly identified and are not native multi-origin issuance/payable proof.",
|
||||
"preserved": {
|
||||
"pilot_manifest_sha256": "1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e",
|
||||
"installed_v1_artifact_untouched": true,
|
||||
"original_proposal_sha256": "945feac2a4f5772edb90fb3533f9f782d17aeef3f40c93aef048a6dd1f3a2fe0",
|
||||
"no_pilot_or_sgf_installation_activation_real_business_data_or_permissions": true
|
||||
},
|
||||
"remaining_authorized_work": [
|
||||
"Native partial/consolidated order document issuance and complete per-origin visibility/quantity lineage",
|
||||
"Native receipt/invoice/payable integration with exactly one invoice principal",
|
||||
"Explicit Finance amendments across order/source allocations, preserving consumed floors and native totals",
|
||||
"Complete mixed frozen-rate journey without an averaged rate or implicit cent compensation",
|
||||
"Affected forms/help/mobile/print and full journey review before any deployment proposal"
|
||||
],
|
||||
"new_import_dependency": "rq01-import-reconciliation.json records the updated owner attachment. This extension does not create landed-cost financial authority, customs rates, JUE submission or bank execution."
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"date": "2026-11-22",
|
||||
"status": "implemented_and_verified_in_isolated_qa_not_installed_in_pilot",
|
||||
"scope": "Private saved criteria for the existing native procurement search: create, edit, reopen, archive and restore. No cached results, shared searches, subscriptions or permission grants.",
|
||||
"migration": "database/migrations/2026_11_22_000006_create_procurement_saved_searches.php",
|
||||
"implementation": [
|
||||
"Every read/write is scoped to the current user and company; current native access is checked again",
|
||||
"Explicit versions prevent lost edits; duplicate create has one preference",
|
||||
"Archived criteria are retained and paginated; restoration refuses active-name collisions",
|
||||
"Opening always reruns the native live query with current scope and permissions",
|
||||
"Encrypted preparation keys separate company, actor, query, source and version",
|
||||
"Quick reopen selector and collapsible management preserve the prominence of current results"
|
||||
],
|
||||
"implementation_choice": "Capacity of 50 active private searches bounds the interface, with archived criteria retained. This is a technical preference limit, not an organisational approval rule or a financial threshold.",
|
||||
"verification": {
|
||||
"sqlite": {"passed": 14, "assertions": 354, "log": "storage/logs/saved-searches-tests.txt"},
|
||||
"postgres": {"passed": 14, "assertions": 354, "isolated_database_removed": true, "log": "storage/logs/saved-searches-pg.txt"},
|
||||
"frontend": {"passed": 3, "log": "storage/logs/saved-searches-ui-tests.txt"},
|
||||
"types": "passed",
|
||||
"phpstan": "passed_zero_errors",
|
||||
"scoped_lint_format": "passed_no_warnings",
|
||||
"private_build": {"path": "storage/framework/testing/sgc-saved-searches-qa-20261122", "manifest_sha256": "876cd584729a3a6d731bfafe52396c5ce176ad015fe9bea66057791933d23706", "installed_in_pilot": false},
|
||||
"native_edge": {"synthetic_only": true, "mobile_width": 390, "desktop_width": 1000, "height": 525, "zoom": "100%", "create_edit_archive_restore": true, "reopen_from_another_query": true, "old_query_results": 0, "reopened_query_results": 3, "one_preference": true, "version": 4, "criteria_preserved": true, "no_draft_update_reservation_or_invoice": true, "database_verification_log": "storage/logs/saved-searches-visual-data.txt", "final_copy_and_counter_checked_on_desktop": true, "private_server_stopped": true, "isolated_database_removed": true, "private_settings_absent": true, "original_pilot_finance_context_restored": true}
|
||||
},
|
||||
"own_corrections": [
|
||||
"The test for withdrawn authority now uses the native Configured role without assigned authority. User security fields remain protected from mass assignment and the NOT NULL constraint remains enforced.",
|
||||
"Inertia form transforms are applied before submission rather than chained through their void return; types and native create/edit/archive/restore passed.",
|
||||
"Correct singular/plural counter and wrapping of long names; the final private candidate was checked without publishing pilot assets."
|
||||
],
|
||||
"limits": ["No pilot migration or asset installation", "No user or company sharing", "No saved financial results or document content", "No complete SGC or enterprise acceptance claim"],
|
||||
"remaining": ["Operational rollout in a separately approved release", "Remaining global-search sources and analytics reconciliation"]
|
||||
}
|
||||
@@ -8,6 +8,7 @@ type SavedLevel = {
|
||||
scope: 'company' | 'department';
|
||||
min_minor: number | null;
|
||||
categories: string[];
|
||||
procurement_categories?: string[];
|
||||
cost_center_ids: number[];
|
||||
};
|
||||
export type RequisitionApprovalPlan = {
|
||||
@@ -28,6 +29,7 @@ const newLevel = () => ({
|
||||
scope: 'department' as 'company' | 'department',
|
||||
min_amount: '',
|
||||
categories_text: '',
|
||||
procurement_categories: [] as string[],
|
||||
cost_center_ids: [] as number[],
|
||||
});
|
||||
|
||||
@@ -37,12 +39,14 @@ export function RequisitionApprovalSettings({
|
||||
profiles,
|
||||
costCenters,
|
||||
version,
|
||||
categoryOptions = {},
|
||||
}: {
|
||||
plan?: RequisitionApprovalPlan | null;
|
||||
ready: boolean;
|
||||
profiles: Profile[];
|
||||
costCenters: { id: number; code: string; name: string }[];
|
||||
version: number;
|
||||
categoryOptions?: Record<string, string>;
|
||||
}) {
|
||||
const form = useForm({
|
||||
version,
|
||||
@@ -55,6 +59,7 @@ export function RequisitionApprovalSettings({
|
||||
scope: level.scope,
|
||||
min_amount: amountInput(level.min_minor),
|
||||
categories_text: level.categories.join('\n'),
|
||||
procurement_categories: level.procurement_categories ?? [],
|
||||
cost_center_ids: level.cost_center_ids,
|
||||
})) ?? [],
|
||||
});
|
||||
@@ -100,6 +105,8 @@ export function RequisitionApprovalSettings({
|
||||
.map((value) => value.trim())
|
||||
.filter(Boolean),
|
||||
cost_center_ids: level.cost_center_ids,
|
||||
procurement_categories:
|
||||
level.procurement_categories,
|
||||
})),
|
||||
}));
|
||||
form.post(
|
||||
@@ -210,7 +217,8 @@ export function RequisitionApprovalSettings({
|
||||
className="grid gap-2 text-sm"
|
||||
htmlFor={`approval-categories-${index}`}
|
||||
>
|
||||
Categorias exactas (opcional, uma por linha)
|
||||
Categorias exactas do artigo (opcional, uma
|
||||
por linha)
|
||||
<textarea
|
||||
id={`approval-categories-${index}`}
|
||||
className={controlClass}
|
||||
@@ -224,6 +232,58 @@ export function RequisitionApprovalSettings({
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
{Object.keys(categoryOptions).length > 0 && (
|
||||
<fieldset className="space-y-2 rounded-lg border p-4">
|
||||
<legend className="text-sm font-medium">
|
||||
Categoria da necessidade (RQ-01)
|
||||
</legend>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Sem selecção, esta condição não
|
||||
restringe o nível. As categorias
|
||||
seleccionadas exigem classificação
|
||||
explícita e combinam-se com o valor, a
|
||||
categoria do artigo e o centro de custo.
|
||||
Os pedidos anteriores não são
|
||||
classificados automaticamente.
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-4">
|
||||
{Object.entries(categoryOptions).map(
|
||||
([value, label]) => (
|
||||
<label
|
||||
key={value}
|
||||
className="flex items-center gap-2 text-sm"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={level.procurement_categories.includes(
|
||||
value,
|
||||
)}
|
||||
onChange={(event) =>
|
||||
change(index, {
|
||||
procurement_categories:
|
||||
event.target
|
||||
.checked
|
||||
? [
|
||||
...level.procurement_categories,
|
||||
value,
|
||||
]
|
||||
: level.procurement_categories.filter(
|
||||
(
|
||||
item,
|
||||
) =>
|
||||
item !==
|
||||
value,
|
||||
),
|
||||
})
|
||||
}
|
||||
/>
|
||||
{label}
|
||||
</label>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
</fieldset>
|
||||
)}
|
||||
<fieldset className="space-y-2">
|
||||
<legend className="text-sm font-medium">
|
||||
Perfis elegíveis — basta um aprovador
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import { controlClass } from '@/components/procurement';
|
||||
|
||||
export const requisitionCategoryLabels: Record<string, string> = {
|
||||
production_input: 'Insumos de produção',
|
||||
spare_part: 'Peças sobressalentes',
|
||||
capital_equipment: 'Maquinaria',
|
||||
office_equipment: 'Equipamento de escritório',
|
||||
other: 'Outra categoria',
|
||||
};
|
||||
|
||||
const guidance: Record<string, string> = {
|
||||
production_input:
|
||||
'Seleccione um material de stock no catálogo publicado. A categoria original do artigo é conservada.',
|
||||
spare_part:
|
||||
'Seleccione o tipo Peça e associe a peça ao equipamento. Os controlos de stock e criticidade existentes mantêm-se.',
|
||||
capital_equipment:
|
||||
'Seleccione o tipo Equipamento e justifique o investimento. Mantêm-se a validação técnica, Finanças e o orçamento de investimento.',
|
||||
office_equipment:
|
||||
'Prefira um artigo do catálogo; se usar texto livre, explique a necessidade.',
|
||||
other: 'Identifique a categoria do artigo e justifique o uso de texto livre quando não existir selecção do catálogo.',
|
||||
};
|
||||
|
||||
export function RequisitionCategoryFields({
|
||||
index,
|
||||
category,
|
||||
reason,
|
||||
options,
|
||||
onChange,
|
||||
}: {
|
||||
index: number;
|
||||
category: string;
|
||||
reason: string;
|
||||
options: Record<string, string>;
|
||||
onChange: (
|
||||
field: 'procurement_category' | 'category_reason',
|
||||
value: string,
|
||||
) => void;
|
||||
}) {
|
||||
const prefix = `rq-category-${index}`;
|
||||
return (
|
||||
<div className="grid gap-3 rounded-lg border p-4 sm:col-span-3">
|
||||
<label className="grid gap-2 text-sm" htmlFor={prefix}>
|
||||
Categoria da necessidade
|
||||
<select
|
||||
id={prefix}
|
||||
className={controlClass}
|
||||
value={category}
|
||||
aria-describedby={`${prefix}-help`}
|
||||
onChange={(event) =>
|
||||
onChange('procurement_category', event.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Sem classificação adicional</option>
|
||||
{Object.entries(options).map(([value, label]) => (
|
||||
<option key={value} value={value}>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<p id={`${prefix}-help`} className="text-sm text-muted-foreground">
|
||||
{(!category && reason
|
||||
? 'Seleccione a categoria para este motivo ou limpe-o se não quiser classificação adicional.'
|
||||
: guidance[category]) ??
|
||||
'Conserva a categoria original do artigo. Uma classificação anterior não é inferida nem alterada automaticamente.'}
|
||||
</p>
|
||||
{(category || reason) && (
|
||||
<label
|
||||
className="grid gap-2 text-sm"
|
||||
htmlFor={`${prefix}-reason`}
|
||||
>
|
||||
{category === 'capital_equipment'
|
||||
? 'Justificação do investimento'
|
||||
: 'Justificação da categoria ou do texto livre'}
|
||||
<textarea
|
||||
id={`${prefix}-reason`}
|
||||
className={controlClass}
|
||||
maxLength={2000}
|
||||
value={reason}
|
||||
onChange={(event) =>
|
||||
onChange('category_reason', event.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
import { Link, router, useForm, usePage, useRemember } from '@inertiajs/react';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { FormErrors, Panel, controlClass } from '@/components/procurement';
|
||||
|
||||
type SavedSearch = {
|
||||
id: number;
|
||||
name: string;
|
||||
term: string;
|
||||
version: number;
|
||||
href: string;
|
||||
};
|
||||
export type SavedSearches = {
|
||||
max_active: number;
|
||||
active: SavedSearch[];
|
||||
archived: {
|
||||
data: SavedSearch[];
|
||||
total: number;
|
||||
prev_page_url: string | null;
|
||||
next_page_url: string | null;
|
||||
};
|
||||
};
|
||||
|
||||
function usePrivatePreparation(dirty: boolean) {
|
||||
const ref = useRef<HTMLFormElement>(null);
|
||||
useEffect(() => {
|
||||
const form = ref.current;
|
||||
window.dispatchEvent(
|
||||
new CustomEvent('sgc:context-dirty', { detail: { form, dirty } }),
|
||||
);
|
||||
return () => {
|
||||
window.dispatchEvent(
|
||||
new CustomEvent('sgc:context-dirty', {
|
||||
detail: { form, dirty: false },
|
||||
}),
|
||||
);
|
||||
};
|
||||
}, [dirty]);
|
||||
return ref;
|
||||
}
|
||||
|
||||
function SavedSearchRow({
|
||||
row,
|
||||
term,
|
||||
archived = false,
|
||||
}: {
|
||||
row: SavedSearch;
|
||||
term: string;
|
||||
archived?: boolean;
|
||||
}) {
|
||||
const actor = usePage().props.auth?.user;
|
||||
const historyKey = `saved-search-edit:${actor?.tenant_id ?? 'none'}:${actor?.id ?? 'none'}:${row.id}:${row.version}`;
|
||||
const [editing, setEditing] = useRemember(false, `${historyKey}:editing`);
|
||||
const edit = useForm(historyKey, {
|
||||
name: row.name,
|
||||
term: row.term,
|
||||
version: row.version,
|
||||
q: term,
|
||||
});
|
||||
const action = useForm({ version: row.version, q: term });
|
||||
const ref = usePrivatePreparation(editing && edit.isDirty);
|
||||
const endpoint = `/compras/pesquisas-guardadas/${row.id}`;
|
||||
return (
|
||||
<li className="grid min-w-0 grid-cols-1 gap-3 border-b py-4 last:border-0">
|
||||
{editing ? (
|
||||
<form
|
||||
ref={ref}
|
||||
className="grid gap-3"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
edit.transform((data) => ({ ...data, q: term }));
|
||||
edit.put(endpoint, {
|
||||
preserveScroll: true,
|
||||
onSuccess: () => setEditing(false),
|
||||
});
|
||||
}}
|
||||
>
|
||||
<label className="grid gap-2 text-sm">
|
||||
Nome da pesquisa
|
||||
<input
|
||||
className={controlClass}
|
||||
value={edit.data.name}
|
||||
maxLength={100}
|
||||
required
|
||||
onChange={(event) =>
|
||||
edit.setData('name', event.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="grid gap-2 text-sm">
|
||||
Texto a procurar
|
||||
<input
|
||||
className={controlClass}
|
||||
value={edit.data.term}
|
||||
minLength={2}
|
||||
maxLength={100}
|
||||
required
|
||||
onChange={(event) =>
|
||||
edit.setData('term', event.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<FormErrors errors={edit.errors} />
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button disabled={edit.processing}>
|
||||
Guardar alterações
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
edit.reset();
|
||||
setEditing(false);
|
||||
}}
|
||||
>
|
||||
Cancelar edição
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
) : (
|
||||
<>
|
||||
{archived ? (
|
||||
<p className="font-medium break-words">{row.name}</p>
|
||||
) : (
|
||||
<Link
|
||||
className="font-medium break-words underline"
|
||||
href={row.href}
|
||||
>
|
||||
{row.name}
|
||||
</Link>
|
||||
)}
|
||||
<p className="text-sm break-words text-muted-foreground">
|
||||
Critério: {row.term}
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{!archived && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => setEditing(true)}
|
||||
aria-label={`Editar pesquisa ${row.name}`}
|
||||
>
|
||||
Editar
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={action.processing}
|
||||
aria-label={`${archived ? 'Restaurar' : 'Arquivar'} pesquisa ${row.name}`}
|
||||
onClick={() => {
|
||||
action.transform((data) => ({
|
||||
...data,
|
||||
q: term,
|
||||
}));
|
||||
action.post(
|
||||
`${endpoint}/${archived ? 'restaurar' : 'arquivar'}`,
|
||||
{ preserveScroll: true },
|
||||
);
|
||||
}}
|
||||
>
|
||||
{archived ? 'Restaurar' : 'Arquivar'}
|
||||
</Button>
|
||||
</div>
|
||||
<FormErrors errors={action.errors} />
|
||||
</>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
export function SavedProcurementSearches({
|
||||
saved,
|
||||
term,
|
||||
}: {
|
||||
saved: SavedSearches;
|
||||
term: string;
|
||||
}) {
|
||||
const actor = usePage().props.auth?.user;
|
||||
const [managing, setManaging] = useRemember(
|
||||
false,
|
||||
`saved-search-management:${actor?.tenant_id ?? 'none'}:${actor?.id ?? 'none'}`,
|
||||
);
|
||||
const create = useForm(
|
||||
`saved-search:${actor?.tenant_id ?? 'none'}:${actor?.id ?? 'none'}:${term}`,
|
||||
{ name: '', term, q: term },
|
||||
);
|
||||
const ref = usePrivatePreparation(create.data.name !== '');
|
||||
return (
|
||||
<Panel title="As minhas pesquisas guardadas">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Guarde apenas os critérios. Ao reabrir, os resultados são
|
||||
consultados de novo com o seu acesso actual. Estas pesquisas são
|
||||
privadas; arquivar conserva os critérios e permite restaurá-los.
|
||||
</p>
|
||||
<label
|
||||
className="my-4 grid gap-2 text-sm"
|
||||
htmlFor="saved-search-open"
|
||||
>
|
||||
Reabrir uma pesquisa
|
||||
<select
|
||||
id="saved-search-open"
|
||||
className={controlClass}
|
||||
value=""
|
||||
disabled={saved.active.length === 0}
|
||||
onChange={(event) => {
|
||||
const row = saved.active.find(
|
||||
(item) => String(item.id) === event.target.value,
|
||||
);
|
||||
if (row) router.get(row.href);
|
||||
}}
|
||||
>
|
||||
<option value="">Seleccione uma pesquisa guardada</option>
|
||||
{saved.active.map((row) => (
|
||||
<option key={row.id} value={row.id}>
|
||||
{row.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<details
|
||||
open={managing}
|
||||
onToggle={(event) => setManaging(event.currentTarget.open)}
|
||||
className="rounded-lg border p-4"
|
||||
>
|
||||
<summary className="cursor-pointer">
|
||||
Guardar, editar ou arquivar pesquisas
|
||||
</summary>
|
||||
<form
|
||||
ref={ref}
|
||||
className="my-4 grid gap-3"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
create.transform((data) => ({
|
||||
...data,
|
||||
term,
|
||||
q: term,
|
||||
}));
|
||||
create.post('/compras/pesquisas-guardadas', {
|
||||
preserveScroll: true,
|
||||
onSuccess: () => create.reset('name'),
|
||||
});
|
||||
}}
|
||||
>
|
||||
<p className="text-sm break-words">
|
||||
Pesquisa apresentada:{' '}
|
||||
{term || 'Introduza primeiro o texto a procurar.'}
|
||||
</p>
|
||||
<label className="grid gap-2 text-sm">
|
||||
Nome para guardar esta pesquisa
|
||||
<input
|
||||
className={controlClass}
|
||||
maxLength={100}
|
||||
value={create.data.name}
|
||||
onChange={(event) =>
|
||||
create.setData('name', event.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<FormErrors errors={create.errors} />
|
||||
<Button
|
||||
className="justify-self-start"
|
||||
disabled={
|
||||
create.processing ||
|
||||
!create.data.name.trim() ||
|
||||
term.trim().length < 2
|
||||
}
|
||||
>
|
||||
Guardar pesquisa
|
||||
</Button>
|
||||
</form>
|
||||
<p className="text-sm">
|
||||
{saved.active.length}{' '}
|
||||
{saved.active.length === 1
|
||||
? 'pesquisa activa'
|
||||
: 'pesquisas activas'}{' '}
|
||||
· até {saved.max_active} por utilizador.
|
||||
</p>
|
||||
<ul>
|
||||
{saved.active.map((row) => (
|
||||
<SavedSearchRow
|
||||
key={`${row.id}:${row.version}`}
|
||||
row={row}
|
||||
term={term}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
{saved.archived.total > 0 && (
|
||||
<details className="mt-4 rounded-lg border p-4">
|
||||
<summary className="cursor-pointer">
|
||||
Pesquisas arquivadas ({saved.archived.total})
|
||||
</summary>
|
||||
<ul>
|
||||
{saved.archived.data.map((row) => (
|
||||
<SavedSearchRow
|
||||
key={`${row.id}:${row.version}`}
|
||||
row={row}
|
||||
term={term}
|
||||
archived
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
<nav
|
||||
aria-label="Pesquisas arquivadas"
|
||||
className="flex flex-wrap gap-4"
|
||||
>
|
||||
{saved.archived.prev_page_url && (
|
||||
<Link href={saved.archived.prev_page_url}>
|
||||
Anteriores
|
||||
</Link>
|
||||
)}
|
||||
{saved.archived.next_page_url && (
|
||||
<Link href={saved.archived.next_page_url}>
|
||||
Seguintes
|
||||
</Link>
|
||||
)}
|
||||
</nav>
|
||||
</details>
|
||||
)}
|
||||
</details>
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
@@ -21,8 +21,19 @@ function preparation(data: Record<string, unknown>): unknown {
|
||||
typeof item === 'object' &&
|
||||
!Array.isArray(item)
|
||||
) {
|
||||
const { key: _rowKey, ...values } = item;
|
||||
return values;
|
||||
const {
|
||||
key: _rowKey,
|
||||
procurement_category,
|
||||
category_reason,
|
||||
...values
|
||||
} = item;
|
||||
return {
|
||||
...values,
|
||||
...(procurement_category
|
||||
? { procurement_category }
|
||||
: {}),
|
||||
...(category_reason ? { category_reason } : {}),
|
||||
};
|
||||
}
|
||||
return item;
|
||||
})
|
||||
|
||||
@@ -173,6 +173,7 @@ function Assignment({
|
||||
export default function Parameters({
|
||||
approvalLevels,
|
||||
approvalLevelsReady = false,
|
||||
requisitionCategoryOptions = {},
|
||||
companyDetails,
|
||||
companyDetailsReady,
|
||||
ready,
|
||||
@@ -201,6 +202,7 @@ export default function Parameters({
|
||||
}: {
|
||||
approvalLevels?: RequisitionApprovalPlan | null;
|
||||
approvalLevelsReady?: boolean;
|
||||
requisitionCategoryOptions?: Record<string, string>;
|
||||
companyDetails: CompanyDetails | null;
|
||||
companyDetailsReady: boolean;
|
||||
ready: boolean;
|
||||
@@ -316,6 +318,7 @@ export default function Parameters({
|
||||
<RequisitionApprovalSettings
|
||||
plan={approvalLevels}
|
||||
ready={approvalLevelsReady}
|
||||
categoryOptions={requisitionCategoryOptions}
|
||||
profiles={profiles}
|
||||
costCenters={costCenters}
|
||||
version={version}
|
||||
|
||||
@@ -14,6 +14,7 @@ import { Label } from '@/components/ui/label';
|
||||
import { money } from '@/types/procurement';
|
||||
import type { CostCenter, Requisition } from '@/types/procurement';
|
||||
import { CatalogueSearch } from '@/components/requisition-catalogue';
|
||||
import { RequisitionCategoryFields } from '@/components/requisition-category-fields';
|
||||
import type { CatalogueOptions } from '@/components/requisition-catalogue';
|
||||
|
||||
type Line = {
|
||||
@@ -33,6 +34,8 @@ type Line = {
|
||||
spare_part_id: string;
|
||||
production_area: string;
|
||||
downtime_started_at: string;
|
||||
procurement_category: string;
|
||||
category_reason: string;
|
||||
};
|
||||
const emptyLine = (taxRate: string): Line => ({
|
||||
source_line_id: '',
|
||||
@@ -51,10 +54,17 @@ const emptyLine = (taxRate: string): Line => ({
|
||||
spare_part_id: '',
|
||||
production_area: '',
|
||||
downtime_started_at: '',
|
||||
procurement_category: '',
|
||||
category_reason: '',
|
||||
});
|
||||
const lineFields = [
|
||||
{ key: 'description', label: 'Descrição', type: 'text', maxLength: 255 },
|
||||
{ key: 'category', label: 'Categoria', type: 'text', maxLength: 100 },
|
||||
{
|
||||
key: 'category',
|
||||
label: 'Categoria do artigo',
|
||||
type: 'text',
|
||||
maxLength: 100,
|
||||
},
|
||||
{
|
||||
key: 'quantity',
|
||||
label: 'Quantidade',
|
||||
@@ -91,6 +101,7 @@ export default function RequisitionForm({
|
||||
defaultTaxRate = '16.00',
|
||||
catalogue,
|
||||
incompleteDraftsAvailable = false,
|
||||
requisitionCategories = {},
|
||||
}: {
|
||||
costCenters: CostCenter[];
|
||||
requisition: Requisition | null;
|
||||
@@ -100,6 +111,7 @@ export default function RequisitionForm({
|
||||
defaultTaxRate?: string;
|
||||
catalogue?: CatalogueOptions;
|
||||
incompleteDraftsAvailable?: boolean;
|
||||
requisitionCategories?: Record<string, string>;
|
||||
}) {
|
||||
const page = usePage();
|
||||
const ready = page.props.internalRequisitionReady === true;
|
||||
@@ -143,6 +155,8 @@ export default function RequisitionForm({
|
||||
key: String(i.id),
|
||||
description: i.description,
|
||||
category: i.category,
|
||||
procurement_category: i.category_context?.category ?? '',
|
||||
category_reason: i.category_context?.reason ?? '',
|
||||
purchase_type: i.purchase_type,
|
||||
quantity: String(i.quantity),
|
||||
unit: i.unit,
|
||||
@@ -340,6 +354,27 @@ export default function RequisitionForm({
|
||||
LINHA {index + 1}
|
||||
</legend>
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{Object.keys(requisitionCategories)
|
||||
.length > 0 && (
|
||||
<RequisitionCategoryFields
|
||||
index={index}
|
||||
category={
|
||||
line.procurement_category ??
|
||||
''
|
||||
}
|
||||
reason={
|
||||
line.category_reason ?? ''
|
||||
}
|
||||
options={requisitionCategories}
|
||||
onChange={(field, value) =>
|
||||
changeLine(
|
||||
index,
|
||||
field,
|
||||
value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{catalogue?.ready && (
|
||||
<label className="space-y-2 sm:col-span-3">
|
||||
Fonte do artigo
|
||||
|
||||
@@ -13,6 +13,7 @@ import { Button } from '@/components/ui/button';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { date, money, priorityLabels, roleLabels } from '@/types/procurement';
|
||||
import type { Requisition } from '@/types/procurement';
|
||||
import { requisitionCategoryLabels } from '@/components/requisition-category-fields';
|
||||
|
||||
type Audit = {
|
||||
id: number;
|
||||
@@ -331,10 +332,11 @@ export default function Show({
|
||||
(r.draft_input?.incomplete ? (
|
||||
<div role="status" className="rounded-xl border p-5">
|
||||
<p>
|
||||
Rascunho incompleto guardado. Os montantes estão
|
||||
por completar; não há submissão nem reserva
|
||||
orçamental. As linhas anteriormente completas
|
||||
não representam esta preparação.
|
||||
Rascunho incompleto guardado. Complete os dados
|
||||
e os requisitos aplicáveis às linhas; não há
|
||||
submissão nem reserva orçamental. As linhas
|
||||
anteriormente completas não representam esta
|
||||
preparação.
|
||||
</p>
|
||||
<Link
|
||||
className="mt-3 inline-block underline"
|
||||
@@ -453,6 +455,22 @@ export default function Show({
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
{i.category}
|
||||
</p>
|
||||
{i.category_context && (
|
||||
<p className="mt-1 text-xs">
|
||||
{requisitionCategoryLabels[
|
||||
i
|
||||
.category_context
|
||||
.category
|
||||
] ??
|
||||
i
|
||||
.category_context
|
||||
.category}
|
||||
{i
|
||||
.category_context
|
||||
.reason &&
|
||||
` · ${i.category_context.reason}`}
|
||||
</p>
|
||||
)}
|
||||
{i.equipment_id && (
|
||||
<p className="mt-1 text-xs">
|
||||
Equipamento #
|
||||
|
||||
@@ -6,6 +6,8 @@ import {
|
||||
controlClass,
|
||||
} from '@/components/procurement';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { SavedProcurementSearches } from '@/components/saved-procurement-searches';
|
||||
import type { SavedSearches } from '@/components/saved-procurement-searches';
|
||||
|
||||
type Group = {
|
||||
key: string;
|
||||
@@ -34,10 +36,12 @@ export default function ProcurementSearch({
|
||||
term,
|
||||
groups,
|
||||
invoiceSearchAvailable = false,
|
||||
savedSearches = null,
|
||||
}: {
|
||||
term: string;
|
||||
groups: Group[];
|
||||
invoiceSearchAvailable?: boolean;
|
||||
savedSearches?: SavedSearches | null;
|
||||
}) {
|
||||
const form = useForm({ q: term });
|
||||
return (
|
||||
@@ -90,6 +94,13 @@ export default function ProcurementSearch({
|
||||
</p>
|
||||
)}
|
||||
</Panel>
|
||||
{savedSearches && (
|
||||
<SavedProcurementSearches
|
||||
key={term}
|
||||
saved={savedSearches}
|
||||
term={term}
|
||||
/>
|
||||
)}
|
||||
{term.trim().length < 2 && (
|
||||
<p role="status">
|
||||
Introduza pelo menos dois caracteres para pesquisar.
|
||||
|
||||
@@ -14,6 +14,11 @@ export type Company = {
|
||||
rules_provisional: boolean;
|
||||
};
|
||||
export type RequisitionItem = {
|
||||
category_context?: {
|
||||
version: number;
|
||||
category: string;
|
||||
reason: string | null;
|
||||
} | null;
|
||||
catalogue_entry_id?: number | null;
|
||||
catalogue_snapshot?: {
|
||||
entry_id: number;
|
||||
@@ -42,7 +47,11 @@ export type RequisitionItem = {
|
||||
total_minor: number;
|
||||
};
|
||||
export type ApprovalStep = {
|
||||
routing?: { name: string; scope: 'company' | 'department'; profile_ids: number[] } | null;
|
||||
routing?: {
|
||||
name: string;
|
||||
scope: 'company' | 'department';
|
||||
profile_ids: number[];
|
||||
} | null;
|
||||
id: number;
|
||||
position: number;
|
||||
role: string;
|
||||
|
||||
@@ -126,6 +126,10 @@ Route::middleware(['auth', 'verified', EnsureOrganizationAccess::class])->group(
|
||||
Route::post('api/stock-returns/{id}/reject', [WarehouseReturnController::class, 'reject'])->whereNumber('id');
|
||||
Route::get('compras/fornecimento', [SupplyPlanningController::class, 'index'])->name('supply.index');
|
||||
Route::get('compras/pesquisa', [\App\Http\Controllers\ProcurementSearchController::class, 'index'])->name('procurement.search');
|
||||
Route::post('compras/pesquisas-guardadas', [\App\Http\Controllers\SavedProcurementSearchController::class, 'store'])->name('procurement.saved-searches.store');
|
||||
Route::put('compras/pesquisas-guardadas/{search}', [\App\Http\Controllers\SavedProcurementSearchController::class, 'update'])->whereNumber('search')->name('procurement.saved-searches.update');
|
||||
Route::post('compras/pesquisas-guardadas/{search}/arquivar', [\App\Http\Controllers\SavedProcurementSearchController::class, 'archive'])->whereNumber('search')->name('procurement.saved-searches.archive');
|
||||
Route::post('compras/pesquisas-guardadas/{search}/restaurar', [\App\Http\Controllers\SavedProcurementSearchController::class, 'restore'])->whereNumber('search')->name('procurement.saved-searches.restore');
|
||||
Route::get('compras/acordos/vigencia', [AgreementFollowupController::class, 'index'])->name('supply.agreements.followup');
|
||||
Route::get('compras/acordos/vigencia.csv', [AgreementFollowupController::class, 'csv'])->name('supply.agreements.followup.csv');
|
||||
Route::get('compras/fornecimento.csv', [SupplyCoordinationReportController::class, 'csv'])->name('supply.coordination.csv');
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const installation = JSON.parse(
|
||||
await fs.readFile('docs/proofs/rq01-distribution-pilot-installation.json', 'utf8'),
|
||||
);
|
||||
assert.equal(installation.status, 'installed_and_capability_enabled_no_business_operations');
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const results=[];
|
||||
for(const role of ['requester','admin','procurement','finance']) {
|
||||
const viewer=client(); await viewer.enter(role);
|
||||
assert.equal((await viewer.request('/contexto','POST',{area:'procurement',option:'procurement.internal'})).status,302);
|
||||
const detail=await viewer.request('/requisicoes/2');
|
||||
assert.equal(detail.status,200);
|
||||
const owner=detail.page.props.requisition.requester_id===detail.page.props.auth.user.id;
|
||||
const eligible=owner && detail.page.props.requisition.status==='draft' && detail.page.props.canEdit;
|
||||
assert.equal(detail.page.props.canPrepareDistributions,eligible);
|
||||
assert.equal('budget_distribution_preparation' in detail.page.props.requisition,false);
|
||||
results.push({role,path:'/requisicoes/2',status:200,request_status:detail.page.props.requisition.status,can_prepare:eligible,restricted_preparation_hidden:true});
|
||||
const form=await viewer.request('/requisicoes/2/distribuicoes');
|
||||
assert.equal(form.status,eligible?200:403);
|
||||
if(eligible) {
|
||||
assert.equal(form.page.component,'requisitions/distributions');
|
||||
assert.equal(form.page.encryptHistory,true);
|
||||
assert.equal(form.page.props.preparation,null);
|
||||
}
|
||||
results.push({role,path:'/requisicoes/2/distribuicoes',status:form.status});
|
||||
}
|
||||
await fs.writeFile('docs/proofs/rq01-distribution-pilot-http.json',JSON.stringify({environment:base,result:'passed',results,business_commands:false,session_context_only:true,visual_review:false},null,2));
|
||||
console.log(JSON.stringify({http_checks:results.length,result:'passed',business_commands:false}));
|
||||
`+'})()')(fs,assert);
|
||||
@@ -24,6 +24,38 @@ if (DB::getDriverName() !== 'pgsql' || DB::connection()->getDatabaseName() !== $
|
||||
throw new LogicException('Review verification database mismatch.');
|
||||
}
|
||||
$request = DB::table('requisitions')->where('id', $proof['synthetic_fixture']['draft'])->first();
|
||||
if (in_array('--saved-searches', $argv, true)) {
|
||||
$owner = DB::table('users')->where('email', $proof['synthetic_fixture']['users']['owner'])->sole();
|
||||
$saved = DB::table('procurement_saved_searches')->sole();
|
||||
if ($saved->tenant_id !== $owner->tenant_id || $saved->user_id !== $owner->id || (int) $saved->version !== 4
|
||||
|| $saved->name !== 'Meus pedidos revistos QA' || $saved->term !== 'REQ' || $saved->archived_at !== null
|
||||
|| $request->status !== 'draft' || (int) $request->process_version !== 2
|
||||
|| DB::table('audit_logs')->where('requisition_id', $request->id)->where('action', 'requisition.updated')->exists()
|
||||
|| DB::table('budget_entries')->where('requisition_id', $request->id)->exists()
|
||||
|| DB::table('budget_distributions')->where('requisition_id', $request->id)->exists()
|
||||
|| DB::table('invoices')->exists()) {
|
||||
throw new RuntimeException('Saved criteria must preserve owner, four native versions and absence of draft or financial operations.');
|
||||
}
|
||||
echo json_encode(['native_private_search_cycle' => true, 'one_preference' => true, 'version' => 4, 'criterion_preserved' => true,
|
||||
'active_after_restore' => true, 'no_draft_update_reservation_or_invoice' => true], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
exit;
|
||||
}
|
||||
if (in_array('--category', $argv, true)) {
|
||||
$line = DB::table('requisition_items')->where('requisition_id', $request->id)->sole();
|
||||
$context = json_decode($line->category_context, true, 32, JSON_THROW_ON_ERROR);
|
||||
if ($request->status !== 'draft' || (int) $request->process_version !== 3
|
||||
|| $context !== ['version' => 1, 'category' => 'office_equipment', 'reason' => 'Artigo sintético de escritório ainda sem entrada no catálogo.']
|
||||
|| $line->category !== 'Material' || $line->purchase_type !== 'consumable' || (int) $request->total_minor !== 10000
|
||||
|| DB::table('budget_entries')->where('requisition_id', $request->id)->exists()
|
||||
|| DB::table('budget_distributions')->where('requisition_id', $request->id)->exists()
|
||||
|| DB::table('audit_logs')->where('requisition_id', $request->id)->where('action', 'requisition.updated')->count() !== 1
|
||||
|| DB::table('invoices')->exists()) {
|
||||
throw new RuntimeException('Native classification save must preserve the original category, type, totals and absence of business effects.');
|
||||
}
|
||||
echo json_encode(['native_category_saved' => true, 'explicit_reason_preserved' => true, 'original_descriptors_and_totals_preserved' => true,
|
||||
'draft_version' => 3, 'one_update_audit' => true, 'no_reservation_or_invoice' => true], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
exit;
|
||||
}
|
||||
$plan = json_decode($request->budget_distribution_preparation, true, 32, JSON_THROW_ON_ERROR);
|
||||
if ((int) $request->process_version !== 3 || $request->status !== 'draft' || count($plan['allocations']) !== 2
|
||||
|| array_column($plan['allocations'], 'subtotal_minor') !== [5000, 5000] || array_column($plan['allocations'], 'total_minor') !== [5000, 5000]
|
||||
|
||||
@@ -15,7 +15,14 @@ if (in_array('--refresh-running-preview', $argv, true)) {
|
||||
|| ! is_file($private.'/settings.json')) {
|
||||
throw new LogicException('Private review identity mismatch.');
|
||||
}
|
||||
$candidate = storage_path('framework/testing/sgc-distribution-integrated-qa-20261122');
|
||||
$candidateRelative = 'storage/framework/testing/sgc-distribution-integrated-qa-20261122';
|
||||
if (in_array('--candidate', $argv, true)) {
|
||||
$candidateRelative = $argv[array_search('--candidate', $argv, true) + 1] ?? '';
|
||||
}
|
||||
if (! preg_match('~^storage/framework/testing/[A-Za-z0-9_-]+$~D', $candidateRelative)) {
|
||||
throw new LogicException('Only an explicit private candidate can refresh this review.');
|
||||
}
|
||||
$candidate = base_path($candidateRelative);
|
||||
$expected = $argv[array_search('--refresh-running-preview', $argv, true) + 1] ?? '';
|
||||
if (! preg_match('/^[a-f0-9]{64}$/D', $expected) || hash_file('sha256', $candidate.'/manifest.json') !== $expected) {
|
||||
throw new LogicException('Explicit validated private manifest hash required.');
|
||||
@@ -58,8 +65,18 @@ $private = 'C:/laragon/data/sgf-tempo/qa/distribution-visual-'.$database;
|
||||
if (! mkdir($private.'/public', 0700, true) && ! is_dir($private.'/public')) {
|
||||
throw new RuntimeException('Private review directory creation failed.');
|
||||
}
|
||||
$candidate = storage_path('framework/testing/sgc-distribution-integrated-qa-20261122');
|
||||
if (hash_file('sha256', $candidate.'/manifest.json') !== '1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e') {
|
||||
$candidateRelative = 'storage/framework/testing/sgc-distribution-integrated-qa-20261122';
|
||||
$candidateHash = '1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e';
|
||||
if (in_array('--candidate', $argv, true)) {
|
||||
$position = array_search('--candidate', $argv, true);
|
||||
$candidateRelative = $argv[$position + 1] ?? '';
|
||||
$candidateHash = $argv[$position + 2] ?? '';
|
||||
}
|
||||
if (! preg_match('~^storage/framework/testing/[A-Za-z0-9_-]+$~D', $candidateRelative) || ! preg_match('/^[a-f0-9]{64}$/D', $candidateHash)) {
|
||||
throw new LogicException('Explicit private candidate path and hash required.');
|
||||
}
|
||||
$candidate = base_path($candidateRelative);
|
||||
if (hash_file('sha256', $candidate.'/manifest.json') !== $candidateHash) {
|
||||
throw new RuntimeException('The private candidate differs from the validated build.');
|
||||
}
|
||||
(new Filesystem)->copyDirectory($candidate, $private.'/public/build');
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
<?php
|
||||
|
||||
use App\Services\BudgetDistributionArtifact;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
// Default: read the pilot and rehearse on a private restore. Application needs a separate exact approval.
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
$root = dirname(__DIR__);
|
||||
$apply = in_array('--apply-authorized', $argv, true);
|
||||
if (! $apply && ! in_array('--restore-and-rehearse', $argv, true)) {
|
||||
throw new LogicException('Explicit preparation or separately authorised installation required.');
|
||||
}
|
||||
$proposalPath = $root.'/docs/proofs/rq01-distribution-pilot-proposal.json';
|
||||
$installationProof = $root.'/docs/proofs/rq01-distribution-pilot-installation.json';
|
||||
if ($apply) {
|
||||
$authorizationPath = $root.'/docs/proofs/rq01-distribution-pilot-authorization.json';
|
||||
$authorization = is_file($authorizationPath) ? json_decode(file_get_contents($authorizationPath), true, 32, JSON_THROW_ON_ERROR) : null;
|
||||
if (! is_array($authorization) || ($authorization['status'] ?? null) !== 'approved'
|
||||
|| ($authorization['environment'] ?? null) !== 'http://127.0.0.1:8005'
|
||||
|| ($authorization['proposal_sha256'] ?? null) !== hash_file('sha256', $proposalPath) || is_file($installationProof)) {
|
||||
throw new LogicException('Exact installation authorisation required; recorded installations are never repeated.');
|
||||
}
|
||||
$proposal = json_decode(file_get_contents($proposalPath), true, 64, JSON_THROW_ON_ERROR);
|
||||
foreach ($proposal['reviewed_files'] as $file => $hash) {
|
||||
if (hash_file('sha256', $root.'/'.$file) !== $hash) {
|
||||
throw new LogicException('Reviewed installation file changed:'.$file);
|
||||
}
|
||||
}
|
||||
}
|
||||
$settingsPath = 'C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json';
|
||||
$settingsBytes = file_get_contents($settingsPath);
|
||||
$settings = json_decode($settingsBytes, true, 32, JSON_THROW_ON_ERROR);
|
||||
if (($settings['APP_ENV'] ?? '') !== 'payable-testing' || ($settings['DB_HOST'] ?? '') !== '127.0.0.1'
|
||||
|| realpath($settings['HOST_ROOT'] ?? '') !== realpath($root)
|
||||
|| ! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $settings['DB_DATABASE'] ?? '', $match)
|
||||
|| $settings['DB_USERNAME'] !== 'payable_qa_'.$match[1]
|
||||
|| filter_var($settings['SGC_BUDGET_DISTRIBUTIONS_ENABLED'] ?? false, FILTER_VALIDATE_BOOLEAN)) {
|
||||
throw new LogicException('Original named pilot with distributions disabled required.');
|
||||
}
|
||||
$artifactPath = $root.'/docs/proofs/rq01-distribution-artifact.json';
|
||||
$artifact = json_decode(file_get_contents($artifactPath), true, 32, JSON_THROW_ON_ERROR);
|
||||
BudgetDistributionArtifact::verify($root.'/'.$artifact['path'], $artifactPath, hash_file('sha256', $artifactPath));
|
||||
$app = require $root.'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
$owner = DB::connection('pgsql')->getConfig();
|
||||
unset($owner['name']);
|
||||
if ($owner['host'] !== '127.0.0.1') {
|
||||
throw new LogicException('Local administrative connection required.');
|
||||
}
|
||||
$pilotConfig = [...$owner, 'url' => null, 'host' => $settings['DB_HOST'], 'database' => $settings['DB_DATABASE'],
|
||||
'username' => $settings['DB_USERNAME'], 'password' => $settings['DB_PASSWORD']];
|
||||
config(['database.connections.distribution_pilot_read' => $pilotConfig,
|
||||
'database.connections.distribution_prepare_owner' => [...$owner, 'database' => 'postgres', 'url' => null]]);
|
||||
$pilot = DB::connection('distribution_pilot_read');
|
||||
$admin = DB::connection('distribution_prepare_owner');
|
||||
$restoreName = 'compras_distribution_restore_'.bin2hex(random_bytes(6));
|
||||
$directory = 'C:/laragon/data/sgf-tempo/backups/compras-distribution-preparation-'.gmdate('Ymd-His').'-'.bin2hex(random_bytes(3));
|
||||
if (! mkdir($directory, 0700, true)) {
|
||||
throw new RuntimeException('Could not create private recovery directory.');
|
||||
}
|
||||
$dump = $directory.'/before.dump';
|
||||
$originalManifest = hash_file('sha256', $root.'/public/build/manifest.json');
|
||||
if ($apply && $originalManifest !== $proposal['previous_manifest_sha256']) {
|
||||
throw new LogicException('Pilot assets changed after the reviewed proposal.');
|
||||
}
|
||||
$previous = DB::getDefaultConnection();
|
||||
$created = false;
|
||||
$fingerprint = static function ($connection, array $columns): array {
|
||||
$out = [];
|
||||
foreach ($columns as $table => $names) {
|
||||
$selected = implode(',', array_map(fn ($name) => '"'.str_replace('"', '""', $name).'"', $names));
|
||||
$rows = $connection->select('select row_to_json(t)::text as row from (select '.$selected.' from "'.$table.'") t order by row_to_json(t)::text');
|
||||
$out[$table] = hash('sha256', json_encode(array_column($rows, 'row'), JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
return $out;
|
||||
};
|
||||
$pg = static function (string $binary, array $arguments) use ($pilotConfig): void {
|
||||
$process = new Process(['C:/Program Files/PostgreSQL/17/bin/'.$binary.'.exe', ...$arguments], null,
|
||||
['PGHOST' => $pilotConfig['host'], 'PGPORT' => (string) $pilotConfig['port'],
|
||||
'PGUSER' => $pilotConfig['username'], 'PGPASSWORD' => $pilotConfig['password']], timeout: 120);
|
||||
$process->run();
|
||||
if (! $process->isSuccessful()) {
|
||||
throw new RuntimeException('Private backup or restore failed; pilot untouched.');
|
||||
}
|
||||
};
|
||||
try {
|
||||
$pilot->beginTransaction();
|
||||
$pilot->statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
$identity = $pilot->selectOne('select current_database() as db, current_user as role');
|
||||
if ($identity->db !== $settings['DB_DATABASE'] || $identity->role !== $settings['DB_USERNAME']) {
|
||||
throw new LogicException('Effective pilot identity mismatch.');
|
||||
}
|
||||
$schema = $pilot->getSchemaBuilder();
|
||||
if ($schema->hasTable('budget_distributions') || $schema->hasColumn('requisitions', 'budget_distribution_preparation')) {
|
||||
throw new LogicException('Optional schema already exists; inspect without reapplying.');
|
||||
}
|
||||
$tables = array_column($pilot->select("select tablename from pg_tables where schemaname='public' order by tablename"), 'tablename');
|
||||
$columns = $keys = [];
|
||||
foreach ($tables as $table) {
|
||||
$columns[$table] = $schema->getColumnListing($table);
|
||||
$keys[$table] = $schema->getForeignKeys($table);
|
||||
}
|
||||
$baseline = $fingerprint($pilot, $columns);
|
||||
$migrationCount = $pilot->table('migrations')->count();
|
||||
$snapshot = $pilot->selectOne('select pg_export_snapshot() as snapshot')->snapshot;
|
||||
$pg('pg_dump', ['--format=custom', '--snapshot='.$snapshot, '--file='.$dump, '--dbname='.$pilotConfig['database']]);
|
||||
$pilot->commit();
|
||||
$admin->statement('CREATE DATABASE "'.$restoreName.'" OWNER "'.$settings['DB_USERNAME'].'"');
|
||||
$created = true;
|
||||
$pg('pg_restore', ['--no-owner', '--no-privileges', '--exit-on-error', '--dbname='.$restoreName, $dump]);
|
||||
config(['database.connections.distribution_rehearsal' => [...$pilotConfig, 'database' => $restoreName]]);
|
||||
$restored = DB::connection('distribution_rehearsal');
|
||||
if ($fingerprint($restored, $columns) !== $baseline) {
|
||||
throw new LogicException('Same-role restore differs from original snapshot.');
|
||||
}
|
||||
DB::setDefaultConnection('distribution_rehearsal');
|
||||
config(['budget-distributions.schema_installation' => ['database' => $restoreName, 'username' => $settings['DB_USERNAME']]]);
|
||||
$migration = 'database/deployment-migrations/2026_11_22_000004_create_budget_distributions.php';
|
||||
if (Artisan::call('migrate', ['--database' => 'distribution_rehearsal', '--path' => [$migration], '--force' => true]) !== 0) {
|
||||
throw new RuntimeException('Exact restored migration failed.');
|
||||
}
|
||||
$after = $fingerprint($restored, $columns);
|
||||
unset($after['migrations'], $baseline['migrations']);
|
||||
if ($after !== $baseline || $restored->table('migrations')->count() !== $migrationCount + 1
|
||||
|| $restored->table('requisitions')->whereNotNull('budget_distribution_preparation')->exists()) {
|
||||
throw new LogicException('Previous records changed or new values are not empty.');
|
||||
}
|
||||
foreach ($keys as $table => $expected) {
|
||||
if ($restored->getSchemaBuilder()->getForeignKeys($table) !== $expected) {
|
||||
throw new LogicException('Previous foreign keys changed.');
|
||||
}
|
||||
}
|
||||
foreach (['budget_distributions', 'budget_distribution_events', 'budget_distribution_entries', 'budget_distribution_consumptions'] as $table) {
|
||||
if ($restored->table($table)->exists()) {
|
||||
throw new LogicException('Optional schema must remain empty.');
|
||||
}
|
||||
}
|
||||
if (hash_file('sha256', $settingsPath) !== hash('sha256', $settingsBytes)
|
||||
|| hash_file('sha256', $root.'/public/build/manifest.json') !== $originalManifest) {
|
||||
throw new LogicException('Deployment changed during preparation; reassess the destination.');
|
||||
}
|
||||
$proof = ['date' => gmdate('Y-m-d'), 'status' => 'restored_pilot_rehearsal_passed_not_installed', 'environment' => 'http://127.0.0.1:8005',
|
||||
'pilot_read_only' => true, 'backup' => $dump, 'backup_sha256' => hash_file('sha256', $dump),
|
||||
'same_restore_role' => true, 'restored_tables_checked' => count($tables), 'previous_business_tables_preserved' => count($tables) - 1,
|
||||
'previous_foreign_keys_preserved' => true, 'new_values_empty' => true, 'optional_tables' => 4,
|
||||
'deployment_settings_unchanged' => true, 'pilot_manifest_sha256' => $originalManifest,
|
||||
'migration' => $migration, 'migration_sha256' => hash_file('sha256', $root.'/'.$migration),
|
||||
'schema_definition_sha256' => hash_file('sha256', $root.'/app/Services/BudgetDistributionSchema.php'),
|
||||
'artifact_manifest_sha256' => hash_file('sha256', $artifactPath), 'pilot_schema_or_activation_changed' => false];
|
||||
if ($apply) {
|
||||
// Preserve deployment state before copying immutable, separately selected release files.
|
||||
if (file_put_contents($directory.'/settings.before.json', $settingsBytes) !== strlen($settingsBytes)
|
||||
|| ! copy($root.'/public/build/manifest.json', $directory.'/manifest.before.json')) {
|
||||
throw new RuntimeException('Could not preserve deployment state.');
|
||||
}
|
||||
$release = $root.'/'.$proposal['release_path'];
|
||||
if (! is_dir($release.'/src') && ! mkdir($release.'/src', 0700, true)) {
|
||||
throw new RuntimeException('Could not create the private release directory.');
|
||||
}
|
||||
foreach ($artifact['files'] as $file => $hash) {
|
||||
if (is_file($release.'/'.$file) && hash_file('sha256', $release.'/'.$file) !== $hash) {
|
||||
throw new LogicException('Existing release differs; it was not overwritten.');
|
||||
}
|
||||
if (! is_file($release.'/'.$file)) {
|
||||
copy($root.'/'.$artifact['path'].'/'.$file, $release.'/'.$file);
|
||||
}
|
||||
}
|
||||
$releaseManifest = $release.'/artifact-manifest.json';
|
||||
if (is_file($releaseManifest) && hash_file('sha256', $releaseManifest) !== hash_file('sha256', $artifactPath)) {
|
||||
throw new LogicException('Existing release manifest differs.');
|
||||
}
|
||||
if (! is_file($releaseManifest)) {
|
||||
copy($artifactPath, $releaseManifest);
|
||||
}
|
||||
BudgetDistributionArtifact::verify($release, $releaseManifest, $proposal['artifact_manifest_sha256']);
|
||||
foreach ($proposal['assets'] as $file => $hash) {
|
||||
$target = $root.'/public/build/'.$file;
|
||||
if (! preg_match('~^assets/[A-Za-z0-9_.-]+$~D', $file)
|
||||
|| hash_file('sha256', $root.'/'.$proposal['candidate_path'].'/'.$file) !== $hash
|
||||
|| (is_file($target) && hash_file('sha256', $target) !== $hash)) {
|
||||
throw new LogicException('Candidate asset changed or collides with an existing asset.');
|
||||
}
|
||||
if (! is_file($target)) {
|
||||
copy($root.'/'.$proposal['candidate_path'].'/'.$file, $target);
|
||||
}
|
||||
if (hash_file('sha256', $target) !== $hash) {
|
||||
throw new RuntimeException('Copied asset verification failed.');
|
||||
}
|
||||
}
|
||||
DB::setDefaultConnection('distribution_pilot_read');
|
||||
config(['budget-distributions.schema_installation' => ['database' => $settings['DB_DATABASE'], 'username' => $settings['DB_USERNAME']]]);
|
||||
$pilot->transaction(function () use ($pilot, $tables, $fingerprint, $columns, $keys, $baseline, $migration, $migrationCount, $settingsPath, $settingsBytes): void {
|
||||
$pilot->statement("SET LOCAL lock_timeout = '5s'");
|
||||
foreach ($tables as $table) {
|
||||
$pilot->statement('LOCK TABLE "'.$table.'" IN SHARE MODE');
|
||||
}
|
||||
$current = $fingerprint($pilot, $columns);
|
||||
unset($current['migrations']);
|
||||
if ($current !== $baseline || hash_file('sha256', $settingsPath) !== hash('sha256', $settingsBytes)) {
|
||||
throw new LogicException('Pilot changed after backup; installation refused.');
|
||||
}
|
||||
foreach ($keys as $table => $expected) {
|
||||
if ($pilot->getSchemaBuilder()->getForeignKeys($table) !== $expected) {
|
||||
throw new LogicException('Pilot foreign keys changed after backup.');
|
||||
}
|
||||
}
|
||||
if (Artisan::call('migrate', ['--database' => 'distribution_pilot_read', '--path' => [$migration], '--force' => true]) !== 0
|
||||
|| $pilot->table('migrations')->count() !== $migrationCount + 1) {
|
||||
throw new RuntimeException('Exact pilot migration failed.');
|
||||
}
|
||||
$after = $fingerprint($pilot, $columns);
|
||||
unset($after['migrations']);
|
||||
if ($after !== $baseline || $pilot->table('requisitions')->whereNotNull('budget_distribution_preparation')->exists()) {
|
||||
throw new LogicException('Previous data changed; installation rolled back.');
|
||||
}
|
||||
foreach ($keys as $table => $expected) {
|
||||
if ($pilot->getSchemaBuilder()->getForeignKeys($table) !== $expected) {
|
||||
throw new LogicException('Previous foreign keys changed; installation rolled back.');
|
||||
}
|
||||
}
|
||||
});
|
||||
$proof['status'] = 'schema_installed_activation_pending';
|
||||
$proof['pilot_read_only'] = false;
|
||||
$proof['pilot_schema_or_activation_changed'] = true;
|
||||
file_put_contents($installationProof, json_encode($proof, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR).PHP_EOL);
|
||||
// All copied chunks are verified before the manifest is atomically switched.
|
||||
$manifestBytes = file_get_contents($root.'/'.$proposal['candidate_path'].'/manifest.json');
|
||||
if (hash('sha256', $manifestBytes) !== $proposal['candidate_manifest_sha256']
|
||||
|| hash_file('sha256', $settingsPath) !== hash('sha256', $settingsBytes)) {
|
||||
throw new LogicException('Activation inputs changed; new empty schema retained, activation refused.');
|
||||
}
|
||||
$nextSettings = [...$settings, 'COMMON_BUDGET_PATH' => str_replace('\\', '/', $release),
|
||||
'SGC_BUDGET_DISTRIBUTIONS_ENABLED' => 'true', 'SGC_BUDGET_DISTRIBUTIONS_MANIFEST' => str_replace('\\', '/', $releaseManifest),
|
||||
'SGC_BUDGET_DISTRIBUTIONS_MANIFEST_SHA256' => $proposal['artifact_manifest_sha256']];
|
||||
$settingsNextBytes = json_encode($nextSettings, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
$manifestNext = $root.'/public/build/manifest.distribution-next.json';
|
||||
$settingsNext = $settingsPath.'.distribution-next';
|
||||
if (file_put_contents($manifestNext, $manifestBytes) !== strlen($manifestBytes)
|
||||
|| file_put_contents($settingsNext, $settingsNextBytes) !== strlen($settingsNextBytes)
|
||||
|| ! rename($manifestNext, $root.'/public/build/manifest.json')) {
|
||||
throw new RuntimeException('Could not switch reviewed assets; deployment state preserved in backup.');
|
||||
}
|
||||
if (! rename($settingsNext, $settingsPath)) {
|
||||
copy($directory.'/manifest.before.json', $root.'/public/build/manifest.json');
|
||||
throw new RuntimeException('Capability switch failed; previous assets restored, schema retained.');
|
||||
}
|
||||
$proof['status'] = 'installed_and_capability_enabled_no_business_operations';
|
||||
$proof['pilot_read_only'] = false;
|
||||
$proof['deployment_settings_unchanged'] = false;
|
||||
$proof['unrelated_deployment_settings_preserved'] = true;
|
||||
$proof['manifest_sha256'] = hash_file('sha256', $root.'/public/build/manifest.json');
|
||||
$proof['release_path'] = $proposal['release_path'];
|
||||
$proof['business_operations'] = false;
|
||||
$proof['grants_changed'] = false;
|
||||
$proof['pinned_packages_changed'] = false;
|
||||
}
|
||||
} finally {
|
||||
if ($pilot->transactionLevel() > 0) {
|
||||
$pilot->rollBack();
|
||||
}
|
||||
DB::setDefaultConnection($previous);
|
||||
config(['budget-distributions.schema_installation' => null]);
|
||||
DB::purge('distribution_rehearsal');
|
||||
if ($created) {
|
||||
$admin->statement('DROP DATABASE "'.$restoreName.'" WITH (FORCE)');
|
||||
}
|
||||
}
|
||||
$proof['restored_database_removed'] = true;
|
||||
file_put_contents($apply ? $installationProof : $root.'/docs/proofs/rq01-distribution-pilot-preparation.json', json_encode($proof, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR).PHP_EOL);
|
||||
echo json_encode($proof, JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
// Produce a reviewable, hash-bound proposal; no application bootstrap, database or deployment writes.
|
||||
$root = dirname(__DIR__);
|
||||
$read = static fn (string $path): array => json_decode(file_get_contents($root.'/'.$path), true, 64, JSON_THROW_ON_ERROR);
|
||||
$artifact = $read('docs/proofs/rq01-distribution-artifact.json');
|
||||
$rehearsal = $read('docs/proofs/rq01-distribution-pilot-preparation.json');
|
||||
if ($rehearsal['status'] !== 'restored_pilot_rehearsal_passed_not_installed' || ! $rehearsal['restored_database_removed']) {
|
||||
throw new LogicException('Successful same-role restored rehearsal required.');
|
||||
}
|
||||
$candidate = 'storage/framework/testing/sgc-distribution-integrated-qa-20261122';
|
||||
$manifest = $read($candidate.'/manifest.json');
|
||||
$assets = [];
|
||||
foreach ($manifest as $entry) {
|
||||
foreach ([$entry['file'], ...($entry['css'] ?? []), ...($entry['assets'] ?? [])] as $file) {
|
||||
if (! preg_match('~^assets/[A-Za-z0-9_.-]+$~D', $file) || ! is_file($root.'/'.$candidate.'/'.$file)) {
|
||||
throw new LogicException('Candidate asset inventory mismatch.');
|
||||
}
|
||||
$assets[$file] = hash_file('sha256', $root.'/'.$candidate.'/'.$file);
|
||||
}
|
||||
}
|
||||
ksort($assets);
|
||||
$files = ['scripts/prepare-budget-distribution-pilot.php', 'scripts/budget-distribution-pilot-http.mjs', 'app/Services/BudgetDistributionArtifact.php', 'app/Services/BudgetDistributionSchema.php',
|
||||
'database/deployment-migrations/2026_11_22_000004_create_budget_distributions.php', 'app/Providers/AppServiceProvider.php',
|
||||
'app/Services/RequisitionBudgetDistributions.php', 'app/Services/InvoiceBudgetDistributions.php', 'app/Services/CommonBudget.php',
|
||||
'app/Services/BudgetWorkflow.php', 'app/Services/PurchaseWorkflow.php', 'app/Services/InvoiceWorkflow.php', 'app/Services/RequisitionWorkflow.php',
|
||||
'app/Models/Requisition.php', 'app/Http/Controllers/RequisitionController.php', 'app/Http/Controllers/PurchaseController.php', 'app/Http/Controllers/InvoiceController.php',
|
||||
'app/Http/Controllers/PurchaseProcessController.php', 'config/budget-distributions.php', 'config/common-budget.php', 'routes/web.php',
|
||||
'docs/proofs/rq01-distribution-artifact.json'];
|
||||
$reviewed = [];
|
||||
foreach ($files as $file) {
|
||||
if (! is_file($root.'/'.$file)) {
|
||||
throw new LogicException('Required reviewed host file missing:'.$file);
|
||||
}
|
||||
$reviewed[$file] = hash_file('sha256', $root.'/'.$file);
|
||||
}
|
||||
foreach ($artifact['files'] as $file => $hash) {
|
||||
if (hash_file('sha256', $root.'/'.$artifact['path'].'/'.$file) !== $hash) {
|
||||
throw new LogicException('Frozen common source changed.');
|
||||
}
|
||||
$reviewed[$artifact['path'].'/'.$file] = $hash;
|
||||
}
|
||||
$proposal = ['date' => '2026-11-22', 'status' => 'prepared_not_authorised_not_installed', 'environment' => 'http://127.0.0.1:8005',
|
||||
'scope' => 'Install only the optional line/cost-centre distributions and explicit Finance amendments in the named SGC pilot; no SGF activation or business operations.',
|
||||
'schema' => ['migration' => $rehearsal['migration'], 'migration_sha256' => $reviewed[$rehearsal['migration']],
|
||||
'nullable_column' => 'requisitions.budget_distribution_preparation', 'new_empty_tables' => ['budget_distributions', 'budget_distribution_events', 'budget_distribution_entries', 'budget_distribution_consumptions']],
|
||||
'release_path' => 'storage/app/private/releases/budget-distribution-'.substr($artifact['canonical_fingerprint'], 0, 16),
|
||||
'artifact_manifest_sha256' => hash_file('sha256', $root.'/docs/proofs/rq01-distribution-artifact.json'),
|
||||
'archive_sha256' => $artifact['archive_sha256'], 'candidate_path' => $candidate,
|
||||
'candidate_manifest_sha256' => hash_file('sha256', $root.'/'.$candidate.'/manifest.json'),
|
||||
'previous_manifest_sha256' => $rehearsal['pilot_manifest_sha256'], 'assets' => $assets, 'reviewed_files' => $reviewed,
|
||||
'private_settings_changes' => ['COMMON_BUDGET_PATH' => 'Selected independent SGC release directory; original pinned package preserved',
|
||||
'SGC_BUDGET_DISTRIBUTIONS_ENABLED' => 'true', 'SGC_BUDGET_DISTRIBUTIONS_MANIFEST' => 'Frozen manifest inside the selected release',
|
||||
'SGC_BUDGET_DISTRIBUTIONS_MANIFEST_SHA256' => 'Exact artifact_manifest_sha256 above'],
|
||||
'verification' => ['native_visual' => 'rq01-distribution-visual.json', 'financial_qa' => 'rq01-distribution-qa.json',
|
||||
'same_role_pilot_restore' => 'rq01-distribution-pilot-preparation.json', 'runtime_integrity_log' => 'storage/logs/budget-distribution-release-integrity.txt',
|
||||
'postgres_schema_and_contract_log' => 'storage/logs/budget-distribution-deployment-schema-pg.txt'],
|
||||
'execution' => ['Exact separate approval bound to this proposal SHA-256', 'Fresh consistent backup and same-role restore before applying',
|
||||
'Recheck pilot data and configuration under locks; refuse intervening changes', 'Apply only the staged migration, preserve all previous columns/data/FKs',
|
||||
'Verify separately copied release and all asset bytes before switching manifest and four settings', 'Confirm named pilot HTTP and effective capability without business commands'],
|
||||
'recovery' => ['Before use: previous settings and manifest preserved privately; new empty schema can remain',
|
||||
'After distribution use: retain compatible runtime and append-only history; never select old runtime or restore a backup automatically',
|
||||
'Any restore affecting later operations requires a separate reviewed decision'],
|
||||
'excluded' => ['Real business operations, budgets, commitments, invoices, payments or accounting commands', 'Changes to roles or grants',
|
||||
'SGF deployment or activation', 'Replacing published or pinned financial packages', 'MFA, inventory conversions, per-order limits, People formalisation',
|
||||
'Production publication and enterprise acceptance']];
|
||||
file_put_contents($root.'/docs/proofs/rq01-distribution-pilot-proposal.json', json_encode($proposal, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR).PHP_EOL);
|
||||
echo json_encode(['proposal_prepared' => true, 'assets' => count($assets), 'reviewed_files' => count($reviewed),
|
||||
'proposal_sha256' => hash_file('sha256', $root.'/docs/proofs/rq01-distribution-pilot-proposal.json')], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
@@ -48,6 +48,36 @@ try {
|
||||
$orderDocumentMode = in_array('--order-document-only', $argv, true);
|
||||
$payableInsightsMode = in_array('--payable-insights-only', $argv, true);
|
||||
$budgetDistributionMode = in_array('--budget-distribution-only', $argv, true);
|
||||
$categoriesMode = in_array('--requisition-categories-only', $argv, true);
|
||||
$savedSearchesMode = in_array('--saved-searches-only', $argv, true);
|
||||
$categoryApprovalsMode = in_array('--category-approvals-only', $argv, true);
|
||||
$orderPartsMode = in_array('--budget-order-parts-only', $argv, true);
|
||||
if ($orderPartsMode) {
|
||||
$environment['COMMON_BUDGET_PATH'] = 'C:/laragon/www/sgf-tempo/packages/budget-control';
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/BudgetOrderPartsContractTest.php', 'tests/Feature/BudgetDistributionContractTest.php', 'tests/Feature/BudgetTest.php', 'tests/Feature/BudgetReinforcementTest.php']];
|
||||
if (in_array('--order-parts-native', $argv, true)) {
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/BudgetOrderPartsContractTest.php',
|
||||
'tests/Feature/InvoiceTest.php', 'tests/Unit/PurchaseLineAmountsTest.php', 'tests/Feature/PurchaseAwardOrderTest.php',
|
||||
'--filter=BudgetOrderPartsContractTest|InvoiceTest|PurchaseLineAmountsTest|optional partial-order']];
|
||||
}
|
||||
if (in_array('--order-parts-recovery', $argv, true)) {
|
||||
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
|
||||
[PHP_BINARY, 'tests/Concurrency/budget-distribution-recovery-worker.php', $database, 'order-parts']];
|
||||
}
|
||||
if (in_array('--order-parts-concurrency', $argv, true)) {
|
||||
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
|
||||
[PHP_BINARY, 'tests/Concurrency/budget-order-parts-worker.php', $database, 'race']];
|
||||
}
|
||||
}
|
||||
if ($categoryApprovalsMode) {
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionApprovalLevelsTest.php', 'tests/Feature/RequisitionCategoriesTest.php']];
|
||||
}
|
||||
if ($savedSearchesMode) {
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/SavedProcurementSearchesTest.php', 'tests/Feature/ProcurementSearchTest.php']];
|
||||
}
|
||||
if ($categoriesMode) {
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionCategoriesTest.php', 'tests/Feature/RequisitionCatalogueTest.php', 'tests/Feature/IncompleteRequisitionDraftTest.php', 'tests/Feature/EquipmentSparePartsTest.php']];
|
||||
}
|
||||
if ($budgetDistributionMode) {
|
||||
$environment['COMMON_BUDGET_PATH'] = 'C:/laragon/www/sgf-tempo/packages/budget-control';
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/BudgetDistributionContractTest.php', 'tests/Feature/BudgetTest.php', 'tests/Feature/BudgetReinforcementTest.php', 'tests/Feature/InvoiceTest.php']];
|
||||
@@ -67,7 +97,7 @@ try {
|
||||
[PHP_BINARY, 'tests/Concurrency/budget-distribution-visual-seed.php', $database]];
|
||||
}
|
||||
if (in_array('--distribution-schema', $argv, true)) {
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/BudgetDistributionSchemaTest.php', 'tests/Feature/BudgetDistributionContractTest.php']];
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/BudgetDistributionSchemaTest.php', 'tests/Feature/BudgetDistributionDeploymentSchemaTest.php', 'tests/Feature/BudgetDistributionContractTest.php']];
|
||||
}
|
||||
}
|
||||
if ($payableInsightsMode) {
|
||||
@@ -118,7 +148,7 @@ try {
|
||||
throw new RuntimeException('Validação PostgreSQL não aprovada.');
|
||||
}
|
||||
}
|
||||
if ($conversionMode || $agreementMode || $orderLimitMode || $upgradeMode || $benchmarkMode || $draftMode || $searchMode || $productionMode || $configuredLevelsMode || $orderDocumentMode || $payableInsightsMode || $budgetDistributionMode) {
|
||||
if ($conversionMode || $agreementMode || $orderLimitMode || $upgradeMode || $benchmarkMode || $draftMode || $searchMode || $productionMode || $configuredLevelsMode || $orderDocumentMode || $payableInsightsMode || $budgetDistributionMode || $categoriesMode || $savedSearchesMode || $categoryApprovalsMode || $orderPartsMode) {
|
||||
return;
|
||||
}
|
||||
config(['database.connections.quotation_fx_proof' => [...$config, 'database' => $database, 'url' => null]]);
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Tempo\Finance\Budget\BudgetControl;
|
||||
|
||||
// No database access or business commands: exercise the host's actual pre-load verification.
|
||||
require dirname(__DIR__, 2).'/vendor/autoload.php';
|
||||
$app = require dirname(__DIR__, 2).'/bootstrap/app.php';
|
||||
try {
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
} catch (Throwable $error) {
|
||||
fwrite(STDERR, $error->getMessage().PHP_EOL);
|
||||
exit(1);
|
||||
}
|
||||
echo json_encode(['runtime' => realpath((new ReflectionClass(BudgetControl::class))->getFileName())], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
@@ -19,6 +19,7 @@ if (! $app->environment('testing') || $db->getDriverName() !== 'pgsql' || $db->g
|
||||
}
|
||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
|
||||
$orderParts = ($argv[2] ?? '') === 'order-parts';
|
||||
$f = receiptFixture();
|
||||
$author = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||
$reviewer = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Admin]);
|
||||
@@ -63,17 +64,23 @@ $preDump = $directory.'/before.dump';
|
||||
$postDump = $directory.'/after.dump';
|
||||
$pg('pg_dump', ['--format=custom', '--file='.$preDump, '--dbname='.$database]);
|
||||
budgetDistributionFixtureSchema();
|
||||
if ($orderParts) {
|
||||
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php')->up();
|
||||
}
|
||||
if ($fingerprint($db, $columns) !== $before || app(CommonBudget::class)->for($author)->balance($budget) !== $balanceBefore
|
||||
|| $db->table('budget_distributions')->exists() || $db->table('requisitions')->whereNotNull('budget_distribution_preparation')->exists()) {
|
||||
throw new RuntimeException('Optional schema changed pre-existing data or native balances.');
|
||||
}
|
||||
$prepare = new Process([PHP_BINARY, __DIR__.'/budget-distribution-worker.php', $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
|
||||
$prepare = new Process([PHP_BINARY, __DIR__.($orderParts ? '/budget-order-parts-worker.php' : '/budget-distribution-worker.php'), $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
|
||||
$prepare->mustRun();
|
||||
$input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
|
||||
$actor = User::query()->findOrFail($input['actor']);
|
||||
auth()->guard()->setUser($actor);
|
||||
$engine = app(CommonBudget::class)->for($actor);
|
||||
$engine->amendDistribution($input['origin'], $input['plan'], $input['hash'], 'Explicit synthetic amendment preserved in backup.', $input['operation']);
|
||||
$apply = static fn ($engine) => $orderParts
|
||||
? $engine->commitOrderParts($input['order'], $input['sources'], $input['operation'])
|
||||
: $engine->amendDistribution($input['origin'], $input['plan'], $input['hash'], 'Explicit synthetic amendment preserved in backup.', $input['operation']);
|
||||
$apply($engine);
|
||||
$afterColumns = [];
|
||||
foreach (array_column($db->select("select tablename from pg_tables where schemaname='public' order by tablename"), 'tablename') as $table) {
|
||||
$afterColumns[$table] = $db->getSchemaBuilder()->getColumnListing($table);
|
||||
@@ -100,8 +107,7 @@ try {
|
||||
DB::setDefaultConnection('distribution_restore');
|
||||
$restoredActor = User::query()->findOrFail($input['actor']);
|
||||
auth()->guard()->setUser($restoredActor);
|
||||
$again = app(CommonBudget::class)->for($restoredActor)->amendDistribution($input['origin'], $input['plan'], $input['hash'],
|
||||
'Explicit synthetic amendment preserved in backup.', $input['operation']);
|
||||
$again = $apply(app(CommonBudget::class)->for($restoredActor));
|
||||
if (! $again['replayed'] || $fingerprint($restored, $afterColumns) !== $after) {
|
||||
throw new RuntimeException('Recovered command was not replayed without new effects.');
|
||||
}
|
||||
@@ -122,7 +128,7 @@ try {
|
||||
if (app(CommonBudget::class)->for(auth()->user())->balance($budget) !== $balanceBefore) {
|
||||
throw new RuntimeException('Pre-extension recovery changed the native balance.');
|
||||
}
|
||||
echo json_encode(['previous_tables_preserved' => count($before), 'optional_tables' => 4, 'existing_balances_preserved' => true,
|
||||
echo json_encode(['previous_tables_preserved' => count($before), 'optional_tables' => $orderParts ? 8 : 4, 'existing_balances_preserved' => true,
|
||||
'post_extension_restore_all_tables_equal' => true, 'recovered_operation_replay_no_effects' => true, 'pre_extension_schema_data_balance_restored' => true,
|
||||
'before_dump_sha256' => hash_file('sha256', $preDump), 'after_dump_sha256' => hash_file('sha256', $postDump)], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
} finally {
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\User;
|
||||
use App\Services\CommonBudget;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
use Symfony\Component\Process\Process;
|
||||
use Tempo\Finance\Budget\BudgetControl;
|
||||
use Tempo\Finance\Budget\BudgetFailure;
|
||||
|
||||
require __DIR__.'/../../vendor/autoload.php';
|
||||
$database = $argv[1] ?? '';
|
||||
$app = require __DIR__.'/../../bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
if (! $app->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getDatabaseName() !== $database
|
||||
|| DB::connection()->getConfig('host') !== '127.0.0.1' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database)
|
||||
|| (($argv[2] ?? '') !== 'legacy' && ! method_exists(BudgetControl::class, 'commitOrderParts'))) {
|
||||
throw new LogicException('Order-part contention requires the explicit common source and disposable local QA.');
|
||||
}
|
||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
|
||||
require_once __DIR__.'/../Support/BudgetOrderPartsFixture.php';
|
||||
if (($argv[2] ?? '') === 'legacy') {
|
||||
$actor = User::query()->findOrFail((int) ($argv[3] ?? 0));
|
||||
auth()->guard()->setUser($actor);
|
||||
try {
|
||||
app(CommonBudget::class)->for($actor);
|
||||
throw new RuntimeException('The old runtime must refuse balances with partial-order effects.');
|
||||
} catch (HttpExceptionInterface $error) {
|
||||
if ($error->getStatusCode() !== 503 || method_exists(BudgetControl::class, 'commitOrderParts')) {
|
||||
throw $error;
|
||||
}
|
||||
echo json_encode(['old_runtime_rejected_before_balance' => true, 'status' => 503], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
}
|
||||
exit;
|
||||
}
|
||||
if (($argv[2] ?? '') === 'prepare') {
|
||||
$f = receiptFixture();
|
||||
$source = unissuedOrderPartsSource($f, 10000);
|
||||
$line = $source->items()->sole();
|
||||
$finance = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||
$reviewer = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Admin]);
|
||||
auth()->guard()->setUser($finance);
|
||||
$budget = app(CommonBudget::class)->for($finance)->create(['cost_center_id' => $f['r']->cost_center_id, 'year' => (int) now()->year,
|
||||
'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 10000, 'reason' => 'Synthetic partial-order contention only.']);
|
||||
auth()->guard()->setUser($reviewer);
|
||||
app(CommonBudget::class)->for($reviewer)->approve($budget);
|
||||
auth()->guard()->setUser($f['issuer']);
|
||||
$engine = app(CommonBudget::class)->for($f['issuer']);
|
||||
$lines = [$line->id => ['subtotal_minor' => 10000, 'total_minor' => 10000, 'required_kind' => 'operating']];
|
||||
$plan = [['allocation_key' => 'synthetic', 'line_id' => $line->id, 'centre_id' => $f['r']->cost_center_id, 'subtotal_minor' => 10000, 'total_minor' => 10000]];
|
||||
$engine->recordDistribution($source->id, 'reserve', $plan, $lines, str_repeat('a', 64), (string) Str::uuid());
|
||||
$award = $engine->recordDistribution($source->id, 'award', $plan, $lines, str_repeat('b', 64), (string) Str::uuid());
|
||||
echo json_encode(['tenant' => $f['tenant']->id, 'actor' => $f['issuer']->id, 'budget' => $budget, 'source' => $award['distribution_id'],
|
||||
'order' => (string) Str::uuid(), 'operation' => (string) Str::uuid(), 'sources' => [['origin' => $source->id, 'version' => 0,
|
||||
'plan_hash' => $award['plan_hash'], 'allocations' => [['allocation_key' => 'synthetic', 'subtotal_minor' => 4000, 'total_minor' => 4000]]]]], JSON_THROW_ON_ERROR);
|
||||
exit;
|
||||
}
|
||||
if (($argv[2] ?? '') === 'write') {
|
||||
$input = json_decode($argv[3], true, 32, JSON_THROW_ON_ERROR);
|
||||
DB::select('select set_config(?, ?, false)', ['application_name', 'sgc_order_parts_write_'.getmypid()]);
|
||||
$actor = User::query()->findOrFail($input['actor']);
|
||||
auth()->guard()->setUser($actor);
|
||||
try {
|
||||
$result = app(CommonBudget::class)->for($actor)->commitOrderParts($input['order'], $input['sources'], $input['operation']);
|
||||
echo json_encode(['status' => 200, 'replayed' => $result['replayed']], JSON_THROW_ON_ERROR);
|
||||
} catch (BudgetFailure $error) {
|
||||
echo json_encode(['status' => $error->status], JSON_THROW_ON_ERROR);
|
||||
} catch (HttpExceptionInterface $error) {
|
||||
echo json_encode(['status' => $error->getStatusCode()], JSON_THROW_ON_ERROR);
|
||||
}
|
||||
exit;
|
||||
}
|
||||
if (($argv[2] ?? '') !== 'race') {
|
||||
throw new InvalidArgumentException('Invalid order-part worker mode.');
|
||||
}
|
||||
budgetDistributionFixtureSchema();
|
||||
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php')->up();
|
||||
foreach (['same_operation', 'conflicting_version'] as $scenario) {
|
||||
$prepare = new Process([PHP_BINARY, __FILE__, $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
|
||||
$prepare->mustRun();
|
||||
$input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
|
||||
$workers = [];
|
||||
$db = DB::connection();
|
||||
$db->beginTransaction();
|
||||
try {
|
||||
$db->table('tenants')->where('id', $input['tenant'])->lockForUpdate()->firstOrFail();
|
||||
for ($index = 0; $index < 2; $index++) {
|
||||
if ($index === 1 && $scenario === 'conflicting_version') {
|
||||
$input['operation'] = (string) Str::uuid();
|
||||
$input['order'] = (string) Str::uuid();
|
||||
$input['sources'][0]['allocations'][0]['subtotal_minor'] = 6000;
|
||||
$input['sources'][0]['allocations'][0]['total_minor'] = 6000;
|
||||
}
|
||||
$worker = new Process([PHP_BINARY, __FILE__, $database, 'write', json_encode($input, JSON_THROW_ON_ERROR)], dirname(__DIR__, 2), timeout: 30);
|
||||
$workers[] = $worker;
|
||||
$worker->start();
|
||||
}
|
||||
$deadline = microtime(true) + 10;
|
||||
do {
|
||||
$db->select('select pg_stat_clear_snapshot()');
|
||||
$blocked = (int) $db->selectOne("select count(*) as n from pg_stat_activity where datname=? and application_name like 'sgc_order_parts_write_%' and wait_event_type='Lock'", [$database])->n;
|
||||
if ($blocked >= 2) {
|
||||
break;
|
||||
}
|
||||
usleep(50000);
|
||||
} while (microtime(true) < $deadline);
|
||||
if ($blocked < 2) {
|
||||
throw new RuntimeException('Both contenders must demonstrably wait on the company lock.');
|
||||
}
|
||||
$db->commit();
|
||||
$results = [];
|
||||
foreach ($workers as $worker) {
|
||||
$worker->wait();
|
||||
if (! $worker->isSuccessful()) {
|
||||
throw new RuntimeException($worker->getErrorOutput());
|
||||
}
|
||||
$results[] = json_decode($worker->getOutput(), true, 32, JSON_THROW_ON_ERROR);
|
||||
}
|
||||
$statuses = array_column($results, 'status');
|
||||
sort($statuses);
|
||||
$entries = $db->table('budget_distribution_entries')->where('distribution_id', $input['source']);
|
||||
$reserved = (int) (clone $entries)->sum('reserved_minor');
|
||||
$committed = (int) (clone $entries)->sum('committed_minor');
|
||||
$commands = $db->table('budget_order_commands')->where('tenant_id', $input['tenant'])->count();
|
||||
$audits = $db->table('audit_logs')->where('tenant_id', $input['tenant'])->where('action', 'budget.orders_committed')->count();
|
||||
if ($statuses !== ($scenario === 'same_operation' ? [200, 200] : [200, 409]) || $commands !== 1 || $audits !== 1
|
||||
|| $reserved + $committed !== 10000 || ! in_array($committed, [4000, 6000], true)
|
||||
|| ($scenario === 'same_operation' && count(array_filter($results, fn ($result) => $result['replayed'])) !== 1)) {
|
||||
throw new RuntimeException('Contention did not preserve one command, one audit and the exact original budget.');
|
||||
}
|
||||
echo json_encode(['scenario' => $scenario, 'statuses' => $statuses, 'blocked_writers_observed' => $blocked,
|
||||
'commands' => $commands, 'audits' => $audits, 'reserved_minor' => $reserved, 'committed_minor' => $committed], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
if ($scenario === 'same_operation') {
|
||||
$proof = json_decode(file_get_contents(base_path('docs/proofs/rq01-distribution-artifact.json')), true, 32, JSON_THROW_ON_ERROR);
|
||||
$legacy = new Process([PHP_BINARY, __FILE__, $database, 'legacy', (string) $input['actor']], dirname(__DIR__, 2),
|
||||
['COMMON_BUDGET_PATH' => base_path($proof['path'])], timeout: 30);
|
||||
$legacy->mustRun();
|
||||
echo $legacy->getOutput();
|
||||
}
|
||||
} finally {
|
||||
if ($db->transactionLevel() > 0) {
|
||||
$db->rollBack();
|
||||
}
|
||||
foreach ($workers as $worker) {
|
||||
if ($worker->isRunning()) {
|
||||
$worker->stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
|
||||
use App\Services\BudgetDistributionArtifact;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
beforeEach(function () {
|
||||
$proof = json_decode(file_get_contents(base_path('docs/proofs/rq01-distribution-artifact.json')), true, 32, JSON_THROW_ON_ERROR);
|
||||
$this->artifactDirectory = storage_path('framework/testing/distribution-integrity-'.Str::uuid());
|
||||
mkdir($this->artifactDirectory.'/src', 0700, true);
|
||||
foreach ($proof['files'] as $file => $hash) {
|
||||
copy(base_path($proof['path'].'/'.$file), $this->artifactDirectory.'/'.$file);
|
||||
}
|
||||
$this->artifactManifest = $this->artifactDirectory.'/manifest.json';
|
||||
$this->artifactData = ['files' => $proof['files']];
|
||||
file_put_contents($this->artifactManifest, json_encode($this->artifactData, JSON_THROW_ON_ERROR));
|
||||
$this->artifactPin = hash_file('sha256', $this->artifactManifest);
|
||||
});
|
||||
|
||||
afterEach(function () {
|
||||
foreach (glob($this->artifactDirectory.'/src/*') as $file) {
|
||||
unlink($file);
|
||||
}
|
||||
rmdir($this->artifactDirectory.'/src');
|
||||
foreach (glob($this->artifactDirectory.'/*') as $file) {
|
||||
unlink($file);
|
||||
}
|
||||
rmdir($this->artifactDirectory);
|
||||
});
|
||||
|
||||
test('frozen standalone budget release verifies all seven files without executing its PHP', function () {
|
||||
BudgetDistributionArtifact::verify($this->artifactDirectory, $this->artifactManifest, $this->artifactPin);
|
||||
expect(config('budget-distributions.enabled'))->toBeFalse();
|
||||
});
|
||||
|
||||
test('budget release rejects changed executable files before loading them', function (string $file) {
|
||||
file_put_contents($this->artifactDirectory.'/'.$file, "\n// changed", FILE_APPEND);
|
||||
expect(fn () => BudgetDistributionArtifact::verify($this->artifactDirectory, $this->artifactManifest, $this->artifactPin))
|
||||
->toThrow(LogicException::class, 'BUDGET_DISTRIBUTION_FILE_MISMATCH');
|
||||
})->with(['bootstrap.php', 'src/BudgetControl.php', 'src/BudgetDistributions.php', 'src/BudgetDistributionPlan.php']);
|
||||
|
||||
test('budget release rejects a changed manifest even when its replacement lists current hashes', function () {
|
||||
$this->artifactData['files']['src/BudgetControl.php'] = str_repeat('0', 64);
|
||||
file_put_contents($this->artifactManifest, json_encode($this->artifactData, JSON_THROW_ON_ERROR));
|
||||
expect(fn () => BudgetDistributionArtifact::verify($this->artifactDirectory, $this->artifactManifest, $this->artifactPin))
|
||||
->toThrow(LogicException::class, 'BUDGET_DISTRIBUTION_MANIFEST_MISMATCH');
|
||||
});
|
||||
|
||||
test('budget release rejects incomplete inventories and missing trust anchors', function () {
|
||||
unset($this->artifactData['files']['src/BudgetDistributions.php']);
|
||||
file_put_contents($this->artifactManifest, json_encode($this->artifactData, JSON_THROW_ON_ERROR));
|
||||
expect(fn () => BudgetDistributionArtifact::verify($this->artifactDirectory, $this->artifactManifest, hash_file('sha256', $this->artifactManifest)))
|
||||
->toThrow(LogicException::class, 'BUDGET_DISTRIBUTION_INVENTORY_MISMATCH')
|
||||
->and(fn () => BudgetDistributionArtifact::verify($this->artifactDirectory, $this->artifactManifest, null))
|
||||
->toThrow(LogicException::class, 'BUDGET_DISTRIBUTION_ARTIFACT_CONFIGURATION');
|
||||
});
|
||||
|
||||
test('host boots the independently pinned release and rejects changed bootstrap before it can execute', function () {
|
||||
$environment = ['APP_ENV' => 'testing', 'COMMON_BUDGET_PATH' => $this->artifactDirectory,
|
||||
'SGC_BUDGET_DISTRIBUTIONS_ENABLED' => 'true', 'SGC_BUDGET_DISTRIBUTIONS_MANIFEST' => $this->artifactManifest,
|
||||
'SGC_BUDGET_DISTRIBUTIONS_MANIFEST_SHA256' => $this->artifactPin];
|
||||
$process = new Process([PHP_BINARY, base_path('tests/Concurrency/budget-distribution-artifact-boot.php')], base_path(), $environment, timeout: 30);
|
||||
$process->run();
|
||||
expect($process->isSuccessful())->toBeTrue();
|
||||
$result = json_decode(trim($process->getOutput()), true, 32, JSON_THROW_ON_ERROR);
|
||||
expect($result['runtime'])->toBe(realpath($this->artifactDirectory.'/src/BudgetControl.php'));
|
||||
file_put_contents($this->artifactDirectory.'/bootstrap.php', '<?php file_put_contents(__DIR__."/executed", "yes");');
|
||||
$process->run();
|
||||
expect($process->isSuccessful())->toBeFalse()
|
||||
->and($process->getOutput().$process->getErrorOutput())->toContain('BUDGET_DISTRIBUTION_FILE_MISMATCH')
|
||||
->and(file_exists($this->artifactDirectory.'/executed'))->toBeFalse();
|
||||
});
|
||||
@@ -63,6 +63,26 @@ test('explicit optional contract composition loads the selected standalone sourc
|
||||
->and(realpath((new ReflectionClass(BudgetControl::class))->getFileName()))->toBe(realpath($selected.'/src/BudgetControl.php'));
|
||||
});
|
||||
|
||||
test('prepared deployment capability verifies the selected standalone artifact outside QA and remains disabled by default', function () {
|
||||
$proofPath = base_path('docs/proofs/rq01-distribution-artifact.json');
|
||||
$proof = json_decode(file_get_contents($proofPath), true, 32, JSON_THROW_ON_ERROR);
|
||||
// Only the process which already loaded the frozen artifact can enable this composition.
|
||||
$selected = realpath((new ReflectionClass(BudgetControl::class))->getFileName());
|
||||
$artifact = base_path($proof['path']);
|
||||
config(['budget-distributions.qa_enabled' => false, 'budget-distributions.enabled' => false]);
|
||||
app()->instance('env', 'local');
|
||||
try {
|
||||
expect(app(RequisitionBudgetDistributions::class)->ready())->toBeFalse();
|
||||
config(['budget-distributions.enabled' => true, 'budget-distributions.artifact_manifest' => $proofPath,
|
||||
'budget-distributions.artifact_manifest_sha256' => hash_file('sha256', $proofPath), 'common-budget.path' => $artifact]);
|
||||
expect(app(RequisitionBudgetDistributions::class)->ready())->toBe($selected === realpath($artifact.'/src/BudgetControl.php'));
|
||||
config(['budget-distributions.artifact_manifest_sha256' => str_repeat('0', 64)]);
|
||||
expect(fn () => app(RequisitionBudgetDistributions::class)->ready())->toThrow(LogicException::class, 'BUDGET_DISTRIBUTION_MANIFEST_MISMATCH');
|
||||
} finally {
|
||||
app()->instance('env', 'testing');
|
||||
}
|
||||
});
|
||||
|
||||
function distributionInvoice(object $test, string $number, int $net, int $gross): Invoice
|
||||
{
|
||||
return Invoice::query()->create(['tenant_id' => $test->author->tenant_id, 'purchase_order_id' => $test->f['order']->id,
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||
|
||||
test('staged pilot schema refuses missing installer scope without changing requisitions', function () {
|
||||
receiptFixture();
|
||||
$migration = require database_path('deployment-migrations/2026_11_22_000004_create_budget_distributions.php');
|
||||
expect(fn () => $migration->up())->toThrow(LogicException::class)
|
||||
->and(Schema::hasColumn('requisitions', 'budget_distribution_preparation'))->toBeFalse();
|
||||
});
|
||||
|
||||
test('local preparation uses the same schema definition and preserves previous records under its exact scope', function () {
|
||||
if (DB::getDriverName() !== 'pgsql') {
|
||||
$this->markTestSkipped('Exact native identity is checked on isolated PostgreSQL.');
|
||||
}
|
||||
receiptFixture();
|
||||
$columns = Schema::getColumnListing('requisitions');
|
||||
$before = DB::table('requisitions')->select($columns)->get()->toJson();
|
||||
config(['budget-distributions.schema_installation' => ['database' => DB::connection()->getDatabaseName(), 'username' => DB::connection()->getConfig('username')]]);
|
||||
$migration = require database_path('deployment-migrations/2026_11_22_000004_create_budget_distributions.php');
|
||||
app()->instance('env', 'local');
|
||||
try {
|
||||
$migration->up();
|
||||
} finally {
|
||||
app()->instance('env', 'testing');
|
||||
}
|
||||
expect(DB::table('requisitions')->select($columns)->get()->toJson())->toBe($before)
|
||||
->and(DB::table('budget_distributions')->count())->toBe(0)
|
||||
->and(DB::table('requisitions')->whereNotNull('budget_distribution_preparation')->count())->toBe(0)
|
||||
->and(fn () => $migration->down())->toThrow(LogicException::class);
|
||||
});
|
||||
|
||||
test('staged pilot schema refuses an incorrect target and operational production environment', function () {
|
||||
receiptFixture();
|
||||
config(['budget-distributions.schema_installation' => ['database' => 'different_database', 'username' => DB::connection()->getConfig('username')]]);
|
||||
$migration = require database_path('deployment-migrations/2026_11_22_000004_create_budget_distributions.php');
|
||||
expect(fn () => $migration->up())->toThrow(LogicException::class);
|
||||
app()->instance('env', 'production');
|
||||
try {
|
||||
expect(fn () => $migration->up())->toThrow(LogicException::class)
|
||||
->and(Schema::hasColumn('requisitions', 'budget_distribution_preparation'))->toBeFalse();
|
||||
} finally {
|
||||
app()->instance('env', 'testing');
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,366 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\Invoice;
|
||||
use App\Models\PurchaseOrder;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\User;
|
||||
use App\Services\CommonBudget;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
use Tempo\Finance\Budget\BudgetControl;
|
||||
use Tempo\Finance\Budget\BudgetFailure;
|
||||
|
||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
|
||||
require_once __DIR__.'/../Support/BudgetOrderPartsFixture.php';
|
||||
|
||||
beforeEach(function () {
|
||||
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
|
||||
$this->markTestSkipped('Select the explicitly authorized unpublished common source for isolated QA.');
|
||||
}
|
||||
$this->f = receiptFixture();
|
||||
budgetDistributionFixtureSchema();
|
||||
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php')->up();
|
||||
$this->finance = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||
$this->reviewer = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Admin]);
|
||||
$this->actingAs($this->finance);
|
||||
$this->budget = app(CommonBudget::class)->for($this->finance)->create(['cost_center_id' => $this->f['r']->cost_center_id,
|
||||
'year' => (int) now()->year, 'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 100000,
|
||||
'reason' => 'Dotação exclusivamente sintética para ordens parciais.']);
|
||||
$this->actingAs($this->reviewer);
|
||||
app(CommonBudget::class)->for($this->reviewer)->approve($this->budget);
|
||||
$this->actingAs($this->f['issuer']);
|
||||
});
|
||||
|
||||
/** Synthetic financial source contract; deliberately not a claim of native purchase issuance. */
|
||||
function orderPartsSource(object $test, int $amount, string $allocation = 'same-key'): array
|
||||
{
|
||||
$source = unissuedOrderPartsSource($test->f, $amount);
|
||||
$line = $source->items()->sole();
|
||||
$lines = [$line->id => ['subtotal_minor' => $amount, 'total_minor' => $amount, 'required_kind' => 'operating']];
|
||||
$plan = [['allocation_key' => $allocation, 'line_id' => $line->id, 'centre_id' => $test->f['r']->cost_center_id, 'subtotal_minor' => $amount, 'total_minor' => $amount]];
|
||||
$control = app(CommonBudget::class)->for($test->f['issuer']);
|
||||
$control->recordDistribution($source->id, 'reserve', $plan, $lines, str_repeat('a', 64), (string) Str::uuid());
|
||||
$award = $control->recordDistribution($source->id, 'award', $plan, $lines, str_repeat('b', 64), (string) Str::uuid());
|
||||
|
||||
return ['origin' => $source->id, 'version' => 0, 'plan_hash' => $award['plan_hash'],
|
||||
'allocations' => [['allocation_key' => $allocation, 'subtotal_minor' => $amount, 'total_minor' => $amount]]];
|
||||
}
|
||||
|
||||
function orderPartsAmount(array $source, int $amount, int $version): array
|
||||
{
|
||||
$source['version'] = $version;
|
||||
$source['allocations'][0]['subtotal_minor'] = $amount;
|
||||
$source['allocations'][0]['total_minor'] = $amount;
|
||||
|
||||
return $source;
|
||||
}
|
||||
|
||||
function orderPartsInvoice(object $test, int $amount): Invoice
|
||||
{
|
||||
return Invoice::query()->create(['tenant_id' => $test->finance->tenant_id, 'purchase_order_id' => $test->f['order']->id,
|
||||
'supplier_id' => $test->f['order']->supplier_id, 'created_by' => $test->finance->id, 'number' => 'QA-PARTS-'.Str::random(12),
|
||||
'issued_on' => today(), 'status' => 'pending', 'subtotal_minor' => $amount, 'tax_minor' => 0, 'total_minor' => $amount,
|
||||
'snapshot' => ['synthetic_contract_fixture' => true]]);
|
||||
}
|
||||
|
||||
function orderPartsBalance(object $test): array
|
||||
{
|
||||
$test->actingAs($test->finance);
|
||||
$balance = app(CommonBudget::class)->for($test->finance)->balance($test->budget);
|
||||
$test->actingAs($test->f['issuer']);
|
||||
|
||||
return $balance;
|
||||
}
|
||||
|
||||
test('one approved synthetic source commits forty then sixty without committing the unissued portion', function () {
|
||||
$source = orderPartsSource($this, 10000);
|
||||
$order = (string) Str::uuid();
|
||||
$operation = (string) Str::uuid();
|
||||
$input = [orderPartsAmount($source, 4000, 0)];
|
||||
$control = app(CommonBudget::class)->for($this->f['issuer']);
|
||||
expect($control->commitOrderParts($order, $input, $operation)['replayed'])->toBeFalse();
|
||||
expect(orderPartsBalance($this))->toMatchArray(['reserved_minor' => 6000, 'committed_minor' => 4000, 'consumed_minor' => 0, 'available_minor' => 90000]);
|
||||
expect($control->commitOrderParts($order, $input, $operation)['replayed'])->toBeTrue();
|
||||
$control->commitOrderParts((string) Str::uuid(), [orderPartsAmount($source, 6000, 1)], (string) Str::uuid());
|
||||
expect(orderPartsBalance($this))->toMatchArray(['reserved_minor' => 0, 'committed_minor' => 10000, 'consumed_minor' => 0]);
|
||||
expect(DB::table('budget_order_commands')->count())->toBe(2)->and(DB::table('budget_order_bindings')->count())->toBe(2)
|
||||
->and(Requisition::query()->findOrFail($source['origin'])->status)->toBe('approved');
|
||||
});
|
||||
|
||||
test('two origins keep identical allocation keys separate and consume one invoice atomically', function () {
|
||||
$a = orderPartsSource($this, 10000);
|
||||
$b = orderPartsSource($this, 20000);
|
||||
$order = (string) Str::uuid();
|
||||
app(CommonBudget::class)->for($this->f['issuer'])->commitOrderParts($order, [$b, $a], (string) Str::uuid());
|
||||
$this->actingAs($this->finance);
|
||||
$invoice = orderPartsInvoice($this, 15000);
|
||||
$input = [orderPartsAmount($a, 5000, 1), orderPartsAmount($b, 10000, 1)];
|
||||
foreach ($input as &$source) {
|
||||
$source['allocations'][0]['order_key'] = $order;
|
||||
}
|
||||
unset($source);
|
||||
$operation = (string) Str::uuid();
|
||||
$control = app(CommonBudget::class)->for($this->finance);
|
||||
$control->checkOrderPartsConsumption($input);
|
||||
expect(DB::table('budget_order_consumptions')->count())->toBe(0);
|
||||
$result = $control->consumeOrderParts($invoice->id, $input, $operation);
|
||||
expect($result['replayed'])->toBeFalse()->and($control->consumeOrderParts($invoice->id, array_reverse($input), $operation)['replayed'])->toBeTrue();
|
||||
expect(DB::table('budget_order_consumptions')->count())->toBe(2)->and(Invoice::query()->whereKey($invoice->id)->count())->toBe(1)
|
||||
->and(DB::table('budget_consumptions')->where('invoice_id', $invoice->id)->count())->toBe(0);
|
||||
expect(orderPartsBalance($this))->toMatchArray(['reserved_minor' => 0, 'committed_minor' => 15000, 'consumed_minor' => 15000, 'available_minor' => 70000]);
|
||||
});
|
||||
|
||||
test('one bad source rejects the complete order before effects, phase or versions change', function () {
|
||||
$a = orderPartsSource($this, 10000);
|
||||
$b = orderPartsSource($this, 20000);
|
||||
$bad = orderPartsAmount($b, 20001, 0);
|
||||
$before = DB::table('budget_distribution_entries')->count();
|
||||
expect(fn () => app(CommonBudget::class)->for($this->f['issuer'])->commitOrderParts((string) Str::uuid(), [$a, $bad], (string) Str::uuid()))->toThrow(BudgetFailure::class);
|
||||
expect(DB::table('budget_order_commands')->count())->toBe(0)->and(DB::table('budget_order_bindings')->count())->toBe(0)
|
||||
->and(DB::table('budget_distribution_entries')->count())->toBe($before)
|
||||
->and(DB::table('budget_distributions')->where('phase', 'award')->count())->toBe(2);
|
||||
});
|
||||
|
||||
test('stale versions and changed replay amounts cannot issue another part', function () {
|
||||
$source = orderPartsSource($this, 10000);
|
||||
$order = (string) Str::uuid();
|
||||
$key = (string) Str::uuid();
|
||||
$control = app(CommonBudget::class)->for($this->f['issuer']);
|
||||
$control->commitOrderParts($order, [orderPartsAmount($source, 4000, 0)], $key);
|
||||
expect(fn () => $control->commitOrderParts((string) Str::uuid(), [orderPartsAmount($source, 6000, 0)], (string) Str::uuid()))->toThrow(BudgetFailure::class)
|
||||
->and(fn () => $control->commitOrderParts($order, [orderPartsAmount($source, 4001, 0)], $key))->toThrow(BudgetFailure::class);
|
||||
expect(DB::table('budget_order_commands')->count())->toBe(1);
|
||||
});
|
||||
|
||||
test('one invoice may consume two parts of the same source with one journal effect per allocation', function () {
|
||||
$source = orderPartsSource($this, 10000);
|
||||
$first = (string) Str::uuid();
|
||||
$second = (string) Str::uuid();
|
||||
$control = app(CommonBudget::class)->for($this->f['issuer']);
|
||||
$control->commitOrderParts($first, [orderPartsAmount($source, 4000, 0)], (string) Str::uuid());
|
||||
$control->commitOrderParts($second, [orderPartsAmount($source, 6000, 1)], (string) Str::uuid());
|
||||
$input = orderPartsAmount($source, 2000, 2);
|
||||
$input['allocations'][0]['order_key'] = $first;
|
||||
$input['allocations'][] = ['allocation_key' => 'same-key', 'order_key' => $second, 'subtotal_minor' => 3000, 'total_minor' => 3000];
|
||||
$this->actingAs($this->finance);
|
||||
$invoice = orderPartsInvoice($this, 5000);
|
||||
app(CommonBudget::class)->for($this->finance)->consumeOrderParts($invoice->id, [$input], (string) Str::uuid());
|
||||
expect(DB::table('budget_order_consumptions')->where('invoice_id', $invoice->id)->count())->toBe(2)
|
||||
->and(DB::table('budget_distribution_entries')->where('kind', 'like', 'order-invoice-%')->count())->toBe(1);
|
||||
expect(orderPartsBalance($this))->toMatchArray(['committed_minor' => 5000, 'consumed_minor' => 5000]);
|
||||
});
|
||||
|
||||
test('cancellation releases only its unconsumed issued part and never replenishes issuance capacity', function () {
|
||||
$source = orderPartsSource($this, 10000);
|
||||
$order = (string) Str::uuid();
|
||||
$control = app(CommonBudget::class)->for($this->f['issuer']);
|
||||
$control->commitOrderParts($order, [orderPartsAmount($source, 4000, 0)], (string) Str::uuid());
|
||||
$key = (string) Str::uuid();
|
||||
$input = [orderPartsAmount($source, 4000, 1)];
|
||||
expect($control->cancelOrderParts($order, $input, $key)['replayed'])->toBeFalse()
|
||||
->and($control->cancelOrderParts($order, $input, $key)['replayed'])->toBeTrue();
|
||||
expect(orderPartsBalance($this))->toMatchArray(['reserved_minor' => 6000, 'committed_minor' => 0, 'available_minor' => 94000]);
|
||||
expect(fn () => $control->commitOrderParts((string) Str::uuid(), [orderPartsAmount($source, 6001, 2)], (string) Str::uuid()))->toThrow(BudgetFailure::class);
|
||||
$control->commitOrderParts((string) Str::uuid(), [orderPartsAmount($source, 6000, 2)], (string) Str::uuid());
|
||||
expect(orderPartsBalance($this))->toMatchArray(['reserved_minor' => 0, 'committed_minor' => 6000]);
|
||||
});
|
||||
|
||||
test('consumed orders reject cancellation and over-consumption without changing the invoice effect', function () {
|
||||
$source = orderPartsSource($this, 10000);
|
||||
$order = (string) Str::uuid();
|
||||
app(CommonBudget::class)->for($this->f['issuer'])->commitOrderParts($order, [$source], (string) Str::uuid());
|
||||
$this->actingAs($this->finance);
|
||||
$input = orderPartsAmount($source, 5000, 1);
|
||||
$input['allocations'][0]['order_key'] = $order;
|
||||
$invoice = orderPartsInvoice($this, 5000);
|
||||
app(CommonBudget::class)->for($this->finance)->consumeOrderParts($invoice->id, [$input], (string) Str::uuid());
|
||||
$next = orderPartsAmount($source, 5001, 2);
|
||||
$next['allocations'][0]['order_key'] = $order;
|
||||
expect(fn () => app(CommonBudget::class)->for($this->finance)->consumeOrderParts(orderPartsInvoice($this, 5001)->id, [$next], (string) Str::uuid()))->toThrow(BudgetFailure::class);
|
||||
$this->actingAs($this->f['issuer']);
|
||||
expect(fn () => app(CommonBudget::class)->for($this->f['issuer'])->cancelOrderParts($order, [orderPartsAmount($source, 10000, 2)], (string) Str::uuid()))->toThrow(BudgetFailure::class);
|
||||
expect(orderPartsBalance($this))->toMatchArray(['committed_minor' => 5000, 'consumed_minor' => 5000]);
|
||||
});
|
||||
|
||||
test('mutating order commands require the current procurement actor and consuming requires Finance', function () {
|
||||
$source = orderPartsSource($this, 10000);
|
||||
$order = (string) Str::uuid();
|
||||
$this->actingAs($this->finance);
|
||||
expect(fn () => app(CommonBudget::class)->for($this->finance)->commitOrderParts($order, [$source], (string) Str::uuid()))->toThrow(HttpException::class);
|
||||
$this->actingAs($this->f['issuer']);
|
||||
app(CommonBudget::class)->for($this->f['issuer'])->commitOrderParts($order, [$source], (string) Str::uuid());
|
||||
$input = orderPartsAmount($source, 100, 1);
|
||||
$input['allocations'][0]['order_key'] = $order;
|
||||
expect(fn () => app(CommonBudget::class)->for($this->f['issuer'])->checkOrderPartsConsumption([$input]))->toThrow(HttpException::class);
|
||||
});
|
||||
|
||||
test('invalid shapes, duplicate sources and empty parts fail before a command is recorded', function () {
|
||||
$source = orderPartsSource($this, 10000);
|
||||
$control = app(CommonBudget::class)->for($this->f['issuer']);
|
||||
foreach ([[], [$source, $source], [orderPartsAmount($source, -1, 0)], [[...$source, 'version' => '0']], [[...$source, 'origin' => -1]]] as $input) {
|
||||
expect(fn () => $control->commitOrderParts((string) Str::uuid(), $input, (string) Str::uuid()))->toThrow(BudgetFailure::class);
|
||||
}
|
||||
expect(DB::table('budget_order_commands')->count())->toBe(0)->and(orderPartsBalance($this)['reserved_minor'])->toBe(10000);
|
||||
});
|
||||
|
||||
test('an explicit zero-cent native rounding remainder retains lineage without inventing another cent', function () {
|
||||
$source = orderPartsSource($this, 1);
|
||||
$first = (string) Str::uuid();
|
||||
$remainder = (string) Str::uuid();
|
||||
$control = app(CommonBudget::class)->for($this->f['issuer']);
|
||||
$control->commitOrderParts($first, [$source], (string) Str::uuid());
|
||||
$control->commitOrderParts($remainder, [orderPartsAmount($source, 0, 1)], (string) Str::uuid());
|
||||
$this->actingAs($this->finance);
|
||||
$invoice = orderPartsInvoice($this, 0);
|
||||
$input = orderPartsAmount($source, 0, 2);
|
||||
$input['allocations'][0]['order_key'] = $remainder;
|
||||
app(CommonBudget::class)->for($this->finance)->consumeOrderParts($invoice->id, [$input], (string) Str::uuid());
|
||||
expect(DB::table('budget_order_consumptions')->where('invoice_id', $invoice->id)->value('amount_minor'))->toBe(0)
|
||||
->and(orderPartsBalance($this))->toMatchArray(['reserved_minor' => 0, 'committed_minor' => 1, 'consumed_minor' => 0, 'available_minor' => 99999]);
|
||||
});
|
||||
|
||||
test('bad invoice allocation rolls back every origin and an unconsumed cancelled order cannot be invoiced', function () {
|
||||
$a = orderPartsSource($this, 10000);
|
||||
$b = orderPartsSource($this, 20000);
|
||||
$order = (string) Str::uuid();
|
||||
$control = app(CommonBudget::class)->for($this->f['issuer']);
|
||||
$control->commitOrderParts($order, [$a, $b], (string) Str::uuid());
|
||||
$this->actingAs($this->finance);
|
||||
$input = [orderPartsAmount($a, 5000, 1), orderPartsAmount($b, 20001, 1)];
|
||||
foreach ($input as &$source) {
|
||||
$source['allocations'][0]['order_key'] = $order;
|
||||
}
|
||||
unset($source);
|
||||
$invoice = orderPartsInvoice($this, 25001);
|
||||
expect(fn () => app(CommonBudget::class)->for($this->finance)->consumeOrderParts($invoice->id, $input, (string) Str::uuid()))->toThrow(BudgetFailure::class);
|
||||
expect(DB::table('budget_order_consumptions')->count())->toBe(0)->and(DB::table('budget_order_commands')->count())->toBe(1);
|
||||
$this->actingAs($this->f['issuer']);
|
||||
$control->cancelOrderParts($order, [orderPartsAmount($a, 10000, 1), orderPartsAmount($b, 20000, 1)], (string) Str::uuid());
|
||||
$this->actingAs($this->finance);
|
||||
$cancelled = orderPartsAmount($a, 100, 2);
|
||||
$cancelled['allocations'][0]['order_key'] = $order;
|
||||
expect(fn () => app(CommonBudget::class)->for($this->finance)->checkOrderPartsConsumption([$cancelled]))->toThrow(BudgetFailure::class);
|
||||
expect(orderPartsBalance($this))->toMatchArray(['reserved_minor' => 0, 'committed_minor' => 0, 'consumed_minor' => 0, 'available_minor' => 100000]);
|
||||
});
|
||||
|
||||
test('operation identifiers cannot cross V1 and partial order contracts', function () {
|
||||
$source = orderPartsSource($this, 10000);
|
||||
$control = app(CommonBudget::class)->for($this->f['issuer']);
|
||||
$oldOperation = DB::table('budget_distribution_events')->value('operation_key');
|
||||
expect(fn () => $control->commitOrderParts((string) Str::uuid(), [$source], $oldOperation))->toThrow(BudgetFailure::class);
|
||||
$operation = (string) Str::uuid();
|
||||
$control->commitOrderParts((string) Str::uuid(), [orderPartsAmount($source, 4000, 0)], $operation);
|
||||
$line = Requisition::query()->findOrFail($source['origin'])->items()->sole();
|
||||
$lines = [$line->id => ['subtotal_minor' => 10000, 'total_minor' => 10000, 'required_kind' => 'operating']];
|
||||
$plan = [['allocation_key' => 'same-key', 'line_id' => $line->id, 'centre_id' => $this->f['r']->cost_center_id, 'subtotal_minor' => 10000, 'total_minor' => 10000]];
|
||||
expect(fn () => $control->recordDistribution($source['origin'], 'commit', $plan, $lines, str_repeat('b', 64), $operation))->toThrow(BudgetFailure::class)
|
||||
->and(fn () => $control->recordDistribution($source['origin'], 'commit', $plan, $lines, str_repeat('b', 64), (string) Str::uuid()))->toThrow(BudgetFailure::class);
|
||||
expect(orderPartsBalance($this))->toMatchArray(['reserved_minor' => 6000, 'committed_minor' => 4000]);
|
||||
});
|
||||
|
||||
test('a complete order command is invisible and unusable from another company', function () {
|
||||
$source = orderPartsSource($this, 10000);
|
||||
$other = receiptFixture();
|
||||
$this->actingAs($other['issuer']);
|
||||
expect(fn () => app(CommonBudget::class)->for($other['issuer'])->commitOrderParts((string) Str::uuid(), [$source], (string) Str::uuid()))->toThrow(BudgetFailure::class);
|
||||
expect(DB::table('budget_order_commands')->count())->toBe(0);
|
||||
});
|
||||
|
||||
test('legacy consumption cannot consume an invoice already used by an order-part command', function () {
|
||||
$source = orderPartsSource($this, 10000);
|
||||
$order = (string) Str::uuid();
|
||||
app(CommonBudget::class)->for($this->f['issuer'])->commitOrderParts($order, [$source], (string) Str::uuid());
|
||||
$this->actingAs($this->finance);
|
||||
$invoice = orderPartsInvoice($this, 5000);
|
||||
$input = orderPartsAmount($source, 5000, 1);
|
||||
$input['allocations'][0]['order_key'] = $order;
|
||||
$control = app(CommonBudget::class)->for($this->finance);
|
||||
$control->consumeOrderParts($invoice->id, [$input], (string) Str::uuid());
|
||||
expect(fn () => $control->consume($this->f['r']->id, $invoice->id, 5000, 5000))->toThrow(BudgetFailure::class);
|
||||
expect(DB::table('budget_consumptions')->count())->toBe(0)->and(DB::table('budget_order_consumptions')->count())->toBe(1);
|
||||
});
|
||||
|
||||
test('explicit adoption preserves all old entries and the exact balance before partial issuance', function () {
|
||||
$control = app(CommonBudget::class)->for($this->f['issuer']);
|
||||
$request = unissuedOrderPartsSource($this->f, 10000);
|
||||
$origin = $request->id;
|
||||
$centre = $this->f['r']->cost_center_id;
|
||||
$line = $request->items()->sole();
|
||||
expect(PurchaseOrder::query()->where('requisition_id', $origin)->exists())->toBeFalse();
|
||||
$control->record($origin, $centre, 'operating', 'reserve', 10000, 10000);
|
||||
$control->record($origin, $centre, 'operating', 'award', 10000, 10000);
|
||||
$original = DB::table('budget_entries')->where('requisition_id', $origin)->orderBy('id')->get()->toArray();
|
||||
$before = orderPartsBalance($this);
|
||||
$lines = [$line->id => ['subtotal_minor' => 10000, 'total_minor' => 10000, 'required_kind' => 'operating']];
|
||||
$plan = [['allocation_key' => 'native-line', 'line_id' => $line->id, 'centre_id' => $centre, 'subtotal_minor' => 10000, 'total_minor' => 10000]];
|
||||
$key = (string) Str::uuid();
|
||||
$adopt = $control->adoptOrderSource($origin, $plan, $lines, str_repeat('b', 64), $key);
|
||||
expect($adopt['replayed'])->toBeFalse()
|
||||
->and($control->adoptOrderSource($origin, $plan, $lines, str_repeat('b', 64), $key)['replayed'])->toBeTrue()
|
||||
->and(orderPartsBalance($this))->toBe($before)
|
||||
->and(DB::table('budget_entries')->where('requisition_id', $origin)->orderBy('id')->limit(2)->get()->toArray())->toEqual($original)
|
||||
->and(DB::table('budget_entries')->where('kind', 'order-adoption')->count())->toBe(1);
|
||||
$input = ['origin' => $origin, 'version' => 0, 'plan_hash' => $adopt['plan_hash'],
|
||||
'allocations' => [['allocation_key' => 'native-line', 'subtotal_minor' => 4000, 'total_minor' => 4000]]];
|
||||
$control->commitOrderParts((string) Str::uuid(), [$input], (string) Str::uuid());
|
||||
expect(orderPartsBalance($this))->toMatchArray(['reserved_minor' => 6000, 'committed_minor' => 4000])
|
||||
->and(fn () => $control->record($origin, $centre, 'operating', 'commit', 10000, 10000))->toThrow(BudgetFailure::class);
|
||||
});
|
||||
|
||||
test('adoption rejects a changed amount and an already committed source without compensating values', function () {
|
||||
$control = app(CommonBudget::class)->for($this->f['issuer']);
|
||||
$request = unissuedOrderPartsSource($this->f, 10000);
|
||||
$origin = $request->id;
|
||||
$centre = $this->f['r']->cost_center_id;
|
||||
$line = $request->items()->sole();
|
||||
$control->record($origin, $centre, 'operating', 'reserve', 10000, 10000);
|
||||
$control->record($origin, $centre, 'operating', 'award', 10000, 10000);
|
||||
$lines = [$line->id => ['subtotal_minor' => 9999, 'total_minor' => 9999, 'required_kind' => 'operating']];
|
||||
$plan = [['allocation_key' => 'native-line', 'line_id' => $line->id, 'centre_id' => $centre, 'subtotal_minor' => 9999, 'total_minor' => 9999]];
|
||||
expect(fn () => $control->adoptOrderSource($origin, $plan, $lines, str_repeat('b', 64), (string) Str::uuid()))->toThrow(BudgetFailure::class);
|
||||
$control->record($origin, $centre, 'operating', 'commit', 10000, 10000);
|
||||
$lines[$line->id]['subtotal_minor'] = $lines[$line->id]['total_minor'] = 10000;
|
||||
$plan[0]['subtotal_minor'] = $plan[0]['total_minor'] = 10000;
|
||||
expect(fn () => $control->adoptOrderSource($origin, $plan, $lines, str_repeat('b', 64), (string) Str::uuid()))->toThrow(BudgetFailure::class);
|
||||
expect(DB::table('budget_order_commands')->count())->toBe(0)->and(DB::table('budget_distributions')->count())->toBe(0)
|
||||
->and(orderPartsBalance($this))->toMatchArray(['reserved_minor' => 0, 'committed_minor' => 10000]);
|
||||
});
|
||||
|
||||
test('order-part schema cannot be installed in an operational environment or silently reinstalled', function () {
|
||||
$migration = require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php';
|
||||
expect(fn () => $migration->up())->toThrow(LogicException::class);
|
||||
app()->instance('env', 'production');
|
||||
try {
|
||||
expect(fn () => $migration->up())->toThrow(LogicException::class, 'guarded disposable QA')
|
||||
->and(fn () => $migration->down())->toThrow(LogicException::class);
|
||||
} finally {
|
||||
app()->instance('env', 'testing');
|
||||
}
|
||||
});
|
||||
|
||||
test('PostgreSQL rejects mutation or deletion of each partial-order history table', function () {
|
||||
if (DB::getDriverName() !== 'pgsql') {
|
||||
$this->markTestSkipped('PostgreSQL append-only triggers require the disposable PostgreSQL run.');
|
||||
}
|
||||
$source = orderPartsSource($this, 10000);
|
||||
$order = (string) Str::uuid();
|
||||
app(CommonBudget::class)->for($this->f['issuer'])->commitOrderParts($order, [$source], (string) Str::uuid());
|
||||
$this->actingAs($this->finance);
|
||||
$invoice = orderPartsInvoice($this, 5000);
|
||||
$input = orderPartsAmount($source, 5000, 1);
|
||||
$input['allocations'][0]['order_key'] = $order;
|
||||
app(CommonBudget::class)->for($this->finance)->consumeOrderParts($invoice->id, [$input], (string) Str::uuid());
|
||||
foreach (['budget_order_commands', 'budget_order_bindings', 'budget_order_allocations', 'budget_order_consumptions'] as $table) {
|
||||
$row = DB::table($table)->orderBy('id')->first();
|
||||
expect($row)->not->toBeNull();
|
||||
expect(fn () => DB::transaction(fn () => DB::table($table)->where('id', $row->id)->update(['tenant_id' => $row->tenant_id])))
|
||||
->toThrow(QueryException::class);
|
||||
expect(fn () => DB::transaction(fn () => DB::table($table)->where('id', $row->id)->delete()))
|
||||
->toThrow(QueryException::class);
|
||||
expect(DB::table($table)->where('id', $row->id)->first())->toEqual($row);
|
||||
}
|
||||
});
|
||||
@@ -133,7 +133,9 @@ test('equipment integration block separates native purchase requests from actual
|
||||
|
||||
test('equipment integration block preserves department and native requisition visibility with tenant isolation', function () {
|
||||
$this->withoutVite();
|
||||
$request = app(RequisitionWorkflow::class)->save($this->f['receiver'], equipmentRequestData($this->f));
|
||||
// An existing equipment association belongs to a spare-part purchase, not a new capital asset.
|
||||
$request = app(RequisitionWorkflow::class)->save($this->f['receiver'], equipmentRequestData($this->f, 'spare_part'));
|
||||
expect($request->items()->sole()->purchase_type)->toBe('spare_part')->and($request->items()->sole()->equipment_id)->toBe($this->f['asset']->id);
|
||||
$this->actingAs($this->f['finance'])->get('/equipamentos/'.$this->f['asset']->id)->assertOk()->assertInertia(fn (Assert $p) => $p->where('purchases.total', 1));
|
||||
$otherDepartment = Department::query()->create(['tenant_id' => $this->f['tenant']->id, 'name' => 'Outra área']);
|
||||
$request->update(['department_id' => $otherDepartment->id]);
|
||||
@@ -150,7 +152,7 @@ test('equipment integration block keeps old purchase and movement pages independ
|
||||
$this->withoutVite();
|
||||
app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $this->f['order'], receiptPayload($this->f));
|
||||
foreach (range(1, 16) as $index) {
|
||||
app(RequisitionWorkflow::class)->save($this->f['receiver'], equipmentRequestData($this->f));
|
||||
app(RequisitionWorkflow::class)->save($this->f['receiver'], equipmentRequestData($this->f, 'spare_part'));
|
||||
app(StockWorkflow::class)->record($this->f['receiver'], ['kind' => 'issue', 'reference' => 'EQ-PAGE-'.$index, 'idempotency_key' => (string) Str::uuid(),
|
||||
'responsible_id' => $this->f['receiver']->id, 'warehouse_id' => $this->f['warehouse']->id, 'stock_item_id' => $this->f['stock']->id, 'equipment_id' => $this->f['asset']->id,
|
||||
'quantity' => '0.001', 'reason' => 'Saída física nativa para paginação.']);
|
||||
|
||||
@@ -10,6 +10,17 @@ use Inertia\Testing\AssertableInertia as Assert;
|
||||
|
||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||
|
||||
afterEach(function () {
|
||||
if ($this->committedDraftReportFixture ?? false) {
|
||||
if (! app()->environment('testing') || DB::getDriverName() !== 'pgsql'
|
||||
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 0) {
|
||||
throw new LogicException('Draft report cleanup requires the disposable PostgreSQL database.');
|
||||
}
|
||||
DB::statement('DROP SCHEMA public CASCADE');
|
||||
DB::statement('CREATE SCHEMA public');
|
||||
}
|
||||
});
|
||||
|
||||
beforeEach(function () {
|
||||
$this->f = receiptFixture();
|
||||
$this->actingAs($this->f['issuer']);
|
||||
@@ -38,6 +49,13 @@ test('incomplete draft persists unknown values without invented amounts and cann
|
||||
$this->get('/requisicoes/'.$r->id.'/editar')->assertInertia(fn (Assert $page) => $page->where('incompleteDraftsAvailable', true)->where('requisition.draft_input.values.justification', 'Ini'));
|
||||
$this->get('/requisicoes/'.$r->id)->assertOk()->assertInertia(fn (Assert $page) => $page->where('requisition.total_minor', null));
|
||||
$this->get('/requisicoes/'.$r->id.'/processo')->assertOk();
|
||||
if (DB::getDriverName() === 'pgsql') {
|
||||
if (! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 1) {
|
||||
throw new LogicException('Commit only the isolated synthetic draft before the native read-only report transaction.');
|
||||
}
|
||||
DB::commit();
|
||||
$this->committedDraftReportFixture = true;
|
||||
}
|
||||
$this->get('/relatorios?search='.$r->number)->assertOk()->assertInertia(fn (Assert $page) => $page->where('records.data.0.total_minor', null));
|
||||
$this->postJson('/requisicoes/'.$r->id.'/submeter')->assertUnprocessable();
|
||||
expect($r->fresh()->status)->toBe('draft')->and(DB::table('budget_entries')->count())->toBe($entries);
|
||||
|
||||
@@ -37,12 +37,14 @@ use App\Services\EquipmentWorkflow;
|
||||
use App\Services\FormalAdmission;
|
||||
use App\Services\OrderCancellationPolicyWorkflow;
|
||||
use App\Services\OrderCancellationWorkflow;
|
||||
use App\Services\OrderPartsPreparation;
|
||||
use App\Services\ProcurementReviewCsv;
|
||||
use App\Services\ProcurementReviewReport;
|
||||
use App\Services\ProposalComparison;
|
||||
use App\Services\ProposalOpeningWorkflow;
|
||||
use App\Services\PurchaseControlPolicyWorkflow;
|
||||
use App\Services\PurchaseRevisionWorkflow;
|
||||
use App\Services\PurchaseWorkflow;
|
||||
use App\Services\QuotationExchange;
|
||||
use App\Services\RequisitionBudgetDistributions;
|
||||
use App\Services\RequisitionCatalogue;
|
||||
@@ -1349,3 +1351,84 @@ test('quotation tasks hand a ready comparison to adjudication without reopening
|
||||
$this->actingAs($this->buyer)->get('/requisicoes/tarefas?module=purchases')->assertInertia(fn (Assert $page) => $page->where('tasks.total', 0));
|
||||
$this->get('/requisicoes/'.$this->r->id.'/cotacoes')->assertInertia(fn (Assert $page) => $page->where('canCreate', false)->where('canEvaluate', false));
|
||||
});
|
||||
|
||||
test('optional partial-order preparation reuses native final approvals and preserves all documents and financial effects', function () {
|
||||
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
|
||||
$this->markTestSkipped('Explicit unpublished common source required.');
|
||||
}
|
||||
config(['order-parts.qa_enabled' => true]);
|
||||
$award = selectPurchaseAward($this);
|
||||
$service = app(OrderPartsPreparation::class);
|
||||
$input = ['sources' => [['award_id' => $award->id, 'items' => [['quotation_item_id' => $this->quotes[0]->items()->sole()->id, 'quantity' => '0.400']]]]];
|
||||
$this->actingAs($this->buyer);
|
||||
expect(fn () => $service->prepare($this->buyer, $input))->toThrow(HttpException::class);
|
||||
approvePurchaseAward($this, $award);
|
||||
$this->actingAs($this->buyer);
|
||||
$before = [PurchaseOrder::query()->count(), DB::table('budget_entries')->count(), DB::table('audit_logs')->count()];
|
||||
$result = $service->prepare($this->buyer, $input);
|
||||
expect($result)->toMatchArray(['currency' => 'MZN', 'subtotal_minor' => 4000, 'tax_minor' => 0, 'total_minor' => 4000, 'issued' => false, 'budget_effects' => false])
|
||||
->and($result['sources'][0]['items'][0]['quantity_offset_milli'])->toBe(0)
|
||||
->and($service->prepare($this->buyer, $input)['fingerprint'])->toBe($result['fingerprint'])
|
||||
->and([PurchaseOrder::query()->count(), DB::table('budget_entries')->count(), DB::table('audit_logs')->count()])->toBe($before);
|
||||
$this->actingAs($this->finance);
|
||||
expect(fn () => $service->prepare($this->finance, $input))->toThrow(HttpException::class);
|
||||
$this->actingAs($this->buyer);
|
||||
$bad = $input;
|
||||
$bad['sources'][0]['items'][0]['quantity'] = '1.001';
|
||||
expect(fn () => $service->prepare($this->buyer, $bad))->toThrow(ValidationException::class);
|
||||
config(['order-parts.qa_enabled' => false]);
|
||||
expect(fn () => $service->prepare($this->buyer, $input))->toThrow(HttpException::class);
|
||||
config(['order-parts.qa_enabled' => true]);
|
||||
$this->post('/adjudicacoes/'.$award->id.'/emitir')->assertSessionHasNoErrors();
|
||||
expect(fn () => $service->prepare($this->buyer, $input))->toThrow(ValidationException::class);
|
||||
});
|
||||
|
||||
test('optional partial-order preparation consolidates two independently approved native origins without issuing or averaging data', function () {
|
||||
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
|
||||
$this->markTestSkipped('Explicit unpublished common source required.');
|
||||
}
|
||||
config(['order-parts.qa_enabled' => true]);
|
||||
$first = selectPurchaseAward($this);
|
||||
approvePurchaseAward($this, $first);
|
||||
$this->actingAs($this->buyer);
|
||||
$secondRequest = $this->r->fresh()->replicate();
|
||||
$secondRequest->number = 'REQ-ORDER-SECOND-QA';
|
||||
$secondRequest->subtotal_minor = $secondRequest->total_minor = 20000;
|
||||
$secondRequest->save();
|
||||
$line = $this->item->replicate();
|
||||
$line->requisition_id = $secondRequest->id;
|
||||
$line->unit_price_minor = $line->subtotal_minor = $line->total_minor = 20000;
|
||||
$line->save();
|
||||
foreach ($this->r->steps()->get() as $step) {
|
||||
$copy = $step->replicate();
|
||||
$copy->requisition_id = $secondRequest->id;
|
||||
$copy->save();
|
||||
}
|
||||
$quotes = [];
|
||||
foreach ($this->suppliers as $index => $supplier) {
|
||||
$this->actingAs($this->buyer)->post('/requisicoes/'.$secondRequest->id.'/cotacoes', ['supplier_id' => $supplier->id,
|
||||
'reference' => 'PROP-SECOND-'.$index, 'delivery_days' => 5, 'valid_until' => now()->addMonth()->format('Y-m-d'),
|
||||
'payment_terms' => '30 dias', 'no_conflict' => true, 'items' => [['requisition_item_id' => $line->id, 'unit_price' => (string) (200 + $index * 100)]]])->assertSessionHasNoErrors();
|
||||
$quote = Quotation::query()->where('requisition_id', $secondRequest->id)->latest('id')->firstOrFail();
|
||||
$quotes[] = $quote;
|
||||
foreach ([$this->buyer, $this->finance] as $evaluator) {
|
||||
$this->actingAs($evaluator)->post('/cotacoes/'.$quote->id.'/avaliar', ['quality' => '8', 'history' => '5', 'payment' => '8',
|
||||
'comment' => 'Independent synthetic evaluation for second origin.', 'no_conflict' => true])->assertSessionHasNoErrors();
|
||||
}
|
||||
}
|
||||
$this->actingAs($this->buyer);
|
||||
$second = app(PurchaseWorkflow::class)->select($this->buyer, $secondRequest, [...$this->selection, 'quotation_id' => $quotes[0]->id]);
|
||||
approvePurchaseAward($this, $second);
|
||||
$this->actingAs($this->buyer);
|
||||
$before = [PurchaseOrder::query()->count(), DB::table('budget_entries')->count(), DB::table('audit_logs')->count()];
|
||||
$input = ['sources' => [
|
||||
['award_id' => $second->id, 'items' => [['quotation_item_id' => $quotes[0]->items()->sole()->id, 'quantity' => '0.500']]],
|
||||
['award_id' => $first->id, 'items' => [['quotation_item_id' => $this->quotes[0]->items()->sole()->id, 'quantity' => '0.400']]],
|
||||
]];
|
||||
$result = app(OrderPartsPreparation::class)->prepare($this->buyer, $input);
|
||||
expect($result)->toMatchArray(['currency' => 'MZN', 'total_minor' => 14000, 'issued' => false, 'budget_effects' => false])
|
||||
->and($result['sources'])->toHaveCount(2)
|
||||
->and(array_column($result['sources'], 'requisition_id'))->toBe([$this->r->id, $secondRequest->id])
|
||||
->and(array_column($result['sources'], 'exchange_basis'))->toBe([null, null])
|
||||
->and([PurchaseOrder::query()->count(), DB::table('budget_entries')->count(), DB::table('audit_logs')->count()])->toBe($before);
|
||||
});
|
||||
|
||||
@@ -148,6 +148,47 @@ test('conditions use exact amount category and cost centre and current rules do
|
||||
expect($r->fresh()->status)->toBe('approved');
|
||||
});
|
||||
|
||||
test('explicit RQ01 category conditions combine with native filters and remain frozen through the full approval journey', function () {
|
||||
$this->plan['levels'] = [$this->plan['levels'][0]];
|
||||
$this->plan['levels'][0] += ['procurement_categories' => ['office_equipment']];
|
||||
$this->plan['levels'][0]['categories'] = ['Material'];
|
||||
$this->plan['levels'][0]['min_amount'] = '116.00';
|
||||
$this->plan['levels'][0]['cost_center_ids'] = [(string) $this->f['r']->cost_center_id];
|
||||
$this->body['items'][0] += ['procurement_category' => 'office_equipment', 'category_reason' => 'Artigo sintético de escritório fora do catálogo.'];
|
||||
$matched = submitConfiguredRequest($this);
|
||||
expect($matched->steps()->count())->toBe(4)
|
||||
->and($matched->approval_snapshot['additional_levels']['configured_1']['procurement_categories'])->toBe(['office_equipment']);
|
||||
$next = $this->body;
|
||||
$next['operation_key'] = (string) Str::uuid();
|
||||
$next['items'][0]['procurement_category'] = 'other';
|
||||
$this->postJson('/requisicoes', $next)->assertRedirect();
|
||||
$different = Requisition::query()->latest('id')->firstOrFail();
|
||||
$this->postJson('/requisicoes/'.$different->id.'/submeter', ['operation_key' => (string) Str::uuid(), 'process_version' => 1])->assertRedirect();
|
||||
expect($different->steps()->count())->toBe(3);
|
||||
$snapshot = $matched->approval_snapshot;
|
||||
$this->postJson('/administracao/parametrizacao/approval_levels', [...$this->plan, 'version' => 2, 'enabled' => false])->assertRedirect();
|
||||
expect($matched->fresh()->approval_snapshot)->toBe($snapshot);
|
||||
foreach ([$this->head, $this->buyer, $this->financier, $this->approvers[0]] as $actor) {
|
||||
configuredDecision($this, $actor, $matched);
|
||||
}
|
||||
expect($matched->fresh()->status)->toBe('approved');
|
||||
});
|
||||
|
||||
test('RQ01 filtered plans refuse an absent classification schema instead of dropping a required approval', function () {
|
||||
$this->plan['levels'] = [$this->plan['levels'][0] + ['procurement_categories' => ['office_equipment']]];
|
||||
$this->postJson('/administracao/parametrizacao/approval_levels', $this->plan)->assertRedirect();
|
||||
$this->body['items'][0] += ['procurement_category' => 'office_equipment', 'category_reason' => 'Artigo sintético de escritório fora do catálogo.'];
|
||||
$this->postJson('/requisicoes', $this->body)->assertRedirect();
|
||||
$request = Requisition::query()->latest('id')->firstOrFail();
|
||||
$policy = $this->f['tenant']->fresh()->requisition_approval_policy;
|
||||
DB::getSchemaBuilder()->table('requisition_items', fn ($table) => $table->dropColumn('category_context'));
|
||||
$this->postJson('/requisicoes/'.$request->id.'/submeter', ['operation_key' => (string) Str::uuid(), 'process_version' => 1])->assertServiceUnavailable();
|
||||
$this->postJson('/administracao/parametrizacao/approval_levels', [...$this->plan, 'version' => 2])->assertUnprocessable();
|
||||
expect($request->fresh()->status)->toBe('draft')->and($request->steps()->count())->toBe(0)
|
||||
->and(DB::table('budget_entries')->where('requisition_id', $request->id)->count())->toBe(0)
|
||||
->and($this->f['tenant']->fresh()->requisition_approval_policy)->toBe($policy);
|
||||
});
|
||||
|
||||
test('revoked membership and expired maintenance do not approve or expose assigned requests and repeated identity cannot decide two stages', function () {
|
||||
$r = submitConfiguredRequest($this);
|
||||
foreach ([$this->head, $this->buyer, $this->financier] as $actor) {
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\User;
|
||||
use App\Services\EquipmentWorkflow;
|
||||
use App\Services\RequisitionCatalogue;
|
||||
use App\Services\RequisitionWorkflow;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||
|
||||
beforeEach(function () {
|
||||
$this->f = receiptFixture();
|
||||
$this->author = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Requester]);
|
||||
$this->actingAs($this->author);
|
||||
$this->payload = ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $this->f['r']->cost_center_id, 'priority' => 'normal',
|
||||
'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Pedido sintético para classificação explícita.',
|
||||
'items' => [['description' => 'Material sintético', 'category' => 'Categoria anterior', 'purchase_type' => 'consumable',
|
||||
'quantity' => '2.000', 'unit' => 'cx', 'unit_price' => '10.00', 'tax_rate' => '16.00']]];
|
||||
});
|
||||
|
||||
test('office classification and its explicit text justification persist through the native HTTP workflow and audit', function () {
|
||||
$this->payload['items'][0] += ['procurement_category' => 'office_equipment', 'category_reason' => 'Artigo de escritório ainda sem entrada no catálogo.'];
|
||||
$this->postJson('/requisicoes', $this->payload)->assertRedirect();
|
||||
$request = Requisition::query()->where('requester_id', $this->author->id)->sole();
|
||||
$line = $request->items()->sole();
|
||||
expect($request->draft_input)->toBeNull()->and($line->category)->toBe('Categoria anterior')
|
||||
->and($line->category_context)->toBe(['version' => 1, 'category' => 'office_equipment', 'reason' => $this->payload['items'][0]['category_reason']])
|
||||
->and($request->total_minor)->toBe(2320)
|
||||
->and(DB::table('budget_entries')->where('requisition_id', $request->id)->count())->toBe(0);
|
||||
$event = DB::table('audit_logs')->where('requisition_id', $request->id)->where('action', 'requisition.created')->sole();
|
||||
expect($event)->not->toBeNull();
|
||||
});
|
||||
|
||||
test('unfinished category requirements are saved as an incomplete draft and cannot reserve or submit', function () {
|
||||
$this->payload['items'][0]['procurement_category'] = 'office_equipment';
|
||||
$request = app(RequisitionWorkflow::class)->save($this->author, $this->payload);
|
||||
expect($request->draft_input['incomplete'])->toBeTrue()->and($request->items()->count())->toBe(0)
|
||||
->and($request->draft_input['values']['items'][0]['procurement_category'])->toBe('office_equipment');
|
||||
$this->postJson('/requisicoes/'.$request->id.'/submeter', ['operation_key' => (string) Str::uuid(), 'process_version' => $request->process_version])->assertUnprocessable();
|
||||
expect($request->fresh()->status)->toBe('draft')->and(DB::table('budget_entries')->where('requisition_id', $request->id)->count())->toBe(0);
|
||||
});
|
||||
|
||||
test('production inputs use the native published stock catalogue and retain its authoritative descriptors', function () {
|
||||
$stock = $this->f['stock']->fresh();
|
||||
$this->actingAs($this->f['receiver']);
|
||||
app(RequisitionCatalogue::class)->save($this->f['receiver'], $stock->id, ['version' => 0, 'stock_basis' => app(RequisitionCatalogue::class)->basis($stock),
|
||||
'category' => 'Material catalogado', 'purchase_type' => 'consumable', 'published' => true, 'reason' => 'Publicação sintética para a classificação.']);
|
||||
$entry = DB::table('requisition_catalogue')->where('stock_item_id', $stock->id)->sole();
|
||||
$this->actingAs($this->author);
|
||||
$this->payload['items'] = [['catalogue_entry_id' => $entry->id, 'catalogue_version' => $entry->version, 'procurement_category' => 'production_input',
|
||||
'quantity' => '2.000', 'unit_price' => '10.00', 'tax_rate' => '16.00']];
|
||||
$request = app(RequisitionWorkflow::class)->save($this->author, $this->payload);
|
||||
expect($request->draft_input)->toBeNull()->and($request->items()->sole()->category_context['category'])->toBe('production_input')
|
||||
->and($request->items()->sole()->catalogue_snapshot['stock_item_id'])->toBe($stock->id)
|
||||
->and($request->items()->sole()->category)->toBe('Material catalogado');
|
||||
});
|
||||
|
||||
test('unclassified legacy lines remain unchanged and adding an empty context preserves the accepted technical basis', function () {
|
||||
$request = app(RequisitionWorkflow::class)->save($this->author, $this->payload);
|
||||
expect($request->items()->sole()->category_context)->toBeNull();
|
||||
$withEmptyColumn = app(EquipmentWorkflow::class)->basis($request);
|
||||
Schema::table('requisition_items', fn ($table) => $table->dropColumn('category_context'));
|
||||
expect(app(EquipmentWorkflow::class)->basis($request->fresh()))->toBe($withEmptyColumn);
|
||||
$migration = require database_path('migrations/2026_11_22_000005_add_requisition_category_context.php');
|
||||
$migration->up();
|
||||
expect(app(EquipmentWorkflow::class)->basis($request->fresh()))->toBe($withEmptyColumn)
|
||||
->and(fn () => $migration->down())->toThrow(LogicException::class);
|
||||
});
|
||||
|
||||
test('unknown classification and a missing schema are rejected without silently discarding inputs', function () {
|
||||
$this->payload['items'][0]['procurement_category'] = 'unknown';
|
||||
$this->postJson('/requisicoes', $this->payload)->assertUnprocessable();
|
||||
Schema::table('requisition_items', fn ($table) => $table->dropColumn('category_context'));
|
||||
$this->payload['items'][0]['procurement_category'] = 'office_equipment';
|
||||
$this->payload['items'][0]['category_reason'] = 'Razão explícita de texto livre.';
|
||||
$this->postJson('/requisicoes', $this->payload)->assertUnprocessable();
|
||||
expect(Requisition::query()->where('requester_id', $this->author->id)->count())->toBe(0);
|
||||
});
|
||||
|
||||
test('capital classification retains the native equipment controls and requires an explicit investment reason', function () {
|
||||
$this->payload['items'][0] += ['procurement_category' => 'capital_equipment', 'category_reason' => 'Investimento sintético para ampliar a capacidade.', 'production_area' => 'Área sintética'];
|
||||
$this->payload['items'][0]['purchase_type'] = 'equipment';
|
||||
$request = app(RequisitionWorkflow::class)->save($this->author, $this->payload);
|
||||
expect($request->draft_input)->toBeNull()->and($request->items()->sole()->purchase_type)->toBe('equipment')
|
||||
->and($request->items()->sole()->category_context['category'])->toBe('capital_equipment');
|
||||
$this->postJson('/requisicoes/'.$request->id.'/submeter', ['operation_key' => (string) Str::uuid(), 'process_version' => $request->process_version])->assertUnprocessable();
|
||||
expect($request->fresh()->status)->toBe('draft');
|
||||
});
|
||||
|
||||
test('an older client preserves the exact classification by native line identity and only an explicit clear removes it', function () {
|
||||
$this->payload['items'][0] += ['procurement_category' => 'office_equipment', 'category_reason' => 'Necessidade sintética sem entrada no catálogo.'];
|
||||
$request = app(RequisitionWorkflow::class)->save($this->author, $this->payload);
|
||||
$original = $request->items()->sole()->category_context;
|
||||
$this->payload['items'][0]['source_line_id'] = $request->items()->sole()->id;
|
||||
unset($this->payload['items'][0]['procurement_category'], $this->payload['items'][0]['category_reason']);
|
||||
$this->payload['operation_key'] = (string) Str::uuid();
|
||||
$this->payload['process_version'] = $request->process_version;
|
||||
$saved = app(RequisitionWorkflow::class)->save($this->author, $this->payload, $request);
|
||||
expect($saved->items()->sole()->category_context)->toBe($original);
|
||||
$this->payload['items'][0] += ['procurement_category' => '', 'category_reason' => ''];
|
||||
$this->payload['operation_key'] = (string) Str::uuid();
|
||||
$this->payload['process_version'] = $saved->process_version;
|
||||
$saved = app(RequisitionWorkflow::class)->save($this->author, $this->payload, $saved);
|
||||
expect($saved->items()->sole()->category_context)->toBeNull();
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
|
||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||
|
||||
beforeEach(function () {
|
||||
$this->withoutVite();
|
||||
$this->f = receiptFixture();
|
||||
$this->actingAs($this->f['issuer']);
|
||||
$this->body = ['name' => 'Necessidades da área', 'term' => 'QA-NEED', 'q' => 'QA-NEED'];
|
||||
});
|
||||
|
||||
test('saved criteria are private encrypted metadata and repeated creation preserves a single preference', function () {
|
||||
foreach ([1, 2] as $attempt) {
|
||||
$this->postJson('/compras/pesquisas-guardadas', $this->body + ['tenant_id' => 999, 'user_id' => 999])->assertRedirect();
|
||||
}
|
||||
$row = DB::table('procurement_saved_searches')->sole();
|
||||
expect($row->tenant_id)->toBe($this->f['tenant']->id)->and($row->user_id)->toBe($this->f['issuer']->id)->and($row->version)->toBe(1);
|
||||
$this->get('/compras/pesquisa?q=QA-NEED')->assertInertia(fn (Assert $page) => $page->has('savedSearches.active', 1)
|
||||
->where('savedSearches.active.0.name', $this->body['name'])->missing('savedSearches.active.0.user_id')->missing('savedSearches.active.0.results'));
|
||||
$this->get('/compras/pesquisa')->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true);
|
||||
});
|
||||
|
||||
test('opening saved criteria reruns the current native query instead of caching results or granting access', function () {
|
||||
$this->f['r']->update(['number' => 'QA-NEED-ONE']);
|
||||
$this->postJson('/compras/pesquisas-guardadas', $this->body)->assertRedirect();
|
||||
$href = '/compras/pesquisa?q=QA-NEED';
|
||||
$this->get($href)->assertInertia(fn (Assert $page) => $page->where('groups.0.records.total', 1));
|
||||
$this->f['r']->update(['number' => 'CHANGED-SOURCE']);
|
||||
$this->get($href)->assertInertia(fn (Assert $page) => $page->where('groups.0.records.total', 0)->has('savedSearches.active', 1));
|
||||
$other = receiptFixture();
|
||||
$this->actingAs($other['issuer'])->get($href)->assertInertia(fn (Assert $page) => $page->where('groups.0.records.total', 0)->has('savedSearches.active', 0));
|
||||
});
|
||||
|
||||
test('rename archive and restore preserve explicit versions criteria and all business records', function () {
|
||||
$this->postJson('/compras/pesquisas-guardadas', $this->body)->assertRedirect();
|
||||
$row = DB::table('procurement_saved_searches')->sole();
|
||||
$before = [];
|
||||
foreach (['requisitions', 'audit_logs', 'budget_entries', 'stock_movements'] as $table) {
|
||||
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
|
||||
}
|
||||
$path = '/compras/pesquisas-guardadas/'.$row->id;
|
||||
$this->putJson($path, ['version' => 1, 'name' => 'Nome revisto', 'term' => 'Texto revisto', 'q' => 'QA'])->assertRedirect();
|
||||
$this->postJson($path.'/arquivar', ['version' => 1])->assertConflict();
|
||||
$this->postJson($path.'/arquivar', ['version' => 2, 'q' => 'QA'])->assertRedirect();
|
||||
$this->get('/compras/pesquisa?q=QA')->assertInertia(fn (Assert $page) => $page->has('savedSearches.active', 0)
|
||||
->where('savedSearches.archived.total', 1)->where('savedSearches.archived.data.0.term', 'Texto revisto'));
|
||||
$this->postJson($path.'/restaurar', ['version' => 3])->assertRedirect();
|
||||
expect(DB::table('procurement_saved_searches')->sole()->version)->toBe(4)
|
||||
->and(DB::table('procurement_saved_searches')->sole()->archived_at)->toBeNull();
|
||||
foreach ($before as $table => $snapshot) {
|
||||
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($snapshot);
|
||||
}
|
||||
});
|
||||
|
||||
test('another user or company cannot read or mutate guessed preference identifiers', function () {
|
||||
$this->postJson('/compras/pesquisas-guardadas', $this->body)->assertRedirect();
|
||||
$id = DB::table('procurement_saved_searches')->sole()->id;
|
||||
$colleague = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Requester]);
|
||||
$foreign = receiptFixture();
|
||||
foreach ([$colleague, $foreign['issuer']] as $actor) {
|
||||
$this->actingAs($actor)->get('/compras/pesquisa')->assertInertia(fn (Assert $page) => $page->has('savedSearches.active', 0));
|
||||
$this->putJson('/compras/pesquisas-guardadas/'.$id, $this->body + ['version' => 1])->assertNotFound();
|
||||
$this->postJson('/compras/pesquisas-guardadas/'.$id.'/arquivar', ['version' => 1])->assertNotFound();
|
||||
}
|
||||
expect(DB::table('procurement_saved_searches')->sole()->version)->toBe(1);
|
||||
});
|
||||
|
||||
test('active names are unique per user and restoring a colliding archived name never overwrites either record', function () {
|
||||
$this->postJson('/compras/pesquisas-guardadas', $this->body)->assertRedirect();
|
||||
$id = DB::table('procurement_saved_searches')->sole()->id;
|
||||
$this->postJson('/compras/pesquisas-guardadas', [...$this->body, 'term' => 'OTHER'])->assertUnprocessable();
|
||||
$this->postJson('/compras/pesquisas-guardadas/'.$id.'/arquivar', ['version' => 1])->assertRedirect();
|
||||
$this->postJson('/compras/pesquisas-guardadas', [...$this->body, 'term' => 'OTHER'])->assertRedirect();
|
||||
$this->postJson('/compras/pesquisas-guardadas/'.$id.'/restaurar', ['version' => 2])->assertUnprocessable();
|
||||
expect(DB::table('procurement_saved_searches')->whereNotNull('archived_at')->sole()->term)->toBe('QA-NEED')
|
||||
->and(DB::table('procurement_saved_searches')->whereNull('archived_at')->sole()->term)->toBe('OTHER');
|
||||
});
|
||||
|
||||
test('query links encode criteria as local text and invalid or unavailable storage never silently discards them', function () {
|
||||
$term = 'https://example.invalid/?x=%_&q=<script>';
|
||||
$this->postJson('/compras/pesquisas-guardadas', [...$this->body, 'term' => $term])->assertRedirect();
|
||||
$response = $this->get('/compras/pesquisa')->assertOk();
|
||||
$page = $response->viewData('page');
|
||||
$href = $page['props']['savedSearches']['active'][0]['href'];
|
||||
expect(str_starts_with($href, '/compras/pesquisa?'))->toBeTrue();
|
||||
parse_str(parse_url($href, PHP_URL_QUERY), $query);
|
||||
expect($query['q'])->toBe($term);
|
||||
$this->postJson('/compras/pesquisas-guardadas', ['name' => ' ', 'term' => ' '])->assertUnprocessable();
|
||||
Schema::drop('procurement_saved_searches');
|
||||
$this->get('/compras/pesquisa')->assertInertia(fn (Assert $page) => $page->where('savedSearches', null));
|
||||
$this->postJson('/compras/pesquisas-guardadas', $this->body)->assertServiceUnavailable();
|
||||
});
|
||||
|
||||
test('revoked native access is checked again before preference changes or live search exposure', function () {
|
||||
$this->postJson('/compras/pesquisas-guardadas', $this->body)->assertRedirect();
|
||||
$id = DB::table('procurement_saved_searches')->sole()->id;
|
||||
// This security field is deliberately not mass assignable on User.
|
||||
DB::table('users')->where('tenant_id', $this->f['tenant']->id)->where('id', $this->f['issuer']->id)->update(['purchasing_role' => PurchasingRole::Configured->value]);
|
||||
expect(User::query()->findOrFail($this->f['issuer']->id)->purchasing_role)->toBe(PurchasingRole::Configured);
|
||||
$this->get('/compras/pesquisa')->assertForbidden();
|
||||
$this->postJson('/compras/pesquisas-guardadas/'.$id.'/arquivar', ['version' => 1])->assertForbidden();
|
||||
expect(DB::table('procurement_saved_searches')->sole()->archived_at)->toBeNull();
|
||||
});
|
||||
|
||||
test('active capacity and archived pagination preserve older criteria instead of deleting or overwriting them', function () {
|
||||
foreach (range(1, 50) as $number) {
|
||||
DB::table('procurement_saved_searches')->insert(['tenant_id' => $this->f['tenant']->id, 'user_id' => $this->f['issuer']->id,
|
||||
'name' => 'Sintética '.$number, 'term' => 'QA-'.$number, 'active_name_key' => hash('sha256', 'sintética '.$number),
|
||||
'version' => 1, 'created_at' => now(), 'updated_at' => now()]);
|
||||
}
|
||||
$this->postJson('/compras/pesquisas-guardadas', $this->body)->assertUnprocessable();
|
||||
foreach (DB::table('procurement_saved_searches')->orderBy('id')->limit(11)->get() as $row) {
|
||||
$this->postJson('/compras/pesquisas-guardadas/'.$row->id.'/arquivar', ['version' => 1])->assertRedirect();
|
||||
}
|
||||
$this->postJson('/compras/pesquisas-guardadas', $this->body)->assertRedirect();
|
||||
$this->get('/compras/pesquisa?archived_page=2')->assertInertia(fn (Assert $page) => $page->has('savedSearches.active', 40)
|
||||
->where('savedSearches.archived.total', 11)->has('savedSearches.archived.data', 1));
|
||||
expect(DB::table('procurement_saved_searches')->count())->toBe(51);
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
use App\Models\Requisition;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/** Financial-contract fixture, without an issued native order. Not a native approval execution. */
|
||||
function unissuedOrderPartsSource(array $fixture, int $amount): Requisition
|
||||
{
|
||||
$db = DB::connection();
|
||||
$isolated = ($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|
||||
|| ($db->getDriverName() === 'pgsql' && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName()));
|
||||
if (! app()->environment('testing') || ! $isolated || $amount < 0) {
|
||||
throw new LogicException('Unissued order fixtures require isolated synthetic QA.');
|
||||
}
|
||||
$source = $fixture['r']->replicate();
|
||||
$source->number = 'REQ-PARTS-'.Str::random(12);
|
||||
$source->subtotal_minor = $source->total_minor = $amount;
|
||||
$source->tax_minor = 0;
|
||||
$source->save();
|
||||
$line = $fixture['r']->items()->firstOrFail()->replicate();
|
||||
$line->requisition_id = $source->id;
|
||||
$line->quantity = '1.000';
|
||||
$line->unit_price_minor = $line->subtotal_minor = $line->total_minor = $amount;
|
||||
$line->tax_rate = '0.00';
|
||||
$line->tax_minor = 0;
|
||||
$line->save();
|
||||
|
||||
return $source;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
use App\Services\PurchaseLineAmounts;
|
||||
|
||||
test('successive native portions preserve the original line price and VAT exactly', function () {
|
||||
$first = PurchaseLineAmounts::portion(223, '16.00', 0, 400);
|
||||
$second = PurchaseLineAmounts::portion(223, '16.00', 400, 600);
|
||||
$third = PurchaseLineAmounts::portion(223, '16.00', 1000, 700);
|
||||
expect($first)->toBe(['subtotal_minor' => 89, 'tax_minor' => 14, 'total_minor' => 103])
|
||||
->and($second)->toBe(['subtotal_minor' => 134, 'tax_minor' => 22, 'total_minor' => 156])
|
||||
->and($third)->toBe(['subtotal_minor' => 156, 'tax_minor' => 25, 'total_minor' => 181])
|
||||
->and($first['total_minor'] + $second['total_minor'] + $third['total_minor'])->toBe(440);
|
||||
});
|
||||
|
||||
test('a half-cent remainder is not rounded again when the original quantity offset is retained', function () {
|
||||
expect(PurchaseLineAmounts::portion(1, '0', 0, 500))->toBe(['subtotal_minor' => 1, 'tax_minor' => 0, 'total_minor' => 1])
|
||||
->and(PurchaseLineAmounts::portion(1, '0', 500, 500))->toBe(['subtotal_minor' => 0, 'tax_minor' => 0, 'total_minor' => 0]);
|
||||
});
|
||||
|
||||
test('invalid cumulative bases are refused without truncation or floating arithmetic', function (int $price, string $tax, int $before, int $quantity) {
|
||||
expect(fn () => PurchaseLineAmounts::portion($price, $tax, $before, $quantity))->toThrow(InvalidArgumentException::class);
|
||||
})->with([[-1, '0', 0, 1], [1, '-1', 0, 1], [1, '0', -1, 1], [1, '0', 0, 0], [1, '0', PHP_INT_MAX, 1]]);
|
||||
@@ -4,7 +4,7 @@ import { expect, test } from 'vitest';
|
||||
import { RequisitionApprovalSettings } from '@/components/requisition-approval-settings';
|
||||
import { procurementNavigation } from '@/lib/procurement-navigation';
|
||||
|
||||
function render(ready: boolean) {
|
||||
function render(ready: boolean, categoryOptions: Record<string, string> = {}) {
|
||||
return renderToStaticMarkup(
|
||||
<App
|
||||
initialComponent={RequisitionApprovalSettings}
|
||||
@@ -17,6 +17,7 @@ function render(ready: boolean) {
|
||||
props: {
|
||||
errors: {},
|
||||
ready,
|
||||
categoryOptions,
|
||||
version: 4,
|
||||
profiles: [
|
||||
{
|
||||
@@ -42,6 +43,13 @@ function render(ready: boolean) {
|
||||
scope: 'company',
|
||||
min_minor: 11601,
|
||||
categories: ['Material'],
|
||||
...(Object.keys(categoryOptions).length
|
||||
? {
|
||||
procurement_categories: [
|
||||
'office_equipment',
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
cost_center_ids: [1],
|
||||
},
|
||||
],
|
||||
@@ -52,6 +60,24 @@ function render(ready: boolean) {
|
||||
);
|
||||
}
|
||||
|
||||
test('explicit RQ01 group conditions are separate from original article categories and remain hidden until available', () => {
|
||||
const html = render(true, {
|
||||
office_equipment: 'Equipamento de escritório',
|
||||
capital_equipment: 'Maquinaria',
|
||||
});
|
||||
expect(html).toContain('Categoria da necessidade (RQ-01)');
|
||||
expect(html).toContain('Categorias exactas do artigo');
|
||||
expect(html).toContain('Equipamento de escritório');
|
||||
expect(html).toContain('Maquinaria');
|
||||
expect(html).toContain('não são classificados automaticamente');
|
||||
const groups = html.slice(
|
||||
html.indexOf('Categoria da necessidade (RQ-01)'),
|
||||
html.indexOf('Perfis elegíveis'),
|
||||
);
|
||||
expect(groups).toContain('checked=""');
|
||||
expect(render(true)).not.toContain('Categoria da necessidade (RQ-01)');
|
||||
});
|
||||
|
||||
test('approval settings retain exact threshold and selected revoked profiles so the administrator can reconcile the plan', () => {
|
||||
const html = render(true);
|
||||
expect(html).toContain('116.01');
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { expect, test } from 'vitest';
|
||||
import {
|
||||
RequisitionCategoryFields,
|
||||
requisitionCategoryLabels,
|
||||
} from '@/components/requisition-category-fields';
|
||||
|
||||
test('classification fields explain the native controls and preserve the explicit investment reason', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<RequisitionCategoryFields
|
||||
index={2}
|
||||
category="capital_equipment"
|
||||
reason="Investimento deliberado"
|
||||
options={requisitionCategoryLabels}
|
||||
onChange={() => {}}
|
||||
/>,
|
||||
);
|
||||
expect(html).toContain('Justificação do investimento');
|
||||
expect(html).toContain('Investimento deliberado');
|
||||
expect(html).toContain('orçamento de investimento');
|
||||
expect(html).toContain('aria-describedby="rq-category-2-help"');
|
||||
expect(html).toContain('Peças sobressalentes');
|
||||
});
|
||||
|
||||
test('legacy classification stays unselected and production guidance requires the published stock catalogue', () => {
|
||||
const legacy = renderToStaticMarkup(
|
||||
<RequisitionCategoryFields
|
||||
index={0}
|
||||
category=""
|
||||
reason=""
|
||||
options={requisitionCategoryLabels}
|
||||
onChange={() => {}}
|
||||
/>,
|
||||
);
|
||||
expect(legacy).toContain('Sem classificação adicional');
|
||||
expect(legacy).toContain('não é inferida');
|
||||
expect(legacy).not.toContain('<textarea');
|
||||
const production = renderToStaticMarkup(
|
||||
<RequisitionCategoryFields
|
||||
index={1}
|
||||
category="production_input"
|
||||
reason=""
|
||||
options={requisitionCategoryLabels}
|
||||
onChange={() => {}}
|
||||
/>,
|
||||
);
|
||||
expect(production).toContain('material de stock no catálogo publicado');
|
||||
});
|
||||
@@ -6,6 +6,38 @@ import { hasPreparationChanges } from '@/lib/requisition-history';
|
||||
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
test('new empty classification fields preserve an older recovered preparation while real classification changes remain dirty', () => {
|
||||
const old = { items: [{ description: 'Artigo anterior' }] };
|
||||
const current = {
|
||||
items: [
|
||||
{
|
||||
description: 'Artigo anterior',
|
||||
procurement_category: '',
|
||||
category_reason: '',
|
||||
},
|
||||
],
|
||||
};
|
||||
expect(hasPreparationChanges(old, current)).toBe(false);
|
||||
expect(hasPreparationChanges(current, old)).toBe(false);
|
||||
expect(
|
||||
hasPreparationChanges(old, {
|
||||
items: [
|
||||
{
|
||||
...current.items[0],
|
||||
procurement_category: 'office_equipment',
|
||||
},
|
||||
],
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
hasPreparationChanges(old, {
|
||||
items: [
|
||||
{ ...current.items[0], category_reason: 'Razão deliberada' },
|
||||
],
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test('restored technical identities do not mark a cleared preparation as changed', () => {
|
||||
const original = {
|
||||
operation_key: 'initial-operation',
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import { App, router } from '@inertiajs/react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { afterEach, expect, test, vi } from 'vitest';
|
||||
import ProcurementSearch from '@/pages/search/procurement';
|
||||
import type { SavedSearches } from '../../resources/js/components/saved-procurement-searches';
|
||||
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
const saved: SavedSearches = {
|
||||
max_active: 50,
|
||||
active: [
|
||||
{
|
||||
id: 3,
|
||||
name: '<script>Nome privado</script>',
|
||||
term: 'QA%_',
|
||||
version: 4,
|
||||
href: '/compras/pesquisa?q=QA%25_',
|
||||
},
|
||||
],
|
||||
archived: {
|
||||
data: [
|
||||
{
|
||||
id: 6,
|
||||
name: 'Anterior',
|
||||
term: 'Outro texto',
|
||||
version: 2,
|
||||
href: '/compras/pesquisa?q=Outro%20texto',
|
||||
},
|
||||
],
|
||||
total: 1,
|
||||
prev_page_url: null,
|
||||
next_page_url: null,
|
||||
},
|
||||
};
|
||||
|
||||
function renderSearch(searches: SavedSearches | null, actorId = 7) {
|
||||
return renderToStaticMarkup(
|
||||
<App
|
||||
initialComponent={ProcurementSearch}
|
||||
initialPage={{
|
||||
component: 'search/procurement',
|
||||
url: '/compras/pesquisa?q=QA',
|
||||
version: null,
|
||||
clearHistory: false,
|
||||
encryptHistory: true,
|
||||
props: {
|
||||
errors: {},
|
||||
auth: { user: { id: actorId, tenant_id: 2 } },
|
||||
term: 'QA',
|
||||
groups: [],
|
||||
savedSearches: searches,
|
||||
},
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
test('private saved criteria reopen a local live search and explain archival recovery without rendering supplied markup', () => {
|
||||
const html = renderSearch(saved);
|
||||
expect(html).toContain('As minhas pesquisas guardadas');
|
||||
expect(html).toContain('pesquisa activa');
|
||||
expect(html).toContain('href="/compras/pesquisa?q=QA%25_"');
|
||||
expect(html).toContain('acesso actual');
|
||||
expect(html).toContain('Arquivar pesquisa');
|
||||
expect(html).toContain('Restaurar pesquisa Anterior');
|
||||
expect(html).toContain('<script>Nome privado</script>');
|
||||
expect(html).not.toContain('<script>Nome privado');
|
||||
});
|
||||
|
||||
test('uninstalled saved-search storage does not advertise unavailable actions', () => {
|
||||
const html = renderSearch(null);
|
||||
expect(html).not.toContain('As minhas pesquisas guardadas');
|
||||
expect(html).not.toContain('Guardar pesquisa');
|
||||
expect(html).toContain('Pesquisar processos');
|
||||
});
|
||||
|
||||
test('encrypted preparation keys isolate owner company source version and editing state', () => {
|
||||
const keys: string[] = [];
|
||||
vi.spyOn(router, 'restore').mockImplementation((key) => {
|
||||
if (key) keys.push(key);
|
||||
return undefined;
|
||||
});
|
||||
renderSearch(saved, 7);
|
||||
expect(keys.some((key) => key.startsWith('saved-search:2:7:QA'))).toBe(
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
keys.some((key) => key.startsWith('saved-search-edit:2:7:3:4')),
|
||||
).toBe(true);
|
||||
keys.length = 0;
|
||||
renderSearch(saved, 8);
|
||||
expect(
|
||||
keys.some((key) => key.startsWith('saved-search-edit:2:8:3:4')),
|
||||
).toBe(true);
|
||||
expect(keys.some((key) => key.includes(':2:7:'))).toBe(false);
|
||||
});
|
||||
Reference in New Issue
Block a user