commit melhorias compras6
tests / ci (push) Waiting to run

This commit is contained in:
2026-11-23 06:37:16 +02:00
parent db1615fac1
commit dc73540558
73 changed files with 7539 additions and 175 deletions
+406 -26
View File
@@ -13,9 +13,11 @@ use App\Models\Department;
use App\Models\Equipment;
use App\Models\EquipmentSparePart;
use App\Models\InvestmentPolicy;
use App\Models\Invoice;
use App\Models\PurchaseAward;
use App\Models\PurchaseControlPolicy;
use App\Models\PurchaseOrder;
use App\Models\PurchaseOrderItem;
use App\Models\PurchaseRevision;
use App\Models\QualificationSet;
use App\Models\Quotation;
@@ -35,9 +37,12 @@ use App\Services\ConflictGuard;
use App\Services\DocumentaryQualificationWorkflow;
use App\Services\EquipmentWorkflow;
use App\Services\FormalAdmission;
use App\Services\ImportTariffCodes;
use App\Services\InvoiceWorkflow;
use App\Services\OrderCancellationPolicyWorkflow;
use App\Services\OrderCancellationWorkflow;
use App\Services\OrderPartsPreparation;
use App\Services\OrderPartsWorkflow;
use App\Services\ProcurementReviewCsv;
use App\Services\ProcurementReviewReport;
use App\Services\ProposalComparison;
@@ -46,11 +51,13 @@ use App\Services\PurchaseControlPolicyWorkflow;
use App\Services\PurchaseRevisionWorkflow;
use App\Services\PurchaseWorkflow;
use App\Services\QuotationExchange;
use App\Services\ReceiptWorkflow;
use App\Services\RequisitionBudgetDistributions;
use App\Services\RequisitionCatalogue;
use App\Services\RequisitionWorkflow;
use App\Services\SupplyPlanning;
use App\Services\WorkflowTaskInbox;
use Brick\Math\BigDecimal;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
@@ -63,6 +70,79 @@ require_once __DIR__.'/../Support/SupplyFixture.php';
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
test('confirmed import classifications freeze in a newly issued native order and survive later proposals', function () {
config(['import-tariffs.qa_enabled' => true]);
$tariffs = app(ImportTariffCodes::class);
$this->actingAs($this->buyer);
$proposal = $tariffs->save($this->buyer, $this->r, ['operation_key' => (string) Str::uuid(), 'action' => 'propose', 'version' => 0,
'requisition_item_id' => $this->item->id, 'code' => '1234.56', 'source_reference' => 'Synthetic documentary classification only',
'reason' => 'Proposed synthetic classification without a legal rate.']);
$award = selectPurchaseAward($this);
approvePurchaseAward($this, $award);
$this->actingAs($this->buyer);
$before = DB::table('budget_entries')->get()->toJson();
expect(fn () => app(PurchaseWorkflow::class)->issue($this->buyer, $award))->toThrow(HttpException::class);
expect(PurchaseOrder::query()->count())->toBe(0)->and(DB::table('budget_entries')->get()->toJson())->toBe($before);
$confirmed = $tariffs->save($this->buyer, $this->r, ['operation_key' => (string) Str::uuid(), 'action' => 'confirm', 'version' => $proposal->version,
'requisition_item_id' => $this->item->id, 'code' => '1234.56', 'source_reference' => 'Synthetic buyer source', 'reason' => 'Buyer confirms the synthetic documentary code.']);
config(['import-tariffs.qa_enabled' => false]);
expect(fn () => app(PurchaseWorkflow::class)->issue($this->buyer, $award))->toThrow(HttpException::class);
expect(PurchaseOrder::query()->count())->toBe(0)->and(DB::table('budget_entries')->get()->toJson())->toBe($before);
config(['import-tariffs.qa_enabled' => true]);
$order = app(PurchaseWorkflow::class)->issue($this->buyer, $award);
expect($order->snapshot['import_tariffs'][$this->item->id]['record_id'])->toBe($confirmed->id);
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('1234.56')->assertSee('Synthetic buyer source');
$tariffs->save($this->buyer, $this->r, ['operation_key' => (string) Str::uuid(), 'action' => 'propose', 'version' => $confirmed->version,
'requisition_item_id' => $this->item->id, 'code' => '1234.57', 'source_reference' => 'Later synthetic proposal', 'reason' => 'Later proposal must preserve the earlier issued classification.']);
expect($order->fresh()->snapshot['import_tariffs'][$this->item->id]['data']['confirmed_code'])->toBe('1234.56');
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('1234.56')->assertDontSee('1234.57');
});
test('a partial native order retains its confirmed imported item classification before committing funds', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Select the approved isolated-QA common source for native order parts.');
}
config(['import-tariffs.qa_enabled' => true]);
$award = nativeOrderPartsAward($this);
$input = nativeOrderPartsInput($this, $award, '0.400', 0);
$this->actingAs($this->buyer);
$tariffs = app(ImportTariffCodes::class);
$proposal = $tariffs->save($this->buyer, $this->r, ['operation_key' => (string) Str::uuid(), 'action' => 'propose', 'version' => 0,
'requisition_item_id' => $this->item->id, 'code' => '1234.56', 'source_reference' => 'Synthetic partial order source', 'reason' => 'Synthetic imported item proposal for a partial order.']);
expect(fn () => app(OrderPartsWorkflow::class)->issue($this->buyer, $input))->toThrow(HttpException::class);
expect(DB::table('budget_order_commands')->count())->toBe(0)->and(PurchaseOrder::query()->count())->toBe(0);
$confirmed = $tariffs->save($this->buyer, $this->r, ['operation_key' => (string) Str::uuid(), 'action' => 'confirm', 'version' => $proposal->version,
'requisition_item_id' => $this->item->id, 'code' => '1234.56', 'source_reference' => 'Synthetic confirmed partial order source', 'reason' => 'Buyer confirms the synthetic partial order classification.']);
$order = app(OrderPartsWorkflow::class)->issue($this->buyer, $input);
expect($order->snapshot['import_tariffs'][$this->item->id]['record_id'])->toBe($confirmed->id)
->and($order->total_minor)->toBe(4000)->and(DB::table('budget_order_commands')->count())->toBe(1);
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('1234.56');
$receiver = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => PurchasingRole::Warehouse]);
supplyGrant($this->buyer, ['procurement', 'import_prepare']);
supplyGrant($receiver, ['warehouse', 'import_customs']);
$warehouse = Warehouse::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'TARIFF-QA', 'name' => 'Synthetic tariff receipt warehouse']);
$stock = StockItem::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'TARIFF-QA', 'name' => 'Synthetic classified material', 'unit' => 'un']);
$payload = ['idempotency_key' => (string) Str::uuid(), 'delivery_note' => 'TARIFF-RECEIPT-QA', 'received_on' => today()->toDateString(),
'warehouse_id' => $warehouse->id, 'items' => [['purchase_order_item_id' => $order->items()->sole()->id,
'received_quantity' => '0.400', 'accepted_quantity' => '0.400', 'quality_status' => 'compliant', 'stock_item_id' => $stock->id]]];
$this->actingAs($receiver);
expect(fn () => app(ReceiptWorkflow::class)->confirm($receiver, $order, $payload))->toThrow(ValidationException::class);
expect(StockMovement::query()->count())->toBe(0);
$this->actingAs($this->buyer);
$planning = app(SupplyPlanning::class);
$import = $planning->save($this->buyer, 'import', supplyInput(['purchase_order_id' => $order->id, 'purpose' => 'internal',
'jurisdiction' => 'Synthetic jurisdiction', 'origin_country' => 'Synthetic A', 'dispatch_country' => 'Synthetic B', 'regime' => 'Synthetic customs regime']));
$event = ['evidence' => 'Synthetic customs evidence only', 'event_date' => today()->toDateString()];
$transit = $planning->save($this->buyer, 'import', supplyInput($event, 'transit', $import));
$arrived = $planning->save($this->buyer, 'import', supplyInput($event, 'arrive', $transit));
$this->actingAs($receiver);
expect(fn () => app(ReceiptWorkflow::class)->confirm($receiver, $order, $payload))->toThrow(ValidationException::class);
$planning->save($receiver, 'import', supplyInput($event, 'release', $arrived));
$receipt = app(ReceiptWorkflow::class)->confirm($receiver, $order, $payload);
expect(app(ReceiptWorkflow::class)->confirm($receiver, $order, $payload)->id)->toBe($receipt->id)
->and(StockMovement::query()->count())->toBe(1)->and((int) StockMovement::query()->sum('quantity_milli'))->toBe(400);
});
test('distributed approved synthetic requisition follows native adjudication approval and issuance without parallel entries', function () {
if (! method_exists(BudgetControl::class, 'recordDistribution')) {
$this->markTestSkipped('Unpublished common source requires explicit QA selection.');
@@ -640,7 +720,7 @@ test('catalogue origin survives order issue and automatically identifies receive
$this->get('/ordens/'.$order->id.'/recepcoes')->assertInertia(fn (Assert $p) => $p->where('progress.lines.0.stock_item_id', $stock->id));
$this->postJson('/ordens/'.$order->id.'/recepcoes', $body)->assertCreated();
$this->postJson('/ordens/'.$order->id.'/recepcoes', $body)->assertOk()->assertJsonPath('created', false);
expect(StockMovement::query()->where('stock_item_id', $stock->id)->sum('quantity_milli'))->toBe(1000);
expect((string) StockMovement::query()->where('stock_item_id', $stock->id)->sum('quantity_milli'))->toBe('1000');
});
function prepareEquipmentInvestment(object $test, string $ceiling = '100.00', bool $includesTax = true): InvestmentPolicy
@@ -1391,31 +1471,7 @@ test('optional partial-order preparation consolidates two independently approved
$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();
}
}
[$secondRequest, $quotes] = secondNativeOrderPartsOrigin($this);
$this->actingAs($this->buyer);
$second = app(PurchaseWorkflow::class)->select($this->buyer, $secondRequest, [...$this->selection, 'quotation_id' => $quotes[0]->id]);
approvePurchaseAward($this, $second);
@@ -1432,3 +1488,327 @@ test('optional partial-order preparation consolidates two independently approved
->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);
});
/** Native adjudication/approval fixture; requisition approval itself is the existing synthetic source. */
function nativeOrderPartsAward(object $test, ?Requisition $request = null, ?Quotation $quote = null): PurchaseAward
{
$request ??= $test->r;
$quote ??= $test->quotes[0];
if (! DB::getSchemaBuilder()->hasTable('budget_order_commands')) {
budgetDistributionFixtureSchema();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php')->up();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000008_create_purchase_order_sources.php')->up();
}
config(['order-parts.qa_enabled' => true, 'budget-distributions.qa_enabled' => true]);
$test->actingAs($test->finance);
if (! DB::table('budgets')->where('tenant_id', $request->tenant_id)->where('cost_center_id', $request->cost_center_id)->exists()) {
$id = app(CommonBudget::class)->for($test->finance)->create(['cost_center_id' => $request->cost_center_id, 'year' => (int) now()->year,
'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 100000, 'reason' => 'Dotacao sintetica de ordens parciais.']);
$test->actingAs($test->admin);
app(CommonBudget::class)->for($test->admin)->approve($id);
}
$host = app(RequisitionBudgetDistributions::class);
$allocations = $quote->items()->get()->map(fn ($line) => ['allocation_key' => (string) Str::uuid(),
'line_id' => $line->requisition_item_id, 'centre_id' => $request->cost_center_id,
'subtotal_minor' => $line->subtotal_minor, 'total_minor' => $line->total_minor])->all();
$request->forceFill(['budget_distribution_preparation' => ['allocations' => $allocations,
'source_revision' => $host->revision($request, $host->requestLines($request)), 'prepared_by' => $test->owner->id,
'reason' => 'Explicit synthetic source allocation.']])->save();
$test->actingAs($test->finance);
DB::transaction(fn () => app(BudgetWorkflow::class)->record($test->finance, $request, 'reserve', $request->total_minor, $request->subtotal_minor));
$test->actingAs($test->buyer);
$data = [...$test->selection, 'quotation_id' => $quote->id, 'reason' => 'Explicit native award distribution.',
'budget_distribution_preparation' => array_map(fn ($row) => ['allocation_key' => $row['allocation_key'], 'line_id' => $row['line_id'], 'centre_id' => $row['centre_id'],
'subtotal' => (string) BigDecimal::of($row['subtotal_minor'])->dividedBy(100, 2),
'total' => (string) BigDecimal::of($row['total_minor'])->dividedBy(100, 2)], $allocations)];
$award = app(PurchaseWorkflow::class)->select($test->buyer, $request, $data);
approvePurchaseAward($test, $award);
$test->actingAs($test->buyer);
return $award;
}
function nativeOrderPartsInput(object $test, PurchaseAward $award, string $quantity, int $version): array
{
$quote = Quotation::query()->whereKey($award->quotation_id)->firstOrFail();
$input = ['sources' => [['award_id' => $award->id, 'items' => [['quotation_item_id' => $quote->items()->sole()->id, 'quantity' => $quantity]]]]];
$prepared = app(OrderPartsPreparation::class)->prepare($test->buyer, $input);
$distribution = DB::table('budget_distributions')->where('requisition_id', $award->requisition_id)->first();
$snapshot = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR);
$line = $prepared['sources'][0]['items'][0];
return [...$input, 'order_key' => (string) Str::uuid(), 'operation_key' => (string) Str::uuid(), 'fingerprint' => $prepared['fingerprint'],
'budget_sources' => [['origin' => $award->requisition_id, 'version' => $version, 'plan_hash' => $snapshot['plan_hash'],
'allocations' => [['allocation_key' => $snapshot['allocations'][0]['allocation_key'], 'subtotal_minor' => $line['subtotal_minor'], 'total_minor' => $line['total_minor']]]]]];
}
test('native partial-order issuance commits only forty then sixty and preserves replay and quantity caps', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
}
(new PurchaseOrder)->fill(['number' => 'Unpersisted legacy metadata warmup']);
(new PurchaseOrderItem)->fill(['description' => 'Unpersisted legacy metadata warmup']);
$award = nativeOrderPartsAward($this);
$input = nativeOrderPartsInput($this, $award, '0.400', 0);
$workflow = app(OrderPartsWorkflow::class);
$first = $workflow->issue($this->buyer, $input);
expect($first->total_minor)->toBe(4000)->and($first->items()->sole()->quantity)->toBe('0.400')
->and($first->items()->sole()->quantity_offset_milli)->toBe(0)
->and($first->hasCompleteDocumentSnapshot())->toBeTrue()
->and($workflow->issue($this->buyer, $input)->id)->toBe($first->id)
->and(DB::table('purchase_order_sources')->count())->toBe(1)
->and((int) DB::table('budget_distribution_entries')->sum('reserved_minor'))->toBe(6000)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(4000);
$changed = $input;
$changed['sources'][0]['items'][0]['quantity'] = '0.401';
expect(fn () => $workflow->issue($this->buyer, $changed))->toThrow(HttpException::class);
$second = $workflow->issue($this->buyer, nativeOrderPartsInput($this, $award, '0.600', 1));
expect($second->total_minor)->toBe(6000)->and($second->items()->sole()->quantity_offset_milli)->toBe(400)
->and(PurchaseOrder::query()->count())->toBe(2)
->and((int) DB::table('budget_distribution_entries')->sum('reserved_minor'))->toBe(0)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(10000)
->and($this->r->fresh()->status)->toBe('approved');
expect(fn () => nativeOrderPartsInput($this, $award, '0.001', 2))->toThrow(ValidationException::class);
$this->withoutVite();
$this->get('/ordens/preparar')->assertOk()->assertViewHas('page', fn (array $page) => $page['props']['candidates']['data'] === []);
$this->post('/adjudicacoes/'.$award->id.'/emitir')->assertConflict();
});
test('native partial-order issuance rolls back the document and all financial effects when its audit fails', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
}
$award = nativeOrderPartsAward($this);
$input = nativeOrderPartsInput($this, $award, '0.400', 0);
$this->mock(RequisitionWorkflow::class)->shouldReceive('audit')->andThrow(new RuntimeException('audit failed'));
expect(fn () => app(OrderPartsWorkflow::class)->issue($this->buyer, $input))->toThrow(RuntimeException::class);
expect(PurchaseOrder::query()->count())->toBe(0)->and(DB::table('purchase_order_sources')->count())->toBe(0)
->and(DB::table('budget_order_commands')->count())->toBe(0)
->and((int) DB::table('budget_distribution_entries')->sum('reserved_minor'))->toBe(10000)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(0);
});
test('native partial-order receipts and independent invoice validation consume exact commitments once with one stock movement per receipt', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
}
$award = nativeOrderPartsAward($this);
$workflow = app(OrderPartsWorkflow::class);
$first = $workflow->issue($this->buyer, nativeOrderPartsInput($this, $award, '0.400', 0));
$second = $workflow->issue($this->buyer, nativeOrderPartsInput($this, $award, '0.600', 1));
$receiver = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => PurchasingRole::Warehouse]);
$validator = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($receiver);
$warehouse = Warehouse::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'PARTS-QA', 'name' => 'Armazem de ensaio']);
$stock = StockItem::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'PARTS-QA', 'name' => 'Material de ensaio', 'unit' => 'un']);
foreach ([[$first, '0.400', '40.00'], [$second, '0.600', '60.00']] as [$order, $quantity, $amount]) {
$this->actingAs($receiver);
$line = $order->items()->sole();
$payload = ['idempotency_key' => (string) Str::uuid(), 'delivery_note' => 'GR-PART-'.$order->id, 'received_on' => today()->toDateString(),
'warehouse_id' => $warehouse->id, 'items' => [['purchase_order_item_id' => $line->id, 'received_quantity' => $quantity,
'accepted_quantity' => $quantity, 'quality_status' => 'compliant', 'stock_item_id' => $stock->id]]];
$receipt = app(ReceiptWorkflow::class)->confirm($receiver, $order, $payload);
expect(app(ReceiptWorkflow::class)->confirm($receiver, $order, $payload)->id)->toBe($receipt->id)
->and($receipt->items()->sole()->snapshot['source_line']['requisition_item_id'])->toBe($this->item->id);
$this->actingAs($this->finance);
$allocation = $order->snapshot['order_parts']['budget_sources'][0]['allocations'][0];
$data = ['number' => 'FT-PART-'.$order->id, 'issued_on' => today()->toDateString(), 'subtotal' => $amount, 'tax' => '0.00', 'total' => $amount,
'items' => [['purchase_order_item_id' => $line->id, 'quantity' => $quantity]], 'reason' => 'Explicit native Finance allocation.',
'order_part_allocations' => [['origin' => $this->r->id, 'allocation_key' => $allocation['allocation_key'], 'subtotal' => $amount, 'total' => $amount]]];
$invoice = app(InvoiceWorkflow::class)->register($this->finance, $order, $data);
expect(fn () => app(InvoiceWorkflow::class)->validate($this->finance, $invoice))->toThrow(HttpException::class);
$this->actingAs($validator);
app(InvoiceWorkflow::class)->validate($validator, $invoice);
app(InvoiceWorkflow::class)->validate($validator, $invoice->fresh());
expect($invoice->fresh()->status)->toBe('validated');
}
expect(Invoice::query()->count())->toBe(2)
->and(DB::table('budget_order_consumptions')->count())->toBe(2)
->and(StockMovement::query()->count())->toBe(2)
->and((int) StockMovement::query()->sum('quantity_milli'))->toBe(1000)
->and((int) DB::table('budget_distribution_entries')->sum('reserved_minor'))->toBe(0)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(0)
->and((int) DB::table('budget_order_consumptions')->sum('amount_minor'))->toBe(10000)
->and(DB::table('budget_distribution_consumptions')->count())->toBe(0)
->and(DB::table('budget_consumptions')->count())->toBe(0);
});
function secondNativeOrderPartsOrigin(object $test): array
{
$secondRequest = $test->r->fresh()->replicate();
$secondRequest->number = 'REQ-ORDER-SECOND-QA';
if (DB::getSchemaBuilder()->hasColumn('requisitions', 'budget_distribution_preparation')) {
$secondRequest->budget_distribution_preparation = null;
}
$secondRequest->subtotal_minor = $secondRequest->total_minor = 20000;
$secondRequest->save();
$line = $test->item->replicate();
$line->requisition_id = $secondRequest->id;
$line->unit_price_minor = $line->subtotal_minor = $line->total_minor = 20000;
$line->save();
foreach ($test->r->steps()->get() as $step) {
$copy = $step->replicate();
$copy->requisition_id = $secondRequest->id;
$copy->save();
}
$quotes = [];
foreach ($test->suppliers as $index => $supplier) {
$test->actingAs($test->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 ([$test->buyer, $test->finance] as $evaluator) {
$test->actingAs($evaluator)->post('/cotacoes/'.$quote->id.'/avaliar', ['quality' => '8', 'history' => '5', 'payment' => '8',
'comment' => 'Independent synthetic evaluation for second origin.', 'no_conflict' => true])->assertSessionHasNoErrors();
}
}
return [$secondRequest, $quotes];
}
test('native consolidated order retains both origins and consumes a single invoice without duplicate stock or debt', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
}
$first = nativeOrderPartsAward($this);
[$request, $quotes] = secondNativeOrderPartsOrigin($this);
$second = nativeOrderPartsAward($this, $request, $quotes[0]);
$a = nativeOrderPartsInput($this, $first, '1.000', 0);
$b = nativeOrderPartsInput($this, $second, '1.000', 0);
$input = [...$a, 'sources' => [...$a['sources'], ...$b['sources']], 'budget_sources' => [...$a['budget_sources'], ...$b['budget_sources']]];
$input['fingerprint'] = app(OrderPartsPreparation::class)->prepare($this->buyer, $input)['fingerprint'];
$order = app(OrderPartsWorkflow::class)->issue($this->buyer, $input);
expect($order->total_minor)->toBe(30000)->and($order->items()->count())->toBe(2)
->and(DB::table('purchase_order_sources')->where('purchase_order_id', $order->id)->count())->toBe(2)
->and(PurchaseOrder::query()->visibleTo($this->buyer)->whereKey($order->id)->exists())->toBeTrue();
$this->withoutVite();
$this->get('/ordens/'.$order->id)->assertOk()->assertViewHas('page', fn (array $page) => count($page['props']['orderPartsSources']) === 2);
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee($this->r->number)->assertSee($request->number)
->assertSee('Origens desta ordem')->assertSee('Controlo orçamental confirmado para as parcelas emitidas.');
$receiver = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => PurchasingRole::Warehouse]);
$reviewer = User::factory()->create(['tenant_id' => $this->tenant->id, 'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($receiver);
$warehouse = Warehouse::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'CONSOL-QA', 'name' => 'Armazem de ensaio']);
$stock = StockItem::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'CONSOL-QA', 'name' => 'Material de ensaio', 'unit' => 'un']);
$lines = $order->items()->orderBy('id')->get();
$receiptData = ['idempotency_key' => (string) Str::uuid(), 'delivery_note' => 'GR-CONSOL-QA', 'received_on' => today()->toDateString(),
'warehouse_id' => $warehouse->id, 'items' => $lines->map(fn ($line) => ['purchase_order_item_id' => $line->id, 'received_quantity' => '1.000',
'accepted_quantity' => '1.000', 'quality_status' => 'compliant', 'stock_item_id' => $stock->id])->all()];
$receipt = app(ReceiptWorkflow::class)->confirm($receiver, $order, $receiptData);
expect($receipt->items()->count())->toBe(2);
$this->actingAs($this->finance);
$data = ['number' => 'FT-CONSOL-QA', 'issued_on' => today()->toDateString(), 'subtotal' => '150.00', 'tax' => '0.00', 'total' => '150.00',
'items' => $lines->map(fn ($line) => ['purchase_order_item_id' => $line->id, 'quantity' => '0.500'])->all(),
'reason' => 'Explicit allocations for both approved origins.', 'order_part_allocations' => [
['origin' => $first->requisition_id, 'allocation_key' => $a['budget_sources'][0]['allocations'][0]['allocation_key'], 'subtotal' => '50.00', 'total' => '50.00'],
['origin' => $second->requisition_id, 'allocation_key' => $b['budget_sources'][0]['allocations'][0]['allocation_key'], 'subtotal' => '100.00', 'total' => '100.00']]];
$invoice = app(InvoiceWorkflow::class)->register($this->finance, $order, $data);
$this->actingAs($reviewer);
app(InvoiceWorkflow::class)->validate($reviewer, $invoice);
app(InvoiceWorkflow::class)->validate($reviewer, $invoice->fresh());
expect(Invoice::query()->count())->toBe(1)
->and($invoice->fresh()->total_minor)->toBe(15000)->and($invoice->fresh()->status)->toBe('validated')
->and(DB::table('budget_order_consumptions')->where('invoice_id', $invoice->id)->count())->toBe(2)
->and((int) DB::table('budget_order_consumptions')->sum('amount_minor'))->toBe(15000)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(15000)
->and(StockMovement::query()->count())->toBe(2)->and((int) StockMovement::query()->sum('quantity_milli'))->toBe(2000);
$this->actingAs($this->owner);
expect(PurchaseOrder::query()->visibleTo($this->owner)->whereKey($order->id)->exists())->toBeTrue();
$request->forceFill(['requester_id' => $this->head->id])->save();
expect(PurchaseOrder::query()->visibleTo($this->owner)->whereKey($order->id)->exists())->toBeFalse();
});
test('native partial-order cancellation uses independent Finance and preserves the unissued reservation and requisition', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
}
$award = nativeOrderPartsAward($this);
$issue = app(OrderPartsWorkflow::class);
$order = $issue->issue($this->buyer, nativeOrderPartsInput($this, $award, '0.400', 0));
config(['order_cancellation.enabled' => true]);
$policyFlow = app(OrderCancellationPolicyWorkflow::class);
$admins = [$this->admin, User::factory()->create(['tenant_id' => $this->tenant->id, 'purchasing_role' => PurchasingRole::Admin]),
User::factory()->create(['tenant_id' => $this->tenant->id, 'purchasing_role' => PurchasingRole::Admin])];
$this->actingAs($admins[0]);
$policy = $policyFlow->propose($admins[0], ['previous_id' => 0, 'mode' => 'issued_order', 'enabled' => true,
'valid_from' => today()->toDateString(), 'valid_until' => today()->addMonth()->toDateString(), 'reason' => 'Synthetic existing cancellation policy.']);
foreach (array_slice($admins, 1) as $admin) {
$this->actingAs($admin);
$policyFlow->review($admin, $policy, 'approved', 'Independent synthetic policy review.');
}
$this->actingAs($this->buyer);
$flow = app(OrderCancellationWorkflow::class);
$record = $flow->request($this->buyer, $order, ['operation_key' => (string) Str::uuid(),
'reason' => 'Synthetic cancellation before any execution.', 'evidence' => 'Documented synthetic business decision.']);
$this->actingAs($this->finance);
$flow->decide($this->finance, $record, 'approved', 'Independent Finance confirmation.');
$flow->decide($this->finance, $record->fresh(), 'approved', 'Independent Finance confirmation.');
expect($flow->state($order))->toBe('cancelled')->and($this->r->fresh()->status)->toBe('approved')
->and((int) DB::table('budget_distribution_entries')->sum('reserved_minor'))->toBe(6000)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(0)
->and(DB::table('budget_order_commands')->where('kind', 'cancel')->count())->toBe(1);
$this->actingAs($this->owner);
expect($flow->canRevise($this->owner, $record->fresh()))->toBeFalse()
->and(fn () => $flow->revise($this->owner, $record->fresh(), today()->addMonth()->toDateString(), 'No automatic whole-source reissue.'))->toThrow(HttpException::class);
$this->actingAs($this->buyer);
$remaining = $issue->issue($this->buyer, nativeOrderPartsInput($this, $award, '0.600', 2));
expect($remaining->total_minor)->toBe(6000)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(6000)
->and((int) DB::table('budget_distribution_entries')->sum('reserved_minor'))->toBe(0);
});
test('native partial-order forms preview without writes and issue through the authenticated encrypted path', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
}
$award = nativeOrderPartsAward($this);
$this->withoutVite();
$this->get('/ordens/preparar')->assertOk()->assertViewHas('page', fn (array $page) => $page['component'] === 'purchases/parts' && $page['encryptHistory'] === true);
$input = nativeOrderPartsInput($this, $award, '0.400', 0);
$before = DB::table('audit_logs')->count();
$this->post('/ordens/preparar', ['sources' => $input['sources']])->assertOk()
->assertViewHas('page', fn (array $page) => $page['props']['preview']['prepared']['total_minor'] === 4000 && $page['props']['preview']['can_issue'] === true);
expect(PurchaseOrder::query()->count())->toBe(0)->and(DB::table('audit_logs')->count())->toBe($before);
$this->post('/ordens/parcelas/emitir', $input)->assertRedirect();
$order = PurchaseOrder::query()->sole();
$this->post('/ordens/parcelas/emitir', $input)->assertRedirect('/ordens/'.$order->id);
expect(PurchaseOrder::query()->count())->toBe(1);
$this->actingAs($this->finance)->get('/ordens/preparar')->assertForbidden();
$this->actingAs($this->buyer);
config(['order-parts.qa_enabled' => false]);
$this->get('/ordens/preparar')->assertServiceUnavailable();
$this->post('/ordens/parcelas/emitir', $input)->assertServiceUnavailable();
expect(PurchaseOrder::query()->count())->toBe(1);
});
test('native explicit adoption keeps the old reserve unchanged and supports replay after a partial order is issued', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
}
budgetDistributionFixtureSchema();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php')->up();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000008_create_purchase_order_sources.php')->up();
config(['order-parts.qa_enabled' => true, 'budget-distributions.qa_enabled' => true]);
$this->actingAs($this->finance);
$id = app(CommonBudget::class)->for($this->finance)->create(['cost_center_id' => $this->r->cost_center_id, 'year' => (int) now()->year,
'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 100000, 'reason' => 'Synthetic legacy budget before adoption.']);
$this->actingAs($this->admin);
app(CommonBudget::class)->for($this->admin)->approve($id);
$this->actingAs($this->finance);
DB::transaction(fn () => app(BudgetWorkflow::class)->record($this->finance, $this->r, 'reserve', 10000, 10000));
$award = selectPurchaseAward($this);
approvePurchaseAward($this, $award);
$old = DB::table('budget_entries')->where('requisition_id', $this->r->id)->orderBy('id')->get()->toArray();
$this->actingAs($this->buyer);
$source = ['sources' => [['award_id' => $award->id, 'items' => [['quotation_item_id' => $this->quotes[0]->items()->sole()->id, 'quantity' => '0.400']]]]];
expect(app(OrderPartsWorkflow::class)->preview($this->buyer, $source)['financial'][0]['requires_adoption'])->toBeTrue();
$operation = (string) Str::uuid();
$this->post('/adjudicacoes/'.$award->id.'/parcelas/adoptar', ['operation_key' => $operation])->assertRedirect('/ordens/preparar');
expect(DB::table('budget_entries')->where('requisition_id', $this->r->id)->orderBy('id')->limit(count($old))->get()->toArray())->toEqual($old)
->and((int) DB::table('budget_entries')->sum('reserved_minor') + (int) DB::table('budget_distribution_entries')->sum('reserved_minor'))->toBe(10000);
app(OrderPartsWorkflow::class)->issue($this->buyer, nativeOrderPartsInput($this, $award, '0.400', 0));
$this->post('/adjudicacoes/'.$award->id.'/parcelas/adoptar', ['operation_key' => $operation])->assertRedirect('/ordens/preparar');
expect(DB::table('budget_order_commands')->where('kind', 'adopt')->count())->toBe(1)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(4000);
});