@@ -0,0 +1,174 @@
|
||||
<?php
|
||||
|
||||
use App\Models\SupplyRecord;
|
||||
use App\Services\SupplyPlanning;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
|
||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||
require_once __DIR__.'/../Support/SupplyFixture.php';
|
||||
|
||||
beforeEach(function () {
|
||||
// Data/workflow checks use a private build separately; never install a new manifest in the pilot for a test.
|
||||
$this->withoutVite();
|
||||
$this->f = receiptFixture();
|
||||
supplyGrant($this->f['issuer'], ['supply_prepare']);
|
||||
supplyGrant($this->f['receiver'], ['supply_read', 'supply_review']);
|
||||
$this->actingAs($this->f['receiver']);
|
||||
});
|
||||
|
||||
function followupAgreement($test, string $from, string $until, string $reference = 'AGREEMENT-QA'): SupplyRecord
|
||||
{
|
||||
$test->actingAs($test->f['issuer']);
|
||||
$service = app(SupplyPlanning::class);
|
||||
$draft = $service->save($test->f['issuer'], 'agreement', supplyInput(['stock_item_id' => $test->f['stock']->id, 'warehouse_id' => $test->f['warehouse']->id,
|
||||
'supplier_id' => $test->f['order']->supplier_id, 'habitual' => false, 'valid_from' => $from, 'valid_until' => $until, 'origin' => 'local',
|
||||
'currency' => 'MZN', 'price_minor' => 10000, 'lead_days' => 4, 'reference' => $reference]));
|
||||
$test->actingAs($test->f['receiver']);
|
||||
|
||||
return $service->save($test->f['receiver'], 'agreement', supplyInput([], 'approve', $draft));
|
||||
}
|
||||
|
||||
function followupCounts(): array
|
||||
{
|
||||
return collect(['supply_records', 'audit_logs', 'stock_movements', 'purchase_orders', 'invoices', 'requisitions'])
|
||||
->mapWithKeys(fn ($table) => [$table => DB::table($table)->count()])->all();
|
||||
}
|
||||
|
||||
test('global contract vigency exports all filtered headers with frozen caps and links to approved articles without writes', function () {
|
||||
config(['agreement_order_limits.qa_enabled' => true]);
|
||||
$service = app(SupplyPlanning::class);
|
||||
$contracts = [];
|
||||
foreach ([null, '0', '100.00', ...array_fill(0, 24, null)] as $i => $cap) {
|
||||
$this->actingAs($this->f['issuer']);
|
||||
$draft = $service->save($this->f['issuer'], 'contract', supplyInput(['supplier_id' => $this->f['order']->supplier_id,
|
||||
'reference' => '=QA-HEADER-'.$i, 'currency' => 'MZN', 'valid_from' => today()->toDateString(), 'valid_until' => today()->addMonth()->toDateString(),
|
||||
'periodicity_days' => 30, 'order_limit_amount' => $cap]));
|
||||
$this->actingAs($this->f['receiver']);
|
||||
$contracts[] = $service->save($this->f['receiver'], 'contract', supplyInput([], 'approve', $draft));
|
||||
}
|
||||
$this->actingAs($this->f['issuer']);
|
||||
$draft = $service->save($this->f['issuer'], 'agreement', supplyInput(['stock_item_id' => $this->f['stock']->id, 'warehouse_id' => $this->f['warehouse']->id,
|
||||
'supplier_id' => $this->f['order']->supplier_id, 'habitual' => false, 'valid_from' => today()->toDateString(), 'valid_until' => today()->addMonth()->toDateString(),
|
||||
'origin' => 'local', 'currency' => 'MZN', 'reference' => 'QA-CHILD', 'contract_key' => $contracts[0]->record_key, 'lead_days' => 2]));
|
||||
$this->actingAs($this->f['receiver']);
|
||||
$child = $service->save($this->f['receiver'], 'agreement', supplyInput([], 'approve', $draft));
|
||||
$before = followupCounts();
|
||||
$this->get('/compras/acordos/vigencia?kind=contract&validity=current')->assertOk()->assertInertia(fn (Assert $page) => $page
|
||||
->where('kind', 'contract')->has('records.data', 25)->where('records.total', 27)->where('records.data.0.approved_articles', 1)->where('records.data.0.max_order_value_minor', null)
|
||||
->where('records.data.1.max_order_value_minor', 0)->where('records.data.0.articles_href', '/compras/fornecimento?view=agreements&linked_contract_key='.$contracts[0]->record_key));
|
||||
$response = $this->get('/compras/acordos/vigencia.csv?kind=contract&validity=current');
|
||||
$response->assertOk()->assertHeader('Content-Disposition', 'attachment; filename="vigencia-contratos-'.today()->toDateString().'.csv"');
|
||||
$rows = followupCsv($response->getContent());
|
||||
expect($rows)->toHaveCount(30)->and($rows[2])->toHaveCount(18)->and($rows[3])->toHaveCount(18)->and($rows[3][2])->toBe("'=QA-HEADER-0")
|
||||
->and($rows[3][14])->toBe('Não definido')->and($rows[4][14])->toBe('0')->and($rows[5][14])->toBe('10000')->and($rows[3][16])->toBe('1');
|
||||
expect(followupCounts())->toBe($before);
|
||||
$service->save($this->f['receiver'], 'agreement', supplyInput([], 'suspend', $child));
|
||||
$this->get('/compras/acordos/vigencia?kind=contract')->assertOk()->assertInertia(fn (Assert $page) => $page->where('records.data.0.approved_articles', 0));
|
||||
$service->save($this->f['receiver'], 'contract', supplyInput([], 'suspend', $contracts[0]));
|
||||
$this->get('/compras/acordos/vigencia?kind=contract')->assertOk()->assertInertia(fn (Assert $page) => $page->where('records.total', 26));
|
||||
config(['agreement_order_limits.qa_enabled' => false]);
|
||||
$this->get('/compras/acordos/vigencia?kind=contract')->assertStatus(503);
|
||||
$this->get('/compras/acordos/vigencia?kind=other')->assertSessionHasErrors('kind');
|
||||
});
|
||||
|
||||
function followupCsv(string $body): array
|
||||
{
|
||||
$file = fopen('php://temp', 'w+');
|
||||
fwrite($file, $body);
|
||||
rewind($file);
|
||||
$rows = [];
|
||||
while (($row = fgetcsv($file, null, ';', '"', '')) !== false) {
|
||||
$rows[] = $row;
|
||||
}
|
||||
fclose($file);
|
||||
|
||||
return $rows;
|
||||
}
|
||||
|
||||
test('agreement vigency uses inclusive boundaries and keeps missing legacy dates indeterminate', function () {
|
||||
$today = today()->toDateString();
|
||||
$endToday = followupAgreement($this, today()->subDay()->toDateString(), $today, 'END-TODAY');
|
||||
$startToday = followupAgreement($this, $today, today()->addDay()->toDateString(), 'START-TODAY');
|
||||
followupAgreement($this, today()->subDays(3)->toDateString(), today()->subDay()->toDateString(), 'EXPIRED');
|
||||
followupAgreement($this, today()->addDay()->toDateString(), today()->addDays(2)->toDateString(), 'FUTURE');
|
||||
// Synthetic legacy source without dates: unknown is not zero, expired or current.
|
||||
SupplyRecord::query()->create(['tenant_id' => $this->f['tenant']->id, 'kind' => 'agreement', 'record_key' => (string) Str::uuid(), 'version' => 1, 'state' => 'approved',
|
||||
'stock_item_id' => $this->f['stock']->id, 'warehouse_id' => $this->f['warehouse']->id, 'supplier_id' => $this->f['order']->supplier_id,
|
||||
'created_by' => $this->f['issuer']->id, 'data' => ['reference' => 'LEGACY-NO-DATE'], 'snapshot' => [], 'reason' => 'Fonte legada sintética de teste.',
|
||||
'operation_key' => (string) Str::uuid(), 'input_hash' => str_repeat('0', 64), 'created_at' => now()]);
|
||||
$counts = followupCounts();
|
||||
$this->get('/compras/acordos/vigencia?validity=current')->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')
|
||||
->assertInertia(fn (Assert $page) => $page->component('supply/agreement-followup')->where('asOf', $today)->where('records.total', 2)
|
||||
->where('records.data.0.id', $endToday->id)->where('records.data.1.id', $startToday->id));
|
||||
foreach (['expired' => 'EXPIRED', 'future' => 'FUTURE', 'unknown' => 'LEGACY-NO-DATE'] as $filter => $reference) {
|
||||
$this->get('/compras/acordos/vigencia?validity='.$filter)->assertInertia(fn (Assert $page) => $page->where('records.total', 1)->where('records.data.0.reference', $reference));
|
||||
}
|
||||
expect(followupCounts())->toBe($counts);
|
||||
});
|
||||
|
||||
test('expiry search and explicit cutoff use the same scope in the page and complete csv across pages', function () {
|
||||
for ($i = 0; $i < 27; $i++) {
|
||||
followupAgreement($this, today()->subDay()->toDateString(), today()->addDay()->toDateString(), 'EXPIRY-QA-'.$i);
|
||||
}
|
||||
followupAgreement($this, today()->toDateString(), today()->addMonth()->toDateString(), 'LATER-QA');
|
||||
$cutoff = today()->addDay()->toDateString();
|
||||
$counts = followupCounts();
|
||||
$this->get('/compras/acordos/vigencia?search=expiry&expires_by='.$cutoff.'&page=2')->assertInertia(fn (Assert $page) => $page->where('records.total', 27)->has('records.data', 2)
|
||||
->where('filters.expires_by', $cutoff)->where('filters.search', 'expiry'));
|
||||
$response = $this->get('/compras/acordos/vigencia.csv?search=expiry&expires_by='.$cutoff.'&page=2')->assertOk()->assertHeader('Content-Type', 'text/csv; charset=UTF-8');
|
||||
$rows = followupCsv($response->getContent());
|
||||
expect($rows)->toHaveCount(30)->and(array_unique(array_column(array_slice($rows, 3), 0)))->toHaveCount(27)
|
||||
->and(array_column(array_slice($rows, 3), 2))->not->toContain('LATER-QA')->and(followupCounts())->toBe($counts);
|
||||
});
|
||||
|
||||
test('a later suspension excludes an old approved version and does not revive it in the report', function () {
|
||||
$record = followupAgreement($this, today()->toDateString(), today()->addWeek()->toDateString());
|
||||
app(SupplyPlanning::class)->save($this->f['receiver'], 'agreement', supplyInput([], 'suspend', $record));
|
||||
$this->get('/compras/acordos/vigencia')->assertInertia(fn (Assert $page) => $page->where('records.total', 0));
|
||||
expect(followupCsv($this->get('/compras/acordos/vigencia.csv')->assertOk()->getContent()))->toHaveCount(3);
|
||||
expect($record->fresh()->state)->toBe('approved');
|
||||
});
|
||||
|
||||
test('the report counts approved policy identities and opens only policies linked to the selected agreement', function () {
|
||||
$record = followupAgreement($this, today()->toDateString(), today()->addWeek()->toDateString());
|
||||
$other = followupAgreement($this, today()->toDateString(), today()->addWeek()->toDateString(), 'OTHER-AGREEMENT');
|
||||
$planning = app(SupplyPlanning::class);
|
||||
$this->actingAs($this->f['issuer']);
|
||||
$draft = $planning->save($this->f['issuer'], 'policy', supplyInput([...supplyPolicy($this->f), 'agreement_key' => $record->record_key]));
|
||||
$this->actingAs($this->f['receiver']);
|
||||
$approved = $planning->save($this->f['receiver'], 'policy', supplyInput([], 'approve', $draft));
|
||||
$this->get('/compras/acordos/vigencia')->assertInertia(fn (Assert $page) => $page->where('records.data.0.approved_policies', 1)->where('records.data.1.approved_policies', 0)
|
||||
->where('records.data.0.policies_href', '/compras/fornecimento?view=calendar&linked_agreement_key='.$record->record_key));
|
||||
$this->get('/compras/fornecimento?view=calendar&linked_agreement_key='.$record->record_key)->assertInertia(fn (Assert $page) => $page->has('records', 1)->where('records.0.id', $approved->id)->where('linkedAgreementKey', $record->record_key));
|
||||
$this->get('/compras/fornecimento?view=calendar&linked_agreement_key='.$other->record_key)->assertInertia(fn (Assert $page) => $page->has('records', 0));
|
||||
});
|
||||
|
||||
test('csv neutralizes formula text and preserves unknown dates without inventing values', function () {
|
||||
$record = followupAgreement($this, today()->toDateString(), today()->addDay()->toDateString(), '=SYNTHETIC()');
|
||||
$rows = followupCsv($this->get('/compras/acordos/vigencia.csv')->assertOk()->getContent());
|
||||
expect($rows[3][2])->toBe("'=SYNTHETIC()")->and($rows[3][9])->toBe('Vigente')->and($rows[3][10])->toBe('0')
|
||||
->and($rows[3][11])->toContain('record_id='.$record->id);
|
||||
});
|
||||
|
||||
test('scope current permissions and maintenance are revalidated with no grants or cross company leakage', function () {
|
||||
followupAgreement($this, today()->toDateString(), today()->addDay()->toDateString());
|
||||
$foreign = receiptFixture();
|
||||
supplyGrant($foreign['receiver'], ['supply_read']);
|
||||
$this->actingAs($foreign['receiver'])->get('/compras/acordos/vigencia')->assertInertia(fn (Assert $page) => $page->where('records.total', 0));
|
||||
$this->actingAs($this->f['otherReceiver'])->get('/compras/acordos/vigencia')->assertForbidden();
|
||||
$this->actingAs($this->f['receiver']);
|
||||
DB::table('organization_memberships')->where('user_id', $this->f['receiver']->id)->update(['maintenance' => true]);
|
||||
$this->get('/compras/acordos/vigencia.csv')->assertForbidden();
|
||||
DB::table('organization_memberships')->where('user_id', $this->f['receiver']->id)->update(['maintenance' => false, 'expires_at' => now()->subMinute()]);
|
||||
$this->get('/compras/acordos/vigencia')->assertForbidden();
|
||||
});
|
||||
|
||||
test('malformed filters are refused rather than silently widening the report', function () {
|
||||
foreach (['validity=wrong', 'expires_by=invalid', 'page=0', 'search='.str_repeat('x', 101)] as $filter) {
|
||||
$this->getJson('/compras/acordos/vigencia?'.$filter)->assertUnprocessable();
|
||||
$this->getJson('/compras/acordos/vigencia.csv?'.$filter)->assertUnprocessable();
|
||||
}
|
||||
$this->getJson('/compras/fornecimento?view=calendar&linked_agreement_key=invalid')->assertUnprocessable();
|
||||
});
|
||||
@@ -322,6 +322,23 @@ test('warehouse shortage carries the original destination and equipment and is n
|
||||
$this->actingAs($this->f['issuer'])->get('/requisicoes/'.$r->id)->assertOk()->assertInertia(fn (Assert $p) => $p->where('automaticSource.origins.0.destination', 'Oficina central, bancada de montagem'));
|
||||
});
|
||||
|
||||
test('production shortage retains the declared production reference in the native purchase origin', function () {
|
||||
activateAutomaticRule($this);
|
||||
supplyGrant($this->f['issuer'], ['warehouse_request_prepare']);
|
||||
supplyGrant($this->f['receiver'], ['warehouse_request_review']);
|
||||
$this->actingAs($this->f['issuer']);
|
||||
$request = app(WarehouseRequests::class)->draft($this->f['issuer'], ['operation_key' => (string) Str::uuid(), 'warehouse_id' => $this->f['warehouse']->id, 'cost_center_id' => $this->f['r']->cost_center_id,
|
||||
'destination' => 'Linha de produção QA', 'reason' => 'Insumos sintéticos para a produção.', 'priority' => 'normal',
|
||||
'lines' => [['stock_item_id' => $this->f['stock']->id, 'quantity' => '125.000', 'use' => 'production', 'equipment_id' => null, 'production_reference' => 'OP-QA-001']]]);
|
||||
app(WarehouseFulfilment::class)->command($this->f['issuer'], $request->id, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'action' => 'submit', 'reason' => 'Submissão de teste da produção.', 'partial_allowed' => true]);
|
||||
$this->actingAs($this->f['receiver']);
|
||||
app(WarehouseFulfilment::class)->command($this->f['receiver'], $request->id, ['operation_key' => (string) Str::uuid(), 'version' => 1, 'action' => 'authorize', 'reason' => 'Autorização de teste da produção.', 'partial_allowed' => true]);
|
||||
app(AutomaticPurchases::class)->evaluate($this->f['receiver'], $this->f['stock']->id, $this->f['warehouse']->id);
|
||||
$need = app(SupplyPlanning::class)->latest('auto_need')->sole();
|
||||
$r = Requisition::query()->findOrFail($need->data['purchases'][0]['id']);
|
||||
expect(app(AutomaticPurchases::class)->origin($r)['origins'][0]['production'])->toBe(['reference' => 'OP-QA-001', 'verification' => 'user_supplied']);
|
||||
});
|
||||
|
||||
test('revoked requester authority or expired work context cannot be borrowed for automatic purchases', function () {
|
||||
activateAutomaticRule($this);
|
||||
DB::table('organization_memberships')->where('user_id', $this->f['issuer']->id)->update(['expires_at' => now()->subMinute()]);
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
|
||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||
|
||||
beforeEach(function () {
|
||||
$this->f = receiptFixture();
|
||||
$this->actingAs($this->f['issuer']);
|
||||
$this->partial = ['operation_key' => (string) Str::uuid(), 'priority' => 'normal', 'justification' => 'Ini', 'items' => [
|
||||
['description' => 'Artigo sintético em preparação', 'purchase_type' => 'consumable', 'quantity' => null, 'unit_price' => null, 'tax_rate' => '16.00', 'unexpected' => 'Do not persist unrelated data'],
|
||||
]];
|
||||
});
|
||||
|
||||
test('incomplete draft persists unknown values without invented amounts and cannot reserve or submit', function () {
|
||||
$entries = DB::table('budget_entries')->count();
|
||||
$this->postJson('/requisicoes', $this->partial)->assertRedirect();
|
||||
$r = Requisition::query()->latest('id')->firstOrFail();
|
||||
expect($r->status)->toBe('draft')->and($r->total_minor)->toBeNull()->and($r->needed_by)->toBeNull()
|
||||
->and($r->cost_center_id)->toBeNull()->and($r->draft_input['values']['items'][0]['unit_price'])->toBeNull()
|
||||
->and($r->items()->count())->toBe(0)->and($r->steps()->count())->toBe(0);
|
||||
expect(array_key_exists('unexpected', $r->draft_input['values']['items'][0]))->toBeFalse();
|
||||
$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();
|
||||
$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);
|
||||
$this->postJson('/requisicoes', $this->partial)->assertRedirect();
|
||||
expect(Requisition::query()->where('requester_id', $this->f['issuer']->id)->where('status', 'draft')->count())->toBe(1);
|
||||
});
|
||||
|
||||
test('completing the same draft restores exact calculations and clears preparation without duplicating the process', function () {
|
||||
$this->postJson('/requisicoes', $this->partial)->assertRedirect();
|
||||
$r = Requisition::query()->latest('id')->firstOrFail();
|
||||
$this->putJson('/requisicoes/'.$r->id, ['operation_key' => (string) Str::uuid(), 'process_version' => $r->process_version,
|
||||
'cost_center_id' => $this->f['r']->cost_center_id, 'priority' => 'normal', 'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Preparação sintética agora completa.',
|
||||
'items' => [['description' => 'Artigo sintético', 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '2.000', 'unit' => 'UN', 'unit_price' => '50.00', 'tax_rate' => '16.00']],
|
||||
])->assertRedirect();
|
||||
expect($r->fresh()->draft_input)->toBeNull()->and($r->fresh()->total_minor)->toBe(11600)->and($r->items()->count())->toBe(1)->and($r->fresh()->status)->toBe('draft');
|
||||
});
|
||||
|
||||
test('partial preparation still rejects invalid supplied values and foreign cost centres', function () {
|
||||
foreach (['quantity' => '-1', 'unit_price' => '-1', 'tax_rate' => '101'] as $key => $value) {
|
||||
$body = $this->partial;
|
||||
$body['items'][0][$key] = $value;
|
||||
$this->postJson('/requisicoes', $body)->assertUnprocessable();
|
||||
}
|
||||
$other = receiptFixture();
|
||||
$this->actingAs($this->f['issuer']);
|
||||
$this->postJson('/requisicoes', [...$this->partial, 'cost_center_id' => $other['r']->cost_center_id])->assertUnprocessable();
|
||||
});
|
||||
|
||||
test('rollback refuses to discard incomplete input and an empty draft can be saved', function () {
|
||||
$this->postJson('/requisicoes', ['items' => []])->assertRedirect();
|
||||
$migration = require database_path('migrations/2026_11_22_000002_allow_incomplete_requisition_drafts.php');
|
||||
expect(fn () => $migration->down())->toThrow(LogicException::class);
|
||||
expect(Requisition::query()->latest('id')->firstOrFail()->total_minor)->toBeNull();
|
||||
});
|
||||
|
||||
test('migration preserves existing document values and legacy validation until explicitly installed', function () {
|
||||
$migration = require database_path('migrations/2026_11_22_000002_allow_incomplete_requisition_drafts.php');
|
||||
$sqlite = DB::getDriverName() === 'sqlite';
|
||||
if ($sqlite) {
|
||||
expect(fn () => $migration->down())->toThrow(LogicException::class);
|
||||
DB::getSchemaBuilder()->table('requisitions', fn ($table) => $table->dropColumn('draft_input'));
|
||||
} else {
|
||||
$migration->down();
|
||||
}
|
||||
$columns = DB::getSchemaBuilder()->getColumnListing('requisitions');
|
||||
$before = DB::table('requisitions')->select($columns)->orderBy('id')->get()->toArray();
|
||||
try {
|
||||
$this->postJson('/requisicoes', $this->partial)->assertUnprocessable();
|
||||
if ($sqlite) {
|
||||
DB::getSchemaBuilder()->table('requisitions', fn ($table) => $table->json('draft_input')->nullable());
|
||||
} else {
|
||||
$migration->up();
|
||||
}
|
||||
expect(DB::table('requisitions')->select($columns)->orderBy('id')->get()->toArray())->toEqual($before);
|
||||
} finally {
|
||||
if (! DB::getSchemaBuilder()->hasColumn('requisitions', 'draft_input')) {
|
||||
if ($sqlite) {
|
||||
DB::getSchemaBuilder()->table('requisitions', fn ($table) => $table->json('draft_input')->nullable());
|
||||
} else {
|
||||
$migration->up();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('partial preparation remains author scoped and refuses stale concurrent edits', function () {
|
||||
$this->postJson('/requisicoes', $this->partial)->assertRedirect();
|
||||
$r = Requisition::query()->latest('id')->firstOrFail();
|
||||
$body = [...$this->partial, 'operation_key' => (string) Str::uuid(), 'process_version' => $r->process_version, 'justification' => 'Nova preparação parcial'];
|
||||
$this->putJson('/requisicoes/'.$r->id, $body)->assertRedirect();
|
||||
$this->putJson('/requisicoes/'.$r->id, [...$body, 'operation_key' => (string) Str::uuid(), 'justification' => 'Edição concorrente'])->assertStatus(409);
|
||||
$other = User::factory()->create(['tenant_id' => $r->tenant_id, 'department_id' => $r->department_id, 'purchasing_role' => PurchasingRole::Requester]);
|
||||
$this->actingAs($other)->putJson('/requisicoes/'.$r->id, [...$body, 'process_version' => $r->fresh()->process_version])->assertForbidden();
|
||||
expect($r->fresh()->draft_input['values']['justification'])->toBe('Nova preparação parcial');
|
||||
});
|
||||
|
||||
test('PostgreSQL refuses a direct transition of incomplete preparation into approval', function () {
|
||||
if (DB::getDriverName() !== 'pgsql') {
|
||||
$this->markTestSkipped('Database constraint is PostgreSQL-specific; SQLite validates application behavior.');
|
||||
}
|
||||
$this->postJson('/requisicoes', $this->partial)->assertRedirect();
|
||||
$r = Requisition::query()->latest('id')->firstOrFail();
|
||||
expect(fn () => DB::transaction(fn () => DB::table('requisitions')->where('id', $r->id)->update(['status' => 'pending'])))->toThrow(QueryException::class);
|
||||
expect($r->fresh()->status)->toBe('draft');
|
||||
});
|
||||
@@ -2,13 +2,16 @@
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\AuditLog;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Services\CompanyDetails;
|
||||
use App\Services\OrganizationAccess;
|
||||
use App\Services\RequisitionWorkflow;
|
||||
use Database\Seeders\DatabaseSeeder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Str;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
|
||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||
@@ -259,3 +262,73 @@ test('a configured account has no fallback development permissions while activat
|
||||
DB::table('organization_access')->where('tenant_id', $this->f['tenant']->id)->update(['active' => true]);
|
||||
$this->get($this->base)->assertOk();
|
||||
});
|
||||
|
||||
test('company details preserve identifiers and are scoped audited and versioned', function () {
|
||||
$body = array_fill_keys(array_keys(CompanyDetails::FIELDS), null) + ['version' => 1, 'reason' => 'Cadastro sintético para ensaio isolado.'];
|
||||
$body['legal_name'] = 'Empresa sintética QA';
|
||||
$body['nuit'] = '001234567';
|
||||
$account = array_fill_keys(array_keys(CompanyDetails::BANK_FIELDS), null);
|
||||
$body['bank_accounts'] = [
|
||||
[...$account, 'id' => (string) Str::uuid(), 'account_number' => '00001234', 'currency' => 'MZN'],
|
||||
[...$account, 'id' => (string) Str::uuid(), 'account_number' => '00005678', 'currency' => 'USD'],
|
||||
];
|
||||
$location = array_fill_keys(array_keys(CompanyDetails::LOCATION_FIELDS), null);
|
||||
$body['establishments'] = [
|
||||
[...$location, 'id' => (string) Str::uuid(), 'kind' => 'headquarters', 'name' => 'Sede QA', 'address' => 'Endereço sintético A'],
|
||||
[...$location, 'id' => (string) Str::uuid(), 'kind' => 'branch', 'name' => 'Sucursal QA', 'address' => 'Endereço sintético B'],
|
||||
];
|
||||
$other = Tenant::query()->create(['name' => 'Outra empresa sintética']);
|
||||
$purchase = $this->f['r']->fresh()->toArray();
|
||||
$this->postJson($this->base.'/company_details', $body)->assertRedirect();
|
||||
expect($this->f['tenant']->fresh()->company_details['bank_accounts'][0]['account_number'])->toBe('00001234')
|
||||
->and($this->f['tenant']->fresh()->company_details['bank_accounts'][1]['currency'])->toBe('USD')
|
||||
->and($this->f['tenant']->fresh()->company_details['establishments'][1]['address'])->toBe('Endereço sintético B')
|
||||
->and($other->fresh()->company_details)->toBeNull()
|
||||
->and($this->f['r']->fresh()->toArray())->toBe($purchase)
|
||||
->and(AuditLog::query()->where('action', 'organization.company_details')->count())->toBe(1);
|
||||
$this->get($this->base)->assertInertia(fn (Assert $page) => $page->where('companyDetailsReady', true)->where('companyDetails.nuit', '001234567'));
|
||||
$this->postJson($this->base.'/company_details', $body)->assertUnprocessable();
|
||||
$this->postJson($this->base.'/company_details', [...$body, 'version' => 2, 'nuit' => '12', 'email' => 'invalid'])->assertUnprocessable();
|
||||
$this->postJson($this->base.'/company_details', [...$body, 'version' => 2, 'tenant_id' => $other->id])->assertUnprocessable();
|
||||
$invalid = $body;
|
||||
$invalid['version'] = 2;
|
||||
$invalid['establishments'][1]['kind'] = 'headquarters';
|
||||
$this->postJson($this->base.'/company_details', $invalid)->assertUnprocessable();
|
||||
$invalid = $body;
|
||||
$invalid['version'] = 2;
|
||||
$invalid['bank_accounts'][1]['id'] = $invalid['bank_accounts'][0]['id'];
|
||||
$this->postJson($this->base.'/company_details', $invalid)->assertUnprocessable();
|
||||
$this->postJson($this->base.'/company_details', [...$body, 'version' => 2])->assertRedirect();
|
||||
expect($this->f['tenant']->fresh()->company_details['bank_accounts'])->toBe($body['bank_accounts']);
|
||||
$invalid = $body;
|
||||
$invalid['version'] = 3;
|
||||
$invalid['bank_accounts'][1]['currency'] = 'US';
|
||||
$this->postJson($this->base.'/company_details', $invalid)->assertUnprocessable();
|
||||
$invalid['bank_accounts'][1]['currency'] = 'USD';
|
||||
$invalid['establishments'][1]['tenant_id'] = $other->id;
|
||||
$this->postJson($this->base.'/company_details', $invalid)->assertUnprocessable();
|
||||
$this->actingAs($this->f['receiver'])->postJson($this->base.'/company_details', [...$body, 'version' => 2])->assertForbidden();
|
||||
});
|
||||
|
||||
test('company details remain unavailable before installation without changing the existing company', function () {
|
||||
$migration = require database_path('migrations/2026_11_22_000001_add_company_details_to_tenants.php');
|
||||
$migration->down();
|
||||
try {
|
||||
$this->get($this->base)->assertInertia(fn (Assert $page) => $page->where('companyDetailsReady', false)->where('companyDetails', null));
|
||||
$body = array_fill_keys(array_keys(CompanyDetails::FIELDS), null) + ['bank_accounts' => [], 'establishments' => [], 'version' => 1, 'reason' => 'Ensaio anterior à instalação dos campos.'];
|
||||
$this->postJson($this->base.'/company_details', $body)->assertStatus(503);
|
||||
expect(DB::table('organization_access')->where('tenant_id', $this->f['tenant']->id)->value('version'))->toBe(1)
|
||||
->and(Tenant::query()->findOrFail($this->f['tenant']->id)->name)->toBe($this->f['tenant']->name);
|
||||
} finally {
|
||||
$migration->up();
|
||||
}
|
||||
});
|
||||
|
||||
test('company details are not saved without their audit record', function () {
|
||||
$body = array_fill_keys(array_keys(CompanyDetails::FIELDS), null) + ['bank_accounts' => [], 'establishments' => [], 'version' => 1, 'reason' => 'Ensaio de recuperação sem auditoria.'];
|
||||
$this->mock(RequisitionWorkflow::class)->shouldReceive('audit')->once()->andThrow(new RuntimeException('Injected audit failure'));
|
||||
$this->withoutExceptionHandling();
|
||||
expect(fn () => $this->postJson($this->base.'/company_details', $body))->toThrow(RuntimeException::class);
|
||||
expect($this->f['tenant']->fresh()->company_details)->toBeNull()
|
||||
->and(DB::table('organization_access')->where('tenant_id', $this->f['tenant']->id)->value('version'))->toBe(1);
|
||||
});
|
||||
|
||||
@@ -228,6 +228,22 @@ test('procurement reading distinguishes submission age need dates and incomplete
|
||||
expect(AuditLog::query()->count())->toBe($audits);
|
||||
});
|
||||
|
||||
test('approval duration uses complete native decisions and filters without inventing missing dates', function () {
|
||||
$this->travelTo(CarbonImmutable::parse('2026-11-22 12:00:00'));
|
||||
$before = AuditLog::query()->count();
|
||||
foreach ([['FAST', '2026-11-21 13:00:00'], ['SLOW', '2026-11-21 15:00:00'], ['FUTURE', '2026-11-23 12:00:00'], ['REVERSED', '2026-11-20 12:00:00']] as [$number, $date]) {
|
||||
$r = reportCopy($this->f['r'], 'DURATION-'.$number, ['status' => 'approved', 'submitted_at' => '2026-11-21 12:00:00']);
|
||||
$r->steps()->create(['tenant_id' => $r->tenant_id, 'position' => 1, 'role' => 'department_head', 'decision' => 'approved', 'decided_at' => $date]);
|
||||
}
|
||||
reportCopy($this->f['r'], 'DURATION-MISSING', ['status' => 'approved', 'submitted_at' => null]);
|
||||
$this->get('/relatorios?search=DURATION')->assertInertia(fn (Assert $page) => $page
|
||||
->where('insights.approval_times.measured', 2)->where('insights.approval_times.unknown', 3)
|
||||
->where('insights.approval_times.total_seconds', 14400)->where('insights.approval_times.min_seconds', 3600)->where('insights.approval_times.max_seconds', 10800));
|
||||
$this->get('/relatorios?search=DURATION-MISSING')->assertInertia(fn (Assert $page) => $page
|
||||
->where('insights.approval_times.measured', 0)->where('insights.approval_times.unknown', 1)->where('insights.approval_times.min_seconds', null));
|
||||
expect(AuditLog::query()->count())->toBe($before);
|
||||
});
|
||||
|
||||
test('reports reject invalid filters on both the screen and export', function () {
|
||||
foreach (['status=unknown', 'from=invalid', 'from=2026-02-02&to=2026-01-01', 'department_id=-1'] as $filter) {
|
||||
$this->getJson('/relatorios?'.$filter)->assertUnprocessable();
|
||||
|
||||
@@ -32,6 +32,20 @@ function reviewCsvRows(string $content): array
|
||||
return $rows;
|
||||
}
|
||||
|
||||
test('review csv exports each frozen per order agreement once and distinguishes undefined caps from zero', function () {
|
||||
$report = app(ProcurementReviewReport::class)->build($this->f['issuer'], $this->f['r']->id);
|
||||
$binding = ['agreement_id' => 7, 'record_key' => 'synthetic', 'version' => 2, 'reference' => '=AGREEMENT-QA', 'basis' => 'per_order', 'currency' => 'MZN', 'unit' => 'un', 'includes_tax' => true,
|
||||
'max_order_value_minor' => null, 'max_order_quantity_milli' => 0, 'checked_order_value_minor' => 12345, 'checked_order_quantity_milli' => '1000'];
|
||||
$report['agreement_limits'] = [$binding, $binding];
|
||||
$rows = reviewCsvRows(app(ProcurementReviewCsv::class)->render($report));
|
||||
expect(array_values(array_filter($rows, fn ($row) => $row === ['Acordo por ordem', '7', 'Referência', "'=AGREEMENT-QA"])))->toHaveCount(1);
|
||||
expect($rows)->toContain(['Acordo por ordem', '7', 'Limite por ordem (centavos)', 'Não definido'])
|
||||
->toContain(['Acordo por ordem', '7', 'Limite por ordem (milésimos)', '0'])
|
||||
->toContain(['Acordo por ordem', '7', 'Total conferido nesta ordem (centavos)', '12345']);
|
||||
$report['agreement_limits'] = 'invalid';
|
||||
expect(fn () => app(ProcurementReviewCsv::class)->render($report))->toThrow(UnexpectedValueException::class);
|
||||
});
|
||||
|
||||
test('complete review csv keeps missing scores distinct from zero and makes no business writes', function () {
|
||||
$before = AuditLog::query()->count();
|
||||
$response = $this->get($this->url)->assertOk()
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\CriticalityLevel;
|
||||
use App\Models\Department;
|
||||
use App\Models\Equipment;
|
||||
use App\Models\GoodsReceipt;
|
||||
use App\Models\Invoice;
|
||||
use App\Models\Supplier;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
|
||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||
|
||||
beforeEach(function () {
|
||||
// The new page is built privately; HTTP scope tests must not require publishing it to the pilot.
|
||||
$this->withoutVite();
|
||||
$this->f = receiptFixture();
|
||||
$this->actingAs($this->f['issuer']);
|
||||
});
|
||||
|
||||
test('process search combines native modules without exposing financial or contact data or writing records', function () {
|
||||
$this->f['r']->update(['number' => 'QA-NEED-001', 'justification' => 'Necessidade sintética de ensaio global.']);
|
||||
$supplier = Supplier::query()->findOrFail($this->f['order']->supplier_id);
|
||||
$supplier->update(['name' => 'QA Supplier', 'email' => 'private@example.invalid']);
|
||||
$before = [];
|
||||
foreach (['audit_logs', 'requisitions', 'purchase_orders', 'stock_movements'] as $table) {
|
||||
$before[$table] = DB::table($table)->count();
|
||||
}
|
||||
$response = $this->get('/compras/pesquisa?q=qa')->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private');
|
||||
$response->assertInertia(fn (Assert $page) => $page->component('search/procurement')->where('term', 'qa')->has('groups', 7)
|
||||
->where('groups.0.records.total', 1)->where('groups.0.records.data.0.title', 'QA-NEED-001')
|
||||
->where('groups.2.records.total', 1)->missing('groups.2.records.data.0.email')->missing('groups.2.records.data.0.nuit'));
|
||||
foreach ($before as $table => $count) {
|
||||
expect(DB::table($table)->count())->toBe($count);
|
||||
}
|
||||
$this->get('/compras/pesquisa?q=global')->assertInertia(fn (Assert $page) => $page->where('groups.0.records.total', 1));
|
||||
$this->get('/compras/pesquisa?q='.urlencode($this->f['order']->number))->assertInertia(fn (Assert $page) => $page->where('groups.1.records.total', 1));
|
||||
});
|
||||
|
||||
test('search scopes results to the current company department and native role', function () {
|
||||
$own = $this->f;
|
||||
$other = receiptFixture();
|
||||
$other['r']->update(['number' => 'SECRET-OTHER-COMPANY']);
|
||||
$this->actingAs($own['issuer']);
|
||||
$department = Department::query()->create(['tenant_id' => $own['tenant']->id, 'name' => 'Outro departamento sintético']);
|
||||
$copy = $own['r']->replicate();
|
||||
$copy->forceFill(['number' => 'SECRET-OTHER-DEPARTMENT', 'department_id' => $department->id])->save();
|
||||
$head = User::factory()->create(['tenant_id' => $own['tenant']->id, 'department_id' => $own['department']->id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
|
||||
$this->actingAs($head)->get('/compras/pesquisa?q=SECRET')->assertInertia(fn (Assert $page) => $page->where('groups.0.records.total', 0));
|
||||
$requester = User::factory()->create(['tenant_id' => $own['tenant']->id, 'department_id' => $own['department']->id, 'purchasing_role' => PurchasingRole::Requester]);
|
||||
$this->actingAs($requester)->get('/compras/pesquisa?q=TEST')->assertInertia(fn (Assert $page) => $page->has('groups', 1)->where('groups.0.records.total', 0));
|
||||
});
|
||||
|
||||
test('search paginates each module and treats wildcards as text without listing the database on empty terms', function () {
|
||||
foreach (range(1, 17) as $index) {
|
||||
$copy = $this->f['r']->replicate();
|
||||
$copy->forceFill(['number' => 'PAGE-SEARCH-'.$index])->save();
|
||||
}
|
||||
$this->get('/compras/pesquisa?q=PAGE-SEARCH')->assertInertia(fn (Assert $page) => $page->where('groups.0.records.total', 17)->has('groups.0.records.data', 15));
|
||||
$this->get('/compras/pesquisa?q=PAGE-SEARCH&requests_page=2')->assertInertia(fn (Assert $page) => $page->where('groups.0.records.current_page', 2)->has('groups.0.records.data', 2));
|
||||
foreach (['', 'x', ' '] as $term) {
|
||||
$this->get('/compras/pesquisa?q='.urlencode($term))->assertInertia(fn (Assert $page) => $page->where('groups', []));
|
||||
}
|
||||
$this->get('/compras/pesquisa?q=%25_')->assertInertia(fn (Assert $page) => $page->where('groups.0.records.total', 0)->where('groups.2.records.total', 0));
|
||||
$this->getJson('/compras/pesquisa?q='.str_repeat('x', 101))->assertUnprocessable();
|
||||
$this->getJson('/compras/pesquisa?q=QA&requests_page=0')->assertUnprocessable();
|
||||
});
|
||||
|
||||
test('search covers stock warehouses equipment and receipt references with native permissions', function () {
|
||||
$f = $this->f;
|
||||
$level = CriticalityLevel::query()->create(['tenant_id' => $f['tenant']->id, 'created_by' => $f['issuer']->id, 'code' => 'SEARCH', 'name' => 'QA', 'criteria' => 'Synthetic test', 'is_critical' => false, 'created_at' => now()]);
|
||||
$asset = Equipment::query()->create(['tenant_id' => $f['tenant']->id, 'created_by' => $f['issuer']->id, 'department_id' => $f['department']->id, 'criticality_level_id' => $level->id, 'code' => 'FIND-EQ', 'description' => 'Synthetic search equipment', 'area' => 'QA', 'status' => 'active']);
|
||||
$receipt = GoodsReceipt::query()->create(['tenant_id' => $f['tenant']->id, 'purchase_order_id' => $f['order']->id, 'received_by' => $f['receiver']->id, 'warehouse_id' => $f['warehouse']->id,
|
||||
'idempotency_key' => (string) Str::uuid(), 'payload_hash' => str_repeat('a', 64), 'delivery_note' => 'FIND-GR', 'received_on' => today(), 'status' => 'confirmed', 'snapshot' => ['synthetic' => true], 'confirmed_at' => now()]);
|
||||
$f['stock']->update(['name' => 'FIND-STOCK']);
|
||||
$f['warehouse']->update(['name' => 'FIND-WAREHOUSE']);
|
||||
$this->get('/compras/pesquisa?q=FIND')->assertInertia(fn (Assert $page) => $page
|
||||
->where('groups.3.records.total', 1)->where('groups.3.records.data.0.href', '/equipamentos/'.$asset->id)
|
||||
->where('groups.4.records.total', 1)->where('groups.5.records.total', 1)
|
||||
->where('groups.6.records.total', 1)->where('groups.6.records.data.0.href', '/recepcoes/'.$receipt->id));
|
||||
$head = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
|
||||
$otherDepartment = Department::query()->create(['tenant_id' => $f['tenant']->id, 'name' => 'Other QA department']);
|
||||
$asset->update(['department_id' => $otherDepartment->id]);
|
||||
$this->actingAs($head)->get('/compras/pesquisa?q=FIND')->assertInertia(fn (Assert $page) => $page->has('groups', 5)->where('groups.3.records.total', 0)->where('groups.4.key', 'receipts')->where('groups.4.records.total', 1));
|
||||
$this->actingAs($f['receiver'])->get('/compras/pesquisa?q=FIND')->assertInertia(fn (Assert $page) => $page->has('groups', 5)->where('groups.1.key', 'equipment')->where('groups.4.records.total', 1));
|
||||
});
|
||||
|
||||
test('search reloads revoked access instead of trusting the authenticated model and requires login', function () {
|
||||
DB::table('users')->where('id', $this->f['issuer']->id)->update(['purchasing_role' => PurchasingRole::Configured->value]);
|
||||
$this->get('/compras/pesquisa?q=TEST')->assertForbidden();
|
||||
auth()->logout();
|
||||
$this->get('/compras/pesquisa?q=TEST')->assertRedirect('/login');
|
||||
});
|
||||
|
||||
test('optional finance search uses native invoice scope and returns references without private snapshots or money', function () {
|
||||
config(['procurement_search.finance_metadata_enabled' => true]);
|
||||
$f = $this->f;
|
||||
$create = fn ($fixture) => Invoice::query()->create(['tenant_id' => $fixture['tenant']->id, 'purchase_order_id' => $fixture['order']->id, 'supplier_id' => $fixture['order']->supplier_id,
|
||||
'created_by' => $fixture['issuer']->id, 'number' => 'QA-SEARCH-INVOICE', 'issued_on' => today(), 'status' => 'pending', 'subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000,
|
||||
'snapshot' => ['synthetic' => true, 'private_note' => 'Never return in search']]);
|
||||
$ownInvoice = $create($f);
|
||||
$create(receiptFixture());
|
||||
$finance = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||
$this->actingAs($finance)->get('/compras/pesquisa?q=QA-SEARCH-INVOICE')->assertInertia(fn (Assert $page) => $page->has('groups', 8)
|
||||
->where('groups.7.key', 'invoices')->where('groups.7.records.total', 1)->where('groups.7.records.data.0.href', '/facturas?invoice_id='.$ownInvoice->id)
|
||||
->missing('groups.7.records.data.0.snapshot')->missing('groups.7.records.data.0.total_minor'));
|
||||
$this->get('/facturas?invoice_id='.$ownInvoice->id)->assertOk()->assertInertia(fn (Assert $page) => $page->where('focusInvoiceId', $ownInvoice->id));
|
||||
$this->actingAs($f['issuer'])->get('/compras/pesquisa?q=QA-SEARCH-INVOICE')->assertInertia(fn (Assert $page) => $page->has('groups', 7));
|
||||
config(['procurement_search.finance_metadata_enabled' => false]);
|
||||
$this->actingAs($finance)->get('/compras/pesquisa?q=QA-SEARCH-INVOICE')->assertInertia(fn (Assert $page) => $page->has('groups', 7));
|
||||
});
|
||||
@@ -27,12 +27,16 @@ use App\Models\Supplier;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Models\Warehouse;
|
||||
use App\Services\AgreementOrderLimits;
|
||||
use App\Services\BudgetWorkflow;
|
||||
use App\Services\ComparisonPolicy;
|
||||
use App\Services\ConflictGuard;
|
||||
use App\Services\DocumentaryQualificationWorkflow;
|
||||
use App\Services\EquipmentWorkflow;
|
||||
use App\Services\FormalAdmission;
|
||||
use App\Services\OrderCancellationPolicyWorkflow;
|
||||
use App\Services\OrderCancellationWorkflow;
|
||||
use App\Services\ProcurementReviewCsv;
|
||||
use App\Services\ProcurementReviewReport;
|
||||
use App\Services\ProposalComparison;
|
||||
use App\Services\ProposalOpeningWorkflow;
|
||||
@@ -41,12 +45,387 @@ use App\Services\PurchaseRevisionWorkflow;
|
||||
use App\Services\QuotationExchange;
|
||||
use App\Services\RequisitionCatalogue;
|
||||
use App\Services\RequisitionWorkflow;
|
||||
use App\Services\SupplyPlanning;
|
||||
use App\Services\WorkflowTaskInbox;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
|
||||
require_once __DIR__.'/../Support/SupplyFixture.php';
|
||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||
|
||||
function perOrderAgreement(object $test, ?string $amount = '100.00', ?string $quantity = '1.000', ?string $stockUnit = null): array
|
||||
{
|
||||
config(['agreement_order_limits.qa_enabled' => true]);
|
||||
expect(app(AgreementOrderLimits::class)->ready())->toBeTrue();
|
||||
foreach (User::query()->where('tenant_id', $test->tenant->id)->get() as $user) {
|
||||
$permissions = [$user->purchasing_role->value];
|
||||
if ($user->id === $test->buyer->id) {
|
||||
$permissions = [...$permissions, 'supply_prepare', 'supply_read'];
|
||||
}
|
||||
if ($user->id === $test->finance->id) {
|
||||
$permissions = [...$permissions, 'supply_review'];
|
||||
}
|
||||
supplyGrant($user, $permissions);
|
||||
}
|
||||
$stock = StockItem::query()->create(['tenant_id' => $test->tenant->id, 'created_by' => $test->buyer->id, 'code' => 'QA-ORDER-LIMIT', 'name' => 'Artigo contratual sintético', 'unit' => $stockUnit ?? $test->item->unit]);
|
||||
$warehouse = Warehouse::query()->create(['tenant_id' => $test->tenant->id, 'created_by' => $test->buyer->id, 'code' => 'QA-LIMIT', 'name' => 'Armazém contratual sintético']);
|
||||
// Explicit synthetic catalogue identity, prepared before selecting/approving the award. Never match by name.
|
||||
$test->item->update(['catalogue_snapshot' => ['stock_item_id' => $stock->id]]);
|
||||
$test->actingAs($test->buyer);
|
||||
$planning = app(SupplyPlanning::class);
|
||||
$draft = $planning->save($test->buyer, 'agreement', supplyInput(['stock_item_id' => $stock->id, 'warehouse_id' => $warehouse->id, 'supplier_id' => $test->quotes[0]->supplier_id,
|
||||
'habitual' => false, 'valid_from' => today()->toDateString(), 'valid_until' => today()->addMonth()->toDateString(), 'origin' => 'local', 'currency' => 'MZN',
|
||||
'price_minor' => 10000, 'lead_days' => 4, 'reference' => 'QA-PER-ORDER', 'order_limit_amount' => $amount, 'order_limit_quantity' => $quantity]));
|
||||
$test->actingAs($test->finance);
|
||||
$agreement = $planning->save($test->finance, 'agreement', supplyInput([], 'approve', $draft));
|
||||
$binding = ['requisition_item_id' => $test->item->id, 'agreement_id' => $agreement->id];
|
||||
|
||||
return compact('agreement', 'binding', 'stock', 'warehouse');
|
||||
}
|
||||
|
||||
test('per order global contract sums different articles and freezes its own approved limit', function (?string $cap, bool $allowed) {
|
||||
$f = perOrderAgreement($this, '100.00', '1.000');
|
||||
$planning = app(SupplyPlanning::class);
|
||||
$this->actingAs($this->buyer);
|
||||
$draft = $planning->save($this->buyer, 'contract', supplyInput(['supplier_id' => $this->quotes[0]->supplier_id, 'reference' => 'QA-GLOBAL-CONTRACT',
|
||||
'currency' => 'MZN', 'valid_from' => today()->toDateString(), 'valid_until' => today()->addMonth()->toDateString(), 'order_limit_amount' => $cap]));
|
||||
$this->actingAs($this->finance);
|
||||
$contract = $planning->save($this->finance, 'contract', supplyInput([], 'approve', $draft));
|
||||
$bindings = [];
|
||||
foreach ([false, true] as $second) {
|
||||
$stock = $f['stock'];
|
||||
$item = $this->item;
|
||||
if ($second) {
|
||||
$stock = $stock->replicate();
|
||||
$stock->forceFill(['code' => 'QA-SECOND-ARTICLE', 'unit' => 'kg'])->save();
|
||||
$item = $this->item->replicate();
|
||||
$item->forceFill(['catalogue_snapshot' => ['stock_item_id' => $stock->id], 'unit' => 'kg'])->save();
|
||||
$this->r->update(['subtotal_minor' => 20000, 'total_minor' => 20000]);
|
||||
foreach ($this->quotes as $quote) {
|
||||
$line = $quote->items()->sole()->replicate();
|
||||
$line->forceFill(['requisition_item_id' => $item->id])->save();
|
||||
$quote->update(['subtotal_minor' => $quote->subtotal_minor * 2, 'total_minor' => $quote->total_minor * 2]);
|
||||
}
|
||||
}
|
||||
$this->actingAs($this->buyer);
|
||||
$draft = $planning->save($this->buyer, 'agreement', supplyInput([...$f['agreement']->data, 'stock_item_id' => $stock->id,
|
||||
'contract_key' => $contract->record_key, 'reference' => 'QA-CONTRACT-ARTICLE-'.($second ? '2' : '1')]));
|
||||
$this->actingAs($this->finance);
|
||||
$agreement = $planning->save($this->finance, 'agreement', supplyInput([], 'approve', $draft));
|
||||
$bindings[] = ['requisition_item_id' => $item->id, 'agreement_id' => $agreement->id];
|
||||
}
|
||||
$award = selectPurchaseAward($this);
|
||||
approvePurchaseAward($this, $award);
|
||||
$response = $this->actingAs($this->buyer)->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => $bindings]);
|
||||
if (! $allowed) {
|
||||
$response->assertUnprocessable()->assertJsonValidationErrors('agreement_bindings');
|
||||
expect(PurchaseOrder::query()->count())->toBe(0);
|
||||
|
||||
return;
|
||||
}
|
||||
$response->assertRedirect();
|
||||
$order = PurchaseOrder::query()->sole();
|
||||
foreach ($order->snapshot['agreement_bindings'] as $row) {
|
||||
expect($row['contract']['checked_order_value_minor'])->toBe(20000)->and($row['contract']['max_order_value_minor'])->toBe($contract->data['max_order_value_minor'])
|
||||
->and($row['contract']['version'])->toBe($contract->version)->and($row['checked_order_value_minor'])->toBe(10000);
|
||||
}
|
||||
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('Contrato global: QA-GLOBAL-CONTRACT');
|
||||
$this->withoutVite()->get('/compras/fornecimento?view=contracts')->assertOk();
|
||||
$this->get('/compras/fornecimento?view=agreements&linked_contract_key='.$contract->record_key)
|
||||
->assertOk()->assertInertia(fn (Assert $page) => $page->component('supply/index')->has('records', 2)->where('linkedContractKey', $contract->record_key));
|
||||
})->with([['150.00', false], ['200.00', true], [null, true], ['0', false]]);
|
||||
|
||||
test('per order contract rejects incompatible association and stale approval without changing earlier versions', function () {
|
||||
$f = perOrderAgreement($this);
|
||||
$planning = app(SupplyPlanning::class);
|
||||
$this->actingAs($this->buyer);
|
||||
$draft = $planning->save($this->buyer, 'contract', supplyInput(['supplier_id' => $this->quotes[0]->supplier_id, 'reference' => 'QA-HEADER',
|
||||
'currency' => 'MZN', 'valid_from' => today()->toDateString(), 'valid_until' => today()->addMonth()->toDateString(), 'order_limit_amount' => '100.00']));
|
||||
expect(fn () => $planning->save($this->buyer, 'contract', supplyInput([], 'approve', $draft)))->toThrow(HttpException::class);
|
||||
$this->actingAs($this->finance);
|
||||
$tasks = collect(app(WorkflowTaskInbox::class)->build($this->finance, 'procurement'))->where('task', 'contract_review');
|
||||
expect($tasks->pluck('href')->all())->toContain('/compras/fornecimento?view=contracts&record_id='.$draft->id.'#supply-record-'.$draft->id);
|
||||
expect($tasks->sole()['reference'])->toBe('QA-HEADER');
|
||||
$contract = $planning->save($this->finance, 'contract', supplyInput([], 'approve', $draft));
|
||||
foreach ([['currency' => 'USD'], ['supplier_id' => 0], ['contract_version' => 999], ['valid_until' => today()->addMonths(2)->toDateString()]] as $change) {
|
||||
expect(fn () => app(AgreementOrderLimits::class)->contract([...$f['agreement']->data, 'contract_key' => $contract->record_key, ...$change], $this->tenant->id))->toThrow(ValidationException::class);
|
||||
}
|
||||
expect(fn () => app(AgreementOrderLimits::class)->contract([...$f['agreement']->data, 'contract_key' => $contract->record_key], $this->tenant->id + 999))->toThrow(ValidationException::class);
|
||||
$this->actingAs($this->buyer);
|
||||
$article = $planning->save($this->buyer, 'agreement', supplyInput([...$f['agreement']->data, 'contract_key' => $contract->record_key]));
|
||||
expect($article->data['contract_version'])->toBe($contract->version);
|
||||
$this->actingAs($this->finance);
|
||||
$approved = $planning->save($this->finance, 'agreement', supplyInput([], 'approve', $article));
|
||||
$this->actingAs($this->buyer);
|
||||
$policyDraft = $planning->save($this->buyer, 'policy', supplyInput([...supplyPolicy($f), 'agreement_key' => $approved->record_key]));
|
||||
$this->actingAs($this->finance);
|
||||
$policy = $planning->save($this->finance, 'policy', supplyInput([], 'approve', $policyDraft));
|
||||
$this->actingAs($this->buyer);
|
||||
$pending = $planning->save($this->buyer, 'agreement', supplyInput([...$f['agreement']->data, 'contract_key' => $contract->record_key]));
|
||||
$this->actingAs($this->finance);
|
||||
$planning->save($this->finance, 'contract', supplyInput([], 'suspend', $contract));
|
||||
expect($planning->calendar($policy, today()->toDateString())['lead_time_available'])->toBeFalse();
|
||||
expect(fn () => $planning->save($this->finance, 'agreement', supplyInput([], 'approve', $pending)))->toThrow(ValidationException::class);
|
||||
expect($contract->fresh()->state)->toBe('approved')->and($article->fresh()->state)->toBe('draft');
|
||||
$award = selectPurchaseAward($this);
|
||||
approvePurchaseAward($this, $award);
|
||||
$this->actingAs($this->buyer)->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [['requisition_item_id' => $this->item->id, 'agreement_id' => $approved->id]]])->assertUnprocessable()->assertJsonValidationErrors('agreement_bindings');
|
||||
expect(PurchaseOrder::query()->count())->toBe(0);
|
||||
});
|
||||
|
||||
test('per order limits preserve equality and each independent order can use the full limit again', function (bool $global) {
|
||||
$f = perOrderAgreement($this);
|
||||
if ($global) {
|
||||
$planning = app(SupplyPlanning::class);
|
||||
$this->actingAs($this->buyer);
|
||||
$draft = $planning->save($this->buyer, 'contract', supplyInput(['supplier_id' => $this->quotes[0]->supplier_id, 'reference' => 'QA-FULL-AGAIN',
|
||||
'currency' => 'MZN', 'valid_from' => today()->toDateString(), 'valid_until' => today()->addMonth()->toDateString(), 'order_limit_amount' => '100.00']));
|
||||
$this->actingAs($this->finance);
|
||||
$header = $planning->save($this->finance, 'contract', supplyInput([], 'approve', $draft));
|
||||
$this->actingAs($this->buyer);
|
||||
$draft = $planning->save($this->buyer, 'agreement', supplyInput([...$f['agreement']->data, 'contract_key' => $header->record_key]));
|
||||
$this->actingAs($this->finance);
|
||||
$f['agreement'] = $planning->save($this->finance, 'agreement', supplyInput([], 'approve', $draft));
|
||||
$f['binding']['agreement_id'] = $f['agreement']->id;
|
||||
}
|
||||
$award = selectPurchaseAward($this);
|
||||
approvePurchaseAward($this, $award);
|
||||
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [$f['binding']]])->assertSessionHasNoErrors()->assertRedirect();
|
||||
$first = PurchaseOrder::query()->sole();
|
||||
$snapshot = $first->snapshot;
|
||||
expect($snapshot['agreement_bindings'][$this->item->id]['max_order_value_minor'])->toBe(10000)
|
||||
->and($snapshot['agreement_bindings'][$this->item->id]['max_order_quantity_milli'])->toBe(1000)
|
||||
->and($snapshot['agreement_bindings'][$this->item->id]['basis'])->toBe('per_order');
|
||||
$request = $this->r->replicate();
|
||||
$request->forceFill(['number' => 'REQ-ORDER-SECOND'])->save();
|
||||
foreach ($this->r->steps()->get() as $step) {
|
||||
$copy = $step->replicate();
|
||||
$copy->forceFill(['requisition_id' => $request->id])->save();
|
||||
}
|
||||
$item = $this->item->replicate();
|
||||
$item->forceFill(['requisition_id' => $request->id])->save();
|
||||
$quotes = [];
|
||||
foreach ($this->quotes as $quote) {
|
||||
$copy = $quote->replicate();
|
||||
$copy->forceFill(['requisition_id' => $request->id])->save();
|
||||
foreach ($quote->items()->get() as $line) {
|
||||
$new = $line->replicate();
|
||||
$new->forceFill(['quotation_id' => $copy->id, 'requisition_item_id' => $item->id])->save();
|
||||
}
|
||||
foreach ($quote->evaluations()->get() as $evaluation) {
|
||||
$new = $evaluation->replicate();
|
||||
$new->forceFill(['quotation_id' => $copy->id])->save();
|
||||
}
|
||||
$quotes[] = $copy;
|
||||
}
|
||||
$this->r = $request;
|
||||
$this->item = $item;
|
||||
$this->quotes = $quotes;
|
||||
$this->selection['quotation_id'] = $quotes[0]->id;
|
||||
$this->awardUrl = '/requisicoes/'.$request->id.'/adjudicacao';
|
||||
$this->actingAs($this->buyer)->post($this->awardUrl, $this->selection)->assertSessionHasNoErrors();
|
||||
$secondAward = PurchaseAward::query()->where('requisition_id', $request->id)->sole();
|
||||
approvePurchaseAward($this, $secondAward);
|
||||
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$secondAward->id.'/emitir', ['agreement_bindings' => [['requisition_item_id' => $item->id, 'agreement_id' => $f['agreement']->id]]])->assertSessionHasNoErrors();
|
||||
expect(PurchaseOrder::query()->count())->toBe(2)->and((int) PurchaseOrder::query()->sum('total_minor'))->toBe(20000)
|
||||
->and($first->fresh()->snapshot)->toBe($snapshot)->and($f['agreement']->fresh()->data['max_order_value_minor'])->toBe(10000);
|
||||
if (DB::getDriverName() === 'sqlite') {
|
||||
// PostgreSQL report snapshots are exercised outside Pest's outer transaction by the existing report worker.
|
||||
$report = app(ProcurementReviewReport::class)->build($this->buyer, $first->requisition_id);
|
||||
expect($report['agreement_limits'])->toBe($snapshot['agreement_bindings']);
|
||||
expect(app(ProcurementReviewCsv::class)->render($report))->toContain('Acordo por ordem')->toContain('QA-PER-ORDER');
|
||||
if ($global) {
|
||||
expect(app(ProcurementReviewCsv::class)->render($report))->toContain('Contrato global por ordem')->toContain('QA-FULL-AGAIN');
|
||||
expect(array_values($first->snapshot['agreement_bindings'])[0]['contract']['checked_order_value_minor'])->toBe(10000);
|
||||
}
|
||||
}
|
||||
})->with([false, true]);
|
||||
|
||||
test('per order limits reject excess and explicit zero before committing any order', function (?string $value, ?string $quantity) {
|
||||
$f = perOrderAgreement($this, $value, $quantity);
|
||||
$award = selectPurchaseAward($this);
|
||||
approvePurchaseAward($this, $award);
|
||||
$before = BudgetEntry::query()->get()->toArray();
|
||||
$this->actingAs($this->buyer)->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [$f['binding']]])->assertUnprocessable()->assertJsonValidationErrors('agreement_bindings');
|
||||
expect(PurchaseOrder::query()->count())->toBe(0)->and(BudgetEntry::query()->get()->toArray())->toBe($before);
|
||||
})->with([['99.99', '1.000'], ['100.00', '0.999'], ['0', null], [null, '0']]);
|
||||
|
||||
test('per order limits keep an absent limit distinct from zero and recover issue without another effect', function () {
|
||||
$f = perOrderAgreement($this, null, null);
|
||||
$award = selectPurchaseAward($this);
|
||||
approvePurchaseAward($this, $award);
|
||||
$payload = ['agreement_bindings' => [$f['binding']]];
|
||||
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/emitir', $payload)->assertSessionHasNoErrors();
|
||||
$order = PurchaseOrder::query()->sole();
|
||||
$snapshot = $order->snapshot;
|
||||
$this->post('/adjudicacoes/'.$award->id.'/emitir', $payload)->assertSessionHasNoErrors();
|
||||
$this->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [[...$f['binding'], 'agreement_id' => $f['agreement']->id + 100]]])->assertConflict();
|
||||
expect(PurchaseOrder::query()->count())->toBe(1)->and($order->fresh()->snapshot)->toBe($snapshot)
|
||||
->and($snapshot['agreement_bindings'][$this->item->id]['max_order_value_minor'])->toBeNull()
|
||||
->and(AuditLog::query()->where('action', 'purchase_order.issued')->count())->toBe(1);
|
||||
});
|
||||
|
||||
test('per order limits refuse suspended stale foreign source data and omitted source read permission', function () {
|
||||
$f = perOrderAgreement($this);
|
||||
$award = selectPurchaseAward($this);
|
||||
approvePurchaseAward($this, $award);
|
||||
$this->actingAs($this->finance);
|
||||
app(SupplyPlanning::class)->save($this->finance, 'agreement', supplyInput([], 'suspend', $f['agreement']));
|
||||
$this->actingAs($this->buyer)->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [$f['binding']]])->assertUnprocessable();
|
||||
$this->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [[...$f['binding'], 'requisition_item_id' => 999999]]])->assertUnprocessable();
|
||||
DB::table('organization_profiles')->whereIn('id', DB::table('organization_memberships')->where('user_id', $this->buyer->id)->select('profile_id'))->update(['permissions' => json_encode(['procurement'])]);
|
||||
$this->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [$f['binding']]])->assertForbidden();
|
||||
expect(PurchaseOrder::query()->count())->toBe(0);
|
||||
});
|
||||
|
||||
test('per order quantity limits use the explicit frozen conversion without changing commercial prices', function () {
|
||||
$f = perOrderAgreement($this, '100.00', '12.000', 'pcs');
|
||||
$award = selectPurchaseAward($this);
|
||||
approvePurchaseAward($this, $award);
|
||||
$body = $f['binding'];
|
||||
$body['conversion'] = ['numerator' => '12', 'denominator' => '1', 'source' => 'Embalagem contratual sintética', 'version' => 'QA-PACK-1'];
|
||||
$bad = $body;
|
||||
$bad['conversion']['denominator'] = '7';
|
||||
$this->actingAs($this->buyer)->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [$bad]])->assertUnprocessable();
|
||||
$this->actingAs($this->buyer)->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [$f['binding']]])->assertUnprocessable();
|
||||
$this->post('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [$body]])->assertSessionHasNoErrors();
|
||||
$order = PurchaseOrder::query()->sole();
|
||||
expect($order->total_minor)->toBe(10000)->and($order->items()->sole()->quantity)->toBe('1.000')
|
||||
->and($order->snapshot['agreement_bindings'][$this->item->id]['agreement_quantity_milli'])->toBe('12000')
|
||||
->and($order->snapshot['agreement_bindings'][$this->item->id]['conversion'])->toBe($body['conversion']);
|
||||
});
|
||||
|
||||
test('per order limit preparation is exact rejects cumulative modes and is unavailable outside its qa switch', function () {
|
||||
config(['agreement_order_limits.qa_enabled' => true]);
|
||||
$limits = app(AgreementOrderLimits::class);
|
||||
expect($limits->terms(['order_limit_amount' => '123.45', 'order_limit_quantity' => '12.345']))->toBe(['order_limit_basis' => 'per_order', 'max_order_value_minor' => 12345, 'max_order_quantity_milli' => 12345]);
|
||||
expect($limits->terms(['order_limit_amount' => '', 'order_limit_quantity' => ' ']))->toBe(['order_limit_basis' => 'per_order', 'max_order_value_minor' => null, 'max_order_quantity_milli' => null]);
|
||||
expect($limits->terms(['order_limit_amount' => '10000000000.00', 'order_limit_quantity' => '1000000000.000']))->toBe(['order_limit_basis' => 'per_order', 'max_order_value_minor' => 1000000000000, 'max_order_quantity_milli' => 1000000000000]);
|
||||
foreach ([['order_limit_amount' => '1.001'], ['order_limit_quantity' => '1.0001'], ['order_limit_amount' => '-1'], ['order_limit_amount' => '1', 'order_limit_basis' => 'cumulative']] as $body) {
|
||||
expect(fn () => $limits->terms($body))->toThrow(ValidationException::class);
|
||||
}
|
||||
config(['agreement_order_limits.qa_enabled' => false]);
|
||||
expect(fn () => $limits->terms(['order_limit_amount' => '1']))->toThrow(HttpException::class)
|
||||
->and($limits->terms(['reference' => 'legacy']))->toBe([]);
|
||||
});
|
||||
|
||||
test('per order limits aggregate all covered lines of the same agreement instead of granting a limit to each line', function (string $amount, string $quantity, bool $allowed) {
|
||||
$f = perOrderAgreement($this, $amount, $quantity);
|
||||
$second = $this->item->replicate();
|
||||
$second->save();
|
||||
$this->r->update(['subtotal_minor' => 20000, 'total_minor' => 20000]);
|
||||
foreach ($this->quotes as $quote) {
|
||||
$line = $quote->items()->sole()->replicate();
|
||||
$line->forceFill(['requisition_item_id' => $second->id])->save();
|
||||
$quote->update(['subtotal_minor' => $quote->subtotal_minor * 2, 'total_minor' => $quote->total_minor * 2]);
|
||||
}
|
||||
$award = selectPurchaseAward($this);
|
||||
approvePurchaseAward($this, $award);
|
||||
$payload = ['agreement_bindings' => [$f['binding'], ['requisition_item_id' => $second->id, 'agreement_id' => $f['agreement']->id]]];
|
||||
$response = $this->actingAs($this->buyer)->postJson('/adjudicacoes/'.$award->id.'/emitir', $payload);
|
||||
if (! $allowed) {
|
||||
$response->assertUnprocessable()->assertJsonValidationErrors('agreement_bindings');
|
||||
expect(PurchaseOrder::query()->count())->toBe(0);
|
||||
|
||||
return;
|
||||
}
|
||||
$response->assertRedirect();
|
||||
$order = PurchaseOrder::query()->sole();
|
||||
expect($order->total_minor)->toBe(20000)->and($order->snapshot['agreement_bindings'][$this->item->id]['checked_order_value_minor'])->toBe(20000)
|
||||
->and($order->snapshot['agreement_bindings'][$second->id]['checked_order_quantity_milli'])->toBe('2000');
|
||||
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('Acordos e limites preservados por ordem')->assertSee('QA-PER-ORDER');
|
||||
})->with([['200.00', '1.500', false], ['150.00', '2.000', false], ['200.00', '2.000', true]]);
|
||||
|
||||
test('per order value limit includes taxes rather than only the net amount', function (string $amount, bool $allowed) {
|
||||
$f = perOrderAgreement($this, $amount, '1.000');
|
||||
awardPrices($this, 10000, 16);
|
||||
$this->r->update(['tax_minor' => 1600, 'total_minor' => 11600]);
|
||||
$award = selectPurchaseAward($this);
|
||||
approvePurchaseAward($this, $award);
|
||||
$response = $this->actingAs($this->buyer)->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [$f['binding']]]);
|
||||
if (! $allowed) {
|
||||
$response->assertUnprocessable()->assertJsonValidationErrors('agreement_bindings');
|
||||
expect(PurchaseOrder::query()->count())->toBe(0);
|
||||
|
||||
return;
|
||||
}
|
||||
$response->assertRedirect();
|
||||
expect(PurchaseOrder::query()->sole()->snapshot['agreement_bindings'][$this->item->id]['checked_order_value_minor'])->toBe(11600);
|
||||
})->with([['100.00', false], ['116.00', true]]);
|
||||
|
||||
test('per order frozen article and warehouse are reused by receipt without changing documentary quantities', function () {
|
||||
$f = perOrderAgreement($this);
|
||||
$award = selectPurchaseAward($this);
|
||||
approvePurchaseAward($this, $award);
|
||||
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [$f['binding']]])->assertSessionHasNoErrors();
|
||||
$order = PurchaseOrder::query()->sole();
|
||||
$original = $order->snapshot;
|
||||
$receiver = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => PurchasingRole::Warehouse]);
|
||||
supplyGrant($receiver, ['warehouse']);
|
||||
$this->actingAs($receiver);
|
||||
$body = ['idempotency_key' => (string) Str::uuid(), 'delivery_note' => 'QA-CONTRACT-RECEIPT', 'received_on' => today()->toDateString(), 'warehouse_id' => null,
|
||||
'items' => [['purchase_order_item_id' => $order->items()->sole()->id, 'received_quantity' => '1.000', 'accepted_quantity' => '1.000', 'quality_status' => 'compliant', 'stock_item_id' => null]]];
|
||||
$this->postJson('/ordens/'.$order->id.'/recepcoes', $body)->assertUnprocessable();
|
||||
$body['warehouse_id'] = $f['warehouse']->id;
|
||||
$this->postJson('/ordens/'.$order->id.'/recepcoes', $body)->assertCreated();
|
||||
expect(StockMovement::query()->sole()->stock_item_id)->toBe($f['stock']->id)->and(StockMovement::query()->sole()->quantity_milli)->toBe(1000)
|
||||
->and($order->fresh()->snapshot)->toBe($original)->and($f['agreement']->fresh()->data['max_order_quantity_milli'])->toBe(1000);
|
||||
});
|
||||
|
||||
test('per order agreement search retains selected eligible sources beyond the hundred row window without reviving suspension', function () {
|
||||
$f = perOrderAgreement($this);
|
||||
$this->actingAs($this->buyer);
|
||||
for ($index = 0; $index < 101; $index++) {
|
||||
$copy = $f['agreement']->replicate();
|
||||
$copy->forceFill(['record_key' => (string) Str::uuid(), 'version' => 1, 'operation_key' => (string) Str::uuid(),
|
||||
'created_at' => now(),
|
||||
'input_hash' => hash('sha256', 'synthetic-pagination-agreement:'.$index),
|
||||
'reason' => 'Fixture sintética de paginação; não representa aprovação empresarial.',
|
||||
'data' => [...$f['agreement']->data, 'reference' => 'NEWER-QA-'.$index]])->save();
|
||||
}
|
||||
$limits = app(AgreementOrderLimits::class);
|
||||
expect($limits->options($this->buyer, $this->r, $this->quotes[0]))->toHaveCount(100);
|
||||
expect($limits->options($this->buyer, $this->r, $this->quotes[0], 'NO-MATCH', [$f['agreement']->id]))->toHaveCount(1);
|
||||
$this->actingAs($this->finance);
|
||||
app(SupplyPlanning::class)->save($this->finance, 'agreement', supplyInput([], 'suspend', $f['agreement']));
|
||||
$this->actingAs($this->buyer);
|
||||
expect($limits->options($this->buyer, $this->r, $this->quotes[0], 'NO-MATCH', [$f['agreement']->id]))->toBe([]);
|
||||
});
|
||||
|
||||
test('per order source from another company cannot be bound even when its identity is known', function () {
|
||||
$f = perOrderAgreement($this);
|
||||
$award = selectPurchaseAward($this);
|
||||
approvePurchaseAward($this, $award);
|
||||
$foreign = receiptFixture();
|
||||
supplyGrant($foreign['issuer'], ['supply_prepare']);
|
||||
supplyGrant($foreign['receiver'], ['supply_review']);
|
||||
$this->actingAs($foreign['issuer']);
|
||||
$planning = app(SupplyPlanning::class);
|
||||
$draft = $planning->save($foreign['issuer'], 'agreement', supplyInput(['stock_item_id' => $foreign['stock']->id, 'warehouse_id' => $foreign['warehouse']->id,
|
||||
'supplier_id' => $foreign['order']->supplier_id, 'habitual' => false, 'valid_from' => today()->toDateString(), 'valid_until' => today()->addMonth()->toDateString(),
|
||||
'origin' => 'local', 'currency' => 'MZN', 'price_minor' => 10000, 'lead_days' => 4, 'reference' => 'FOREIGN-QA', 'order_limit_amount' => '100.00']));
|
||||
$this->actingAs($foreign['receiver']);
|
||||
$other = $planning->save($foreign['receiver'], 'agreement', supplyInput([], 'approve', $draft));
|
||||
$this->actingAs($this->buyer)->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [[...$f['binding'], 'agreement_id' => $other->id]]])->assertUnprocessable();
|
||||
expect(PurchaseOrder::query()->where('tenant_id', $this->tenant->id)->count())->toBe(0);
|
||||
});
|
||||
|
||||
test('per order limits refuse an agreement in another currency without inventing a conversion', function () {
|
||||
$f = perOrderAgreement($this);
|
||||
$planning = app(SupplyPlanning::class);
|
||||
$this->actingAs($this->buyer);
|
||||
$draft = $planning->save($this->buyer, 'agreement', supplyInput([...$f['agreement']->data, 'currency' => 'USD', 'reference' => 'WRONG-CURRENCY-QA']));
|
||||
$this->actingAs($this->finance);
|
||||
$wrong = $planning->save($this->finance, 'agreement', supplyInput([], 'approve', $draft));
|
||||
$award = selectPurchaseAward($this);
|
||||
approvePurchaseAward($this, $award);
|
||||
$this->actingAs($this->buyer)->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [[...$f['binding'], 'agreement_id' => $wrong->id]]])->assertUnprocessable()->assertJsonValidationErrors('agreement_bindings');
|
||||
expect(PurchaseOrder::query()->count())->toBe(0);
|
||||
});
|
||||
|
||||
test('mixed currency comparison ranks the frozen mzn reference rather than raw foreign amounts', function () {
|
||||
$this->actingAs($this->finance);
|
||||
@@ -97,7 +476,7 @@ test('foreign currency conversion determines final approval thresholds without c
|
||||
|
||||
test('foreign order cancellation reverses the mzn commitment while preserving the original foreign document', function () {
|
||||
$this->actingAs($this->finance);
|
||||
$exchange = app(\App\Services\QuotationExchange::class);
|
||||
$exchange = app(QuotationExchange::class);
|
||||
$exchange->record($this->finance, $this->r, ['operation_id' => (string) Str::uuid(), 'currency' => 'USD', 'rate' => '60',
|
||||
'quoted_on' => today()->toDateString(), 'source' => 'Taxa sintética para testar reversão do compromisso']);
|
||||
$quote = $this->quotes[0];
|
||||
@@ -118,7 +497,7 @@ test('foreign order cancellation reverses the mzn commitment while preserving th
|
||||
$admins[] = User::factory()->create(['tenant_id' => $this->tenant->id, 'purchasing_role' => PurchasingRole::Admin]);
|
||||
}
|
||||
$this->actingAs($admins[0]);
|
||||
$policyWorkflow = app(\App\Services\OrderCancellationPolicyWorkflow::class);
|
||||
$policyWorkflow = app(OrderCancellationPolicyWorkflow::class);
|
||||
$policy = $policyWorkflow->propose($admins[0], ['previous_id' => 0, 'mode' => 'issued_order', 'enabled' => true,
|
||||
'valid_from' => today()->toDateString(), 'valid_until' => today()->addWeek()->toDateString(), 'reason' => 'Política exclusivamente sintética para cancelamento']);
|
||||
foreach (array_slice($admins, 1) as $reviewer) {
|
||||
@@ -126,7 +505,7 @@ test('foreign order cancellation reverses the mzn commitment while preserving th
|
||||
$policyWorkflow->review($reviewer, $policy, 'approved', 'Conferência sintética independente');
|
||||
}
|
||||
$this->actingAs($this->buyer);
|
||||
$flow = app(\App\Services\OrderCancellationWorkflow::class);
|
||||
$flow = app(OrderCancellationWorkflow::class);
|
||||
$cancellation = $flow->request($this->buyer, $order, ['operation_key' => (string) Str::uuid(),
|
||||
'reason' => 'Cancelamento sintético antes de qualquer execução', 'evidence' => 'Evidência documental exclusivamente sintética']);
|
||||
$this->actingAs($this->finance);
|
||||
|
||||
@@ -172,6 +172,24 @@ function warehouseCommand($test, $actor, string $action, array $extra = []): arr
|
||||
return $input;
|
||||
}
|
||||
|
||||
test('production delivery preserves its original reference and uses one native stock issue and print document', function (string $reference) {
|
||||
$data = $this->draftData;
|
||||
$data['operation_key'] = (string) Str::uuid();
|
||||
$data['lines'][0] = [...$data['lines'][0], 'use' => 'production', 'production_reference' => $reference];
|
||||
$this->r = app(WarehouseRequests::class)->draft($this->f['issuer'], $data);
|
||||
warehouseCommand($this, $this->f['issuer'], 'submit');
|
||||
warehouseCommand($this, $this->reviewer, 'authorize');
|
||||
$input = warehouseCommand($this, $this->f['receiver'], 'deliver', ['lines' => [['index' => 0, 'quantity' => '4.000']]]);
|
||||
$this->postJson('/stock/requisicoes/'.$this->r->id.'/eventos', $input)->assertRedirect();
|
||||
$delivery = WarehouseRequestEvent::query()->where('warehouse_request_id', $this->r->id)->where('action', 'deliver')->sole();
|
||||
expect($delivery->data['lines'][0]['production']['reference'])->toBe($reference)
|
||||
->and(DB::table('stock_operations')->where('kind', 'issue')->count())->toBe(1)
|
||||
->and(app(StockWorkflow::class)->balance($this->f['stock']->id, $this->f['warehouse']->id)['quantity'])->toBe(6000);
|
||||
$this->get('/stock/requisicoes/'.$this->r->id.'/entregas/'.$delivery->id.'/imprimir')->assertOk()->assertSee('Insumos para produção')->assertSee('Referência declarada: '.$reference);
|
||||
$this->get('/stock/requisicoes.csv')->assertOk();
|
||||
expect($this->get('/stock/requisicoes.csv')->streamedContent())->toContain('Referência declarada: '.$reference);
|
||||
})->with(['OP-QA-001', '0']);
|
||||
|
||||
test('internal request is the exit document and partial deliveries consume only actual quantities with independent receipt', function () {
|
||||
warehouseCommand($this, $this->f['issuer'], 'submit', ['partial_allowed' => true]);
|
||||
warehouseCommand($this, $this->reviewer, 'authorize', ['partial_allowed' => true]);
|
||||
|
||||
@@ -52,6 +52,24 @@ test('equipment destination is conditional and selected from the permitted catal
|
||||
$this->postJson('/stock/requisicoes', $this->data)->assertUnprocessable();
|
||||
});
|
||||
|
||||
test('production input destination freezes a declared reference without requiring an external production order or creating a purchase', function () {
|
||||
$body = $this->data;
|
||||
$body['lines'][0] = [...$body['lines'][0], 'use' => 'production', 'production_reference' => 'OP-QA-001'];
|
||||
$purchases = DB::table('requisitions')->count();
|
||||
$this->postJson('/stock/requisicoes', $body)->assertRedirect();
|
||||
$this->postJson('/stock/requisicoes', $body)->assertRedirect();
|
||||
$record = WarehouseRequest::query()->sole();
|
||||
expect($record->snapshot['lines'][0]['production'])->toBe(['reference' => 'OP-QA-001', 'verification' => 'user_supplied'])
|
||||
->and(DB::table('requisitions')->count())->toBe($purchases)->and(DB::table('stock_movements')->count())->toBe(0);
|
||||
$body['operation_key'] = (string) Str::uuid();
|
||||
$body['lines'][0]['production_reference'] = null;
|
||||
$this->postJson('/stock/requisicoes', $body)->assertRedirect();
|
||||
$body['operation_key'] = (string) Str::uuid();
|
||||
$body['lines'][0]['use'] = 'internal';
|
||||
$body['lines'][0]['production_reference'] = 'OP-QA-002';
|
||||
$this->postJson('/stock/requisicoes', $body)->assertUnprocessable();
|
||||
});
|
||||
|
||||
test('warehouse draft rejects another company sources and revoked access', function () {
|
||||
$foreign = receiptFixture();
|
||||
$this->actingAs($this->f['issuer'])->postJson('/stock/requisicoes', [...$this->data, 'warehouse_id' => $foreign['warehouse']->id])->assertNotFound();
|
||||
|
||||
Reference in New Issue
Block a user