@@ -47,6 +47,7 @@ use App\Services\OrderPartsAmendments;
|
||||
use App\Services\OrderPartsPreparation;
|
||||
use App\Services\OrderPartsWorkflow;
|
||||
use App\Services\ProcurementContractInsights;
|
||||
use App\Services\ProcurementDeliveryInsights;
|
||||
use App\Services\ProcurementReviewCsv;
|
||||
use App\Services\ProcurementReviewReport;
|
||||
use App\Services\ProposalComparison;
|
||||
@@ -56,12 +57,14 @@ use App\Services\PurchaseRevisionWorkflow;
|
||||
use App\Services\PurchaseWorkflow;
|
||||
use App\Services\QuotationExchange;
|
||||
use App\Services\ReceiptWorkflow;
|
||||
use App\Services\RequisitionAccountAssignments;
|
||||
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 Carbon\CarbonImmutable;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
@@ -69,16 +72,17 @@ use Illuminate\Validation\ValidationException;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
use Tempo\Finance\Budget\BudgetControl;
|
||||
use Tempo\Finance\GeneralLedger\LedgerSchema;
|
||||
|
||||
require_once __DIR__.'/../Support/SupplyFixture.php';
|
||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
|
||||
|
||||
function nativeCapitalAssignment(object $test): array
|
||||
function nativeCapitalAssignment(object $test, string $type = 'project'): array
|
||||
{
|
||||
config(['capital-register.qa_enabled' => true]);
|
||||
$test->actingAs($test->buyer);
|
||||
$input = ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0, 'type' => 'project',
|
||||
$input = ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0, 'type' => $type,
|
||||
'code' => 'PRJ-NATIVE-QA', 'name' => 'Projecto sintético da ordem', 'department_id' => $test->department->id,
|
||||
'equipment_id' => null, 'reference' => 'Documento sintético de investimento', 'state' => 'active', 'reason' => 'Cadastro estritamente sintético da ligação à ordem'];
|
||||
$source = app(CapitalRegister::class)->save($test->buyer, $input);
|
||||
@@ -121,6 +125,45 @@ test('native order preserves the capital destination and print after the indepen
|
||||
expect(DB::table('stock_movements')->get()->toJson())->toBe($before);
|
||||
});
|
||||
|
||||
test('native frozen asset origin connects later equipment registration to its actual order and receipt', function () {
|
||||
[$source, $assignment, $input] = nativeCapitalAssignment($this, 'asset');
|
||||
$order = issuePurchaseOrder($this, selectPurchaseAward($this));
|
||||
expect($order->snapshot['capital_assignments'][$this->item->id]['snapshot']['source']['data']['equipment_id'])->toBeNull();
|
||||
$receiver = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => PurchasingRole::Warehouse]);
|
||||
$this->actingAs($receiver);
|
||||
$warehouse = Warehouse::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'ASSET-QA', 'name' => 'Armazém sintético']);
|
||||
$stock = StockItem::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'ASSET-QA', 'name' => 'Artigo sintético', 'unit' => 'un']);
|
||||
$receipt = app(ReceiptWorkflow::class)->confirm($receiver, $order, ['idempotency_key' => (string) Str::uuid(), 'delivery_note' => 'ASSET-LATE-LINK-QA',
|
||||
'received_on' => today()->toDateString(), 'warehouse_id' => $warehouse->id,
|
||||
'items' => [['purchase_order_item_id' => $order->items()->sole()->id, 'received_quantity' => '1.000', 'accepted_quantity' => '1.000', 'quality_status' => 'compliant', 'stock_item_id' => $stock->id]]]);
|
||||
$this->actingAs($this->buyer);
|
||||
$level = CriticalityLevel::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $this->buyer->id, 'created_at' => now(),
|
||||
'code' => 'ASSET-QA', 'name' => 'Criticidade de ensaio', 'criteria' => 'Registo exclusivamente sintético', 'is_critical' => false]);
|
||||
$equipment = Equipment::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $this->buyer->id, 'department_id' => $this->department->id,
|
||||
'code' => 'EQ-LATE-QA', 'description' => 'Equipamento registado após recepção sintética', 'area' => 'Área de ensaio', 'status' => 'active', 'criticality_level_id' => $level->id]);
|
||||
app(CapitalRegister::class)->save($this->buyer, [...$input, 'operation_key' => (string) Str::uuid(), 'record_key' => $source->record_key,
|
||||
'version' => 1, 'equipment_id' => $equipment->id, 'name' => 'Referência actual do activo', 'state' => 'archived']);
|
||||
$before = [];
|
||||
foreach (['purchase_orders', 'purchase_order_items', 'goods_receipts', 'goods_receipt_items', 'budget_entries', 'stock_movements', 'audit_logs', 'supply_records'] as $table) {
|
||||
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
|
||||
}
|
||||
$this->withoutVite();
|
||||
$this->get('/equipamentos/'.$equipment->id)->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')
|
||||
->assertInertia(fn (Assert $page) => $page->where('capitalReference.record_key', $source->record_key)->where('capitalReference.version', 2)
|
||||
->where('capitalReference.state', 'archived')->missing('capitalReference.reason')->missing('capitalReference.snapshot'));
|
||||
$this->get('/projectos-imobilizado?history='.$source->record_key)->assertOk()->assertInertia(fn (Assert $page) => $page
|
||||
->where('trace.orders.data.0.order_number', $order->number)->where('trace.receipts.data.0.receipt_id', $receipt->id));
|
||||
expect($order->fresh()->snapshot['capital_assignments'][$this->item->id]['snapshot']['source']['version'])->toBe(1)
|
||||
->and($order->fresh()->snapshot['capital_assignments'][$this->item->id]['snapshot']['source']['data']['equipment_id'])->toBeNull();
|
||||
foreach ($before as $table => $rows) {
|
||||
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
|
||||
}
|
||||
config(['capital-register.qa_enabled' => false]);
|
||||
$this->get('/equipamentos/'.$equipment->id)->assertOk()->assertInertia(fn (Assert $page) => $page->where('capitalReference', null));
|
||||
$other = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => Department::query()->create(['tenant_id' => $this->tenant->id, 'name' => 'Outra área QA'])->id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
|
||||
$this->actingAs($other)->get('/equipamentos/'.$equipment->id)->assertNotFound();
|
||||
});
|
||||
|
||||
test('native partial order freezes the same explicit capital origin without changing its financial allocation', function () {
|
||||
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
|
||||
$this->markTestSkipped('Select the approved isolated-QA common source for native order parts.');
|
||||
@@ -815,6 +858,18 @@ function prepareEquipmentInvestment(object $test, string $ceiling = '100.00', bo
|
||||
}
|
||||
|
||||
beforeEach(function () {
|
||||
if (getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') === '1') {
|
||||
require_once __DIR__.'/../Support/RequisitionLedgerQaRuntime.php';
|
||||
$source = requisitionLedgerQaSource();
|
||||
if ($source === null) {
|
||||
throw new LogicException('Integrated orders require the dedicated actual-ledger QA runner.');
|
||||
}
|
||||
require_once $source.'/bootstrap.php';
|
||||
LedgerSchema::install(DB::connection());
|
||||
require_once __DIR__.'/../Support/IntegratedPurchasingQaSchema.php';
|
||||
$composition = integratedPurchasingQaSchema();
|
||||
expect($composition['verified_tables'])->toHaveCount(12);
|
||||
}
|
||||
$this->tenant = Tenant::query()->create(['name' => 'Empresa das ordens']);
|
||||
$this->department = Department::query()->create(['tenant_id' => $this->tenant->id, 'name' => 'Produção']);
|
||||
$center = CostCenter::query()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'code' => 'PROD', 'name' => 'Produção']);
|
||||
@@ -880,6 +935,89 @@ test('discount evidence and net prices survive award order and printable report'
|
||||
$this->actingAs($this->buyer)->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('20.00%');
|
||||
});
|
||||
|
||||
test('native order preserves common ledger account references without creating a journal or changing the chart', function () {
|
||||
$source = getenv('RQ01_LEDGER_QA_SOURCE');
|
||||
if ($source !== 'C:/laragon/www/sgf-tempo/packages/general-ledger') {
|
||||
$this->markTestSkipped('Dedicated real common-ledger QA schema required.');
|
||||
}
|
||||
require_once $source.'/bootstrap.php';
|
||||
LedgerSchema::install(DB::connection());
|
||||
config(['requisition-accounts.qa_enabled' => true]);
|
||||
$id = DB::table('gl_accounts')->insertGetId(['tenant_id' => $this->tenant->id, 'company_id' => 0, 'unit_id' => 0,
|
||||
'code' => 'QA-NATIVE-ACCOUNT', 'label' => 'Conta fictícia da necessidade', 'currency' => 'MZN', 'is_movement' => true]);
|
||||
$this->r->update(['status' => 'draft']);
|
||||
$this->actingAs($this->owner);
|
||||
$service = app(RequisitionAccountAssignments::class);
|
||||
$space = $service->workspace($this->owner, $this->r);
|
||||
$record = $service->save($this->owner, $this->r, ['operation_key' => (string) Str::uuid(), 'version' => 0,
|
||||
'item_id' => $this->item->id, 'basis_hash' => $space['items'][0]['basis_hash'], 'reason' => 'Referência contabilística da necessidade sintética',
|
||||
'allocations' => [['account_id' => $id, 'source_hash' => $space['accounts']['data'][0]['source_hash'], 'subtotal' => '100.00', 'total' => '100.00']]]);
|
||||
$this->r->update(['status' => 'approved']);
|
||||
$before = DB::table('gl_accounts')->get()->toJson();
|
||||
$award = selectPurchaseAward($this);
|
||||
$order = issuePurchaseOrder($this, $award);
|
||||
expect($order->snapshot['account_assignments'][$this->item->id]['id'])->toBe($record->id)
|
||||
->and($order->snapshot['account_assignments'][$this->item->id]['data']['allocations'][0]['account']['code'])->toBe('QA-NATIVE-ACCOUNT')
|
||||
->and(DB::table('gl_journals')->count())->toBe(0)->and(DB::table('gl_accounts')->get()->toJson())->toBe($before);
|
||||
$this->actingAs($this->buyer)->get('/ordens/'.$order->id.'/imprimir')->assertOk()
|
||||
->assertSee('QA-NATIVE-ACCOUNT')->assertSee('Parcelas originais');
|
||||
});
|
||||
|
||||
test('native order preserves common ledger across partial and consolidated origins', function (string $mode) {
|
||||
$source = getenv('RQ01_LEDGER_QA_SOURCE');
|
||||
if ($source !== 'C:/laragon/www/sgf-tempo/packages/general-ledger' || ! method_exists(BudgetControl::class, 'commitOrderParts')) {
|
||||
$this->markTestSkipped('Dedicated common ledger and authorised order-parts QA composition required.');
|
||||
}
|
||||
require_once $source.'/bootstrap.php';
|
||||
LedgerSchema::install(DB::connection());
|
||||
config(['requisition-accounts.qa_enabled' => true]);
|
||||
DB::table('gl_accounts')->insert(['tenant_id' => $this->tenant->id, 'company_id' => 0, 'unit_id' => 0,
|
||||
'code' => 'QA-ORIGINS-ACCOUNT', 'label' => 'Conta fictícia das origens', 'currency' => 'MZN', 'is_movement' => true]);
|
||||
$firstAward = nativeOrderPartsAward($this);
|
||||
$requests = [$this->r];
|
||||
$secondAward = null;
|
||||
if ($mode === 'consolidated') {
|
||||
[$second, $quotes] = secondNativeOrderPartsOrigin($this);
|
||||
$secondAward = nativeOrderPartsAward($this, $second, $quotes[0]);
|
||||
$requests[] = $second;
|
||||
}
|
||||
$records = [];
|
||||
foreach ($requests as $request) {
|
||||
$request->refresh()->update(['status' => 'draft']);
|
||||
$this->actingAs($this->owner);
|
||||
$service = app(RequisitionAccountAssignments::class);
|
||||
$space = $service->workspace($this->owner, $request);
|
||||
$line = $space['items'][0];
|
||||
$account = $space['accounts']['data'][0];
|
||||
$records[$line['id']] = $service->save($this->owner, $request, ['operation_key' => (string) Str::uuid(), 'version' => 0,
|
||||
'item_id' => $line['id'], 'basis_hash' => $line['basis_hash'], 'reason' => 'Imputação original explícita no ensaio das origens',
|
||||
'allocations' => [['account_id' => $account['id'], 'source_hash' => $account['source_hash'],
|
||||
'subtotal' => (string) BigDecimal::of($line['subtotal_minor'])->dividedBy(100, 2), 'total' => (string) BigDecimal::of($line['total_minor'])->dividedBy(100, 2)]]]);
|
||||
$request->update(['status' => 'approved']);
|
||||
}
|
||||
$this->actingAs($this->buyer);
|
||||
$flow = app(OrderPartsWorkflow::class);
|
||||
if ($secondAward === null) {
|
||||
$orders = [$flow->issue($this->buyer, nativeOrderPartsInput($this, $firstAward, '0.400', 0)),
|
||||
$flow->issue($this->buyer, nativeOrderPartsInput($this, $firstAward, '0.600', 1))];
|
||||
} else {
|
||||
$a = nativeOrderPartsInput($this, $firstAward, '1.000', 0);
|
||||
$b = nativeOrderPartsInput($this, $secondAward, '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'];
|
||||
$orders = [$flow->issue($this->buyer, $input)];
|
||||
}
|
||||
foreach ($orders as $order) {
|
||||
expect($order->snapshot['account_assignments'])->toHaveCount(count($records));
|
||||
foreach ($records as $line => $record) {
|
||||
expect($order->snapshot['account_assignments'][$line]['id'])->toBe($record->id)
|
||||
->and($order->snapshot['account_assignments'][$line]['data']['allocations'])->toBe($record->data['allocations']);
|
||||
}
|
||||
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('QA-ORIGINS-ACCOUNT')->assertSee('Parcelas originais');
|
||||
}
|
||||
expect(DB::table('gl_journals')->count())->toBe(0)->and(DB::table('gl_accounts')->count())->toBe(1);
|
||||
})->with(['partial', 'consolidated']);
|
||||
|
||||
test('comparison rule is printed with the order and policy tampering invalidates an approved award', function () {
|
||||
$policy = [...ComparisonPolicy::DEFAULTS, 'revision' => 1, 'configured' => true];
|
||||
$this->r->update(['comparison_policy' => $policy]);
|
||||
@@ -964,12 +1102,25 @@ test('invalid source policy approval or unsupported purchase type cannot be pres
|
||||
$this->r->update(['approval_snapshot' => null]);
|
||||
} elseif ($change === 'approval') {
|
||||
$this->r->steps()->update(['decision' => 'pending']);
|
||||
} elseif (in_array($change, ['additional', 'routing'], true)) {
|
||||
// Deliberately inconsistent synthetic history: a frozen level without its decision.
|
||||
$this->r->update(['approval_snapshot' => [...$this->r->approval_snapshot,
|
||||
'additional_levels' => ['configured_1' => ['name' => 'Synthetic missing level', 'profile_ids' => [1], 'scope' => 'company']]]]);
|
||||
if ($change === 'routing') {
|
||||
$this->r->steps()->create(['tenant_id' => $this->tenant->id, 'position' => $this->r->steps()->count() + 1,
|
||||
'role' => 'configured_1', 'decision' => 'approved', 'approver_id' => $this->finance->id, 'decided_at' => now(),
|
||||
'routing' => ['name' => 'Mismatched synthetic routing', 'profile_ids' => [2], 'scope' => 'company']]);
|
||||
}
|
||||
} elseif ($change === 'approval_basis') {
|
||||
// A frozen landed-cost basis cannot be replaced by the lower goods-only amount.
|
||||
$this->r->update(['approval_snapshot' => [...$this->r->approval_snapshot,
|
||||
'approval_basis' => ['subtotal_minor' => 1000000000, 'total_minor' => 1000000000]]]);
|
||||
} else {
|
||||
$this->item->update(['purchase_type' => $change]);
|
||||
}
|
||||
$this->post($this->awardUrl, $this->selection)->assertSessionHasErrors($error);
|
||||
expect(PurchaseAward::query()->count())->toBe(0);
|
||||
})->with([['snapshot', 'policy'], ['approval', 'approvals'], ['equipment', 'purchase_type'], ['spare_part', 'purchase_type']]);
|
||||
})->with([['snapshot', 'policy'], ['approval', 'approvals'], ['additional', 'approvals'], ['routing', 'approvals'], ['approval_basis', 'approvals'], ['equipment', 'purchase_type'], ['spare_part', 'purchase_type']]);
|
||||
|
||||
test('award approvals enforce role order department distinct people and no self approval', function () {
|
||||
awardPrices($this, 15000001);
|
||||
@@ -1630,6 +1781,48 @@ function nativeOrderPartsInput(object $test, PurchaseAward $award, string $quant
|
||||
'allocations' => [['allocation_key' => $snapshot['allocations'][0]['allocation_key'], 'subtotal_minor' => $line['subtotal_minor'], 'total_minor' => $line['total_minor']]]]]];
|
||||
}
|
||||
|
||||
test('budget consultations use the common balance and protect private history without source writes', function () {
|
||||
$this->withoutVite();
|
||||
$centre = CostCenter::query()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id,
|
||||
'code' => 'BUD-PRIV-QA', 'name' => 'Synthetic private budget view']);
|
||||
$this->actingAs($this->finance);
|
||||
$budget = app(CommonBudget::class)->for($this->finance)->create(['cost_center_id' => $centre->id, 'year' => (int) now()->year,
|
||||
'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 100000, 'reason' => 'Explicit synthetic budget for private native read regression']);
|
||||
$this->actingAs($this->admin);
|
||||
app(CommonBudget::class)->for($this->admin)->approve($budget);
|
||||
$tables = ['budgets', 'budget_entries', 'budget_consumptions', 'audit_logs'];
|
||||
$snapshot = fn () => array_map(fn ($table) => DB::table($table)->orderBy('id')->get()->toJson(), $tables);
|
||||
$before = $snapshot();
|
||||
$response = $this->actingAs($this->finance)->get('/orcamentos')->assertOk()
|
||||
->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true)
|
||||
->assertInertia(fn (Assert $page) => $page->component('budgets/index')->where('budgets.0.id', $budget)->where('budgets.0.available_minor', 100000));
|
||||
expect($response->headers->get('Cache-Control'))->toContain('private', 'no-store');
|
||||
$this->actingAs($this->owner)->getJson('/orcamentos')->assertForbidden();
|
||||
expect($snapshot())->toBe($before);
|
||||
});
|
||||
|
||||
test('purchase control preparations retain native scope encrypted history and private headers without source writes', function () {
|
||||
$this->withoutVite();
|
||||
$this->actingAs($this->admin);
|
||||
app(PurchaseControlPolicyWorkflow::class)->propose($this->admin, ['previous_id' => 0, 'mode' => 'unissued_award',
|
||||
'enabled' => false, 'valid_from' => today()->toDateString(), 'valid_until' => today()->addMonth()->toDateString(),
|
||||
'reason' => 'Pending disabled synthetic proposal exists before comparing operational and requester visibility']);
|
||||
$tables = ['requisitions', 'purchase_awards', 'purchase_control_policies', 'purchase_control_reviews', 'award_cancellations',
|
||||
'purchase_revisions', 'audit_logs', 'budget_entries', 'stock_movements'];
|
||||
$snapshot = fn () => array_map(fn ($table) => DB::table($table)->orderBy('id')->get()->toJson(), $tables);
|
||||
$before = $snapshot();
|
||||
$response = $this->actingAs($this->admin)->get('/revisao-compras')->assertOk()
|
||||
->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true)
|
||||
->assertInertia(fn (Assert $page) => $page->component('purchase-controls/index')->where('actorId', $this->admin->id)
|
||||
->has('policies', 1)->where('policies.0.status', 'pending')->where('policies.0.enabled', false));
|
||||
expect($response->headers->get('Cache-Control'))->toContain('private', 'no-store');
|
||||
$response = $this->actingAs($this->owner)->get('/revisao-compras')->assertOk()
|
||||
->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true)
|
||||
->assertInertia(fn (Assert $page) => $page->where('actorId', $this->owner->id)->has('policies', 0)->has('awards', 0)->has('cancellations', 0));
|
||||
expect($response->headers->get('Cache-Control'))->toContain('private', 'no-store')
|
||||
->and($snapshot())->toBe($before);
|
||||
});
|
||||
|
||||
test('native partial-order foreign receipts and invoices preserve origin rates and cumulative remainders', function () {
|
||||
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
|
||||
$this->markTestSkipped('Explicit unpublished common source required.');
|
||||
@@ -1813,10 +2006,12 @@ test('native partial-order issuance commits only forty then sixty and preserves
|
||||
if (! method_exists(BudgetControl::class, 'beginRequisitionCycle')) {
|
||||
$this->markTestSkipped('Explicit cycle-capable common QA source required.');
|
||||
}
|
||||
budgetDistributionFixtureSchema();
|
||||
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php')->up();
|
||||
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000008_create_purchase_order_sources.php')->up();
|
||||
(require __DIR__.'/../../database/qa-migrations/2026_11_27_000001_add_requisition_cycles.php')->up();
|
||||
if (getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') !== '1') {
|
||||
budgetDistributionFixtureSchema();
|
||||
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php')->up();
|
||||
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000008_create_purchase_order_sources.php')->up();
|
||||
(require __DIR__.'/../../database/qa-migrations/2026_11_27_000001_add_requisition_cycles.php')->up();
|
||||
}
|
||||
config(['requisition-expiry.qa_enabled' => true]);
|
||||
$engine = app(CommonBudget::class)->for($this->buyer, [$this->r->id => 1]);
|
||||
$engine->beginRequisitionCycle($this->r->id, 1, (string) Str::uuid());
|
||||
@@ -1935,13 +2130,13 @@ function commitNativeReviewReportFixture(object $test): void
|
||||
$test->committedConsolidatedReportFixture = true;
|
||||
}
|
||||
|
||||
test('native delivery analysis follows the frozen promise partial receipts and actual completion without changing sources', function () {
|
||||
test('native delivery analysis follows the frozen promise partial receipts and actual completion without changing sources', function (bool $afterDue) {
|
||||
$award = selectPurchaseAward($this);
|
||||
$order = issuePurchaseOrder($this, $award);
|
||||
$service = app(\App\Services\ProcurementDeliveryInsights::class);
|
||||
$read = fn () => $service->build($this->buyer, Requisition::query()->whereKey($this->r->id), \Carbon\CarbonImmutable::now(), null, 'all');
|
||||
$service = app(ProcurementDeliveryInsights::class);
|
||||
$read = fn () => $service->build($this->buyer, Requisition::query()->whereKey($this->r->id), CarbonImmutable::now(), null, 'all');
|
||||
expect($read()['coverage']['pending'])->toBe(1);
|
||||
$due = \Carbon\CarbonImmutable::parse($order->snapshot['award']['delivery_date'], config('app.timezone'))->setTime(12, 0);
|
||||
$due = CarbonImmutable::parse($order->snapshot['award']['delivery_date'], config('app.timezone'))->setTime(12, 0);
|
||||
$this->travelTo($due);
|
||||
expect($read()['coverage']['pending'])->toBe(1);
|
||||
$receiver = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => PurchasingRole::Warehouse]);
|
||||
@@ -1952,27 +2147,29 @@ test('native delivery analysis follows the frozen promise partial receipts and a
|
||||
'received_quantity' => $quantity, 'accepted_quantity' => $quantity, 'quality_status' => 'compliant', 'stock_item_id' => $stock->id]]];
|
||||
$this->actingAs($receiver);
|
||||
app(ReceiptWorkflow::class)->confirm($receiver, $order, $payload('0.400'));
|
||||
$this->travel(1)->days();
|
||||
$this->travel($afterDue ? 1 : 0)->days();
|
||||
$this->actingAs($this->buyer);
|
||||
$late = $read();
|
||||
expect($late['coverage']['pending_late'])->toBe(1)->and($late['records']['data'][0]['late_days'])->toBe(1)
|
||||
->and($late['records']['data'][0]['late_lines'][0]['pending_quantity'])->toBe('0.600');
|
||||
expect($late['coverage'][$afterDue ? 'pending_late' : 'pending'])->toBe(1);
|
||||
if ($afterDue) {
|
||||
expect($late['records']['data'][0]['late_days'])->toBe(1)->and($late['records']['data'][0]['late_lines'][0]['pending_quantity'])->toBe('0.600');
|
||||
}
|
||||
$this->actingAs($receiver);
|
||||
app(ReceiptWorkflow::class)->confirm($receiver, $order, $payload('0.600'));
|
||||
$this->actingAs($this->buyer);
|
||||
$before = [DB::table('stock_movements')->get()->toJson(), DB::table('budget_entries')->get()->toJson(), DB::table('audit_logs')->get()->toJson()];
|
||||
$complete = $read();
|
||||
expect($complete['coverage']['completed_late'])->toBe(1)->and($complete['pending_lines'])->toBe(0)
|
||||
->and($complete['records']['data'][0]['late_lines'][0]['completed_on'])->toBe(today()->toDateString())
|
||||
$completedState = $afterDue ? 'completed_late' : 'completed_on_time';
|
||||
expect($complete['coverage'][$completedState])->toBe(1)->and($complete['pending_lines'])->toBe(0)
|
||||
->and([DB::table('stock_movements')->get()->toJson(), DB::table('budget_entries')->get()->toJson(), DB::table('audit_logs')->get()->toJson()])->toBe($before);
|
||||
commitNativeReviewReportFixture($this);
|
||||
$this->withoutVite();
|
||||
$this->get('/relatorios?delivery_state=completed_late')->assertOk()->assertInertia(fn (Assert $page) => $page
|
||||
->where('deliveryInsights.coverage.completed_late', 1)->where('deliveryInsights.records.data.0.number', $order->number));
|
||||
$csv = $this->get('/relatorios/entregas.csv?delivery_state=completed_late')->assertOk()->assertDownload()->streamedContent();
|
||||
expect($csv)->toContain($order->number)->toContain('Recepção integral depois da data acordada')->toContain('0.000');
|
||||
$this->get('/relatorios?delivery_state='.$completedState)->assertOk()->assertInertia(fn (Assert $page) => $page
|
||||
->where('deliveryInsights.coverage.'.$completedState, 1)->where('deliveryInsights.records.data.0.number', $order->number));
|
||||
$csv = $this->get('/relatorios/entregas.csv?delivery_state='.$completedState)->assertOk()->assertDownload()->streamedContent();
|
||||
expect($csv)->toContain($order->number)->toContain(ProcurementDeliveryInsights::LABELS[$completedState]);
|
||||
$this->travelBack();
|
||||
});
|
||||
})->with([false, true]);
|
||||
|
||||
function secondNativeOrderPartsOrigin(object $test): array
|
||||
{
|
||||
@@ -2035,8 +2232,8 @@ test('native consolidated order retains both origins and consumes a single invoi
|
||||
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();
|
||||
$delivery = app(\App\Services\ProcurementDeliveryInsights::class)->build($this->buyer, Requisition::query()->whereKey($request->id),
|
||||
\Carbon\CarbonImmutable::now()->addDays(8), null, 'all');
|
||||
$delivery = app(ProcurementDeliveryInsights::class)->build($this->buyer, Requisition::query()->whereKey($request->id),
|
||||
CarbonImmutable::now()->addDays(8), null, 'all');
|
||||
expect($delivery['coverage']['pending_late'])->toBe(1)->and($delivery['unknown_lines'])->toBe(0)
|
||||
->and($delivery['records']['data'][0]['late_lines'])->toHaveCount(1)
|
||||
->and($delivery['records']['data'][0]['late_lines'][0]['id'])->toBe($order->items()->where('requisition_item_id', $this->item->id)->value('id'));
|
||||
|
||||
Reference in New Issue
Block a user