feat: consolidar desenvolvimentos do portal InvestMoz
This commit is contained in:
@@ -0,0 +1,242 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\BusinessPointPublication;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Tests\Support\AuthenticatesQaActors;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class BusinessPointPublicationTest extends TestCase
|
||||
{
|
||||
use AuthenticatesQaActors;
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $owner;
|
||||
|
||||
private string $province;
|
||||
|
||||
private string $district;
|
||||
|
||||
private int $sector;
|
||||
|
||||
private string $base = '/api/v1/existing-business/listings';
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
config(['existing-business.enabled' => true, 'portal.profile_access_enabled' => false, 'portal.profile_administration_enabled' => false]);
|
||||
$this->owner = User::factory()->create();
|
||||
$country = $this->territory('country');
|
||||
$this->province = $this->territory('province', $country);
|
||||
$this->district = $this->territory('district', $this->province);
|
||||
$this->sector = DB::table('sectors')->insertGetId(['name' => 'Synthetic point sector', 'slug' => 'synthetic-point-sector', 'is_active' => true]);
|
||||
}
|
||||
|
||||
private function territory(string $kind, ?string $parent = null): string
|
||||
{
|
||||
$id = (string) Str::uuid();
|
||||
DB::table('geo_locations')->insert(['id' => $id, 'name' => 'Synthetic '.$kind, 'code' => $id, 'location_type' => $kind,
|
||||
'parent_id' => $parent, 'version_no' => 1, 'data_classification' => 'public', 'source_system' => 'cartografia-workbook',
|
||||
'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:'.$id]);
|
||||
|
||||
return $id;
|
||||
}
|
||||
|
||||
private function draft(array $payload = []): array
|
||||
{
|
||||
return ['modality' => 'participation_sale', 'classification' => 'restricted', 'reason' => 'Synthetic point preparation',
|
||||
'public_title' => 'Synthetic public point listing', 'sector_id' => $this->sector,
|
||||
'payload' => [...[
|
||||
'title' => 'Synthetic private point listing', 'description' => 'Synthetic description for a staged independent publication.',
|
||||
'source_reference' => 'SYNTHETIC source already registered', 'source_date' => '2026-10-02',
|
||||
'geography_scope' => 'specific', 'province_id' => $this->province, 'district_id' => $this->district,
|
||||
'location_unknown' => 'no', 'disclosure_precision' => 'exact', 'location_point_enabled' => 'yes',
|
||||
'location_latitude' => '-26.0001', 'location_longitude' => '32.0001',
|
||||
'location_point_source_mode' => 'listing', 'location_point_share_source' => 'yes',
|
||||
], ...$payload]];
|
||||
}
|
||||
|
||||
private function create(array $payload = []): array
|
||||
{
|
||||
return $this->actingAs($this->owner)->postJson($this->base, $this->draft($payload))->assertCreated()->json();
|
||||
}
|
||||
|
||||
private function designated(string $role): User
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
$user->forceFill(['two_factor_secret' => Crypt::encryptString('SYNTHETIC'), 'two_factor_confirmed_at' => now()])->save();
|
||||
config(['portal.managers' => [...config('portal.managers', []), $user->email],
|
||||
'existing-business.'.$role => [...config('existing-business.'.$role, []), $user->email]]);
|
||||
|
||||
return $user;
|
||||
}
|
||||
|
||||
private function approve(string $id, int $version): User
|
||||
{
|
||||
$locationsBefore = DB::table('existing_business_locations')->orderBy('id')->get()->toJson();
|
||||
$roles = ['submitted' => null, 'triage' => 'triagers', 'in_review' => 'reviewers', 'approval_l1' => 'reviewers', 'approval_l2' => 'approvers_l1', 'approved' => 'approvers_l2'];
|
||||
$users = [];
|
||||
foreach ($roles as $action => $role) {
|
||||
if ($role === null) {
|
||||
$this->actingAs($this->owner);
|
||||
} else {
|
||||
$this->actingAsWithMfa($users[$role] ??= $this->designated($role));
|
||||
}
|
||||
$this->postJson($this->base.'/'.$id.'/transitions', ['version_no' => $version++, 'action' => $action,
|
||||
'note' => 'Synthetic normal workflow decision', 'review_consent' => $action === 'submitted'])->assertOk();
|
||||
$this->assertSame($locationsBefore, DB::table('existing_business_locations')->orderBy('id')->get()->toJson());
|
||||
}
|
||||
|
||||
return $this->designated('publishers');
|
||||
}
|
||||
|
||||
public function test_point_stays_private_until_normal_independent_publication_then_feeds_radius_and_source_dates(): void
|
||||
{
|
||||
$record = $this->create();
|
||||
$id = $record['id'];
|
||||
$this->assertDatabaseCount('existing_business_locations', 0);
|
||||
$raw = DB::table('existing_businesses')->where('id', $id)->value('payload');
|
||||
$this->assertStringNotContainsString('-26.0001', $raw);
|
||||
$this->getJson($this->base.'/'.$id)->assertOk()->assertJsonPath('record.payload.location_point_source_mode', 'listing')
|
||||
->assertHeader('Cache-Control', 'no-store, private');
|
||||
$this->actingAs(User::factory()->create())->getJson($this->base.'/'.$id)->assertForbidden();
|
||||
$this->getJson('/api/v1/business-opportunities')->assertOk()->assertJsonCount(0, 'data');
|
||||
$publisher = $this->approve($id, 1);
|
||||
$this->actingAs($this->owner)->postJson($this->base.'/'.$id.'/transitions', ['version_no' => 7, 'action' => 'published', 'note' => 'Synthetic owner cannot self publish'])->assertForbidden();
|
||||
$this->actingAsWithMfa($publisher)->postJson($this->base.'/'.$id.'/transitions', ['version_no' => 6, 'action' => 'published', 'note' => 'Synthetic stale publication'])->assertConflict();
|
||||
$this->assertDatabaseCount('existing_business_locations', 0);
|
||||
$saved = $this->postJson($this->base.'/'.$id.'/transitions', ['version_no' => 7, 'action' => 'published', 'note' => 'Synthetic authorized publication'])->assertOk()->assertJsonPath('version_no', 8);
|
||||
$point = DB::table('existing_business_locations')->where('existing_business_id', $id)->first();
|
||||
$this->assertTrue($point->is_primary);
|
||||
$this->assertTrue($point->is_public);
|
||||
$this->assertSame(8, $point->source_payload_version);
|
||||
$this->assertSame($this->district, $point->district_id);
|
||||
$response = $this->getJson('/api/v1/business-opportunities?'.http_build_query(['near_business' => $id, 'radius_km' => 10]))->assertOk()
|
||||
->assertJsonCount(1, 'data')->assertJsonPath('data.0.id', $id)
|
||||
->assertJsonPath('data.0.location_source_reference', 'SYNTHETIC source already registered')
|
||||
->assertJsonPath('data.0.location_source_date', '2026-10-02')->assertJsonPath('geographicCoverage.origin_source_date', '2026-10-02')
|
||||
->assertJsonMissingPath('data.0.location_latitude')->assertJsonMissingPath('data.0.source_payload_version');
|
||||
$this->assertStringNotContainsString('-26.0001', $response->getContent());
|
||||
$this->get('/negocios/'.$saved->json('public_slug'))->assertOk()->assertInertia(fn ($page) => $page->where('similarRadiusAvailable', true));
|
||||
$snapshot = json_decode(Crypt::decryptString(DB::table('existing_business_revisions')->where('business_id', $id)->where('action', 'published')->value('snapshot')), true);
|
||||
$this->assertSame('Synthetic district', $snapshot['context']['point_publication']['used']['reference_snapshot'][1]['name']);
|
||||
$this->assertSame('SYNTHETIC source already registered', $snapshot['context']['point_publication']['used']['source_reference']);
|
||||
$this->assertCount(1, $snapshot['locations']);
|
||||
$before = DB::table('existing_business_revisions')->where('business_id', $id)->pluck('sha256')->all();
|
||||
DB::table('geo_locations')->where('id', $this->district)->update(['name' => 'Updated synthetic district', 'version_no' => 2]);
|
||||
$this->assertSame($before, DB::table('existing_business_revisions')->where('business_id', $id)->pluck('sha256')->all());
|
||||
$this->putJson($this->base.'/'.$id, [...$this->draft(), 'version_no' => 8])->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_point_chooses_one_declared_path_and_does_not_assume_the_first_of_multiple_locations(): void
|
||||
{
|
||||
$other = $this->territory('district', $this->province);
|
||||
$paths = [['province_id' => $this->province, 'district_id' => $this->district], ['province_id' => $this->province, 'district_id' => $other]];
|
||||
$record = $this->create(['geography_scope' => 'multiple', 'locations_json' => json_encode($paths)]);
|
||||
$url = $this->base.'/'.$record['id'];
|
||||
$this->postJson($url.'/transitions', ['version_no' => 1, 'action' => 'submitted', 'review_consent' => true, 'note' => 'Synthetic point needs a selected site'])
|
||||
->assertUnprocessable()->assertJsonValidationErrors('location_point_territory');
|
||||
$key = app(BusinessPointPublication::class)->pathKey($paths[1]);
|
||||
$point = app(BusinessPointPublication::class)->candidate([...$this->draft()['payload'], 'geography_scope' => 'multiple', 'locations_json' => json_encode($paths), 'location_point_territory' => $key]);
|
||||
$this->assertSame($other, $point['path']['district_id']);
|
||||
$this->assertSame('-26.0001', $record['payload']['location_latitude']);
|
||||
$this->expectException(ValidationException::class);
|
||||
app(BusinessPointPublication::class)->candidate([...$this->draft()['payload'], 'geography_scope' => 'multiple', 'locations_json' => json_encode([$paths[0]]), 'location_point_territory' => $key]);
|
||||
}
|
||||
|
||||
public function test_inapplicable_point_fields_remain_private_and_do_not_block_or_activate_a_point(): void
|
||||
{
|
||||
foreach ([['geography_scope' => 'national'], ['geography_scope' => 'digital'], ['disclosure_precision' => 'administrative'], ['location_unknown' => 'yes'], ['location_point_enabled' => 'no']] as $changes) {
|
||||
$payload = [...$this->draft()['payload'], ...$changes, 'location_latitude' => 'unfinished', 'location_point_source_mode' => 'custom', 'location_point_source_date' => 'unfinished'];
|
||||
$record = $this->actingAs($this->owner)->postJson($this->base, $this->draft($payload))->assertCreated()->json();
|
||||
$this->assertSame('unfinished', $record['payload']['location_latitude']);
|
||||
$this->assertNull(app(BusinessPointPublication::class)->candidate($payload));
|
||||
}
|
||||
$this->assertDatabaseCount('existing_business_locations', 0);
|
||||
}
|
||||
|
||||
public function test_custom_source_unknown_date_and_reserved_reference_are_preserved_without_false_public_citation(): void
|
||||
{
|
||||
$record = $this->create(['location_point_source_mode' => 'custom', 'location_point_source_reference' => 'SYNTHETIC PRIVATE point source', 'location_point_source_date' => '', 'location_point_share_source' => 'no']);
|
||||
$publisher = $this->approve($record['id'], 1);
|
||||
$this->actingAsWithMfa($publisher)->postJson($this->base.'/'.$record['id'].'/transitions', ['version_no' => 7, 'action' => 'published', 'note' => 'Synthetic authorized source-aware publication'])->assertOk();
|
||||
$this->getJson('/api/v1/business-opportunities')->assertOk()->assertJsonPath('data.0.location_source_reference', null)->assertJsonPath('data.0.location_source_date', null)
|
||||
->assertDontSee('SYNTHETIC PRIVATE point source');
|
||||
$snapshot = Crypt::decryptString(DB::table('existing_business_revisions')->where('business_id', $record['id'])->where('action', 'published')->value('snapshot'));
|
||||
$this->assertStringContainsString('SYNTHETIC PRIVATE point source', $snapshot);
|
||||
$this->assertStringNotContainsString('SYNTHETIC PRIVATE point source', DB::table('existing_business_revisions')->where('business_id', $record['id'])->where('action', 'published')->value('snapshot'));
|
||||
}
|
||||
|
||||
public function test_invalid_coordinates_and_retired_territory_do_not_publish_or_change_the_workflow(): void
|
||||
{
|
||||
foreach ([['location_latitude' => '91'], ['location_longitude' => '-181'], ['location_latitude' => 'NaN'], ['location_latitude' => 'Infinity']] as $change) {
|
||||
$this->actingAs($this->owner)->postJson($this->base, $this->draft($change))->assertUnprocessable();
|
||||
}
|
||||
$record = $this->create(['location_longitude' => '']);
|
||||
$this->postJson($this->base.'/'.$record['id'].'/transitions', ['version_no' => 1, 'action' => 'submitted', 'review_consent' => true, 'note' => 'Synthetic incomplete point submission'])->assertUnprocessable();
|
||||
$this->assertDatabaseCount('business_workflow_transitions', 0);
|
||||
$record = $this->create();
|
||||
$publisher = $this->approve($record['id'], 1);
|
||||
DB::table('geo_locations')->where('id', $this->district)->update(['data_classification' => 'restricted']);
|
||||
$this->actingAsWithMfa($publisher)->postJson($this->base.'/'.$record['id'].'/transitions', ['version_no' => 7, 'action' => 'published', 'note' => 'Synthetic retired point cannot publish'])->assertUnprocessable();
|
||||
$this->assertDatabaseHas('existing_businesses', ['id' => $record['id'], 'status' => 'approved', 'version_no' => 7]);
|
||||
$this->assertDatabaseCount('existing_business_locations', 0);
|
||||
}
|
||||
|
||||
public function test_migration_preserves_legacy_rows_and_public_queries_work_without_optional_source_columns(): void
|
||||
{
|
||||
$migration = require database_path('migrations/2026_11_03_000000_existing_business_location_sources.php');
|
||||
$migration->down();
|
||||
$this->assertFalse(Schema::hasColumn('existing_business_locations', 'public_source_reference'));
|
||||
$this->getJson('/api/v1/business-opportunities')->assertOk();
|
||||
$migration->up();
|
||||
$this->create();
|
||||
DB::table('existing_business_locations')->insert(['id' => (string) Str::uuid(), 'existing_business_id' => DB::table('existing_businesses')->value('id'),
|
||||
'province_id' => $this->province, 'precision_level' => 'province', 'is_primary' => true, 'is_public' => false, 'source_system' => 'synthetic-private-source']);
|
||||
$this->expectException(\RuntimeException::class);
|
||||
$migration->down();
|
||||
}
|
||||
|
||||
public function test_explicit_point_replacement_preserves_primary_identity_secondary_rows_and_prior_geometry_in_history(): void
|
||||
{
|
||||
$record = $this->create();
|
||||
$primary = (string) Str::uuid();
|
||||
$secondary = (string) Str::uuid();
|
||||
foreach ([$primary, $secondary] as $location) {
|
||||
DB::table('existing_business_locations')->insert(['id' => $location, 'existing_business_id' => $record['id'],
|
||||
'province_id' => $this->province, 'district_id' => $this->district, 'precision_level' => 'exact', 'is_primary' => $location === $primary,
|
||||
'is_public' => false, 'geom' => DB::raw("ST_GeomFromText('POINT(33 -27)',4326)"), 'source_system' => 'SYNTHETIC previous source']);
|
||||
}
|
||||
$secondaryBefore = DB::table('existing_business_locations')->where('id', $secondary)->first();
|
||||
$this->getJson($this->base.'/'.$record['id'])->assertOk()->assertJsonPath('registeredLocation.longitude', 33);
|
||||
$publisher = $this->approve($record['id'], 1);
|
||||
$this->actingAsWithMfa($publisher)->postJson($this->base.'/'.$record['id'].'/transitions', ['version_no' => 7, 'action' => 'published', 'note' => 'Synthetic explicit reviewed replacement'])->assertOk();
|
||||
$this->assertDatabaseCount('existing_business_locations', 2);
|
||||
$this->assertDatabaseHas('existing_business_locations', ['id' => $primary, 'is_primary' => true, 'is_public' => true, 'source_system' => 'portal-business-form']);
|
||||
$this->assertEquals($secondaryBefore, DB::table('existing_business_locations')->where('id', $secondary)->first());
|
||||
$snapshot = json_decode(Crypt::decryptString(DB::table('existing_business_revisions')->where('business_id', $record['id'])->where('action', 'published')->value('snapshot')), true);
|
||||
$this->assertSame('SRID=4326;POINT(33 -27)', $snapshot['context']['point_publication']['previous']['geometry_snapshot']);
|
||||
$this->assertSame('SYNTHETIC previous source', $snapshot['context']['point_publication']['previous']['source_system']);
|
||||
}
|
||||
|
||||
public function test_no_point_opt_in_preserves_existing_location_and_source_through_publication(): void
|
||||
{
|
||||
$record = $this->create(['location_point_enabled' => 'no']);
|
||||
DB::table('existing_business_locations')->insert(['id' => (string) Str::uuid(), 'existing_business_id' => $record['id'],
|
||||
'province_id' => $this->province, 'precision_level' => 'province', 'is_primary' => true, 'is_public' => true,
|
||||
'source_system' => 'SYNTHETIC preserved source', 'public_source_reference' => 'Synthetic previous public citation']);
|
||||
$before = DB::table('existing_business_locations')->first();
|
||||
$publisher = $this->approve($record['id'], 1);
|
||||
$this->actingAsWithMfa($publisher)->postJson($this->base.'/'.$record['id'].'/transitions', ['version_no' => 7, 'action' => 'published', 'note' => 'Synthetic preserve source publication'])->assertOk();
|
||||
$this->assertEquals($before, DB::table('existing_business_locations')->first());
|
||||
$this->getJson('/api/v1/business-opportunities')->assertOk()->assertJsonPath('data.0.location_source_reference', 'Synthetic previous public citation')->assertJsonPath('data.0.distance_km', null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
use App\Services\ExistingBusinessClassification;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class BusinessProximitySearchTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
config(['existing-business.enabled' => true]);
|
||||
}
|
||||
|
||||
private function business(?string $geometry = 'POINT(32 -26)', array $location = [], array $attributes = []): string
|
||||
{
|
||||
$id = (string) Str::uuid();
|
||||
DB::table('existing_businesses')->insert([...[
|
||||
'id' => $id, 'code' => 'QA-'.Str::uuid(), 'owner_user_id' => User::factory()->create()->id,
|
||||
'modality' => 'company_sale', 'status' => 'published', 'classification' => 'confidential',
|
||||
'version_no' => 1, 'payload' => Crypt::encryptString('{"title":"PRIVATE SYNTHETIC"}'),
|
||||
'public_title' => 'Synthetic public '.$id, 'public_slug' => 'qa-'.$id,
|
||||
'published_at' => now()->subDay(), 'created_at' => now(), 'updated_at' => now(),
|
||||
], ...$attributes]);
|
||||
if ($geometry !== null || $location !== []) {
|
||||
DB::table('existing_business_locations')->insert([...[
|
||||
'id' => (string) Str::uuid(), 'existing_business_id' => $id,
|
||||
'precision_level' => 'exact', 'is_primary' => true, 'is_public' => true,
|
||||
'geom' => $geometry === null ? null : DB::raw("ST_GeomFromText('".$geometry."',4326)"),
|
||||
'created_at' => '2026-10-01 10:00:00+00', 'updated_at' => '2026-10-02 10:00:00+00',
|
||||
], ...$location]);
|
||||
}
|
||||
|
||||
return $id;
|
||||
}
|
||||
|
||||
private function url(string $origin, array $filters = []): string
|
||||
{
|
||||
return '/api/v1/business-opportunities?'.http_build_query(['near_business' => $origin, 'radius_km' => 20, ...$filters]);
|
||||
}
|
||||
|
||||
public function test_radius_orders_by_distance_excludes_unusable_and_private_points_and_retains_context(): void
|
||||
{
|
||||
$origin = $this->business();
|
||||
$near = $this->business('POINT(32.01 -26)');
|
||||
$far = $this->business('POINT(34 -26)');
|
||||
$this->business('POINT(32.001 -26)', ['is_public' => false]);
|
||||
$this->business('POINT(32.001 -26)', ['is_primary' => false]);
|
||||
$this->business('POLYGON((32 -26,32.01 -26,32.01 -26.01,32 -26))');
|
||||
$this->business('POINT(200 -26)');
|
||||
$this->business(null);
|
||||
$this->business('POINT(32.001 -26)', [], ['status' => 'draft']);
|
||||
$this->business('POINT(32.001 -26)', [], ['published_at' => now()->addDay()]);
|
||||
$this->business('POINT(32.001 -26)', [], ['expires_at' => now()->subDay()]);
|
||||
$deleted = $this->business();
|
||||
DB::table('existing_businesses')->where('id', $deleted)->update(['deleted_at' => now()]);
|
||||
$response = $this->getJson($this->url($origin))->assertOk()->assertJsonCount(2, 'data')
|
||||
->assertJsonPath('data.0.id', $origin)->assertJsonPath('data.0.distance_km', 0)
|
||||
->assertJsonPath('data.1.id', $near)->assertJsonPath('geographicCoverage.with_public_point', 3)
|
||||
->assertJsonPath('geographicCoverage.without_public_point', 5)
|
||||
->assertJsonPath('geographicCoverage.origin_id', $origin)
|
||||
->assertJsonPath('data.1.location_recorded_at', '2026-10-02T10:00:00+00:00');
|
||||
$this->assertGreaterThan(0, $response->json('data.1.distance_km'));
|
||||
$this->assertLessThan(2, $response->json('data.1.distance_km'));
|
||||
foreach (['geom', 'point', 'ewkt', 'owner_user_id', 'payload'] as $field) {
|
||||
$response->assertJsonMissingPath('data.0.'.$field)->assertJsonMissingPath('geographicCoverage.'.$field);
|
||||
}
|
||||
$this->assertStringNotContainsString('PRIVATE SYNTHETIC', $response->getContent());
|
||||
$first = $this->getJson($this->url($origin, ['per_page' => 1]))->assertOk();
|
||||
$next = $first->json('links.next');
|
||||
$this->assertStringContainsString('near_business='.$origin, $next);
|
||||
$this->getJson($next)->assertOk()->assertJsonPath('data.0.id', $near);
|
||||
$this->getJson($this->url($origin, ['radius_km' => 300]))->assertOk()->assertJsonCount(3, 'data')->assertJsonPath('data.2.id', $far);
|
||||
$this->get('/negocios?'.http_build_query(['near_business' => $origin, 'radius_km' => 20]))
|
||||
->assertInertia(fn (Assert $page) => $page->where('geographicCoverage.origin_id', $origin)->has('results.data', 2));
|
||||
$query = '?'.http_build_query(['near_business' => $origin, 'radius_km' => 20]);
|
||||
$this->get('/negocios/qa-'.$near.$query)->assertInertia(fn (Assert $page) => $page
|
||||
->where('similarRadiusAvailable', true)->where('returnUrl', '/negocios'.$query)
|
||||
->where('interestUrl', '/negocios/qa-'.$near.'/manifestar-interesse'.$query));
|
||||
}
|
||||
|
||||
public function test_radius_combines_sector_modality_and_disclosed_classification_without_widening(): void
|
||||
{
|
||||
$sector = Sector::create(['name' => 'Synthetic QA', 'slug' => 'synthetic-proximity', 'is_active' => true, 'published_at' => now()]);
|
||||
$origin = $this->business();
|
||||
$match = $this->business('POINT(32.01 -26)', [], ['sector_id' => $sector->id]);
|
||||
$this->business('POINT(32.01 -26)', [], ['sector_id' => $sector->id]);
|
||||
$other = $this->business('POINT(32.01 -26)', [], ['sector_id' => $sector->id, 'modality' => 'real_estate']);
|
||||
$wrongSector = $this->business('POINT(32.01 -26)');
|
||||
foreach ([$match, $other, $wrongSector] as $id) {
|
||||
$row = ['related_id' => (string) $sector->id, 'classification' => ['target_type' => 'sector', 'purpose' => 'coverage',
|
||||
'disclosure' => 'public', 'requested_state' => 'preliminary', 'external_status' => 'not_declared', 'source_reference' => 'Synthetic QA source']];
|
||||
$state = ['schema_version' => ExistingBusinessClassification::VERSION, 'relations' => [$row], 'authors' => [], 'decisions' => [], 'publication' => [$row]];
|
||||
DB::table('existing_business_revisions')->insert(['id' => (string) Str::uuid(), 'business_id' => $id, 'version_no' => 1,
|
||||
'action' => 'classification_disclosed', 'snapshot' => Crypt::encryptString(json_encode(['context' => ['multidimensional' => $state]], JSON_THROW_ON_ERROR)),
|
||||
'sha256' => hash('sha256', $id), 'actor_id' => DB::table('existing_businesses')->where('id', $id)->value('owner_user_id'),
|
||||
'reason' => 'Synthetic disclosed classification', 'created_at' => now()]);
|
||||
}
|
||||
$this->getJson($this->url($origin, ['sector' => $sector->id, 'modality' => 'company_sale', 'association_type' => 'sector', 'association_target' => (string) $sector->id]))
|
||||
->assertOk()->assertJsonCount(1, 'data')->assertJsonPath('data.0.id', $match)
|
||||
->assertJsonPath('geographicCoverage.with_public_point', 1)->assertJsonPath('geographicCoverage.without_public_point', 0);
|
||||
}
|
||||
|
||||
public function test_invalid_or_unpublished_reference_never_falls_back_to_an_area_or_centroid(): void
|
||||
{
|
||||
$private = $this->business('POINT(32 -26)', ['is_public' => false]);
|
||||
$polygon = $this->business('POLYGON((32 -26,32.01 -26,32.01 -26.01,32 -26))');
|
||||
$draft = $this->business('POINT(32 -26)', [], ['status' => 'draft']);
|
||||
foreach ([$private, $polygon, $draft, (string) Str::uuid()] as $origin) {
|
||||
$this->getJson($this->url($origin))->assertUnprocessable()->assertJsonValidationErrors('near_business');
|
||||
}
|
||||
$origin = $this->business();
|
||||
foreach ([0, -1, 2001, 'bad'] as $radius) {
|
||||
$this->getJson($this->url($origin, ['radius_km' => $radius]))->assertUnprocessable()->assertJsonValidationErrors('radius_km');
|
||||
}
|
||||
$this->getJson('/api/v1/business-opportunities?near_business='.$origin)->assertUnprocessable()->assertJsonValidationErrors('radius_km');
|
||||
$this->getJson('/api/v1/business-opportunities?radius_km=20')->assertUnprocessable()->assertJsonValidationErrors('near_business');
|
||||
}
|
||||
|
||||
public function test_coarse_precision_does_not_disclose_a_finer_territory_through_filters_or_radius(): void
|
||||
{
|
||||
$ids = ['country' => (string) Str::uuid(), 'province' => (string) Str::uuid(), 'district' => (string) Str::uuid()];
|
||||
foreach ($ids as $kind => $id) {
|
||||
DB::table('geo_locations')->insert(['id' => $id, 'code' => $id, 'name' => 'Synthetic '.$kind, 'location_type' => $kind,
|
||||
'parent_id' => $kind === 'country' ? null : $ids[$kind === 'province' ? 'country' : 'province'],
|
||||
'data_classification' => 'public', 'source_system' => 'cartografia-workbook',
|
||||
'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:'.$id]);
|
||||
}
|
||||
$coarse = $this->business('POINT(32 -26)', ['precision_level' => 'province', 'province_id' => $ids['province'], 'district_id' => $ids['district']]);
|
||||
$fine = $this->business('POINT(32 -26)', ['precision_level' => 'district', 'province_id' => $ids['province'], 'district_id' => $ids['district']]);
|
||||
$this->getJson('/api/v1/business-opportunities?province_id='.$ids['province'].'&district_id='.$ids['district'])
|
||||
->assertOk()->assertJsonCount(1, 'data')->assertJsonPath('data.0.id', $fine);
|
||||
$this->getJson('/api/v1/business-opportunities/qa-'.$coarse)->assertOk()->assertJsonPath('data.district', null);
|
||||
foreach ([$coarse, $fine] as $origin) {
|
||||
$this->getJson($this->url($origin))->assertUnprocessable();
|
||||
}
|
||||
$exact = $this->business('POINT(32 -26)', ['province_id' => $ids['province'], 'district_id' => $ids['district']]);
|
||||
$origin = $this->business();
|
||||
$this->getJson($this->url($origin, ['province_id' => $ids['province'], 'district_id' => $ids['district']]))
|
||||
->assertOk()->assertJsonCount(1, 'data')->assertJsonPath('data.0.id', $exact)
|
||||
->assertJsonPath('geographicCoverage.with_public_point', 1)->assertJsonPath('geographicCoverage.without_public_point', 1);
|
||||
DB::table('geo_locations')->where('id', $ids['district'])->update(['data_classification' => 'restricted']);
|
||||
$this->getJson($this->url($exact))->assertUnprocessable();
|
||||
$this->getJson('/api/v1/business-opportunities/qa-'.$coarse)->assertOk()->assertJsonPath('data.province', 'Synthetic province');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\InvestmentGuides;
|
||||
use App\Services\VirtualDesk;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class BvmAdmissionGuideTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $owner;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
config(['investor-path.enabled' => true, 'investmoz_ai.enabled' => false, 'suitecrm.enabled' => false, 'portal.notifications_enabled' => false]);
|
||||
Http::preventStrayRequests();
|
||||
$this->owner = User::factory()->create();
|
||||
}
|
||||
|
||||
private function dossier(): string
|
||||
{
|
||||
return $this->actingAs($this->owner)->postJson('/investimentos', ['title' => 'SYNTHETIC BVM preparation', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertCreated()->json('id');
|
||||
}
|
||||
|
||||
private function url(string $id, string $slug = 'bolsa'): string
|
||||
{
|
||||
return '/investimentos/'.$id.'/guias/'.$slug;
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function input(string $id, string $slug = 'bolsa', array $extra = []): array
|
||||
{
|
||||
return [...['version' => DB::table('desk_cases')->where('id', $id)->value('version'), 'operation_key' => (string) Str::uuid(), 'sha256' => app(InvestmentGuides::class)->guide($slug)['sha256'], 'instruments' => $slug === 'bolsa' ? ['third_shares'] : ['debt'], 'note' => 'SYNTHETIC private '.$slug], ...$extra];
|
||||
}
|
||||
|
||||
public function test_public_guide_has_five_real_paths_with_article_page_and_redaction_per_requirement(): void
|
||||
{
|
||||
$r = $this->getJson('/guias-investimento/bolsa')->assertOk()->assertHeader('Cache-Control', 'no-store, private')
|
||||
->assertJsonCount(5, 'guide.instruments')->assertJsonCount(7, 'guide.sources')->assertJsonCount(6, 'guide.preparation')->assertJsonPath('case', null)->json();
|
||||
$guide = $r['guide'];
|
||||
$this->assertSame(['official_shares', 'official_bonds', 'second_shares', 'second_bonds', 'third_shares'], array_keys($guide['instruments']));
|
||||
foreach ([$guide['requirements'], ...array_column($guide['instruments'], 'requirements')] as $requirements) {
|
||||
foreach ($requirements as $requirement) {
|
||||
$this->assertNotEmpty($requirement['citations']);
|
||||
foreach ($requirement['citations'] as $cite) {
|
||||
$this->assertArrayHasKey($cite['source'], $guide['sources']);
|
||||
$this->assertNotEmpty($guide['sources'][$cite['source']]['edition']);
|
||||
$this->assertGreaterThan(0, $cite['page']);
|
||||
$this->assertMatchesRegularExpression('/art|âmbito/iu', $cite['reference']);
|
||||
}
|
||||
}
|
||||
}
|
||||
$this->get('/guias-investimento/bolsa')->assertOk()->assertInertia(fn ($page) => $page->component('investment/guide'));
|
||||
$this->assertDatabaseCount('desk_cases', 0);
|
||||
$this->assertDatabaseCount('desk_requests', 0);
|
||||
}
|
||||
|
||||
public function test_current_minimums_remain_unknown_instead_of_reusing_the_expired_amounts_or_zero(): void
|
||||
{
|
||||
$guide = $this->getJson('/guias-investimento/bolsa')->assertOk()->assertJsonPath('guide.sources.minimums_historical.valid_until', '2025-03-31')->json('guide');
|
||||
foreach ($guide['instruments'] as $path) {
|
||||
$gap = collect($path['requirements'])->firstWhere('kind', 'gap');
|
||||
$this->assertNull($gap['value']);
|
||||
$this->assertSame('MZN', $gap['unit']);
|
||||
$this->assertStringContainsString('31/03/2025', $gap['text']);
|
||||
$this->assertStringContainsString('regulamento anual', $gap['text']);
|
||||
}
|
||||
$serialized = json_encode($guide, JSON_THROW_ON_ERROR);
|
||||
foreach (['16.000.000', '4.000.000', '1.000.000', '8.000.000', '2.000.000'] as $expired) {
|
||||
$this->assertStringNotContainsString($expired, $serialized);
|
||||
}
|
||||
$this->assertStringContainsString('um quarto', $guide['instruments']['second_shares']['requirements'][0]['text']);
|
||||
$this->assertStringContainsString('25%', $guide['instruments']['third_shares']['requirements'][0]['text']);
|
||||
}
|
||||
|
||||
public function test_third_market_uses_2021_instead_of_the_old_nine_month_transition_and_keeps_initial_waivers_scoped(): void
|
||||
{
|
||||
$guide = app(InvestmentGuides::class)->guide('bolsa');
|
||||
$third = collect($guide['instruments']['third_shares']['requirements'])->keyBy('id');
|
||||
$this->assertStringContainsString('dois anos', $third['third_entry_dispersion']['text']);
|
||||
$this->assertStringContainsString('mais um ano', $third['third_entry_dispersion']['text']);
|
||||
$this->assertStringContainsString('sem extensão automática', $third['third_entry_dispersion']['text']);
|
||||
$this->assertStringNotContainsString('nove meses', json_encode($third, JSON_THROW_ON_ERROR));
|
||||
$this->assertSame('exception', $third['third_entry_audit']['kind']);
|
||||
$this->assertStringContainsString('momento do pedido', $third['third_entry_audit']['text']);
|
||||
$this->assertStringContainsString('OCAM', $third['third_finances']['text']);
|
||||
$this->assertStringContainsString('semestrais', $third['third_reporting']['text']);
|
||||
$docs = collect($guide['documents'])->keyBy('id');
|
||||
$this->assertNotContains('third_shares', $docs['audit']['paths']);
|
||||
$this->assertContains('third_shares', $docs['updated_information']['paths']);
|
||||
$this->assertStringContainsString('não reproduz uma dispensa geral', $docs['updated_information']['text']);
|
||||
$this->assertStringContainsString('um ano', $guide['instruments']['second_shares']['requirements'][1]['text']);
|
||||
$this->assertStringContainsString('nove meses', $guide['instruments']['second_shares']['requirements'][1]['text']);
|
||||
}
|
||||
|
||||
public function test_sources_distinguish_supervision_sponsorship_registry_and_the_2022_nominative_and_sas_rules(): void
|
||||
{
|
||||
$guide = app(InvestmentGuides::class)->guide('bolsa');
|
||||
$roles = implode(' ', array_column($guide['eligibility'], 'text'));
|
||||
foreach (['Banco de Moçambique', 'BVM', 'operador', 'Central de Valores Mobiliários', 'Não é um regulador separado'] as $expected) {
|
||||
$this->assertStringContainsString($expected, $roles);
|
||||
}
|
||||
$rules = collect($guide['requirements'])->keyBy('id');
|
||||
$this->assertStringContainsString('simplificada', $rules['legal_form']['text']);
|
||||
$this->assertSame(63, $rules['legal_form']['citations'][1]['page']);
|
||||
$this->assertStringContainsString('2022', $rules['nominative']['text']);
|
||||
$this->assertStringContainsString('ao portador', $rules['nominative']['text']);
|
||||
foreach ($guide['handoffs'] as $link) {
|
||||
$this->assertStringStartsWith('https://www.bvm.co.mz/', $link['url']);
|
||||
$this->assertStringNotContainsString('?', $link['url']);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_dossier_choice_and_creation_pin_the_bvm_edition_without_saving_or_submitting_by_arrasto(): void
|
||||
{
|
||||
$guide = app(InvestmentGuides::class)->guide('bolsa');
|
||||
$selection = ['slug' => 'bolsa', 'sha256' => $guide['sha256'], 'instruments' => ['second_bonds', 'third_shares']];
|
||||
$target = '/investimentos?'.http_build_query(['investment_guide' => $selection]);
|
||||
$this->get($target)->assertRedirect('/login');
|
||||
$this->assertSame(url($target), session('url.intended'));
|
||||
$id = $this->dossier();
|
||||
$this->getJson($target)->assertOk()->assertJsonPath('guideSelection.slug', 'bolsa');
|
||||
$record = $this->postJson('/investimentos', ['title' => 'SYNTHETIC selected destination', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true, 'investment_guide' => $selection])->assertCreated()->json();
|
||||
$this->getJson($record['guide_href'])->assertOk()->assertJsonPath('guide.slug', 'bolsa')->assertJsonPath('instruments', ['second_bonds', 'third_shares'])->assertJsonPath('saved', null);
|
||||
$this->assertSame(0, DB::table('desk_events')->where('action', InvestmentGuides::EVENT)->count());
|
||||
$this->getJson($this->url($id).'?instruments[0]=third_bonds')->assertUnprocessable();
|
||||
$this->getJson($this->url($id).'?instruments[0]=debt')->assertUnprocessable();
|
||||
}
|
||||
|
||||
public function test_multiple_guides_reuse_one_dossier_and_cannot_replay_or_open_each_others_revisions(): void
|
||||
{
|
||||
$id = $this->dossier();
|
||||
$before = DB::table('journey_steps')->orderBy('id')->get()->toJson();
|
||||
$capital = $this->input($id, 'capitalizacao');
|
||||
$this->postJson($this->url($id, 'capitalizacao'), $capital)->assertOk();
|
||||
$first = $this->getJson($this->url($id, 'capitalizacao'))->json();
|
||||
$bvm = $this->input($id);
|
||||
$this->postJson($this->url($id), $bvm)->assertOk()->assertJsonPath('revision', 1);
|
||||
$this->postJson($this->url($id), $bvm)->assertOk()->assertJsonPath('replayed', true);
|
||||
$this->postJson($this->url($id), [...$bvm, 'operation_key' => $capital['operation_key']])->assertConflict();
|
||||
$this->getJson($this->url($id).'?revision='.$first['history'][0]['id'])->assertNotFound();
|
||||
$this->getJson($this->url($id, 'capitalizacao'))->assertOk()->assertJsonPath('saved', $first['saved'])->assertJsonCount(1, 'history');
|
||||
$this->getJson($this->url($id))->assertOk()->assertJsonCount(1, 'history')->assertJsonPath('guide.slug', 'bolsa');
|
||||
$this->assertSame($before, DB::table('journey_steps')->orderBy('id')->get()->toJson());
|
||||
$stored = DB::table('desk_cases')->where('id', $id)->first();
|
||||
$this->assertStringNotContainsString('SYNTHETIC private bolsa', $stored->payload);
|
||||
$payload = app(VirtualDesk::class)->decode($stored->payload);
|
||||
$this->assertCount(2, $payload['investment_guides']);
|
||||
$this->assertDatabaseCount('desk_requests', 0);
|
||||
$this->assertDatabaseCount('organizations', 0);
|
||||
}
|
||||
|
||||
public function test_pagination_filters_the_requested_guide_when_the_shared_event_stream_is_interleaved(): void
|
||||
{
|
||||
$id = $this->dossier();
|
||||
for ($i = 1; $i <= 26; $i++) {
|
||||
$this->postJson($this->url($id), $this->input($id, 'bolsa', ['note' => 'SYNTHETIC BVM revision '.$i]))->assertOk();
|
||||
$this->postJson($this->url($id, 'capitalizacao'), $this->input($id, 'capitalizacao', ['note' => 'SYNTHETIC capital revision '.$i]))->assertOk();
|
||||
}
|
||||
$page = $this->getJson($this->url($id))->assertOk()->assertJsonCount(25, 'history')->assertJsonPath('saved.revision', 26)->json();
|
||||
$old = $this->getJson($this->url($id).'?history_before='.$page['historyNext'])->assertOk()->assertJsonCount(1, 'history')->assertJsonPath('history.0.revision', 1)->json();
|
||||
$this->getJson($this->url($id).'?revision='.$old['history'][0]['id'])->assertOk()->assertJsonPath('guide.slug', 'bolsa')->assertJsonPath('note', 'SYNTHETIC BVM revision 1');
|
||||
$this->getJson($this->url($id, 'capitalizacao').'?revision='.$old['history'][0]['id'])->assertNotFound();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\CompanyComparison;
|
||||
use App\Services\VirtualDesk;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class CompanyComparisonTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $owner;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
config(['investor-path.enabled' => true, 'investmoz_ai.enabled' => false, 'suitecrm.enabled' => false, 'portal.notifications_enabled' => false]);
|
||||
Http::preventStrayRequests();
|
||||
$this->owner = User::factory()->create();
|
||||
}
|
||||
|
||||
private function dossier(): string
|
||||
{
|
||||
return $this->actingAs($this->owner)->postJson('/investimentos', ['title' => 'SYNTHETIC company preparation', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertCreated()->json('id');
|
||||
}
|
||||
|
||||
public function test_public_incomplete_comparison_uses_exact_mozambican_source_without_writing_or_requiring_ia(): void
|
||||
{
|
||||
$this->getJson('/formas-juridicas')->assertOk()->assertHeader('Cache-Control', 'no-store, private')
|
||||
->assertJsonPath('result.source.sha256', '8009ef95a352dc02283e671cd717449ec8ad747a8995153cd3122ea16aa22a0f')
|
||||
->assertJsonCount(5, 'result.forms')->assertJsonPath('case', null)->assertJsonCount(8, 'result.pending');
|
||||
$this->get('/formas-juridicas')->assertOk()->assertInertia(fn ($page) => $page->component('investment/company-comparison'));
|
||||
$this->assertDatabaseCount('desk_cases', 0);
|
||||
$this->assertDatabaseCount('organizations', 0);
|
||||
}
|
||||
|
||||
public function test_answers_explain_single_participant_and_listing_conflicts_without_an_automatic_winner(): void
|
||||
{
|
||||
$r = $this->getJson('/formas-juridicas?'.http_build_query(['answers' => ['purpose' => 'new', 'participants' => 'one', 'listing' => 'yes', 'participation' => 'shares', 'preferred' => 'simplified']]))->assertOk();
|
||||
$forms = collect($r->json('result.forms'))->keyBy('code');
|
||||
$this->assertNotEmpty($forms['collective']['constraints']);
|
||||
$this->assertNotEmpty($forms['simplified']['constraints']);
|
||||
$this->assertTrue($forms['simplified']['selected']);
|
||||
foreach (['quotas', 'anonymous', 'simplified'] as $code) {
|
||||
$this->assertStringContainsString('unipessoal', implode(' ', $forms[$code]['notes']));
|
||||
}
|
||||
$this->assertArrayNotHasKey('score', $forms['simplified']);
|
||||
$this->assertStringContainsString('preferência', implode(' ', $forms['quotas']['notes']));
|
||||
$this->getJson('/formas-juridicas?'.http_build_query(['answers' => ['participants' => 'several']]))->assertOk()->assertJsonCount(1, 'result.forms.0.constraints');
|
||||
$this->getJson('/formas-juridicas?'.http_build_query(['answers' => ['unexpected' => 'field']]))->assertUnprocessable();
|
||||
$this->getJson('/formas-juridicas?'.http_build_query(['answers' => ['preferred' => 'invented']]))->assertUnprocessable();
|
||||
}
|
||||
|
||||
public function test_representation_and_cooperation_keep_inactive_answers_without_treating_them_as_new_societies(): void
|
||||
{
|
||||
foreach (['representation', 'cooperation'] as $purpose) {
|
||||
$this->getJson('/formas-juridicas?'.http_build_query(['answers' => ['purpose' => $purpose, 'participants' => 'one', 'preferred' => 'quotas']]))->assertOk()
|
||||
->assertJsonCount(0, 'result.forms')->assertJsonPath('result.active', ['purpose', 'regulated'])
|
||||
->assertJsonPath('answers.participants', 'one')->assertJsonPath('answers.preferred', 'quotas');
|
||||
}
|
||||
}
|
||||
|
||||
public function test_questions_produce_applicable_preparation_without_a_false_choice_between_partners_and_administration(): void
|
||||
{
|
||||
$answers = ['purpose' => 'new', 'participants' => 'several', 'participation' => 'work', 'capital' => 'defined', 'management' => 'both', 'responsibility' => 'limited', 'listing' => 'yes', 'regulated' => 'yes'];
|
||||
$response = $this->getJson('/formas-juridicas?'.http_build_query(['answers' => $answers]))->assertOk()->assertJsonCount(0, 'result.pending');
|
||||
$preparation = implode(' ', $response->json('result.preparation'));
|
||||
foreach (['contribuições definidas', 'poderes de gestão', 'nomeação', 'regime de responsabilidade', 'mercado pretendido', 'habilitações específicas'] as $expected) {
|
||||
$this->assertStringContainsString($expected, $preparation);
|
||||
}
|
||||
$this->assertStringContainsString('trabalho', implode(' ', $response->json('result.forms.1.notes')));
|
||||
}
|
||||
|
||||
public function test_private_comparison_saves_recovers_and_replays_without_changing_master_identity_or_steps(): void
|
||||
{
|
||||
$id = $this->dossier();
|
||||
$url = '/investimentos/'.$id.'/forma-juridica';
|
||||
$before = DB::table('journey_steps')->orderBy('id')->get()->toJson();
|
||||
$case = DB::table('desk_cases')->where('id', $id)->first();
|
||||
$payloadBefore = app(VirtualDesk::class)->decode($case->payload);
|
||||
$input = ['version' => $case->version, 'operation_key' => (string) Str::uuid(), 'answers' => ['participants' => 'one', 'preferred' => 'quotas']];
|
||||
$this->postJson($url, $input)->assertOk()->assertJsonPath('replayed', false)->assertJsonPath('revision', 1);
|
||||
$this->postJson($url, $input)->assertOk()->assertJsonPath('replayed', true);
|
||||
$this->postJson($url, [...$input, 'answers' => ['participants' => 'several']])->assertConflict();
|
||||
$this->getJson($url)->assertOk()->assertHeader('Cache-Control', 'no-store, private')->assertJsonPath('saved.revision', 1)->assertJsonPath('answers.participants', 'one');
|
||||
$this->assertSame(1, DB::table('desk_events')->where('case_id', $id)->where('action', CompanyComparison::EVENT)->count());
|
||||
$stored = DB::table('desk_cases')->where('id', $id)->first();
|
||||
$payload = app(VirtualDesk::class)->decode($stored->payload);
|
||||
unset($payload['company_comparison']);
|
||||
$this->assertSame($payloadBefore, $payload);
|
||||
$this->assertStringNotContainsString('company_comparison', $stored->payload);
|
||||
$this->assertSame($before, DB::table('journey_steps')->orderBy('id')->get()->toJson());
|
||||
$this->assertDatabaseCount('organizations', 0);
|
||||
$this->assertDatabaseCount('investment_company_declarations', 0);
|
||||
$this->assertDatabaseCount('desk_requests', 0);
|
||||
$currentVersion = $stored->version;
|
||||
$this->postJson($url, [...$input, 'version' => $currentVersion, 'operation_key' => (string) Str::uuid()])->assertOk()->assertJsonPath('unchanged', true);
|
||||
$this->assertSame($currentVersion, DB::table('desk_cases')->where('id', $id)->value('version'));
|
||||
$this->assertSame(1, DB::table('desk_events')->where('case_id', $id)->where('action', CompanyComparison::EVENT)->count());
|
||||
$this->getJson('/investimentos/'.$id)->assertOk()->assertJsonPath('tools.company', $url);
|
||||
$this->postJson($url, [...$input, 'operation_key' => (string) Str::uuid()])->assertConflict();
|
||||
}
|
||||
|
||||
public function test_historical_answers_sources_and_results_do_not_follow_future_engine_changes(): void
|
||||
{
|
||||
$id = $this->dossier();
|
||||
$url = '/investimentos/'.$id.'/forma-juridica';
|
||||
$version = DB::table('desk_cases')->where('id', $id)->value('version');
|
||||
$original = ['version' => $version, 'operation_key' => (string) Str::uuid(), 'answers' => ['participants' => 'one']];
|
||||
$this->postJson($url, $original)->assertOk();
|
||||
$first = $this->getJson($url)->assertOk()->json();
|
||||
config(['company-comparison.version' => 'SYNTHETIC-future-version', 'company-comparison.source.edition' => 'SYNTHETIC-future-edition']);
|
||||
config(['company-comparison.questions.synthetic_future' => ['label' => 'SYNTHETIC future question', 'options' => ['unknown' => 'Unknown']]]);
|
||||
$this->postJson($url, [...$original, 'version' => (string) $original['version']])->assertOk()->assertJsonPath('replayed', true)->assertJsonPath('revision', 1);
|
||||
$this->getJson($url)->assertOk()->assertJsonPath('result', $first['result']);
|
||||
$this->postJson($url, ['version' => $first['case']['version'], 'operation_key' => (string) Str::uuid(), 'answers' => ['participants' => 'several']])->assertOk()->assertJsonPath('revision', 2);
|
||||
$revision = $first['history'][0]['id'];
|
||||
$this->getJson($url.'?revision='.$revision)->assertOk()->assertJsonPath('historical', true)->assertJsonPath('result', $first['result'])->assertJsonPath('answers.participants', 'one');
|
||||
$this->getJson($url.'?'.http_build_query(['revision' => $revision, 'answers' => ['participants' => 'several']]))->assertUnprocessable();
|
||||
$this->getJson($url)->assertOk()->assertJsonPath('result.engine_version', 'SYNTHETIC-future-version')->assertJsonPath('answers.participants', 'several');
|
||||
}
|
||||
|
||||
public function test_scope_is_rechecked_before_validation_and_revocation_or_closure_does_not_allow_writes(): void
|
||||
{
|
||||
$id = $this->dossier();
|
||||
$url = '/investimentos/'.$id.'/forma-juridica';
|
||||
$input = ['version' => DB::table('desk_cases')->where('id', $id)->value('version'), 'operation_key' => (string) Str::uuid(), 'answers' => []];
|
||||
$this->actingAs(User::factory()->create())->getJson($url)->assertForbidden();
|
||||
$this->postJson($url, [])->assertForbidden();
|
||||
$this->actingAs($this->owner);
|
||||
$this->postJson($url, $input)->assertOk();
|
||||
DB::table('desk_cases')->where('id', $id)->update(['closed_at' => now()]);
|
||||
$this->getJson($url)->assertOk()->assertJsonPath('canWrite', false);
|
||||
$this->postJson($url, $input)->assertOk()->assertJsonPath('replayed', true);
|
||||
$this->postJson($url, [...$input, 'operation_key' => (string) Str::uuid()])->assertConflict();
|
||||
}
|
||||
|
||||
public function test_public_answers_continue_through_dossier_choice_and_explicit_creation_without_automatic_save(): void
|
||||
{
|
||||
$answers = ['participants' => 'one', 'preferred' => 'anonymous'];
|
||||
$target = '/investimentos?'.http_build_query(['company_comparison' => $answers]);
|
||||
$this->get($target)->assertRedirect('/login');
|
||||
$this->assertSame(url($target), session('url.intended'));
|
||||
$id = $this->dossier();
|
||||
$this->getJson($target)->assertOk()->assertJsonPath('companyComparisonAnswers.participants', 'one');
|
||||
$record = $this->postJson('/investimentos', ['title' => 'SYNTHETIC comparison destination', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true, 'company_comparison' => $answers])->assertCreated()->json();
|
||||
$this->assertStringContainsString('/forma-juridica?', $record['comparison_href']);
|
||||
$this->getJson($record['comparison_href'])->assertOk()->assertJsonPath('workingCopy', true)->assertJsonPath('answers.preferred', 'anonymous')->assertJsonPath('saved', null);
|
||||
$this->assertSame(0, DB::table('desk_events')->where('action', CompanyComparison::EVENT)->count());
|
||||
$this->getJson('/investimentos/'.$id.'/forma-juridica?'.http_build_query(['answers' => $answers]))->assertOk()->assertJsonPath('saved', null);
|
||||
}
|
||||
|
||||
public function test_organization_coeditor_revocation_is_effective_before_replay_or_validation(): void
|
||||
{
|
||||
$id = $this->dossier();
|
||||
$org = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $org, 'name' => 'SYNTHETIC comparison organization', 'organization_type' => 'private']);
|
||||
DB::table('desk_cases')->where('id', $id)->update(['organization_id' => $org]);
|
||||
$coeditor = User::factory()->create();
|
||||
$viewer = User::factory()->create();
|
||||
foreach ([[$this->owner, 'officer'], [$coeditor, 'officer'], [$viewer, 'viewer']] as [$actor, $role]) {
|
||||
DB::table('memberships')->insert(['id' => (string) Str::uuid(), 'organization_id' => $org, 'user_id' => $actor->id, 'role' => $role]);
|
||||
}
|
||||
$url = '/investimentos/'.$id.'/forma-juridica';
|
||||
$input = ['version' => DB::table('desk_cases')->where('id', $id)->value('version'), 'operation_key' => (string) Str::uuid(), 'answers' => ['participants' => 'several']];
|
||||
$this->actingAs($coeditor)->postJson($url, $input)->assertOk();
|
||||
$this->actingAs($viewer)->getJson($url)->assertOk()->assertJsonPath('canWrite', false);
|
||||
$this->postJson($url, $input)->assertForbidden();
|
||||
$this->actingAs($coeditor);
|
||||
DB::table('memberships')->where('organization_id', $org)->where('user_id', $coeditor->id)->update(['deleted_at' => now()]);
|
||||
$this->getJson($url)->assertForbidden();
|
||||
$this->postJson($url, $input)->assertForbidden();
|
||||
$this->postJson($url, [])->assertForbidden();
|
||||
$this->actingAs($this->owner)->getJson($url)->assertOk()->assertJsonPath('answers.participants', 'several');
|
||||
$this->assertSame(1, DB::table('desk_events')->where('case_id', $id)->where('action', CompanyComparison::EVENT)->count());
|
||||
}
|
||||
|
||||
public function test_all_history_pages_recover_old_editions_without_overwriting_the_latest_snapshot(): void
|
||||
{
|
||||
$id = $this->dossier();
|
||||
$url = '/investimentos/'.$id.'/forma-juridica';
|
||||
$version = DB::table('desk_cases')->where('id', $id)->value('version');
|
||||
for ($revision = 1; $revision <= 26; $revision++) {
|
||||
$this->postJson($url, ['version' => $version++, 'operation_key' => (string) Str::uuid(), 'answers' => ['participants' => $revision % 2 === 1 ? 'one' : 'several']])->assertOk()->assertJsonPath('revision', $revision);
|
||||
}
|
||||
$page = $this->getJson($url)->assertOk()->assertJsonCount(25, 'history')->assertJsonPath('saved.revision', 26)->json();
|
||||
$this->assertNotNull($page['historyNext']);
|
||||
$older = $this->getJson($url.'?history_before='.$page['historyNext'])->assertOk()->assertJsonCount(1, 'history')->assertJsonPath('history.0.revision', 1)->assertJsonPath('saved.revision', 26)->json();
|
||||
$this->getJson($url.'?revision='.$older['history'][0]['id'])->assertOk()->assertJsonPath('saved.revision', 1);
|
||||
$this->getJson($url)->assertOk()->assertJsonPath('saved.revision', 26);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\CompanyPreparation;
|
||||
use App\Services\VirtualDesk;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class CompanyPreparationTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $owner;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
config(['investor-path.enabled' => true, 'investmoz_ai.enabled' => false, 'suitecrm.enabled' => false, 'portal.notifications_enabled' => false]);
|
||||
Http::preventStrayRequests();
|
||||
$this->owner = User::factory()->create(['name' => 'SYNTHETIC Proponent']);
|
||||
}
|
||||
|
||||
private function dossier(): string
|
||||
{
|
||||
return $this->actingAs($this->owner)->postJson('/investimentos', ['title' => 'SYNTHETIC corporate preparation', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertCreated()->json('id');
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function party(array $changes = []): array
|
||||
{
|
||||
return [...['id' => (string) Str::uuid(), 'name' => 'SYNTHETIC Participant', 'kind' => 'person', 'source' => null, 'roles' => ['subscriber'], 'cash' => '0', 'in_kind' => '0', 'paid' => '0'], ...$changes];
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function input(string $id, array $facts): array
|
||||
{
|
||||
return ['version' => DB::table('desk_cases')->where('id', $id)->value('version'), 'operation_key' => (string) Str::uuid(), 'facts' => $facts];
|
||||
}
|
||||
|
||||
public function test_private_empty_preparation_needs_no_templates_ia_or_master_writes(): void
|
||||
{
|
||||
$id = $this->dossier();
|
||||
$url = '/investimentos/'.$id.'/preparar-empresa';
|
||||
$this->getJson($url)->assertOk()->assertHeader('Cache-Control', 'no-store, private')->assertJsonPath('definition.template_status', 'source_pending')->assertJsonPath('review.totals', null)->assertJsonPath('saved', null);
|
||||
$this->get($url)->assertOk()->assertInertia(fn ($page) => $page->component('investment/company-preparation'));
|
||||
$this->postJson($url, $this->input($id, []))->assertOk()->assertJsonPath('revision', 1);
|
||||
$this->getJson($url)->assertOk()->assertJsonPath('saved.revision', 1)->assertJsonPath('review.status', 'preparation');
|
||||
$this->assertDatabaseCount('organizations', 0);
|
||||
$this->assertDatabaseCount('investment_company_declarations', 0);
|
||||
$this->assertDatabaseCount('desk_requests', 0);
|
||||
}
|
||||
|
||||
public function test_exact_capital_and_shares_do_not_round_large_or_fractional_values(): void
|
||||
{
|
||||
$id = $this->dossier();
|
||||
$url = '/investimentos/'.$id.'/preparar-empresa';
|
||||
$facts = ['form' => 'anonymous', 'currency' => 'MZN', 'capital' => '999999999999999999.000003', 'nominal_value' => '0,000001', 'parties' => [
|
||||
$this->party(['cash' => '999999999999999999', 'in_kind' => '0', 'paid' => '999999999999999999', 'share_count' => '999999999999999999']),
|
||||
$this->party(['cash' => '0.000001', 'in_kind' => '0.000002', 'paid' => '0.000001', 'share_count' => '3']),
|
||||
]];
|
||||
$this->postJson($url, $this->input($id, $facts))->assertOk();
|
||||
$r = $this->getJson($url)->assertOk()->assertJsonPath('review.totals.subscribed', '999999999999999999.000003')
|
||||
->assertJsonPath('review.totals.paid', '999999999999999999.000001')->assertJsonPath('review.totals.unpaid', '0.000002')
|
||||
->assertJsonPath('review.totals.shares_nominal', '1000000000000.000002')->json();
|
||||
$this->assertStringContainsString('valor nominal', implode(' ', $r['review']['issues']));
|
||||
$this->assertStringNotContainsString('soma das subscrições difere', implode(' ', $r['review']['issues']));
|
||||
}
|
||||
|
||||
public function test_unknown_amounts_never_become_zero_and_inconsistencies_can_be_saved_as_draft(): void
|
||||
{
|
||||
$id = $this->dossier();
|
||||
$url = '/investimentos/'.$id.'/preparar-empresa';
|
||||
$facts = ['form' => 'quotas', 'capital' => '100', 'currency' => 'MZN', 'parties' => [$this->party(['cash' => null, 'paid' => null])]];
|
||||
$this->postJson($url, $this->input($id, $facts))->assertOk();
|
||||
$this->getJson($url)->assertOk()->assertJsonPath('review.totals.subscribed', null)->assertJsonPath('review.totals.paid', null)->assertJsonPath('review.totals.unpaid', null);
|
||||
$facts['parties'][0]['cash'] = '40';
|
||||
$facts['parties'][0]['paid'] = '41';
|
||||
$this->postJson($url, $this->input($id, $facts))->assertOk();
|
||||
$r = $this->getJson($url)->assertOk()->assertJsonPath('review.totals.unpaid', '-1')->json();
|
||||
$issues = implode(' ', $r['review']['issues']);
|
||||
$this->assertStringContainsString('excede', $issues);
|
||||
$this->assertStringContainsString('difere do capital', $issues);
|
||||
foreach (['-1', '1e3', '1.1234567', '1 000', '1000000000000000000'] as $invalid) {
|
||||
$this->postJson($url, $this->input($id, ['capital' => $invalid]))->assertUnprocessable()->assertJsonValidationErrors('facts.capital');
|
||||
}
|
||||
$this->postJson($url, $this->input($id, ['parties' => [$this->party(['share_count' => '1.5'])]]))->assertUnprocessable();
|
||||
}
|
||||
|
||||
public function test_role_accumulation_distinct_people_and_work_are_not_merged_or_counted_as_capital(): void
|
||||
{
|
||||
$id = $this->dossier();
|
||||
$url = '/investimentos/'.$id.'/preparar-empresa';
|
||||
$a = $this->party(['cash' => '10', 'work' => 'SYNTHETIC labour', 'roles' => ['subscriber', 'administrator']]);
|
||||
$b = $this->party(['cash' => '20', 'roles' => ['subscriber', 'representative'], 'represented_id' => $a['id']]);
|
||||
$this->postJson($url, $this->input($id, ['form' => 'collective', 'capital' => '30', 'currency' => 'MZN', 'parties' => [$a, $b]]))->assertOk();
|
||||
$r = $this->getJson($url)->assertOk()->assertJsonCount(2, 'facts.parties')->assertJsonPath('review.totals.subscribed', '30')->json();
|
||||
$this->assertStringContainsString('artigo 266', $r['review']['note']);
|
||||
$this->assertStringNotContainsString('representante', implode(' ', $r['review']['issues']));
|
||||
$this->assertNotContains('beneficial_owner', $r['facts']['parties'][0]['roles']);
|
||||
$b['represented_id'] = $b['id'];
|
||||
$this->postJson($url, $this->input($id, ['parties' => [$a, $b]]))->assertOk();
|
||||
$this->assertStringContainsString('representante', implode(' ', $this->getJson($url)->json('review.issues')));
|
||||
$this->postJson($url, $this->input($id, ['parties' => [$a, $a]]))->assertUnprocessable();
|
||||
}
|
||||
|
||||
public function test_reused_dossier_identity_is_server_resolved_and_historical_values_remain_frozen(): void
|
||||
{
|
||||
$id = $this->dossier();
|
||||
$url = '/investimentos/'.$id.'/preparar-empresa';
|
||||
$party = $this->party(['source' => 'case_proponent', 'name' => 'FORGED identity', 'kind' => 'entity']);
|
||||
$this->postJson($url, $this->input($id, ['parties' => [$party]]))->assertOk();
|
||||
$r = $this->getJson($url)->assertOk()->assertJsonPath('facts.parties.0.name', 'SYNTHETIC Proponent')->assertJsonPath('facts.parties.0.kind', 'person')->json();
|
||||
$this->assertSame($id, $r['facts']['parties'][0]['source_snapshot']['reference']);
|
||||
$case = DB::table('desk_cases')->where('id', $id)->first();
|
||||
$payload = app(VirtualDesk::class)->decode($case->payload);
|
||||
$payload['name'] = 'SYNTHETIC future context';
|
||||
DB::table('desk_cases')->where('id', $id)->update(['payload' => app(VirtualDesk::class)->encode($payload)]);
|
||||
$this->postJson($url, $this->input($id, ['parties' => [$party]]))->assertOk()->assertJsonPath('unchanged', true);
|
||||
$this->getJson($url)->assertJsonPath('facts.parties.0.name', 'SYNTHETIC Proponent');
|
||||
$this->postJson($url, $this->input($id, ['parties' => [$this->party(['source' => 'case_company'])]]))->assertUnprocessable();
|
||||
$forged = $this->party(['source_snapshot' => ['reference' => 'invented']]);
|
||||
$this->postJson($url, $this->input($id, ['parties' => [$forged]]))->assertUnprocessable();
|
||||
$stored = DB::table('desk_cases')->where('id', $id)->first();
|
||||
$this->assertStringNotContainsString('SYNTHETIC Proponent', $stored->payload);
|
||||
$event = DB::table('desk_events')->where('case_id', $id)->where('action', CompanyPreparation::EVENT)->first();
|
||||
$this->assertStringNotContainsString('SYNTHETIC Proponent', $event->payload);
|
||||
$this->assertStringNotContainsString('SYNTHETIC Proponent', DB::table('audit_events')->where('entity_id', $id)->get()->toJson());
|
||||
}
|
||||
|
||||
public function test_correct_draft_history_and_dossier_version_are_preserved_without_advancing_workflow(): void
|
||||
{
|
||||
$id = $this->dossier();
|
||||
$url = '/investimentos/'.$id.'/preparar-empresa';
|
||||
$before = DB::table('journey_steps')->orderBy('id')->get()->toJson();
|
||||
$input = $this->input($id, ['form' => 'quotas', 'capital' => '10']);
|
||||
$this->postJson($url, $input)->assertOk()->assertJsonPath('revision', 1);
|
||||
$this->postJson($url, $input)->assertOk()->assertJsonPath('replayed', true);
|
||||
$this->postJson($url, [...$input, 'facts' => ['capital' => '11']])->assertConflict();
|
||||
$this->postJson($url, [...$input, 'operation_key' => (string) Str::uuid()])->assertConflict();
|
||||
$first = $this->getJson($url)->json();
|
||||
$this->postJson($url, $this->input($id, ['form' => 'quotas', 'capital' => '10.000']))->assertOk()->assertJsonPath('unchanged', true);
|
||||
$this->postJson($url, $this->input($id, ['form' => 'individual', 'capital' => '10']))->assertOk()->assertJsonPath('revision', 2);
|
||||
$this->getJson($url)->assertJsonPath('facts.capital', '10')->assertJsonPath('review.totals', null);
|
||||
config(['company-comparison.source.edition' => 'SYNTHETIC future edition']);
|
||||
$this->getJson($url.'?revision='.$first['history'][0]['id'])->assertOk()->assertJsonPath('historical', true)->assertJsonPath('facts.form', 'quotas')->assertJsonPath('definition.source', $first['definition']['source']);
|
||||
$this->getJson($url)->assertJsonPath('saved.revision', 2);
|
||||
$this->assertSame($before, DB::table('journey_steps')->orderBy('id')->get()->toJson());
|
||||
DB::table('desk_cases')->where('id', $id)->update(['closed_at' => now()]);
|
||||
config(['company-comparison.forms' => ['individual' => ['title' => 'SYNTHETIC future catalogue']]]);
|
||||
$this->postJson($url, $input)->assertOk()->assertJsonPath('replayed', true);
|
||||
$this->postJson($url, $this->input($id, []))->assertConflict();
|
||||
}
|
||||
|
||||
public function test_all_history_pages_and_cross_dossier_revision_access(): void
|
||||
{
|
||||
$id = $this->dossier();
|
||||
$url = '/investimentos/'.$id.'/preparar-empresa';
|
||||
for ($i = 1; $i <= 26; $i++) {
|
||||
$this->postJson($url, $this->input($id, ['notes' => 'SYNTHETIC revision '.$i]))->assertOk();
|
||||
}
|
||||
$r = $this->getJson($url)->assertJsonCount(25, 'history')->json();
|
||||
$old = $this->getJson($url.'?history_before='.$r['historyNext'])->assertJsonCount(1, 'history')->json();
|
||||
$this->getJson($url.'?revision='.$old['history'][0]['id'])->assertOk()->assertJsonPath('saved.revision', 1);
|
||||
$other = $this->dossier();
|
||||
$this->getJson('/investimentos/'.$other.'/preparar-empresa?revision='.$old['history'][0]['id'])->assertNotFound();
|
||||
$this->getJson($url.'?history_before=invalid')->assertUnprocessable();
|
||||
}
|
||||
|
||||
public function test_current_permission_is_required_before_read_replay_or_validation(): void
|
||||
{
|
||||
$id = $this->dossier();
|
||||
$url = '/investimentos/'.$id.'/preparar-empresa';
|
||||
$org = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $org, 'name' => 'SYNTHETIC Org', 'organization_type' => 'private']);
|
||||
DB::table('desk_cases')->where('id', $id)->update(['organization_id' => $org]);
|
||||
$editor = User::factory()->create();
|
||||
$viewer = User::factory()->create();
|
||||
foreach ([[$this->owner, 'officer'], [$editor, 'officer'], [$viewer, 'viewer']] as [$actor, $role]) {
|
||||
DB::table('memberships')->insert(['id' => (string) Str::uuid(), 'organization_id' => $org, 'user_id' => $actor->id, 'role' => $role]);
|
||||
}
|
||||
$input = $this->input($id, ['notes' => 'SYNTHETIC private']);
|
||||
$this->actingAs($editor)->postJson($url, $input)->assertOk();
|
||||
$this->actingAs($viewer)->getJson($url)->assertOk()->assertJsonPath('canWrite', false);
|
||||
$this->postJson($url, $input)->assertForbidden();
|
||||
DB::table('memberships')->where('organization_id', $org)->where('user_id', $editor->id)->update(['deleted_at' => now()]);
|
||||
$this->actingAs($editor)->getJson($url)->assertForbidden();
|
||||
$this->postJson($url, $input)->assertForbidden();
|
||||
$this->postJson($url, [])->assertForbidden();
|
||||
$this->actingAs(User::factory()->create())->getJson($url)->assertForbidden();
|
||||
$this->assertSame(1, DB::table('desk_events')->where('case_id', $id)->where('action', CompanyPreparation::EVENT)->count());
|
||||
}
|
||||
}
|
||||
@@ -124,10 +124,10 @@ class CrmIntakeTest extends TestCase
|
||||
$this->post('/management/crm/convert/'.$interest->id, $this->data($user))->assertRedirect();
|
||||
$lead = Lead::firstOrFail();
|
||||
$task = CrmTask::firstOrFail();
|
||||
$this->patch('/management/crm/leads/'.$lead->id.'/tasks/'.$task->id, ['status' => 'done'])->assertSessionHasErrors('status');
|
||||
$this->patch('/management/crm/leads/'.$lead->id.'/tasks/'.$task->id, ['version' => $task->fresh()->getAttribute('version_no'), 'status' => 'done'])->assertSessionHasErrors('status');
|
||||
$this->post('/management/crm/leads/'.$lead->id.'/tasks', ['title' => 'Reunião', 'due_at' => now()->addDays(2)->toIso8601String(), 'assignee_user_id' => $user->id])->assertRedirect();
|
||||
$this->patch('/management/crm/leads/'.$lead->id.'/tasks/'.$task->id, ['status' => 'done'])->assertRedirect();
|
||||
$this->patch('/management/crm/leads/'.$lead->id, ['status' => 'qualified', 'owner_user_id' => $user->id, 'qualification_reason' => 'Informação confirmada pelo gestor.'])->assertRedirect();
|
||||
$this->patch('/management/crm/leads/'.$lead->id.'/tasks/'.$task->id, ['version' => $task->fresh()->getAttribute('version_no'), 'status' => 'done'])->assertRedirect();
|
||||
$this->patch('/management/crm/leads/'.$lead->id, ['version' => $lead->fresh()->getAttribute('version_no'), 'status' => 'qualified', 'owner_user_id' => $user->id, 'qualification_reason' => 'Informação confirmada pelo gestor.'])->assertRedirect();
|
||||
$this->assertSame('qualified', $lead->fresh()->status);
|
||||
$this->assertDatabaseHas('audit_events', ['entity_id' => $lead->id, 'action' => 'updated']);
|
||||
}
|
||||
@@ -141,10 +141,10 @@ class CrmIntakeTest extends TestCase
|
||||
$contact = Contact::firstOrFail();
|
||||
$this->get('/management/crm/investors')->assertOk();
|
||||
$this->get('/management/crm/investors/'.$investor->id)->assertOk();
|
||||
$this->patch('/management/crm/investors/'.$investor->id, ['legal_name' => 'Nome revisto', 'investor_type' => 'domestic', 'status' => 'active'])->assertRedirect();
|
||||
$this->patch('/management/crm/investors/'.$investor->id, ['version' => $investor->fresh()->getAttribute('version_no'), 'legal_name' => 'Nome revisto', 'investor_type' => 'domestic', 'status' => 'active'])->assertRedirect();
|
||||
$this->assertSame('Nome revisto', $investor->fresh()->legal_name);
|
||||
$other = Contact::create(['full_name' => 'Outro', 'email' => 'other@example.invalid']);
|
||||
$this->patch('/management/crm/investors/'.$investor->id.'/contacts/'.$contact->id, ['full_name' => 'Nome revisto', 'email' => 'OTHER@example.invalid'])->assertSessionHasErrors('email');
|
||||
$this->patch('/management/crm/investors/'.$investor->id.'/contacts/'.$other->id, ['full_name' => 'Outro', 'email' => 'new@example.invalid'])->assertNotFound();
|
||||
$this->patch('/management/crm/investors/'.$investor->id.'/contacts/'.$contact->id, ['version' => $contact->fresh()->getAttribute('version_no'), 'full_name' => 'Nome revisto', 'email' => 'OTHER@example.invalid'])->assertSessionHasErrors('email');
|
||||
$this->patch('/management/crm/investors/'.$investor->id.'/contacts/'.$other->id, ['version' => $other->fresh()->getAttribute('version_no'), 'full_name' => 'Outro', 'email' => 'new@example.invalid'])->assertNotFound();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\CrmTask;
|
||||
use App\Models\Lead;
|
||||
use App\Models\User;
|
||||
use App\Services\Ai\AssistiveRules;
|
||||
use App\Services\VirtualDesk;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\Support\AuthenticatesQaActors;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class CrmNextActionTest extends TestCase
|
||||
{
|
||||
use AuthenticatesQaActors;
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $manager;
|
||||
|
||||
private User $owner;
|
||||
|
||||
private Lead $lead;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
Http::fake();
|
||||
Mail::fake();
|
||||
$this->manager = User::factory()->create();
|
||||
$this->owner = User::factory()->create();
|
||||
config(['portal.managers' => [$this->manager->email], 'suitecrm.enabled' => false, 'investmoz_ai.enabled' => false]);
|
||||
$this->lead = Lead::create(['title' => 'SYNTHETIC next action lead', 'status' => 'new', 'owner_user_id' => $this->manager->id])->fresh();
|
||||
$this->actingAsWithMfa($this->manager);
|
||||
}
|
||||
|
||||
private function caseId(): string
|
||||
{
|
||||
return app(VirtualDesk::class)->createCase($this->owner, ['title' => 'SYNTHETIC next action dossier', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->id;
|
||||
}
|
||||
|
||||
private function task(?string $case = null, array $changes = []): CrmTask
|
||||
{
|
||||
$data = ['lead_id' => $this->lead->id, 'title' => 'SYNTHETIC next action task', 'status' => 'open', 'due_at' => now()->addDay(), 'assignee_user_id' => $this->manager->id];
|
||||
if ($case !== null) {
|
||||
$data = [...$data, 'desk_case_id' => $case, 'accepted_by' => $this->owner->id, 'accepted_at' => now(), 'guidance_key' => 'synthetic-'.Str::uuid(), 'data_classification' => 'confidential', 'external_sync_status' => 'pending_authorization'];
|
||||
}
|
||||
|
||||
return CrmTask::create([...$data, ...$changes])->fresh();
|
||||
}
|
||||
|
||||
private function state(string $case, string $state): void
|
||||
{
|
||||
app(VirtualDesk::class)->changeCaseState($this->owner, $case, ['version' => (int) DB::table('desk_cases')->where('id', $case)->value('version'), 'state' => $state, 'reason' => 'SYNTHETIC owner changes dossier availability', 'client_key' => (string) Str::uuid()]);
|
||||
}
|
||||
|
||||
private function qualification(string $status = 'qualified'): array
|
||||
{
|
||||
return ['version' => $this->lead->fresh()->version_no, 'owner_user_id' => $this->manager->id, 'status' => $status, 'qualification_reason' => 'SYNTHETIC internal qualification reason'];
|
||||
}
|
||||
|
||||
public function test_a_suspended_future_task_cannot_qualify_the_lead(): void
|
||||
{
|
||||
$case = $this->caseId();
|
||||
$task = $this->task($case);
|
||||
$this->state($case, 'closed');
|
||||
$before = [$this->lead->fresh()->getAttributes(), $task->fresh()->getAttributes(), DB::table('audit_events')->count()];
|
||||
$this->patchJson('/management/crm/leads/'.$this->lead->id, $this->qualification())->assertUnprocessable()->assertJsonValidationErrors('status');
|
||||
$this->assertSame($before, [$this->lead->fresh()->getAttributes(), $task->fresh()->getAttributes(), DB::table('audit_events')->count()]);
|
||||
}
|
||||
|
||||
public function test_a_suspended_alternative_cannot_allow_finishing_the_last_available_task(): void
|
||||
{
|
||||
$current = $this->task();
|
||||
$case = $this->caseId();
|
||||
$alternative = $this->task($case);
|
||||
$this->state($case, 'closed');
|
||||
$this->patchJson('/management/crm/leads/'.$this->lead->id.'/tasks/'.$current->id, ['version' => 1, 'status' => 'done'])->assertUnprocessable()->assertJsonValidationErrors('status');
|
||||
$this->assertSame('open', $current->fresh()->status);
|
||||
$this->assertSame(1, $current->fresh()->version_no);
|
||||
$this->assertSame('open', $alternative->fresh()->status);
|
||||
}
|
||||
|
||||
public function test_guidance_cannot_bypass_the_next_action_rule_for_a_task_linked_to_an_active_lead(): void
|
||||
{
|
||||
$case = $this->caseId();
|
||||
$task = $this->task($case);
|
||||
$events = DB::table('desk_events')->count();
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$case.'/tarefas/'.$task->id, ['version' => 1, 'status' => 'done', 'reason' => 'SYNTHETIC attempted final response'])->assertUnprocessable()->assertJsonValidationErrors('status');
|
||||
$this->assertSame('open', $task->fresh()->status);
|
||||
$this->assertSame(1, $task->fresh()->version_no);
|
||||
$this->assertSame($events, DB::table('desk_events')->count());
|
||||
}
|
||||
|
||||
public function test_owner_reopening_restores_eligibility_without_rewriting_task_states(): void
|
||||
{
|
||||
$current = $this->task();
|
||||
$case = $this->caseId();
|
||||
$alternative = $this->task($case);
|
||||
$before = $alternative->getAttributes();
|
||||
$this->state($case, 'closed');
|
||||
$this->state($case, 'open');
|
||||
$this->assertSame($before, $alternative->fresh()->getAttributes());
|
||||
$this->patchJson('/management/crm/leads/'.$this->lead->id, $this->qualification())->assertRedirect();
|
||||
$this->patchJson('/management/crm/leads/'.$this->lead->id.'/tasks/'.$current->id, ['version' => 1, 'status' => 'done'])->assertRedirect();
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$case.'/tarefas/'.$alternative->id, ['version' => 1, 'status' => 'cancelled', 'reason' => 'SYNTHETIC last alternative cannot finish'])->assertUnprocessable()->assertJsonValidationErrors('status');
|
||||
$this->assertSame('open', $alternative->fresh()->status);
|
||||
}
|
||||
|
||||
public function test_guidance_can_finish_with_another_available_future_task_and_keeps_its_audit_route(): void
|
||||
{
|
||||
$case = $this->caseId();
|
||||
$current = $this->task($case);
|
||||
$other = $this->task(null, ['status' => 'in_progress']);
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$case.'/tarefas/'.$current->id, ['version' => 1, 'status' => 'done', 'reason' => 'SYNTHETIC response with next action'])->assertOk();
|
||||
$this->assertSame('done', $current->fresh()->status);
|
||||
$this->assertSame(2, $current->fresh()->version_no);
|
||||
$this->assertSame('in_progress', $other->fresh()->status);
|
||||
$this->assertSame(1, DB::table('desk_events')->where('action', 'guidance_task_updated')->count());
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$case.'/tarefas/'.$current->id, ['version' => 1, 'status' => 'open', 'reason' => 'SYNTHETIC stale response'])->assertConflict();
|
||||
}
|
||||
|
||||
public function test_expired_undated_deleted_and_other_lead_tasks_are_not_future_replacements_but_disqualification_still_works(): void
|
||||
{
|
||||
$current = $this->task(null, ['due_at' => now()->subDay()]);
|
||||
$this->task(null, ['due_at' => null]);
|
||||
$this->task()->delete();
|
||||
$other = Lead::create(['title' => 'SYNTHETIC different lead', 'status' => 'new']);
|
||||
$this->task(null, ['lead_id' => $other->id]);
|
||||
$this->patchJson('/management/crm/leads/'.$this->lead->id, $this->qualification())->assertUnprocessable()->assertJsonValidationErrors('status');
|
||||
$this->patchJson('/management/crm/leads/'.$this->lead->id, $this->qualification('disqualified'))->assertRedirect();
|
||||
$this->patchJson('/management/crm/leads/'.$this->lead->id.'/tasks/'.$current->id, ['version' => 1, 'status' => 'done'])->assertRedirect();
|
||||
}
|
||||
|
||||
public function test_guidance_without_a_crm_lead_keeps_existing_permissions_and_owner_closure(): void
|
||||
{
|
||||
$case = $this->caseId();
|
||||
$task = $this->task($case, ['lead_id' => null, 'assignee_user_id' => $this->owner->id]);
|
||||
$this->actingAs($this->owner)->postJson('/balcao-virtual/dossiers/'.$case.'/tarefas/'.$task->id, ['version' => 1, 'status' => 'done', 'reason' => 'SYNTHETIC standalone investor task'])->assertOk();
|
||||
$this->state($case, 'closed');
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$case.'/tarefas/'.$task->id, ['version' => 2, 'status' => 'open', 'reason' => 'SYNTHETIC closed case remains read only'])->assertConflict();
|
||||
$this->assertSame('done', $task->fresh()->status);
|
||||
}
|
||||
|
||||
public function test_new_rule_does_not_grant_crm_or_dossier_access(): void
|
||||
{
|
||||
$case = $this->caseId();
|
||||
$task = $this->task($case);
|
||||
$other = User::factory()->create();
|
||||
$this->actingAs($other)->patchJson('/management/crm/leads/'.$this->lead->id.'/tasks/'.$task->id, ['version' => 1, 'status' => 'done'])->assertForbidden();
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$case.'/tarefas/'.$task->id, ['version' => 1, 'status' => 'done', 'reason' => 'SYNTHETIC unrelated account'])->assertForbidden();
|
||||
$this->assertSame('open', $task->fresh()->status);
|
||||
}
|
||||
|
||||
public function test_archived_lead_does_not_block_an_existing_authorized_guidance_response(): void
|
||||
{
|
||||
$case = $this->caseId();
|
||||
$task = $this->task($case);
|
||||
$this->lead->delete();
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$case.'/tarefas/'.$task->id, ['version' => 1, 'status' => 'done', 'reason' => 'SYNTHETIC archived lead retains dossier response'])->assertOk();
|
||||
$this->assertSame('done', $task->fresh()->status);
|
||||
$this->assertSoftDeleted('leads', ['id' => $this->lead->id]);
|
||||
}
|
||||
|
||||
public function test_unlinked_crm_does_not_depend_on_optional_desk_tables(): void
|
||||
{
|
||||
$first = $this->task();
|
||||
$this->task();
|
||||
DB::statement('ALTER TABLE desk_cases RENAME TO desk_cases_qa_unavailable');
|
||||
try {
|
||||
$this->patchJson('/management/crm/leads/'.$this->lead->id, $this->qualification())->assertRedirect();
|
||||
$this->patchJson('/management/crm/leads/'.$this->lead->id.'/tasks/'.$first->id, ['version' => 1, 'status' => 'done'])->assertRedirect();
|
||||
} finally {
|
||||
DB::statement('ALTER TABLE desk_cases_qa_unavailable RENAME TO desk_cases');
|
||||
}
|
||||
}
|
||||
|
||||
public function test_read_models_distinguish_suspended_tasks_and_keep_their_history(): void
|
||||
{
|
||||
$case = $this->caseId();
|
||||
$suspended = $this->task($case, ['due_at' => now()->subDay()]);
|
||||
$this->state($case, 'closed');
|
||||
$available = $this->task(null, ['due_at' => now()->subHour()]);
|
||||
$this->get('/management/crm/leads')->assertInertia(fn ($page) => $page->where('leads.data.0.overdue_tasks_count', 1));
|
||||
$this->get('/management/crm/leads/'.$this->lead->id)->assertInertia(fn ($page) => $page->where('nextAction.future_tasks', 0)->has('lead.tasks', 2));
|
||||
$this->assertSame('open', $suspended->fresh()->status);
|
||||
$this->assertSame('open', $available->fresh()->status);
|
||||
$available->delete();
|
||||
$alerts = app(AssistiveRules::class)->quality();
|
||||
$this->assertCount(1, array_filter($alerts, fn ($row) => ($row['rule'] ?? null) === 'missing_next_action' && ($row['record_id'] ?? null) === $this->lead->id));
|
||||
Http::assertNothingSent();
|
||||
Mail::assertNothingSent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\Contact;
|
||||
use App\Models\CrmTask;
|
||||
use App\Models\Investor;
|
||||
use App\Models\Lead;
|
||||
use App\Models\User;
|
||||
use App\Services\PortalAudit;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\Support\AuthenticatesQaActors;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class CrmRecordVersionsTest extends TestCase
|
||||
{
|
||||
use AuthenticatesQaActors;
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $first;
|
||||
|
||||
private User $second;
|
||||
|
||||
private Investor $investor;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
$this->first = User::factory()->create();
|
||||
$this->second = User::factory()->create();
|
||||
config(['portal.managers' => [$this->first->email, $this->second->email]]);
|
||||
$this->actingAsWithMfa($this->first);
|
||||
$this->investor = Investor::create(['legal_name' => 'SYNTHETIC original investor', 'investor_type' => 'domestic', 'status' => 'prospect'])->fresh();
|
||||
}
|
||||
|
||||
private function investorData(array $changes = []): array
|
||||
{
|
||||
return ['version' => 1, 'legal_name' => 'SYNTHETIC first edit', 'investor_type' => 'domestic', 'status' => 'active', ...$changes];
|
||||
}
|
||||
|
||||
public function test_stale_investor_form_cannot_overwrite_a_more_recent_edit_and_audit_excludes_personal_text(): void
|
||||
{
|
||||
$url = '/management/crm/investors/'.$this->investor->id;
|
||||
$this->patchJson($url, $this->investorData())->assertRedirect();
|
||||
$this->actingAsWithMfa($this->second)->patchJson($url, $this->investorData(['legal_name' => 'SYNTHETIC stale edit']))->assertUnprocessable()->assertJsonValidationErrors('version');
|
||||
$this->assertDatabaseHas('investors', ['id' => $this->investor->id, 'legal_name' => 'SYNTHETIC first edit', 'version_no' => 2]);
|
||||
$events = DB::table('audit_events')->where('entity_type', 'investors')->where('entity_id', $this->investor->id)->where('action', 'updated')->get();
|
||||
$this->assertCount(1, $events);
|
||||
$this->assertSame(1, json_decode($events[0]->before_data, true)['values']['version_no']);
|
||||
$this->assertSame(2, json_decode($events[0]->after_data, true)['values']['version_no']);
|
||||
$this->assertStringNotContainsString('SYNTHETIC first edit', $events[0]->after_data);
|
||||
}
|
||||
|
||||
public function test_shared_contact_has_one_version_across_investors_and_old_forms_do_not_restore_old_phone(): void
|
||||
{
|
||||
$contact = Contact::create(['full_name' => 'SYNTHETIC shared contact', 'email' => 'synthetic-shared@example.invalid', 'phone' => '111'])->fresh();
|
||||
$other = Investor::create(['legal_name' => 'SYNTHETIC other investor', 'investor_type' => 'domestic', 'status' => 'prospect']);
|
||||
foreach ([$this->investor->id, $other->id] as $id) {
|
||||
DB::table('investor_contacts')->insert(['investor_id' => $id, 'contact_id' => $contact->id]);
|
||||
}
|
||||
$data = ['version' => 1, 'full_name' => 'SYNTHETIC shared contact', 'email' => 'SYNTHETIC-SHARED@example.invalid', 'phone' => '222'];
|
||||
$this->patchJson('/management/crm/investors/'.$this->investor->id.'/contacts/'.$contact->id, $data)->assertRedirect();
|
||||
$this->actingAsWithMfa($this->second)->patchJson('/management/crm/investors/'.$other->id.'/contacts/'.$contact->id, [...$data, 'phone' => '111', 'full_name' => 'SYNTHETIC stale name'])->assertUnprocessable()->assertJsonValidationErrors('version');
|
||||
$this->assertDatabaseHas('contacts', ['id' => $contact->id, 'phone' => '222', 'email' => 'synthetic-shared@example.invalid', 'version_no' => 2]);
|
||||
$this->get('/management/crm/investors/'.$other->id)->assertOk()->assertInertia(fn ($page) => $page->where('contacts.0.version_no', 2)->where('contacts.0.phone', '222'));
|
||||
}
|
||||
|
||||
public function test_lead_and_task_edits_are_versioned_without_bypassing_the_next_action_rule(): void
|
||||
{
|
||||
$lead = Lead::create(['investor_id' => $this->investor->id, 'owner_user_id' => $this->first->id, 'title' => 'SYNTHETIC lead', 'status' => 'new'])->fresh();
|
||||
$task = CrmTask::create(['lead_id' => $lead->id, 'title' => 'SYNTHETIC next action', 'status' => 'open', 'due_at' => now()->addDay(), 'assignee_user_id' => $this->first->id])->fresh();
|
||||
$taskUrl = '/management/crm/leads/'.$lead->id.'/tasks/'.$task->id;
|
||||
$this->patchJson($taskUrl, ['version' => 1, 'status' => 'done'])->assertUnprocessable()->assertJsonValidationErrors('status');
|
||||
$this->patchJson($taskUrl, ['version' => 1, 'status' => 'in_progress'])->assertRedirect();
|
||||
CrmTask::create(['lead_id' => $lead->id, 'title' => 'SYNTHETIC alternative next action', 'status' => 'open', 'due_at' => now()->addDays(2), 'assignee_user_id' => $this->first->id]);
|
||||
$this->patchJson($taskUrl, ['version' => 1, 'status' => 'done'])->assertUnprocessable()->assertJsonValidationErrors('version');
|
||||
$data = ['version' => 1, 'owner_user_id' => $this->first->id, 'status' => 'qualified', 'qualification_reason' => 'SYNTHETIC qualified after internal review'];
|
||||
$this->patchJson('/management/crm/leads/'.$lead->id, $data)->assertRedirect();
|
||||
$this->actingAsWithMfa($this->second)->patchJson('/management/crm/leads/'.$lead->id, [...$data, 'status' => 'disqualified', 'qualification_reason' => 'SYNTHETIC stale qualification'])->assertUnprocessable()->assertJsonValidationErrors('version');
|
||||
$this->assertDatabaseHas('leads', ['id' => $lead->id, 'status' => 'qualified', 'version_no' => 2]);
|
||||
$this->assertDatabaseHas('tasks', ['id' => $task->id, 'status' => 'in_progress', 'version_no' => 2]);
|
||||
}
|
||||
|
||||
public function test_missing_version_is_an_explicit_validation_error_and_does_not_change_the_record(): void
|
||||
{
|
||||
$data = $this->investorData();
|
||||
unset($data['version']);
|
||||
$this->patchJson('/management/crm/investors/'.$this->investor->id, $data)->assertUnprocessable()->assertJsonValidationErrors('version')->assertJsonPath('errors.version.0', 'Actualize os dados para recuperar a versão deste registo antes de gravar. As suas edições foram conservadas.');
|
||||
$this->assertDatabaseHas('investors', ['id' => $this->investor->id, 'legal_name' => 'SYNTHETIC original investor', 'version_no' => 1]);
|
||||
}
|
||||
|
||||
public function test_noop_does_not_create_another_revision_or_audit_and_metadata_cannot_be_reset_by_input(): void
|
||||
{
|
||||
$before = $this->investor->getAttributes();
|
||||
$url = '/management/crm/investors/'.$this->investor->id;
|
||||
$this->patchJson($url, ['version' => 1, 'legal_name' => $this->investor->legal_name, 'investor_type' => 'domestic', 'status' => 'prospect'])->assertRedirect();
|
||||
$this->assertSame($before, $this->investor->fresh()->getAttributes());
|
||||
$this->assertSame(0, DB::table('audit_events')->where('entity_id', $this->investor->id)->count());
|
||||
$this->patchJson($url, [...$this->investorData(), 'version_no' => 0])->assertRedirect();
|
||||
$this->assertSame(2, $this->investor->fresh()->version_no);
|
||||
}
|
||||
|
||||
public function test_other_existing_crm_writers_advance_the_revision_without_changing_their_authority(): void
|
||||
{
|
||||
PortalAudit::save($this->investor, ['status' => 'active'], $this->first->id);
|
||||
$this->assertSame(2, $this->investor->fresh()->version_no);
|
||||
$this->patchJson('/management/crm/investors/'.$this->investor->id, $this->investorData())->assertUnprocessable()->assertJsonValidationErrors('version');
|
||||
}
|
||||
|
||||
public function test_document_edition_is_not_incremented_by_the_crm_revision_policy(): void
|
||||
{
|
||||
$id = (string) Str::uuid();
|
||||
DB::table('documents')->insert(['id' => $id, 'version_no' => 7, 'source_system' => 'synthetic', 'file_name' => 'synthetic-source.txt', 'media_type' => 'text/plain', 'storage_key' => 'synthetic-no-binary-required/'.$id, 'sha256' => str_repeat('a', 64), 'status' => 'quarantined']);
|
||||
$document = new class extends Model
|
||||
{
|
||||
protected $table = 'documents';
|
||||
|
||||
protected $guarded = [];
|
||||
|
||||
public $incrementing = false;
|
||||
|
||||
protected $keyType = 'string';
|
||||
};
|
||||
$document = $document->newQuery()->findOrFail($id);
|
||||
PortalAudit::save($document, ['file_name' => 'synthetic-renamed.txt'], $this->first->id);
|
||||
$this->assertDatabaseHas('documents', ['id' => $id, 'version_no' => 7, 'file_name' => 'synthetic-renamed.txt']);
|
||||
}
|
||||
|
||||
public function test_a_valid_revision_does_not_grant_manager_authority(): void
|
||||
{
|
||||
$this->actingAs(User::factory()->create())->patchJson('/management/crm/investors/'.$this->investor->id, $this->investorData())->assertForbidden();
|
||||
$this->assertDatabaseHas('investors', ['id' => $this->investor->id, 'version_no' => 1]);
|
||||
$this->actingAs($this->second)->patchJson('/management/crm/investors/'.$this->investor->id, $this->investorData())->assertRedirect();
|
||||
$this->assertDatabaseHas('investors', ['id' => $this->investor->id, 'version_no' => 2, 'legal_name' => 'SYNTHETIC first edit']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\CrmTask;
|
||||
use App\Models\Lead;
|
||||
use App\Models\User;
|
||||
use App\Services\CrmTaskCreation;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Str;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use Tests\Support\AuthenticatesQaActors;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class CrmTaskCreationTest extends TestCase
|
||||
{
|
||||
use AuthenticatesQaActors;
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $manager;
|
||||
|
||||
private Lead $lead;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
Http::fake();
|
||||
Mail::fake();
|
||||
$this->manager = User::factory()->create();
|
||||
config(['portal.managers' => [$this->manager->email], 'suitecrm.enabled' => false, 'investmoz_ai.enabled' => false]);
|
||||
$this->lead = Lead::create(['title' => 'SYNTHETIC task creation lead', 'status' => 'new', 'owner_user_id' => $this->manager->id])->fresh();
|
||||
$this->actingAsWithMfa($this->manager);
|
||||
}
|
||||
|
||||
private function url(): string
|
||||
{
|
||||
return '/management/crm/leads/'.$this->lead->id.'/tasks';
|
||||
}
|
||||
|
||||
/** @return array{client_key:string,title:string,due_at:string,assignee_user_id:int} */
|
||||
private function command(): array
|
||||
{
|
||||
return ['client_key' => (string) Str::uuid(), 'title' => 'SYNTHETIC next action', 'due_at' => now()->addDay()->toIso8601String(), 'assignee_user_id' => $this->manager->id];
|
||||
}
|
||||
|
||||
public function test_repeating_the_same_creation_does_not_create_a_second_task(): void
|
||||
{
|
||||
$command = $this->command();
|
||||
$this->post($this->url(), $command)->assertRedirect();
|
||||
$events = DB::table('audit_events')->where('entity_type', 'tasks')->count();
|
||||
$this->post($this->url(), $command)->assertRedirect();
|
||||
$this->assertDatabaseCount('tasks', 1);
|
||||
$this->assertSame($events, DB::table('audit_events')->where('entity_type', 'tasks')->count());
|
||||
}
|
||||
|
||||
public function test_retry_uses_the_original_receipt_after_deadline_expiry_and_assignee_retirement(): void
|
||||
{
|
||||
$other = User::factory()->create();
|
||||
config(['portal.managers' => [$this->manager->email, $other->email]]);
|
||||
$command = [...$this->command(), 'assignee_user_id' => $other->id];
|
||||
$this->post($this->url(), $command)->assertRedirect();
|
||||
$events = DB::table('audit_events')->where('entity_type', 'tasks')->count();
|
||||
config(['portal.managers' => [$this->manager->email]]);
|
||||
$this->travel(2)->days();
|
||||
$this->post($this->url(), $command)->assertRedirect();
|
||||
$this->assertDatabaseCount('tasks', 1);
|
||||
$this->assertSame($events, DB::table('audit_events')->where('entity_type', 'tasks')->count());
|
||||
}
|
||||
|
||||
public function test_a_used_key_cannot_create_a_modified_task(): void
|
||||
{
|
||||
$command = $this->command();
|
||||
$this->post($this->url(), $command)->assertRedirect();
|
||||
$events = DB::table('audit_events')->where('entity_type', 'tasks')->count();
|
||||
$this->postJson($this->url(), [...$command, 'title' => 'SYNTHETIC changed'])->assertConflict();
|
||||
$this->assertDatabaseCount('tasks', 1);
|
||||
$this->assertSame($events, DB::table('audit_events')->where('entity_type', 'tasks')->count());
|
||||
}
|
||||
|
||||
public function test_validation_does_not_consume_the_key_or_write_a_task(): void
|
||||
{
|
||||
$command = $this->command();
|
||||
$this->postJson($this->url(), [...$command, 'due_at' => now()->subDay()->toIso8601String(), 'assignee_user_id' => 999999])->assertUnprocessable()->assertJsonValidationErrors(['due_at', 'assignee_user_id']);
|
||||
$this->assertDatabaseCount('tasks', 0);
|
||||
$this->assertDatabaseCount('audit_events', 0);
|
||||
$this->post($this->url(), $command)->assertRedirect();
|
||||
$this->assertDatabaseCount('tasks', 1);
|
||||
}
|
||||
|
||||
public function test_equivalent_offsets_and_whitespace_replay_the_same_canonical_values(): void
|
||||
{
|
||||
$command = $this->command();
|
||||
$this->post($this->url(), $command)->assertRedirect();
|
||||
$this->post($this->url(), [...$command, 'client_key' => strtoupper($command['client_key']), 'title' => ' '.$command['title'].' ', 'due_at' => CarbonImmutable::parse($command['due_at'])->setTimezone('Africa/Maputo')->toIso8601String()])->assertRedirect();
|
||||
$this->assertDatabaseCount('tasks', 1);
|
||||
}
|
||||
|
||||
public function test_receipts_are_scoped_to_the_current_actor_and_lead_without_raw_audit_payloads(): void
|
||||
{
|
||||
$command = $this->command();
|
||||
$this->post($this->url(), $command)->assertRedirect();
|
||||
$other = User::factory()->create();
|
||||
config(['portal.managers' => [$this->manager->email, $other->email]]);
|
||||
$this->actingAsWithMfa($other);
|
||||
$this->post($this->url(), $command)->assertRedirect();
|
||||
$secondLead = Lead::create(['title' => 'SYNTHETIC second', 'status' => 'new']);
|
||||
app(CrmTaskCreation::class)->create($other, $secondLead, $command, [$this->manager->id]);
|
||||
$this->assertDatabaseCount('tasks', 3);
|
||||
$this->get('/management/crm/leads/'.$this->lead->id)->assertOk()->assertInertia(fn (Assert $page) => $page->component('crm/lead')
|
||||
->where('taskCreation.actor_id', $other->id)->where('taskCreation.lead_id', $this->lead->id)
|
||||
->has('taskCreation.commands', 1)->where('taskCreation.commands.0.key', $command['client_key'])
|
||||
->missing('taskCreation.commands.0.hash')->missing('taskCreation.commands.0.title')->missing('taskCreation.commands.0.after_data'));
|
||||
}
|
||||
|
||||
public function test_replay_requires_current_management_authority_even_when_the_creation_was_accepted(): void
|
||||
{
|
||||
$command = $this->command();
|
||||
$this->post($this->url(), $command)->assertRedirect();
|
||||
$events = DB::table('audit_events')->where('entity_type', 'tasks')->count();
|
||||
config(['portal.managers' => []]);
|
||||
$this->postJson($this->url(), $command)->assertForbidden();
|
||||
$this->get('/management/crm/leads/'.$this->lead->id)->assertForbidden();
|
||||
$this->assertDatabaseCount('tasks', 1);
|
||||
$this->assertSame($events, DB::table('audit_events')->where('entity_type', 'tasks')->count());
|
||||
}
|
||||
|
||||
public function test_completed_and_deleted_tasks_are_not_restored_by_replay(): void
|
||||
{
|
||||
$command = $this->command();
|
||||
$this->post($this->url(), $command)->assertRedirect();
|
||||
$task = CrmTask::firstOrFail();
|
||||
$task->update(['status' => 'done', 'version_no' => 2]);
|
||||
$this->post($this->url(), $command)->assertRedirect();
|
||||
$this->assertSame('done', $task->fresh()->status);
|
||||
$task->delete();
|
||||
$events = DB::table('audit_events')->where('entity_type', 'tasks')->count();
|
||||
$this->post($this->url(), $command)->assertRedirect();
|
||||
$this->assertDatabaseCount('tasks', 1);
|
||||
$this->assertSoftDeleted($task);
|
||||
$this->assertSame($events, DB::table('audit_events')->where('entity_type', 'tasks')->count());
|
||||
$this->get('/management/crm/leads/'.$this->lead->id)->assertInertia(fn (Assert $page) => $page->has('lead.tasks', 0)->has('taskCreation.commands', 1));
|
||||
}
|
||||
|
||||
public function test_legacy_callers_without_a_key_keep_the_existing_creation_contract(): void
|
||||
{
|
||||
$command = $this->command();
|
||||
unset($command['client_key']);
|
||||
$this->post($this->url(), $command)->assertRedirect();
|
||||
$this->post($this->url(), $command)->assertRedirect();
|
||||
$this->assertDatabaseCount('tasks', 2);
|
||||
$this->assertSame(0, DB::table('audit_events')->where('source_system', 'portal-crm-task-creation')->count());
|
||||
}
|
||||
|
||||
public function test_malformed_keys_and_unapproved_assignees_are_rejected_without_writes(): void
|
||||
{
|
||||
$command = $this->command();
|
||||
$this->postJson($this->url(), [...$command, 'client_key' => 'invalid'])->assertUnprocessable()->assertJsonValidationErrors('client_key');
|
||||
$unapproved = User::factory()->create();
|
||||
$this->postJson($this->url(), [...$command, 'assignee_user_id' => $unapproved->id])->assertUnprocessable()->assertJsonValidationErrors('assignee_user_id');
|
||||
$this->assertDatabaseCount('tasks', 0);
|
||||
$this->assertDatabaseCount('audit_events', 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\Lead;
|
||||
use App\Models\User;
|
||||
use App\Services\CrmTaskPreparations;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Str;
|
||||
use Inertia\Testing\AssertableInertia;
|
||||
use Tests\Support\AuthenticatesQaActors;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class CrmTaskPreparationTest extends TestCase
|
||||
{
|
||||
use AuthenticatesQaActors, RefreshDatabase;
|
||||
|
||||
private User $manager;
|
||||
|
||||
private Lead $lead;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
Http::fake();
|
||||
Mail::fake();
|
||||
$this->manager = User::factory()->create();
|
||||
config(['portal.managers' => [$this->manager->email], 'suitecrm.enabled' => false, 'investmoz_ai.enabled' => false]);
|
||||
$this->lead = Lead::create(['title' => 'SYNTHETIC preparation lead', 'status' => 'new', 'owner_user_id' => $this->manager->id])->fresh();
|
||||
$this->actingAsWithMfa($this->manager);
|
||||
}
|
||||
|
||||
private function url(): string
|
||||
{
|
||||
return '/management/crm/leads/'.$this->lead->id.'/task-preparation';
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function input(): array
|
||||
{
|
||||
return ['version' => 0, 'operation_key' => (string) Str::uuid(), 'snapshot' => [
|
||||
'values' => ['title' => 'SYNTHETIC partial task', 'due_at' => '', 'assignee_user_id' => ''],
|
||||
'generation' => ['title' => 1, 'due_at' => 0, 'assignee_user_id' => 0], 'pending' => null,
|
||||
]];
|
||||
}
|
||||
|
||||
public function test_partial_preparation_is_encrypted_and_recoverable_without_creating_a_task(): void
|
||||
{
|
||||
$input = $this->input();
|
||||
$this->postJson($this->url(), $input)->assertOk()->assertJsonPath('preparation.version', 1)->assertJsonPath('preparation.snapshot', $input['snapshot']);
|
||||
$stored = DB::table('crm_task_preparations')->first();
|
||||
$this->assertStringNotContainsString('SYNTHETIC partial task', $stored->snapshot);
|
||||
$this->assertSame($input['snapshot'], json_decode(Crypt::decryptString($stored->snapshot), true));
|
||||
$this->assertDatabaseCount('tasks', 0);
|
||||
$this->assertSame(1, DB::table('audit_events')->where('source_system', 'portal-crm-task-preparation')->count());
|
||||
$this->assertSame($input['snapshot'], app(CrmTaskPreparations::class)->view($this->manager, $this->lead)['snapshot']);
|
||||
}
|
||||
|
||||
public function test_repeated_checkpoint_is_read_only_and_changed_payload_with_same_key_conflicts(): void
|
||||
{
|
||||
$input = $this->input();
|
||||
$this->postJson($this->url(), $input)->assertOk();
|
||||
$audit = DB::table('audit_events')->where('source_system', 'portal-crm-task-preparation')->count();
|
||||
$this->postJson($this->url(), $input)->assertOk()->assertJsonPath('preparation.version', 1);
|
||||
$this->assertSame($audit, DB::table('audit_events')->where('source_system', 'portal-crm-task-preparation')->count());
|
||||
$input['snapshot']['values']['title'] = 'SYNTHETIC changed';
|
||||
$this->postJson($this->url(), $input)->assertConflict();
|
||||
$this->assertDatabaseCount('crm_task_preparations', 1);
|
||||
$this->assertSame(1, DB::table('crm_task_preparations')->value('version'));
|
||||
}
|
||||
|
||||
public function test_another_tab_cannot_overwrite_a_newer_preparation_with_a_stale_version(): void
|
||||
{
|
||||
$input = $this->input();
|
||||
$this->postJson($this->url(), $input)->assertOk();
|
||||
$other = $this->input();
|
||||
$other['snapshot']['values']['title'] = 'SYNTHETIC competing';
|
||||
$this->postJson($this->url(), $other)->assertConflict();
|
||||
$this->assertSame($input['snapshot'], app(CrmTaskPreparations::class)->view($this->manager, $this->lead)['snapshot']);
|
||||
$other['version'] = 1;
|
||||
$this->postJson($this->url(), $other)->assertOk()->assertJsonPath('preparation.version', 2);
|
||||
$this->assertSame($other['snapshot'], app(CrmTaskPreparations::class)->view($this->manager, $this->lead)['snapshot']);
|
||||
}
|
||||
|
||||
public function test_partial_text_and_empty_fields_survive_framework_normalisation(): void
|
||||
{
|
||||
$input = $this->input();
|
||||
$input['snapshot']['values']['title'] = " SYNTHETIC\npartial ";
|
||||
$this->postJson($this->url(), $input)->assertOk()->assertJsonPath('preparation.snapshot', $input['snapshot']);
|
||||
$this->assertDatabaseCount('tasks', 0);
|
||||
}
|
||||
|
||||
public function test_a_frozen_attempt_and_later_edits_survive_a_new_authenticated_session(): void
|
||||
{
|
||||
$input = $this->input();
|
||||
$input['snapshot']['pending'] = ['values' => ['title' => 'SYNTHETIC original', 'due_at' => now()->addDay()->toIso8601String(), 'assignee_user_id' => (string) $this->manager->id, 'client_key' => (string) Str::uuid()],
|
||||
'generation' => ['title' => 1, 'due_at' => 1, 'assignee_user_id' => 0]];
|
||||
$input['snapshot']['values']['title'] = 'SYNTHETIC later';
|
||||
$input['snapshot']['generation']['title'] = 2;
|
||||
$this->postJson($this->url(), $input)->assertOk();
|
||||
$this->flushSession();
|
||||
$this->actingAsWithMfa($this->manager->fresh());
|
||||
$this->get('/management/crm/leads/'.$this->lead->id)->assertOk()->assertInertia(fn (AssertableInertia $page) => $page->where('taskCreation.preparation.snapshot', $input['snapshot']));
|
||||
$this->assertDatabaseCount('tasks', 0);
|
||||
}
|
||||
|
||||
public function test_preparations_are_private_to_the_current_actor_and_lead(): void
|
||||
{
|
||||
$input = $this->input();
|
||||
$this->postJson($this->url(), $input)->assertOk();
|
||||
$other = User::factory()->create();
|
||||
config(['portal.managers' => [$this->manager->email, $other->email]]);
|
||||
$this->actingAsWithMfa($other);
|
||||
$this->get('/management/crm/leads/'.$this->lead->id)->assertOk()->assertInertia(fn (AssertableInertia $page) => $page->where('taskCreation.actor_id', $other->id)->where('taskCreation.preparation.snapshot', null));
|
||||
$this->postJson($this->url(), $this->input())->assertOk();
|
||||
$second = Lead::create(['title' => 'SYNTHETIC another lead', 'status' => 'new']);
|
||||
$this->assertNull(app(CrmTaskPreparations::class)->view($other, $second)['snapshot']);
|
||||
$this->assertDatabaseCount('crm_task_preparations', 2);
|
||||
}
|
||||
|
||||
public function test_current_management_authority_is_required_to_read_and_write_preparation(): void
|
||||
{
|
||||
$this->postJson($this->url(), $this->input())->assertOk();
|
||||
$stored = DB::table('crm_task_preparations')->value('snapshot');
|
||||
config(['portal.managers' => []]);
|
||||
$this->get('/management/crm/leads/'.$this->lead->id)->assertForbidden();
|
||||
$this->postJson($this->url(), $this->input())->assertForbidden();
|
||||
$this->assertSame($stored, DB::table('crm_task_preparations')->value('snapshot'));
|
||||
}
|
||||
|
||||
public function test_unknown_fields_invalid_nonce_and_generation_are_not_persisted(): void
|
||||
{
|
||||
$input = $this->input();
|
||||
$input['snapshot']['values']['private_extra'] = 'SYNTHETIC unwanted';
|
||||
$this->postJson($this->url(), $input)->assertUnprocessable();
|
||||
$input = $this->input();
|
||||
$input['operation_key'] = 'not-a-uuid';
|
||||
$this->postJson($this->url(), $input)->assertUnprocessable();
|
||||
$input = $this->input();
|
||||
$input['snapshot']['generation']['title'] = -1;
|
||||
$this->postJson($this->url(), $input)->assertUnprocessable();
|
||||
$this->assertDatabaseCount('crm_task_preparations', 0);
|
||||
$this->assertDatabaseCount('tasks', 0);
|
||||
}
|
||||
|
||||
public function test_unreadable_ciphertext_is_preserved_and_does_not_prevent_the_manual_task_path(): void
|
||||
{
|
||||
$this->postJson($this->url(), $this->input())->assertOk();
|
||||
DB::table('crm_task_preparations')->update(['snapshot' => 'SYNTHETIC unreadable ciphertext']);
|
||||
$this->get('/management/crm/leads/'.$this->lead->id)->assertOk()->assertInertia(fn (AssertableInertia $page) => $page->where('taskCreation.preparation.unavailable', true)->where('taskCreation.preparation.snapshot', null));
|
||||
$input = $this->input();
|
||||
$input['version'] = 1;
|
||||
$this->postJson($this->url(), $input)->assertConflict();
|
||||
$this->assertSame('SYNTHETIC unreadable ciphertext', DB::table('crm_task_preparations')->value('snapshot'));
|
||||
$this->post('/management/crm/leads/'.$this->lead->id.'/tasks', ['client_key' => (string) Str::uuid(), 'title' => 'SYNTHETIC manual', 'due_at' => now()->addDay()->toIso8601String(), 'assignee_user_id' => $this->manager->id])->assertRedirect();
|
||||
$this->assertDatabaseCount('tasks', 1);
|
||||
}
|
||||
|
||||
public function test_uninstalled_preparation_preserves_the_existing_manual_creation_contract(): void
|
||||
{
|
||||
Schema::rename('crm_task_preparations', 'crm_task_preparations_not_installed');
|
||||
$this->get('/management/crm/leads/'.$this->lead->id)->assertOk()->assertInertia(fn (AssertableInertia $page) => $page->where('taskCreation.preparation.installed', false));
|
||||
$this->postJson($this->url(), $this->input())->assertConflict();
|
||||
$this->post('/management/crm/leads/'.$this->lead->id.'/tasks', ['title' => 'SYNTHETIC manual', 'due_at' => now()->addDay()->toIso8601String(), 'assignee_user_id' => $this->manager->id])->assertRedirect();
|
||||
$this->assertDatabaseCount('tasks', 1);
|
||||
}
|
||||
|
||||
public function test_audit_metadata_does_not_copy_the_private_preparation(): void
|
||||
{
|
||||
$input = $this->input();
|
||||
$this->postJson($this->url(), $input)->assertOk();
|
||||
$event = DB::table('audit_events')->where('source_system', 'portal-crm-task-preparation')->first();
|
||||
$this->assertSame(['version' => 1], json_decode($event->after_data, true));
|
||||
$this->assertStringNotContainsString('SYNTHETIC partial task', json_encode($event, JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
public function test_creation_receipt_and_later_preparation_survive_a_new_session_without_duplicate_tasks(): void
|
||||
{
|
||||
$input = $this->input();
|
||||
$before = $this->lead->getAttributes();
|
||||
$command = ['title' => 'SYNTHETIC original task', 'due_at' => now()->addYear()->toIso8601String(), 'assignee_user_id' => (string) $this->manager->id, 'client_key' => (string) Str::uuid()];
|
||||
$input['snapshot']['pending'] = ['values' => $command, 'generation' => ['title' => 1, 'due_at' => 1, 'assignee_user_id' => 0]];
|
||||
$input['snapshot']['values']['title'] = 'SYNTHETIC next draft';
|
||||
$input['snapshot']['generation']['title'] = 2;
|
||||
$this->postJson($this->url(), $input)->assertOk();
|
||||
$taskUrl = '/management/crm/leads/'.$this->lead->id.'/tasks';
|
||||
$this->post($taskUrl, $command)->assertRedirect();
|
||||
$task = DB::table('tasks')->first();
|
||||
$this->flushSession();
|
||||
$this->actingAsWithMfa($this->manager->fresh());
|
||||
$this->get('/management/crm/leads/'.$this->lead->id)->assertOk()->assertInertia(fn (AssertableInertia $page) => $page
|
||||
->where('taskCreation.preparation.snapshot', $input['snapshot'])->has('taskCreation.commands', 1)
|
||||
->where('taskCreation.commands.0.key', $command['client_key'])->where('taskCreation.commands.0.task_id', $task->id));
|
||||
$events = DB::table('audit_events')->where('entity_type', 'tasks')->count();
|
||||
$this->post($taskUrl, $command)->assertRedirect();
|
||||
$this->assertDatabaseCount('tasks', 1);
|
||||
$this->assertSame($events, DB::table('audit_events')->where('entity_type', 'tasks')->count());
|
||||
$this->assertSame($before, $this->lead->fresh()->getAttributes());
|
||||
}
|
||||
|
||||
public function test_a_changed_access_revision_rejects_the_old_session_without_overwriting_preparation(): void
|
||||
{
|
||||
$this->postJson($this->url(), $this->input())->assertOk();
|
||||
$stored = DB::table('crm_task_preparations')->value('snapshot');
|
||||
DB::table('users')->where('id', $this->manager->id)->increment('portal_access_revision');
|
||||
$input = $this->input();
|
||||
$input['version'] = 1;
|
||||
$this->postJson($this->url(), $input)->assertUnauthorized();
|
||||
$this->assertSame($stored, DB::table('crm_task_preparations')->value('snapshot'));
|
||||
$this->assertDatabaseCount('tasks', 0);
|
||||
}
|
||||
|
||||
public function test_accepted_integer_strings_and_uppercase_attempt_keys_have_a_canonical_json_projection(): void
|
||||
{
|
||||
$input = $this->input();
|
||||
$key = (string) Str::uuid();
|
||||
$input['snapshot']['generation']['title'] = '2';
|
||||
$input['snapshot']['pending'] = ['values' => ['title' => 'SYNTHETIC pending', 'due_at' => now()->addYear()->toIso8601String(), 'assignee_user_id' => (string) $this->manager->id, 'client_key' => strtoupper($key)],
|
||||
'generation' => ['title' => '1', 'due_at' => 0, 'assignee_user_id' => 0]];
|
||||
$this->postJson($this->url(), $input)->assertOk()->assertJsonPath('preparation.snapshot.generation.title', 2)
|
||||
->assertJsonPath('preparation.snapshot.pending.generation.title', 1)->assertJsonPath('preparation.snapshot.pending.values.client_key', $key);
|
||||
$this->postJson($this->url(), $input)->assertOk()->assertJsonPath('preparation.version', 1);
|
||||
$this->assertSame(1, DB::table('audit_events')->where('source_system', 'portal-crm-task-preparation')->count());
|
||||
$this->assertDatabaseCount('tasks', 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\CrmTask;
|
||||
use App\Models\InterestRequest;
|
||||
use App\Models\Lead;
|
||||
use App\Models\User;
|
||||
use App\Services\DeskServiceEditor;
|
||||
use App\Services\PortalProfileAdministration;
|
||||
use App\Services\VirtualDesk;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\Support\AuthenticatesQaActors;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class DashboardWorkQueueTest extends TestCase
|
||||
{
|
||||
use AuthenticatesQaActors;
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $manager;
|
||||
|
||||
private User $other;
|
||||
|
||||
private ?string $edition = null;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
Http::fake();
|
||||
Mail::fake();
|
||||
$this->travelTo(now()->setDate(2026, 11, 3)->setTime(10, 0));
|
||||
$this->manager = User::factory()->create();
|
||||
$this->other = User::factory()->create();
|
||||
config(['portal.managers' => [$this->manager->email], 'portal.profile_access_enabled' => true, 'investor-path.enabled' => false, 'suitecrm.enabled' => false, 'investmoz_ai.enabled' => false]);
|
||||
}
|
||||
|
||||
private function interest(User $actor, array $changes = []): InterestRequest
|
||||
{
|
||||
return InterestRequest::create(['reference' => 'SYNTHETIC-'.Str::uuid(), 'full_name' => 'SYNTHETIC private contact', 'email' => 'synthetic-private@example.invalid',
|
||||
'investor_type' => 'empresa', 'message' => 'SYNTHETIC dashboard queue, not an active investor request.', 'country' => 'MZ', 'sector_interest' => 'Agricultura', 'privacy_consent' => true, 'assigned_to' => $actor->id, 'status' => 'received',
|
||||
'next_action' => 'SYNTHETIC assigned follow-up', 'next_action_due_at' => now()->subHour(), ...$changes]);
|
||||
}
|
||||
|
||||
/** @return array{id:string,case_id:string} */
|
||||
private function deskRequest(User $analyst, array $changes = [], bool $closed = false): array
|
||||
{
|
||||
$desk = app(VirtualDesk::class);
|
||||
$this->edition ??= app(DeskServiceEditor::class)->publish($this->manager, 'project-change', ['base_version' => 0, 'definition' => config('virtual-desk.services.project-change'), 'reason' => 'SYNTHETIC dashboard queue fixture', 'confirm' => true])->id;
|
||||
$case = $desk->createCase($this->other, ['title' => 'SYNTHETIC assigned dossier', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true]);
|
||||
$request = $desk->createRequest($this->other, $case->id, $this->edition, (string) Str::uuid());
|
||||
if (($changes['status'] ?? 'reviewing') !== 'draft') {
|
||||
$desk->save($this->other, $request->id, ['version' => 1, 'payload' => ['title' => 'SYNTHETIC queue project', 'description' => 'SYNTHETIC private preparation', 'original_reference' => 'SYNTHETIC-REF', 'change_reason' => 'SYNTHETIC internal change'], 'consent' => true], true);
|
||||
}
|
||||
// Queue fixture only: owner close/reopen and submission are exercised by their own accepted HTTP suites.
|
||||
DB::table('desk_requests')->where('id', $request->id)->update(['analyst_id' => $analyst->id, 'status' => 'reviewing', 'due_at' => now()->subHour(), ...$changes]);
|
||||
if ($closed) {
|
||||
DB::table('desk_cases')->where('id', $case->id)->update(['closed_at' => now()]);
|
||||
}
|
||||
|
||||
return ['id' => $request->id, 'case_id' => $case->id];
|
||||
}
|
||||
|
||||
private function task(User $actor, array $changes = []): CrmTask
|
||||
{
|
||||
$lead = Lead::create(['title' => 'SYNTHETIC assigned lead', 'owner_user_id' => $actor->id, 'status' => 'new']);
|
||||
|
||||
return CrmTask::create(['lead_id' => $lead->id, 'title' => 'SYNTHETIC assigned CRM task', 'assignee_user_id' => $actor->id, 'status' => 'open', 'due_at' => now()->subHour(), ...$changes]);
|
||||
}
|
||||
|
||||
private function queue(string $url = '/dashboard'): ?array
|
||||
{
|
||||
return $this->get($url)->assertOk()->viewData('page')['props']['workQueue'];
|
||||
}
|
||||
|
||||
public function test_public_investor_guest_and_unverified_actor_do_not_gain_operational_data(): void
|
||||
{
|
||||
$this->interest($this->manager);
|
||||
$this->task($this->manager);
|
||||
$this->actingAs($this->other)->get('/dashboard')->assertInertia(fn ($page) => $page->where('workQueue', null)->where('summary', null));
|
||||
$this->get('/management/crm/leads')->assertForbidden();
|
||||
$unverified = User::factory()->unverified()->create();
|
||||
$this->actingAs($unverified)->get('/dashboard')->assertRedirect('/email/verify');
|
||||
auth()->forgetGuards();
|
||||
$this->flushSession();
|
||||
$this->get('/dashboard')->assertRedirect('/login');
|
||||
}
|
||||
|
||||
public function test_assigned_interest_operator_sees_only_active_personal_records_and_real_destination(): void
|
||||
{
|
||||
$operator = User::factory()->create();
|
||||
$first = $this->interest($operator);
|
||||
$this->interest($operator, ['next_action_due_at' => now()->addDay()]);
|
||||
$this->interest($operator, ['next_action_due_at' => null, 'next_action' => null]);
|
||||
$other = $this->interest($this->other);
|
||||
foreach (['closed', 'cancelled', 'refused', 'converted'] as $status) {
|
||||
$this->interest($operator, ['status' => $status]);
|
||||
}
|
||||
$this->interest($operator)->delete();
|
||||
$this->actingAsWithMfa($operator);
|
||||
$queue = $this->queue();
|
||||
$this->assertSame(['interests'], array_keys($queue['groups']));
|
||||
$group = $queue['groups']['interests'];
|
||||
$this->assertSame(3, $group['total']);
|
||||
$this->assertSame(1, $group['overdue']);
|
||||
$this->assertSame((string) $first->id, $group['items'][0]['id']);
|
||||
$this->assertNull($group['items'][2]['due_at']);
|
||||
$this->assertSame('Acompanhar manifestação', $group['items'][2]['title']);
|
||||
$this->get($group['items'][0]['href'])->assertOk();
|
||||
$this->get('/management/interests/'.$other->id)->assertForbidden();
|
||||
$this->assertStringNotContainsString('synthetic-private@example.invalid', json_encode($queue));
|
||||
}
|
||||
|
||||
public function test_personal_groups_are_separate_and_dashboard_does_not_mutate_workflow_or_audit(): void
|
||||
{
|
||||
$interest = $this->interest($this->manager);
|
||||
$request = $this->deskRequest($this->manager);
|
||||
$task = $this->task($this->manager);
|
||||
$this->interest($this->other);
|
||||
$this->deskRequest($this->other);
|
||||
$this->task($this->other);
|
||||
$this->actingAsWithMfa($this->manager);
|
||||
$before = [DB::table('audit_events')->count(), DB::table('desk_events')->count(), DB::table('desk_notifications')->count(), $interest->fresh()->getAttributes(), $task->fresh()->getAttributes(), (array) DB::table('desk_requests')->find($request['id'])];
|
||||
$queue = $this->queue();
|
||||
foreach (['interests', 'desk', 'crm_tasks'] as $kind) {
|
||||
$this->assertSame(1, $queue['groups'][$kind]['total']);
|
||||
$this->assertSame(1, $queue['groups'][$kind]['overdue']);
|
||||
}
|
||||
$after = [DB::table('audit_events')->count(), DB::table('desk_events')->count(), DB::table('desk_notifications')->count(), $interest->fresh()->getAttributes(), $task->fresh()->getAttributes(), (array) DB::table('desk_requests')->find($request['id'])];
|
||||
$this->assertSame($before, $after);
|
||||
$this->getJson($queue['groups']['desk']['items'][0]['href'])->assertOk()->assertJsonPath('request.id', $request['id']);
|
||||
$href = $queue['groups']['crm_tasks']['items'][0]['href'];
|
||||
$this->assertStringEndsWith('#crm-task-'.$task->id, $href);
|
||||
$this->get(strtok($href, '#'))->assertOk()->assertInertia(fn ($page) => $page->where('lead.id', $task->lead_id));
|
||||
}
|
||||
|
||||
public function test_closed_dossiers_and_finished_deleted_or_unassigned_records_leave_the_active_queue(): void
|
||||
{
|
||||
$closed = $this->deskRequest($this->manager);
|
||||
$this->task($this->manager, ['desk_case_id' => $closed['case_id'], 'accepted_by' => $this->other->id, 'accepted_at' => now(), 'guidance_key' => 'SYNTHETIC-dashboard', 'data_classification' => 'confidential', 'external_sync_status' => 'pending_authorization']);
|
||||
DB::table('desk_cases')->where('id', $closed['case_id'])->update(['closed_at' => now()]);
|
||||
foreach (['draft', 'closed', 'cancelled'] as $status) {
|
||||
$this->deskRequest($this->manager, ['status' => $status]);
|
||||
}
|
||||
$this->deskRequest($this->manager, ['analyst_id' => null]);
|
||||
foreach (['done', 'cancelled'] as $status) {
|
||||
$this->task($this->manager, ['status' => $status]);
|
||||
}
|
||||
$this->task($this->manager)->delete();
|
||||
$deletedLead = $this->task($this->manager);
|
||||
Lead::findOrFail($deletedLead->lead_id)->delete();
|
||||
$active = $this->task($this->manager, ['due_at' => null]);
|
||||
$this->actingAsWithMfa($this->manager);
|
||||
$queue = $this->queue();
|
||||
$this->assertSame(0, $queue['groups']['desk']['total']);
|
||||
$this->assertSame(1, $queue['groups']['crm_tasks']['total']);
|
||||
$this->assertSame(0, $queue['groups']['crm_tasks']['overdue']);
|
||||
$this->assertSame($active->id, $queue['groups']['crm_tasks']['items'][0]['id']);
|
||||
$this->assertDatabaseHas('desk_requests', ['id' => $closed['id'], 'status' => 'reviewing']);
|
||||
}
|
||||
|
||||
public function test_assigned_desk_consultation_does_not_require_unrelated_management_privileges_and_revocation_is_immediate(): void
|
||||
{
|
||||
$analyst = User::factory()->create();
|
||||
$request = $this->deskRequest($analyst);
|
||||
$this->interest($analyst); // No confirmed MFA: detail authority for interests is still required.
|
||||
$this->actingAs($analyst);
|
||||
$queue = $this->queue();
|
||||
$this->assertSame(['desk'], array_keys($queue['groups']));
|
||||
$this->getJson($queue['groups']['desk']['items'][0]['href'])->assertOk();
|
||||
DB::table('desk_requests')->where('id', $request['id'])->update(['analyst_id' => $this->manager->id]);
|
||||
$this->assertNull($this->queue());
|
||||
$this->getJson('/balcao-virtual/pedidos/'.$request['id'])->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_independent_pagination_covers_every_row_once_and_uses_full_group_totals(): void
|
||||
{
|
||||
for ($i = 0; $i < 13; $i++) {
|
||||
$this->interest($this->manager);
|
||||
}
|
||||
for ($i = 0; $i < 6; $i++) {
|
||||
$this->deskRequest($this->manager);
|
||||
$this->task($this->manager);
|
||||
}
|
||||
$this->actingAsWithMfa($this->manager);
|
||||
$queue = $this->queue('/dashboard?desk_page=2&crm_tasks_page=2');
|
||||
$ids = [];
|
||||
for ($page = 1; $page <= 3; $page++) {
|
||||
$group = $queue['groups']['interests'];
|
||||
$this->assertSame($page, $group['page']);
|
||||
$this->assertSame(13, $group['total']);
|
||||
$this->assertSame(13, $group['overdue']);
|
||||
$ids = [...$ids, ...array_column($group['items'], 'id')];
|
||||
$this->assertSame(2, $queue['groups']['desk']['page']);
|
||||
$this->assertSame(2, $queue['groups']['crm_tasks']['page']);
|
||||
if ($group['next']) {
|
||||
$queue = $this->queue($group['next']);
|
||||
}
|
||||
}
|
||||
$this->assertCount(13, array_unique($ids));
|
||||
$this->assertNull($group['next']);
|
||||
$this->assertSame($ids, array_map('strval', InterestRequest::orderBy('id')->pluck('id')->all()));
|
||||
$this->assertSame(1, count($queue['groups']['desk']['items']));
|
||||
}
|
||||
|
||||
public function test_assignment_changes_recover_stale_pages_and_deadline_equal_to_now_is_not_overdue(): void
|
||||
{
|
||||
$this->interest($this->manager, ['next_action_due_at' => now()]);
|
||||
$this->actingAsWithMfa($this->manager);
|
||||
$queue = $this->queue('/dashboard?interests_page=99');
|
||||
$this->assertSame(1, $queue['groups']['interests']['page']);
|
||||
$this->assertSame(0, $queue['groups']['interests']['overdue']);
|
||||
$this->assertFalse($queue['groups']['interests']['items'][0]['overdue']);
|
||||
InterestRequest::query()->update(['assigned_to' => $this->other->id]);
|
||||
$queue = $this->queue('/dashboard?interests_page=99');
|
||||
$this->assertSame(0, $queue['groups']['interests']['total']);
|
||||
$this->assertSame(1, $queue['groups']['interests']['page']);
|
||||
}
|
||||
|
||||
public function test_mfa_expiration_auditor_restriction_and_removed_manager_are_not_bypassed(): void
|
||||
{
|
||||
$operator = User::factory()->create();
|
||||
$this->interest($operator);
|
||||
$this->actingAsWithMfa($operator);
|
||||
$this->assertNotNull($this->queue());
|
||||
$this->withSession(['portal.mfa_at' => time() - 901]);
|
||||
$this->assertNull($this->queue());
|
||||
$this->interest($this->manager);
|
||||
$this->task($this->manager);
|
||||
$this->actingAsWithMfa($this->manager);
|
||||
app(PortalProfileAdministration::class)->insertGrant((string) Str::uuid(), $this->other, ['user_id' => $this->manager->id, 'role' => 'auditor', 'opportunity_types' => [], 'responsibilities' => []]);
|
||||
$this->get('/dashboard')->assertInertia(fn ($page) => $page->where('workQueue', null)->where('summary', null));
|
||||
$this->get('/management/crm/leads')->assertForbidden();
|
||||
config(['portal.managers' => []]);
|
||||
$this->get('/dashboard')->assertInertia(fn ($page) => $page->where('summary', null)->where('workQueue', null));
|
||||
}
|
||||
|
||||
public function test_unlinked_crm_still_works_when_the_optional_desk_is_unavailable(): void
|
||||
{
|
||||
$this->task($this->manager);
|
||||
$this->actingAs($this->manager);
|
||||
DB::statement('ALTER TABLE desk_cases RENAME TO desk_cases_qa_unavailable');
|
||||
try {
|
||||
$queue = $this->queue();
|
||||
$this->assertArrayNotHasKey('desk', $queue['groups']);
|
||||
$this->assertSame(1, $queue['groups']['crm_tasks']['total']);
|
||||
$this->get(strtok($queue['groups']['crm_tasks']['items'][0]['href'], '#'))->assertOk();
|
||||
} finally {
|
||||
DB::statement('ALTER TABLE desk_cases_qa_unavailable RENAME TO desk_cases');
|
||||
}
|
||||
}
|
||||
|
||||
public function test_removing_manager_configuration_removes_crm_queue_and_dashboard_summary_independently_of_auditor_status(): void
|
||||
{
|
||||
$this->task($this->manager);
|
||||
$this->actingAs($this->manager);
|
||||
$this->assertSame(1, $this->queue()['groups']['crm_tasks']['total']);
|
||||
config(['portal.managers' => []]);
|
||||
$this->get('/dashboard')->assertInertia(fn ($page) => $page->where('summary', null)->where('workQueue', null));
|
||||
$this->get('/management/crm/leads')->assertForbidden();
|
||||
Http::assertNothingSent();
|
||||
Mail::assertNothingSent();
|
||||
}
|
||||
|
||||
public function test_invalid_pagination_is_rejected_without_querying_an_arbitrary_scope(): void
|
||||
{
|
||||
$this->actingAs($this->manager)->getJson('/dashboard?desk_page=-1')->assertUnprocessable()->assertJsonValidationErrors('desk_page');
|
||||
$this->getJson('/dashboard?crm_tasks_page=other')->assertUnprocessable()->assertJsonValidationErrors('crm_tasks_page');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,409 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\VirtualDesk;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Queue;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Testing\TestResponse;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class DeskAttachmentFieldsTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $owner;
|
||||
|
||||
private User $manager;
|
||||
|
||||
private string $caseId;
|
||||
|
||||
private string $id;
|
||||
|
||||
private string $edition;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
Storage::fake('local');
|
||||
Queue::fake();
|
||||
$this->owner = User::factory()->create();
|
||||
$this->manager = User::factory()->create();
|
||||
config(['portal.managers' => [$this->manager->email]]);
|
||||
$this->edition = $this->actingAs($this->manager)->putJson('/management/balcao/servicos/project-change', $this->publication())->assertCreated()->json('id');
|
||||
$this->caseId = $this->actingAs($this->owner)->postJson('/balcao-virtual/dossiers', ['title' => 'SYNTHETIC attachments', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertCreated()->json('id');
|
||||
$this->id = $this->newRequest();
|
||||
}
|
||||
|
||||
private function publication(int $base = 0): array
|
||||
{
|
||||
$definition = config('virtual-desk.services.project-change');
|
||||
$definition['fields'] = [...$definition['fields'],
|
||||
'branch' => ['label' => 'SYNTHETIC branch', 'type' => 'select', 'required' => false, 'options' => ['yes' => 'Yes', 'no' => 'No']],
|
||||
'support' => ['label' => 'SYNTHETIC required support', 'type' => 'attachment', 'required' => true, 'mime_types' => ['text/plain'], 'max_size_kb' => 2, 'max_files' => 2, 'when' => ['field' => 'branch', 'equals' => 'yes']],
|
||||
'optional_support' => ['label' => 'SYNTHETIC optional support', 'type' => 'attachment', 'required' => false, 'mime_types' => ['text/plain'], 'max_size_kb' => 2, 'max_files' => 1],
|
||||
];
|
||||
|
||||
return ['base_version' => $base, 'definition' => $definition, 'confirm' => true, 'reason' => 'SYNTHETIC attachment field QA, not an actual publication.'];
|
||||
}
|
||||
|
||||
private function newRequest(): string
|
||||
{
|
||||
return $this->postJson('/balcao-virtual/dossiers/'.$this->caseId.'/pedidos', ['service_version_id' => $this->edition, 'client_key' => (string) Str::uuid()])->assertCreated()->json('id');
|
||||
}
|
||||
|
||||
private function answers(array $support = []): array
|
||||
{
|
||||
return ['title' => 'SYNTHETIC submission', 'description' => 'SYNTHETIC complete private description', 'original_reference' => 'SYNTHETIC-REF', 'change_reason' => 'SYNTHETIC change', 'branch' => 'yes', 'support' => $support];
|
||||
}
|
||||
|
||||
private function upload(string $bytes = 'SYNTHETIC original bytes', ?string $requestId = null, ?string $field = 'support'): array
|
||||
{
|
||||
return $this->post('/balcao-virtual/dossiers/'.$this->caseId.'/documentos', ['version' => DB::table('desk_cases')->where('id', $this->caseId)->value('version'), 'request_id' => $requestId ?? $this->id, 'field_key' => $field,
|
||||
'file' => UploadedFile::fake()->createWithContent('synthetic-proof.txt', $bytes), 'source_reference' => 'SYNTHETIC source only', 'category' => 'SYNTHETIC evidence', 'consent' => true], ['Accept' => 'application/json'])->assertOk()->json();
|
||||
}
|
||||
|
||||
private function clean(string $link): \stdClass
|
||||
{
|
||||
$id = DB::table('desk_documents')->where('id', $link)->value('document_id');
|
||||
$document = DB::table('documents')->where('id', $id)->first();
|
||||
DB::table('documents')->where('id', $id)->update(['status' => 'active', 'malware_scan_status' => 'clean', 'malware_scanned_sha256' => trim($document->sha256)]);
|
||||
|
||||
return DB::table('documents')->where('id', $id)->first();
|
||||
}
|
||||
|
||||
private function save(array $payload, int $version = 1, bool $submit = true): TestResponse
|
||||
{
|
||||
return $this->putJson('/balcao-virtual/pedidos/'.$this->id, ['version' => $version, 'payload' => $payload, 'submit' => $submit, 'consent' => $submit]);
|
||||
}
|
||||
|
||||
public function test_required_attachment_pending_scan_draft_and_checkpoint_are_preserved_but_submission_requires_a_usable_original(): void
|
||||
{
|
||||
$this->save($this->answers())->assertUnprocessable()->assertJsonValidationErrors('payload.support');
|
||||
$uploaded = $this->upload();
|
||||
$link = $uploaded['link_id'];
|
||||
$payload = $this->answers([$link]);
|
||||
$this->assertCount(1, $uploaded['documents']);
|
||||
$this->assertSame(2, $uploaded['case_version']);
|
||||
$this->save($payload, 1, false)->assertOk();
|
||||
$this->postJson('/balcao-virtual/pedidos/'.$this->id.'/rascunho', ['version' => 0, 'request_version' => 2, 'operation_key' => (string) Str::uuid(), 'payload' => $payload, 'edited_keys' => []])->assertOk();
|
||||
$this->save($payload, 2)->assertUnprocessable()->assertJsonValidationErrors('payload.support');
|
||||
$document = $this->clean($link);
|
||||
$this->save($payload, 2)->assertOk()->assertJsonPath('status', 'submitted');
|
||||
$snapshot = app(VirtualDesk::class)->decode(DB::table('desk_requests')->where('id', $this->id)->value('submitted_snapshot'));
|
||||
$this->assertTrue($snapshot['field_attachments']['support']['applicable']);
|
||||
$this->assertTrue($snapshot['field_attachments']['support']['files'][0]['usable_at_submission']);
|
||||
$this->assertSame(trim($document->sha256), $snapshot['field_attachments']['support']['files'][0]['sha256']);
|
||||
$this->assertSame($this->edition, $snapshot['field_attachments']['support']['service_version_id']);
|
||||
$this->get('/balcao-virtual/pedidos/'.$this->id.'/recibo?format=html')->assertOk()->assertSee('synthetic-proof.txt')->assertSee('Limites desta versão: 2 KB');
|
||||
$this->actingAs(User::factory()->create())->get('/balcao-virtual/pedidos/'.$this->id.'/recibo?format=html')->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_uploaded_and_reused_files_must_fit_the_pinned_field_limits(): void
|
||||
{
|
||||
$this->post('/balcao-virtual/dossiers/'.$this->caseId.'/documentos', ['version' => 1, 'request_id' => $this->id, 'field_key' => 'support', 'file' => UploadedFile::fake()->createWithContent('oversized.txt', str_repeat('SYNTHETIC ', 400)), 'source_reference' => 'SYNTHETIC', 'consent' => true], ['Accept' => 'application/json'])->assertUnprocessable()->assertJsonValidationErrors('file');
|
||||
$png = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=');
|
||||
$this->post('/balcao-virtual/dossiers/'.$this->caseId.'/documentos', ['version' => 1, 'request_id' => $this->id, 'field_key' => 'support', 'file' => UploadedFile::fake()->createWithContent('synthetic.png', $png), 'source_reference' => 'SYNTHETIC', 'consent' => true], ['Accept' => 'application/json'])->assertUnprocessable()->assertJsonValidationErrors('file');
|
||||
$this->assertDatabaseCount('documents', 0);
|
||||
$this->assertSame([], Storage::disk('local')->allFiles());
|
||||
$upload = $this->upload(str_repeat('SYNTHETIC ', 400), null, null);
|
||||
$docId = $upload['documents'][0]['document_id'];
|
||||
$this->save($this->answers([$upload['link_id']]), 1, false)->assertUnprocessable()->assertJsonValidationErrors('payload.support');
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$this->caseId.'/documentos', ['version' => 2, 'request_id' => $this->id, 'field_key' => 'support', 'document_id' => $docId, 'consent' => true])->assertUnprocessable()->assertJsonValidationErrors('document_id');
|
||||
$this->assertDatabaseCount('documents', 1);
|
||||
$this->assertDatabaseCount('desk_documents', 1);
|
||||
}
|
||||
|
||||
public function test_selection_rejects_scalar_duplicate_unknown_and_excessive_references(): void
|
||||
{
|
||||
$one = $this->upload('SYNTHETIC one')['link_id'];
|
||||
$two = $this->upload('SYNTHETIC two')['link_id'];
|
||||
$three = $this->upload('SYNTHETIC three')['link_id'];
|
||||
foreach ([$one, [$one, $one], [(string) Str::uuid()], [$one, $two, $three]] as $invalid) {
|
||||
$this->save([...$this->answers(), 'support' => $invalid], 1, false)->assertUnprocessable();
|
||||
}
|
||||
$this->clean($one);
|
||||
$this->clean($two);
|
||||
$this->save($this->answers([$two, $one]))->assertOk();
|
||||
$before = DB::table('desk_requests')->where('id', $this->id)->first();
|
||||
$this->save($this->answers([$one, $two]))->assertOk();
|
||||
$this->assertEquals($before, DB::table('desk_requests')->where('id', $this->id)->first());
|
||||
}
|
||||
|
||||
public function test_same_binary_can_be_linked_to_two_requests_without_copying_or_widening_the_previous_scope(): void
|
||||
{
|
||||
$one = $this->upload();
|
||||
$other = $this->newRequest();
|
||||
$two = $this->upload('SYNTHETIC original bytes', $other);
|
||||
$this->assertNotSame($one['link_id'], $two['link_id']);
|
||||
$this->assertSame($one['documents'][0]['document_id'], $two['documents'][0]['document_id']);
|
||||
$this->assertDatabaseCount('documents', 1);
|
||||
$this->assertDatabaseCount('desk_documents', 2);
|
||||
$this->assertCount(1, Storage::disk('local')->allFiles());
|
||||
$this->assertDatabaseHas('desk_documents', ['id' => $one['link_id'], 'request_id' => $this->id]);
|
||||
$this->assertDatabaseHas('desk_documents', ['id' => $two['link_id'], 'request_id' => $other]);
|
||||
$this->save($this->answers([$two['link_id']]), 1, false)->assertUnprocessable()->assertJsonValidationErrors('payload.support');
|
||||
$version = DB::table('desk_cases')->where('id', $this->caseId)->value('version');
|
||||
$repeat = $this->upload();
|
||||
$this->assertSame($one['link_id'], $repeat['link_id']);
|
||||
$this->assertSame($version, $repeat['case_version']);
|
||||
$this->assertDatabaseCount('desk_documents', 2);
|
||||
}
|
||||
|
||||
public function test_authorised_reuse_uses_the_existing_reference_and_keeps_reviewer_access_within_the_new_link_scope(): void
|
||||
{
|
||||
$other = $this->newRequest();
|
||||
$original = $this->upload('SYNTHETIC original bytes', $other);
|
||||
$document = $this->clean($original['link_id']);
|
||||
$response = $this->postJson('/balcao-virtual/dossiers/'.$this->caseId.'/documentos', ['version' => $original['case_version'], 'request_id' => $this->id, 'field_key' => 'support', 'document_id' => $document->id, 'consent' => true])->assertOk();
|
||||
$link = $response->json('link_id');
|
||||
$this->assertNotSame($original['link_id'], $link);
|
||||
$this->assertDatabaseHas('desk_documents', ['id' => $link, 'source_reference' => 'SYNTHETIC source only', 'request_id' => $this->id]);
|
||||
$analyst = User::factory()->create();
|
||||
DB::table('desk_requests')->where('id', $this->id)->update(['analyst_id' => $analyst->id]);
|
||||
$this->actingAs($analyst)->getJson('/balcao-virtual/pedidos/'.$this->id)->assertOk()->assertJsonCount(1, 'documents')->assertJsonCount(0, 'reusableDocuments');
|
||||
$this->get('/balcao-virtual/dossiers/'.$this->caseId.'/documentos/'.$link)->assertOk();
|
||||
$this->get('/balcao-virtual/dossiers/'.$this->caseId.'/documentos/'.$original['link_id'])->assertForbidden();
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$this->caseId.'/documentos', ['version' => $response->json('case_version'), 'request_id' => $this->id, 'field_key' => 'support', 'document_id' => $document->id, 'consent' => true])->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_global_support_is_reused_by_multiple_questions_without_new_upload_or_source_entry(): void
|
||||
{
|
||||
$global = $this->post('/balcao-virtual/dossiers/'.$this->caseId.'/documentos', ['version' => 1, 'category' => 'SYNTHETIC global', 'file' => UploadedFile::fake()->createWithContent('synthetic-global.txt', 'SYNTHETIC shared bytes'), 'source_reference' => 'SYNTHETIC shared source', 'consent' => true], ['Accept' => 'application/json'])->assertOk()->json();
|
||||
$this->clean($global['link_id']);
|
||||
$this->save([...$this->answers([$global['link_id']]), 'optional_support' => [$global['link_id']]])->assertOk();
|
||||
$this->assertDatabaseCount('documents', 1);
|
||||
$this->assertDatabaseCount('desk_documents', 1);
|
||||
$snapshot = app(VirtualDesk::class)->decode(DB::table('desk_requests')->where('id', $this->id)->value('submitted_snapshot'));
|
||||
$this->assertSame($snapshot['field_attachments']['support']['files'], $snapshot['field_attachments']['optional_support']['files']);
|
||||
}
|
||||
|
||||
public function test_inactive_answers_are_preserved_without_becoming_required_or_claiming_applicable_evidence(): void
|
||||
{
|
||||
$unavailable = $this->upload(str_repeat('SYNTHETIC ', 400), null, null)['link_id'];
|
||||
$this->save([...$this->answers([$unavailable]), 'branch' => 'no'])->assertOk();
|
||||
$snapshot = app(VirtualDesk::class)->decode(DB::table('desk_requests')->where('id', $this->id)->value('submitted_snapshot'));
|
||||
$this->assertFalse($snapshot['field_attachments']['support']['applicable']);
|
||||
$this->assertFalse($snapshot['field_attachments']['support']['files'][0]['usable_at_submission']);
|
||||
$this->get('/balcao-virtual/pedidos/'.$this->id.'/recibo?format=html')->assertOk()->assertSee('Resposta conservada de pergunta não aplicável');
|
||||
}
|
||||
|
||||
public function test_tampered_missing_and_inconsistent_originals_cannot_be_submitted(): void
|
||||
{
|
||||
$link = $this->upload()['link_id'];
|
||||
$document = $this->clean($link);
|
||||
$original = Storage::disk('local')->get($document->storage_key);
|
||||
Storage::disk('local')->put($document->storage_key, 'SYNTHETIC changed bytes');
|
||||
$this->save($this->answers([$link]))->assertUnprocessable()->assertJsonValidationErrors('payload.support');
|
||||
Storage::disk('local')->delete($document->storage_key);
|
||||
$this->save($this->answers([$link]))->assertUnprocessable();
|
||||
Storage::disk('local')->put($document->storage_key, $original);
|
||||
DB::table('documents')->where('id', $document->id)->update(['size_bytes' => 1]);
|
||||
$this->save($this->answers([$link]))->assertUnprocessable();
|
||||
$this->assertDatabaseHas('desk_requests', ['id' => $this->id, 'version' => 1, 'submitted_snapshot' => null]);
|
||||
}
|
||||
|
||||
public function test_new_definition_does_not_change_old_limits_answers_or_receipt(): void
|
||||
{
|
||||
$one = $this->upload('SYNTHETIC one')['link_id'];
|
||||
$two = $this->upload('SYNTHETIC two')['link_id'];
|
||||
$this->clean($one);
|
||||
$this->clean($two);
|
||||
$this->save($this->answers([$one, $two]))->assertOk();
|
||||
$before = DB::table('desk_requests')->where('id', $this->id)->first();
|
||||
$input = $this->publication(1);
|
||||
$input['definition']['fields']['support']['max_files'] = 1;
|
||||
$input['definition']['fields']['support']['mime_types'] = ['application/pdf'];
|
||||
$this->actingAs($this->manager)->putJson('/management/balcao/servicos/project-change', $input)->assertCreated();
|
||||
$this->actingAs($this->owner)->getJson('/balcao-virtual/pedidos/'.$this->id)->assertOk()->assertJsonPath('definition.fields.support.max_files', 2)->assertJsonPath('definition.fields.support.mime_types', ['text/plain']);
|
||||
$this->get('/balcao-virtual/pedidos/'.$this->id.'/recibo?format=html')->assertOk()->assertSee('2 ficheiro(s).');
|
||||
$this->assertEquals($before, DB::table('desk_requests')->where('id', $this->id)->first());
|
||||
}
|
||||
|
||||
public function test_returned_field_scope_and_closed_or_submitted_state_are_enforced_for_uploads(): void
|
||||
{
|
||||
$link = $this->upload()['link_id'];
|
||||
$this->clean($link);
|
||||
$this->save($this->answers([$link]))->assertOk();
|
||||
$this->post('/balcao-virtual/dossiers/'.$this->caseId.'/documentos', ['version' => 2, 'request_id' => $this->id, 'field_key' => 'support', 'file' => UploadedFile::fake()->createWithContent('new.txt', 'SYNTHETIC new'), 'source_reference' => 'SYNTHETIC', 'consent' => true], ['Accept' => 'application/json'])->assertConflict();
|
||||
app(VirtualDesk::class)->transition($this->manager, $this->id, ['version' => 2, 'status' => 'returned', 'reason' => 'SYNTHETIC support only', 'editable_fields' => ['support']]);
|
||||
$this->post('/balcao-virtual/dossiers/'.$this->caseId.'/documentos', ['version' => 2, 'request_id' => $this->id, 'field_key' => 'optional_support', 'file' => UploadedFile::fake()->createWithContent('new.txt', 'SYNTHETIC new'), 'source_reference' => 'SYNTHETIC', 'consent' => true], ['Accept' => 'application/json'])->assertUnprocessable()->assertJsonValidationErrors('field_key');
|
||||
$new = $this->upload('SYNTHETIC replacement')['link_id'];
|
||||
$this->clean($new);
|
||||
$this->putJson('/balcao-virtual/pedidos/'.$this->id, ['version' => 3, 'payload' => $this->answers([$new]), 'submit' => true, 'consent' => true, 'reason' => 'SYNTHETIC corrected support'])->assertOk();
|
||||
$this->assertDatabaseCount('documents', 2);
|
||||
$this->assertDatabaseCount('desk_documents', 2);
|
||||
}
|
||||
|
||||
public function test_definition_rejects_missing_or_inappropriate_file_limits_and_rollback_preserves_scoped_uses(): void
|
||||
{
|
||||
$input = $this->publication(1);
|
||||
foreach ([['max_size_kb' => 0], ['max_size_kb' => 10241], ['max_files' => 0], ['mime_types' => []], ['mime_types' => ['text/html']]] as $invalid) {
|
||||
$bad = $input;
|
||||
$bad['definition']['fields']['support'] = [...$bad['definition']['fields']['support'], ...$invalid];
|
||||
$this->actingAs($this->manager)->putJson('/management/balcao/servicos/project-change', $bad)->assertUnprocessable();
|
||||
}
|
||||
$bad = $input;
|
||||
unset($bad['definition']['fields']['support']['max_files']);
|
||||
$this->putJson('/management/balcao/servicos/project-change', $bad)->assertUnprocessable();
|
||||
$bad = $input;
|
||||
$bad['definition']['fields']['title']['max_files'] = 1;
|
||||
$this->putJson('/management/balcao/servicos/project-change', $bad)->assertUnprocessable();
|
||||
$this->actingAs($this->owner);
|
||||
$this->upload();
|
||||
$other = $this->newRequest();
|
||||
$this->upload('SYNTHETIC original bytes', $other);
|
||||
$migration = require database_path('migrations/2026_11_03_050000_scope_desk_document_links.php');
|
||||
try {
|
||||
$migration->down();
|
||||
$this->fail('Scoped links must not be destroyed.');
|
||||
} catch (\RuntimeException $error) {
|
||||
$this->assertStringContainsString('Preserve', $error->getMessage());
|
||||
}
|
||||
$this->assertDatabaseCount('desk_documents', 2);
|
||||
}
|
||||
|
||||
public function test_organisation_representative_can_reuse_an_already_authorised_case_document_without_being_its_uploader(): void
|
||||
{
|
||||
$org = (string) Str::uuid();
|
||||
$officer = User::factory()->create();
|
||||
DB::table('organizations')->insert(['id' => $org, 'name' => 'SYNTHETIC document org', 'organization_type' => 'private']);
|
||||
foreach ([[$this->owner, 'admin'], [$officer, 'officer']] as [$actor,$role]) {
|
||||
DB::table('memberships')->insert(['id' => (string) Str::uuid(), 'organization_id' => $org, 'user_id' => $actor->id, 'role' => $role]);
|
||||
}
|
||||
DB::table('desk_cases')->where('id', $this->caseId)->update(['organization_id' => $org]);
|
||||
$first = $this->upload();
|
||||
$other = $this->newRequest();
|
||||
$this->actingAs($officer)->postJson('/balcao-virtual/dossiers/'.$this->caseId.'/documentos', ['version' => $first['case_version'], 'request_id' => $other, 'field_key' => 'support', 'document_id' => $first['documents'][0]['document_id'], 'consent' => true])->assertOk();
|
||||
$this->assertDatabaseCount('documents', 1);
|
||||
$this->assertDatabaseHas('desk_documents', ['request_id' => $other, 'linked_by' => $officer->id, 'source_reference' => 'SYNTHETIC source only']);
|
||||
DB::table('memberships')->where('organization_id', $org)->where('user_id', $officer->id)->update(['deleted_at' => now()]);
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$this->caseId.'/documentos', ['version' => 3, 'request_id' => $other, 'field_key' => 'support', 'document_id' => $first['documents'][0]['document_id'], 'consent' => true])->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_two_link_aliases_cannot_count_as_two_documents_in_the_same_question(): void
|
||||
{
|
||||
$first = $this->upload();
|
||||
$global = $this->postJson('/balcao-virtual/dossiers/'.$this->caseId.'/documentos', ['version' => $first['case_version'], 'document_id' => $first['documents'][0]['document_id'], 'category' => 'SYNTHETIC dossier use', 'consent' => true])->assertOk()->json();
|
||||
$this->save($this->answers([$first['link_id'], $global['link_id']]), 1, false)->assertUnprocessable()->assertJsonValidationErrors('payload.support');
|
||||
$this->assertDatabaseCount('documents', 1);
|
||||
$this->assertDatabaseCount('desk_documents', 2);
|
||||
}
|
||||
|
||||
public function test_missing_scope_migration_is_a_specific_dependency_without_removing_manual_drafts(): void
|
||||
{
|
||||
DB::statement('ALTER INDEX desk_documents_scope_unique RENAME TO desk_documents_scope_qa_absent');
|
||||
try {
|
||||
$input = $this->publication(1);
|
||||
$input['definition']['title'] = 'SYNTHETIC changed title';
|
||||
$this->actingAs($this->manager)->putJson('/management/balcao/servicos/project-change', $input)->assertUnprocessable();
|
||||
$this->actingAs($this->owner);
|
||||
$this->save(['title' => 'SYNTHETIC still editable'], 1, false)->assertOk();
|
||||
$this->post('/balcao-virtual/dossiers/'.$this->caseId.'/documentos', ['version' => 1, 'request_id' => $this->id, 'field_key' => 'support', 'file' => UploadedFile::fake()->createWithContent('new.txt', 'SYNTHETIC'), 'source_reference' => 'SYNTHETIC', 'consent' => true], ['Accept' => 'application/json'])->assertConflict();
|
||||
} finally {
|
||||
DB::statement('ALTER INDEX desk_documents_scope_qa_absent RENAME TO desk_documents_scope_unique');
|
||||
}
|
||||
$this->assertDatabaseCount('documents', 0);
|
||||
}
|
||||
|
||||
public function test_encrypted_original_can_be_submitted_and_reviewed_with_the_shared_integrity_rules(): void
|
||||
{
|
||||
$link = $this->upload()['link_id'];
|
||||
$document = $this->clean($link);
|
||||
$bytes = Storage::disk('local')->get($document->storage_key);
|
||||
Storage::disk('local')->put($document->storage_key, Crypt::encryptString($bytes));
|
||||
DB::table('documents')->where('id', $document->id)->update(['storage_encryption' => 'laravel']);
|
||||
$this->save($this->answers([$link]))->assertOk();
|
||||
$this->actingAs($this->manager)->postJson('/balcao-virtual/dossiers/'.$this->caseId.'/documentos/'.$link.'/conferencia', ['version' => 2, 'request_id' => $this->id, 'outcome' => 'internal_verified', 'what_checked' => 'SYNTHETIC original bytes and scope', 'evidence' => 'SYNTHETIC review only', 'supports' => []])->assertOk();
|
||||
$this->assertSame(1, DB::table('desk_events')->where('action', 'document_reviewed')->count());
|
||||
Storage::disk('local')->put($document->storage_key, 'SYNTHETIC corrupt ciphertext');
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$this->caseId.'/documentos/'.$link.'/conferencia', ['version' => 3, 'request_id' => $this->id, 'outcome' => 'internal_verified', 'what_checked' => 'SYNTHETIC repeat', 'evidence' => 'SYNTHETIC repeat', 'supports' => []])->assertUnprocessable();
|
||||
$this->assertSame(1, DB::table('desk_events')->where('action', 'document_reviewed')->count());
|
||||
}
|
||||
|
||||
public function test_attachment_questions_with_financial_identifiers_do_not_become_numeric_answers_or_financing_questions(): void
|
||||
{
|
||||
$fields = [];
|
||||
$payload = [];
|
||||
foreach (['investment_amount', 'own_finance', 'other_finance'] as $key) {
|
||||
$fields[$key] = ['label' => 'SYNTHETIC evidence', 'type' => 'attachment', 'required' => false, 'mime_types' => ['text/plain'], 'max_files' => 1, 'max_size_kb' => 2];
|
||||
$payload[$key] = [(string) Str::uuid()];
|
||||
}
|
||||
$findings = app(VirtualDesk::class)->findings($payload, ['fields' => $fields]);
|
||||
$this->assertNotContains('finance_unknown', array_column($findings, 'code'));
|
||||
$this->assertNotContains('finance_difference', array_column($findings, 'code'));
|
||||
}
|
||||
|
||||
public function test_unknown_legacy_file_metadata_is_measured_without_reupload_or_rewriting_the_original_record(): void
|
||||
{
|
||||
$link = $this->upload()['link_id'];
|
||||
$document = $this->clean($link);
|
||||
DB::table('documents')->where('id', $document->id)->update(['media_type' => '', 'size_bytes' => null]);
|
||||
$this->save($this->answers([$link]))->assertOk();
|
||||
$snapshot = app(VirtualDesk::class)->decode(DB::table('desk_requests')->where('id', $this->id)->value('submitted_snapshot'));
|
||||
$file = $snapshot['field_attachments']['support']['files'][0];
|
||||
$this->assertSame('text/plain', $file['media_type']);
|
||||
$this->assertSame($document->size_bytes, $file['size_bytes']);
|
||||
$this->assertTrue($file['metadata_measured']);
|
||||
$this->assertSame('', $file['recorded_media_type']);
|
||||
$this->assertNull($file['recorded_size_bytes']);
|
||||
$this->assertDatabaseHas('documents', ['id' => $document->id, 'media_type' => '', 'size_bytes' => null]);
|
||||
$this->assertDatabaseCount('documents', 1);
|
||||
}
|
||||
|
||||
public function test_actual_file_format_cannot_be_replaced_by_a_misleading_registered_mime_type(): void
|
||||
{
|
||||
$link = $this->upload()['link_id'];
|
||||
$document = $this->clean($link);
|
||||
DB::table('documents')->where('id', $document->id)->update(['media_type' => 'application/pdf']);
|
||||
$input = $this->publication(1);
|
||||
$input['definition']['fields']['support']['mime_types'] = ['application/pdf'];
|
||||
$this->edition = $this->actingAs($this->manager)->putJson('/management/balcao/servicos/project-change', $input)->assertCreated()->json('id');
|
||||
$this->actingAs($this->owner);
|
||||
$this->id = $this->newRequest();
|
||||
$result = $this->postJson('/balcao-virtual/dossiers/'.$this->caseId.'/documentos', ['version' => 2, 'request_id' => $this->id, 'field_key' => 'support', 'document_id' => $document->id, 'consent' => true])->assertOk();
|
||||
$this->save($this->answers([$result->json('link_id')]))->assertUnprocessable()->assertJsonValidationErrors('payload.support');
|
||||
$this->assertDatabaseHas('desk_requests', ['id' => $this->id, 'version' => 1, 'submitted_snapshot' => null]);
|
||||
}
|
||||
|
||||
public function test_owner_reuse_picker_preserves_the_chosen_source_and_declared_dates_without_exposing_other_request_inventory_to_reviewers(): void
|
||||
{
|
||||
$second = $this->newRequest();
|
||||
$fromB = $this->upload('SYNTHETIC reused original', $second);
|
||||
$third = $this->newRequest();
|
||||
$fromC = $this->upload('SYNTHETIC reused original', $third);
|
||||
DB::table('desk_documents')->where('id', $fromB['link_id'])->update(['source_reference' => 'SYNTHETIC ref B', 'stage' => 'E1', 'valid_until' => '2027-01-02']);
|
||||
DB::table('desk_documents')->where('id', $fromC['link_id'])->update(['source_reference' => 'SYNTHETIC ref C', 'stage' => 'E2', 'valid_until' => '2028-03-04']);
|
||||
$this->getJson('/balcao-virtual/pedidos/'.$this->id)->assertOk()->assertJsonCount(0, 'documents')->assertJsonCount(2, 'reusableDocuments');
|
||||
$version = DB::table('desk_cases')->where('id', $this->caseId)->value('version');
|
||||
$body = ['version' => $version, 'request_id' => $this->id, 'field_key' => 'support', 'document_id' => $fromB['documents'][0]['document_id'], 'reuse_link_id' => $fromB['link_id'], 'consent' => true];
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$this->caseId.'/documentos', [...$body, 'reuse_link_id' => (string) Str::uuid()])->assertForbidden();
|
||||
$result = $this->postJson('/balcao-virtual/dossiers/'.$this->caseId.'/documentos', $body)->assertOk();
|
||||
$link = $result->json('link_id');
|
||||
$this->assertDatabaseHas('desk_documents', ['id' => $link, 'request_id' => $this->id, 'source_reference' => 'SYNTHETIC ref B', 'valid_until' => '2027-01-02', 'stage' => 'E10']);
|
||||
$event = DB::table('desk_events')->where('request_id', $this->id)->where('action', 'document_linked')->orderByDesc('event_order')->first();
|
||||
$trace = app(VirtualDesk::class)->decode($event->payload);
|
||||
$this->assertSame($fromB['link_id'], $trace['source_link_id']);
|
||||
$this->assertSame('E1', $trace['reused_source']['stage']);
|
||||
$this->assertArrayNotHasKey('request_id', $trace['reused_source']);
|
||||
$this->assertDatabaseCount('documents', 1);
|
||||
$this->assertDatabaseCount('desk_documents', 3);
|
||||
$this->assertCount(1, Storage::disk('local')->allFiles());
|
||||
}
|
||||
|
||||
public function test_closed_dossier_keeps_request_readable_without_offering_edits_or_document_reuse(): void
|
||||
{
|
||||
DB::table('desk_cases')->where('id', $this->caseId)->update(['closed_at' => now()]);
|
||||
$this->getJson('/balcao-virtual/pedidos/'.$this->id)->assertOk()->assertJsonPath('request.status', 'draft')->assertJsonPath('fieldsEditable', false)->assertJsonCount(0, 'reusableDocuments');
|
||||
$this->post('/balcao-virtual/dossiers/'.$this->caseId.'/documentos', ['version' => 1, 'request_id' => $this->id, 'field_key' => 'support', 'file' => UploadedFile::fake()->createWithContent('synthetic.txt', 'SYNTHETIC'), 'source_reference' => 'SYNTHETIC', 'consent' => true], ['Accept' => 'application/json'])->assertConflict();
|
||||
$this->assertDatabaseCount('documents', 0);
|
||||
$this->assertSame([], Storage::disk('local')->allFiles());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\CrmTask;
|
||||
use App\Models\User;
|
||||
use App\Services\VirtualDesk;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Testing\TestResponse;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class DeskCaseStateTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $owner;
|
||||
|
||||
private User $manager;
|
||||
|
||||
private string $caseId;
|
||||
|
||||
private string $requestId;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
$this->owner = User::factory()->create();
|
||||
$this->manager = User::factory()->create();
|
||||
config(['portal.managers' => [$this->manager->email], 'investmoz_ai.enabled' => false, 'suitecrm.enabled' => false]);
|
||||
$edition = $this->actingAs($this->manager)->putJson('/management/balcao/servicos/project-change', ['base_version' => 0, 'definition' => config('virtual-desk.services.project-change'), 'confirm' => true, 'reason' => 'SYNTHETIC owner lifecycle QA'])->assertCreated()->json('id');
|
||||
$this->caseId = $this->actingAs($this->owner)->postJson('/balcao-virtual/dossiers', ['title' => 'SYNTHETIC owned dossier', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertCreated()->json('id');
|
||||
$this->requestId = $this->postJson('/balcao-virtual/dossiers/'.$this->caseId.'/pedidos', ['service_version_id' => $edition, 'client_key' => (string) Str::uuid()])->assertCreated()->json('id');
|
||||
}
|
||||
|
||||
private function operation(string $state, int $version): array
|
||||
{
|
||||
return ['state' => $state, 'version' => $version, 'reason' => 'SYNTHETIC owner decision '.$state, 'client_key' => (string) Str::uuid()];
|
||||
}
|
||||
|
||||
private function change(array $input): TestResponse
|
||||
{
|
||||
return $this->putJson('/balcao-virtual/dossiers/'.$this->caseId.'/estado', $input);
|
||||
}
|
||||
|
||||
public function test_owner_closes_and_reopens_without_changing_payload_workflow_or_child_states(): void
|
||||
{
|
||||
$task = CrmTask::create(['desk_case_id' => $this->caseId, 'guidance_key' => 'synthetic_open_task', 'title' => 'SYNTHETIC accepted task', 'status' => 'open', 'accepted_by' => $this->owner->id, 'accepted_at' => now(), 'assignee_user_id' => $this->owner->id, 'external_sync_status' => 'pending_authorization', 'data_classification' => 'confidential']);
|
||||
$payment = (string) Str::uuid();
|
||||
DB::table('desk_payments')->insert(['id' => $payment, 'request_id' => $this->requestId, 'reference' => 'SYNTHETIC-PENDING', 'amount' => '25.50', 'currency' => 'MZN', 'source_reference' => 'SYNTHETIC pending declaration', 'status' => 'pending']);
|
||||
$before = DB::table('desk_cases')->where('id', $this->caseId)->first();
|
||||
$request = (array) DB::table('desk_requests')->where('id', $this->requestId)->first();
|
||||
$this->getJson('/balcao-virtual/dossiers/'.$this->caseId)->assertOk()->assertJsonPath('canChangeState', true)->assertJsonPath('activity.open_requests', 1)->assertJsonPath('activity.open_tasks', 1)->assertJsonPath('activity.pending_payments', 1);
|
||||
$this->change($this->operation('closed', 1))->assertOk()->assertJsonPath('version', 2)->assertJsonPath('replayed', false);
|
||||
$closed = DB::table('desk_cases')->where('id', $this->caseId)->first();
|
||||
$this->assertNotNull($closed->closed_at);
|
||||
$this->assertSame($before->payload, $closed->payload);
|
||||
$this->assertSame($before->workflow, $closed->workflow);
|
||||
$this->getJson('/balcao-virtual/pedidos/'.$this->requestId)->assertOk()->assertJsonPath('operationsEditable', false)->assertJsonPath('request.status', 'draft');
|
||||
$this->change($this->operation('open', 2))->assertOk()->assertJsonPath('version', 3)->assertJsonPath('closed_at', null);
|
||||
$this->assertSame($request, (array) DB::table('desk_requests')->where('id', $this->requestId)->first());
|
||||
$this->assertDatabaseHas('tasks', ['id' => $task->id, 'status' => 'open', 'version_no' => 1]);
|
||||
$this->assertDatabaseHas('desk_payments', ['id' => $payment, 'status' => 'pending', 'amount' => '25.50', 'version' => 1]);
|
||||
$this->getJson('/balcao-virtual/pedidos/'.$this->requestId)->assertOk()->assertJsonPath('fieldsEditable', true);
|
||||
}
|
||||
|
||||
public function test_manager_or_other_organization_writer_is_not_the_registered_owner(): void
|
||||
{
|
||||
$this->actingAs($this->manager)->change($this->operation('closed', 1))->assertForbidden();
|
||||
$org = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $org, 'name' => 'SYNTHETIC owner organization', 'organization_type' => 'private']);
|
||||
DB::table('desk_cases')->where('id', $this->caseId)->update(['organization_id' => $org]);
|
||||
foreach ([$this->owner, $this->manager] as $member) {
|
||||
DB::table('memberships')->insert(['id' => (string) Str::uuid(), 'organization_id' => $org, 'user_id' => $member->id, 'role' => 'admin']);
|
||||
}
|
||||
$this->getJson('/balcao-virtual/dossiers/'.$this->caseId)->assertOk()->assertJsonPath('canWrite', true)->assertJsonPath('canChangeState', false);
|
||||
$this->change($this->operation('closed', 1))->assertForbidden();
|
||||
$this->actingAs($this->owner)->change($this->operation('closed', 1))->assertOk();
|
||||
DB::table('memberships')->where('organization_id', $org)->where('user_id', $this->owner->id)->update(['deleted_at' => now()]);
|
||||
$this->change($this->operation('open', 2))->assertForbidden();
|
||||
$this->assertDatabaseHas('desk_cases', ['id' => $this->caseId, 'version' => 2]);
|
||||
}
|
||||
|
||||
public function test_exact_retry_is_idempotent_and_old_close_retry_does_not_reverse_a_later_reopening(): void
|
||||
{
|
||||
$close = $this->operation('closed', 1);
|
||||
$this->change($close)->assertOk();
|
||||
$this->change([...$close, 'version' => '1'])->assertOk()->assertJsonPath('version', 2)->assertJsonPath('replayed', true);
|
||||
$this->change([...$close, 'reason' => 'SYNTHETIC changed operation'])->assertConflict();
|
||||
$this->change($this->operation('open', 2))->assertOk();
|
||||
$this->change($close)->assertOk()->assertJsonPath('version', 3)->assertJsonPath('closed_at', null)->assertJsonPath('replayed', true);
|
||||
$this->assertSame(2, DB::table('desk_events')->where('action', 'case_state_changed')->count());
|
||||
}
|
||||
|
||||
public function test_stale_version_missing_reason_or_same_state_cannot_change_the_dossier(): void
|
||||
{
|
||||
$this->change($this->operation('open', 1))->assertConflict();
|
||||
$this->change([...$this->operation('closed', 1), 'reason' => ''])->assertUnprocessable()->assertJsonValidationErrors('reason');
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$this->caseId.'/etapas', ['version' => 1, 'stage' => 'E0', 'status' => 'preparing', 'reason' => 'SYNTHETIC intervening change'])->assertOk();
|
||||
$this->change($this->operation('closed', 1))->assertConflict();
|
||||
$this->assertDatabaseHas('desk_cases', ['id' => $this->caseId, 'closed_at' => null, 'version' => 2]);
|
||||
}
|
||||
|
||||
public function test_reopening_does_not_reopen_a_cancelled_request_and_records_owner_reason_and_summary(): void
|
||||
{
|
||||
$this->postJson('/balcao-virtual/pedidos/'.$this->requestId.'/estado', ['version' => 1, 'status' => 'cancelled', 'reason' => 'SYNTHETIC request cancellation'])->assertOk();
|
||||
$this->change($this->operation('closed', 1))->assertOk();
|
||||
$this->change($this->operation('open', 2))->assertOk();
|
||||
$this->getJson('/balcao-virtual/pedidos/'.$this->requestId)->assertOk()->assertJsonPath('request.status', 'cancelled')->assertJsonPath('operationsEditable', false);
|
||||
$event = DB::table('desk_events')->where('case_id', $this->caseId)->where('action', 'case_state_changed')->orderBy('event_order')->first();
|
||||
$data = app(VirtualDesk::class)->decode($event->payload);
|
||||
$this->assertSame($this->owner->id, (int) $event->actor_id);
|
||||
$this->assertSame('SYNTHETIC owner decision closed', $data['reason']);
|
||||
$this->assertSame(0, $data['activity']['open_requests']);
|
||||
$this->assertNull($data['before']['closed_at']);
|
||||
$this->assertNotNull($data['after']['closed_at']);
|
||||
}
|
||||
|
||||
public function test_unknown_optional_task_count_is_not_reported_as_zero(): void
|
||||
{
|
||||
DB::statement('ALTER TABLE tasks RENAME TO tasks_qa_unavailable');
|
||||
try {
|
||||
$activity = app(VirtualDesk::class)->caseActivity(DB::table('desk_cases')->where('id', $this->caseId)->first());
|
||||
$this->assertNull($activity['open_tasks']);
|
||||
$this->assertSame(1, $activity['open_requests']);
|
||||
} finally {
|
||||
DB::statement('ALTER TABLE tasks_qa_unavailable RENAME TO tasks');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\CrmTask;
|
||||
use App\Models\Lead;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\Support\AuthenticatesQaActors;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class DeskClosedLifecycleTest extends TestCase
|
||||
{
|
||||
use AuthenticatesQaActors;
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $owner;
|
||||
|
||||
private User $manager;
|
||||
|
||||
private string $caseId;
|
||||
|
||||
private string $requestId;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
Http::fake();
|
||||
$this->owner = User::factory()->create();
|
||||
$this->manager = User::factory()->create();
|
||||
config(['portal.managers' => [$this->manager->email], 'investmoz_ai.enabled' => false, 'suitecrm.enabled' => false]);
|
||||
$edition = $this->actingAs($this->manager)->putJson('/management/balcao/servicos/project-change', ['base_version' => 0, 'definition' => config('virtual-desk.services.project-change'), 'reason' => 'SYNTHETIC lifecycle QA', 'confirm' => true])->assertCreated()->json('id');
|
||||
$this->caseId = $this->actingAs($this->owner)->postJson('/balcao-virtual/dossiers', ['title' => 'SYNTHETIC closed dossier', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertCreated()->json('id');
|
||||
$this->requestId = $this->postJson('/balcao-virtual/dossiers/'.$this->caseId.'/pedidos', ['service_version_id' => $edition, 'client_key' => (string) Str::uuid()])->assertCreated()->json('id');
|
||||
}
|
||||
|
||||
private function submit(): void
|
||||
{
|
||||
$this->putJson('/balcao-virtual/pedidos/'.$this->requestId, ['version' => 1, 'payload' => ['title' => 'SYNTHETIC project', 'description' => 'SYNTHETIC private preparation', 'original_reference' => 'SYNTHETIC-REF', 'change_reason' => 'SYNTHETIC change'], 'submit' => true, 'consent' => true])->assertOk();
|
||||
}
|
||||
|
||||
private function closeFixture(): array
|
||||
{
|
||||
DB::table('desk_cases')->where('id', $this->caseId)->update(['closed_at' => now()]);
|
||||
|
||||
return ['request' => (array) DB::table('desk_requests')->where('id', $this->requestId)->first(), 'case' => (array) DB::table('desk_cases')->where('id', $this->caseId)->first(), 'events' => DB::table('desk_events')->count(), 'notifications' => DB::table('desk_notifications')->count(), 'messages' => DB::table('desk_messages')->count()];
|
||||
}
|
||||
|
||||
private function assertUnchanged(array $before): void
|
||||
{
|
||||
$this->assertSame($before['request'], (array) DB::table('desk_requests')->where('id', $this->requestId)->first());
|
||||
$this->assertSame($before['case'], (array) DB::table('desk_cases')->where('id', $this->caseId)->first());
|
||||
foreach (['events' => 'desk_events', 'notifications' => 'desk_notifications', 'messages' => 'desk_messages'] as $key => $table) {
|
||||
$this->assertSame($before[$key], DB::table($table)->count());
|
||||
}
|
||||
}
|
||||
|
||||
public function test_closed_dossier_rejects_request_transition_without_changing_its_history(): void
|
||||
{
|
||||
$this->submit();
|
||||
$before = $this->closeFixture();
|
||||
$this->actingAs($this->manager)->postJson('/balcao-virtual/pedidos/'.$this->requestId.'/estado', ['version' => 2, 'status' => 'reviewing', 'reason' => 'SYNTHETIC review attempt'])->assertConflict();
|
||||
$this->assertUnchanged($before);
|
||||
$this->getJson('/balcao-virtual/pedidos/'.$this->requestId)->assertOk()->assertJsonPath('operationsEditable', false)->assertJsonCount(0, 'transitions');
|
||||
}
|
||||
|
||||
public function test_closed_dossier_rejects_stage_changes_but_keeps_workflow_readable(): void
|
||||
{
|
||||
$before = $this->closeFixture();
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$this->caseId.'/etapas', ['version' => 1, 'stage' => 'E0', 'status' => 'preparing', 'reason' => 'SYNTHETIC preparation attempt'])->assertConflict();
|
||||
$this->assertUnchanged($before);
|
||||
$this->getJson('/balcao-virtual/dossiers/'.$this->caseId)->assertOk()->assertJsonPath('canWrite', false)->assertJsonStructure(['case' => ['workflow', 'closed_at']]);
|
||||
}
|
||||
|
||||
public function test_closed_dossier_is_excluded_from_triage_and_rejects_assignment(): void
|
||||
{
|
||||
$this->submit();
|
||||
$before = $this->closeFixture();
|
||||
$this->actingAsWithMfa($this->manager)->postJson('/balcao-virtual/pedidos/'.$this->requestId.'/responsavel', ['version' => 2, 'analyst_id' => $this->manager->id, 'reason' => 'SYNTHETIC assignment attempt'])->assertConflict();
|
||||
$this->assertUnchanged($before);
|
||||
$this->getJson('/management/balcao/atribuicoes')->assertOk()->assertJsonCount(0, 'requests');
|
||||
}
|
||||
|
||||
public function test_closed_dossier_refuses_messages_even_if_its_request_is_still_open(): void
|
||||
{
|
||||
$this->submit();
|
||||
$before = $this->closeFixture();
|
||||
foreach ([$this->owner, $this->manager] as $actor) {
|
||||
$this->actingAs($actor)->postJson('/balcao-virtual/pedidos/'.$this->requestId.'/mensagens', ['body' => 'SYNTHETIC message attempt', 'client_key' => (string) Str::uuid()])->assertConflict();
|
||||
}
|
||||
$this->assertUnchanged($before);
|
||||
}
|
||||
|
||||
public function test_closed_dossier_refuses_task_updates_and_guidance_remains_readable_without_write_actions(): void
|
||||
{
|
||||
$view = $this->getJson('/balcao-virtual/dossiers/'.$this->caseId.'/orientacao')->assertOk()->json();
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$this->caseId.'/recomendacoes', ['code' => 'support_preparation', 'context_hash' => $view['fingerprint'], 'decision' => 'accepted', 'reason' => 'SYNTHETIC preparation intent'])->assertOk();
|
||||
$task = $this->postJson('/balcao-virtual/dossiers/'.$this->caseId.'/tarefas', ['code' => 'support_preparation', 'context_hash' => $view['fingerprint'], 'consent' => true, 'due_at' => now()->addDays(2)->toIso8601String()])->assertCreated()->json('id');
|
||||
$before = $this->closeFixture();
|
||||
foreach ([$this->owner, $this->manager] as $actor) {
|
||||
$this->actingAs($actor)->postJson('/balcao-virtual/dossiers/'.$this->caseId.'/tarefas/'.$task, ['version' => 1, 'status' => 'done', 'reason' => 'SYNTHETIC task update attempt'])->assertConflict();
|
||||
}
|
||||
$this->assertDatabaseHas('tasks', ['id' => $task, 'status' => 'open', 'version_no' => 1]);
|
||||
$this->assertUnchanged($before);
|
||||
$this->getJson('/balcao-virtual/dossiers/'.$this->caseId.'/orientacao')->assertOk()->assertJsonPath('can_write', false)->assertJsonPath('can_update_tasks', false)->assertJsonCount(1, 'tasks');
|
||||
}
|
||||
|
||||
public function test_open_dossier_keeps_existing_transition_assignment_message_and_task_permissions(): void
|
||||
{
|
||||
$this->submit();
|
||||
$this->postJson('/balcao-virtual/pedidos/'.$this->requestId.'/estado', ['version' => 2, 'status' => 'reviewing', 'reason' => 'SYNTHETIC self-review'])->assertForbidden();
|
||||
$this->actingAsWithMfa($this->manager)->postJson('/balcao-virtual/pedidos/'.$this->requestId.'/responsavel', ['version' => 2, 'analyst_id' => $this->manager->id, 'reason' => 'SYNTHETIC permitted assignment'])->assertOk();
|
||||
$this->postJson('/balcao-virtual/pedidos/'.$this->requestId.'/estado', ['version' => 3, 'status' => 'reviewing', 'reason' => 'SYNTHETIC permitted review'])->assertOk();
|
||||
$this->actingAs($this->owner)->postJson('/balcao-virtual/pedidos/'.$this->requestId.'/mensagens', ['body' => 'SYNTHETIC permitted message', 'client_key' => (string) Str::uuid()])->assertOk();
|
||||
$this->getJson('/balcao-virtual/dossiers/'.$this->caseId.'/orientacao')->assertOk()->assertJsonPath('can_write', true)->assertJsonPath('can_update_tasks', true);
|
||||
$this->actingAs(User::factory()->create())->getJson('/balcao-virtual/pedidos/'.$this->requestId)->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_draft_cancellation_preserves_payload_documents_and_case_and_cannot_cancel_a_submitted_request(): void
|
||||
{
|
||||
$before = DB::table('desk_requests')->where('id', $this->requestId)->first();
|
||||
$this->postJson('/balcao-virtual/pedidos/'.$this->requestId.'/estado', ['version' => 1, 'status' => 'cancelled', 'reason' => 'SYNTHETIC deliberate cancellation'])->assertOk()->assertJsonPath('status', 'cancelled');
|
||||
$after = DB::table('desk_requests')->where('id', $this->requestId)->first();
|
||||
$this->assertSame($before->payload, $after->payload);
|
||||
$this->assertSame($before->submitted_snapshot, $after->submitted_snapshot);
|
||||
$this->assertDatabaseHas('desk_cases', ['id' => $this->caseId, 'closed_at' => null]);
|
||||
$this->assertNotNull($after->closed_at);
|
||||
$this->getJson('/balcao-virtual/pedidos/'.$this->requestId)->assertOk()->assertJsonPath('operationsEditable', false);
|
||||
$edition = DB::table('desk_requests')->where('id', $this->requestId)->value('service_version_id');
|
||||
$this->requestId = $this->postJson('/balcao-virtual/dossiers/'.$this->caseId.'/pedidos', ['service_version_id' => $edition, 'client_key' => (string) Str::uuid()])->assertCreated()->json('id');
|
||||
$this->submit();
|
||||
$this->postJson('/balcao-virtual/pedidos/'.$this->requestId.'/estado', ['version' => 2, 'status' => 'cancelled', 'reason' => 'SYNTHETIC submitted cancellation attempt'])->assertForbidden();
|
||||
$this->assertDatabaseHas('desk_requests', ['id' => $this->requestId, 'status' => 'submitted', 'version' => 2]);
|
||||
}
|
||||
|
||||
public function test_dual_linked_crm_task_observes_dossier_closure_without_changing_crm_authority(): void
|
||||
{
|
||||
$lead = Lead::create(['title' => 'SYNTHETIC dual-linked lead', 'status' => 'disqualified', 'owner_user_id' => $this->manager->id]);
|
||||
$task = CrmTask::create(['lead_id' => $lead->id, 'desk_case_id' => $this->caseId, 'guidance_key' => 'synthetic_dual_link', 'title' => 'SYNTHETIC existing linked task', 'status' => 'open', 'assignee_user_id' => $this->manager->id, 'accepted_by' => $this->owner->id, 'accepted_at' => now(), 'external_sync_status' => 'pending_authorization', 'data_classification' => 'confidential']);
|
||||
$url = '/management/crm/leads/'.$lead->id.'/tasks/'.$task->id;
|
||||
$this->actingAsWithMfa($this->manager)->patch($url, ['version' => $task->fresh()->getAttribute('version_no'), 'status' => 'in_progress'])->assertRedirect();
|
||||
$this->assertDatabaseHas('tasks', ['id' => $task->id, 'status' => 'in_progress']);
|
||||
$this->closeFixture();
|
||||
$this->patchJson($url, ['version' => $task->fresh()->getAttribute('version_no'), 'status' => 'done'])->assertConflict();
|
||||
$this->assertDatabaseHas('tasks', ['id' => $task->id, 'status' => 'in_progress']);
|
||||
$this->get('/management/crm/leads/'.$lead->id)->assertOk()->assertInertia(fn ($page) => $page->where('lead.tasks.0.can_update', false));
|
||||
}
|
||||
|
||||
public function test_crm_without_linked_tasks_does_not_require_an_installed_desk(): void
|
||||
{
|
||||
$lead = Lead::create(['title' => 'SYNTHETIC standalone CRM', 'status' => 'disqualified', 'owner_user_id' => $this->manager->id]);
|
||||
$this->actingAsWithMfa($this->manager);
|
||||
DB::statement('ALTER TABLE desk_cases RENAME TO desk_cases_qa_unavailable');
|
||||
try {
|
||||
$this->get('/management/crm/leads/'.$lead->id)->assertOk()->assertInertia(fn ($page) => $page->where('lead.title', 'SYNTHETIC standalone CRM'));
|
||||
} finally {
|
||||
DB::statement('ALTER TABLE desk_cases_qa_unavailable RENAME TO desk_cases');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Queue;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Testing\TestResponse;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class DeskDocumentReuseTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $owner;
|
||||
|
||||
private string $caseId;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
Storage::fake('local');
|
||||
Queue::fake();
|
||||
$this->owner = User::factory()->create();
|
||||
$this->actingAs($this->owner);
|
||||
$this->caseId = $this->makeCase('SYNTHETIC destination');
|
||||
}
|
||||
|
||||
private function makeCase(string $title): string
|
||||
{
|
||||
return $this->postJson('/balcao-virtual/dossiers', ['title' => $title, 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertCreated()->json('id');
|
||||
}
|
||||
|
||||
private function upload(string $case, string $name = 'synthetic-source.txt'): array
|
||||
{
|
||||
return $this->post('/balcao-virtual/dossiers/'.$case.'/documentos', ['version' => DB::table('desk_cases')->where('id', $case)->value('version'), 'file' => UploadedFile::fake()->createWithContent($name, 'SYNTHETIC '.$name), 'category' => 'project_evidence', 'source_reference' => 'SYNTHETIC source '.$name, 'consent' => true], ['Accept' => 'application/json'])->assertOk()->json();
|
||||
}
|
||||
|
||||
private function catalogue(string $query = ''): TestResponse
|
||||
{
|
||||
return $this->getJson('/balcao-virtual/dossiers/'.$this->caseId.'/documentos-disponiveis'.$query);
|
||||
}
|
||||
|
||||
public function test_personal_source_is_searchable_and_reused_without_reentering_reference_dates_or_copying_original(): void
|
||||
{
|
||||
$source = $this->makeCase('SYNTHETIC previous dossier');
|
||||
$upload = $this->upload($source);
|
||||
DB::table('desk_documents')->where('id', $upload['link_id'])->update(['stage' => 'E2', 'valid_until' => '2028-02-03']);
|
||||
$this->catalogue('?q=previous')->assertOk()->assertJsonCount(1, 'documents')->assertJsonPath('documents.0.id', $upload['link_id'])->assertJsonPath('documents.0.valid_until', '2028-02-03')->assertHeader('Cache-Control', 'no-store, private');
|
||||
$document = $upload['documents'][0]['document_id'];
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$this->caseId.'/documentos', ['version' => 1, 'document_id' => $document, 'reuse_link_id' => $upload['link_id'], 'category' => 'resource_evidence', 'consent' => true])->assertOk();
|
||||
$this->assertDatabaseCount('documents', 1);
|
||||
$this->assertDatabaseCount('desk_documents', 2);
|
||||
$this->assertCount(1, Storage::disk('local')->allFiles());
|
||||
$this->assertDatabaseHas('desk_documents', ['case_id' => $this->caseId, 'document_id' => $document, 'source_reference' => 'SYNTHETIC source synthetic-source.txt', 'stage' => 'E2', 'valid_until' => '2028-02-03']);
|
||||
$this->assertDatabaseHas('desk_cases', ['id' => $source, 'version' => 2]);
|
||||
}
|
||||
|
||||
public function test_catalogue_matches_existing_authority_and_hides_another_dossiers_private_source_from_its_uploader(): void
|
||||
{
|
||||
$source = $this->makeCase('SYNTHETIC secret organization context');
|
||||
$upload = $this->upload($source);
|
||||
$org = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $org, 'name' => 'SYNTHETIC organization', 'organization_type' => 'private']);
|
||||
DB::table('desk_cases')->where('id', $source)->update(['organization_id' => $org]);
|
||||
$this->catalogue()->assertOk()->assertJsonCount(1, 'documents')->assertJsonPath('documents.0.id', null)->assertJsonPath('documents.0.source_reference', null)->assertJsonPath('documents.0.origin_label', null);
|
||||
$this->catalogue('?q=secret')->assertOk()->assertJsonCount(0, 'documents');
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$this->caseId.'/documentos', ['version' => 1, 'document_id' => $upload['documents'][0]['document_id'], 'reuse_link_id' => $upload['link_id'], 'category' => 'project_evidence', 'consent' => true])->assertForbidden();
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$this->caseId.'/documentos', ['version' => 1, 'document_id' => $upload['documents'][0]['document_id'], 'category' => 'project_evidence', 'consent' => true])->assertUnprocessable()->assertJsonValidationErrors('source_reference');
|
||||
$other = User::factory()->create();
|
||||
config(['portal.managers' => [$other->email]]);
|
||||
$this->actingAs($other);
|
||||
$this->catalogue()->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_current_organization_files_are_reusable_but_revoked_members_cannot_keep_using_the_catalogue(): void
|
||||
{
|
||||
$upload = $this->upload($this->caseId);
|
||||
$org = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $org, 'name' => 'SYNTHETIC collaboration', 'organization_type' => 'private']);
|
||||
DB::table('desk_cases')->where('id', $this->caseId)->update(['organization_id' => $org]);
|
||||
$colleague = User::factory()->create();
|
||||
$membership = (string) Str::uuid();
|
||||
DB::table('memberships')->insert(['id' => $membership, 'organization_id' => $org, 'user_id' => $colleague->id, 'role' => 'officer']);
|
||||
$this->actingAs($colleague);
|
||||
$this->catalogue()->assertOk()->assertJsonPath('documents.0.id', $upload['link_id']);
|
||||
DB::table('memberships')->where('id', $membership)->update(['role' => 'viewer']);
|
||||
$this->catalogue()->assertForbidden();
|
||||
DB::table('memberships')->where('id', $membership)->update(['role' => 'officer', 'deleted_at' => now()]);
|
||||
$this->catalogue()->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_unlinked_uploads_are_available_without_invented_provenance_and_foreign_or_deleted_uploads_are_absent(): void
|
||||
{
|
||||
$upload = $this->upload($this->caseId);
|
||||
DB::table('desk_documents')->where('id', $upload['link_id'])->delete();
|
||||
$this->catalogue()->assertOk()->assertJsonCount(1, 'documents')->assertJsonPath('documents.0.id', null)->assertJsonPath('documents.0.source_reference', null);
|
||||
$document = $upload['documents'][0]['document_id'];
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$this->caseId.'/documentos', ['version' => 2, 'document_id' => $document, 'category' => 'project_evidence', 'source_reference' => 'SYNTHETIC supplied missing reference', 'consent' => true])->assertOk();
|
||||
DB::table('documents')->where('id', $document)->update(['deleted_at' => now()]);
|
||||
$this->catalogue()->assertOk()->assertJsonCount(0, 'documents');
|
||||
$this->actingAs(User::factory()->create());
|
||||
$foreign = $this->makeCase('SYNTHETIC foreign');
|
||||
$this->upload($foreign, 'private-foreign.txt');
|
||||
$this->actingAs($this->owner);
|
||||
$this->catalogue()->assertOk()->assertJsonCount(0, 'documents');
|
||||
}
|
||||
|
||||
public function test_opportunity_source_authority_is_checked_in_catalogue_and_attachment_even_for_uploader(): void
|
||||
{
|
||||
$upload = $this->upload($this->caseId);
|
||||
$document = $upload['documents'][0]['document_id'];
|
||||
DB::table('documents')->where('id', $document)->update(['source_system' => 'opportunity-resources']);
|
||||
$this->catalogue()->assertOk()->assertJsonCount(0, 'documents');
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$this->caseId.'/documentos', ['version' => 2, 'document_id' => $document, 'category' => 'project_evidence', 'consent' => true])->assertForbidden();
|
||||
$this->assertDatabaseHas('desk_cases', ['id' => $this->caseId, 'version' => 2]);
|
||||
}
|
||||
|
||||
public function test_literal_search_pagination_and_invalid_input_do_not_expand_scope(): void
|
||||
{
|
||||
$upload = $this->upload($this->caseId, 'SYNTHETIC %_ literal.txt');
|
||||
$row = (array) DB::table('documents')->where('id', $upload['documents'][0]['document_id'])->first();
|
||||
for ($i = 0; $i < 27; $i++) {
|
||||
$copy = (string) Str::uuid();
|
||||
$key = 'synthetic-catalogue/'.$copy;
|
||||
Storage::disk('local')->put($key, Storage::disk('local')->get($row['storage_key']));
|
||||
DB::table('documents')->insert([...$row, 'id' => $copy, 'storage_key' => $key, 'file_name' => sprintf('SYNTHETIC paged %02d.txt', $i)]);
|
||||
}
|
||||
$this->catalogue('?q='.urlencode('%_'))->assertOk()->assertJsonCount(1, 'documents')->assertJsonPath('documents.0.file_name', 'SYNTHETIC %_ literal.txt');
|
||||
$first = $this->catalogue('?q=paged')->assertOk()->assertJsonCount(25, 'documents')->assertJsonPath('next_offset', 25)->json('documents');
|
||||
$last = $this->catalogue('?q=paged&offset=25')->assertOk()->assertJsonCount(2, 'documents')->assertJsonPath('next_offset', null)->json('documents');
|
||||
$this->assertCount(27, array_unique(array_column([...$first, ...$last], 'document_id')));
|
||||
$this->catalogue('?offset=-1')->assertUnprocessable();
|
||||
$this->catalogue('?q='.str_repeat('x', 121))->assertUnprocessable();
|
||||
}
|
||||
|
||||
public function test_selected_stage_link_preserves_its_exact_provenance_and_legacy_document_id_still_works(): void
|
||||
{
|
||||
$upload = $this->upload($this->caseId);
|
||||
$other = $this->makeCase('SYNTHETIC other source');
|
||||
$foreign = $this->upload($other, 'foreign-link.txt');
|
||||
$body = ['version' => 2, 'stage' => 'E0', 'status' => 'preparing', 'reason' => 'SYNTHETIC exact support', 'document_link_id' => $upload['link_id']];
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$this->caseId.'/etapas', [...$body, 'document_link_id' => $foreign['link_id']])->assertUnprocessable();
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$this->caseId.'/etapas', $body)->assertOk();
|
||||
$case = DB::table('desk_cases')->where('id', $this->caseId)->first();
|
||||
$snapshot = json_decode($case->workflow, true)['E0'];
|
||||
$this->assertSame($upload['link_id'], $snapshot['document_link_id']);
|
||||
$this->assertSame($upload['documents'][0]['document_id'], $snapshot['document_id']);
|
||||
$this->assertSame('SYNTHETIC source synthetic-source.txt', $snapshot['document_source']['source_reference']);
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$this->caseId.'/etapas', ['version' => 3, 'stage' => 'E0', 'status' => 'preparing', 'reason' => 'SYNTHETIC legacy client', 'document_id' => $upload['documents'][0]['document_id']])->assertOk();
|
||||
}
|
||||
|
||||
public function test_closed_dossiers_remain_readable_without_upload_or_catalogue_and_anonymous_access_is_refused(): void
|
||||
{
|
||||
DB::table('desk_cases')->where('id', $this->caseId)->update(['closed_at' => now()]);
|
||||
$this->getJson('/balcao-virtual/dossiers/'.$this->caseId)->assertOk()->assertJsonPath('canWrite', false);
|
||||
$this->catalogue()->assertConflict();
|
||||
auth()->logout();
|
||||
$this->catalogue()->assertUnauthorized();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\VirtualDesk;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Queue;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Testing\TestResponse;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class DeskPaymentEvidenceTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $owner;
|
||||
|
||||
private User $reviewer;
|
||||
|
||||
private string $caseId;
|
||||
|
||||
private string $requestId;
|
||||
|
||||
private string $edition;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
Queue::fake();
|
||||
Storage::fake('local');
|
||||
$this->owner = User::factory()->create();
|
||||
$this->reviewer = User::factory()->create();
|
||||
config(['portal.managers' => [$this->reviewer->email]]);
|
||||
$this->edition = $this->actingAs($this->reviewer)->putJson('/management/balcao/servicos/project-change', ['base_version' => 0, 'definition' => config('virtual-desk.services.project-change'), 'reason' => 'SYNTHETIC payment evidence QA', 'confirm' => true])->assertCreated()->json('id');
|
||||
$this->caseId = $this->actingAs($this->owner)->postJson('/balcao-virtual/dossiers', ['title' => 'SYNTHETIC payment dossier', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertCreated()->json('id');
|
||||
$this->requestId = $this->newRequest();
|
||||
}
|
||||
|
||||
private function newRequest(): string
|
||||
{
|
||||
return $this->postJson('/balcao-virtual/dossiers/'.$this->caseId.'/pedidos', ['service_version_id' => $this->edition, 'client_key' => (string) Str::uuid()])->assertCreated()->json('id');
|
||||
}
|
||||
|
||||
private function upload(?string $request = null, string $name = 'synthetic-proof.txt'): array
|
||||
{
|
||||
return $this->post('/balcao-virtual/dossiers/'.$this->caseId.'/documentos', ['version' => DB::table('desk_cases')->where('id', $this->caseId)->value('version'), 'request_id' => $request, 'file' => UploadedFile::fake()->createWithContent($name, 'SYNTHETIC '.$name), 'category' => 'proof', 'source_reference' => 'SYNTHETIC documentary origin', 'consent' => true], ['Accept' => 'application/json'])->assertOk()->json();
|
||||
}
|
||||
|
||||
private function declare(array $changes = []): string
|
||||
{
|
||||
$this->postJson('/balcao-virtual/pedidos/'.$this->requestId.'/pagamentos', [...$this->declaration(), ...$changes])->assertOk();
|
||||
|
||||
return DB::table('desk_payments')->where('request_id', $this->requestId)->value('id');
|
||||
}
|
||||
|
||||
private function declaration(): array
|
||||
{
|
||||
return ['reference' => 'SYNTHETIC-REFERENCE-1', 'amount' => '25.50', 'currency' => 'MZN', 'source_reference' => 'SYNTHETIC amount and purpose, not a fee', 'consent' => true];
|
||||
}
|
||||
|
||||
private function operation(string $link, int $version = 1): array
|
||||
{
|
||||
return ['version' => $version, 'document_link_id' => $link, 'reason' => 'SYNTHETIC new documentary evidence', 'consent' => true, 'client_key' => (string) Str::uuid()];
|
||||
}
|
||||
|
||||
private function attach(string $payment, array $data): TestResponse
|
||||
{
|
||||
return $this->putJson('/balcao-virtual/pedidos/'.$this->requestId.'/pagamentos/'.$payment.'/comprovativo', $data);
|
||||
}
|
||||
|
||||
private function clean(string $document): void
|
||||
{
|
||||
$hash = DB::table('documents')->where('id', $document)->value('sha256');
|
||||
DB::table('documents')->where('id', $document)->update(['status' => 'active', 'malware_scan_status' => 'clean', 'malware_scanned_sha256' => trim($hash)]);
|
||||
}
|
||||
|
||||
private function review(string $payment, int $version, string $status = 'internal_verified'): TestResponse
|
||||
{
|
||||
return $this->postJson('/balcao-virtual/pedidos/'.$this->requestId.'/pagamentos/'.$payment.'/conferencia', ['version' => $version, 'status' => $status, 'reason' => 'SYNTHETIC internal review only', 'evidence' => 'SYNTHETIC evidence, not a bank confirmation']);
|
||||
}
|
||||
|
||||
public function test_pending_reference_can_receive_a_proof_without_a_second_declaration_or_changing_financial_facts(): void
|
||||
{
|
||||
$payment = $this->declare();
|
||||
$uploaded = $this->upload();
|
||||
$before = DB::table('desk_requests')->where('id', $this->requestId)->first();
|
||||
$this->attach($payment, [...$this->operation($uploaded['link_id']), 'amount' => '999.00'])->assertOk();
|
||||
$this->assertDatabaseCount('desk_payments', 1);
|
||||
$this->assertDatabaseCount('documents', 1);
|
||||
$this->assertCount(1, Storage::disk('local')->allFiles());
|
||||
$this->assertDatabaseHas('desk_payments', ['id' => $payment, 'reference' => 'SYNTHETIC-REFERENCE-1', 'amount' => '25.50', 'currency' => 'MZN', 'source_reference' => 'SYNTHETIC amount and purpose, not a fee', 'status' => 'pending', 'version' => 2, 'verified_by' => null]);
|
||||
$after = DB::table('desk_requests')->where('id', $this->requestId)->first();
|
||||
$this->assertSame($before->payload, $after->payload);
|
||||
$this->assertSame($before->version, $after->version);
|
||||
$this->getJson('/balcao-virtual/pedidos/'.$this->requestId)->assertOk()->assertJsonPath('payments.0.document_evidence.link_id', $uploaded['link_id'])->assertJsonPath('payments.0.document_evidence.source_reference', 'SYNTHETIC documentary origin');
|
||||
$this->assertSame(1, DB::table('desk_events')->where('action', 'payment_declared')->count());
|
||||
$this->assertSame(1, DB::table('desk_events')->where('action', 'payment_document_linked')->count());
|
||||
}
|
||||
|
||||
public function test_replay_is_idempotent_and_changed_operation_or_stale_version_does_not_overwrite_evidence(): void
|
||||
{
|
||||
$payment = $this->declare();
|
||||
$uploaded = $this->upload();
|
||||
$operation = $this->operation($uploaded['link_id']);
|
||||
$this->attach($payment, $operation)->assertOk();
|
||||
$this->attach($payment, [...$operation, 'version' => '1', 'consent' => '1'])->assertOk();
|
||||
$this->attach($payment, [...$operation, 'reason' => 'SYNTHETIC changed operation'])->assertConflict();
|
||||
$this->attach($payment, $this->operation($uploaded['link_id']))->assertConflict();
|
||||
$this->assertDatabaseHas('desk_payments', ['id' => $payment, 'version' => 2]);
|
||||
$this->assertSame(1, DB::table('desk_events')->where('action', 'payment_document_linked')->count());
|
||||
}
|
||||
|
||||
public function test_selected_alias_is_frozen_and_another_requests_private_link_cannot_support_this_payment(): void
|
||||
{
|
||||
$other = $this->newRequest();
|
||||
$uploaded = $this->upload($other);
|
||||
$this->postJson('/balcao-virtual/pedidos/'.$this->requestId.'/pagamentos', [...$this->declaration(), 'document_link_id' => $uploaded['link_id']])->assertUnprocessable();
|
||||
$document = $uploaded['documents'][0]['document_id'];
|
||||
$global = $this->postJson('/balcao-virtual/dossiers/'.$this->caseId.'/documentos', ['version' => 2, 'document_id' => $document, 'category' => 'proof', 'source_reference' => 'SYNTHETIC selected global source', 'valid_until' => '2028-02-03', 'consent' => true])->assertOk()->json('link_id');
|
||||
$payment = $this->declare(['document_link_id' => $global]);
|
||||
$this->postJson('/balcao-virtual/pedidos/'.$this->requestId.'/pagamentos', [...$this->declaration(), 'document_link_id' => $global])->assertOk();
|
||||
DB::table('desk_documents')->where('id', $global)->update(['source_reference' => 'SYNTHETIC later edit', 'valid_until' => '2029-01-01']);
|
||||
$this->getJson('/balcao-virtual/pedidos/'.$this->requestId)->assertOk()->assertJsonPath('payments.0.document_evidence.link_id', $global)->assertJsonPath('payments.0.document_evidence.source_reference', 'SYNTHETIC selected global source')->assertJsonPath('payments.0.document_evidence.valid_until', '2028-02-03');
|
||||
$this->assertDatabaseHas('desk_payments', ['id' => $payment, 'document_id' => $document, 'version' => 1]);
|
||||
}
|
||||
|
||||
public function test_issue_can_receive_corrected_support_but_a_verified_record_cannot_be_silently_replaced(): void
|
||||
{
|
||||
$uploaded = $this->upload();
|
||||
$this->clean($uploaded['documents'][0]['document_id']);
|
||||
$payment = $this->declare(['document_link_id' => $uploaded['link_id']]);
|
||||
$this->actingAs($this->reviewer);
|
||||
$this->review($payment, 1)->assertOk();
|
||||
$this->actingAs($this->owner);
|
||||
$this->attach($payment, $this->operation($uploaded['link_id'], 2))->assertConflict();
|
||||
$this->actingAs($this->reviewer);
|
||||
$this->review($payment, 2, 'internal_issue')->assertOk();
|
||||
$this->actingAs($this->owner);
|
||||
$new = $this->upload(null, 'synthetic-corrected.txt');
|
||||
$this->attach($payment, $this->operation($new['link_id'], 3))->assertOk();
|
||||
$this->assertDatabaseHas('desk_payments', ['id' => $payment, 'status' => 'pending', 'version' => 4, 'verified_by' => null, 'reason' => null, 'amount' => '25.50']);
|
||||
$this->assertSame(2, DB::table('desk_events')->where('action', 'payment_reviewed')->count());
|
||||
$event = DB::table('desk_events')->where('action', 'payment_document_linked')->first();
|
||||
$history = app(VirtualDesk::class)->decode($event->payload);
|
||||
$this->assertSame($uploaded['link_id'], $history['previous_document_evidence']['link_id']);
|
||||
}
|
||||
|
||||
public function test_pending_scan_and_changed_original_are_not_verified_against_the_old_snapshot(): void
|
||||
{
|
||||
$uploaded = $this->upload();
|
||||
$document = $uploaded['documents'][0]['document_id'];
|
||||
$payment = $this->declare(['document_link_id' => $uploaded['link_id']]);
|
||||
$this->actingAs($this->reviewer);
|
||||
$this->review($payment, 1)->assertUnprocessable();
|
||||
$row = DB::table('documents')->where('id', $document)->first();
|
||||
$bytes = 'SYNTHETIC replaced original';
|
||||
Storage::disk('local')->put($row->storage_key, $bytes);
|
||||
DB::table('documents')->where('id', $document)->update(['sha256' => hash('sha256', $bytes), 'size_bytes' => strlen($bytes), 'version_no' => 2]);
|
||||
$this->clean($document);
|
||||
$this->review($payment, 1)->assertUnprocessable();
|
||||
$this->actingAs($this->owner);
|
||||
$this->attach($payment, $this->operation($uploaded['link_id']))->assertOk();
|
||||
$this->actingAs($this->reviewer);
|
||||
$this->review($payment, 2)->assertOk();
|
||||
}
|
||||
|
||||
public function test_legacy_payment_without_association_metadata_is_readable_and_keeps_its_historical_unknowns(): void
|
||||
{
|
||||
$uploaded = $this->upload();
|
||||
$document = $uploaded['documents'][0]['document_id'];
|
||||
$payment = (string) Str::uuid();
|
||||
DB::table('desk_payments')->insert(['id' => $payment, 'request_id' => $this->requestId, 'reference' => 'SYNTHETIC-REFERENCE-1', 'amount' => '25.50', 'currency' => 'MZN', 'source_reference' => $this->declaration()['source_reference'], 'document_id' => $document, 'status' => 'pending']);
|
||||
$this->getJson('/balcao-virtual/pedidos/'.$this->requestId)->assertOk()->assertJsonPath('payments.0.document_evidence', null);
|
||||
$this->postJson('/balcao-virtual/pedidos/'.$this->requestId.'/pagamentos', [...$this->declaration(), 'document_id' => $document])->assertOk();
|
||||
$this->assertSame(0, DB::table('desk_events')->where('action', 'payment_declared')->count());
|
||||
$this->clean($document);
|
||||
$this->actingAs($this->reviewer);
|
||||
$this->review($payment, 1)->assertOk();
|
||||
}
|
||||
|
||||
public function test_only_the_effective_owner_can_attach_evidence_and_review_remains_independent(): void
|
||||
{
|
||||
$uploaded = $this->upload();
|
||||
$payment = $this->declare();
|
||||
$this->review($payment, 1, 'internal_issue')->assertForbidden();
|
||||
$this->actingAs($this->reviewer);
|
||||
$this->attach($payment, $this->operation($uploaded['link_id']))->assertForbidden();
|
||||
$this->actingAs(User::factory()->create());
|
||||
$this->attach($payment, $this->operation($uploaded['link_id']))->assertForbidden();
|
||||
$this->actingAs($this->owner);
|
||||
$this->attach($payment, $this->operation((string) Str::uuid()))->assertUnprocessable();
|
||||
DB::table('documents')->where('id', $uploaded['documents'][0]['document_id'])->update(['source_system' => 'opportunity-resources']);
|
||||
$this->attach($payment, $this->operation($uploaded['link_id']))->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_closed_dossier_keeps_payment_history_readable_and_rejects_all_manual_writes(): void
|
||||
{
|
||||
$uploaded = $this->upload();
|
||||
$payment = $this->declare();
|
||||
DB::table('desk_cases')->where('id', $this->caseId)->update(['closed_at' => now()]);
|
||||
$this->getJson('/balcao-virtual/pedidos/'.$this->requestId)->assertOk()->assertJsonPath('operationsEditable', false)->assertJsonCount(1, 'payments');
|
||||
$this->attach($payment, $this->operation($uploaded['link_id']))->assertConflict();
|
||||
$this->postJson('/balcao-virtual/pedidos/'.$this->requestId.'/pagamentos', $this->declaration())->assertConflict();
|
||||
$this->actingAs($this->reviewer);
|
||||
$this->review($payment, 1, 'internal_issue')->assertConflict();
|
||||
$this->postJson('/balcao-virtual/pedidos/'.$this->requestId.'/comunicacoes', ['channel' => 'phone', 'direction' => 'received', 'occurred_at' => now()->subMinute()->toIso8601String(), 'summary' => 'SYNTHETIC historical communication', 'evidence' => 'SYNTHETIC reference', 'client_key' => (string) Str::uuid()])->assertConflict();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\VirtualDesk;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class DeskRequestCheckpointTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $owner;
|
||||
|
||||
private User $manager;
|
||||
|
||||
private string $id;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
$this->owner = User::factory()->create();
|
||||
$this->manager = User::factory()->create();
|
||||
config(['portal.managers' => [$this->manager->email]]);
|
||||
$definition = config('virtual-desk.services.project-change');
|
||||
$definition['fields'] = [...$definition['fields'],
|
||||
'email' => ['label' => 'SYNTHETIC email', 'type' => 'email', 'required' => false],
|
||||
'amount' => ['label' => 'SYNTHETIC amount', 'type' => 'number', 'required' => false],
|
||||
'choices' => ['label' => 'SYNTHETIC choices', 'type' => 'multiselect', 'required' => false, 'options' => ['0' => 'Zero', 'cotton' => 'Cotton']],
|
||||
'declaration' => ['label' => 'SYNTHETIC declaration', 'type' => 'consent', 'required' => false, 'statement' => 'SYNTHETIC statement, no actual authorisation.'],
|
||||
];
|
||||
$edition = $this->actingAs($this->manager)->putJson('/management/balcao/servicos/project-change', ['base_version' => 0, 'definition' => $definition, 'confirm' => true, 'reason' => 'SYNTHETIC checkpoint QA, not an actual publication.'])->assertCreated()->json('id');
|
||||
$case = $this->actingAs($this->owner)->postJson('/balcao-virtual/dossiers', ['title' => 'SYNTHETIC checkpoint', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertCreated()->json('id');
|
||||
$this->id = $this->postJson('/balcao-virtual/dossiers/'.$case.'/pedidos', ['service_version_id' => $edition, 'client_key' => (string) Str::uuid()])->assertCreated()->json('id');
|
||||
}
|
||||
|
||||
private function url(): string
|
||||
{
|
||||
return '/balcao-virtual/pedidos/'.$this->id.'/rascunho';
|
||||
}
|
||||
|
||||
private function input(array $payload = [], int $version = 0, int $requestVersion = 1): array
|
||||
{
|
||||
return ['version' => $version, 'request_version' => $requestVersion, 'operation_key' => (string) Str::uuid(), 'payload' => $payload, 'edited_keys' => array_keys($payload), 'reason' => 'SYNTHETIC incomplete correction'];
|
||||
}
|
||||
|
||||
private function answers(): array
|
||||
{
|
||||
return ['title' => 'SYNTHETIC main', 'description' => 'SYNTHETIC complete description', 'original_reference' => 'SYNTHETIC-REF', 'change_reason' => 'SYNTHETIC reason'];
|
||||
}
|
||||
|
||||
public function test_incomplete_formats_are_recoverable_encrypted_and_never_change_the_authoritative_request_or_notifications(): void
|
||||
{
|
||||
$before = DB::table('desk_requests')->where('id', $this->id)->first();
|
||||
$events = DB::table('desk_events')->count();
|
||||
$notifications = DB::table('desk_notifications')->count();
|
||||
$payload = ['email' => 'incomplete@', 'amount' => '-', 'choices' => ['cotton', '0'], 'declaration' => 'declined'];
|
||||
$this->postJson($this->url(), $this->input($payload))->assertOk()->assertJsonPath('checkpoint.version', 1)->assertJsonPath('checkpoint.payload.email', 'incomplete@');
|
||||
$this->getJson($this->url())->assertOk()->assertHeader('Cache-Control', 'no-store, private')->assertJsonPath('checkpoint.payload.amount', '-')->assertJsonPath('checkpoint.payload.choices', ['0', 'cotton'])->assertJsonPath('checkpoint.payload.declaration', 'declined');
|
||||
$row = DB::table('desk_request_checkpoints')->first();
|
||||
$this->assertStringNotContainsString('incomplete@', $row->snapshot);
|
||||
$this->assertSame(app(VirtualDesk::class)->decode($before->payload), app(VirtualDesk::class)->decode($row->snapshot)['base_payload']);
|
||||
$this->assertEquals($before, DB::table('desk_requests')->where('id', $this->id)->first());
|
||||
$this->assertSame($events, DB::table('desk_events')->count());
|
||||
$this->assertSame($notifications, DB::table('desk_notifications')->count());
|
||||
$this->assertDatabaseCount('desk_revisions', 0);
|
||||
$audit = DB::table('audit_events')->where('action', 'draft_checkpoint_saved')->first();
|
||||
$this->assertSame(['version' => 1, 'request_version' => 1], json_decode($audit->after_data, true));
|
||||
$this->putJson('/balcao-virtual/pedidos/'.$this->id, ['version' => 1, 'payload' => [...$this->answers(), ...$payload], 'submit' => true, 'consent' => true])->assertUnprocessable()->assertJsonValidationErrors(['payload.email', 'payload.amount']);
|
||||
}
|
||||
|
||||
public function test_attempt_retry_is_idempotent_but_changed_body_reused_key_and_stale_version_conflict(): void
|
||||
{
|
||||
$input = $this->input(['title' => 'SYNTHETIC one']);
|
||||
$this->postJson($this->url(), $input)->assertOk();
|
||||
$row = DB::table('desk_request_checkpoints')->first();
|
||||
$this->postJson($this->url(), $input)->assertOk()->assertJsonPath('checkpoint.version', 1);
|
||||
$this->assertEquals($row, DB::table('desk_request_checkpoints')->first());
|
||||
$this->postJson($this->url(), [...$input, 'payload' => ['title' => 'SYNTHETIC changed key']])->assertConflict();
|
||||
$this->postJson($this->url(), $this->input(['title' => 'SYNTHETIC other tab']))->assertConflict();
|
||||
$this->postJson($this->url(), $this->input(['title' => 'SYNTHETIC fresh'], 1))->assertOk()->assertJsonPath('checkpoint.version', 2);
|
||||
$this->assertSame(2, DB::table('audit_events')->where('action', 'draft_checkpoint_saved')->count());
|
||||
}
|
||||
|
||||
public function test_stale_main_version_is_exposed_for_comparison_and_cannot_be_silently_overwritten(): void
|
||||
{
|
||||
$this->postJson($this->url(), $this->input(['title' => 'SYNTHETIC pending']))->assertOk();
|
||||
$this->putJson('/balcao-virtual/pedidos/'.$this->id, ['version' => 1, 'payload' => ['title' => 'SYNTHETIC manually changed']])->assertOk();
|
||||
$this->postJson($this->url(), $this->input(['title' => 'SYNTHETIC stale'], 1))->assertConflict();
|
||||
$this->getJson($this->url())->assertOk()->assertJsonPath('request.version', 2)->assertJsonPath('request.payload.title', 'SYNTHETIC manually changed')->assertJsonPath('checkpoint.request_version', 1)->assertJsonPath('checkpoint.payload.title', 'SYNTHETIC pending');
|
||||
$this->postJson($this->url(), $this->input(['title' => 'SYNTHETIC deliberately recovered'], 1, 2))->assertOk()->assertJsonPath('checkpoint.base_payload.title', 'SYNTHETIC manually changed');
|
||||
$this->assertSame('SYNTHETIC manually changed', app(VirtualDesk::class)->decode(DB::table('desk_requests')->where('id', $this->id)->value('payload'))['title']);
|
||||
}
|
||||
|
||||
public function test_checkpoint_route_cannot_submit_accept_arbitrary_keys_or_forged_baseline_and_still_bounds_types(): void
|
||||
{
|
||||
foreach ([['submit' => true], ['consent' => true], ['base_payload' => []], ['field_declarations' => []]] as $extra) {
|
||||
$this->postJson($this->url(), [...$this->input(), ...$extra])->assertUnprocessable();
|
||||
}
|
||||
foreach ([['unknown' => 'SYNTHETIC'], ['choices' => ['absent']], ['choices' => [0]], ['declaration' => true], ['email' => ['nested']], ['amount' => false], ['amount' => str_repeat('1', 1001)]] as $payload) {
|
||||
$this->postJson($this->url(), $this->input($payload))->assertUnprocessable();
|
||||
}
|
||||
$this->postJson($this->url(), [...$this->input(), 'edited_keys' => ['unknown']])->assertUnprocessable();
|
||||
$this->assertDatabaseCount('desk_request_checkpoints', 0);
|
||||
$this->postJson($this->url(), $this->input())->assertOk()->assertJsonPath('checkpoint.payload', []);
|
||||
}
|
||||
|
||||
public function test_server_derives_edit_intent_and_conserves_deliberate_clear_and_zero(): void
|
||||
{
|
||||
$this->postJson($this->url(), [...$this->input(['title' => 'SYNTHETIC changed', 'amount' => 0]), 'edited_keys' => []])->assertOk()->assertJsonPath('checkpoint.edited_keys', ['title', 'description', 'regime', 'amount']);
|
||||
$this->postJson($this->url(), $this->input(['amount' => 0, 'choices' => [], 'declaration' => null], 1))->assertOk()->assertJsonPath('checkpoint.payload.amount', 0)->assertJsonPath('checkpoint.payload.choices', [])->assertJsonPath('checkpoint.payload.declaration', null);
|
||||
}
|
||||
|
||||
public function test_manager_and_unrelated_user_cannot_read_or_write_private_recovery(): void
|
||||
{
|
||||
$this->postJson($this->url(), $this->input(['title' => 'SYNTHETIC private recovery']))->assertOk();
|
||||
foreach ([$this->manager, User::factory()->create()] as $actor) {
|
||||
$this->actingAs($actor)->getJson($this->url())->assertForbidden()->assertDontSee('SYNTHETIC private recovery');
|
||||
$this->postJson($this->url(), $this->input())->assertForbidden();
|
||||
}
|
||||
$this->assertDatabaseCount('desk_request_checkpoints', 1);
|
||||
}
|
||||
|
||||
public function test_submitted_and_closed_requests_reject_checkpoint_writes_and_do_not_create_a_declaration_snapshot_from_recovery(): void
|
||||
{
|
||||
$this->postJson($this->url(), $this->input(['declaration' => 'accepted']))->assertOk();
|
||||
$this->putJson('/balcao-virtual/pedidos/'.$this->id, ['version' => 1, 'payload' => $this->answers(), 'submit' => true, 'consent' => true])->assertOk();
|
||||
$row = DB::table('desk_requests')->where('id', $this->id)->first();
|
||||
$this->postJson($this->url(), $this->input(['declaration' => 'accepted'], 1, 2))->assertConflict();
|
||||
$this->getJson($this->url())->assertOk()->assertJsonPath('request.can_edit', false);
|
||||
$this->assertSame([], app(VirtualDesk::class)->decode($row->submitted_snapshot)['field_declarations']);
|
||||
$this->assertArrayNotHasKey('declaration', app(VirtualDesk::class)->decode($row->submitted_snapshot)['payload']);
|
||||
$this->assertEquals($row, DB::table('desk_requests')->where('id', $this->id)->first());
|
||||
}
|
||||
|
||||
public function test_returned_scope_is_enforced_for_both_values_and_claimed_intent(): void
|
||||
{
|
||||
$this->putJson('/balcao-virtual/pedidos/'.$this->id, ['version' => 1, 'payload' => $this->answers(), 'submit' => true, 'consent' => true])->assertOk();
|
||||
app(VirtualDesk::class)->transition($this->manager, $this->id, ['version' => 2, 'status' => 'returned', 'reason' => 'SYNTHETIC description only', 'editable_fields' => ['description']]);
|
||||
$this->postJson($this->url(), $this->input([...$this->answers(), 'description' => 'SYNTHETIC revised'], 0, 3))->assertUnprocessable();
|
||||
$data = [...$this->input([...$this->answers(), 'description' => 'SYNTHETIC revised'], 0, 3), 'edited_keys' => ['description']];
|
||||
$this->postJson($this->url(), $data)->assertOk()->assertJsonPath('checkpoint.edited_keys', ['description']);
|
||||
$this->postJson($this->url(), [...$data, 'version' => 1, 'operation_key' => (string) Str::uuid(), 'payload' => [...$this->answers(), 'title' => 'SYNTHETIC forbidden']])->assertUnprocessable();
|
||||
}
|
||||
|
||||
public function test_missing_migration_keeps_manual_route_available_and_rollback_refuses_retained_drafts(): void
|
||||
{
|
||||
Schema::rename('desk_request_checkpoints', 'desk_request_checkpoints_qa_absent');
|
||||
try {
|
||||
$this->getJson($this->url())->assertOk()->assertJsonPath('installed', false);
|
||||
$this->postJson($this->url(), $this->input())->assertConflict();
|
||||
$this->putJson('/balcao-virtual/pedidos/'.$this->id, ['version' => 1, 'payload' => []])->assertOk();
|
||||
} finally {
|
||||
Schema::rename('desk_request_checkpoints_qa_absent', 'desk_request_checkpoints');
|
||||
}
|
||||
$this->postJson($this->url(), $this->input(['title' => 'SYNTHETIC preserved'], 0, 2))->assertOk();
|
||||
$migration = require database_path('migrations/2026_11_03_040000_create_desk_request_checkpoints.php');
|
||||
try {
|
||||
$migration->down();
|
||||
$this->fail('Rollback must not remove retained drafts.');
|
||||
} catch (\RuntimeException $error) {
|
||||
$this->assertStringContainsString('Preserve', $error->getMessage());
|
||||
}
|
||||
$this->assertDatabaseCount('desk_request_checkpoints', 1);
|
||||
}
|
||||
|
||||
public function test_organisation_recovery_is_private_per_actor_and_revoked_or_read_only_members_have_no_access(): void
|
||||
{
|
||||
$org = (string) Str::uuid();
|
||||
$officer = User::factory()->create();
|
||||
$reader = User::factory()->create();
|
||||
DB::table('organizations')->insert(['id' => $org, 'name' => 'SYNTHETIC checkpoint org', 'organization_type' => 'private']);
|
||||
foreach ([[$this->owner, 'admin'], [$officer, 'officer'], [$reader, 'viewer']] as [$actor,$role]) {
|
||||
DB::table('memberships')->insert(['id' => (string) Str::uuid(), 'organization_id' => $org, 'user_id' => $actor->id, 'role' => $role]);
|
||||
}
|
||||
$caseId = DB::table('desk_requests')->where('id', $this->id)->value('case_id');
|
||||
DB::table('desk_cases')->where('id', $caseId)->update(['organization_id' => $org]);
|
||||
$this->postJson($this->url(), $this->input(['title' => 'SYNTHETIC owner only']))->assertOk();
|
||||
$this->actingAs($officer)->getJson($this->url())->assertOk()->assertJsonPath('checkpoint', null)->assertDontSee('SYNTHETIC owner only');
|
||||
$this->postJson($this->url(), $this->input(['title' => 'SYNTHETIC officer only']))->assertOk();
|
||||
$this->actingAs($this->owner)->getJson($this->url())->assertOk()->assertJsonPath('checkpoint.payload.title', 'SYNTHETIC owner only');
|
||||
$this->actingAs($reader)->getJson($this->url())->assertForbidden();
|
||||
DB::table('memberships')->where('organization_id', $org)->where('user_id', $officer->id)->update(['deleted_at' => now()]);
|
||||
$this->actingAs($officer)->getJson($this->url())->assertForbidden()->assertDontSee('SYNTHETIC officer only');
|
||||
$this->postJson($this->url(), $this->input([], 1))->assertForbidden();
|
||||
$this->assertDatabaseCount('desk_request_checkpoints', 2);
|
||||
}
|
||||
|
||||
public function test_closed_dossier_does_not_accept_checkpoint_even_when_request_is_still_a_draft(): void
|
||||
{
|
||||
$caseId = DB::table('desk_requests')->where('id', $this->id)->value('case_id');
|
||||
DB::table('desk_cases')->where('id', $caseId)->update(['closed_at' => now()]);
|
||||
$this->getJson($this->url())->assertOk()->assertJsonPath('request.can_edit', false);
|
||||
$this->postJson($this->url(), $this->input(['title' => 'SYNTHETIC forbidden']))->assertConflict();
|
||||
$this->putJson('/balcao-virtual/pedidos/'.$this->id, ['version' => 1, 'payload' => []])->assertConflict();
|
||||
$this->assertSame(1, DB::table('desk_requests')->where('id', $this->id)->value('version'));
|
||||
$this->assertDatabaseCount('desk_request_checkpoints', 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\DeskServiceAvailability;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class DeskServiceEffectiveDatesTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $manager;
|
||||
|
||||
private User $investor;
|
||||
|
||||
private string $url = '/management/balcao/servicos/project-change';
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
$this->travelTo(CarbonImmutable::parse('2026-11-02 10:00:00', 'UTC'));
|
||||
$this->manager = User::factory()->create();
|
||||
$this->investor = User::factory()->create();
|
||||
config(['portal.managers' => [$this->manager->email]]);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$this->travelBack();
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
private function input(int $base, string $title, ?string $date = null): array
|
||||
{
|
||||
$definition = config('virtual-desk.services.project-change');
|
||||
$definition['title'] = $title;
|
||||
|
||||
return ['base_version' => $base, 'definition' => $definition, 'confirm' => true,
|
||||
'reason' => 'SYNTHETIC QA edition date; not an actual service publication.', 'effective_from' => $date];
|
||||
}
|
||||
|
||||
private function publish(int $base, string $title, ?string $date = null): string
|
||||
{
|
||||
return $this->actingAs($this->manager)->putJson($this->url, $this->input($base, $title, $date))->assertCreated()->json('id');
|
||||
}
|
||||
|
||||
private function dossier(): string
|
||||
{
|
||||
return $this->actingAs($this->investor)->postJson('/balcao-virtual/dossiers', ['title' => 'SYNTHETIC dated forms', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertCreated()->json('id');
|
||||
}
|
||||
|
||||
public function test_only_started_edition_is_offered_and_forged_stale_or_future_selection_never_creates_a_request(): void
|
||||
{
|
||||
$v1 = $this->publish(0, 'SYNTHETIC current edition');
|
||||
$case = $this->dossier();
|
||||
$key = (string) Str::uuid();
|
||||
$request = $this->postJson('/balcao-virtual/dossiers/'.$case.'/pedidos', ['service_version_id' => $v1, 'client_key' => $key])->assertCreated()->json('id');
|
||||
$before = DB::table('desk_requests')->where('id', $request)->first();
|
||||
$v2 = $this->publish(1, 'SYNTHETIC future edition', '2026-11-03');
|
||||
$this->actingAs($this->investor)->getJson('/balcao-virtual/servicos')->assertOk()->assertJsonPath('services.0.id', $v1)->assertDontSee('SYNTHETIC future edition');
|
||||
$this->getJson('/balcao-virtual/dossiers/'.$case)->assertOk()->assertJsonPath('services.0.id', $v1);
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$case.'/pedidos', ['service_version_id' => $v2, 'client_key' => (string) Str::uuid()])->assertUnprocessable()->assertJsonValidationErrors('service_version_id');
|
||||
$this->assertDatabaseCount('desk_requests', 1);
|
||||
$this->travelTo(CarbonImmutable::parse('2026-11-03 00:00:00', 'UTC'));
|
||||
$this->getJson('/balcao-virtual/servicos')->assertOk()->assertJsonPath('services.0.id', $v2)->assertJsonPath('services.0.effective_from', '2026-11-03');
|
||||
$this->getJson('/balcao-virtual/dossiers/'.$case)->assertOk()->assertJsonPath('services.0.id', $v2);
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$case.'/pedidos', ['service_version_id' => $v1, 'client_key' => $key])->assertCreated()->assertJsonPath('id', $request);
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$case.'/pedidos', ['service_version_id' => $v1, 'client_key' => (string) Str::uuid()])->assertUnprocessable()->assertJsonValidationErrors('service_version_id');
|
||||
$this->getJson('/balcao-virtual/pedidos/'.$request)->assertOk()->assertJsonPath('definition.title', 'SYNTHETIC current edition')->assertJsonPath('serviceEffectiveFrom', '2026-11-02');
|
||||
$this->assertEquals($before, DB::table('desk_requests')->where('id', $request)->first());
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$case.'/pedidos', ['service_version_id' => $v2, 'client_key' => (string) Str::uuid()])->assertCreated();
|
||||
}
|
||||
|
||||
public function test_immediate_correction_does_not_cancel_later_schedule_and_same_date_uses_highest_version(): void
|
||||
{
|
||||
$this->publish(0, 'SYNTHETIC initial');
|
||||
$v2 = $this->publish(1, 'SYNTHETIC scheduled', '2026-11-12');
|
||||
$v3 = $this->publish(2, 'SYNTHETIC correction', '2026-11-02');
|
||||
$this->assertSame($v3, app(DeskServiceAvailability::class)->current()->first()->id);
|
||||
$this->getJson('/management/balcao/servicos')->assertOk()->assertJsonPath('services.1.upcoming.0.version', 2);
|
||||
$v4 = $this->publish(3, 'SYNTHETIC scheduled correction', '2026-11-12');
|
||||
$this->getJson('/management/balcao/servicos')->assertOk()->assertJsonPath('services.1.activeVersion', 3)->assertJsonCount(1, 'services.1.upcoming')->assertJsonPath('services.1.upcoming.0.version', 4);
|
||||
$this->travelTo(CarbonImmutable::parse('2026-11-12 00:00:00', 'UTC'));
|
||||
$this->assertSame($v4, app(DeskServiceAvailability::class)->current()->first()->id);
|
||||
$this->assertNotSame($v2, $v4);
|
||||
$this->getJson('/management/balcao/servicos/project-change/versoes')->assertOk()->assertJsonPath('data.0.effective_from', '2026-11-12');
|
||||
$this->assertDatabaseCount('desk_service_versions', 4);
|
||||
}
|
||||
|
||||
public function test_scheduling_without_question_changes_is_a_new_edition_and_retries_keep_original_authorship_after_date_passes(): void
|
||||
{
|
||||
$this->publish(0, 'SYNTHETIC unchanged definition');
|
||||
$v2 = $this->publish(1, 'SYNTHETIC unchanged definition', '2026-11-05');
|
||||
$before = DB::table('desk_service_versions')->where('id', $v2)->first();
|
||||
$this->actingAs($this->manager)->putJson($this->url, $this->input(1, 'SYNTHETIC unchanged definition'))->assertConflict();
|
||||
$this->travelTo(CarbonImmutable::parse('2026-11-06 10:00:00', 'UTC'));
|
||||
$this->actingAs($this->manager)->putJson($this->url, $this->input(1, 'SYNTHETIC unchanged definition', '2026-11-05'))->assertCreated()->assertJsonPath('id', $v2);
|
||||
$this->assertEquals($before, DB::table('desk_service_versions')->where('id', $v2)->first());
|
||||
$this->assertDatabaseCount('desk_service_versions', 2);
|
||||
$this->assertSame(2, DB::table('audit_events')->where('action', 'service_definition_version_published')->count());
|
||||
$this->putJson($this->url, $this->input(2, 'SYNTHETIC new backdated edition', '2026-11-05'))->assertUnprocessable()->assertJsonValidationErrors('effective_from');
|
||||
}
|
||||
|
||||
public function test_invalid_dates_and_unprivileged_publication_are_rejected_without_changing_versions(): void
|
||||
{
|
||||
$this->actingAs($this->investor)->putJson($this->url, $this->input(0, 'SYNTHETIC denied', '2026-11-03'))->assertForbidden();
|
||||
foreach (['2026-11-01', '2026-02-30', 'tomorrow', '2026-11-03T10:00:00Z'] as $date) {
|
||||
$this->actingAs($this->manager)->putJson($this->url, $this->input(0, 'SYNTHETIC invalid', $date))->assertUnprocessable()->assertJsonValidationErrors('effective_from');
|
||||
}
|
||||
$this->assertDatabaseCount('desk_service_versions', 0);
|
||||
}
|
||||
|
||||
public function test_existing_submitted_answers_and_definition_remain_intact_when_new_date_starts(): void
|
||||
{
|
||||
$v1 = $this->publish(0, 'SYNTHETIC submission edition');
|
||||
$case = $this->dossier();
|
||||
$request = $this->postJson('/balcao-virtual/dossiers/'.$case.'/pedidos', ['service_version_id' => $v1, 'client_key' => (string) Str::uuid()])->assertCreated()->json('id');
|
||||
$answers = ['title' => 'SYNTHETIC actual answers', 'description' => 'SYNTHETIC reserved preparation description', 'original_reference' => 'SYNTHETIC-REF', 'change_reason' => 'SYNTHETIC change'];
|
||||
$this->putJson('/balcao-virtual/pedidos/'.$request, ['version' => 1, 'payload' => $answers, 'submit' => true, 'consent' => true])->assertOk();
|
||||
$before = DB::table('desk_requests')->where('id', $request)->first();
|
||||
$input = $this->input(1, 'SYNTHETIC new required question', '2026-11-03');
|
||||
$input['definition']['fields']['new_evidence'] = ['label' => 'SYNTHETIC new evidence', 'type' => 'text', 'required' => true];
|
||||
$v2 = $this->actingAs($this->manager)->putJson($this->url, $input)->assertCreated()->json('id');
|
||||
$this->travelTo(CarbonImmutable::parse('2026-11-03 10:00:00', 'UTC'));
|
||||
$this->actingAs($this->investor)->getJson('/balcao-virtual/pedidos/'.$request)->assertOk()->assertJsonMissingPath('definition.fields.new_evidence');
|
||||
$this->assertEquals($before, DB::table('desk_requests')->where('id', $request)->first());
|
||||
$next = $this->postJson('/balcao-virtual/dossiers/'.$case.'/pedidos', ['service_version_id' => $v2, 'client_key' => (string) Str::uuid()])->assertCreated()->json('id');
|
||||
$this->putJson('/balcao-virtual/pedidos/'.$next, ['version' => 1, 'payload' => $answers, 'submit' => true, 'consent' => true])->assertUnprocessable()->assertJsonValidationErrors('payload.new_evidence');
|
||||
$this->getJson('/balcao-virtual/pedidos/'.$request.'/recibo')->assertOk();
|
||||
}
|
||||
|
||||
public function test_legacy_undated_versions_still_work_and_scheduling_requires_migration_without_rewriting_legacy_rows(): void
|
||||
{
|
||||
$migration = require database_path('migrations/2026_11_03_010000_desk_service_effective_dates.php');
|
||||
$migration->down();
|
||||
$this->assertFalse(Schema::hasColumn('desk_service_versions', 'effective_from'));
|
||||
$v1 = $this->publish(0, 'SYNTHETIC legacy edition');
|
||||
$before = DB::table('desk_service_versions')->where('id', $v1)->first();
|
||||
$this->putJson($this->url, $this->input(1, 'SYNTHETIC unsupported scheduling', '2026-11-03'))->assertUnprocessable()->assertJsonValidationErrors('effective_from');
|
||||
$this->assertSame($v1, app(DeskServiceAvailability::class)->current()->first()->id);
|
||||
$migration->up();
|
||||
$this->assertSame($before->definition, DB::table('desk_service_versions')->where('id', $v1)->value('definition'));
|
||||
$this->assertNull(DB::table('desk_service_versions')->where('id', $v1)->value('effective_from'));
|
||||
$this->publish(1, 'SYNTHETIC scheduled after legacy', '2026-11-03');
|
||||
$this->assertSame($v1, app(DeskServiceAvailability::class)->current()->first()->id);
|
||||
$this->expectException(\RuntimeException::class);
|
||||
$migration->down();
|
||||
}
|
||||
|
||||
public function test_investor_path_uses_the_same_dated_edition_as_the_catalogue(): void
|
||||
{
|
||||
config(['investor-path.enabled' => true, 'investmoz_ai.enabled' => false, 'suitecrm.enabled' => false]);
|
||||
$v1 = $this->publish(0, 'SYNTHETIC path current');
|
||||
$v2 = $this->publish(1, 'SYNTHETIC path future', '2026-11-03');
|
||||
$id = $this->actingAs($this->investor)->postJson('/investimentos', ['title' => 'SYNTHETIC dated path', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertCreated()->json('id');
|
||||
$this->getJson('/investimentos/'.$id)->assertOk()->assertJsonPath('services.0.id', $v1);
|
||||
$this->travelTo(CarbonImmutable::parse('2026-11-03 10:00:00', 'UTC'));
|
||||
$this->getJson('/investimentos/'.$id)->assertOk()->assertJsonPath('services.0.id', $v2)->assertJsonPath('services.0.effective_from', '2026-11-03');
|
||||
}
|
||||
|
||||
public function test_immediate_retry_retains_original_start_date_after_midnight(): void
|
||||
{
|
||||
$v1 = $this->publish(0, 'SYNTHETIC immediate retry');
|
||||
$this->travelTo(CarbonImmutable::parse('2026-11-03 10:00:00', 'UTC'));
|
||||
$this->actingAs($this->manager)->putJson($this->url, $this->input(0, 'SYNTHETIC immediate retry'))->assertCreated()
|
||||
->assertJsonPath('id', $v1)->assertJsonPath('effective_from', '2026-11-02');
|
||||
$this->assertDatabaseCount('desk_service_versions', 1);
|
||||
$this->assertSame(1, DB::table('audit_events')->where('action', 'service_definition_version_published')->count());
|
||||
}
|
||||
|
||||
public function test_initial_template_publication_also_records_the_immediate_date_and_retains_legacy_retry(): void
|
||||
{
|
||||
$input = ['code' => 'project-preparation', 'confirm' => true];
|
||||
$id = $this->actingAs($this->manager)->postJson('/management/balcao/servicos', $input)->assertCreated()->json('id');
|
||||
$this->assertSame('2026-11-02', DB::table('desk_service_versions')->where('id', $id)->value('effective_from'));
|
||||
$this->assertSame($id, app(DeskServiceAvailability::class)->current()->first()->id);
|
||||
$this->travelTo(CarbonImmutable::parse('2026-11-03 10:00:00', 'UTC'));
|
||||
$this->postJson('/management/balcao/servicos', $input)->assertCreated()->assertJsonPath('id', $id);
|
||||
$this->assertDatabaseCount('desk_service_versions', 1);
|
||||
$this->assertSame('2026-11-02', DB::table('desk_service_versions')->where('id', $id)->value('effective_from'));
|
||||
}
|
||||
|
||||
public function test_calendar_change_alone_does_not_create_a_duplicate_unchanged_publication(): void
|
||||
{
|
||||
$this->publish(0, 'SYNTHETIC same form');
|
||||
$this->travelTo(CarbonImmutable::parse('2026-11-03 10:00:00', 'UTC'));
|
||||
$this->actingAs($this->manager)->putJson($this->url, $this->input(1, 'SYNTHETIC same form'))->assertUnprocessable()->assertJsonValidationErrors('definition');
|
||||
$this->assertDatabaseCount('desk_service_versions', 1);
|
||||
$this->putJson($this->url, $this->input(1, 'SYNTHETIC same form', '2026-11-03'))->assertCreated()->assertJsonPath('version', 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\VirtualDesk;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class DeskTypedFieldsTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $manager;
|
||||
|
||||
private User $investor;
|
||||
|
||||
private string $editorUrl = '/management/balcao/servicos/project-change';
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
$this->manager = User::factory()->create();
|
||||
$this->investor = User::factory()->create();
|
||||
config(['portal.managers' => [$this->manager->email]]);
|
||||
}
|
||||
|
||||
private function fields(): array
|
||||
{
|
||||
return [
|
||||
'branch' => ['label' => 'SYNTHETIC branch', 'type' => 'select', 'required' => false, 'options' => ['on' => 'Open', 'off' => 'Closed']],
|
||||
'activities' => ['label' => 'SYNTHETIC activities', 'type' => 'multiselect', 'required' => true, 'options' => ['0' => 'Synthetic zero', 'cotton' => 'Synthetic cotton', 'other' => 'Synthetic other'], 'when' => ['field' => 'branch', 'equals' => 'on']],
|
||||
'declaration' => ['label' => 'SYNTHETIC declaration', 'type' => 'consent', 'required' => true, 'statement' => 'SYNTHETIC statement <script>fictional</script> — no real authorisation.', 'when' => ['field' => 'activities', 'operator' => 'contains', 'equals' => 'cotton']],
|
||||
'explanation' => ['label' => 'SYNTHETIC refusal explanation', 'type' => 'textarea', 'required' => true, 'when' => ['field' => 'declaration', 'equals' => 'declined']],
|
||||
];
|
||||
}
|
||||
|
||||
private function input(int $base = 0): array
|
||||
{
|
||||
$definition = config('virtual-desk.services.project-change');
|
||||
$definition['fields'] = [...$definition['fields'], ...$this->fields()];
|
||||
|
||||
return ['base_version' => $base, 'definition' => $definition, 'confirm' => true, 'reason' => 'SYNTHETIC typed fields QA; no actual service publication.'];
|
||||
}
|
||||
|
||||
private function requestId(?array $input = null): string
|
||||
{
|
||||
$edition = $this->actingAs($this->manager)->putJson($this->editorUrl, $input ?? $this->input())->assertCreated()->json('id');
|
||||
$case = $this->actingAs($this->investor)->postJson('/balcao-virtual/dossiers', ['title' => 'SYNTHETIC typed forms', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertCreated()->json('id');
|
||||
|
||||
return $this->postJson('/balcao-virtual/dossiers/'.$case.'/pedidos', ['service_version_id' => $edition, 'client_key' => (string) Str::uuid()])->assertCreated()->json('id');
|
||||
}
|
||||
|
||||
private function answers(): array
|
||||
{
|
||||
return ['title' => 'SYNTHETIC typed answers', 'description' => 'SYNTHETIC reserved private description', 'original_reference' => 'SYNTHETIC-REF', 'change_reason' => 'SYNTHETIC change', 'branch' => 'on', 'activities' => ['cotton', '0'], 'declaration' => 'declined', 'explanation' => 'SYNTHETIC explicit refusal'];
|
||||
}
|
||||
|
||||
public function test_empty_drafts_are_valid_but_submission_requires_applicable_answers_and_global_consent(): void
|
||||
{
|
||||
$id = $this->requestId();
|
||||
$url = '/balcao-virtual/pedidos/'.$id;
|
||||
$this->putJson($url, ['version' => 1])->assertUnprocessable()->assertJsonValidationErrors('payload');
|
||||
$this->putJson($url, ['version' => 1, 'payload' => []])->assertOk()->assertJsonPath('version', 2);
|
||||
$this->putJson($url, ['version' => 2, 'payload' => [], 'submit' => true, 'consent' => true])->assertUnprocessable()->assertJsonValidationErrors(['payload.title', 'payload.description']);
|
||||
$answers = $this->answers();
|
||||
unset($answers['declaration']);
|
||||
$this->putJson($url, ['version' => 2, 'payload' => $answers, 'submit' => true, 'consent' => true])->assertUnprocessable()->assertJsonValidationErrors('payload.declaration');
|
||||
$this->putJson($url, ['version' => 2, 'payload' => $this->answers(), 'submit' => true, 'consent' => false])->assertUnprocessable()->assertJsonValidationErrors('consent');
|
||||
$this->assertSame([], app(VirtualDesk::class)->decode(DB::table('desk_requests')->where('id', $id)->value('submitted_snapshot')));
|
||||
}
|
||||
|
||||
public function test_multiple_answers_are_strict_distinct_lists_of_declared_string_codes(): void
|
||||
{
|
||||
$id = $this->requestId();
|
||||
foreach ([['cotton', 'cotton'], ['missing'], [0], 'cotton', ['wrong' => 'cotton'], [['cotton']]] as $value) {
|
||||
$response = $this->putJson('/balcao-virtual/pedidos/'.$id, ['version' => 1, 'payload' => ['activities' => $value]]);
|
||||
$response->assertUnprocessable();
|
||||
$this->assertNotEmpty(array_filter(array_keys($response->json('errors')), fn ($key) => str_starts_with($key, 'payload.activities')));
|
||||
}
|
||||
$this->putJson('/balcao-virtual/pedidos/'.$id, ['version' => 1, 'payload' => ['activities' => ['cotton', '0']]])->assertOk();
|
||||
$this->assertSame(['0', 'cotton'], app(VirtualDesk::class)->decode(DB::table('desk_requests')->where('id', $id)->value('payload'))['activities']);
|
||||
}
|
||||
|
||||
public function test_required_multiselect_is_not_satisfied_by_empty_or_null_and_declaration_never_accepts_boolean(): void
|
||||
{
|
||||
$desk = app(VirtualDesk::class);
|
||||
foreach ([[], null] as $answer) {
|
||||
try {
|
||||
$desk->validateFields(['branch' => 'on', 'activities' => $answer], ['fields' => $this->fields()], true);
|
||||
$this->fail('An applicable required choice cannot be empty.');
|
||||
} catch (ValidationException $error) {
|
||||
$this->assertArrayHasKey('payload.activities', $error->errors());
|
||||
}
|
||||
}
|
||||
foreach ([true, false, 'yes', 1] as $answer) {
|
||||
try {
|
||||
$desk->validateFields(['branch' => 'on', 'activities' => ['cotton'], 'declaration' => $answer], ['fields' => $this->fields()], true);
|
||||
$this->fail('An explicit declaration choice is required.');
|
||||
} catch (ValidationException $error) {
|
||||
$this->assertArrayHasKey('payload.declaration', $error->errors());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function test_ancestor_conditions_preserve_hidden_answers_without_activating_descendants(): void
|
||||
{
|
||||
$desk = app(VirtualDesk::class);
|
||||
$payload = ['branch' => 'off', 'activities' => ['cotton'], 'declaration' => 'declined'];
|
||||
$definition = ['fields' => $this->fields()];
|
||||
$this->assertSame($payload, $desk->validateFields($payload, $definition, true));
|
||||
$this->assertSame(['branch'], array_keys($desk->applicableFields($payload, $definition)));
|
||||
$payload['branch'] = 'on';
|
||||
try {
|
||||
$desk->validateFields($payload, $definition, true);
|
||||
$this->fail('Opening ancestors must require the refusal explanation.');
|
||||
} catch (ValidationException $error) {
|
||||
$this->assertArrayHasKey('payload.explanation', $error->errors());
|
||||
}
|
||||
$payload['explanation'] = 'SYNTHETIC saved refusal';
|
||||
$this->assertSame($payload, $desk->validateFields($payload, $definition, true));
|
||||
$this->assertCount(4, $desk->applicableFields($payload, $definition));
|
||||
}
|
||||
|
||||
public function test_zero_choice_is_a_real_answer_and_optional_declaration_can_remain_unanswered(): void
|
||||
{
|
||||
$desk = app(VirtualDesk::class);
|
||||
$fields = $this->fields();
|
||||
$payload = ['branch' => 'on', 'activities' => ['0']];
|
||||
$this->assertSame($payload, $desk->validateFields($payload, ['fields' => $fields], true));
|
||||
$fields['declaration']['required'] = false;
|
||||
$payload = ['branch' => 'on', 'activities' => ['cotton'], 'declaration' => null];
|
||||
$this->assertSame($payload, $desk->validateFields($payload, ['fields' => $fields], true));
|
||||
$this->assertArrayNotHasKey('explanation', $desk->applicableFields($payload, ['fields' => $fields]));
|
||||
$payload['declaration'] = 'accepted';
|
||||
$this->assertSame($payload, $desk->validateFields($payload, ['fields' => $fields], true));
|
||||
}
|
||||
|
||||
public function test_location_source_must_cover_the_multiple_choice_condition_of_its_location(): void
|
||||
{
|
||||
$input = $this->input();
|
||||
$input['definition']['fields']['territory_id']['when'] = ['field' => 'activities', 'operator' => 'contains', 'equals' => 'cotton'];
|
||||
$input['definition']['fields']['location_source']['when'] = ['field' => 'activities', 'operator' => 'contains', 'equals' => 'other'];
|
||||
$this->actingAs($this->manager)->putJson($this->editorUrl, $input)->assertUnprocessable()->assertJsonValidationErrors('definition.fields.location_source.when');
|
||||
$input['definition']['fields']['location_source']['when'] = $input['definition']['fields']['territory_id']['when'];
|
||||
$this->putJson($this->editorUrl, $input)->assertCreated();
|
||||
}
|
||||
|
||||
public function test_refusal_is_a_valid_answer_snapshot_is_server_bound_and_reordered_retry_is_idempotent(): void
|
||||
{
|
||||
$id = $this->requestId();
|
||||
$answers = $this->answers();
|
||||
$url = '/balcao-virtual/pedidos/'.$id;
|
||||
$this->putJson($url, ['version' => 1, 'payload' => $answers, 'submit' => true, 'consent' => true, 'field_declarations' => ['forged' => 'accepted']])->assertOk()->assertJsonPath('status', 'submitted');
|
||||
$row = DB::table('desk_requests')->where('id', $id)->first();
|
||||
$snapshot = app(VirtualDesk::class)->decode($row->submitted_snapshot);
|
||||
$declaration = $snapshot['field_declarations']['declaration'];
|
||||
$this->assertSame('declined', $declaration['answer']);
|
||||
$this->assertSame($this->investor->id, $declaration['actor_id']);
|
||||
$this->assertSame($row->service_version_id, $declaration['service_version_id']);
|
||||
$this->assertSame($this->fields()['declaration']['statement'], $declaration['statement']);
|
||||
$this->assertSame(hash('sha256', $declaration['statement']), $declaration['statement_sha256']);
|
||||
$this->assertNotEmpty($declaration['declared_at']);
|
||||
$this->assertSame(['declaration'], array_keys($snapshot['field_declarations']));
|
||||
$answers['activities'] = ['0', 'cotton'];
|
||||
$this->putJson($url, ['version' => 1, 'payload' => $answers, 'submit' => true, 'consent' => true])->assertOk();
|
||||
$this->assertEquals($row, DB::table('desk_requests')->where('id', $id)->first());
|
||||
$this->assertSame(1, DB::table('desk_events')->where('request_id', $id)->where('action', 'submitted')->count());
|
||||
$this->get($url.'/recibo?format=html')->assertOk()->assertSee('Synthetic zero · Synthetic cotton')->assertSee('Recusado')->assertSee($declaration['statement'])->assertDontSee('<script>fictional</script>', false);
|
||||
$this->actingAs(User::factory()->create())->get($url.'/recibo?format=html')->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_inactive_declarations_remain_answers_but_are_not_recorded_as_active_consent(): void
|
||||
{
|
||||
$id = $this->requestId();
|
||||
$answers = [...$this->answers(), 'branch' => 'off', 'declaration' => 'accepted'];
|
||||
$this->putJson('/balcao-virtual/pedidos/'.$id, ['version' => 1, 'payload' => $answers, 'submit' => true, 'consent' => true])->assertOk();
|
||||
$snapshot = app(VirtualDesk::class)->decode(DB::table('desk_requests')->where('id', $id)->value('submitted_snapshot'));
|
||||
$this->assertSame('accepted', $snapshot['payload']['declaration']);
|
||||
$this->assertSame([], $snapshot['field_declarations']);
|
||||
$this->get('/balcao-virtual/pedidos/'.$id.'/recibo?format=html')->assertOk()->assertSee('Respostas conservadas de perguntas não aplicáveis')->assertDontSee('Declarações registadas nesta submissão');
|
||||
}
|
||||
|
||||
public function test_new_schema_does_not_rewrite_old_labels_options_declaration_or_receipt(): void
|
||||
{
|
||||
$id = $this->requestId();
|
||||
$answers = [...$this->answers(), 'declaration' => 'accepted'];
|
||||
$this->putJson('/balcao-virtual/pedidos/'.$id, ['version' => 1, 'payload' => $answers, 'submit' => true, 'consent' => true])->assertOk();
|
||||
$before = DB::table('desk_requests')->where('id', $id)->first();
|
||||
$input = $this->input(1);
|
||||
$input['definition']['fields']['activities']['options']['cotton'] = 'SYNTHETIC revised label';
|
||||
$input['definition']['fields']['declaration']['statement'] = 'SYNTHETIC different future wording.';
|
||||
$this->actingAs($this->manager)->putJson($this->editorUrl, $input)->assertCreated();
|
||||
$this->actingAs($this->investor)->getJson('/balcao-virtual/pedidos/'.$id)->assertOk()->assertJsonPath('definition.fields.activities.options.cotton', 'Synthetic cotton')->assertJsonPath('definition.fields.declaration.statement', $this->fields()['declaration']['statement']);
|
||||
$this->get('/balcao-virtual/pedidos/'.$id.'/recibo?format=html')->assertOk()->assertSee('Synthetic cotton')->assertDontSee('SYNTHETIC different future wording.');
|
||||
$this->assertEquals($before, DB::table('desk_requests')->where('id', $id)->first());
|
||||
}
|
||||
|
||||
public function test_publication_rejects_ambiguous_conditions_or_incomplete_typed_definitions(): void
|
||||
{
|
||||
$valid = $this->input();
|
||||
$this->actingAs($this->investor)->putJson($this->editorUrl, $valid)->assertForbidden();
|
||||
$mutations = [
|
||||
fn ($fields) => array_replace_recursive($fields, ['declaration' => ['statement' => ' ']]),
|
||||
function ($fields) {
|
||||
unset($fields['declaration']['statement']);
|
||||
|
||||
return $fields;
|
||||
},
|
||||
fn ($fields) => array_replace_recursive($fields, ['branch' => ['statement' => 'SYNTHETIC invalid metadata']]),
|
||||
function ($fields) {
|
||||
$fields['activities']['options'] = [];
|
||||
|
||||
return $fields;
|
||||
},
|
||||
fn ($fields) => array_replace_recursive($fields, ['declaration' => ['when' => ['operator' => 'equals']]]),
|
||||
fn ($fields) => array_replace_recursive($fields, ['activities' => ['when' => ['operator' => 'contains']]]),
|
||||
fn ($fields) => array_replace_recursive($fields, ['declaration' => ['when' => ['equals' => 'absent']]]),
|
||||
fn ($fields) => array_replace_recursive($fields, ['explanation' => ['when' => ['equals' => 'yes']]]),
|
||||
fn ($fields) => array_replace_recursive($fields, ['branch' => ['when' => ['field' => 'explanation', 'equals' => 'cycle']]]),
|
||||
];
|
||||
foreach ($mutations as $mutate) {
|
||||
$input = $valid;
|
||||
$input['definition']['fields'] = $mutate($input['definition']['fields']);
|
||||
$this->actingAs($this->manager)->putJson($this->editorUrl, $input)->assertUnprocessable();
|
||||
}
|
||||
$this->assertDatabaseCount('desk_service_versions', 0);
|
||||
$this->putJson($this->editorUrl, $valid)->assertCreated();
|
||||
}
|
||||
|
||||
public function test_returned_requests_reuse_array_answers_without_granting_extra_edit_rights(): void
|
||||
{
|
||||
$id = $this->requestId();
|
||||
$url = '/balcao-virtual/pedidos/'.$id;
|
||||
$answers = $this->answers();
|
||||
$this->putJson($url, ['version' => 1, 'payload' => $answers, 'submit' => true, 'consent' => true])->assertOk();
|
||||
app(VirtualDesk::class)->transition($this->manager, $id, ['version' => 2, 'status' => 'returned', 'reason' => 'SYNTHETIC clarify explanation only', 'editable_fields' => ['explanation']]);
|
||||
$answers['activities'] = ['other'];
|
||||
$this->actingAs($this->investor)->putJson($url, ['version' => 3, 'payload' => $answers])->assertUnprocessable()->assertJsonValidationErrors('payload.activities');
|
||||
$answers = [...$this->answers(), 'activities' => ['0', 'cotton'], 'explanation' => 'SYNTHETIC revised explanation'];
|
||||
$this->putJson($url, ['version' => 3, 'payload' => $answers, 'submit' => true, 'consent' => true, 'reason' => 'SYNTHETIC correction'])->assertOk();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Jobs\ScanDocumentForMalware;
|
||||
use App\Models\User;
|
||||
use App\Services\Malware\DocumentScanDelivery;
|
||||
use App\Services\Malware\DocumentScanRetry;
|
||||
use App\Services\PortalProfileAdministration;
|
||||
use Illuminate\Bus\UniqueLock;
|
||||
use Illuminate\Contracts\Cache\Repository;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Bus;
|
||||
use Illuminate\Support\Facades\Context;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Facades\Queue;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Testing\TestResponse;
|
||||
use Tests\Support\CleanScannerFixture;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class DocumentScanRetryTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $manager;
|
||||
|
||||
private string $id;
|
||||
|
||||
private string $cipher;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
Http::fake();
|
||||
Mail::fake();
|
||||
Queue::fake();
|
||||
Storage::fake('local');
|
||||
$this->manager = User::factory()->create();
|
||||
config(['portal.managers' => [$this->manager->email], 'portal.document_managers' => [], 'suitecrm.enabled' => false, 'investmoz_ai.enabled' => false]);
|
||||
$this->actingAs($this->manager);
|
||||
$this->id = (string) Str::uuid();
|
||||
$bytes = "%PDF-1.7\nSYNTHETIC retry document\n%%EOF";
|
||||
$this->cipher = Crypt::encryptString($bytes);
|
||||
Storage::disk('local')->put('opportunity-resources/'.$this->id, $this->cipher);
|
||||
DB::table('documents')->insert(['id' => $this->id, 'source_system' => 'portal-services', 'file_name' => 'PRIVATE-synthetic.pdf', 'storage_key' => 'opportunity-resources/'.$this->id,
|
||||
'sha256' => hash('sha256', $bytes), 'size_bytes' => strlen($bytes), 'media_type' => 'application/pdf', 'status' => 'quarantined', 'data_classification' => 'restricted',
|
||||
'storage_encryption' => 'laravel', 'uploaded_by' => $this->manager->id, 'malware_scan_status' => 'inconclusive', 'malware_failure_reason' => 'scanner_unavailable']);
|
||||
}
|
||||
|
||||
private function retry(): TestResponse
|
||||
{
|
||||
return $this->from('/management/portal')->post('/management/documents/'.$this->id.'/malware/retry');
|
||||
}
|
||||
|
||||
private function document(): \stdClass
|
||||
{
|
||||
return DB::table('documents')->where('id', $this->id)->first();
|
||||
}
|
||||
|
||||
private function assertOriginal(): void
|
||||
{
|
||||
$this->assertSame($this->cipher, Storage::disk('local')->get('opportunity-resources/'.$this->id));
|
||||
$this->assertSame(1, DB::table('documents')->count());
|
||||
}
|
||||
|
||||
public function test_http_retry_confirms_dispatch_acceptance_and_audits_the_existing_manager(): void
|
||||
{
|
||||
$this->retry()->assertRedirect('/management/portal')->assertSessionHas('success', fn ($value) => str_contains($value, 'aceite pelo serviço de envio'));
|
||||
Queue::assertPushed(ScanDocumentForMalware::class, 1);
|
||||
$this->assertSame('pending', $this->document()->malware_scan_status);
|
||||
$this->assertSame('quarantined', $this->document()->status);
|
||||
$event = DB::table('audit_events')->where('action', 'scan_retry_requested')->sole();
|
||||
$this->assertSame($this->manager->id, $event->actor_user_id);
|
||||
$data = json_decode($event->after_data, true);
|
||||
$this->assertSame($this->id, $data['document_id']);
|
||||
$this->assertTrue(Str::isUuid($data['reference']));
|
||||
$this->assertStringNotContainsString('PRIVATE', $event->after_data);
|
||||
$this->assertOriginal();
|
||||
}
|
||||
|
||||
public function test_an_existing_unique_lease_neither_resets_failure_nor_claims_another_push(): void
|
||||
{
|
||||
$job = new ScanDocumentForMalware($this->id);
|
||||
$this->assertTrue((new UniqueLock(app(Repository::class)))->acquire($job));
|
||||
$before = $this->document();
|
||||
$this->retry()->assertRedirect()->assertSessionMissing('success')->assertSessionHas('warning', fn ($value) => str_contains($value, 'reserva de análise'));
|
||||
Queue::assertNothingPushed();
|
||||
$this->assertEquals($before, $this->document());
|
||||
$this->assertSame(0, DB::table('audit_events')->where('action', 'scan_retry_requested')->count());
|
||||
$this->assertOriginal();
|
||||
}
|
||||
|
||||
public function test_transport_failure_is_reported_as_uncertain_and_does_not_erase_the_original(): void
|
||||
{
|
||||
Bus::shouldReceive('dispatch')->once()->andThrow(new \RuntimeException('PRIVATE queue password and SQL'));
|
||||
$this->retry()->assertRedirect()->assertSessionMissing('success')->assertSessionHas('warning', fn ($value) => str_contains($value, 'Não foi possível confirmar'));
|
||||
$this->assertStringNotContainsString('PRIVATE', session('warning'));
|
||||
$this->assertSame('failed', $this->document()->malware_scan_status);
|
||||
$this->assertSame('quarantined', $this->document()->status);
|
||||
$this->assertSame(0, DB::table('document_malware_scans')->count());
|
||||
$this->assertNull(Context::getHidden('laravel_unique_job_key'));
|
||||
$this->assertFalse((new UniqueLock(app(Repository::class)))->acquire(new ScanDocumentForMalware($this->id)));
|
||||
$this->assertOriginal();
|
||||
}
|
||||
|
||||
public function test_lost_acknowledgement_after_a_sync_clean_result_does_not_requarantine_it(): void
|
||||
{
|
||||
Bus::shouldReceive('dispatch')->once()->andReturnUsing(function ($job) {
|
||||
$job->handle(new CleanScannerFixture);
|
||||
throw new \RuntimeException('PRIVATE acknowledgement lost');
|
||||
});
|
||||
$this->retry()->assertRedirect()->assertSessionHas('warning')->assertSessionMissing('success');
|
||||
$this->assertSame('clean', $this->document()->malware_scan_status);
|
||||
$this->assertSame('active', $this->document()->status);
|
||||
$this->assertSame(1, DB::table('document_malware_scans')->count());
|
||||
$this->assertOriginal();
|
||||
}
|
||||
|
||||
public function test_outer_rollback_discards_the_request_and_a_later_clean_result_blocks_a_stale_callback(): void
|
||||
{
|
||||
DB::beginTransaction();
|
||||
$result = app(DocumentScanRetry::class)->request($this->manager, $this->id);
|
||||
$this->assertSame('deferred', $result['outcome']);
|
||||
DB::rollBack();
|
||||
Queue::assertNothingPushed();
|
||||
$this->assertSame('inconclusive', $this->document()->malware_scan_status);
|
||||
DB::beginTransaction();
|
||||
app(DocumentScanRetry::class)->request($this->manager, $this->id);
|
||||
DB::table('documents')->where('id', $this->id)->update(['status' => 'active', 'malware_scan_status' => 'clean']);
|
||||
DB::commit();
|
||||
Queue::assertNothingPushed();
|
||||
$this->assertSame('clean', $this->document()->malware_scan_status);
|
||||
$this->assertTrue((new UniqueLock(app(Repository::class)))->acquire(new ScanDocumentForMalware($this->id)));
|
||||
$this->assertSame(0, DB::table('audit_events')->where('action', 'scan_retry_requested')->count());
|
||||
}
|
||||
|
||||
public function test_current_permission_is_rechecked_after_commit_before_any_scan_state_change(): void
|
||||
{
|
||||
DB::beginTransaction();
|
||||
app(DocumentScanRetry::class)->request($this->manager, $this->id);
|
||||
config(['portal.managers' => []]);
|
||||
DB::commit();
|
||||
Queue::assertNothingPushed();
|
||||
$this->assertSame('inconclusive', $this->document()->malware_scan_status);
|
||||
$this->assertSame(0, DB::table('audit_events')->where('action', 'scan_retry_requested')->count());
|
||||
$this->assertTrue((new UniqueLock(app(Repository::class)))->acquire(new ScanDocumentForMalware($this->id)));
|
||||
}
|
||||
|
||||
public function test_support_without_document_management_authority_cannot_request_a_scan(): void
|
||||
{
|
||||
$support = User::factory()->create();
|
||||
app(PortalProfileAdministration::class)->insertGrant((string) Str::uuid(), $this->manager, ['user_id' => $support->id, 'role' => 'technical_support', 'opportunity_types' => ['investment_project'], 'source' => 'synthetic-retry-support-fixture']);
|
||||
$this->actingAs($support);
|
||||
$this->retry()->assertForbidden();
|
||||
Queue::assertNothingPushed();
|
||||
$this->assertSame('inconclusive', $this->document()->malware_scan_status);
|
||||
}
|
||||
|
||||
public function test_clean_infected_scanning_and_deleted_documents_are_not_reset_by_retry(): void
|
||||
{
|
||||
foreach (['clean', 'infected', 'scanning'] as $state) {
|
||||
DB::table('documents')->where('id', $this->id)->update(['malware_scan_status' => $state]);
|
||||
$this->retry()->assertStatus(422);
|
||||
$this->assertSame($state, $this->document()->malware_scan_status);
|
||||
}
|
||||
DB::table('documents')->where('id', $this->id)->update(['status' => 'deleted', 'deleted_at' => now()]);
|
||||
$this->retry()->assertNotFound();
|
||||
Queue::assertNothingPushed();
|
||||
}
|
||||
|
||||
public function test_different_documents_have_independent_delivery_leases_and_stale_preparation_can_be_retried(): void
|
||||
{
|
||||
$first = new ScanDocumentForMalware($this->id);
|
||||
$delivery = app(DocumentScanDelivery::class);
|
||||
$this->assertSame('stale', $delivery->dispatch($first, fn () => false));
|
||||
$this->assertSame('accepted', $delivery->dispatch(new ScanDocumentForMalware($this->id)));
|
||||
$this->assertSame('duplicate', $delivery->dispatch(new ScanDocumentForMalware($this->id)));
|
||||
$this->assertSame('accepted', $delivery->dispatch(new ScanDocumentForMalware((string) Str::uuid())));
|
||||
Queue::assertPushed(ScanDocumentForMalware::class, 2);
|
||||
}
|
||||
|
||||
public function test_json_retry_has_no_redirect_and_distinguishes_duplicate_from_transport_failure(): void
|
||||
{
|
||||
$url = '/management/documents/'.$this->id.'/malware/retry';
|
||||
$this->postJson($url)->assertOk()->assertJsonPath('outcome', 'accepted')->assertHeader('Cache-Control', 'no-store, private');
|
||||
$this->postJson($url)->assertOk()->assertJsonPath('outcome', 'duplicate');
|
||||
Queue::assertPushed(ScanDocumentForMalware::class, 1);
|
||||
}
|
||||
|
||||
public function test_json_transport_failure_returns_only_a_safe_reference_with_the_uncertain_status(): void
|
||||
{
|
||||
Bus::shouldReceive('dispatch')->once()->andThrow(new \RuntimeException('PRIVATE transport payload'));
|
||||
$response = $this->postJson('/management/documents/'.$this->id.'/malware/retry')->assertStatus(503)->assertJsonPath('outcome', 'unconfirmed');
|
||||
$this->assertTrue(Str::isUuid($response->json('reference')));
|
||||
$this->assertStringNotContainsString('PRIVATE', $response->getContent());
|
||||
$this->assertSame('failed', $this->document()->malware_scan_status);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\Course;
|
||||
use App\Models\Occupation;
|
||||
use App\Models\Project;
|
||||
use App\Models\Skill;
|
||||
use App\Models\TrainingProvider;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class EducationDeclarationDraftsTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $owner;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
$this->owner = User::factory()->create();
|
||||
config(['education.enabled' => true, 'portal.managers' => [$this->owner->email]]);
|
||||
$this->actingAs($this->owner);
|
||||
}
|
||||
|
||||
private function valid(string $kind = 'demands'): array
|
||||
{
|
||||
$province = (string) Str::uuid();
|
||||
DB::table('geo_locations')->insert(['id' => $province, 'name' => 'SYNTHETIC QA province', 'code' => $province, 'location_type' => 'province']);
|
||||
$data = ['occupation_id' => Occupation::create(['code' => (string) Str::uuid(), 'name' => 'Synthetic occupation'])->id,
|
||||
'skill_id' => Skill::create(['code' => (string) Str::uuid(), 'name' => 'Synthetic skill'])->id, 'geo_location_id' => $province,
|
||||
'qualification' => 'Synthetic qualification', 'quantity' => 20, 'period_start' => today()->addMonth()->toDateString(),
|
||||
'period_end' => today()->addMonths(2)->toDateString(), 'source' => 'SENSITIVE SYNTHETIC QA SOURCE TEXT',
|
||||
'reference_date' => today()->toDateString(), 'valid_until' => today()->addYear()->toDateString()];
|
||||
if ($kind === 'demands') {
|
||||
return [...$data, 'employer' => 'SENSITIVE SYNTHETIC QA EMPLOYER', 'project_id' => Project::create(['code' => (string) Str::uuid(), 'name' => 'Synthetic project', 'status' => 'draft'])->id];
|
||||
}
|
||||
$provider = TrainingProvider::create(['name' => 'Synthetic provider', 'status' => 'candidate']);
|
||||
|
||||
return [...$data, 'course_id' => Course::create(['provider_id' => $provider->id, 'code' => (string) Str::uuid(), 'title' => 'Synthetic course', 'status' => 'draft'])->id];
|
||||
}
|
||||
|
||||
private function create(string $kind, array $payload = []): array
|
||||
{
|
||||
$input = ['client_key' => (string) Str::uuid(), 'version_no' => 0, 'payload' => $payload];
|
||||
$response = $this->postJson('/management/education/drafts/'.$kind, $input)->assertOk()->assertHeader('Cache-Control', 'no-store, private');
|
||||
|
||||
return [$response->json('id'), $input];
|
||||
}
|
||||
|
||||
public function test_incomplete_drafts_are_private_encrypted_recoverable_and_repeated_requests_do_not_duplicate(): void
|
||||
{
|
||||
[$id, $input] = $this->create('demands', ['employer' => 'PRIVATE SYNTHETIC EMPLOYER']);
|
||||
$this->postJson('/management/education/drafts/demands', $input)->assertOk()->assertJsonPath('version_no', 1)->assertJsonPath('id', $id);
|
||||
$this->assertDatabaseCount('education_declaration_drafts', 1);
|
||||
$this->assertDatabaseCount('labour_demands', 0);
|
||||
$this->assertStringNotContainsString('PRIVATE SYNTHETIC', DB::table('education_declaration_drafts')->sole()->payload);
|
||||
$this->assertStringNotContainsString('PRIVATE SYNTHETIC', DB::table('audit_events')->where('source_system', 'education-drafts')->first()->after_data);
|
||||
$other = User::factory()->create();
|
||||
config(['portal.managers' => [$this->owner->email, $other->email]]);
|
||||
$this->actingAs($other)->getJson('/management/education/drafts/demands/'.$id)->assertNotFound();
|
||||
$this->get('/management/education?draft='.$id)->assertNotFound();
|
||||
$this->get('/management/education')->assertOk()->assertInertia(fn ($page) => $page->has('ownDrafts.data', 0)->where('selectedDraft', null));
|
||||
$this->getJson('/management/education/drafts/demands')->assertOk()->assertJsonCount(0, 'data');
|
||||
$this->putJson('/management/education/drafts/demands/'.$id, ['version_no' => 1, 'payload' => []])->assertNotFound();
|
||||
$this->actingAs(User::findOrFail($this->owner->id))->getJson('/management/education/drafts/demands/'.$id)->assertOk()->assertJsonPath('payload.employer', 'PRIVATE SYNTHETIC EMPLOYER');
|
||||
$this->get('/management/education?draft='.$id)->assertOk()->assertHeader('Cache-Control', 'no-store, private')
|
||||
->assertInertia(fn ($page) => $page->component('education/index')->where('selectedDraft.id', $id)
|
||||
->where('selectedDraft.payload.employer', 'PRIVATE SYNTHETIC EMPLOYER')->has('ownDrafts.data', 1)->missing('ownDrafts.data.0.payload'));
|
||||
$this->actingAs(User::factory()->create())->postJson('/management/education/drafts/demands', $input)->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_stale_edits_and_wrong_kind_are_rejected_while_incomplete_submission_creates_nothing(): void
|
||||
{
|
||||
[$id, $input] = $this->create('demands');
|
||||
$url = '/management/education/drafts/demands/'.$id;
|
||||
$this->putJson($url, ['version_no' => 1, 'payload' => ['quantity' => 0]])->assertOk()->assertJsonPath('version_no', 2);
|
||||
$this->putJson($url, ['version_no' => 1, 'payload' => ['quantity' => 0]])->assertOk()->assertJsonPath('version_no', 2);
|
||||
$this->putJson($url, ['version_no' => 1, 'payload' => ['quantity' => 5]])->assertConflict();
|
||||
$this->postJson('/management/education/drafts/capacities', $input)->assertConflict();
|
||||
$this->getJson('/management/education/drafts/capacities/'.$id)->assertNotFound();
|
||||
$this->putJson($url, ['version_no' => 2, 'payload' => ['status' => 'reviewed']])->assertUnprocessable();
|
||||
$this->postJson($url.'/submit', ['version_no' => 2, 'payload' => ['quantity' => 0]])->assertUnprocessable();
|
||||
$this->assertDatabaseCount('labour_demands', 0);
|
||||
$this->getJson($url)->assertJsonPath('state', 'draft');
|
||||
}
|
||||
|
||||
public function test_distinct_numeric_text_is_not_collapsed_and_rollback_preserves_drafts(): void
|
||||
{
|
||||
[$id] = $this->create('demands', ['employer' => '001']);
|
||||
$this->putJson('/management/education/drafts/demands/'.$id, ['version_no' => 1, 'payload' => ['employer' => '1']])->assertOk()
|
||||
->assertJsonPath('version_no', 2)->assertJsonPath('payload.employer', '1');
|
||||
$migration = require database_path('migrations/2026_11_02_230000_education_declaration_drafts.php');
|
||||
$this->expectException(\RuntimeException::class);
|
||||
$this->expectExceptionMessage('Preserve education drafts');
|
||||
$migration->down();
|
||||
}
|
||||
|
||||
public function test_submission_is_single_preserves_snapshot_and_still_requires_independent_review(): void
|
||||
{
|
||||
$payload = $this->valid();
|
||||
[$id] = $this->create('demands', ['employer' => $payload['employer']]);
|
||||
$url = '/management/education/drafts/demands/'.$id;
|
||||
$input = ['version_no' => 1, 'payload' => $payload];
|
||||
$record = $this->postJson($url.'/submit', $input)->assertOk()->assertJsonPath('state', 'submitted')->json('record_id');
|
||||
$this->postJson($url.'/submit', $input)->assertOk()->assertJsonPath('record_id', $record);
|
||||
$this->assertDatabaseCount('labour_demands', 1);
|
||||
$this->assertSame('submitted', DB::table('labour_demands')->sole()->status);
|
||||
$this->postJson('/management/education/demands/'.$record.'/review', ['version_no' => 1, 'status' => 'reviewed', 'review_reason' => 'Synthetic self-review must be refused.'])->assertForbidden();
|
||||
$this->putJson($url, ['version_no' => 2, 'payload' => $payload])->assertConflict();
|
||||
$this->postJson($url.'/submit', [...$input, 'payload' => [...$payload, 'quantity' => 50]])->assertConflict();
|
||||
Project::whereKey($payload['project_id'])->update(['name' => 'Changed synthetic project']);
|
||||
$this->getJson($url)->assertJsonPath('references.project_id.name', 'Synthetic project')->assertJsonPath('payload.quantity', 20);
|
||||
$this->get('/management/education?draft='.$id)->assertOk()->assertInertia(fn ($page) => $page->where('selectedDraft.state', 'submitted')
|
||||
->where('selectedDraft.references.project_id.name', 'Synthetic project')->where('ownDrafts.data.0.label', 'Synthetic qualification'));
|
||||
}
|
||||
|
||||
public function test_capacity_reuses_final_validation_and_does_not_accept_employer_or_project_fields(): void
|
||||
{
|
||||
$payload = $this->valid('capacities');
|
||||
[$id] = $this->create('capacities', [...$payload, 'employer' => 'NOT APPLICABLE', 'project_id' => 'not-applicable']);
|
||||
$url = '/management/education/drafts/capacities/'.$id;
|
||||
$this->getJson($url)->assertJsonMissingPath('payload.employer')->assertJsonMissingPath('payload.project_id');
|
||||
Course::whereKey($payload['course_id'])->update(['status' => 'retired']);
|
||||
$this->postJson($url.'/submit', ['version_no' => 1, 'payload' => $payload])->assertUnprocessable();
|
||||
Course::whereKey($payload['course_id'])->update(['status' => 'draft']);
|
||||
$this->postJson($url.'/submit', ['version_no' => 1, 'payload' => $payload])->assertOk()->assertJsonPath('state', 'submitted');
|
||||
$this->assertDatabaseCount('training_capacities', 1);
|
||||
$this->assertDatabaseCount('labour_demands', 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\Course;
|
||||
use App\Models\LabourDemand;
|
||||
use App\Models\Occupation;
|
||||
use App\Models\Project;
|
||||
use App\Models\Skill;
|
||||
use App\Models\TrainingCapacity;
|
||||
use App\Models\TrainingProvider;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Str;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use Tests\Support\AuthenticatesQaActors;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class EducationWorkQueueTest extends TestCase
|
||||
{
|
||||
use AuthenticatesQaActors,RefreshDatabase;
|
||||
|
||||
private User $manager;
|
||||
|
||||
private User $other;
|
||||
|
||||
/** @var array<string,mixed> */
|
||||
private array $data;
|
||||
|
||||
private string $project;
|
||||
|
||||
private string $course;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
Http::fake();
|
||||
Mail::fake();
|
||||
$this->manager = User::factory()->create(['name' => 'SYNTHETIC education manager']);
|
||||
$this->other = User::factory()->create(['name' => 'SYNTHETIC other submitter']);
|
||||
config(['education.enabled' => true, 'portal.managers' => [$this->manager->email, $this->other->email], 'suitecrm.enabled' => false, 'investmoz_ai.enabled' => false]);
|
||||
$this->actingAsWithMfa($this->manager);
|
||||
$geo = (string) Str::uuid();
|
||||
DB::table('geo_locations')->insert(['id' => $geo, 'name' => 'SYNTHETIC province', 'code' => $geo, 'location_type' => 'province']);
|
||||
$this->project = Project::create(['code' => (string) Str::uuid(), 'name' => 'SYNTHETIC project', 'status' => 'draft'])->id;
|
||||
$provider = TrainingProvider::create(['name' => 'SYNTHETIC provider', 'status' => 'candidate']);
|
||||
$this->course = Course::create(['provider_id' => $provider->id, 'code' => (string) Str::uuid(), 'title' => 'SYNTHETIC course', 'status' => 'draft'])->id;
|
||||
$this->data = ['occupation_id' => Occupation::create(['code' => (string) Str::uuid(), 'name' => 'SYNTHETIC occupation'])->id,
|
||||
'skill_id' => Skill::create(['code' => (string) Str::uuid(), 'name' => 'SYNTHETIC skill'])->id, 'geo_location_id' => $geo, 'qualification' => 'SYNTHETIC qualification',
|
||||
'quantity' => 10, 'period_start' => today()->addMonth()->toDateString(), 'period_end' => today()->addMonths(3)->toDateString(), 'reference_date' => today()->subMonth()->toDateString(),
|
||||
'valid_until' => today()->addYear()->toDateString(), 'source' => 'PRIVATE SYNTHETIC EDUCATION SOURCE', 'status' => 'submitted'];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $changes */
|
||||
private function demand(User $actor, array $changes = []): LabourDemand
|
||||
{
|
||||
return LabourDemand::create([...$this->data, 'project_id' => $this->project, 'employer' => 'SYNTHETIC employer', 'submitted_by' => $actor->id, ...$changes])->fresh();
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $changes */
|
||||
private function capacity(User $actor, array $changes = []): TrainingCapacity
|
||||
{
|
||||
return TrainingCapacity::create([...$this->data, 'course_id' => $this->course, 'submitted_by' => $actor->id, ...$changes])->fresh();
|
||||
}
|
||||
|
||||
/** @return array{client_key:string,version_no:int,status:string,review_reason:string} */
|
||||
private function decision(): array
|
||||
{
|
||||
return ['client_key' => (string) Str::uuid(), 'version_no' => 1, 'status' => 'reviewed', 'review_reason' => 'SYNTHETIC independent review with evidence.'];
|
||||
}
|
||||
|
||||
public function test_personal_counts_include_legacy_declarations_and_separate_units_and_expiry(): void
|
||||
{
|
||||
$this->demand($this->manager, ['quantity' => 100]);
|
||||
$this->demand($this->manager, ['status' => 'reviewed', 'reviewed_by' => $this->other->id, 'review_reason' => 'SYNTHETIC previous review']);
|
||||
$this->demand($this->manager, ['valid_until' => today()->subDay()->toDateString()]);
|
||||
$this->demand($this->other, ['quantity' => 500]);
|
||||
$this->demand($this->other, ['valid_until' => today()->subDay()->toDateString()]);
|
||||
$this->capacity($this->manager, ['quantity' => 700]);
|
||||
$this->capacity($this->other, ['quantity' => 999]);
|
||||
$this->demand($this->manager)->delete();
|
||||
$this->get('/management/education?q=not-found')->assertOk()->assertInertia(fn (Assert $page) => $page->component('education/index')->has('demands.data', 0)
|
||||
->where('workQueue.actor_id', $this->manager->id)->where('workQueue.demands.total', 3)->where('workQueue.demands.submitted', 1)->where('workQueue.demands.reviewed', 1)
|
||||
->where('workQueue.demands.expired', 1)->where('workQueue.demands.to_review', 1)->where('workQueue.capacities.total', 1)->where('workQueue.capacities.to_review', 1));
|
||||
}
|
||||
|
||||
public function test_mine_and_independent_review_scopes_do_not_mix_authors_or_expired_decisions(): void
|
||||
{
|
||||
$mine = $this->demand($this->manager);
|
||||
$other = $this->demand($this->other);
|
||||
$this->demand($this->other, ['valid_until' => today()->subDay()->toDateString()]);
|
||||
$this->get('/management/education?scope=mine')->assertOk()->assertInertia(fn (Assert $page) => $page->has('demands.data', 1)->where('demands.data.0.id', $mine->id)
|
||||
->where('demands.data.0.can_review', false)->where('demands.data.0.review_unavailable', 'self'));
|
||||
$this->get('/management/education?scope=review&status=reviewed')->assertOk()->assertInertia(fn (Assert $page) => $page->has('demands.data', 1)->where('demands.data.0.id', $other->id)
|
||||
->where('demands.data.0.can_review', true)->where('filters.scope', 'review')->missing('filters.status'));
|
||||
}
|
||||
|
||||
public function test_personal_view_keeps_territorial_catalogue_evidence_from_other_submitters(): void
|
||||
{
|
||||
$this->capacity($this->other);
|
||||
$this->get('/management/education?scope=mine&geo_location_id='.$this->data['geo_location_id'])->assertOk()->assertInertia(fn (Assert $page) => $page
|
||||
->has('capacities.data', 0)->has('providers', 1)->has('courses', 1)->where('courses.0.id', $this->course));
|
||||
}
|
||||
|
||||
public function test_private_open_drafts_are_counted_without_counting_derived_submissions_twice(): void
|
||||
{
|
||||
$input = ['version_no' => 0, 'client_key' => (string) Str::uuid(), 'payload' => []];
|
||||
$this->postJson('/management/education/drafts/demands', $input)->assertOk();
|
||||
$this->demand($this->manager);
|
||||
$payload = $this->data;
|
||||
unset($payload['status']);
|
||||
$payload = [...$payload, 'project_id' => $this->project, 'employer' => 'SYNTHETIC derived employer'];
|
||||
$created = $this->postJson('/management/education/drafts/demands', [...$input, 'client_key' => (string) Str::uuid(), 'payload' => $payload])->assertOk()->json('id');
|
||||
$this->postJson('/management/education/drafts/demands/'.$created.'/submit', ['version_no' => 1, 'payload' => $payload])->assertOk();
|
||||
$this->postJson('/management/education/drafts/demands/'.$created.'/submit', ['version_no' => 1, 'payload' => $payload])->assertOk();
|
||||
$this->actingAsWithMfa($this->other);
|
||||
$this->postJson('/management/education/drafts/demands', [...$input, 'client_key' => (string) Str::uuid()])->assertOk();
|
||||
$this->actingAsWithMfa($this->manager);
|
||||
$this->get('/management/education')->assertInertia(fn (Assert $page) => $page->where('workQueue.drafts', 1)->where('workQueue.demands.total', 2)->has('ownDrafts.data', 2));
|
||||
}
|
||||
|
||||
public function test_detail_preserves_filter_context_and_shows_current_capabilities_and_reference_names(): void
|
||||
{
|
||||
$record = $this->demand($this->other);
|
||||
$this->get('/management/education/demands/'.$record->id.'?scope=review&q=SYNTHETIC&demand_page=2')->assertOk()->assertHeader('Cache-Control', 'no-store, private')
|
||||
->assertInertia(fn (Assert $page) => $page->component('education/declaration')->where('actorId', $this->manager->id)->where('declaration.can_review', true)
|
||||
->where('declaration.submitted_by_name', 'SYNTHETIC other submitter')->where('references.project', 'SYNTHETIC project')->where('references.location', 'SYNTHETIC province')
|
||||
->where('backUrl', function (string $url): bool {
|
||||
parse_str(parse_url($url, PHP_URL_QUERY) ?? '', $query);
|
||||
|
||||
return str_starts_with($url, '/management/education?') && $query == ['scope' => 'review', 'q' => 'SYNTHETIC', 'demand_page' => '2'];
|
||||
}));
|
||||
}
|
||||
|
||||
public function test_same_decision_key_replays_without_another_decision_version_or_business_event(): void
|
||||
{
|
||||
$record = $this->demand($this->other);
|
||||
$url = '/management/education/demands/'.$record->id.'/review';
|
||||
$data = $this->decision();
|
||||
$this->post($url, $data)->assertRedirect();
|
||||
$events = DB::table('audit_events')->where('entity_type', 'labour_demands')->count();
|
||||
$this->post($url, $data)->assertRedirect();
|
||||
$this->assertSame(2, $record->fresh()->version_no);
|
||||
$this->assertSame($events, DB::table('audit_events')->where('entity_type', 'labour_demands')->count());
|
||||
$this->get('/management/education/demands/'.$record->id)->assertInertia(fn (Assert $page) => $page->has('declaration.review_context.commands', 1)
|
||||
->where('declaration.review_context.commands.0.key', $data['client_key'])->where('declaration.review_context.commands.0.version', 2)
|
||||
->missing('declaration.review_context.commands.0.hash'));
|
||||
}
|
||||
|
||||
public function test_used_key_with_different_data_and_fresh_key_with_stale_version_are_rejected(): void
|
||||
{
|
||||
$record = $this->capacity($this->other);
|
||||
$url = '/management/education/capacities/'.$record->id.'/review';
|
||||
$data = $this->decision();
|
||||
$this->post($url, $data)->assertRedirect();
|
||||
$this->postJson($url, [...$data, 'status' => 'rejected'])->assertConflict();
|
||||
$this->postJson($url, [...$data, 'client_key' => (string) Str::uuid()])->assertConflict();
|
||||
$this->assertSame('reviewed', $record->fresh()->status);
|
||||
$this->assertSame(2, $record->fresh()->version_no);
|
||||
}
|
||||
|
||||
public function test_self_review_and_expired_new_decisions_are_denied_while_reading_remains_available(): void
|
||||
{
|
||||
$own = $this->demand($this->manager);
|
||||
$expired = $this->capacity($this->other, ['valid_until' => today()->subDay()->toDateString()]);
|
||||
$this->postJson('/management/education/demands/'.$own->id.'/review', $this->decision())->assertForbidden();
|
||||
$this->postJson('/management/education/capacities/'.$expired->id.'/review', $this->decision())->assertUnprocessable();
|
||||
$this->get('/management/education/capacities/'.$expired->id)->assertOk()->assertInertia(fn (Assert $page) => $page->where('declaration.can_review', false)->where('declaration.review_unavailable', 'expired'));
|
||||
}
|
||||
|
||||
public function test_replay_after_expiry_confirms_the_old_decision_without_extending_validity(): void
|
||||
{
|
||||
$record = $this->demand($this->other);
|
||||
$url = '/management/education/demands/'.$record->id.'/review';
|
||||
$data = $this->decision();
|
||||
$this->post($url, $data)->assertRedirect();
|
||||
$before = $record->fresh()->getAttributes();
|
||||
$this->travel(2)->years();
|
||||
$this->post($url, $data)->assertRedirect();
|
||||
$this->assertSame($before, $record->fresh()->getAttributes());
|
||||
$this->postJson($url, [...$data, 'client_key' => (string) Str::uuid(), 'version_no' => 2])->assertUnprocessable();
|
||||
}
|
||||
|
||||
public function test_replay_requires_current_access_and_command_metadata_is_private_to_its_actor(): void
|
||||
{
|
||||
$record = $this->demand($this->other);
|
||||
$url = '/management/education/demands/'.$record->id.'/review';
|
||||
$data = $this->decision();
|
||||
$this->post($url, $data)->assertRedirect();
|
||||
$this->actingAsWithMfa($this->other);
|
||||
$this->get('/management/education/demands/'.$record->id)->assertOk()->assertInertia(fn (Assert $page) => $page->has('declaration.review_context.commands', 0));
|
||||
$this->actingAsWithMfa($this->manager);
|
||||
config(['portal.managers' => [$this->other->email]]);
|
||||
$this->postJson($url, $data)->assertForbidden();
|
||||
$this->get('/management/education/demands/'.$record->id)->assertForbidden();
|
||||
$this->assertSame(2, $record->fresh()->version_no);
|
||||
}
|
||||
|
||||
public function test_legacy_review_contract_and_public_scope_are_preserved(): void
|
||||
{
|
||||
$record = $this->demand($this->other);
|
||||
$data = $this->decision();
|
||||
unset($data['client_key']);
|
||||
$url = '/management/education/demands/'.$record->id.'/review';
|
||||
$this->post($url, $data)->assertRedirect();
|
||||
$this->postJson($url, $data)->assertConflict();
|
||||
$this->assertSame(1, DB::table('audit_events')->where('source_system', 'portal-education-review')->count());
|
||||
$event = json_decode(DB::table('audit_events')->where('source_system', 'portal-education-review')->value('after_data'), true);
|
||||
$this->assertNull($event['education_review']['key']);
|
||||
$this->actingAsWithMfa(User::factory()->create());
|
||||
$this->get('/management/education')->assertForbidden();
|
||||
$this->get('/management/education/demands/'.$record->id)->assertForbidden();
|
||||
config(['education.enabled' => false]);
|
||||
$this->actingAsWithMfa($this->manager);
|
||||
$this->get('/management/education')->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_personal_pagination_keeps_the_other_collection_and_filter_context(): void
|
||||
{
|
||||
for ($i = 0; $i < 22; $i++) {
|
||||
$this->demand($this->manager);
|
||||
}$this->demand($this->other);
|
||||
$this->get('/management/education?scope=mine&q=SYNTHETIC&capacity_page=3')->assertOk()->assertInertia(fn (Assert $page) => $page->has('demands.data', 20)->where('demands.total', 22)
|
||||
->where('demands.next_page_url', fn (string $url) => str_contains($url, 'scope=mine') && str_contains($url, 'capacity_page=3') && str_contains($url, 'demand_page=2')));
|
||||
}
|
||||
|
||||
public function test_an_old_receipt_does_not_overwrite_a_later_independent_decision(): void
|
||||
{
|
||||
$record = $this->demand($this->other);
|
||||
$url = '/management/education/demands/'.$record->id.'/review';
|
||||
$original = $this->decision();
|
||||
$this->post($url, $original)->assertRedirect();
|
||||
$third = User::factory()->create();
|
||||
config(['portal.managers' => [$this->manager->email, $this->other->email, $third->email]]);
|
||||
$this->actingAsWithMfa($third);
|
||||
$this->post($url, [...$this->decision(), 'version_no' => 2, 'status' => 'rejected'])->assertRedirect();
|
||||
$before = $record->fresh()->getAttributes();
|
||||
$this->actingAsWithMfa($this->manager);
|
||||
$this->post($url, $original)->assertRedirect();
|
||||
$this->assertSame($before, $record->fresh()->getAttributes());
|
||||
$this->get('/management/education/demands/'.$record->id)->assertInertia(fn (Assert $page) => $page->where('declaration.version_no', 3)->where('declaration.status', 'rejected')
|
||||
->where('declaration.review_context.commands.0.version', 2)->has('declaration.review_context.commands', 1));
|
||||
}
|
||||
|
||||
public function test_current_declarations_remain_available_without_the_optional_draft_table(): void
|
||||
{
|
||||
Schema::rename('education_declaration_drafts', 'education_declaration_drafts_not_installed');
|
||||
$record = $this->demand($this->other);
|
||||
$this->get('/management/education?scope=review')->assertOk()->assertInertia(fn (Assert $page) => $page->where('workQueue.drafts', null)->where('workQueue.demands.to_review', 1)->has('demands.data', 1));
|
||||
$this->post('/management/education/demands/'.$record->id.'/review', $this->decision())->assertRedirect();
|
||||
}
|
||||
|
||||
public function test_review_history_preserves_encrypted_subject_and_previous_reason_without_exposing_command_metadata(): void
|
||||
{
|
||||
$record = $this->demand($this->other, ['review_reason' => 'PRIVATE SYNTHETIC previous legacy reason']);
|
||||
$data = $this->decision();
|
||||
$this->post('/management/education/demands/'.$record->id.'/review', $data)->assertRedirect();
|
||||
$raw = DB::table('audit_events')->where('source_system', 'portal-education-review')->value('after_data');
|
||||
$this->assertStringNotContainsString($data['review_reason'], $raw);
|
||||
$this->assertStringNotContainsString('PRIVATE SYNTHETIC previous legacy reason', $raw);
|
||||
$envelope = json_decode($raw, true)['education_review'];
|
||||
$snapshot = json_decode(Crypt::decryptString($envelope['snapshot']), true);
|
||||
$this->assertSame($record->id, $snapshot['subject']['id']);
|
||||
$this->assertSame('PRIVATE SYNTHETIC previous legacy reason', $snapshot['before']['review_reason']);
|
||||
$this->assertSame($data['review_reason'], $snapshot['after']['review_reason']);
|
||||
$this->get('/management/education/demands/'.$record->id)->assertOk()->assertInertia(fn (Assert $page) => $page->has('history.data', 1)
|
||||
->where('history.data.0.available', true)->where('history.data.0.reason', $data['review_reason'])->where('history.data.0.previous_reason', 'PRIVATE SYNTHETIC previous legacy reason')
|
||||
->missing('history.data.0.snapshot')->missing('history.data.0.key')->missing('history.data.0.hash'));
|
||||
}
|
||||
|
||||
public function test_review_history_paginates_versions_and_keeps_unreadable_originals_without_inventing_reasons(): void
|
||||
{
|
||||
$record = $this->capacity($this->other);
|
||||
for ($version = 1; $version <= 12; $version++) {
|
||||
$this->post('/management/education/capacities/'.$record->id.'/review', [...$this->decision(), 'version_no' => $version])->assertRedirect();
|
||||
}
|
||||
$demand = $this->demand($this->other);
|
||||
$this->post('/management/education/demands/'.$demand->id.'/review', $this->decision())->assertRedirect();
|
||||
$this->get('/management/education/capacities/'.$record->id.'?scope=review&q=SYNTHETIC')->assertOk()->assertInertia(fn (Assert $page) => $page
|
||||
->has('history.data', 10)->where('history.total', 12)->where('history.data.0.version', 13)->where('history.data.9.version', 4)
|
||||
->where('history.next_page_url', fn (string $url) => str_contains($url, 'scope=review') && str_contains($url, 'history_page=2')));
|
||||
DB::table('audit_events')->insert(['source_system' => 'portal-education-review', 'entity_type' => 'training_capacities', 'entity_id' => $record->id, 'actor_user_id' => $this->manager->id, 'action' => 'review_committed', 'data_classification' => 'restricted',
|
||||
'after_data' => json_encode(['education_review' => ['version' => 14, 'snapshot' => 'SYNTHETIC unreadable ciphertext']])]);
|
||||
$this->get('/management/education/capacities/'.$record->id)->assertOk()->assertInertia(fn (Assert $page) => $page->where('history.data.0.available', false)->where('history.data.0.reason', null)->where('history.data.0.version', 14));
|
||||
$this->get('/management/education/capacities/'.$record->id.'?history_page=2')->assertOk()->assertInertia(fn (Assert $page) => $page->has('history.data', 3)->where('history.data.0.version', 4)->where('history.data.2.version', 2));
|
||||
$this->assertSame(14, DB::table('audit_events')->where('source_system', 'portal-education-review')->count());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\InvestmentGuides;
|
||||
use App\Services\InvestorContext;
|
||||
use App\Services\VirtualDesk;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class InvestmentGuidesTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $owner;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
config(['investor-path.enabled' => true, 'investmoz_ai.enabled' => false, 'suitecrm.enabled' => false, 'portal.notifications_enabled' => false]);
|
||||
Http::preventStrayRequests();
|
||||
$this->owner = User::factory()->create();
|
||||
}
|
||||
|
||||
private function dossier(): string
|
||||
{
|
||||
return $this->actingAs($this->owner)->postJson('/investimentos', ['title' => 'SYNTHETIC capitalisation', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertCreated()->json('id');
|
||||
}
|
||||
|
||||
private function url(string $id): string
|
||||
{
|
||||
return '/investimentos/'.$id.'/guias/capitalizacao';
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function input(string $id, array $extra = []): array
|
||||
{
|
||||
return [...['version' => DB::table('desk_cases')->where('id', $id)->value('version'), 'operation_key' => (string) Str::uuid(), 'sha256' => app(InvestmentGuides::class)->guide('capitalizacao')['sha256'], 'instruments' => ['private_equity', 'debt'], 'note' => 'SYNTHETIC private preparation'], ...$extra];
|
||||
}
|
||||
|
||||
public function test_public_source_versioned_guide_requires_neither_login_nor_ia_and_does_not_capture_private_notes(): void
|
||||
{
|
||||
$this->getJson('/guias-investimento/capitalizacao?note=PRIVATE')->assertOk()->assertHeader('Cache-Control', 'no-store, private')
|
||||
->assertJsonPath('note', '')->assertJsonPath('case', null)->assertJsonCount(4, 'guide.instruments')->assertJsonCount(5, 'guide.sources')
|
||||
->assertJsonPath('guide.sources.bni.sha256', 'fbeaab84c4cad22ee63e5c1dfb61ea3206333885ddd80c8001d37a3f49d2820e')
|
||||
->assertJsonPath('guide.sources.ifc_apply.locator', 'Eligibility; Investment Proposals, pontos 1–7');
|
||||
$this->get('/guias-investimento/capitalizacao')->assertOk()->assertInertia(fn ($page) => $page->component('investment/guide'));
|
||||
$this->assertDatabaseCount('desk_cases', 0);
|
||||
$this->assertDatabaseCount('organizations', 0);
|
||||
$this->getJson('/guias-investimento/invented')->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_instrument_choices_are_coded_and_source_pin_survives_normal_authentication_and_dossier_choice(): void
|
||||
{
|
||||
$guide = app(InvestmentGuides::class)->guide('capitalizacao');
|
||||
$selection = ['slug' => 'capitalizacao', 'sha256' => $guide['sha256'], 'instruments' => ['private_equity', 'debt', 'debt']];
|
||||
$this->getJson('/guias-investimento/capitalizacao?'.http_build_query($selection))->assertOk()->assertJsonPath('instruments', ['debt', 'private_equity']);
|
||||
$this->getJson('/guias-investimento/capitalizacao?instruments[0]=invented')->assertUnprocessable();
|
||||
$this->getJson('/guias-investimento/capitalizacao?instruments=debt')->assertUnprocessable();
|
||||
$target = '/investimentos?'.http_build_query(['investment_guide' => $selection]);
|
||||
$this->get($target)->assertRedirect('/login');
|
||||
$this->assertSame(url($target), session('url.intended'));
|
||||
$id = $this->dossier();
|
||||
$this->getJson($target)->assertOk()->assertJsonPath('guideSelection.instruments', ['debt', 'private_equity']);
|
||||
$this->getJson($this->url($id).'?'.http_build_query(['current' => 1, ...$selection]))->assertOk()->assertJsonPath('workingCopy', true)->assertJsonPath('saved', null);
|
||||
$new = $this->postJson('/investimentos', ['title' => 'SYNTHETIC chosen guide destination', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true, 'investment_guide' => $selection])->assertCreated()->json();
|
||||
$this->getJson($new['guide_href'])->assertOk()->assertJsonPath('instruments', ['debt', 'private_equity'])->assertJsonPath('saved', null);
|
||||
$this->assertSame(0, DB::table('desk_events')->where('action', InvestmentGuides::EVENT)->count());
|
||||
$before = DB::table('desk_cases')->count();
|
||||
$this->postJson('/investimentos', ['title' => 'SYNTHETIC invalid guide', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true, 'investment_guide' => [...$selection, 'sha256' => str_repeat('0', 64)]])->assertConflict();
|
||||
$this->assertSame($before, DB::table('desk_cases')->count());
|
||||
}
|
||||
|
||||
public function test_private_reference_is_encrypted_scoped_versioned_idempotent_and_does_not_advance_any_finance_stage(): void
|
||||
{
|
||||
$id = $this->dossier();
|
||||
$url = $this->url($id);
|
||||
$steps = DB::table('journey_steps')->orderBy('id')->get()->toJson();
|
||||
$before = app(VirtualDesk::class)->decode(DB::table('desk_cases')->where('id', $id)->value('payload'));
|
||||
$input = $this->input($id, ['guide' => ['title' => 'FORGED guarantee'], 'instruments' => ['debt', 'private_equity']]);
|
||||
$this->postJson($url, $input)->assertOk()->assertJsonPath('revision', 1);
|
||||
$this->postJson($url, $input)->assertOk()->assertJsonPath('replayed', true);
|
||||
$this->postJson($url, [...$input, 'note' => 'SYNTHETIC changed body'])->assertConflict();
|
||||
$this->postJson($url, [...$input, 'operation_key' => (string) Str::uuid()])->assertConflict();
|
||||
$this->postJson($url, $this->input($id))->assertOk()->assertJsonPath('unchanged', true);
|
||||
$r = $this->getJson($url)->assertOk()->assertJsonPath('saved.scope', 'dossier_reference')->assertJsonPath('note', 'SYNTHETIC private preparation')->json();
|
||||
$this->assertSame(app(InvestmentGuides::class)->guide('capitalizacao'), $r['guide']);
|
||||
$stored = DB::table('desk_cases')->where('id', $id)->first();
|
||||
$this->assertStringNotContainsString('SYNTHETIC private preparation', $stored->payload);
|
||||
$payload = app(VirtualDesk::class)->decode($stored->payload);
|
||||
unset($payload['investment_guides']);
|
||||
$this->assertSame($before, $payload);
|
||||
$event = DB::table('desk_events')->where('case_id', $id)->where('action', InvestmentGuides::EVENT)->first();
|
||||
$this->assertStringNotContainsString('SYNTHETIC private preparation', $event->payload);
|
||||
$this->assertStringNotContainsString('SYNTHETIC private preparation', DB::table('audit_events')->where('entity_id', $id)->get()->toJson());
|
||||
$this->assertSame($steps, DB::table('journey_steps')->orderBy('id')->get()->toJson());
|
||||
$this->assertDatabaseCount('desk_requests', 0);
|
||||
$this->assertDatabaseCount('investment_company_declarations', 0);
|
||||
$this->assertSame(1, DB::table('desk_events')->where('action', InvestmentGuides::EVENT)->count());
|
||||
$this->getJson($url.'?'.http_build_query(['current' => 1, 'selection' => 1, 'sha256' => $r['guide']['sha256']]))->assertOk()->assertJsonPath('instruments', [])->assertJsonPath('workingCopy', true)->assertJsonPath('saved.instruments', ['debt', 'private_equity']);
|
||||
DB::table('desk_cases')->where('id', $id)->update(['closed_at' => now()]);
|
||||
$this->postJson($url, $input)->assertOk()->assertJsonPath('replayed', true);
|
||||
$this->postJson($url, $this->input($id))->assertConflict();
|
||||
}
|
||||
|
||||
public function test_source_editions_and_notes_remain_recoverable_after_updates_or_withdrawal_and_replays_use_original_choices(): void
|
||||
{
|
||||
$id = $this->dossier();
|
||||
$url = $this->url($id);
|
||||
$input = $this->input($id);
|
||||
$this->postJson($url, $input)->assertOk();
|
||||
$first = $this->getJson($url)->json();
|
||||
config(['investment-guides.capitalizacao.version' => 'SYNTHETIC future', 'investment-guides.capitalizacao.instruments.debt' => null]);
|
||||
$this->postJson($url, $input)->assertOk()->assertJsonPath('replayed', true);
|
||||
$this->getJson($url)->assertJsonPath('olderEdition', true)->assertJsonPath('guide', $first['guide']);
|
||||
$this->postJson($url, [...$input, 'version' => $first['case']['version'], 'operation_key' => (string) Str::uuid()])->assertConflict();
|
||||
config(['investment-guides.capitalizacao.instruments' => ['private_equity' => $first['guide']['instruments']['private_equity']]]);
|
||||
$this->getJson($url.'?current=1')->assertOk()->assertJsonPath('unavailableInstruments', [$first['guide']['instruments']['debt']['title']])->assertJsonPath('note', $first['note']);
|
||||
$this->postJson($url, $this->input($id, ['instruments' => ['private_equity'], 'note' => 'SYNTHETIC new edition']))->assertOk()->assertJsonPath('revision', 2);
|
||||
$this->getJson($url.'?revision='.$first['history'][0]['id'])->assertOk()->assertJsonPath('guide', $first['guide'])->assertJsonPath('note', $first['note']);
|
||||
config(['investment-guides.capitalizacao' => null]);
|
||||
$this->getJson('/guias-investimento/capitalizacao')->assertNotFound();
|
||||
$this->getJson($url)->assertOk()->assertJsonPath('currentAvailable', false)->assertJsonPath('note', 'SYNTHETIC new edition');
|
||||
$this->getJson($url.'?current=1')->assertConflict();
|
||||
$this->postJson($url, $input)->assertOk()->assertJsonPath('replayed', true);
|
||||
}
|
||||
|
||||
public function test_pagination_preserves_every_revision_and_rejects_another_dossiers_history_identifier(): void
|
||||
{
|
||||
$id = $this->dossier();
|
||||
$url = $this->url($id);
|
||||
for ($i = 1; $i <= 26; $i++) {
|
||||
$this->postJson($url, $this->input($id, ['note' => 'SYNTHETIC note '.$i]))->assertOk();
|
||||
}
|
||||
$r = $this->getJson($url)->assertJsonCount(25, 'history')->json();
|
||||
$old = $this->getJson($url.'?history_before='.$r['historyNext'])->assertJsonCount(1, 'history')->json();
|
||||
$revision = $old['history'][0]['id'];
|
||||
$this->getJson($url.'?revision='.$revision)->assertOk()->assertJsonPath('saved.revision', 1)->assertJsonPath('historical', true);
|
||||
$this->getJson($url.'?revision='.$revision.'¤t=1')->assertUnprocessable();
|
||||
$other = $this->dossier();
|
||||
$this->getJson($this->url($other).'?revision='.$revision)->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_context_changes_are_explicit_without_rewriting_the_previous_reference(): void
|
||||
{
|
||||
$id = $this->dossier();
|
||||
$url = $this->url($id);
|
||||
$this->postJson($url, $this->input($id))->assertOk();
|
||||
$r = $this->getJson($url)->assertJsonPath('contextChanged', false)->json();
|
||||
$case = DB::table('desk_cases')->where('id', $id)->first();
|
||||
$payload = app(VirtualDesk::class)->decode($case->payload);
|
||||
$payload['investor_path']['context'] = app(InvestorContext::class)->state($case);
|
||||
$payload['investor_path']['context']['revision'] = 99;
|
||||
$payload['investor_path']['context']['fields']['project_title'] = 'SYNTHETIC changed scope';
|
||||
DB::table('desk_cases')->where('id', $id)->update(['payload' => app(VirtualDesk::class)->encode($payload)]);
|
||||
$this->getJson($url)->assertJsonPath('contextChanged', true)->assertJsonPath('saved.context', $r['saved']['context']);
|
||||
}
|
||||
|
||||
public function test_revocation_and_read_only_membership_are_effective_before_replay_or_validation(): void
|
||||
{
|
||||
$id = $this->dossier();
|
||||
$url = $this->url($id);
|
||||
$org = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $org, 'name' => 'SYNTHETIC financing organization', 'organization_type' => 'private']);
|
||||
DB::table('desk_cases')->where('id', $id)->update(['organization_id' => $org]);
|
||||
$editor = User::factory()->create();
|
||||
$viewer = User::factory()->create();
|
||||
foreach ([[$this->owner, 'officer'], [$editor, 'officer'], [$viewer, 'viewer']] as [$actor, $role]) {
|
||||
DB::table('memberships')->insert(['id' => (string) Str::uuid(), 'organization_id' => $org, 'user_id' => $actor->id, 'role' => $role]);
|
||||
}
|
||||
$input = $this->input($id);
|
||||
$this->actingAs($editor)->postJson($url, $input)->assertOk();
|
||||
$this->actingAs($viewer)->getJson($url)->assertOk()->assertJsonPath('canWrite', false);
|
||||
$this->postJson($url, $input)->assertForbidden();
|
||||
DB::table('memberships')->where('organization_id', $org)->where('user_id', $editor->id)->update(['deleted_at' => now()]);
|
||||
$this->actingAs($editor)->getJson($url)->assertForbidden();
|
||||
$this->postJson($url, $input)->assertForbidden();
|
||||
$this->postJson($url, [])->assertForbidden();
|
||||
$this->assertSame(1, DB::table('desk_events')->where('action', InvestmentGuides::EVENT)->count());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Str;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class InvestmentProfileCommandsTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
Http::fake();
|
||||
Mail::fake();
|
||||
$this->actingAs(User::factory()->create());
|
||||
}
|
||||
|
||||
private function company(): array
|
||||
{
|
||||
return ['version' => 0, 'operation_key' => (string) Str::uuid(), 'payload' => ['name' => 'SYNTHETIC private company', 'incorporation_country_code' => 'MZ', 'role' => 'SYNTHETIC declared representative']];
|
||||
}
|
||||
|
||||
public function test_new_company_replay_returns_the_original_identity_and_preserves_ciphertext_and_audit(): void
|
||||
{
|
||||
$command = $this->company();
|
||||
$first = $this->postJson('/api/v1/investment/companies', $command)->assertOk()->json();
|
||||
$cipher = DB::table('investment_company_declarations')->value('payload');
|
||||
$events = DB::table('audit_events')->count();
|
||||
$this->postJson('/api/v1/investment/companies', $command)->assertExactJson($first);
|
||||
$this->assertSame(1, DB::table('investment_company_declarations')->count());
|
||||
$this->assertSame($cipher, DB::table('investment_company_declarations')->value('payload'));
|
||||
$this->assertSame($events, DB::table('audit_events')->count());
|
||||
$this->assertSame(0, DB::table('organizations')->count());
|
||||
$this->assertSame(0, DB::table('memberships')->count());
|
||||
$record = DB::table('audit_events')->where('source_system', 'investment-workspace-command')->sole();
|
||||
$this->assertStringNotContainsString('SYNTHETIC private company', $record->after_data);
|
||||
$metadata = json_decode($record->after_data, true);
|
||||
$this->assertSame('SYNTHETIC private company', json_decode(Crypt::decryptString($metadata['command_encrypted']), true)['payload']['name']);
|
||||
}
|
||||
|
||||
public function test_key_reuse_with_changed_content_is_a_conflict_and_cannot_change_the_original(): void
|
||||
{
|
||||
$command = $this->company();
|
||||
$id = $this->postJson('/api/v1/investment/companies', $command)->assertOk()->json('id');
|
||||
$before = DB::table('investment_company_declarations')->where('id', $id)->first();
|
||||
$this->postJson('/api/v1/investment/companies', [...$command, 'payload' => [...$command['payload'], 'name' => 'SYNTHETIC changed']])->assertConflict();
|
||||
$this->assertEquals($before, DB::table('investment_company_declarations')->where('id', $id)->first());
|
||||
}
|
||||
|
||||
public function test_profile_commands_validate_iso_replay_without_increment_and_preserve_historical_country(): void
|
||||
{
|
||||
$command = ['version' => 0, 'operation_key' => (string) Str::uuid(), 'payload' => ['residence_country_code' => 'PT', 'country' => 'Historical country', 'phone' => 'SYNTHETIC-contact']];
|
||||
$this->putJson('/api/v1/investment/profile', $command)->assertExactJson(['version' => 1]);
|
||||
$before = DB::table('investment_accounts')->first();
|
||||
$this->putJson('/api/v1/investment/profile', ['payload' => array_reverse($command['payload'], true), 'operation_key' => strtoupper($command['operation_key']), 'version' => 0])->assertExactJson(['version' => 1]);
|
||||
$this->assertEquals($before, DB::table('investment_accounts')->first());
|
||||
$this->putJson('/api/v1/investment/profile', ['version' => 1, 'operation_key' => (string) Str::uuid(), 'payload' => ['residence_country_code' => 'ZZ']])->assertUnprocessable()->assertJsonValidationErrors('payload.residence_country_code');
|
||||
$this->getJson('/api/v1/investment/profile')->assertOk()->assertJsonPath('account.version', 1)->assertJsonPath('account.payload.residence_country_code', 'PT')->assertJsonPath('account.payload.country', 'Historical country')->assertHeader('Cache-Control', 'no-store, private');
|
||||
$this->get('/investidor/profile')->assertOk()->assertHeader('Cache-Control', 'no-store, private')->assertInertia(fn (Assert $page) => $page->component('investment/profile')->where('actorId', auth()->id())->where('account.payload.residence_country_code', 'PT'));
|
||||
$this->assertEquals($before, DB::table('investment_accounts')->first());
|
||||
}
|
||||
|
||||
public function test_replay_after_later_updates_returns_the_original_receipt_without_reverting_current_data(): void
|
||||
{
|
||||
$command = $this->company();
|
||||
$id = $this->postJson('/api/v1/investment/companies', $command)->assertOk()->json('id');
|
||||
$update = ['version' => 1, 'operation_key' => (string) Str::uuid(), 'payload' => [...$command['payload'], 'name' => 'SYNTHETIC newer name']];
|
||||
$this->postJson('/api/v1/investment/companies/'.$id, $update)->assertJsonPath('version', 2);
|
||||
$before = DB::table('investment_company_declarations')->where('id', $id)->first();
|
||||
$this->postJson('/api/v1/investment/companies', $command)->assertExactJson(['id' => $id, 'version' => 1]);
|
||||
$this->postJson('/api/v1/investment/companies/'.$id, $update)->assertExactJson(['id' => $id, 'version' => 2]);
|
||||
$this->assertEquals($before, DB::table('investment_company_declarations')->where('id', $id)->first());
|
||||
$this->postJson('/api/v1/investment/companies/'.$id, [...$update, 'operation_key' => (string) Str::uuid()])->assertConflict();
|
||||
}
|
||||
|
||||
public function test_commands_are_private_per_actor_and_do_not_identify_companies_by_name(): void
|
||||
{
|
||||
$command = $this->company();
|
||||
$id = $this->postJson('/api/v1/investment/companies', $command)->assertOk()->json('id');
|
||||
$this->actingAs(User::factory()->create());
|
||||
$otherId = $this->postJson('/api/v1/investment/companies', $command)->assertOk()->json('id');
|
||||
$this->assertNotSame($id, $otherId);
|
||||
$this->postJson('/api/v1/investment/companies/'.$id, [...$command, 'version' => 1])->assertNotFound();
|
||||
$this->getJson('/api/v1/investment/profile')->assertJsonCount(1, 'companies')->assertJsonPath('companies.0.id', $otherId);
|
||||
$this->assertSame(2, DB::table('investment_company_declarations')->count());
|
||||
}
|
||||
|
||||
public function test_malformed_keys_are_rejected_before_any_write_and_legacy_requests_remain_supported(): void
|
||||
{
|
||||
$command = $this->company();
|
||||
$this->postJson('/api/v1/investment/companies', [...$command, 'operation_key' => 'bad'])->assertUnprocessable()->assertJsonValidationErrors('operation_key');
|
||||
$this->assertSame(0, DB::table('investment_company_declarations')->count());
|
||||
unset($command['operation_key']);
|
||||
$this->postJson('/api/v1/investment/companies', $command)->assertOk();
|
||||
$this->assertSame(1, DB::table('investment_company_declarations')->count());
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ use App\Services\OpportunityCanonicalValue;
|
||||
use App\Services\OpportunityCategoryFields;
|
||||
use App\Services\OpportunityCompleteness;
|
||||
use App\Services\OpportunityManagement;
|
||||
use App\Services\OpportunityMaturity;
|
||||
use App\Services\OpportunityModularProfiles;
|
||||
use App\Services\OpportunityReviewMateriality;
|
||||
use App\Services\PortalProfileAccess;
|
||||
@@ -23,6 +24,7 @@ use Illuminate\Support\Facades\URL;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use Tests\TestCase;
|
||||
|
||||
class OpportunityCanonicalWorkflowTest extends TestCase
|
||||
@@ -424,6 +426,124 @@ class OpportunityCanonicalWorkflowTest extends TestCase
|
||||
$this->assertNotSame($before['approval']['review_cycle'], $published['approval']['review_cycle']);
|
||||
}
|
||||
|
||||
/** @return array<string,array{string,int,string}> */
|
||||
public static function maturityStages(): array
|
||||
{
|
||||
$cases = [];
|
||||
foreach (OpportunityMaturity::STAGES as $stage => $label) {
|
||||
$cases[$stage] = [$stage, count($cases) + 1, $label];
|
||||
}
|
||||
|
||||
return $cases;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $payload */
|
||||
private function maturityLocation(array $payload): void
|
||||
{
|
||||
$location = json_decode(DB::table('opportunity_location_drafts')->where('id', $payload['locations'][0])->value('payload'), true);
|
||||
$country = (string) Str::uuid();
|
||||
DB::table('geo_locations')->insert(['id' => $country, 'code' => $country, 'name' => 'Synthetic QA maturity country', 'location_type' => 'country',
|
||||
'data_classification' => 'public', 'source_system' => 'cartografia-workbook',
|
||||
'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:'.$country]);
|
||||
DB::table('geo_locations')->where('id', $location['province_id'])->update(['parent_id' => $country]);
|
||||
foreach ([$location['province_id'], $location['district_id']] as $territory) {
|
||||
DB::table('geo_locations')->where('id', $territory)->update(['data_classification' => 'public', 'source_system' => 'cartografia-workbook',
|
||||
'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:'.$territory]);
|
||||
}
|
||||
}
|
||||
|
||||
#[DataProvider('maturityStages')]
|
||||
public function test_clearing_an_optional_stage_does_not_reinterpret_its_published_number_as_historical(string $stage, int $position, string $label): void
|
||||
{
|
||||
[$id, $promoter, $validator, $publisher, $payload, $document] = $this->fixture();
|
||||
$this->maturityLocation($payload);
|
||||
$payload['maturity_stage'] = $stage;
|
||||
if ($position >= 4) {
|
||||
$payload['financial_indicators'] = ['npv' => 123, 'irr' => 6, 'payback_years' => 5, 'horizon_years' => 10,
|
||||
'discount_rate' => 7, 'currency' => 'MZN', 'scenario' => 'SYNTHETIC policy fixture, not a real financial model', 'model_document_id' => $document];
|
||||
}
|
||||
foreach ([1, 2] as $cycle) {
|
||||
$this->loginFixture($promoter)->putJson('/minhas-oportunidades/'.$id.'/draft', [
|
||||
'etag' => app(OpportunityManagement::class)->etag(Opportunity::findOrFail($id)),
|
||||
'canonical' => $payload, 'reason' => self::REASON,
|
||||
])->assertOk();
|
||||
$this->assertSame($payload['maturity_stage'], app(OpportunityManagement::class)->values(Opportunity::findOrFail($id))['canonical']['maturity_stage']);
|
||||
$this->action($promoter, $id, 'submit');
|
||||
$this->action($validator, $id, 'start_review');
|
||||
foreach (['property_review', 'registry_urban_review', 'building_compliance_review'] as $gate) {
|
||||
$this->action($validator, $id, 'review_gate', ['gate' => $gate, 'gate_decision' => 'approved', 'evidence_document_ids' => [$document]]);
|
||||
}
|
||||
$this->action($validator, $id, 'approve');
|
||||
$this->action($publisher, $id, 'publish');
|
||||
$record = Opportunity::findOrFail($id);
|
||||
$this->assertSame($cycle === 1 ? $position : null, $record->maturity_level);
|
||||
$this->assertSame($cycle === 1 ? $label : null, $record->maturity_label);
|
||||
$this->assertEquals(['catalogue_version' => OpportunityMaturity::VERSION, 'stage' => $cycle === 1 ? $stage : null,
|
||||
'level' => $cycle === 1 ? $position : null, 'label' => $cycle === 1 ? $label : null], data_get($record->workflow_context, 'publication.maturity'));
|
||||
$query = Opportunity::whereKey($id);
|
||||
OpportunityMaturity::constrainSearch($query, 'historical:'.$position);
|
||||
$this->assertSame(0, $query->count());
|
||||
$query = Opportunity::whereKey($id);
|
||||
OpportunityMaturity::constrainSearch($query, 'stage:'.$stage);
|
||||
$this->assertSame($cycle === 1 ? 1 : 0, $query->count());
|
||||
$this->assertSame(0, Opportunity::published()->whereKey($id)->count());
|
||||
if ($cycle === 1) {
|
||||
$this->action($publisher, $id, 'suspend');
|
||||
$this->action($promoter, $id, 'request_revision');
|
||||
$payload['maturity_stage'] = null;
|
||||
}
|
||||
}
|
||||
$this->assertSame($stage, data_get($record->workflow_context, 'publication_history.0.maturity.stage'));
|
||||
}
|
||||
|
||||
public function test_unknown_optional_maturity_stage_is_reported_before_review(): void
|
||||
{
|
||||
[$id, $promoter, , , $payload] = $this->fixture();
|
||||
$payload['maturity_stage'] = 'SYNTHETIC-NOT-A-CATALOGUE-STAGE';
|
||||
$this->loginFixture($promoter)->putJson('/minhas-oportunidades/'.$id.'/draft', [
|
||||
'etag' => app(OpportunityManagement::class)->etag(Opportunity::findOrFail($id)),
|
||||
'canonical' => $payload, 'reason' => self::REASON,
|
||||
])->assertUnprocessable()->assertJsonValidationErrors('canonical.maturity_stage');
|
||||
$this->assertSame('draft', Opportunity::findOrFail($id)->status);
|
||||
$this->assertArrayNotHasKey('maturity_stage', app(OpportunityManagement::class)->values(Opportunity::findOrFail($id))['canonical']);
|
||||
}
|
||||
|
||||
/** @return array<int,array{int,string}> */
|
||||
public static function historicalMaturityLevels(): array
|
||||
{
|
||||
$cases = [];
|
||||
foreach (OpportunityMaturity::LEGACY_LABELS as $level => $label) {
|
||||
$cases[] = [$level, $label];
|
||||
}
|
||||
|
||||
return $cases;
|
||||
}
|
||||
|
||||
#[DataProvider('historicalMaturityLevels')]
|
||||
public function test_publication_without_a_maturity_stage_retains_its_legacy_level(int $level, string $label): void
|
||||
{
|
||||
[$id, $promoter, $validator, $publisher, $payload, $document] = $this->fixture();
|
||||
$this->maturityLocation($payload);
|
||||
Opportunity::findOrFail($id)->forceFill(['maturity_level' => $level, 'maturity_label' => $label])->save();
|
||||
$this->action($promoter, $id, 'submit');
|
||||
$this->action($validator, $id, 'start_review');
|
||||
foreach (['property_review', 'registry_urban_review', 'building_compliance_review'] as $gate) {
|
||||
$this->action($validator, $id, 'review_gate', ['gate' => $gate, 'gate_decision' => 'approved', 'evidence_document_ids' => [$document]]);
|
||||
}
|
||||
$this->action($validator, $id, 'approve');
|
||||
$this->action($publisher, $id, 'publish');
|
||||
$record = Opportunity::findOrFail($id);
|
||||
$this->assertSame($level, $record->maturity_level);
|
||||
$this->assertSame($label, $record->maturity_label);
|
||||
$query = Opportunity::whereKey($id);
|
||||
OpportunityMaturity::constrainSearch($query, 'historical:'.$level);
|
||||
$this->assertSame(1, $query->count());
|
||||
$query = Opportunity::whereKey($id);
|
||||
OpportunityMaturity::constrainSearch($query, 'stage:'.array_keys(OpportunityMaturity::STAGES)[$level - 1]);
|
||||
$this->assertSame(0, $query->count());
|
||||
$this->assertSame(0, Opportunity::published()->whereKey($id)->count());
|
||||
}
|
||||
|
||||
public function test_semantic_errors_are_keyed_to_fields_and_incomplete_drafts_remain_recoverable(): void
|
||||
{
|
||||
[$id,$promoter,$validator,$publisher,$payload,$document] = $this->fixture();
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\User;
|
||||
use App\Services\OpportunityManagement;
|
||||
use App\Services\OpportunityTechnicalIncidents;
|
||||
use App\Services\PortalProfileAccess;
|
||||
use App\Services\PortalProfileAdministration;
|
||||
use App\Services\ScopedPortalAdministration;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Testing\TestResponse;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class OpportunityTechnicalIncidentsTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private const REASON = 'SYNTHETIC technical incident preservation test';
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
Http::fake();
|
||||
Mail::fake();
|
||||
Storage::fake('local');
|
||||
config(['portal.profile_access_enabled' => true, 'portal.opportunity_specialized_drafts_enabled' => true, 'suitecrm.enabled' => false, 'investmoz_ai.enabled' => false]);
|
||||
}
|
||||
|
||||
/** @param list<string> $responsibilities */
|
||||
private function actor(string $role, string $org, array $responsibilities = []): User
|
||||
{
|
||||
$actor = User::factory()->create();
|
||||
$actor->forceFill(['two_factor_secret' => Crypt::encryptString('JBSWY3DPEHPK3PXP'), 'two_factor_confirmed_at' => now()])->save();
|
||||
app(PortalProfileAdministration::class)->insertGrant((string) Str::uuid(), User::factory()->create(), ['user_id' => $actor->id, 'role' => $role, 'organization_id' => $role === 'promoter' ? $org : null, 'opportunity_types' => ['real_estate'], 'responsibilities' => $responsibilities, 'source' => 'synthetic-incident-fixture']);
|
||||
|
||||
return $actor;
|
||||
}
|
||||
|
||||
private function loginFixture(User $actor): static
|
||||
{
|
||||
return $this->actingAs($actor)->withSession(['portal.mfa_actor' => $actor->id, 'portal.mfa_at' => time(), 'portal.access_revision' => (int) $actor->portal_access_revision]);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $extra */
|
||||
private function act(User $actor, int $id, string $action, array $extra = []): TestResponse
|
||||
{
|
||||
$record = Opportunity::findOrFail($id);
|
||||
|
||||
return $this->loginFixture($actor)->postJson('/minhas-oportunidades/'.$id.'/workflow', ['etag' => app(OpportunityManagement::class)->etag($record), 'action' => $action, 'reason' => self::REASON, ...$extra]);
|
||||
}
|
||||
|
||||
private function failAudit(string $action, bool $incidentToo = false): void
|
||||
{
|
||||
$source = $incidentToo ? "NEW.source_system = 'portal-opportunity-incident' OR " : '';
|
||||
DB::unprepared("CREATE FUNCTION qa_incident_failure() RETURNS trigger LANGUAGE plpgsql AS \$\$ BEGIN IF ({$source}NEW.action = '{$action}') THEN RAISE EXCEPTION 'PRIVATE SYNTHETIC SQL TOKEN MUST NEVER REACH THE RESPONSE'; END IF; RETURN NEW; END \$\$; CREATE TRIGGER qa_incident_failure BEFORE INSERT ON audit_events FOR EACH ROW EXECUTE FUNCTION qa_incident_failure();");
|
||||
}
|
||||
|
||||
public function test_failed_submission_rolls_back_and_records_only_minimal_private_metadata_then_allows_manual_recovery(): void
|
||||
{
|
||||
[$id,$promoter,$validator] = $this->fixture();
|
||||
$before = Opportunity::findOrFail($id)->getRawOriginal();
|
||||
$taskCount = DB::table('tasks')->count();
|
||||
$this->failAudit('workflow_submit');
|
||||
$response = $this->act($promoter, $id, 'submit')->assertStatus(503)->assertHeader('Cache-Control', 'no-store, private')->assertJsonPath('incident_recorded', true);
|
||||
$reference = $response->json('reference');
|
||||
$this->assertTrue(Str::isUuid($reference));
|
||||
$this->assertStringNotContainsString('SQL TOKEN', $response->getContent());
|
||||
$this->assertSame($before, Opportunity::findOrFail($id)->getRawOriginal());
|
||||
$this->assertSame($taskCount, DB::table('tasks')->count());
|
||||
$event = DB::table('audit_events')->where('id', $reference)->first();
|
||||
$data = json_decode($event->after_data, true)['incident'];
|
||||
$this->assertSame('restricted', $event->data_classification);
|
||||
$this->assertSame($reference, $event->correlation_id);
|
||||
$this->assertSame($id, $data['opportunity_id']);
|
||||
$this->assertSame('submit', $data['operation']);
|
||||
$this->assertSame('database_failure', $data['error_code']);
|
||||
$this->assertArrayNotHasKey('reason', $data);
|
||||
$this->assertArrayNotHasKey('exception', $data);
|
||||
$this->assertArrayNotHasKey('payload', $data);
|
||||
$this->get('/minhas-oportunidades/'.$id.'/view')->assertOk()->assertInertia(fn (Assert $page) => $page->has('workflowIncidents', 1)->where('workflowIncidents.0.reference', $reference)->missing('workflowIncidents.0.attempted_etag'));
|
||||
$this->loginFixture($validator)->get('/minhas-oportunidades/'.$id.'/view')->assertOk()->assertInertia(fn (Assert $page) => $page->has('workflowIncidents', 0));
|
||||
DB::unprepared('DROP TRIGGER qa_incident_failure ON audit_events; DROP FUNCTION qa_incident_failure();');
|
||||
$this->act($promoter, $id, 'submit')->assertOk()->assertJsonPath('status', 'submitted');
|
||||
$this->assertSame(1, DB::table('audit_events')->where('source_system', 'portal-opportunity-incident')->count());
|
||||
$this->assertSame($taskCount + 1, DB::table('tasks')->count());
|
||||
}
|
||||
|
||||
public function test_publication_failure_preserves_approved_content_public_projection_tasks_and_original_decisions(): void
|
||||
{
|
||||
[$id,$promoter,$validator,$publisher,$payload,$document] = $this->fixture();
|
||||
$this->act($promoter, $id, 'submit')->assertOk();
|
||||
$this->act($validator, $id, 'start_review')->assertOk();
|
||||
foreach (['property_review', 'registry_urban_review', 'building_compliance_review'] as $gate) {
|
||||
$this->act($validator, $id, 'review_gate', ['gate' => $gate, 'gate_decision' => 'approved', 'evidence_document_ids' => [$document]])->assertOk();
|
||||
}
|
||||
$this->act($validator, $id, 'approve')->assertOk();
|
||||
$record = Opportunity::findOrFail($id);
|
||||
$before = $record->getRawOriginal();
|
||||
$tasks = DB::table('tasks')->orderBy('id')->get()->toJson();
|
||||
$this->failAudit('workflow_publish');
|
||||
$this->act($publisher, $id, 'publish', ['confirm_publication' => true, 'preview_hash' => $record->workflow_context['approval']['hash']])->assertStatus(503)->assertJsonPath('incident_recorded', true);
|
||||
$this->assertSame($before, Opportunity::findOrFail($id)->getRawOriginal());
|
||||
$this->assertSame($tasks, DB::table('tasks')->orderBy('id')->get()->toJson());
|
||||
$this->assertSame('publish', app(OpportunityTechnicalIncidents::class)->recent($publisher, $record)[0]['operation']);
|
||||
$this->assertSame([], app(OpportunityTechnicalIncidents::class)->recent($promoter, $record));
|
||||
}
|
||||
|
||||
public function test_validation_conflicts_and_permission_failures_are_not_technical_incidents(): void
|
||||
{
|
||||
[$id,$promoter,$validator] = $this->fixture();
|
||||
$this->act($promoter, $id, 'submit', ['reason' => 'short'])->assertUnprocessable();
|
||||
$this->act($promoter, $id, 'submit', ['etag' => str_repeat('0', 64)])->assertConflict();
|
||||
$this->act($validator, $id, 'submit')->assertForbidden();
|
||||
$this->assertSame(0, DB::table('audit_events')->where('source_system', 'portal-opportunity-incident')->count());
|
||||
}
|
||||
|
||||
public function test_a_second_storage_failure_returns_an_honest_reference_without_leaking_sql_or_claiming_a_saved_incident(): void
|
||||
{
|
||||
[$id,$promoter] = $this->fixture();
|
||||
$before = Opportunity::findOrFail($id)->getRawOriginal();
|
||||
$this->failAudit('workflow_submit', true);
|
||||
Log::shouldReceive('warning')->once()->with('Opportunity technical incident could not be stored.', \Mockery::on(fn ($context) => Str::isUuid($context['reference']) && $context['error_code'] === 'database_failure'));
|
||||
$response = $this->act($promoter, $id, 'submit')->assertStatus(503)->assertJsonPath('incident_recorded', false);
|
||||
$this->assertStringNotContainsString('SQL TOKEN', $response->getContent());
|
||||
$this->assertTrue(Str::isUuid($response->json('reference')));
|
||||
$this->assertSame($before, Opportunity::findOrFail($id)->getRawOriginal());
|
||||
$this->assertSame(0, DB::table('audit_events')->where('source_system', 'portal-opportunity-incident')->count());
|
||||
}
|
||||
|
||||
public function test_incident_consultation_rechecks_current_authority_and_never_grants_other_record_or_document_access(): void
|
||||
{
|
||||
[$id,$promoter] = $this->fixture();
|
||||
$this->failAudit('workflow_submit');
|
||||
$this->act($promoter, $id, 'submit')->assertStatus(503);
|
||||
$draft = $this->loginFixture($promoter)->postJson('/minhas-oportunidades/drafts', ['creation_key' => (string) Str::uuid(), 'organization_id' => Opportunity::findOrFail($id)->organization_id, 'opportunity_category' => 'real_estate', 'reason' => self::REASON])->assertCreated()->json('id');
|
||||
$this->assertSame([], app(OpportunityTechnicalIncidents::class)->recent($promoter, Opportunity::findOrFail($draft)));
|
||||
DB::table('portal_role_assignments')->where('user_id', $promoter->id)->update(['revoked_at' => now()]);
|
||||
$this->get('/minhas-oportunidades/'.$id.'/view')->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_support_profile_receives_only_current_scope_metadata_without_operational_or_document_access(): void
|
||||
{
|
||||
[$id,$promoter] = $this->fixture();
|
||||
$record = Opportunity::findOrFail($id);
|
||||
$this->failAudit('workflow_submit');
|
||||
$this->act($promoter, $id, 'submit')->assertStatus(503);
|
||||
$support = $this->actor('technical_support', $record->organization_id);
|
||||
DB::table('portal_role_assignments')->where('user_id', $support->id)->update(['organization_id' => $record->organization_id]);
|
||||
$this->loginFixture($support)->get('/suporte-tecnico/incidentes')->assertOk()->assertHeader('Cache-Control', 'no-store, private')->assertInertia(fn (Assert $page) => $page->component('profiles/technical-support')->has('incidents.data', 1)->missing('incidents.data.0.attempted_etag')->missing('incidents.data.0.opportunity_id'));
|
||||
$this->get('/minhas-oportunidades/'.$id.'/view')->assertForbidden();
|
||||
$this->act($support, $id, 'publish')->assertForbidden();
|
||||
$otherOrganization = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $otherOrganization, 'name' => 'SYNTHETIC other organization', 'organization_type' => 'private']);
|
||||
DB::table('portal_role_assignments')->where('user_id', $support->id)->update(['organization_id' => $otherOrganization]);
|
||||
$this->get('/suporte-tecnico/incidentes')->assertOk()->assertInertia(fn (Assert $page) => $page->has('incidents.data', 0));
|
||||
DB::table('portal_role_assignments')->where('user_id', $support->id)->update(['organization_id' => null]);
|
||||
DB::table('opportunities')->where('id', $id)->update(['organization_id' => $otherOrganization]);
|
||||
$this->get('/suporte-tecnico/incidentes')->assertOk()->assertInertia(fn (Assert $page) => $page->has('incidents.data', 0));
|
||||
}
|
||||
|
||||
public function test_support_scope_revocation_expiry_and_auditor_restriction_are_effective(): void
|
||||
{
|
||||
[$id,$promoter] = $this->fixture();
|
||||
$record = Opportunity::findOrFail($id);
|
||||
$this->failAudit('workflow_submit');
|
||||
$this->act($promoter, $id, 'submit')->assertStatus(503);
|
||||
$support = $this->actor('technical_support', 'unused');
|
||||
$this->loginFixture($support)->get('/suporte-tecnico/incidentes')->assertOk();
|
||||
app(PortalProfileAdministration::class)->insertGrant((string) Str::uuid(), User::factory()->create(), ['user_id' => $support->id, 'role' => 'auditor', 'opportunity_types' => ['real_estate']]);
|
||||
$this->get('/suporte-tecnico/incidentes')->assertForbidden();
|
||||
DB::table('portal_role_assignments')->where('user_id', $support->id)->where('role', 'auditor')->update(['revoked_at' => now()]);
|
||||
$this->get('/suporte-tecnico/incidentes')->assertOk();
|
||||
$this->travel(2)->hours();
|
||||
DB::table('portal_role_assignments')->where('user_id', $support->id)->where('role', 'technical_support')->update(['expires_at' => now()->subHour()]);
|
||||
$this->get('/suporte-tecnico/incidentes')->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_support_grant_uses_existing_independent_administration_and_is_audited(): void
|
||||
{
|
||||
$admin = User::factory()->create();
|
||||
$second = User::factory()->create();
|
||||
DB::table('portal_superuser_pair')->insert(['id' => 1, 'first_user_id' => $admin->id, 'second_user_id' => $second->id, 'approved_by' => $second->id, 'version' => 1, 'created_at' => now(), 'updated_at' => now()]);
|
||||
$admin->forceFill(['two_factor_secret' => Crypt::encryptString('JBSWY3DPEHPK3PXP'), 'two_factor_confirmed_at' => now()])->save();
|
||||
$subject = User::factory()->create();
|
||||
$this->loginFixture($admin);
|
||||
$input = ['user_id' => $subject->id, 'role' => 'technical_support', 'opportunity_types' => ['real_estate'], 'reason' => self::REASON];
|
||||
$this->postJson('/perfis/atribuicoes', $input)->assertCreated();
|
||||
$this->assertTrue(app(PortalProfileAccess::class)->has($subject, 'technical_support'));
|
||||
$this->assertSame(1, DB::table('audit_events')->where('action', 'role_granted')->count());
|
||||
$this->postJson('/perfis/atribuicoes', [...$input, 'user_id' => $admin->id])->assertForbidden();
|
||||
$this->postJson('/perfis/atribuicoes', [...$input, 'responsibilities' => ['technical_reviewer']])->assertUnprocessable();
|
||||
$this->assertFalse(app(PortalProfileAccess::class)->canCreate($subject, null, 'real_estate'));
|
||||
$this->assertFalse(app(ScopedPortalAdministration::class)->administrative($subject));
|
||||
}
|
||||
|
||||
/** @return array{int,User,User,User,array<string,mixed>,string} */
|
||||
private function fixture(): array
|
||||
{
|
||||
$org = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $org, 'name' => 'Synthetic QA organization', 'organization_type' => 'private']);
|
||||
$promoter = $this->actor('promoter', $org);
|
||||
DB::table('memberships')->insert(['id' => (string) Str::uuid(), 'user_id' => $promoter->id, 'organization_id' => $org, 'role' => 'officer']);
|
||||
$validator = $this->actor('validator', $org, ['technical_reviewer', 'legal_reviewer', 'validation_coordinator']);
|
||||
$publisher = $this->actor('publisher', $org, ['publication_coordinator']);
|
||||
$version = (string) Str::uuid();
|
||||
DB::table('reference_catalog_versions')->insert(['id' => $version, 'catalog_code' => 'qa-only-'.$org, 'version_no' => 1, 'source_system' => 'synthetic-policy-fixture', 'source_version' => 'qa', 'source_reference' => 'Not official', 'status' => 'published']);
|
||||
$ids = [];
|
||||
$parent = null;
|
||||
foreach (range(1, 3) as $i) {
|
||||
$sector = DB::table('sectors')->insertGetId(['name' => 'QA '.$i, 'slug' => 'qa-'.$org.'-'.$i, 'is_active' => true]);
|
||||
$id = (string) Str::uuid();
|
||||
DB::table('economic_activities')->insert(['id' => $id, 'parent_id' => $parent, 'sector_id' => $sector, 'catalog_version_id' => $version, 'code' => 'qa-'.$i, 'label_pt_mz' => 'QA '.$i, 'status' => 'published', 'valid_from' => today()]);
|
||||
$ids[] = [$id, $sector];
|
||||
$parent = $id;
|
||||
}
|
||||
$contact = (string) Str::uuid();
|
||||
$investor = (string) Str::uuid();
|
||||
DB::table('contacts')->insert(['id' => $contact, 'full_name' => 'Synthetic QA contact']);
|
||||
DB::table('investors')->insert(['id' => $investor, 'organization_id' => $org, 'legal_name' => 'Synthetic QA entity', 'investor_type' => 'institutional', 'status' => 'active']);
|
||||
DB::table('investor_contacts')->insert(['investor_id' => $investor, 'contact_id' => $contact]);
|
||||
$draft = $this->loginFixture($promoter)->postJson('/minhas-oportunidades/drafts', ['creation_key' => (string) Str::uuid(), 'organization_id' => $org, 'opportunity_category' => 'real_estate', 'reason' => self::REASON])->assertCreated()->json();
|
||||
$id = $draft['id'];
|
||||
$location = (string) Str::uuid();
|
||||
$provinceId = (string) Str::uuid();
|
||||
$districtId = (string) Str::uuid();
|
||||
DB::table('geo_locations')->insert([['id' => $provinceId, 'code' => $provinceId, 'name' => 'Synthetic QA province', 'location_type' => 'province', 'parent_id' => null, 'data_classification' => 'internal'], ['id' => $districtId, 'code' => $districtId, 'name' => 'Synthetic QA district', 'location_type' => 'district', 'parent_id' => $provinceId, 'data_classification' => 'internal']]);
|
||||
$province = DB::table('geo_locations')->where('id', $provinceId)->first();
|
||||
$district = DB::table('geo_locations')->where('id', $districtId)->first();
|
||||
DB::table('opportunity_location_drafts')->insert(['id' => $location, 'opportunity_id' => $id, 'version' => 1, 'created_by' => $promoter->id, 'payload' => json_encode(['country_code' => 'MZ', 'province_id' => $province->id, 'district_id' => $district->id, 'role' => 'headquarters', 'is_primary' => true])]);
|
||||
$document = (string) Str::uuid();
|
||||
$file = (string) Str::uuid();
|
||||
$bytes = 'Synthetic policy fixture, not a real scanner result.';
|
||||
$key = 'opportunity-contract-test/'.$file;
|
||||
Storage::disk('local')->put($key, Crypt::encryptString($bytes));
|
||||
DB::table('documents')->insert(['id' => $file, 'file_name' => 'qa-fixture.txt', 'storage_key' => $key, 'storage_encryption' => 'laravel', 'media_type' => 'text/plain', 'sha256' => hash('sha256', $bytes), 'status' => 'active', 'malware_scan_status' => 'clean', 'malware_engine' => 'synthetic-policy-fixture', 'malware_scanned_sha256' => hash('sha256', $bytes), 'uploaded_by' => $promoter->id]);
|
||||
DB::table('opportunity_documents')->insert(['id' => $document, 'opportunity_id' => $id, 'document_id' => $file, 'version' => 1, 'created_by' => $promoter->id, 'payload' => json_encode(['title' => 'QA', 'category' => 'qa', 'visibility' => 'internal'])]);
|
||||
$payload = ['opportunity_category' => 'real_estate', 'official_title' => 'Imóvel sintético para ensaio QA', 'promoter_id' => $org, 'promoter_type' => 'private', 'internal_contact_id' => $contact, 'sector_id' => $ids[0][1], 'subsector_id' => $ids[1][0], 'economic_activity_id' => $ids[2][0], 'location_mode' => 'single', 'geographic_scope' => 'district', 'locations' => [$location], 'executive_summary' => trim(str_repeat('Resumo sintético QA. ', 20)), 'demand_statement' => trim(str_repeat('Necessidade sintética QA. ', 6)), 'documents' => [$document], 'evidences' => [['title' => 'QA', 'evidence_type' => 'qa', 'document_id' => $document]], 'publication_languages' => [['language_code' => 'pt-MZ', 'title' => 'QA', 'summary' => 'QA']], 'visibility' => 'internal', 'currency' => 'MZN', 'truth_declaration' => true, 'real_estate' => ['transaction_type' => 'sale', 'property_type' => 'warehouse', 'construction_status' => 'completed', 'property_condition' => 'good', 'land_area' => 1000, 'built_area' => 500, 'area_unit' => 'sqm', 'utilities' => [['type' => 'water', 'status' => 'existing']], 'occupancy_status' => 'vacant', 'title_type' => 'QA', 'registration_number' => 'QA-'.$id, 'encumbrances' => [['type' => 'none']], 'valuation' => ['value' => 1000, 'date' => '2026-10-10', 'method' => 'qa', 'appraiser' => 'QA', 'document_id' => $document], 'price' => 1000, 'use_license_document_id' => $document]];
|
||||
$authority = (string) Str::uuid();
|
||||
DB::table('authorities')->insert(['id' => $authority, 'catalog_version_id' => $version, 'organization_id' => $org, 'code' => 'QA-'.$id, 'authority_type' => 'qa-synthetic', 'label_pt_mz' => 'Entidade sintética QA', 'source_reference' => 'Synthetic policy fixture; not official', 'valid_from' => '2026-01-01', 'status' => 'published']);
|
||||
$payload['real_estate']['utilities'] = array_map(fn ($type) => ['type' => $type, 'status' => 'existing'], ['electricity', 'water', 'sanitation', 'telecommunications', 'access']);
|
||||
$payload['real_estate'] += ['title_document_id' => $document, 'title_holder_name' => 'Synthetic QA organization', 'issuing_authority_id' => $authority];
|
||||
|
||||
$this->loginFixture($promoter)->putJson('/minhas-oportunidades/'.$id.'/draft', ['etag' => $draft['etag'], 'canonical' => $payload, 'reason' => self::REASON])->assertOk();
|
||||
|
||||
return [$id, $promoter, $validator, $publisher, $payload, $document];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\PortalProfileAdministration;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class OrganizationCountryCommandsTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $actor;
|
||||
|
||||
private string $organization;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
Http::fake();
|
||||
Mail::fake();
|
||||
config(['portal.organization_country_enabled' => true, 'portal.profile_access_enabled' => true]);
|
||||
$this->actor = User::factory()->create();
|
||||
$this->organization = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $this->organization, 'name' => 'SYNTHETIC country master', 'organization_type' => 'private', 'source_system' => 'synthetic-command-fixture', 'external_id' => 'SYNTHETIC-stable-source']);
|
||||
DB::table('memberships')->insert(['user_id' => $this->actor->id, 'organization_id' => $this->organization, 'role' => 'officer']);
|
||||
$this->actingAs($this->actor);
|
||||
}
|
||||
|
||||
private function command(): array
|
||||
{
|
||||
return ['operation_key' => (string) Str::uuid(), 'version' => 1, 'country' => 'FR', 'source_reference' => 'SYNTHETIC PRIVATE declaration reference'];
|
||||
}
|
||||
|
||||
private function url(?string $id = null): string
|
||||
{
|
||||
return '/api/v1/investment/organizations/'.($id ?? $this->organization).'/country';
|
||||
}
|
||||
|
||||
public function test_replay_keeps_country_provenance_version_and_audit_identical(): void
|
||||
{
|
||||
$command = $this->command();
|
||||
$first = $this->putJson($this->url(), $command)->assertOk()->assertJsonPath('version', 2)->json();
|
||||
$before = DB::table('organizations')->where('id', $this->organization)->first();
|
||||
$audits = DB::table('audit_events')->get()->toArray();
|
||||
$this->putJson($this->url(), [...$command, 'operation_key' => strtoupper($command['operation_key'])])->assertExactJson($first);
|
||||
$this->assertEquals($before, DB::table('organizations')->where('id', $this->organization)->first());
|
||||
$this->assertEquals($audits, DB::table('audit_events')->get()->toArray());
|
||||
$this->assertSame(2, DB::table('audit_events')->count());
|
||||
$receipt = json_decode(DB::table('audit_events')->where('source_system', 'investment-workspace-command')->value('after_data'), true);
|
||||
$this->assertStringNotContainsString('SYNTHETIC PRIVATE', json_encode($receipt));
|
||||
$this->assertSame($command['source_reference'], json_decode(Crypt::decryptString($receipt['command_encrypted']), true)['payload']['source_reference']);
|
||||
}
|
||||
|
||||
public function test_original_receipt_survives_a_later_change_without_reverting_current_country(): void
|
||||
{
|
||||
$command = $this->command();
|
||||
$this->putJson($this->url(), $command)->assertOk();
|
||||
$this->putJson($this->url(), [...$command, 'operation_key' => (string) Str::uuid(), 'version' => 2, 'country' => 'ZA'])->assertJsonPath('version', 3);
|
||||
$before = DB::table('organizations')->where('id', $this->organization)->first();
|
||||
$this->putJson($this->url(), $command)->assertExactJson(['version' => 2, 'country' => 'FR']);
|
||||
$this->assertEquals($before, DB::table('organizations')->where('id', $this->organization)->first());
|
||||
$this->assertSame('ZA', $before->incorporation_country_code);
|
||||
}
|
||||
|
||||
public function test_changed_reference_country_target_or_operation_cannot_reuse_the_same_key(): void
|
||||
{
|
||||
$command = $this->command();
|
||||
$this->putJson($this->url(), $command)->assertOk();
|
||||
$this->putJson($this->url(), [...$command, 'source_reference' => 'SYNTHETIC altered reference'])->assertConflict();
|
||||
$this->putJson($this->url(), [...$command, 'country' => 'ZA'])->assertConflict();
|
||||
$id = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $id, 'name' => 'SYNTHETIC second master', 'organization_type' => 'private']);
|
||||
DB::table('memberships')->insert(['user_id' => $this->actor->id, 'organization_id' => $id, 'role' => 'officer']);
|
||||
$this->putJson($this->url($id), $command)->assertConflict();
|
||||
$this->putJson('/api/v1/investment/profile', ['version' => 0, 'operation_key' => $command['operation_key'], 'payload' => ['residence_country_code' => 'PT']])->assertConflict();
|
||||
$this->assertSame(0, DB::table('investment_accounts')->count());
|
||||
$this->assertSame(2, DB::table('audit_events')->count());
|
||||
}
|
||||
|
||||
public function test_revoked_representation_auditor_and_deleted_organization_cannot_read_a_replay_confirmation(): void
|
||||
{
|
||||
$command = $this->command();
|
||||
$this->putJson($this->url(), $command)->assertOk();
|
||||
$before = DB::table('organizations')->where('id', $this->organization)->first();
|
||||
DB::table('memberships')->where('user_id', $this->actor->id)->update(['deleted_at' => now()]);
|
||||
$this->putJson($this->url(), $command)->assertForbidden();
|
||||
DB::table('memberships')->where('user_id', $this->actor->id)->update(['deleted_at' => null]);
|
||||
$approver = User::factory()->create();
|
||||
app(PortalProfileAdministration::class)->insertGrant((string) Str::uuid(), $approver, ['user_id' => $this->actor->id, 'role' => 'auditor', 'opportunity_types' => [], 'source' => 'synthetic-country-command-auditor']);
|
||||
$this->actor->refresh();
|
||||
$this->actingAs($this->actor)->withSession(['portal.access_revision' => $this->actor->portal_access_revision]);
|
||||
$this->putJson($this->url(), $command)->assertForbidden();
|
||||
DB::table('portal_role_assignments')->where('user_id', $this->actor->id)->update(['revoked_at' => now()]);
|
||||
DB::table('organizations')->where('id', $this->organization)->update(['deleted_at' => now()]);
|
||||
$this->putJson($this->url(), $command)->assertForbidden();
|
||||
$after = DB::table('organizations')->where('id', $this->organization)->first();
|
||||
$this->assertSame($before->incorporation_country_provenance, $after->incorporation_country_provenance);
|
||||
$this->assertSame(2, $after->version_no);
|
||||
}
|
||||
|
||||
public function test_invalid_country_reference_and_key_do_not_increment_version_and_legacy_requests_still_work(): void
|
||||
{
|
||||
$command = $this->command();
|
||||
foreach ([['country' => 'ZZ'], ['source_reference' => 'x'], ['operation_key' => 'bad']] as $invalid) {
|
||||
$this->putJson($this->url(), [...$command, ...$invalid])->assertUnprocessable()->assertJsonValidationErrors(array_keys($invalid));
|
||||
}
|
||||
$this->assertSame(1, DB::table('organizations')->where('id', $this->organization)->value('version_no'));
|
||||
$this->assertSame(0, DB::table('audit_events')->count());
|
||||
unset($command['operation_key']);
|
||||
$this->putJson($this->url(), $command)->assertOk()->assertJsonPath('version', 2);
|
||||
$this->assertSame(1, DB::table('audit_events')->count());
|
||||
}
|
||||
|
||||
public function test_current_membership_role_changes_project_the_same_authority_as_the_write_endpoint(): void
|
||||
{
|
||||
$this->getJson('/api/v1/investment/profile')->assertOk()->assertJsonCount(1, 'organizations')->assertJsonPath('organizations.0.canEdit', true);
|
||||
$this->putJson($this->url(), $this->command())->assertOk();
|
||||
DB::table('memberships')->where('user_id', $this->actor->id)->update(['role' => 'viewer']);
|
||||
$this->getJson('/api/v1/investment/profile')->assertOk()->assertJsonPath('organizations.0.canEdit', false);
|
||||
$this->putJson($this->url(), [...$this->command(), 'version' => 2])->assertForbidden();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class OrganizationCountryReuseCommandsTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $actor;
|
||||
|
||||
private string $organization;
|
||||
|
||||
private string $company;
|
||||
|
||||
private string $submission;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
Http::fake();
|
||||
Mail::fake();
|
||||
config(['portal.organization_country_enabled' => true, 'portal.profile_access_enabled' => true]);
|
||||
$this->actor = User::factory()->create();
|
||||
$this->actingAs($this->actor);
|
||||
$this->organization = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $this->organization, 'name' => 'SYNTHETIC reuse source', 'organization_type' => 'private', 'source_system' => 'synthetic-reuse-fixture', 'external_id' => 'SYNTHETIC-stable', 'version_no' => 3, 'incorporation_country_code' => 'FR', 'incorporation_country_provenance' => json_encode(['kind' => 'representative_declaration', 'reference' => 'SYNTHETIC source reference'])]);
|
||||
DB::table('memberships')->insert(['user_id' => $this->actor->id, 'organization_id' => $this->organization, 'role' => 'viewer']);
|
||||
$this->putJson('/api/v1/investment/profile', ['version' => 0, 'payload' => ['residence_country_code' => 'PT']])->assertOk();
|
||||
$this->company = $this->postJson('/api/v1/investment/companies', ['version' => 0, 'payload' => ['name' => 'SYNTHETIC private reuse target', 'role' => 'SYNTHETIC representative', 'incorporation_country_code' => 'MZ']])->assertOk()->json('id');
|
||||
$this->submission = $this->postJson('/api/v1/investment/submissions', ['company_id' => $this->company])->assertCreated()->json('id');
|
||||
}
|
||||
|
||||
private function command(): array
|
||||
{
|
||||
return ['version' => 1, 'organization_id' => $this->organization, 'organization_version' => 3, 'operation_key' => (string) Str::uuid()];
|
||||
}
|
||||
|
||||
private function url(?string $id = null): string
|
||||
{
|
||||
return '/api/v1/investment/companies/'.($id ?? $this->company).'/organization-country';
|
||||
}
|
||||
|
||||
private function target(): \stdClass
|
||||
{
|
||||
return DB::table('investment_company_declarations')->where('id', $this->company)->first();
|
||||
}
|
||||
|
||||
public function test_read_authority_can_reuse_once_and_replay_keeps_the_original_snapshot_and_encrypted_receipt(): void
|
||||
{
|
||||
$command = $this->command();
|
||||
$submission = DB::table('investment_submissions')->where('id', $this->submission)->first();
|
||||
$first = $this->postJson($this->url(), $command)->assertOk()->assertHeader('Cache-Control', 'no-store, private')->json();
|
||||
$target = $this->target();
|
||||
$auditCount = DB::table('audit_events')->count();
|
||||
$this->postJson($this->url(strtoupper($this->company)), [...$command, 'organization_id' => strtoupper($this->organization), 'operation_key' => strtoupper($command['operation_key'])])->assertExactJson($first);
|
||||
$this->assertEquals($target, $this->target());
|
||||
$this->assertSame($auditCount, DB::table('audit_events')->count());
|
||||
$payload = json_decode(Crypt::decryptString($target->payload), true);
|
||||
$this->assertSame('FR', $payload['incorporation_country_code']);
|
||||
$this->assertSame(3, $payload['organization_country_snapshot']['organization_version']);
|
||||
$receipt = json_decode(DB::table('audit_events')->where('source_system', 'investment-workspace-command')->value('after_data'), true);
|
||||
$this->assertArrayNotHasKey('result', $receipt);
|
||||
$this->assertArrayNotHasKey('country', $receipt);
|
||||
$this->assertSame(['version' => 2, 'country' => 'FR'], json_decode(Crypt::decryptString($receipt['result_encrypted']), true));
|
||||
$this->assertEquals($submission, DB::table('investment_submissions')->where('id', $this->submission)->first());
|
||||
$this->getJson('/api/v1/investment/profile')->assertJsonPath('account.payload.residence_country_code', 'PT')->assertJsonPath('organizations.0.canEdit', false);
|
||||
$this->assertSame(1, DB::table('organizations')->count());
|
||||
$this->assertSame(1, DB::table('memberships')->count());
|
||||
}
|
||||
|
||||
public function test_replay_reads_its_original_country_after_later_source_and_target_changes_even_if_source_country_is_now_missing(): void
|
||||
{
|
||||
$first = $this->command();
|
||||
$this->postJson($this->url(), $first)->assertOk();
|
||||
DB::table('organizations')->where('id', $this->organization)->update(['version_no' => 4, 'incorporation_country_code' => 'ZA']);
|
||||
$this->postJson($this->url(), [...$first, 'operation_key' => (string) Str::uuid(), 'version' => 2, 'organization_version' => 4])->assertJsonPath('version', 3)->assertJsonPath('country', 'ZA');
|
||||
$target = $this->target();
|
||||
DB::table('organizations')->where('id', $this->organization)->update(['version_no' => 5, 'incorporation_country_code' => null]);
|
||||
$this->postJson($this->url(), $first)->assertExactJson(['version' => 2, 'country' => 'FR']);
|
||||
$this->assertEquals($target, $this->target());
|
||||
$this->postJson($this->url(), [...$first, 'operation_key' => (string) Str::uuid(), 'version' => 3, 'organization_version' => 5])->assertUnprocessable();
|
||||
$this->assertEquals($target, $this->target());
|
||||
$this->assertSame(2, DB::table('audit_events')->where('action', 'organization_country_reused')->count());
|
||||
}
|
||||
|
||||
public function test_stale_versions_malformed_keys_and_changed_intentions_do_not_write(): void
|
||||
{
|
||||
$command = $this->command();
|
||||
$before = $this->target();
|
||||
$this->postJson($this->url(), [...$command, 'organization_version' => 2])->assertConflict();
|
||||
$this->postJson($this->url(), [...$command, 'version' => 2])->assertConflict();
|
||||
$this->postJson($this->url(), [...$command, 'operation_key' => 'bad'])->assertUnprocessable()->assertJsonValidationErrors('operation_key');
|
||||
$this->assertEquals($before, $this->target());
|
||||
$this->postJson($this->url(), $command)->assertOk();
|
||||
$after = $this->target();
|
||||
$this->postJson($this->url(), [...$command, 'organization_version' => 4])->assertConflict();
|
||||
$this->putJson('/api/v1/investment/profile', ['version' => 1, 'operation_key' => $command['operation_key'], 'payload' => ['residence_country_code' => 'ZA']])->assertConflict();
|
||||
$this->assertEquals($after, $this->target());
|
||||
}
|
||||
|
||||
public function test_replay_requires_current_source_access_and_current_ownership_and_can_resume_after_representation_is_restored(): void
|
||||
{
|
||||
$command = $this->command();
|
||||
$this->postJson($this->url(), $command)->assertOk();
|
||||
$target = $this->target();
|
||||
DB::table('memberships')->where('user_id', $this->actor->id)->update(['deleted_at' => now()]);
|
||||
$this->postJson($this->url(), $command)->assertForbidden();
|
||||
DB::table('memberships')->where('user_id', $this->actor->id)->update(['deleted_at' => null]);
|
||||
$this->postJson($this->url(), $command)->assertExactJson(['version' => 2, 'country' => 'FR']);
|
||||
DB::table('organizations')->where('id', $this->organization)->update(['deleted_at' => now()]);
|
||||
$this->postJson($this->url(), $command)->assertForbidden();
|
||||
$this->actingAs(User::factory()->create())->postJson($this->url(), $command)->assertNotFound();
|
||||
$this->assertEquals($target, $this->target());
|
||||
}
|
||||
|
||||
public function test_legacy_reuse_without_a_key_is_supported_and_its_country_never_updates_old_submissions(): void
|
||||
{
|
||||
$command = $this->command();
|
||||
unset($command['operation_key']);
|
||||
$before = DB::table('investment_submissions')->where('id', $this->submission)->first();
|
||||
$this->postJson($this->url(), $command)->assertOk()->assertJsonPath('country', 'FR');
|
||||
$new = $this->postJson('/api/v1/investment/submissions', ['company_id' => $this->company])->assertCreated()->json('id');
|
||||
$this->getJson('/api/v1/investment/submissions/'.$new)->assertJsonPath('submission.payload.incorporation_country_code', 'FR')->assertJsonPath('submission.payload.organization_country_snapshot.organization_version', 3);
|
||||
$this->assertEquals($before, DB::table('investment_submissions')->where('id', $this->submission)->first());
|
||||
$this->assertSame(0, DB::table('audit_events')->where('source_system', 'investment-workspace-command')->count());
|
||||
}
|
||||
|
||||
public function test_a_receipt_failure_rolls_back_the_company_and_business_audit_together(): void
|
||||
{
|
||||
$before = $this->target();
|
||||
$auditCount = DB::table('audit_events')->count();
|
||||
DB::statement("ALTER TABLE audit_events ADD CONSTRAINT qa_reject_country_reuse_receipt CHECK (source_system <> 'investment-workspace-command')");
|
||||
$response = $this->postJson($this->url(), $this->command())->assertStatus(503);
|
||||
$this->assertStringNotContainsString('SQLSTATE', $response->getContent());
|
||||
$this->assertEquals($before, $this->target());
|
||||
$this->assertSame($auditCount, DB::table('audit_events')->count());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\PartnershipAgreements;
|
||||
use App\Services\PartnershipExchange;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Facades\Queue;
|
||||
use Illuminate\Support\Str;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class PartnershipAgreementHistoryTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $owner;
|
||||
|
||||
private User $candidate;
|
||||
|
||||
private int $roomId;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
Http::fake();
|
||||
Mail::fake();
|
||||
Queue::fake();
|
||||
$this->owner = User::factory()->create();
|
||||
$this->candidate = User::factory()->create();
|
||||
$moderator = User::factory()->create();
|
||||
config(['portal.managers' => [$moderator->email]]);
|
||||
$service = app(PartnershipExchange::class);
|
||||
$record = $service->save($this->owner, ['client_key' => (string) Str::uuid(), 'title' => 'SYNTHETIC agreement', 'kind' => 'seeking', 'partnership_type' => 'joint_venture', 'offer' => 'SYNTHETIC offer', 'payload' => ['consent' => true]]);
|
||||
$record = $service->transition($this->owner, $record->id, $record->version, 'submit', 'SYNTHETIC submit');
|
||||
$record = $service->transition($moderator, $record->id, $record->version, 'publish', 'SYNTHETIC publish');
|
||||
$interest = $service->interest($this->candidate, $record->id, ['proposal' => 'SYNTHETIC candidacy', 'payload' => ['consent' => true]]);
|
||||
$interest = $service->decideInterest($this->owner, $interest->id, $interest->version, 'shortlist', 'SYNTHETIC shortlist');
|
||||
$service->decideInterest($this->owner, $interest->id, $interest->version, 'connect', 'SYNTHETIC connect');
|
||||
$this->roomId = (int) DB::table('partnership_rooms')->where('interest_id', $interest->id)->value('id');
|
||||
$this->actingAs($this->owner)->postJson($this->url(), ['version' => 1, 'action' => 'record', 'title' => 'SYNTHETIC instrument', 'terms' => 'SYNTHETIC terms', 'reason' => 'SYNTHETIC record'])->assertOk();
|
||||
}
|
||||
|
||||
private function url(): string
|
||||
{
|
||||
return '/parcerias/salas/'.$this->roomId.'/acordo';
|
||||
}
|
||||
|
||||
private function command(string $action = 'cancel'): array
|
||||
{
|
||||
$context = app(PartnershipExchange::class)->room($this->owner, $this->roomId);
|
||||
|
||||
return ['client_key' => (string) Str::uuid(), 'version' => $context['room']->version, 'partnership_version' => $context['partnership']->version, 'interest_version' => $context['interest']->version, 'action' => $action, 'reason' => 'SYNTHETIC documented action'];
|
||||
}
|
||||
|
||||
public function test_history_reads_the_saved_instrument_without_changing_the_room(): void
|
||||
{
|
||||
$room = DB::table('partnership_rooms')->where('id', $this->roomId)->first();
|
||||
$events = DB::table('partnership_events')->count();
|
||||
$audits = DB::table('audit_events')->count();
|
||||
$notices = DB::table('partnership_notifications')->count();
|
||||
$this->getJson($this->history())->assertOk()->assertHeader('Cache-Control', 'no-store, private')->assertJsonPath('room_id', $this->roomId)
|
||||
->assertJsonCount(1, 'entries')->assertJsonPath('entries.0.after.instrument.title', 'SYNTHETIC instrument')
|
||||
->assertJsonPath('entries.0.after.instrument.legal_signature_status', 'not_verified')->assertJsonPath('entries.0.previous.instrument_availability', 'not_recorded');
|
||||
$this->assertEquals($room, DB::table('partnership_rooms')->where('id', $this->roomId)->first());
|
||||
$this->assertSame($events, DB::table('partnership_events')->count());
|
||||
$this->assertSame($audits, DB::table('audit_events')->count());
|
||||
$this->assertSame($notices, DB::table('partnership_notifications')->count());
|
||||
}
|
||||
|
||||
private function history(): string
|
||||
{
|
||||
return '/parcerias/salas/'.$this->roomId.'/historico';
|
||||
}
|
||||
|
||||
private function record(string $title = 'SYNTHETIC next instrument'): void
|
||||
{
|
||||
app(PartnershipAgreements::class)->act($this->owner, $this->roomId, [...$this->command('record'), 'title' => $title, 'terms' => 'SYNTHETIC frozen conditions']);
|
||||
}
|
||||
|
||||
private function alterEvent(callable $change): void
|
||||
{
|
||||
$event = DB::table('partnership_events')->where('event_type', 'partnership_agreement.changed.v1')->orderByDesc('aggregate_version')->first();
|
||||
$payload = json_decode($event->payload, true);
|
||||
$payload['payload'] = $change($payload['payload']);
|
||||
DB::table('partnership_events')->where('id', $event->id)->update(['payload' => json_encode($payload)]);
|
||||
}
|
||||
|
||||
public function test_both_parties_read_closed_history_but_moderation_is_not_private_room_access(): void
|
||||
{
|
||||
$this->postJson($this->url(), $this->command())->assertOk();
|
||||
$this->actingAs($this->candidate)->getJson($this->history())->assertOk()->assertJsonPath('entries.0.action', 'cancel');
|
||||
$this->actingAs($this->owner)->get($this->history())->assertOk()->assertInertia(fn (Assert $page) => $page->component('partnerships/agreement-history')->where('room_id', $this->roomId));
|
||||
$other = User::factory()->create();
|
||||
config(['portal.managers' => [$other->email]]);
|
||||
$this->actingAs($other)->getJson($this->history())->assertForbidden();
|
||||
$this->getJson('/parcerias/salas/999999999/historico')->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_instruments_and_confirmations_are_frozen_and_only_projected_fields_leave_events(): void
|
||||
{
|
||||
$this->postJson($this->url(), $this->command('confirm'))->assertOk();
|
||||
$this->alterEvent(function ($data) {
|
||||
$data['applied']['agreement']['private_secret'] = 'SYNTHETIC do not disclose';
|
||||
$data['applied']['agreement']['confirmations']['proponent']['private_secret'] = 'SYNTHETIC do not disclose';
|
||||
|
||||
return $data;
|
||||
});
|
||||
$instrument = json_decode(DB::table('partnership_rooms')->where('id', $this->roomId)->value('agreement'), true);
|
||||
$instrument['title'] = 'SYNTHETIC current title never a historical fallback';
|
||||
DB::table('partnership_rooms')->where('id', $this->roomId)->update(['agreement' => json_encode($instrument)]);
|
||||
$result = $this->getJson($this->history())->assertOk()->assertJsonPath('entries.0.previous.instrument.title', 'SYNTHETIC instrument')
|
||||
->assertJsonPath('entries.0.after.instrument.title', 'SYNTHETIC instrument')->assertJsonPath('entries.0.confirmation_party', 'proponent')
|
||||
->assertJsonPath('entries.0.after.instrument.confirmations.proponent.reason', 'SYNTHETIC documented action');
|
||||
foreach (['private_secret', 'do not disclose', 'command_hash', 'client_key', '_notification_context', 'previous_versions', 'current title never'] as $secret) {
|
||||
$this->assertStringNotContainsString($secret, $result->getContent());
|
||||
}
|
||||
}
|
||||
|
||||
public function test_pagination_is_bounded_and_inserting_a_newer_event_does_not_repeat_older_pages(): void
|
||||
{
|
||||
for ($i = 0; $i < 12; $i++) {
|
||||
$this->record('SYNTHETIC revision '.$i);
|
||||
}
|
||||
$first = $this->getJson($this->history())->assertOk()->assertJsonCount(10, 'entries');
|
||||
$next = $first->json('next_url');
|
||||
$this->assertIsString($next);
|
||||
$this->record('SYNTHETIC inserted after pagination');
|
||||
$older = $this->getJson($next)->assertOk()->assertJsonCount(3, 'entries')->assertJsonPath('next_url', null)->assertJsonPath('older_page', true);
|
||||
$versions = [...array_column($first->json('entries'), 'version'), ...array_column($older->json('entries'), 'version')];
|
||||
$this->assertCount(13, array_unique($versions));
|
||||
$sorted = $versions;
|
||||
rsort($sorted);
|
||||
$this->assertSame($sorted, $versions);
|
||||
}
|
||||
|
||||
public function test_cursor_is_bound_to_account_room_relationship_and_purpose(): void
|
||||
{
|
||||
for ($i = 0; $i < 10; $i++) {
|
||||
$this->record();
|
||||
}
|
||||
$next = $this->getJson($this->history())->assertOk()->json('next_url');
|
||||
$this->actingAs($this->candidate)->getJson($next)->assertUnprocessable();
|
||||
$this->actingAs($this->owner)->getJson($this->history().'?before=invalid')->assertUnprocessable();
|
||||
$context = app(PartnershipExchange::class)->room($this->owner, $this->roomId);
|
||||
foreach (['purpose' => 'publication', 'actor' => $this->candidate->id, 'room' => $this->roomId + 1, 'interest' => $context['interest']->id + 1, 'partnership' => $context['partnership']->id + 1, 'before' => '1'] as $key => $wrong) {
|
||||
$cursor = ['purpose' => 'agreement', 'actor' => $this->owner->id, 'room' => $this->roomId, 'interest' => (int) $context['interest']->id, 'partnership' => (int) $context['partnership']->id, 'before' => 9999];
|
||||
$cursor[$key] = $wrong;
|
||||
$this->getJson($this->history().'?before='.rawurlencode(Crypt::encryptString(json_encode($cursor))))->assertUnprocessable();
|
||||
}
|
||||
}
|
||||
|
||||
public function test_current_representative_cannot_inherit_an_older_organization_instrument(): void
|
||||
{
|
||||
$a = (string) Str::uuid();
|
||||
$b = (string) Str::uuid();
|
||||
$viewer = User::factory()->create();
|
||||
foreach ([$a, $b] as $org) {
|
||||
DB::table('organizations')->insert(['id' => $org, 'name' => 'SYNTHETIC organization', 'organization_type' => 'private']);
|
||||
DB::table('memberships')->insert(['user_id' => $this->owner->id, 'organization_id' => $org, 'role' => 'officer']);
|
||||
}
|
||||
DB::table('memberships')->insert(['user_id' => $viewer->id, 'organization_id' => $b, 'role' => 'viewer']);
|
||||
$exchange = app(PartnershipExchange::class);
|
||||
$parent = $exchange->room($this->owner, $this->roomId)['partnership'];
|
||||
$parent = $exchange->save($this->owner, ['version' => $parent->version, 'kind' => 'seeking', 'organization_id' => $a], $parent->id);
|
||||
$this->record('SYNTHETIC OLD organization instrument');
|
||||
$exchange->save($this->owner, ['version' => $parent->version, 'kind' => 'seeking', 'organization_id' => $b], $parent->id);
|
||||
$this->postJson($this->url(), $this->command('confirm'))->assertOk();
|
||||
$result = $this->actingAs($viewer)->getJson($this->history())->assertOk()->assertJsonPath('entries.0.restricted', false)
|
||||
->assertJsonPath('entries.0.after.instrument_availability', 'restricted')->assertJsonPath('entries.1.restricted', true);
|
||||
$this->assertStringNotContainsString('OLD organization instrument', $result->getContent());
|
||||
$this->actingAs($this->candidate)->getJson($this->history())->assertOk()->assertJsonPath('entries.0.after.instrument.title', 'SYNTHETIC OLD organization instrument');
|
||||
DB::table('memberships')->where('user_id', $viewer->id)->update(['deleted_at' => now()]);
|
||||
$this->actingAs($viewer)->getJson($this->history())->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_missing_or_inconsistent_historical_scope_hides_content_instead_of_using_current_parties(): void
|
||||
{
|
||||
$this->alterEvent(function ($data) {
|
||||
$data['_notification_context']['interest']['id']++;
|
||||
|
||||
return $data;
|
||||
});
|
||||
$result = $this->getJson($this->history())->assertOk()->assertJsonPath('entries.0.restricted', true)->assertJsonPath('entries.0.reason', null)->assertJsonPath('entries.0.after.availability', 'scope_unknown');
|
||||
$this->assertStringNotContainsString('SYNTHETIC instrument', $result->getContent());
|
||||
$this->alterEvent(function ($data) {
|
||||
unset($data['_notification_context']);
|
||||
|
||||
return $data;
|
||||
});
|
||||
$this->getJson($this->history())->assertOk()->assertJsonPath('entries.0.after.availability', 'scope_unknown');
|
||||
}
|
||||
|
||||
public function test_legacy_events_without_snapshots_are_explicitly_incomplete(): void
|
||||
{
|
||||
$this->alterEvent(function ($data) {
|
||||
unset($data['previous'], $data['applied']);
|
||||
|
||||
return $data;
|
||||
});
|
||||
$result = $this->getJson($this->history())->assertOk()->assertJsonPath('entries.0.previous.availability', 'not_recorded')->assertJsonPath('entries.0.after.availability', 'not_recorded');
|
||||
$this->assertStringNotContainsString('SYNTHETIC instrument', $result->getContent());
|
||||
}
|
||||
|
||||
public function test_foreign_snapshot_id_and_unknown_instrument_origin_do_not_disclose_values(): void
|
||||
{
|
||||
$this->alterEvent(function ($data) {
|
||||
$data['previous'] = $data['applied'];
|
||||
$data['previous']['id']++;
|
||||
unset($data['applied']['agreement']['recorded_context']);
|
||||
|
||||
return $data;
|
||||
});
|
||||
$result = $this->getJson($this->history())->assertOk()->assertJsonPath('entries.0.previous.availability', 'scope_unknown')->assertJsonPath('entries.0.after.instrument_availability', 'scope_unknown');
|
||||
$this->assertStringNotContainsString('SYNTHETIC instrument', $result->getContent());
|
||||
}
|
||||
|
||||
public function test_legacy_confirmation_shapes_remain_explicit_and_private_fields_are_omitted(): void
|
||||
{
|
||||
$this->alterEvent(function ($data) {
|
||||
$data['applied']['agreement']['confirmations'] = ['proponent' => ['actor_id' => 'wrong', 'date' => ['SYNTHETIC private']], 'unknown-secret-key' => ['SYNTHETIC private']];
|
||||
|
||||
return $data;
|
||||
});
|
||||
$result = $this->getJson($this->history())->assertOk()->assertJsonPath('entries.0.after.instrument.confirmations.proponent.actor_id', null)->assertJsonPath('entries.0.after.instrument.confirmations._unrecognized_references', true);
|
||||
$this->assertStringNotContainsString('unknown-secret-key', $result->getContent());
|
||||
$this->assertStringNotContainsString('SYNTHETIC private', $result->getContent());
|
||||
$this->alterEvent(function ($data) {
|
||||
$data['applied']['agreement']['confirmations'] = null;
|
||||
|
||||
return $data;
|
||||
});
|
||||
$this->getJson($this->history())->assertOk()->assertJsonPath('entries.0.after.instrument.confirmations', null);
|
||||
}
|
||||
|
||||
public function test_another_room_is_never_included_in_the_history(): void
|
||||
{
|
||||
$exchange = app(PartnershipExchange::class);
|
||||
$context = $exchange->room($this->owner, $this->roomId);
|
||||
$other = User::factory()->create();
|
||||
$interest = $exchange->interest($other, $context['partnership']->id, ['proposal' => 'SYNTHETIC other candidacy', 'payload' => ['consent' => true]]);
|
||||
$interest = $exchange->decideInterest($this->owner, $interest->id, $interest->version, 'shortlist', 'SYNTHETIC shortlist');
|
||||
$exchange->decideInterest($this->owner, $interest->id, $interest->version, 'connect', 'SYNTHETIC connect');
|
||||
$room = DB::table('partnership_rooms')->where('interest_id', $interest->id)->first();
|
||||
app(PartnershipAgreements::class)->act($this->owner, $room->id, ['version' => 1, 'action' => 'record', 'reason' => 'SYNTHETIC other', 'title' => 'SYNTHETIC OTHER PRIVATE', 'terms' => 'SYNTHETIC private']);
|
||||
$result = $this->getJson($this->history())->assertOk()->assertJsonCount(1, 'entries');
|
||||
$this->assertStringNotContainsString('OTHER PRIVATE', $result->getContent());
|
||||
$this->actingAs($other)->getJson($this->history())->assertForbidden();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\PartnershipExchange;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Facades\Queue;
|
||||
use Illuminate\Support\Str;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class PartnershipAgreementProjectionTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $owner;
|
||||
|
||||
private User $candidate;
|
||||
|
||||
private int $roomId;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
Http::fake();
|
||||
Mail::fake();
|
||||
Queue::fake();
|
||||
$this->owner = User::factory()->create();
|
||||
$this->candidate = User::factory()->create();
|
||||
$moderator = User::factory()->create();
|
||||
config(['portal.managers' => [$moderator->email]]);
|
||||
$service = app(PartnershipExchange::class);
|
||||
$record = $service->save($this->owner, ['client_key' => (string) Str::uuid(), 'title' => 'SYNTHETIC agreement', 'kind' => 'seeking', 'partnership_type' => 'joint_venture', 'offer' => 'SYNTHETIC offer', 'payload' => ['consent' => true]]);
|
||||
$record = $service->transition($this->owner, $record->id, $record->version, 'submit', 'SYNTHETIC submit');
|
||||
$record = $service->transition($moderator, $record->id, $record->version, 'publish', 'SYNTHETIC publish');
|
||||
$interest = $service->interest($this->candidate, $record->id, ['proposal' => 'SYNTHETIC candidacy', 'payload' => ['consent' => true]]);
|
||||
$interest = $service->decideInterest($this->owner, $interest->id, $interest->version, 'shortlist', 'SYNTHETIC shortlist');
|
||||
$service->decideInterest($this->owner, $interest->id, $interest->version, 'connect', 'SYNTHETIC connect');
|
||||
$this->roomId = (int) DB::table('partnership_rooms')->where('interest_id', $interest->id)->value('id');
|
||||
$this->actingAs($this->owner)->postJson($this->url(), ['version' => 1, 'action' => 'record', 'title' => 'SYNTHETIC instrument', 'terms' => 'SYNTHETIC terms', 'reason' => 'SYNTHETIC record'])->assertOk();
|
||||
}
|
||||
|
||||
private function url(): string
|
||||
{
|
||||
return '/parcerias/salas/'.$this->roomId.'/acordo';
|
||||
}
|
||||
|
||||
private function command(string $action = 'cancel'): array
|
||||
{
|
||||
$context = app(PartnershipExchange::class)->room($this->owner, $this->roomId);
|
||||
|
||||
return ['client_key' => (string) Str::uuid(), 'version' => $context['room']->version, 'partnership_version' => $context['partnership']->version, 'interest_version' => $context['interest']->version, 'action' => $action, 'reason' => 'SYNTHETIC documented action'];
|
||||
}
|
||||
|
||||
public function test_current_room_does_not_disclose_versions_from_an_older_organization(): void
|
||||
{
|
||||
$a = (string) Str::uuid();
|
||||
$b = (string) Str::uuid();
|
||||
$viewer = User::factory()->create();
|
||||
foreach ([$a, $b] as $org) {
|
||||
DB::table('organizations')->insert(['id' => $org, 'name' => 'SYNTHETIC organization', 'organization_type' => 'private']);
|
||||
DB::table('memberships')->insert(['user_id' => $this->owner->id, 'organization_id' => $org, 'role' => 'officer']);
|
||||
}
|
||||
DB::table('memberships')->insert(['user_id' => $viewer->id, 'organization_id' => $b, 'role' => 'viewer']);
|
||||
$exchange = app(PartnershipExchange::class);
|
||||
$parent = $exchange->room($this->owner, $this->roomId)['partnership'];
|
||||
$parent = $exchange->save($this->owner, ['version' => $parent->version, 'kind' => 'seeking', 'organization_id' => $a], $parent->id);
|
||||
$this->postJson($this->url(), [...$this->command('record'), 'title' => 'SYNTHETIC OLD PRIVATE INSTRUMENT', 'terms' => 'SYNTHETIC OLD PRIVATE CONDITIONS'])->assertOk();
|
||||
$exchange->save($this->owner, ['version' => $parent->version, 'kind' => 'seeking', 'organization_id' => $b], $parent->id);
|
||||
$this->postJson($this->url(), [...$this->command('record'), 'title' => 'SYNTHETIC CURRENT INSTRUMENT', 'terms' => 'SYNTHETIC CURRENT CONDITIONS'])->assertOk();
|
||||
$saved = DB::table('partnership_rooms')->where('id', $this->roomId)->value('agreement');
|
||||
$response = $this->actingAs($viewer)->getJson('/parcerias/salas/'.$this->roomId)->assertOk()->assertJsonPath('room.agreement.title', 'SYNTHETIC CURRENT INSTRUMENT')->assertJsonMissingPath('room.agreement.previous_versions');
|
||||
$this->assertStringNotContainsString('OLD PRIVATE', $response->getContent());
|
||||
$this->assertSame($saved, DB::table('partnership_rooms')->where('id', $this->roomId)->value('agreement'));
|
||||
$this->getJson('/parcerias/salas/'.$this->roomId.'/historico')->assertOk()->assertJsonPath('entries.1.restricted', true)->assertJsonPath('entries.1.after.availability', 'restricted');
|
||||
$this->actingAs($this->candidate)->getJson('/parcerias/salas/'.$this->roomId.'/historico')->assertOk()->assertJsonPath('entries.1.after.instrument.title', 'SYNTHETIC OLD PRIVATE INSTRUMENT');
|
||||
}
|
||||
|
||||
private function roomUrl(): string
|
||||
{
|
||||
return '/parcerias/salas/'.$this->roomId;
|
||||
}
|
||||
|
||||
private function instrument(): array
|
||||
{
|
||||
return json_decode(DB::table('partnership_rooms')->where('id', $this->roomId)->value('agreement'), true);
|
||||
}
|
||||
|
||||
private function storeInstrument(mixed $value): string
|
||||
{
|
||||
DB::table('partnership_rooms')->where('id', $this->roomId)->update(['agreement' => json_encode($value)]);
|
||||
|
||||
return DB::table('partnership_rooms')->where('id', $this->roomId)->value('agreement');
|
||||
}
|
||||
|
||||
public function test_current_fields_and_named_confirmations_survive_while_private_extensions_do_not(): void
|
||||
{
|
||||
$this->postJson($this->url(), $this->command('confirm'))->assertOk();
|
||||
$this->actingAs($this->candidate)->postJson($this->url(), $this->command('confirm'))->assertOk();
|
||||
$instrument = $this->instrument();
|
||||
$instrument['private_extension'] = ['secret' => 'SYNTHETIC INTERNAL SECRET'];
|
||||
$instrument['confirmations']['proponent']['actor_name'] = 'SYNTHETIC FORGED NAME';
|
||||
$instrument['confirmations']['proponent']['private_extension'] = 'SYNTHETIC INTERNAL SECRET';
|
||||
$saved = $this->storeInstrument($instrument);
|
||||
$response = $this->actingAs($this->owner)->getJson($this->roomUrl())->assertOk()
|
||||
->assertJsonPath('room.status', 'agreed')->assertJsonPath('room.agreement.title', 'SYNTHETIC instrument')
|
||||
->assertJsonPath('room.agreement.terms', 'SYNTHETIC terms')->assertJsonPath('room.agreement.legal_signature_status', 'not_verified')
|
||||
->assertJsonPath('room.agreement.confirmations.proponent.actor_id', $this->owner->id)
|
||||
->assertJsonPath('room.agreement.confirmations.candidate.actor_id', $this->candidate->id)
|
||||
->assertJsonPath('room.agreement.confirmations.proponent.reason', 'SYNTHETIC documented action')->assertJsonCount(1, 'agreementCommands');
|
||||
foreach (['previous_versions', 'recorded_context', 'private_extension', 'INTERNAL SECRET', 'FORGED NAME'] as $hidden) {
|
||||
$this->assertStringNotContainsString($hidden, $response->getContent());
|
||||
}
|
||||
$this->assertSame($instrument['confirmations']['proponent']['date'], $response->json('room.agreement.confirmations.proponent.date'));
|
||||
$this->assertSame($saved, DB::table('partnership_rooms')->where('id', $this->roomId)->value('agreement'));
|
||||
}
|
||||
|
||||
public function test_native_inertia_uses_the_same_current_projection_and_private_response(): void
|
||||
{
|
||||
$instrument = $this->instrument();
|
||||
$instrument['previous_versions'] = [['title' => 'SYNTHETIC NATIVE PRIVATE']];
|
||||
$instrument['private_extension'] = 'SYNTHETIC NATIVE PRIVATE';
|
||||
$this->storeInstrument($instrument);
|
||||
$this->get($this->roomUrl())->assertOk()->assertHeader('Cache-Control', 'no-store, private')
|
||||
->assertInertia(fn (Assert $page) => $page->component('partnerships/room')->where('room.id', $this->roomId)
|
||||
->where('room.agreement.title', 'SYNTHETIC instrument')->missing('room.agreement.previous_versions')->missing('room.agreement.recorded_context'))
|
||||
->assertDontSee('NATIVE PRIVATE');
|
||||
}
|
||||
|
||||
public function test_unrecognized_legacy_instruments_are_marked_without_echoing_opaque_content(): void
|
||||
{
|
||||
foreach (['SYNTHETIC OPAQUE PRIVATE', false, 123, ['SYNTHETIC OPAQUE PRIVATE']] as $value) {
|
||||
$saved = $this->storeInstrument($value);
|
||||
$response = $this->getJson($this->roomUrl())->assertOk()->assertJsonPath('room.agreement', 'unrecognized');
|
||||
$this->assertStringNotContainsString('OPAQUE PRIVATE', $response->getContent());
|
||||
$this->assertSame($saved, DB::table('partnership_rooms')->where('id', $this->roomId)->value('agreement'));
|
||||
}
|
||||
$this->storeInstrument(null);
|
||||
$this->getJson($this->roomUrl())->assertOk()->assertJsonPath('room.agreement', null);
|
||||
}
|
||||
|
||||
public function test_missing_null_empty_and_malformed_confirmation_maps_remain_distinguishable(): void
|
||||
{
|
||||
$base = $this->instrument();
|
||||
foreach ([null, [], (object) [], 'SYNTHETIC MAP PRIVATE', [['actor_id' => $this->owner->id]]] as $map) {
|
||||
$saved = $this->storeInstrument([...$base, 'confirmations' => $map]);
|
||||
$response = $this->getJson($this->roomUrl())->assertOk();
|
||||
$projected = $response->json('room.agreement.confirmations');
|
||||
if ($map === null) {
|
||||
$this->assertNull($projected);
|
||||
} elseif ($map === [] || $map instanceof \stdClass) {
|
||||
$this->assertSame([], $projected);
|
||||
} else {
|
||||
$this->assertSame('unrecognized', $projected);
|
||||
}
|
||||
$this->assertStringNotContainsString('MAP PRIVATE', $response->getContent());
|
||||
$this->assertSame($saved, DB::table('partnership_rooms')->where('id', $this->roomId)->value('agreement'));
|
||||
}
|
||||
unset($base['confirmations']);
|
||||
$this->storeInstrument($base);
|
||||
$this->getJson($this->roomUrl())->assertOk()->assertJsonMissingPath('room.agreement.confirmations');
|
||||
}
|
||||
|
||||
public function test_incomplete_stamps_and_unknown_references_do_not_disclose_their_raw_fields(): void
|
||||
{
|
||||
$value = $this->instrument();
|
||||
$value['confirmations'] = ['proponent' => ['actor_id' => 'SYNTHETIC BAD PRIVATE', 'date' => ['SYNTHETIC BAD PRIVATE'], 'reason' => ['secret' => 'SYNTHETIC BAD PRIVATE']], 'SYNTHETIC UNKNOWN PRIVATE' => ['actor_id' => $this->candidate->id]];
|
||||
$saved = $this->storeInstrument($value);
|
||||
$response = $this->getJson($this->roomUrl())->assertOk()->assertJsonPath('room.agreement.confirmations.proponent.actor_id', null)
|
||||
->assertJsonPath('room.agreement.confirmations.proponent.date', null)->assertJsonPath('room.agreement.confirmations.proponent.reason', null)
|
||||
->assertJsonPath('room.agreement.confirmations._unrecognized_references', true)->assertJsonMissingPath('room.agreement.confirmations.candidate');
|
||||
$this->assertStringNotContainsString('PRIVATE', $response->getContent());
|
||||
$this->assertSame($saved, DB::table('partnership_rooms')->where('id', $this->roomId)->value('agreement'));
|
||||
}
|
||||
|
||||
public function test_reads_and_replay_do_not_sanitize_the_stored_aggregate_or_its_audit_snapshots(): void
|
||||
{
|
||||
$original = $this->instrument();
|
||||
$original['private_extension'] = 'SYNTHETIC PRESERVED PRIVATE';
|
||||
$original['previous_versions'] = [['title' => 'SYNTHETIC HISTORICAL PRIVATE']];
|
||||
$this->storeInstrument($original);
|
||||
$command = [...$this->command('record'), 'title' => 'SYNTHETIC new public-facing title', 'terms' => 'SYNTHETIC new terms'];
|
||||
$this->postJson($this->url(), $command)->assertOk();
|
||||
$saved = DB::table('partnership_rooms')->where('id', $this->roomId)->value('agreement');
|
||||
$stored = $this->instrument();
|
||||
$this->assertSame('SYNTHETIC PRESERVED PRIVATE', $stored['previous_versions'][1]['private_extension']);
|
||||
$events = DB::table('partnership_events')->count();
|
||||
$audits = DB::table('audit_events')->count();
|
||||
$notices = DB::table('partnership_notifications')->count();
|
||||
$this->getJson($this->roomUrl())->assertOk()->assertJsonMissingPath('room.agreement.previous_versions');
|
||||
$this->postJson($this->url(), $command)->assertOk()->assertJsonPath('replayed', true);
|
||||
$this->assertSame($saved, DB::table('partnership_rooms')->where('id', $this->roomId)->value('agreement'));
|
||||
$this->assertSame($events, DB::table('partnership_events')->count());
|
||||
$this->assertSame($audits, DB::table('audit_events')->count());
|
||||
$this->assertSame($notices, DB::table('partnership_notifications')->count());
|
||||
$event = DB::table('partnership_events')->where('event_type', 'partnership_agreement.changed.v1')->orderByDesc('aggregate_version')->first();
|
||||
$data = json_decode($event->payload, true)['payload'];
|
||||
$this->assertSame('SYNTHETIC PRESERVED PRIVATE', $data['previous']['agreement']['private_extension']);
|
||||
$this->assertSame($stored, $data['applied']['agreement']);
|
||||
}
|
||||
|
||||
public function test_current_representation_and_private_room_access_still_apply(): void
|
||||
{
|
||||
$outsider = User::factory()->create();
|
||||
config(['portal.managers' => [$outsider->email]]);
|
||||
$this->actingAs($outsider)->getJson($this->roomUrl())->assertForbidden();
|
||||
$org = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $org, 'name' => 'SYNTHETIC access', 'organization_type' => 'private']);
|
||||
DB::table('memberships')->insert(['user_id' => $this->owner->id, 'organization_id' => $org, 'role' => 'viewer']);
|
||||
DB::table('portal_partnerships')->where('id', app(PartnershipExchange::class)->room($this->owner, $this->roomId)['partnership']->id)->update(['organization_id' => $org]);
|
||||
$this->actingAs($this->owner)->getJson($this->roomUrl())->assertOk()->assertJsonPath('canWrite', false)->assertJsonPath('agreementCommands', []);
|
||||
$this->postJson($this->url(), $this->command('confirm'))->assertForbidden();
|
||||
DB::table('memberships')->where('user_id', $this->owner->id)->update(['deleted_at' => now()]);
|
||||
$this->getJson($this->roomUrl())->assertForbidden();
|
||||
$this->actingAs($this->candidate)->getJson($this->roomUrl())->assertOk();
|
||||
}
|
||||
|
||||
public function test_other_room_consumers_link_to_the_room_without_embedding_its_instrument_history(): void
|
||||
{
|
||||
$value = $this->instrument();
|
||||
$value['previous_versions'] = [['title' => 'SYNTHETIC OTHER CONSUMER PRIVATE']];
|
||||
$this->storeInstrument($value);
|
||||
$parent = app(PartnershipExchange::class)->room($this->owner, $this->roomId)['partnership'];
|
||||
$response = $this->getJson('/parcerias/'.$parent->id)->assertOk()->assertJsonPath('interests.0.room_id', $this->roomId);
|
||||
$this->assertStringNotContainsString('OTHER CONSUMER PRIVATE', $response->getContent());
|
||||
$this->actingAs($this->candidate)->get('/parcerias/painel')->assertOk()
|
||||
->assertInertia(fn (Assert $page) => $page->component('partnerships/dashboard')->where('interests.0.room_id', $this->roomId))
|
||||
->assertDontSee('OTHER CONSUMER PRIVATE');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\PartnershipExchange;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Facades\Queue;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class PartnershipAgreementRecoveryTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $owner;
|
||||
|
||||
private User $candidate;
|
||||
|
||||
private int $roomId;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
Http::fake();
|
||||
Mail::fake();
|
||||
Queue::fake();
|
||||
$this->owner = User::factory()->create();
|
||||
$this->candidate = User::factory()->create();
|
||||
$moderator = User::factory()->create();
|
||||
config(['portal.managers' => [$moderator->email]]);
|
||||
$service = app(PartnershipExchange::class);
|
||||
$record = $service->save($this->owner, ['client_key' => (string) Str::uuid(), 'title' => 'SYNTHETIC agreement', 'kind' => 'seeking', 'partnership_type' => 'joint_venture', 'offer' => 'SYNTHETIC offer', 'payload' => ['consent' => true]]);
|
||||
$record = $service->transition($this->owner, $record->id, $record->version, 'submit', 'SYNTHETIC submit');
|
||||
$record = $service->transition($moderator, $record->id, $record->version, 'publish', 'SYNTHETIC publish');
|
||||
$interest = $service->interest($this->candidate, $record->id, ['proposal' => 'SYNTHETIC candidacy', 'payload' => ['consent' => true]]);
|
||||
$interest = $service->decideInterest($this->owner, $interest->id, $interest->version, 'shortlist', 'SYNTHETIC shortlist');
|
||||
$service->decideInterest($this->owner, $interest->id, $interest->version, 'connect', 'SYNTHETIC connect');
|
||||
$this->roomId = (int) DB::table('partnership_rooms')->where('interest_id', $interest->id)->value('id');
|
||||
$this->actingAs($this->owner)->postJson($this->url(), ['version' => 1, 'action' => 'record', 'title' => 'SYNTHETIC instrument', 'terms' => 'SYNTHETIC terms', 'reason' => 'SYNTHETIC record'])->assertOk();
|
||||
}
|
||||
|
||||
private function url(): string
|
||||
{
|
||||
return '/parcerias/salas/'.$this->roomId.'/acordo';
|
||||
}
|
||||
|
||||
private function command(string $action = 'cancel'): array
|
||||
{
|
||||
$context = app(PartnershipExchange::class)->room($this->owner, $this->roomId);
|
||||
|
||||
return ['client_key' => (string) Str::uuid(), 'version' => $context['room']->version, 'partnership_version' => $context['partnership']->version, 'interest_version' => $context['interest']->version, 'action' => $action, 'reason' => 'SYNTHETIC documented action'];
|
||||
}
|
||||
|
||||
public function test_cancel_replay_after_terminal_state_is_a_read_without_repeated_events(): void
|
||||
{
|
||||
$data = $this->command();
|
||||
$this->postJson($this->url(), $data)->assertOk();
|
||||
$events = DB::table('partnership_events')->count();
|
||||
$audits = DB::table('audit_events')->count();
|
||||
$notices = DB::table('partnership_notifications')->count();
|
||||
$this->postJson($this->url(), $data)->assertOk()->assertJsonPath('replayed', true)->assertJsonPath('status', 'cancelled');
|
||||
$this->assertSame($events, DB::table('partnership_events')->count());
|
||||
$this->assertSame($audits, DB::table('audit_events')->count());
|
||||
$this->assertSame($notices, DB::table('partnership_notifications')->count());
|
||||
}
|
||||
|
||||
public function test_changed_proposal_context_requires_review_even_when_room_version_is_unchanged(): void
|
||||
{
|
||||
$data = $this->command('confirm');
|
||||
$context = app(PartnershipExchange::class)->room($this->owner, $this->roomId);
|
||||
$record = $context['partnership'];
|
||||
app(PartnershipExchange::class)->save($this->owner, ['version' => $record->version, 'kind' => 'seeking', 'title' => 'SYNTHETIC changed proposal'], $record->id);
|
||||
$this->postJson($this->url(), $data)->assertConflict();
|
||||
$this->assertSame(2, DB::table('partnership_rooms')->where('id', $this->roomId)->value('version'));
|
||||
}
|
||||
|
||||
private function instrument(): array
|
||||
{
|
||||
return json_decode(DB::table('partnership_rooms')->where('id', $this->roomId)->value('agreement'), true);
|
||||
}
|
||||
|
||||
private function confirmBoth(): void
|
||||
{
|
||||
$this->actingAs($this->owner)->postJson($this->url(), $this->command('confirm'))->assertOk();
|
||||
$this->actingAs($this->candidate)->postJson($this->url(), $this->command('confirm'))->assertOk()->assertJsonPath('status', 'agreed');
|
||||
$this->actingAs($this->owner);
|
||||
}
|
||||
|
||||
public function test_record_replay_preserves_a_later_confirmation(): void
|
||||
{
|
||||
$data = [...$this->command('record'), 'title' => 'SYNTHETIC revised instrument', 'terms' => 'SYNTHETIC revised terms'];
|
||||
$this->postJson($this->url(), $data)->assertOk();
|
||||
$this->postJson($this->url(), $this->command('confirm'))->assertOk();
|
||||
$before = $this->instrument();
|
||||
$events = DB::table('partnership_events')->count();
|
||||
$this->postJson($this->url(), $data)->assertOk()->assertJsonPath('replayed', true)->assertJsonPath('saved_version', 3);
|
||||
$this->assertSame($before, $this->instrument());
|
||||
$this->assertSame($events, DB::table('partnership_events')->count());
|
||||
}
|
||||
|
||||
public function test_key_conflicts_and_case_normalization_do_not_duplicate_decisions(): void
|
||||
{
|
||||
$data = $this->command('confirm');
|
||||
$this->postJson($this->url(), $data)->assertOk();
|
||||
$events = DB::table('partnership_events')->count();
|
||||
$this->postJson($this->url(), [...$data, 'reason' => 'SYNTHETIC changed reason'])->assertConflict();
|
||||
$this->postJson($this->url(), [...$data, 'client_key' => strtoupper($data['client_key'])])->assertOk()->assertJsonPath('replayed', true);
|
||||
$this->assertSame($events, DB::table('partnership_events')->count());
|
||||
}
|
||||
|
||||
public function test_only_the_two_named_parties_count_and_supplied_party_does_not_override_authority(): void
|
||||
{
|
||||
$agreement = $this->instrument();
|
||||
$agreement['confirmations'] = ['unrelated' => ['actor_id' => $this->candidate->id, 'date' => 'SYNTHETIC']];
|
||||
DB::table('partnership_rooms')->where('id', $this->roomId)->update(['agreement' => json_encode($agreement)]);
|
||||
$data = $this->command('confirm');
|
||||
$this->postJson($this->url(), [...$data, 'party' => 'candidate', 'actor_id' => $this->candidate->id])->assertOk()->assertJsonPath('status', 'agreement_recorded');
|
||||
$this->assertSame($this->owner->id, $this->instrument()['confirmations']['proponent']['actor_id']);
|
||||
$this->assertArrayNotHasKey('candidate', $this->instrument()['confirmations']);
|
||||
$this->actingAs($this->candidate)->postJson($this->url(), [...$this->command('confirm'), 'client_key' => $data['client_key']])->assertOk()->assertJsonPath('replayed', false)->assertJsonPath('status', 'agreed');
|
||||
$this->assertSame('not_verified', $this->instrument()['legal_signature_status']);
|
||||
}
|
||||
|
||||
public function test_record_and_renew_preserve_versions_and_reset_only_their_confirmation_set(): void
|
||||
{
|
||||
$this->postJson($this->url(), [...$this->command('record'), 'title' => 'SYNTHETIC version two', 'terms' => 'SYNTHETIC version two terms'])->assertOk();
|
||||
$this->assertSame('SYNTHETIC instrument', $this->instrument()['previous_versions'][0]['title']);
|
||||
$this->confirmBoth();
|
||||
$data = $this->command('renew');
|
||||
$this->postJson($this->url(), $data)->assertOk()->assertJsonPath('status', 'negotiation');
|
||||
$instrument = $this->instrument();
|
||||
$this->assertCount(2, $instrument['previous_versions']);
|
||||
$this->assertSame([], $instrument['confirmations']);
|
||||
$this->assertArrayHasKey('recorded_context', $instrument['previous_versions'][1]);
|
||||
$this->assertArrayHasKey('proponent', $instrument['previous_versions'][1]['confirmations']);
|
||||
$this->postJson($this->url(), $data)->assertOk()->assertJsonPath('replayed', true);
|
||||
$this->assertSame($instrument, $this->instrument());
|
||||
}
|
||||
|
||||
public function test_completion_requires_finished_milestones_and_closure_replay_is_read_only(): void
|
||||
{
|
||||
$this->confirmBoth();
|
||||
$data = ['title' => 'SYNTHETIC delivery', 'responsible_id' => $this->candidate->id, 'status' => 'pending'];
|
||||
$this->postJson('/parcerias/salas/'.$this->roomId.'/marcos', $data)->assertOk();
|
||||
$this->postJson($this->url(), $this->command('start'))->assertOk()->assertJsonPath('status', 'execution');
|
||||
$complete = $this->command('complete');
|
||||
$this->postJson($this->url(), $complete)->assertConflict();
|
||||
$item = DB::table('partnership_milestones')->where('room_id', $this->roomId)->first();
|
||||
$this->putJson('/parcerias/salas/'.$this->roomId.'/marcos/'.$item->id, [...$data, 'version' => $item->version, 'status' => 'completed', 'evidence' => 'SYNTHETIC evidence'])->assertOk();
|
||||
$this->postJson($this->url(), $complete)->assertOk()->assertJsonPath('status', 'closed');
|
||||
$events = DB::table('partnership_events')->count();
|
||||
$this->postJson($this->url(), $complete)->assertOk()->assertJsonPath('replayed', true);
|
||||
$this->assertSame($events, DB::table('partnership_events')->count());
|
||||
$this->assertSame('completed', DB::table('partnership_milestones')->where('id', $item->id)->value('status'));
|
||||
}
|
||||
|
||||
public function test_revocation_or_read_only_role_prevents_replay_and_private_command_receipts(): void
|
||||
{
|
||||
$context = app(PartnershipExchange::class)->room($this->owner, $this->roomId);
|
||||
$org = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $org, 'name' => 'SYNTHETIC agreement organization', 'organization_type' => 'private']);
|
||||
DB::table('memberships')->insert(['user_id' => $this->owner->id, 'organization_id' => $org, 'role' => 'officer']);
|
||||
app(PartnershipExchange::class)->save($this->owner, ['version' => $context['partnership']->version, 'kind' => 'seeking', 'organization_id' => $org], $context['partnership']->id);
|
||||
$data = $this->command();
|
||||
$this->postJson($this->url(), $data)->assertOk();
|
||||
DB::table('memberships')->where('organization_id', $org)->where('user_id', $this->owner->id)->update(['role' => 'viewer']);
|
||||
$this->postJson($this->url(), $data)->assertForbidden();
|
||||
$this->getJson('/parcerias/salas/'.$this->roomId)->assertOk()->assertJsonPath('agreementCommands', [])->assertJsonPath('agreementParty', null)->assertJsonPath('canWrite', false);
|
||||
DB::table('memberships')->where('organization_id', $org)->where('user_id', $this->owner->id)->update(['deleted_at' => now()]);
|
||||
$this->postJson($this->url(), $data)->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_receipts_are_actor_specific_and_snapshots_do_not_expose_internal_hashes(): void
|
||||
{
|
||||
$data = $this->command('confirm');
|
||||
$this->postJson($this->url(), $data)->assertOk();
|
||||
$response = $this->getJson('/parcerias/salas/'.$this->roomId)->assertOk()->assertJsonPath('agreementActorId', $this->owner->id)->assertJsonPath('agreementParty', 'proponent')->assertJsonPath('agreementCommands.0.key', $data['client_key'])->assertJsonPath('agreementCommands.0.party', 'proponent');
|
||||
foreach (['command_hash', '_creation_hash', '_notification_context'] as $key) {
|
||||
$this->assertStringNotContainsString($key, $response->getContent());
|
||||
}$this->actingAs($this->candidate)->getJson('/parcerias/salas/'.$this->roomId)->assertOk()->assertJsonPath('agreementCommands', [])->assertJsonPath('agreementParty', 'candidate');
|
||||
$event = DB::table('partnership_events')->where('event_type', 'partnership_agreement.changed.v1')->orderByDesc('aggregate_version')->first();
|
||||
$metadata = json_decode($event->payload, true)['payload'];
|
||||
$this->assertSame('SYNTHETIC terms', $metadata['previous']['agreement']['terms']);
|
||||
$this->assertSame($this->owner->id, $metadata['applied']['agreement']['confirmations']['proponent']['actor_id']);
|
||||
$this->assertSame('proponent', $metadata['confirmation_party']);
|
||||
}
|
||||
|
||||
public function test_context_tokens_reject_stale_candidacy_and_legacy_calls_keep_the_room_protocol(): void
|
||||
{
|
||||
$data = $this->command('confirm');
|
||||
$this->postJson($this->url(), [...$data, 'interest_version' => $data['interest_version'] + 1])->assertConflict();
|
||||
$this->postJson($this->url(), [...$data, 'client_key' => 'invalid'])->assertUnprocessable();
|
||||
unset($data['client_key'],$data['interest_version'],$data['partnership_version']);
|
||||
$this->postJson($this->url(), $data)->assertOk()->assertJsonPath('replayed', false);
|
||||
}
|
||||
|
||||
public function test_malformed_legacy_instrument_is_not_overwritten_or_a_server_error(): void
|
||||
{
|
||||
$instrument = $this->instrument();
|
||||
$instrument['previous_versions'] = 'SYNTHETIC invalid legacy';
|
||||
DB::table('partnership_rooms')->where('id', $this->roomId)->update(['agreement' => json_encode($instrument)]);
|
||||
$events = DB::table('partnership_events')->count();
|
||||
$this->postJson($this->url(), [...$this->command('record'), 'title' => 'SYNTHETIC new title', 'terms' => 'SYNTHETIC new terms'])->assertConflict();
|
||||
$this->assertSame($instrument, $this->instrument());
|
||||
$this->assertSame($events, DB::table('partnership_events')->count());
|
||||
$instrument['previous_versions'] = [];
|
||||
$instrument['confirmations'] = 'SYNTHETIC invalid confirmations';
|
||||
DB::table('partnership_rooms')->where('id', $this->roomId)->update(['agreement' => json_encode($instrument)]);
|
||||
$this->postJson($this->url(), $this->command('confirm'))->assertConflict();
|
||||
}
|
||||
|
||||
public function test_keys_are_room_scoped_and_moderation_does_not_grant_private_room_access(): void
|
||||
{
|
||||
$data = $this->command();
|
||||
$this->postJson($this->url(), $data)->assertOk();
|
||||
$service = app(PartnershipExchange::class);
|
||||
$context = $service->room($this->owner, $this->roomId);
|
||||
$other = User::factory()->create();
|
||||
$interest = $service->interest($other, $context['partnership']->id, ['proposal' => 'SYNTHETIC other candidature', 'payload' => ['consent' => true]]);
|
||||
$interest = $service->decideInterest($this->owner, $interest->id, $interest->version, 'shortlist', 'SYNTHETIC shortlist');
|
||||
$interest = $service->decideInterest($this->owner, $interest->id, $interest->version, 'connect', 'SYNTHETIC connect');
|
||||
$room = DB::table('partnership_rooms')->where('interest_id',$interest->id)->first();
|
||||
$this->postJson('/parcerias/salas/'.$room->id.'/acordo',[...$data, 'version' => $room->version, 'interest_version' => $interest->version])->assertOk()->assertJsonPath('replayed',false);
|
||||
config(['portal.managers' => [$other->email]]);
|
||||
$this->actingAs($other)->postJson($this->url(),$data)->assertForbidden();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\PartnershipExchange;
|
||||
use App\Services\PartnershipMatching;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Facades\Queue;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class PartnershipCandidaciesTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $owner;
|
||||
|
||||
private User $candidate;
|
||||
|
||||
private object $record;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
Http::fake();
|
||||
Mail::fake();
|
||||
Queue::fake();
|
||||
$this->owner = User::factory()->create();
|
||||
$this->candidate = User::factory()->create();
|
||||
$this->record = $this->published($this->owner);
|
||||
$this->actingAs($this->candidate);
|
||||
}
|
||||
|
||||
private function published(User $owner): object
|
||||
{
|
||||
$service = app(PartnershipExchange::class);
|
||||
$record = $service->save($owner, ['client_key' => (string) Str::uuid(), 'title' => 'SYNTHETIC candidature context', 'kind' => 'seeking', 'partnership_type' => 'joint_venture', 'offer' => 'SYNTHETIC offer', 'seeking' => 'SYNTHETIC cooperation', 'payload' => ['consent' => true, 'mandatory' => ['capacity']]]);
|
||||
$record = $service->transition($owner, $record->id, $record->version, 'submit', 'SYNTHETIC submission');
|
||||
$moderator = User::factory()->create();
|
||||
config(['portal.managers' => [$moderator->email]]);
|
||||
|
||||
return $service->transition($moderator, $record->id, $record->version, 'publish', 'SYNTHETIC independent review');
|
||||
}
|
||||
|
||||
private function input(array $changes = []): array
|
||||
{
|
||||
return ['proposal' => 'SYNTHETIC original proposal', 'payload' => ['consent' => true, 'capacity' => 'SYNTHETIC original capacity', 'availability' => 'SYNTHETIC original availability', 'contribution' => 'SYNTHETIC original contribution', 'conflicts' => 'SYNTHETIC declared conflicts'], ...$changes];
|
||||
}
|
||||
|
||||
private function url(): string
|
||||
{
|
||||
return '/parcerias/'.$this->record->id.'/interesses';
|
||||
}
|
||||
|
||||
private function interest(array $changes = [], ?User $actor = null): object
|
||||
{
|
||||
return app(PartnershipExchange::class)->interest($actor ?? $this->candidate, $this->record->id, $this->input($changes));
|
||||
}
|
||||
|
||||
private function organization(User $user, string $role = 'officer'): string
|
||||
{
|
||||
$id = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $id, 'name' => 'SYNTHETIC candidacy organization', 'organization_type' => 'private']);
|
||||
DB::table('memberships')->insert(['user_id' => $user->id, 'organization_id' => $id, 'role' => $role]);
|
||||
|
||||
return $id;
|
||||
}
|
||||
|
||||
public function test_omitted_declarations_and_organization_survive_a_partial_resubmission(): void
|
||||
{
|
||||
$org = $this->organization($this->candidate);
|
||||
$interest = $this->interest(['organization_id' => $org]);
|
||||
$this->postJson($this->url(), ['interest_id' => $interest->id, 'version' => $interest->version, 'proposal' => 'SYNTHETIC changed proposal', 'payload' => ['consent' => true]])->assertOk();
|
||||
$saved = DB::table('partnership_interests')->where('id', $interest->id)->first();
|
||||
$this->assertSame($org, $saved->organization_id);
|
||||
$payload = json_decode($saved->payload, true);
|
||||
$this->assertSame('SYNTHETIC original capacity', $payload['capacity']);
|
||||
$this->assertSame('SYNTHETIC original availability', $payload['availability']);
|
||||
$this->assertSame('SYNTHETIC declared conflicts', $payload['conflicts']);
|
||||
}
|
||||
|
||||
public function test_explicit_candidacy_identity_updates_the_selected_withdrawn_organization_record(): void
|
||||
{
|
||||
$personal = $this->interest();
|
||||
$otherAuthor = User::factory()->create();
|
||||
$org = $this->organization($otherAuthor);
|
||||
DB::table('memberships')->insert(['user_id' => $this->candidate->id, 'organization_id' => $org, 'role' => 'officer']);
|
||||
$organizational = $this->interest(['organization_id' => $org], $otherAuthor);
|
||||
$organizational = app(PartnershipExchange::class)->decideInterest($otherAuthor, $organizational->id, $organizational->version, 'withdraw', 'SYNTHETIC withdrawal');
|
||||
DB::table('partnership_interests')->where('id', $personal->id)->update(['version' => $organizational->version]);
|
||||
$this->postJson($this->url(), $this->input(['interest_id' => $organizational->id, 'version' => $organizational->version, 'organization_id' => $org, 'proposal' => 'SYNTHETIC intended organization update']))->assertOk()->assertJsonPath('id', $organizational->id);
|
||||
$this->assertDatabaseHas('partnership_interests', ['id' => $personal->id, 'organization_id' => null, 'proposal' => 'SYNTHETIC original proposal']);
|
||||
$this->assertDatabaseHas('partnership_interests', ['id' => $organizational->id, 'status' => 'submitted', 'proposal' => 'SYNTHETIC intended organization update']);
|
||||
}
|
||||
|
||||
public function test_read_only_representative_can_consult_but_has_no_candidacy_write_actions(): void
|
||||
{
|
||||
$org = $this->organization($this->candidate);
|
||||
$interest = $this->interest(['organization_id' => $org]);
|
||||
$viewer = User::factory()->create();
|
||||
DB::table('memberships')->insert(['user_id' => $viewer->id, 'organization_id' => $org, 'role' => 'viewer']);
|
||||
$this->actingAs($viewer)->getJson('/parcerias/'.$this->record->id)->assertOk()->assertJsonPath('interests.0.can_edit', false);
|
||||
$this->postJson($this->url(), $this->input(['interest_id' => $interest->id, 'version' => 1, 'organization_id' => $org]))->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_owning_actor_can_recover_a_committed_submission_without_resetting_assessment_or_version(): void
|
||||
{
|
||||
$input = $this->input(['client_key' => (string) Str::uuid()]);
|
||||
$interest = app(PartnershipExchange::class)->interest($this->candidate, $this->record->id, $input);
|
||||
$assessed = app(PartnershipExchange::class)->decideInterest($this->owner, $interest->id, 1, 'assess', 'SYNTHETIC evidence reviewed', ['capacity' => ['state' => 'met', 'evidence' => 'SYNTHETIC evidence']]);
|
||||
$before = DB::table('partnership_events')->count();
|
||||
$this->postJson($this->url(), $input)->assertOk()->assertJsonPath('id', $interest->id)->assertJsonPath('version', $assessed->version)->assertJsonPath('replayed', true);
|
||||
$this->assertSame($before, DB::table('partnership_events')->count());
|
||||
$this->assertSame('met', json_decode(DB::table('partnership_interests')->where('id', $interest->id)->value('assessment'), true)['capacity']['state']);
|
||||
}
|
||||
|
||||
public function test_explicit_clearing_creates_a_new_submission_and_preserves_the_previous_evaluation_in_the_event(): void
|
||||
{
|
||||
$org = $this->organization($this->candidate);
|
||||
$interest = $this->interest(['organization_id' => $org]);
|
||||
$interest = app(PartnershipExchange::class)->decideInterest($this->owner, $interest->id, 1, 'assess', 'SYNTHETIC evidence reviewed', ['capacity' => ['state' => 'met', 'evidence' => 'SYNTHETIC prior evidence']]);
|
||||
$input = $this->input(['client_key' => (string) Str::uuid(), 'interest_id' => $interest->id, 'version' => 2, 'organization_id' => null, 'payload' => ['consent' => true, 'capacity' => '', 'conflicts' => null]]);
|
||||
$this->postJson($this->url(), $input)->assertOk()->assertJsonPath('version', 3);
|
||||
$saved = DB::table('partnership_interests')->where('id', $interest->id)->first();
|
||||
$this->assertNull($saved->organization_id);
|
||||
$this->assertEmpty(json_decode($saved->assessment, true));
|
||||
$this->assertNull(json_decode($saved->payload, true)['capacity']);
|
||||
$this->assertNull(json_decode($saved->payload, true)['conflicts']);
|
||||
$event = DB::table('partnership_events')->where('event_type', 'partnership_interest.submitted.v1')->orderByDesc('aggregate_version')->first();
|
||||
$payload = json_decode($event->payload, true)['payload'];
|
||||
$this->assertSame(2, $payload['previous']['version']);
|
||||
$this->assertSame($org, $payload['previous']['organization_id']);
|
||||
$this->assertSame('SYNTHETIC prior evidence', $payload['previous']['assessment']['capacity']['evidence']);
|
||||
$this->assertSame('SYNTHETIC original capacity', $payload['previous']['payload']['capacity']);
|
||||
$this->assertSame(3, $payload['submitted']['version']);
|
||||
}
|
||||
|
||||
public function test_ambiguous_legacy_submission_and_a_foreign_candidacy_cannot_change_another_record(): void
|
||||
{
|
||||
$personal = $this->interest();
|
||||
$other = User::factory()->create();
|
||||
$org = $this->organization($other);
|
||||
DB::table('memberships')->insert(['user_id' => $this->candidate->id, 'organization_id' => $org, 'role' => 'officer']);
|
||||
$organizational = $this->interest(['organization_id' => $org], $other);
|
||||
$this->postJson($this->url(), $this->input(['version' => 1, 'organization_id' => $org]))->assertConflict();
|
||||
$different = $this->published(User::factory()->create());
|
||||
$foreign = app(PartnershipExchange::class)->interest($this->candidate, $different->id, $this->input());
|
||||
$this->postJson($this->url(), $this->input(['interest_id' => $foreign->id, 'version' => 1]))->assertNotFound();
|
||||
$this->assertDatabaseHas('partnership_interests', ['id' => $personal->id, 'organization_id' => null, 'version' => 1]);
|
||||
$this->assertDatabaseHas('partnership_interests', ['id' => $organizational->id, 'organization_id' => $org, 'version' => 1]);
|
||||
}
|
||||
|
||||
public function test_replay_is_content_bound_case_normalized_and_never_grants_revoked_representation(): void
|
||||
{
|
||||
$org = $this->organization($this->candidate);
|
||||
$input = $this->input(['organization_id' => $org, 'client_key' => (string) Str::uuid()]);
|
||||
$interest = app(PartnershipExchange::class)->interest($this->candidate, $this->record->id, $input);
|
||||
$this->postJson($this->url(), [...$input, 'client_key' => strtoupper($input['client_key'])])->assertOk()->assertJsonPath('replayed', true);
|
||||
$this->postJson($this->url(), [...$input, 'proposal' => 'SYNTHETIC different content'])->assertConflict();
|
||||
DB::table('memberships')->where('organization_id', $org)->update(['deleted_at' => now()]);
|
||||
$this->postJson($this->url(), $input)->assertForbidden();
|
||||
$this->getJson('/parcerias/'.$this->record->id)->assertOk()->assertJsonPath('canStartInterest', false)->assertJsonCount(0, 'interests');
|
||||
$this->assertDatabaseHas('partnership_interests', ['id' => $interest->id, 'version' => 1]);
|
||||
}
|
||||
|
||||
public function test_submission_and_decision_reject_stale_partnership_context_without_writes(): void
|
||||
{
|
||||
$interest = $this->interest();
|
||||
$before = DB::table('partnership_events')->count();
|
||||
$this->postJson($this->url(), $this->input(['interest_id' => $interest->id, 'version' => 1, 'partnership_version' => $this->record->version - 1]))->assertConflict();
|
||||
$this->actingAs($this->owner)->postJson('/parcerias/candidaturas/'.$interest->id, ['version' => 1, 'partnership_version' => $this->record->version - 1, 'action' => 'assess', 'reason' => 'SYNTHETIC stale context', 'assessment' => ['capacity' => ['state' => 'met', 'evidence' => 'SYNTHETIC stale evidence']]])->assertConflict();
|
||||
$this->assertSame($before, DB::table('partnership_events')->count());
|
||||
$this->assertDatabaseHas('partnership_interests', ['id' => $interest->id, 'version' => 1, 'assessment' => '{}']);
|
||||
}
|
||||
|
||||
public function test_matching_weights_are_checked_and_legacy_decisions_keep_their_existing_path(): void
|
||||
{
|
||||
$interest = $this->interest();
|
||||
$hash = app(PartnershipMatching::class)->explain($this->record, $interest)['weights_hash'];
|
||||
config(['partnerships.weights.capacity' => 21]);
|
||||
$this->actingAs($this->owner)->postJson('/parcerias/candidaturas/'.$interest->id, ['version' => 1, 'partnership_version' => $this->record->version, 'weights_hash' => $hash, 'action' => 'assess', 'reason' => 'SYNTHETIC old weights', 'assessment' => ['capacity' => ['state' => 'met', 'evidence' => 'SYNTHETIC evidence']]])->assertConflict();
|
||||
$this->postJson('/parcerias/candidaturas/'.$interest->id, ['version' => 1, 'action' => 'assess', 'reason' => 'SYNTHETIC legacy client', 'assessment' => ['capacity' => ['state' => 'met', 'evidence' => 'SYNTHETIC evidence', 'irrelevant' => 'Must not persist']]])->assertOk();
|
||||
$stored = json_decode(DB::table('partnership_interests')->where('id', $interest->id)->value('assessment'), true)['capacity'];
|
||||
$this->assertArrayNotHasKey('irrelevant', $stored);
|
||||
$this->assertSame($this->owner->id, $stored['assessed_by']);
|
||||
$event = DB::table('partnership_events')->where('event_type', 'partnership_interest.changed.v1')->orderByDesc('aggregate_version')->first();
|
||||
$payload = json_decode($event->payload, true)['payload'];
|
||||
$this->assertSame($this->record->version, $payload['partnership_version']);
|
||||
$this->assertNotSame($hash, $payload['matching_context']['weights_hash']);
|
||||
$this->assertSame('transparent-rules.v1', $payload['matching_context']['algorithm_version']);
|
||||
$capacity = array_values(array_filter($payload['matching_context']['criteria'], fn ($criterion) => $criterion['code'] === 'capacity'))[0];
|
||||
$this->assertSame(21, $capacity['weight']);
|
||||
$this->assertTrue($capacity['mandatory']);
|
||||
}
|
||||
|
||||
public function test_replaying_a_decision_does_not_repeat_events_or_affect_another_candidacy(): void
|
||||
{
|
||||
$interest = $this->interest();
|
||||
$other = $this->interest([], User::factory()->create());
|
||||
$input = ['client_key' => (string) Str::uuid(), 'version' => 1, 'action' => 'shortlist', 'reason' => 'SYNTHETIC shortlist unknown evidence'];
|
||||
$this->actingAs($this->owner)->postJson('/parcerias/candidaturas/'.$interest->id, $input)->assertOk();
|
||||
$events = DB::table('partnership_events')->count();
|
||||
$this->postJson('/parcerias/candidaturas/'.$interest->id, $input)->assertOk()->assertJsonPath('replayed', true)->assertJsonPath('version', 2);
|
||||
$this->postJson('/parcerias/candidaturas/'.$other->id, $input)->assertConflict();
|
||||
$this->assertSame($events, DB::table('partnership_events')->count());
|
||||
$this->assertDatabaseHas('partnership_interests', ['id' => $other->id, 'version' => 1, 'status' => 'submitted']);
|
||||
$this->getJson('/parcerias/'.$this->record->id)->assertOk()->assertJsonPath('interests.0.commands.0.key', $input['client_key']);
|
||||
$this->actingAs($this->candidate)->getJson('/parcerias/'.$this->record->id)->assertOk()->assertJsonCount(0, 'interests.0.commands');
|
||||
}
|
||||
|
||||
public function test_withdrawal_and_read_only_recovery_do_not_depend_on_a_current_publication_window(): void
|
||||
{
|
||||
$input = $this->input(['client_key' => (string) Str::uuid()]);
|
||||
$interest = app(PartnershipExchange::class)->interest($this->candidate, $this->record->id, $input);
|
||||
DB::table('portal_partnerships')->where('id', $this->record->id)->update(['status' => 'archived', 'version' => $this->record->version + 1]);
|
||||
$withdraw = ['client_key' => (string) Str::uuid(), 'version' => 1, 'partnership_version' => 1, 'weights_hash' => str_repeat('0', 64), 'action' => 'withdraw', 'reason' => 'SYNTHETIC withdrawal independent of publication'];
|
||||
$this->postJson('/parcerias/candidaturas/'.$interest->id, $withdraw)->assertOk();
|
||||
$this->postJson($this->url(), $input)->assertOk()->assertJsonPath('replayed', true)->assertJsonPath('version', 2);
|
||||
$this->postJson('/parcerias/candidaturas/'.$interest->id, $withdraw)->assertOk()->assertJsonPath('replayed', true);
|
||||
$this->postJson($this->url(), $this->input(['interest_id' => $interest->id, 'version' => 2]))->assertConflict();
|
||||
$this->assertDatabaseHas('partnership_interests', ['id' => $interest->id, 'status' => 'withdrawn', 'version' => 2]);
|
||||
}
|
||||
|
||||
public function test_explicit_update_replay_preserves_later_decisions_and_requires_accepted_consent(): void
|
||||
{
|
||||
$interest = $this->interest();
|
||||
$input = $this->input(['interest_id' => $interest->id, 'version' => 1, 'client_key' => (string) Str::uuid()]);
|
||||
$this->postJson($this->url(), [...$input, 'payload' => ['consent' => false]])->assertUnprocessable();
|
||||
$this->postJson($this->url(), $input)->assertOk()->assertJsonPath('version', 2);
|
||||
app(PartnershipExchange::class)->decideInterest($this->owner, $interest->id, 2, 'shortlist', 'SYNTHETIC shortlist after update');
|
||||
$events = DB::table('partnership_events')->count();
|
||||
$this->postJson($this->url(), $input)->assertOk()->assertJsonPath('version', 3)->assertJsonPath('replayed', true);
|
||||
$this->assertDatabaseHas('partnership_interests', ['id' => $interest->id, 'status' => 'shortlisted', 'version' => 3]);
|
||||
$this->assertSame($events, DB::table('partnership_events')->count());
|
||||
}
|
||||
|
||||
public function test_organization_choices_keep_distinct_entities_with_equal_names(): void
|
||||
{
|
||||
$first = $this->organization($this->candidate);
|
||||
$second = $this->organization($this->candidate);
|
||||
$choices = $this->getJson('/parcerias/'.$this->record->id)->assertOk()->assertJsonCount(2, 'organizations')->json('organizations');
|
||||
$this->assertEqualsCanonicalizing([$first, $second], array_column($choices, 'id'));
|
||||
$this->assertSame($choices[0]['name'], $choices[1]['name']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Http\Middleware\HandleInertiaRequests;
|
||||
use App\Models\User;
|
||||
use App\Services\PartnershipExchange;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Facades\Queue;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class PartnershipCandidacyHistoryTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $owner;
|
||||
|
||||
private User $candidate;
|
||||
|
||||
private User $moderator;
|
||||
|
||||
private object $record;
|
||||
|
||||
private object $interest;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
Http::fake();
|
||||
Mail::fake();
|
||||
Queue::fake();
|
||||
$this->owner = User::factory()->create();
|
||||
$this->candidate = User::factory()->create();
|
||||
$this->moderator = User::factory()->create();
|
||||
config(['portal.managers' => [$this->moderator->email]]);
|
||||
$service = app(PartnershipExchange::class);
|
||||
$record = $service->save($this->owner, ['client_key' => (string) Str::uuid(), 'title' => 'SYNTHETIC private history context', 'kind' => 'seeking', 'partnership_type' => 'joint_venture', 'offer' => 'SYNTHETIC offer', 'seeking' => 'SYNTHETIC cooperation', 'payload' => ['consent' => true, 'mandatory' => ['capacity']]]);
|
||||
$record = $service->transition($this->owner, $record->id, $record->version, 'submit', 'SYNTHETIC submission');
|
||||
$this->record = $service->transition($this->moderator, $record->id, $record->version, 'publish', 'SYNTHETIC review');
|
||||
$this->interest = $service->interest($this->candidate, $record->id, ['client_key' => (string) Str::uuid(), 'proposal' => 'SYNTHETIC original proposal', 'payload' => ['consent' => true, 'capacity' => 'SYNTHETIC original capacity']]);
|
||||
$this->actingAs($this->candidate);
|
||||
}
|
||||
|
||||
private function url(?int $id = null): string
|
||||
{
|
||||
return '/parcerias/candidaturas/'.($id ?? $this->interest->id).'/historico';
|
||||
}
|
||||
|
||||
private function assess(int $version, string $evidence = 'SYNTHETIC preserved evidence'): object
|
||||
{
|
||||
return app(PartnershipExchange::class)->decideInterest($this->owner, $this->interest->id, $version, 'assess', 'SYNTHETIC evidence reviewed', ['capacity' => ['state' => 'met', 'evidence' => $evidence]]);
|
||||
}
|
||||
|
||||
private function organization(User $person, string $role = 'officer'): string
|
||||
{
|
||||
$id = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $id, 'name' => 'SYNTHETIC history organization', 'organization_type' => 'private']);
|
||||
DB::table('memberships')->insert(['user_id' => $person->id, 'organization_id' => $id, 'role' => $role]);
|
||||
|
||||
return $id;
|
||||
}
|
||||
|
||||
public function test_history_recovers_real_versions_and_frozen_matching_without_recalculation(): void
|
||||
{
|
||||
$this->assess(1);
|
||||
app(PartnershipExchange::class)->interest($this->candidate, $this->record->id, ['interest_id' => $this->interest->id, 'version' => 2, 'proposal' => 'SYNTHETIC revised proposal', 'payload' => ['consent' => true, 'capacity' => 'SYNTHETIC revised capacity']]);
|
||||
config(['partnerships.weights.capacity' => 99, 'partnerships.criteria.capacity' => 'SYNTHETIC renamed current label']);
|
||||
$response = $this->getJson($this->url())->assertOk()->assertJsonCount(3, 'entries')->assertJsonPath('entries.0.version', 3)->assertJsonPath('entries.0.after.fields.proposal', 'SYNTHETIC revised proposal')->assertJsonPath('entries.0.previous.fields.capacity', 'SYNTHETIC original capacity')->assertJsonPath('entries.1.after.fields.proposal', 'SYNTHETIC original proposal')->assertJsonPath('entries.1.after.assessment.0.evidence', 'SYNTHETIC preserved evidence')->assertJsonPath('entries.2.previous.availability', 'not_recorded');
|
||||
$criteria = collect($response->json('entries.1.matching.criteria'))->keyBy('code');
|
||||
$this->assertSame(20, $criteria['capacity']['weight']);
|
||||
$this->assertSame('Capacidade técnica/produtiva', $criteria['capacity']['label']);
|
||||
$this->assertTrue($criteria['capacity']['mandatory']);
|
||||
$this->assertStringNotContainsString('client_key', $response->getContent());
|
||||
$this->assertStringNotContainsString('command_hash', $response->getContent());
|
||||
}
|
||||
|
||||
public function test_anonymous_competitors_and_moderation_do_not_receive_another_candidacy_history(): void
|
||||
{
|
||||
$other = User::factory()->create();
|
||||
$otherInterest = app(PartnershipExchange::class)->interest($other, $this->record->id, ['proposal' => 'SYNTHETIC other candidature', 'payload' => ['consent' => true]]);
|
||||
$this->getJson($this->url($otherInterest->id))->assertForbidden();
|
||||
$this->actingAs($this->moderator)->getJson($this->url())->assertForbidden();
|
||||
$this->actingAs($other)->getJson($this->url())->assertForbidden();
|
||||
$this->getJson($this->url($otherInterest->id))->assertOk()->assertJsonCount(1, 'entries');
|
||||
$this->actingAs($this->owner)->getJson($this->url())->assertOk();
|
||||
auth()->forgetGuards();
|
||||
$this->app['auth']->forgetGuards();
|
||||
$this->getJson($this->url())->assertUnauthorized();
|
||||
}
|
||||
|
||||
public function test_read_only_organization_members_can_read_and_revoked_authors_cannot(): void
|
||||
{
|
||||
$org = $this->organization($this->candidate);
|
||||
app(PartnershipExchange::class)->interest($this->candidate, $this->record->id, ['interest_id' => $this->interest->id, 'version' => 1, 'organization_id' => $org, 'proposal' => 'SYNTHETIC organizational version', 'payload' => ['consent' => true]]);
|
||||
$viewer = User::factory()->create();
|
||||
DB::table('memberships')->insert(['user_id' => $viewer->id, 'organization_id' => $org, 'role' => 'viewer']);
|
||||
$this->actingAs($viewer)->getJson($this->url())->assertOk()->assertJsonPath('entries.0.after.availability', 'available')->assertJsonPath('entries.0.previous.availability', 'restricted')->assertJsonPath('entries.1.restricted', true);
|
||||
DB::table('memberships')->where('user_id', $this->candidate->id)->update(['deleted_at' => now()]);
|
||||
$this->actingAs($this->candidate)->getJson($this->url())->assertForbidden();
|
||||
$this->actingAs($viewer)->getJson($this->url())->assertOk();
|
||||
}
|
||||
|
||||
public function test_new_organization_does_not_gain_old_organization_snapshots_or_assessment(): void
|
||||
{
|
||||
$orgA = $this->organization($this->candidate);
|
||||
$orgB = $this->organization($this->candidate);
|
||||
app(PartnershipExchange::class)->interest($this->candidate, $this->record->id, ['interest_id' => $this->interest->id, 'version' => 1, 'organization_id' => $orgA, 'proposal' => 'SYNTHETIC A-only proposal', 'payload' => ['consent' => true]]);
|
||||
$this->assess(2, 'SYNTHETIC A-only evidence');
|
||||
app(PartnershipExchange::class)->interest($this->candidate, $this->record->id, ['interest_id' => $this->interest->id, 'version' => 3, 'organization_id' => $orgB, 'proposal' => 'SYNTHETIC B submission', 'payload' => ['consent' => true, 'capacity' => 'SYNTHETIC B capacity']]);
|
||||
$viewer = User::factory()->create();
|
||||
DB::table('memberships')->insert(['user_id' => $viewer->id, 'organization_id' => $orgB, 'role' => 'viewer']);
|
||||
$response = $this->actingAs($viewer)->getJson($this->url())->assertOk()->assertJsonPath('entries.0.after.fields.proposal', 'SYNTHETIC B submission')->assertJsonPath('entries.0.previous.availability', 'restricted')->assertJsonPath('entries.1.restricted', true)->assertJsonPath('entries.1.actor_name', null)->assertJsonPath('entries.1.matching', null);
|
||||
$this->assertStringNotContainsString('SYNTHETIC A-only', $response->getContent());
|
||||
$this->actingAs($this->owner)->getJson($this->url())->assertOk()->assertJsonPath('entries.0.previous.fields.proposal', 'SYNTHETIC A-only proposal');
|
||||
DB::table('memberships')->where('organization_id', $orgA)->where('user_id', $this->candidate->id)->update(['deleted_at' => now()]);
|
||||
$this->actingAs($this->candidate)->getJson($this->url())->assertOk()->assertJsonPath('entries.0.previous.availability', 'restricted');
|
||||
}
|
||||
|
||||
public function test_legacy_partial_events_explain_missing_snapshots_without_copying_current_declarations(): void
|
||||
{
|
||||
DB::table('partnership_interests')->where('id', $this->interest->id)->update(['proposal' => 'SYNTHETIC current-only declaration', 'version' => 2, 'status' => 'clarification']);
|
||||
app(PartnershipExchange::class)->event($this->record, $this->owner, 'partnership_interest.changed.v1', ['interest_id' => $this->interest->id, 'interest_version' => 2, 'from' => 'submitted', 'to' => 'clarification', 'reason' => 'SYNTHETIC legacy reason', 'assessment' => ['capacity' => ['state' => 'met', 'evidence' => 'SYNTHETIC legacy evidence']]], 'SYNTHETIC legacy fixture');
|
||||
$response = $this->actingAs($this->owner)->getJson($this->url())->assertOk()->assertJsonPath('entries.0.action', null)->assertJsonPath('entries.0.previous.availability', 'not_recorded')->assertJsonPath('entries.0.after.complete', false)->assertJsonPath('entries.0.after.status', 'clarification')->assertJsonPath('entries.0.matching', null);
|
||||
$this->assertArrayNotHasKey('proposal', $response->json('entries.0.after.fields'));
|
||||
$this->assertStringNotContainsString('SYNTHETIC current-only', $response->getContent());
|
||||
$this->actingAs($this->candidate)->getJson($this->url())->assertOk()->assertJsonPath('entries.0.restricted', true)->assertJsonPath('entries.0.after.availability', 'scope_unknown');
|
||||
}
|
||||
|
||||
public function test_pagination_is_stable_when_new_decisions_arrive_and_never_mixes_candidacies(): void
|
||||
{
|
||||
for ($version = 1; $version <= 21; $version++) {
|
||||
$this->assess($version);
|
||||
}
|
||||
$other = app(PartnershipExchange::class)->interest(User::factory()->create(), $this->record->id, ['proposal' => 'SYNTHETIC unrelated timeline', 'payload' => ['consent' => true]]);
|
||||
$first = $this->actingAs($this->owner)->getJson($this->url())->assertOk()->assertJsonCount(10, 'entries');
|
||||
$versions = array_column($first->json('entries'), 'version');
|
||||
$this->assertSame(range(22, 13), $versions);
|
||||
$this->assess(22);
|
||||
$second = $this->getJson($first->json('next_url'))->assertOk()->assertJsonCount(10, 'entries');
|
||||
$third = $this->getJson($second->json('next_url'))->assertOk()->assertJsonCount(2, 'entries')->assertJsonPath('next_url', null);
|
||||
$this->assertSame(range(22, 1), [...$versions, ...array_column($second->json('entries'), 'version'), ...array_column($third->json('entries'), 'version')]);
|
||||
$this->getJson($this->url())->assertOk()->assertJsonPath('entries.0.version', 23);
|
||||
$this->getJson($this->url($other->id))->assertOk()->assertJsonCount(1, 'entries');
|
||||
}
|
||||
|
||||
public function test_cursors_are_bound_to_actor_and_candidacy_and_checked_after_current_access(): void
|
||||
{
|
||||
for ($version = 1; $version <= 10; $version++) {
|
||||
$this->assess($version);
|
||||
}
|
||||
$cursor = $this->actingAs($this->owner)->getJson($this->url())->assertOk()->json('next_url');
|
||||
$this->actingAs($this->candidate)->getJson($cursor)->assertUnprocessable();
|
||||
$other = app(PartnershipExchange::class)->interest(User::factory()->create(), $this->record->id, ['proposal' => 'SYNTHETIC other', 'payload' => ['consent' => true]]);
|
||||
$query = parse_url($cursor, PHP_URL_QUERY);
|
||||
$this->actingAs($this->owner)->getJson($this->url($other->id).'?'.$query)->assertUnprocessable();
|
||||
$this->getJson($this->url().'?before=invalid-token')->assertUnprocessable();
|
||||
$this->getJson($cursor)->assertOk();
|
||||
}
|
||||
|
||||
public function test_private_history_remains_readable_after_archiving_without_exposing_a_new_draft(): void
|
||||
{
|
||||
DB::table('portal_partnerships')->where('id', $this->record->id)->update(['status' => 'archived', 'title' => 'SYNTHETIC undisclosed revised title', 'offer' => 'SYNTHETIC private new draft']);
|
||||
$response = $this->getJson($this->url())->assertOk()->assertJsonPath('partnership_href', null)->assertJsonPath('dashboard_href', '/parcerias/painel');
|
||||
$this->assertStringNotContainsString('SYNTHETIC undisclosed', $response->getContent());
|
||||
$this->assertStringNotContainsString('SYNTHETIC private new draft', $response->getContent());
|
||||
$this->getJson('/parcerias/'.$this->record->id)->assertNotFound();
|
||||
$this->actingAs($this->owner)->getJson($this->url())->assertOk()->assertJsonPath('partnership_href', '/parcerias/'.$this->record->id);
|
||||
}
|
||||
|
||||
public function test_consultation_is_read_only_private_and_uses_the_native_history_page(): void
|
||||
{
|
||||
$this->assess(1);
|
||||
$row = DB::table('partnership_interests')->where('id', $this->interest->id)->first();
|
||||
$events = DB::table('partnership_events')->count();
|
||||
$audits = DB::table('audit_events')->count();
|
||||
$notifications = DB::table('partnership_notifications')->count();
|
||||
$version = app(HandleInertiaRequests::class)->version(Request::create($this->url()));
|
||||
$response = $this->get($this->url(), ['X-Inertia' => 'true', 'X-Inertia-Version' => $version ?? ''])->assertOk()->assertJsonPath('component', 'partnerships/interest-history')->assertJsonPath('encryptHistory', true);
|
||||
$this->assertTrue($response->headers->hasCacheControlDirective('private'));
|
||||
$this->assertTrue($response->headers->hasCacheControlDirective('no-store'));
|
||||
$this->assertEquals($row, DB::table('partnership_interests')->where('id', $this->interest->id)->first());
|
||||
$this->assertSame($events, DB::table('partnership_events')->count());
|
||||
$this->assertSame($audits, DB::table('audit_events')->count());
|
||||
$this->assertSame($notifications, DB::table('partnership_notifications')->count());
|
||||
}
|
||||
|
||||
public function test_missing_or_malformed_matching_parameters_stay_unknown_and_never_become_zero(): void
|
||||
{
|
||||
$this->assess(1);
|
||||
$event = DB::table('partnership_events')->where('event_type', 'partnership_interest.changed.v1')->first();
|
||||
$data = json_decode($event->payload, true);
|
||||
$data['payload']['matching_context']['score_min'] = ['invalid'];
|
||||
$data['payload']['matching_context']['score_max'] = null;
|
||||
$data['payload']['matching_context']['criteria'][0]['weight'] = ['invalid'];
|
||||
DB::table('partnership_events')->where('id', $event->id)->update(['payload' => json_encode($data)]);
|
||||
$this->getJson($this->url())->assertOk()->assertJsonPath('entries.0.matching.score_min', null)->assertJsonPath('entries.0.matching.score_max', null)->assertJsonPath('entries.0.matching.criteria.0.weight', null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Http\Middleware\HandleInertiaRequests;
|
||||
use App\Models\User;
|
||||
use App\Services\PartnershipExchange;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Facades\Queue;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Testing\TestResponse;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class PartnershipDashboardPrivacyTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $owner;
|
||||
|
||||
private User $candidate;
|
||||
|
||||
private User $moderator;
|
||||
|
||||
private object $record;
|
||||
|
||||
private object $interest;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
Http::fake();
|
||||
Mail::fake();
|
||||
Queue::fake();
|
||||
$this->owner = User::factory()->create();
|
||||
$this->candidate = User::factory()->create();
|
||||
$this->moderator = User::factory()->create();
|
||||
config(['portal.managers' => [$this->moderator->email]]);
|
||||
$service = app(PartnershipExchange::class);
|
||||
$record = $service->save($this->owner, ['client_key' => (string) Str::uuid(), 'title' => 'SYNTHETIC published title', 'kind' => 'seeking', 'partnership_type' => 'joint_venture', 'offer' => 'SYNTHETIC offer', 'payload' => ['consent' => true]]);
|
||||
$record = $service->transition($this->owner, $record->id, $record->version, 'submit', 'SYNTHETIC submit');
|
||||
$this->record = $service->transition($this->moderator, $record->id, $record->version, 'publish', 'SYNTHETIC publish');
|
||||
$this->interest = $service->interest($this->candidate, $record->id, ['client_key' => (string) Str::uuid(), 'proposal' => 'SYNTHETIC candidate', 'payload' => ['consent' => true]]);
|
||||
$this->actingAs($this->candidate);
|
||||
}
|
||||
|
||||
private function panel(): TestResponse
|
||||
{
|
||||
$version = app(HandleInertiaRequests::class)->version(Request::create('/parcerias/painel'));
|
||||
|
||||
return $this->get('/parcerias/painel', ['X-Inertia' => 'true', 'X-Inertia-Version' => $version ?? '']);
|
||||
}
|
||||
|
||||
private function organization(User $person, string $role = 'officer'): string
|
||||
{
|
||||
$id = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $id, 'name' => 'SYNTHETIC dashboard organization', 'organization_type' => 'private']);
|
||||
DB::table('memberships')->insert(['user_id' => $person->id, 'organization_id' => $id, 'role' => $role]);
|
||||
|
||||
return $id;
|
||||
}
|
||||
|
||||
public function test_dashboard_does_not_disclose_current_title_after_unpublication(): void
|
||||
{
|
||||
DB::table('portal_partnerships')->where('id', $this->record->id)->update(['status' => 'draft', 'title' => 'SYNTHETIC undisclosed private replacement']);
|
||||
$response = $this->panel()->assertOk()->assertJsonPath('props.interests.0.title', null)->assertJsonPath('props.interests.0.partnership_href', null);
|
||||
$this->assertStringNotContainsString('SYNTHETIC undisclosed private replacement', $response->getContent());
|
||||
}
|
||||
|
||||
public function test_deleted_organization_does_not_leave_its_drafts_in_the_panel(): void
|
||||
{
|
||||
$org = $this->organization($this->candidate);
|
||||
DB::table('portal_partnerships')->where('id', $this->record->id)->update(['organization_id' => $org, 'status' => 'draft', 'title' => 'SYNTHETIC deleted organization draft']);
|
||||
DB::table('partnership_interests')->where('id', $this->interest->id)->update(['organization_id' => $org]);
|
||||
DB::table('organizations')->where('id', $org)->update(['deleted_at' => now()]);
|
||||
$response = $this->panel()->assertOk()->assertJsonCount(0, 'props.mine')->assertJsonCount(0, 'props.interests');
|
||||
$this->assertStringNotContainsString('SYNTHETIC deleted organization draft', $response->getContent());
|
||||
}
|
||||
|
||||
public function test_revoked_candidate_does_not_read_or_acknowledge_old_notification(): void
|
||||
{
|
||||
$org = $this->organization($this->candidate);
|
||||
app(PartnershipExchange::class)->interest($this->candidate, $this->record->id, ['interest_id' => $this->interest->id, 'version' => 1, 'organization_id' => $org, 'proposal' => 'SYNTHETIC organizational candidate', 'payload' => ['consent' => true]]);
|
||||
app(PartnershipExchange::class)->decideInterest($this->owner, $this->interest->id, 2, 'clarify', 'SYNTHETIC clarification');
|
||||
$notice = DB::table('partnership_notifications')->where('user_id', $this->candidate->id)->orderByDesc('id')->first();
|
||||
DB::table('memberships')->where('organization_id', $org)->where('user_id', $this->candidate->id)->update(['deleted_at' => now()]);
|
||||
$response = $this->panel()->assertOk();
|
||||
$ids = array_column($response->json('props.notifications'), 'id');
|
||||
$this->assertNotContains($notice->id, $ids);
|
||||
$this->post('/parcerias/notificacoes/'.$notice->id.'/ler')->assertNotFound();
|
||||
$this->assertNull(DB::table('partnership_notifications')->where('id', $notice->id)->value('read_at'));
|
||||
}
|
||||
|
||||
public function test_current_parent_reader_or_moderator_keeps_the_authorized_proposal_link(): void
|
||||
{
|
||||
$this->panel()->assertOk()->assertJsonPath('props.interests.0.title', 'SYNTHETIC published title')->assertJsonPath('props.interests.0.partnership_href', '/parcerias/'.$this->record->id);
|
||||
DB::table('portal_partnerships')->where('id', $this->record->id)->update(['status' => 'draft']);
|
||||
$org = $this->organization($this->owner);
|
||||
DB::table('memberships')->insert(['user_id' => $this->candidate->id, 'organization_id' => $org, 'role' => 'viewer']);
|
||||
DB::table('portal_partnerships')->where('id', $this->record->id)->update(['organization_id' => $org]);
|
||||
$this->panel()->assertOk()->assertJsonPath('props.mine.0.title', 'SYNTHETIC published title')->assertJsonPath('props.interests.0.partnership_href', '/parcerias/'.$this->record->id);
|
||||
config(['portal.managers' => [$this->candidate->email]]);
|
||||
DB::table('memberships')->where('organization_id', $org)->where('user_id', $this->candidate->id)->update(['deleted_at' => now()]);
|
||||
$this->panel()->assertOk()->assertJsonCount(0, 'props.mine')->assertJsonPath('props.interests.0.partnership_href', '/parcerias/'.$this->record->id);
|
||||
}
|
||||
|
||||
public function test_new_notices_follow_current_operational_participants_without_notifying_revoked_authors(): void
|
||||
{
|
||||
$proponentOrg = $this->organization($this->owner);
|
||||
$candidateOrg = $this->organization($this->candidate);
|
||||
$proponent = User::factory()->create();
|
||||
$candidate = User::factory()->create();
|
||||
$viewer = User::factory()->create();
|
||||
DB::table('memberships')->insert([['user_id' => $proponent->id, 'organization_id' => $proponentOrg, 'role' => 'manager'], ['user_id' => $candidate->id, 'organization_id' => $candidateOrg, 'role' => 'officer'], ['user_id' => $viewer->id, 'organization_id' => $candidateOrg, 'role' => 'viewer']]);
|
||||
DB::table('portal_partnerships')->where('id', $this->record->id)->update(['organization_id' => $proponentOrg]);
|
||||
app(PartnershipExchange::class)->interest($this->candidate, $this->record->id, ['interest_id' => $this->interest->id, 'version' => 1, 'organization_id' => $candidateOrg, 'proposal' => 'SYNTHETIC organizational candidate', 'payload' => ['consent' => true]]);
|
||||
DB::table('memberships')->whereIn('user_id', [$this->owner->id, $this->candidate->id])->update(['deleted_at' => now()]);
|
||||
app(PartnershipExchange::class)->decideInterest($proponent, $this->interest->id, 2, 'clarify', 'SYNTHETIC current representatives');
|
||||
$event = DB::table('partnership_events')->where('partnership_id', $this->record->id)->orderByDesc('aggregate_version')->first();
|
||||
$recipients = DB::table('partnership_notifications')->where('event_id', $event->id)->pluck('user_id')->all();
|
||||
sort($recipients);
|
||||
$expected = [$proponent->id, $candidate->id];
|
||||
sort($expected);
|
||||
$this->assertSame($expected, $recipients);
|
||||
$payload = json_decode($event->payload, true)['payload']['_notification_context'];
|
||||
$this->assertSame($proponentOrg, $payload['partnership']['organization_id']);
|
||||
$this->assertSame($candidateOrg, $payload['interest']['organization_id']);
|
||||
$this->actingAs($candidate);
|
||||
$this->panel()->assertOk()->assertJsonPath('props.notifications.0.href', '/parcerias/candidaturas/'.$this->interest->id.'/historico');
|
||||
$this->actingAs($viewer);
|
||||
$this->panel()->assertOk()->assertJsonCount(0, 'props.notifications');
|
||||
}
|
||||
|
||||
public function test_change_to_another_organization_does_not_transfer_old_notices_to_the_new_representation(): void
|
||||
{
|
||||
$orgA = $this->organization($this->candidate);
|
||||
$representative = User::factory()->create();
|
||||
DB::table('memberships')->insert(['user_id' => $representative->id, 'organization_id' => $orgA, 'role' => 'officer']);
|
||||
$service = app(PartnershipExchange::class);
|
||||
$service->interest($this->candidate, $this->record->id, ['interest_id' => $this->interest->id, 'version' => 1, 'organization_id' => $orgA, 'proposal' => 'SYNTHETIC organization A', 'payload' => ['consent' => true]]);
|
||||
$service->decideInterest($this->owner, $this->interest->id, 2, 'clarify', 'SYNTHETIC A clarification');
|
||||
$old = DB::table('partnership_notifications')->where('user_id', $representative->id)->orderByDesc('id')->first();
|
||||
$orgB = $this->organization($this->candidate);
|
||||
DB::table('memberships')->insert(['user_id' => $representative->id, 'organization_id' => $orgB, 'role' => 'officer']);
|
||||
$service->interest($this->candidate, $this->record->id, ['interest_id' => $this->interest->id, 'version' => 3, 'organization_id' => $orgB, 'proposal' => 'SYNTHETIC organization B', 'payload' => ['consent' => true]]);
|
||||
DB::table('memberships')->where('organization_id', $orgA)->where('user_id', $representative->id)->update(['deleted_at' => now()]);
|
||||
$this->actingAs($representative);
|
||||
$response = $this->panel()->assertOk()->assertJsonCount(1, 'props.notifications');
|
||||
$this->assertNotContains($old->id, array_column($response->json('props.notifications'), 'id'));
|
||||
$this->post('/parcerias/notificacoes/'.$old->id.'/ler')->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_historical_scope_is_required_even_when_current_proponent_organization_is_authorized(): void
|
||||
{
|
||||
$orgA = $this->organization($this->owner);
|
||||
$representative = User::factory()->create();
|
||||
DB::table('memberships')->insert(['user_id' => $representative->id, 'organization_id' => $orgA, 'role' => 'officer']);
|
||||
DB::table('portal_partnerships')->where('id', $this->record->id)->update(['organization_id' => $orgA]);
|
||||
$service = app(PartnershipExchange::class);
|
||||
$service->event($service->find($this->record->id), $this->owner, 'partnership_opportunity.changed.v1', [], 'SYNTHETIC A private notice', [$this->owner->id]);
|
||||
$old = DB::table('partnership_notifications')->where('user_id', $representative->id)->orderByDesc('id')->first();
|
||||
$orgB = $this->organization($representative);
|
||||
DB::table('portal_partnerships')->where('id', $this->record->id)->update(['organization_id' => $orgB]);
|
||||
DB::table('memberships')->where('organization_id', $orgA)->where('user_id', $representative->id)->update(['deleted_at' => now()]);
|
||||
$this->actingAs($representative);
|
||||
$this->panel()->assertOk()->assertJsonCount(0, 'props.notifications');
|
||||
$this->post('/parcerias/notificacoes/'.$old->id.'/ler')->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_legacy_candidate_snapshot_is_reused_without_inventing_missing_proponent_scope(): void
|
||||
{
|
||||
$event = DB::table('partnership_events')->where('event_type', 'partnership_interest.submitted.v1')->first();
|
||||
$payload = json_decode($event->payload, true);
|
||||
unset($payload['payload']['_notification_context']);
|
||||
DB::table('partnership_events')->where('id', $event->id)->update(['payload' => json_encode($payload)]);
|
||||
$this->panel()->assertOk()->assertJsonCount(1, 'props.notifications')->assertJsonPath('props.notifications.0.href', '/parcerias/candidaturas/'.$this->interest->id.'/historico');
|
||||
$this->actingAs($this->owner);
|
||||
$response = $this->panel()->assertOk();
|
||||
$candidateNotice = DB::table('partnership_notifications')->where('event_id', $event->id)->where('user_id', $this->owner->id)->first();
|
||||
$this->assertNotContains($candidateNotice->id, array_column($response->json('props.notifications'), 'id'));
|
||||
unset($payload['payload']['submitted']['organization_id']);
|
||||
DB::table('partnership_events')->where('id', $event->id)->update(['payload' => json_encode($payload)]);
|
||||
$this->actingAs($this->candidate);
|
||||
$this->panel()->assertOk()->assertJsonCount(0, 'props.notifications');
|
||||
$this->assertSame(2, DB::table('partnership_notifications')->where('event_id', $event->id)->count());
|
||||
}
|
||||
|
||||
public function test_inaccessible_rows_do_not_consume_the_visible_limit_or_hide_an_older_authorized_notice(): void
|
||||
{
|
||||
$record = app(PartnershipExchange::class)->find($this->record->id);
|
||||
$sequence = DB::table('partnership_events')->where('partnership_id', $record->id)->max('aggregate_version');
|
||||
$events = [];
|
||||
$notices = [];
|
||||
for ($i = 1; $i <= 105; $i++) {
|
||||
$event = (string) Str::uuid();
|
||||
$events[] = ['id' => $event, 'partnership_id' => $record->id, 'actor_id' => $this->owner->id, 'event_type' => 'partnership_opportunity.changed.v1', 'aggregate_version' => $sequence + $i, 'payload' => json_encode(['payload' => ['_notification_context' => ['version' => 1, 'partnership' => ['id' => $record->id, 'user_id' => $this->owner->id, 'organization_id' => null], 'interest' => null, 'room_id' => null]]])];
|
||||
$notices[] = ['event_id' => $event, 'user_id' => $this->candidate->id, 'title' => 'SYNTHETIC inaccessible title', 'href' => 'javascript:synthetic()'];
|
||||
}
|
||||
DB::table('partnership_events')->insert($events);
|
||||
DB::table('partnership_notifications')->insert($notices);
|
||||
$response = $this->panel()->assertOk()->assertJsonCount(1, 'props.notifications');
|
||||
$this->assertStringNotContainsString('SYNTHETIC inaccessible title', $response->getContent());
|
||||
$this->assertStringNotContainsString('javascript:', $response->getContent());
|
||||
}
|
||||
|
||||
public function test_notification_link_is_rebuilt_and_marking_read_is_idempotent_without_business_events(): void
|
||||
{
|
||||
$notice = DB::table('partnership_notifications')->where('user_id', $this->candidate->id)->first();
|
||||
DB::table('partnership_notifications')->where('id', $notice->id)->update(['href' => 'javascript:synthetic()']);
|
||||
$events = DB::table('partnership_events')->count();
|
||||
$audits = DB::table('audit_events')->count();
|
||||
$this->panel()->assertOk()->assertJsonPath('props.notifications.0.href', '/parcerias/candidaturas/'.$this->interest->id.'/historico');
|
||||
$this->post('/parcerias/notificacoes/'.$notice->id.'/ler')->assertRedirect();
|
||||
$first = DB::table('partnership_notifications')->where('id', $notice->id)->value('read_at');
|
||||
$this->assertNotNull($first);
|
||||
$this->travel(5)->minutes();
|
||||
$this->post('/parcerias/notificacoes/'.$notice->id.'/ler')->assertRedirect();
|
||||
$this->assertSame($first, DB::table('partnership_notifications')->where('id', $notice->id)->value('read_at'));
|
||||
$this->assertSame($events, DB::table('partnership_events')->count());
|
||||
$this->assertSame($audits, DB::table('audit_events')->count());
|
||||
$this->actingAs($this->owner)->post('/parcerias/notificacoes/'.$notice->id.'/ler')->assertNotFound();
|
||||
auth()->forgetGuards();
|
||||
$this->postJson('/parcerias/notificacoes/'.$notice->id.'/ler')->assertUnauthorized();
|
||||
}
|
||||
|
||||
public function test_room_notices_link_to_the_current_authorized_room_and_message_replay_does_not_duplicate_delivery(): void
|
||||
{
|
||||
$service = app(PartnershipExchange::class);
|
||||
$service->decideInterest($this->owner, $this->interest->id, 1, 'shortlist', 'SYNTHETIC shortlist');
|
||||
$service->decideInterest($this->owner, $this->interest->id, 2, 'connect', 'SYNTHETIC connect');
|
||||
$room = DB::table('partnership_rooms')->where('interest_id', $this->interest->id)->first();
|
||||
$data = ['client_key' => (string) Str::uuid(), 'body' => 'SYNTHETIC message'];
|
||||
$this->postJson('/parcerias/salas/'.$room->id.'/mensagens', $data)->assertOk();
|
||||
$count = DB::table('partnership_notifications')->count();
|
||||
$this->postJson('/parcerias/salas/'.$room->id.'/mensagens', $data)->assertOk();
|
||||
$this->assertSame($count, DB::table('partnership_notifications')->count());
|
||||
$this->panel()->assertOk()->assertJsonPath('props.notifications.0.href', '/parcerias/salas/'.$room->id);
|
||||
}
|
||||
|
||||
public function test_malformed_explicit_context_does_not_fall_back_to_a_legacy_snapshot(): void
|
||||
{
|
||||
$event = DB::table('partnership_events')->where('event_type', 'partnership_interest.submitted.v1')->first();
|
||||
$payload = json_decode($event->payload, true);
|
||||
$notice = DB::table('partnership_notifications')->where('event_id', $event->id)->where('user_id', $this->candidate->id)->first();
|
||||
foreach ([null, ['version' => 99], ['version' => 1, 'partnership' => ['id' => $this->record->id + 999, 'user_id' => $this->owner->id, 'organization_id' => null]]] as $invalid) {
|
||||
$payload['payload']['_notification_context'] = $invalid;
|
||||
DB::table('partnership_events')->where('id', $event->id)->update(['payload' => json_encode($payload)]);
|
||||
$this->panel()->assertOk()->assertJsonCount(0, 'props.notifications');
|
||||
$this->post('/parcerias/notificacoes/'.$notice->id.'/ler')->assertNotFound();
|
||||
}
|
||||
}
|
||||
|
||||
public function test_a_read_only_representative_keeps_reading_an_existing_notice_without_receiving_new_operational_delivery(): void
|
||||
{
|
||||
$org = $this->organization($this->candidate);
|
||||
$service = app(PartnershipExchange::class);
|
||||
$service->interest($this->candidate, $this->record->id, ['interest_id' => $this->interest->id, 'version' => 1, 'organization_id' => $org, 'proposal' => 'SYNTHETIC organization', 'payload' => ['consent' => true]]);
|
||||
$notice = DB::table('partnership_notifications')->where('user_id', $this->candidate->id)->orderByDesc('id')->first();
|
||||
DB::table('memberships')->where('organization_id', $org)->where('user_id', $this->candidate->id)->update(['role' => 'viewer']);
|
||||
$this->panel()->assertOk()->assertJsonPath('props.notifications.0.id', $notice->id);
|
||||
$this->post('/parcerias/notificacoes/'.$notice->id.'/ler')->assertRedirect();
|
||||
$service->decideInterest($this->owner, $this->interest->id, 2, 'clarify', 'SYNTHETIC later decision');
|
||||
$this->assertSame(2, DB::table('partnership_notifications')->where('user_id', $this->candidate->id)->count());
|
||||
$this->postJson('/parcerias/candidaturas/'.$this->interest->id, ['version' => 3, 'action' => 'withdraw', 'reason' => 'SYNTHETIC unauthorized write'])->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_visible_limit_keeps_the_latest_fifty_authorized_notifications_in_order(): void
|
||||
{
|
||||
$event = DB::table('partnership_events')->where('event_type', 'partnership_interest.submitted.v1')->first();
|
||||
$payload = $event->payload;
|
||||
$sequence = DB::table('partnership_events')->where('partnership_id', $this->record->id)->max('aggregate_version');
|
||||
$events = [];
|
||||
$notices = [];
|
||||
for ($i = 1; $i <= 55; $i++) {
|
||||
$id = (string) Str::uuid();
|
||||
$events[] = ['id' => $id, 'partnership_id' => $this->record->id, 'actor_id' => $this->candidate->id, 'event_type' => 'partnership_interest.submitted.v1', 'aggregate_version' => $sequence + $i, 'payload' => $payload];
|
||||
$notices[] = ['event_id' => $id, 'user_id' => $this->candidate->id, 'title' => 'SYNTHETIC notice '.$i, 'href' => '/unused'];
|
||||
}
|
||||
DB::table('partnership_events')->insert($events);
|
||||
DB::table('partnership_notifications')->insert($notices);
|
||||
$response = $this->panel()->assertOk()->assertJsonCount(50, 'props.notifications')->assertJsonPath('props.notifications.0.title', 'SYNTHETIC notice 55')->assertJsonPath('props.notifications.49.title', 'SYNTHETIC notice 6');
|
||||
$ids = array_column($response->json('props.notifications'), 'id');
|
||||
$sorted = $ids;
|
||||
rsort($sorted);
|
||||
$this->assertSame($sorted, $ids);
|
||||
$this->assertCount(50, array_unique($ids));
|
||||
}
|
||||
|
||||
public function test_an_inconsistent_event_context_rolls_back_without_cross_partnership_delivery(): void
|
||||
{
|
||||
$service = app(PartnershipExchange::class);
|
||||
$other = $service->save($this->owner, ['client_key' => (string) Str::uuid(), 'title' => 'SYNTHETIC other partnership', 'kind' => 'seeking']);
|
||||
$events = DB::table('partnership_events')->count();
|
||||
$notices = DB::table('partnership_notifications')->count();
|
||||
$audits = DB::table('audit_events')->count();
|
||||
try {
|
||||
$service->event($other, $this->owner, 'partnership_interest.changed.v1', ['interest_id' => $this->interest->id], 'SYNTHETIC inconsistent context', [$this->candidate->id]);
|
||||
$this->fail('A foreign candidacy must not produce a notification.');
|
||||
} catch (\LogicException $error) {
|
||||
$this->assertSame('Notification belongs to another partnership.', $error->getMessage());
|
||||
}
|
||||
$this->assertSame($events, DB::table('partnership_events')->count());
|
||||
$this->assertSame($notices, DB::table('partnership_notifications')->count());
|
||||
$this->assertSame($audits, DB::table('audit_events')->count());
|
||||
}
|
||||
|
||||
public function test_events_without_a_notification_intent_remain_without_delivery_and_shared_parties_are_deduplicated(): void
|
||||
{
|
||||
$service = app(PartnershipExchange::class);
|
||||
$before = DB::table('partnership_notifications')->count();
|
||||
$service->event($service->find($this->record->id), $this->owner, 'partnership.document_accessed.v1', [], 'SYNTHETIC read only');
|
||||
$this->assertSame($before, DB::table('partnership_notifications')->count());
|
||||
$org = $this->organization($this->owner);
|
||||
DB::table('portal_partnerships')->where('id', $this->record->id)->update(['organization_id' => $org]);
|
||||
DB::table('partnership_interests')->where('id', $this->interest->id)->update(['organization_id' => $org]);
|
||||
$service->event($service->find($this->record->id), $this->owner, 'partnership_interest.changed.v1', ['interest_id' => $this->interest->id], 'SYNTHETIC same party', [$this->owner->id, $this->candidate->id]);
|
||||
$event = DB::table('partnership_events')->where('partnership_id', $this->record->id)->orderByDesc('aggregate_version')->first();
|
||||
$this->assertSame([$this->owner->id], DB::table('partnership_notifications')->where('event_id',$event->id)->pluck('user_id')->all());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Http\Middleware\HandleInertiaRequests;
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
use App\Services\PartnershipExchange;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Facades\Queue;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class PartnershipDraftRecoveryTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $owner;
|
||||
|
||||
private object $record;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
Http::fake();
|
||||
Mail::fake();
|
||||
Queue::fake();
|
||||
$this->owner = User::factory()->create();
|
||||
$this->actingAs($this->owner);
|
||||
$this->record = app(PartnershipExchange::class)->save($this->owner, ['client_key' => (string) Str::uuid(), 'title' => 'SYNTHETIC original draft', 'kind' => 'seeking', 'partnership_type' => 'joint_venture', 'offer' => 'SYNTHETIC offer', 'payload' => ['consent' => true, 'mandatory' => ['capacity']]]);
|
||||
}
|
||||
|
||||
private function command(array $changes = []): array
|
||||
{
|
||||
return ['operation_key' => (string) Str::uuid(), 'version' => $this->record->version, 'kind' => 'seeking', 'title' => 'SYNTHETIC saved revision', 'partnership_type' => 'joint_venture', 'payload' => ['mandatory' => ['capacity']], ...$changes];
|
||||
}
|
||||
|
||||
private function url(): string
|
||||
{
|
||||
return '/parcerias/'.$this->record->id;
|
||||
}
|
||||
|
||||
public function test_repeating_a_committed_edit_preserves_a_later_state_and_does_not_create_another_revision(): void
|
||||
{
|
||||
$data = $this->command();
|
||||
$this->putJson($this->url(), $data)->assertOk();
|
||||
$current = app(PartnershipExchange::class)->find($this->record->id);
|
||||
app(PartnershipExchange::class)->transition($this->owner, $current->id, $current->version, 'submit', 'SYNTHETIC submit after edit');
|
||||
$events = DB::table('partnership_events')->count();
|
||||
$audits = DB::table('audit_events')->count();
|
||||
$notices = DB::table('partnership_notifications')->count();
|
||||
$this->putJson($this->url(), $data)->assertOk()->assertJsonPath('replayed', true)->assertJsonPath('saved_version', $data['version'] + 1)->assertJsonPath('status', 'submitted');
|
||||
$this->assertSame($events, DB::table('partnership_events')->count());
|
||||
$this->assertSame($audits, DB::table('audit_events')->count());
|
||||
$this->assertSame($notices, DB::table('partnership_notifications')->count());
|
||||
}
|
||||
|
||||
public function test_replay_does_not_revalidate_retired_type_or_criteria_as_a_new_write(): void
|
||||
{
|
||||
$data = $this->command();
|
||||
$this->putJson($this->url(), $data)->assertOk();
|
||||
config(['partnerships.types' => [], 'partnerships.criteria' => []]);
|
||||
$this->putJson($this->url(), $data)->assertOk()->assertJsonPath('replayed', true);
|
||||
}
|
||||
|
||||
public function test_changed_payload_with_the_same_operation_key_is_a_conflict_without_new_events(): void
|
||||
{
|
||||
$data = $this->command();
|
||||
$this->putJson($this->url(), $data)->assertOk();
|
||||
$events = DB::table('partnership_events')->count();
|
||||
$this->putJson($this->url(), [...$data, 'title' => 'SYNTHETIC changed content'])->assertConflict();
|
||||
$this->assertSame($events, DB::table('partnership_events')->count());
|
||||
$this->assertSame('SYNTHETIC saved revision', DB::table('portal_partnerships')->where('id', $this->record->id)->value('title'));
|
||||
}
|
||||
|
||||
public function test_updates_use_distinct_operation_keys_without_changing_the_creation_identity(): void
|
||||
{
|
||||
$first = $this->command(['client_key' => (string) Str::uuid()]);
|
||||
$this->putJson($this->url(), $first)->assertOk()->assertJsonPath('replayed', false);
|
||||
$second = $this->command(['version' => $first['version'] + 1, 'title' => 'SYNTHETIC second revision', 'client_key' => $first['client_key']]);
|
||||
$this->putJson($this->url(), $second)->assertOk()->assertJsonPath('saved_version', $second['version'] + 1);
|
||||
$this->assertNotSame($first['operation_key'], $second['operation_key']);
|
||||
$this->assertSame($this->record->client_key, DB::table('portal_partnerships')->where('id', $this->record->id)->value('client_key'));
|
||||
}
|
||||
|
||||
public function test_authority_is_required_for_recovery_even_for_a_revoked_original_author(): void
|
||||
{
|
||||
$org = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $org, 'name' => 'SYNTHETIC editing organization', 'organization_type' => 'private']);
|
||||
DB::table('memberships')->insert(['user_id' => $this->owner->id, 'organization_id' => $org, 'role' => 'officer']);
|
||||
DB::table('portal_partnerships')->where('id', $this->record->id)->update(['organization_id' => $org]);
|
||||
$data = $this->command();
|
||||
$this->putJson($this->url(), $data)->assertOk();
|
||||
DB::table('memberships')->where('user_id', $this->owner->id)->where('organization_id', $org)->update(['role' => 'viewer']);
|
||||
$this->putJson($this->url(), $data)->assertForbidden();
|
||||
$this->get($this->url().'/editar')->assertForbidden();
|
||||
DB::table('memberships')->where('user_id', $this->owner->id)->where('organization_id', $org)->update(['deleted_at' => now()]);
|
||||
$this->putJson($this->url(), $data)->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_editor_exposes_only_the_current_actors_save_keys_and_not_private_hashes(): void
|
||||
{
|
||||
$data = $this->command();
|
||||
$this->putJson($this->url(), $data)->assertOk();
|
||||
$url = $this->url().'/editar';
|
||||
$version = app(HandleInertiaRequests::class)->version(Request::create($url));
|
||||
$response = $this->get($url, ['X-Inertia' => 'true', 'X-Inertia-Version' => $version ?? ''])->assertOk()->assertJsonPath('props.editorActorId', $this->owner->id)->assertJsonPath('props.saveCommands.0.key', $data['operation_key'])->assertJsonPath('props.saveCommands.0.version', $data['version'] + 1);
|
||||
foreach (['operation_hash', 'command_hash', '_creation_hash', '_notification_context'] as $private) {
|
||||
$this->assertStringNotContainsString($private, $response->getContent());
|
||||
}
|
||||
$org = (string) Str::uuid();
|
||||
$other = User::factory()->create();
|
||||
DB::table('organizations')->insert(['id' => $org, 'name' => 'SYNTHETIC shared draft', 'organization_type' => 'private']);
|
||||
DB::table('memberships')->insert([['user_id' => $this->owner->id, 'organization_id' => $org, 'role' => 'officer'], ['user_id' => $other->id, 'organization_id' => $org, 'role' => 'officer']]);
|
||||
DB::table('portal_partnerships')->where('id', $this->record->id)->update(['organization_id' => $org]);
|
||||
$this->actingAs($other)->get($url, ['X-Inertia' => 'true', 'X-Inertia-Version' => $version ?? ''])->assertOk()->assertJsonPath('props.saveCommands', [])->assertJsonPath('props.editorActorId', $other->id);
|
||||
}
|
||||
|
||||
public function test_retired_sector_blocks_a_new_edit_but_not_a_read_only_replay(): void
|
||||
{
|
||||
$sector = Sector::create(['name' => 'SYNTHETIC edit sector', 'slug' => 'synthetic-'.Str::uuid(), 'is_active' => true]);
|
||||
$data = $this->command(['sector_id' => $sector->id]);
|
||||
$this->putJson($this->url(), $data)->assertOk();
|
||||
$sector->update(['is_active' => false]);
|
||||
$this->putJson($this->url(), $data)->assertOk()->assertJsonPath('replayed', true);
|
||||
$this->putJson($this->url(), [...$data, 'operation_key' => (string) Str::uuid(), 'version' => $data['version'] + 1])->assertUnprocessable();
|
||||
}
|
||||
|
||||
public function test_invalid_or_stale_uncommitted_attempts_do_not_consume_a_key(): void
|
||||
{
|
||||
$data = $this->command();
|
||||
$events = DB::table('partnership_events')->count();
|
||||
$this->putJson($this->url(), [...$data, 'operation_key' => 'invalid'])->assertUnprocessable();
|
||||
$this->putJson($this->url(), [...$data, 'version' => $data['version'] + 9])->assertConflict();
|
||||
$this->assertSame($events, DB::table('partnership_events')->count());
|
||||
$this->putJson($this->url(), $data)->assertOk()->assertJsonPath('replayed', false);
|
||||
}
|
||||
|
||||
public function test_operation_uuid_case_and_unused_creation_key_do_not_change_the_committed_edit(): void
|
||||
{
|
||||
$data = $this->command();
|
||||
$this->putJson($this->url(), $data)->assertOk();
|
||||
$this->putJson($this->url(), [...$data, 'operation_key' => strtoupper($data['operation_key']), 'client_key' => (string) Str::uuid()])->assertOk()->assertJsonPath('replayed', true);
|
||||
}
|
||||
|
||||
public function test_omitted_organization_and_payload_are_preserved_and_explicit_removal_is_a_new_command(): void
|
||||
{
|
||||
$org = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $org, 'name' => 'SYNTHETIC source organization', 'organization_type' => 'private']);
|
||||
DB::table('memberships')->insert(['user_id' => $this->owner->id, 'organization_id' => $org, 'role' => 'officer']);
|
||||
DB::table('portal_partnerships')->where('id', $this->record->id)->update(['organization_id' => $org]);
|
||||
$data = $this->command();
|
||||
$this->putJson($this->url(), $data)->assertOk();
|
||||
$saved = app(PartnershipExchange::class)->find($this->record->id);
|
||||
$this->assertSame($org, $saved->organization_id);
|
||||
$this->assertTrue(json_decode($saved->payload, true)['consent']);
|
||||
$this->putJson($this->url(), [...$data, 'organization_id' => null])->assertConflict();
|
||||
$this->putJson($this->url(), [...$data, 'operation_key' => (string) Str::uuid(), 'version' => $saved->version, 'organization_id' => null])->assertOk();
|
||||
$this->assertNull(app(PartnershipExchange::class)->find($saved->id)->organization_id);
|
||||
}
|
||||
|
||||
public function test_legacy_edits_without_operation_keys_keep_version_conflicts_instead_of_a_false_replay(): void
|
||||
{
|
||||
$data = $this->command();
|
||||
unset($data['operation_key']);
|
||||
$this->putJson($this->url(), $data)->assertOk()->assertJsonPath('replayed', false)->assertJsonPath('saved_version', null);
|
||||
$this->putJson($this->url(), $data)->assertConflict();
|
||||
}
|
||||
|
||||
public function test_operation_keys_are_scoped_to_the_actor_and_partnership(): void
|
||||
{
|
||||
$data = $this->command();
|
||||
$this->putJson($this->url(), $data)->assertOk();
|
||||
$other = User::factory()->create();
|
||||
$record = app(PartnershipExchange::class)->save($other, ['client_key' => (string) Str::uuid(), 'kind' => 'seeking']);
|
||||
$this->actingAs($other)->putJson('/parcerias/'.$record->id,[...$data, 'version' => $record->version])->assertOk()->assertJsonPath('replayed',false);
|
||||
$this->putJson($this->url(),$data)->assertForbidden();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\InvestmentDossier;
|
||||
use App\Models\Project;
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
use App\Services\PartnershipExchange;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class PartnershipEditingTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $owner;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
Http::fake();
|
||||
Mail::fake();
|
||||
$this->owner = User::factory()->create();
|
||||
$this->actingAs($this->owner);
|
||||
}
|
||||
|
||||
private function input(array $changes = []): array
|
||||
{
|
||||
return ['client_key' => (string) Str::uuid(), 'title' => 'SYNTHETIC partnership draft', 'kind' => 'seeking', 'partnership_type' => 'joint_venture',
|
||||
'offer' => 'SYNTHETIC existing resources', 'seeking' => 'SYNTHETIC collaboration', 'payload' => ['summary' => 'SYNTHETIC summary', 'requirements' => 'SYNTHETIC requirements', 'mandatory' => ['capacity'], 'consent' => true, 'confidentiality' => 'private', 'availability' => 'SYNTHETIC resources available from November'], 'origins' => [], 'locations' => [], ...$changes];
|
||||
}
|
||||
|
||||
private function payload(int $id): array
|
||||
{
|
||||
return json_decode(DB::table('portal_partnerships')->where('id', $id)->value('payload'), true, 512, JSON_THROW_ON_ERROR);
|
||||
}
|
||||
|
||||
private function organization(string $name): string
|
||||
{
|
||||
$id = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $id, 'name' => 'SYNTHETIC '.$name, 'source_system' => 'unit-synthetic', 'organization_type' => 'private']);
|
||||
|
||||
return $id;
|
||||
}
|
||||
|
||||
private function links(): array
|
||||
{
|
||||
$place = (string) Str::uuid();
|
||||
// Positive QA fixture for the existing workbook predicate, not an imported official place or geometry.
|
||||
DB::table('geo_locations')->insert(['id' => $place, 'code' => $place, 'name' => 'SYNTHETIC coverage reference', 'location_type' => 'country', 'data_classification' => 'public', 'source_system' => 'cartografia-workbook', 'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:synthetic-'.substr($place, 0, 8)]);
|
||||
$project = Project::factory()->create();
|
||||
InvestmentDossier::create(['project_id' => $project->id, 'title' => 'SYNTHETIC source dossier', 'source' => 'Synthetic fixture, no actual disclosure', 'content' => [], 'publication_status' => 'published', 'published_at' => now()->subMinute(), 'data_classification' => 'public', 'approval_basis' => 'document_owner', 'approval_evidence' => 'Synthetic QA fixture only']);
|
||||
|
||||
return ['origins' => [['type' => 'project', 'target_id' => $project->id]], 'locations' => [['geo_location_id' => $place, 'role' => 'coverage', 'source_reference' => 'SYNTHETIC declared coverage']]];
|
||||
}
|
||||
|
||||
public function test_partial_edits_preserve_organization_and_scalar_fields_without_transferring_ownership(): void
|
||||
{
|
||||
$organization = $this->organization('retained organization');
|
||||
$officer = User::factory()->create();
|
||||
foreach ([$this->owner->id, $officer->id] as $actor) {
|
||||
DB::table('memberships')->insert(['user_id' => $actor, 'organization_id' => $organization, 'role' => 'officer']);
|
||||
}
|
||||
$sector = Sector::create(['name' => 'SYNTHETIC retained sector', 'slug' => 'synthetic-'.Str::uuid(), 'is_active' => true]);
|
||||
$input = $this->input(['organization_id' => $organization, 'sector_id' => $sector->id, 'deadline' => now()->addMonth()->toDateString(), ...$this->links()]);
|
||||
$record = app(PartnershipExchange::class)->save($this->owner, $input);
|
||||
$origins = DB::table('partnership_origins')->where('partnership_id', $record->id)->get()->toArray();
|
||||
$locations = DB::table('partnership_locations')->where('partnership_id', $record->id)->get()->toArray();
|
||||
$this->actingAs($officer)->putJson('/parcerias/'.$record->id, ['version' => $record->version, 'kind' => 'seeking', 'payload' => ['summary' => 'SYNTHETIC summary only']])->assertOk();
|
||||
$saved = DB::table('portal_partnerships')->where('id', $record->id)->first();
|
||||
foreach (['title', 'offer', 'seeking', 'organization_id', 'sector_id', 'partnership_type', 'deadline'] as $field) {
|
||||
$this->assertSame($input[$field], $saved->{$field});
|
||||
}
|
||||
$this->assertSame($record->user_id, $saved->user_id);
|
||||
$this->assertEquals($origins, DB::table('partnership_origins')->where('partnership_id', $record->id)->get()->toArray());
|
||||
$this->assertEquals($locations, DB::table('partnership_locations')->where('partnership_id', $record->id)->get()->toArray());
|
||||
$this->get('/parcerias/'.$record->id.'/editar')->assertOk();
|
||||
}
|
||||
|
||||
public function test_explicit_empty_scalar_and_relation_values_still_remove_the_selected_information(): void
|
||||
{
|
||||
$organization = $this->organization('explicitly removed link');
|
||||
DB::table('memberships')->insert(['user_id' => $this->owner->id, 'organization_id' => $organization, 'role' => 'officer']);
|
||||
$record = app(PartnershipExchange::class)->save($this->owner, $this->input(['organization_id' => $organization, ...$this->links()]));
|
||||
$this->putJson('/parcerias/'.$record->id, ['version' => $record->version, 'kind' => 'seeking', 'title' => null, 'offer' => null, 'seeking' => null, 'organization_id' => null, 'sector_id' => null, 'partnership_type' => null, 'deadline' => null, 'origins' => [], 'locations' => []])->assertOk();
|
||||
$saved = DB::table('portal_partnerships')->where('id', $record->id)->first();
|
||||
$this->assertSame('', $saved->title);
|
||||
$this->assertSame('', $saved->offer);
|
||||
$this->assertSame('', $saved->seeking);
|
||||
$this->assertNull($saved->organization_id);
|
||||
$this->assertNull($saved->sector_id);
|
||||
$this->assertNull($saved->deadline);
|
||||
$this->assertNull($saved->partnership_type);
|
||||
$this->assertSame(0, DB::table('partnership_origins')->where('partnership_id', $record->id)->count());
|
||||
$this->assertSame(0, DB::table('partnership_locations')->where('partnership_id', $record->id)->count());
|
||||
$this->assertSame('SYNTHETIC resources available from November', $this->payload($record->id)['availability']);
|
||||
$this->get('/parcerias/'.$record->id.'/editar')->assertOk();
|
||||
}
|
||||
|
||||
public function test_omitted_availability_is_preserved_when_an_older_editor_saves_other_fields(): void
|
||||
{
|
||||
$input = $this->input();
|
||||
$record = app(PartnershipExchange::class)->save($this->owner, $input);
|
||||
unset($input['payload']['availability']);
|
||||
$this->putJson('/parcerias/'.$record->id, [...$input, 'version' => $record->version, 'title' => 'SYNTHETIC changed title'])->assertOk();
|
||||
$this->assertSame('SYNTHETIC resources available from November', $this->payload($record->id)['availability'] ?? null);
|
||||
}
|
||||
|
||||
public function test_explicit_clearing_is_preserved_and_previous_event_is_not_rewritten(): void
|
||||
{
|
||||
$input = $this->input();
|
||||
$record = app(PartnershipExchange::class)->save($this->owner, $input);
|
||||
$before = DB::table('partnership_events')->where('partnership_id', $record->id)->orderBy('aggregate_version')->first();
|
||||
$input['payload']['availability'] = null;
|
||||
$this->putJson('/parcerias/'.$record->id, [...$input, 'version' => $record->version])->assertOk();
|
||||
$this->assertNull($this->payload($record->id)['availability']);
|
||||
$this->assertSame((array) $before, (array) DB::table('partnership_events')->where('id', $before->id)->first());
|
||||
}
|
||||
|
||||
public function test_omitted_payload_fields_are_retained_but_explicit_false_empty_text_and_lists_are_applied(): void
|
||||
{
|
||||
$input = $this->input();
|
||||
$record = app(PartnershipExchange::class)->save($this->owner, $input);
|
||||
$original = $this->payload($record->id);
|
||||
$this->putJson('/parcerias/'.$record->id, ['version' => $record->version, 'kind' => 'seeking', 'payload' => ['summary' => 'SYNTHETIC only new summary']])->assertOk();
|
||||
$saved = $this->payload($record->id);
|
||||
$this->assertSame($original['availability'], $saved['availability']);
|
||||
$this->assertSame($original['mandatory'], $saved['mandatory']);
|
||||
$this->assertTrue($saved['consent']);
|
||||
$version = DB::table('portal_partnerships')->where('id', $record->id)->value('version');
|
||||
$this->putJson('/parcerias/'.$record->id, ['version' => $version, 'kind' => 'seeking', 'payload' => ['mandatory' => [], 'consent' => false, 'requirements' => '']])->assertOk();
|
||||
$saved = $this->payload($record->id);
|
||||
$this->assertSame([], $saved['mandatory']);
|
||||
$this->assertFalse($saved['consent']);
|
||||
$this->assertNull($saved['requirements']);
|
||||
$this->assertSame($original['_creation_hash'], $saved['_creation_hash']);
|
||||
}
|
||||
|
||||
public function test_creation_replay_requires_current_representation_after_the_record_moves_to_another_organization(): void
|
||||
{
|
||||
$a = $this->organization('original organization');
|
||||
$b = $this->organization('current organization');
|
||||
$representative = User::factory()->create();
|
||||
foreach ([[$this->owner->id, $a], [$representative->id, $a], [$representative->id, $b]] as [$user, $organization]) {
|
||||
DB::table('memberships')->insert(['user_id' => $user, 'organization_id' => $organization, 'role' => 'officer']);
|
||||
}
|
||||
$input = $this->input(['organization_id' => $a]);
|
||||
$record = app(PartnershipExchange::class)->save($this->owner, $input);
|
||||
app(PartnershipExchange::class)->save($representative, [...$input, 'version' => $record->version, 'organization_id' => $b], $record->id);
|
||||
$before = (array) DB::table('portal_partnerships')->where('id', $record->id)->first();
|
||||
$this->postJson('/parcerias/rascunhos', $input)->assertForbidden();
|
||||
$this->assertSame($before, (array) DB::table('portal_partnerships')->where('id', $record->id)->first());
|
||||
$this->get('/parcerias/'.$record->id.'/editar')->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_identical_creation_replay_is_read_only_even_when_its_sector_is_no_longer_active(): void
|
||||
{
|
||||
$sector = Sector::create(['name' => 'SYNTHETIC old sector', 'slug' => 'synthetic-'.Str::uuid(), 'is_active' => true]);
|
||||
$input = $this->input(['sector_id' => $sector->id]);
|
||||
$record = app(PartnershipExchange::class)->save($this->owner, $input);
|
||||
$sector->update(['is_active' => false]);
|
||||
$before = (array) DB::table('portal_partnerships')->where('id', $record->id)->first();
|
||||
$events = DB::table('partnership_events')->count();
|
||||
$this->postJson('/parcerias/rascunhos', $input)->assertOk()->assertJsonPath('id', $record->id)->assertJsonPath('version', $record->version);
|
||||
$this->assertSame($before, (array) DB::table('portal_partnerships')->where('id', $record->id)->first());
|
||||
$this->assertSame($events, DB::table('partnership_events')->count());
|
||||
$this->postJson('/parcerias/rascunhos', [...$input, 'client_key' => (string) Str::uuid()])->assertUnprocessable()->assertJsonValidationErrors('sector_id')->assertJsonPath('errors.sector_id.0', 'Seleccione um sector activo ou deixe a classificação por definir.');
|
||||
$this->putJson('/parcerias/'.$record->id, [...$input, 'version' => $record->version])->assertUnprocessable()->assertJsonValidationErrors('sector_id');
|
||||
}
|
||||
|
||||
public function test_stale_version_and_invalid_fields_cannot_overwrite_current_payload(): void
|
||||
{
|
||||
$input = $this->input();
|
||||
$record = app(PartnershipExchange::class)->save($this->owner, $input);
|
||||
$this->putJson('/parcerias/'.$record->id, [...$input, 'version' => $record->version, 'title' => 'SYNTHETIC current revision'])->assertOk();
|
||||
$current = (array) DB::table('portal_partnerships')->where('id', $record->id)->first();
|
||||
$this->putJson('/parcerias/'.$record->id, [...$input, 'version' => $record->version, 'title' => 'SYNTHETIC stale revision'])->assertConflict();
|
||||
$this->assertSame($current, (array) DB::table('portal_partnerships')->where('id', $record->id)->first());
|
||||
$this->putJson('/parcerias/'.$record->id, [...$input, 'version' => $current['version'], 'payload' => ['availability' => str_repeat('a', 1001)]])->assertUnprocessable()->assertJsonValidationErrors('payload.availability')->assertJsonPath('errors', fn ($errors) => ($errors['payload.availability'][0] ?? null) === 'Indique a disponibilidade em até 1000 caracteres.');
|
||||
$this->assertSame($current, (array) DB::table('portal_partnerships')->where('id', $record->id)->first());
|
||||
}
|
||||
|
||||
public function test_editing_a_published_record_still_returns_to_draft_and_preserves_omitted_availability(): void
|
||||
{
|
||||
$manager = User::factory()->create();
|
||||
config(['portal.managers' => [$manager->email]]);
|
||||
$input = $this->input();
|
||||
$record = app(PartnershipExchange::class)->save($this->owner, $input);
|
||||
$exchange = app(PartnershipExchange::class);
|
||||
$record = $exchange->transition($this->owner, $record->id, $record->version, 'submit', 'SYNTHETIC submission');
|
||||
$record = $exchange->transition($manager, $record->id, $record->version, 'publish', 'SYNTHETIC independent publication');
|
||||
unset($input['payload']['availability']);
|
||||
$this->putJson('/parcerias/'.$record->id, [...$input, 'version' => $record->version, 'title' => 'SYNTHETIC revision for review'])->assertOk()->assertJsonPath('status', 'draft');
|
||||
$this->assertSame('SYNTHETIC resources available from November', $this->payload($record->id)['availability']);
|
||||
}
|
||||
|
||||
public function test_unverified_personal_drafts_and_editor_remain_available_without_organization_or_mfa(): void
|
||||
{
|
||||
$this->owner->update(['email_verified_at' => null]);
|
||||
$record = $this->postJson('/parcerias/rascunhos', $this->input(['title' => '']))->assertOk()->json('id');
|
||||
$this->get('/parcerias/'.$record.'/editar')->assertOk();
|
||||
Http::assertNothingSent();
|
||||
Mail::assertNothingSent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\PartnershipExchange;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Facades\Queue;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class PartnershipParticipantsTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
Http::fake();
|
||||
Mail::fake();
|
||||
Queue::fake();
|
||||
}
|
||||
|
||||
private function organization(string $name): string
|
||||
{
|
||||
$id = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $id, 'name' => 'SYNTHETIC '.$name, 'source_system' => 'unit-synthetic', 'organization_type' => 'private']);
|
||||
|
||||
return $id;
|
||||
}
|
||||
|
||||
private function member(User $user, string $organization, string $role = 'officer'): void
|
||||
{
|
||||
DB::table('memberships')->insert(['user_id' => $user->id, 'organization_id' => $organization, 'role' => $role]);
|
||||
}
|
||||
|
||||
private function room(?string $proponentOrganization = null, ?string $candidateOrganization = null): array
|
||||
{
|
||||
$owner = User::factory()->create(['name' => 'SYNTHETIC original proponent']);
|
||||
$candidate = User::factory()->create(['name' => 'SYNTHETIC original candidate']);
|
||||
if ($proponentOrganization) {
|
||||
$this->member($owner, $proponentOrganization);
|
||||
}
|
||||
if ($candidateOrganization) {
|
||||
$this->member($candidate, $candidateOrganization);
|
||||
}
|
||||
$service = app(PartnershipExchange::class);
|
||||
$record = $service->save($owner, ['client_key' => (string) Str::uuid(), 'title' => 'SYNTHETIC partnership', 'kind' => 'seeking', 'partnership_type' => 'joint_venture', 'organization_id' => $proponentOrganization, 'offer' => 'SYNTHETIC offer', 'seeking' => 'SYNTHETIC cooperation', 'payload' => ['consent' => true]]);
|
||||
$service->transition($owner, $record->id, $record->version, 'submit', 'SYNTHETIC consent to review');
|
||||
$moderator = User::factory()->create();
|
||||
config(['portal.managers' => [$moderator->email]]);
|
||||
$record = $service->find($record->id);
|
||||
$service->transition($moderator, $record->id, $record->version, 'publish', 'SYNTHETIC reviewed');
|
||||
$interest = $service->interest($candidate, $record->id, ['organization_id' => $candidateOrganization, 'proposal' => 'SYNTHETIC proposal', 'payload' => ['consent' => true]]);
|
||||
$interest = $service->decideInterest($owner, $interest->id, $interest->version, 'shortlist', 'SYNTHETIC consideration');
|
||||
$service->decideInterest($owner, $interest->id, $interest->version, 'connect', 'SYNTHETIC connection');
|
||||
$room = DB::table('partnership_rooms')->where('interest_id', $interest->id)->first();
|
||||
$this->actingAs($owner)->postJson('/parcerias/salas/'.$room->id.'/acordo', ['version' => 1, 'action' => 'record', 'title' => 'SYNTHETIC plan', 'terms' => 'SYNTHETIC terms', 'reason' => 'SYNTHETIC record'])->assertOk();
|
||||
|
||||
return [$room->id, $owner, $candidate];
|
||||
}
|
||||
|
||||
public function test_authorized_representatives_are_selectable_and_accepted_without_exposing_account_secrets(): void
|
||||
{
|
||||
$proponentOrganization = $this->organization('proponent');
|
||||
$candidateOrganization = $this->organization('candidate');
|
||||
[$room, $owner, $candidate] = $this->room($proponentOrganization, $candidateOrganization);
|
||||
$officer = User::factory()->create(['name' => 'SYNTHETIC current proponent officer']);
|
||||
$manager = User::factory()->create(['name' => 'SYNTHETIC current candidate manager']);
|
||||
$viewer = User::factory()->create();
|
||||
$outsider = User::factory()->create();
|
||||
$this->member($officer, $proponentOrganization);
|
||||
$this->member($manager, $candidateOrganization, 'manager');
|
||||
$this->member($viewer, $proponentOrganization, 'viewer');
|
||||
$otherOrganization = $this->organization('unrelated');
|
||||
$this->member($outsider, $otherOrganization);
|
||||
$response = $this->actingAs($officer)->getJson('/parcerias/salas/'.$room)->assertOk();
|
||||
$choices = collect($response->json('participants'))->keyBy('id');
|
||||
$this->assertEqualsCanonicalizing([$owner->id, $candidate->id, $officer->id, $manager->id], $choices->keys()->all());
|
||||
$this->assertSame(['proponent'], $choices[$officer->id]['parties']);
|
||||
$this->assertSame(['candidate'], $choices[$manager->id]['parties']);
|
||||
foreach ($choices as $choice) {
|
||||
$this->assertEqualsCanonicalizing(['id', 'name', 'parties'], array_keys($choice));
|
||||
}
|
||||
$this->postJson('/parcerias/salas/'.$room.'/marcos', ['title' => 'SYNTHETIC representative deliverable', 'responsible_id' => $manager->id, 'status' => 'pending'])->assertOk();
|
||||
$this->assertDatabaseHas('partnership_milestones', ['room_id' => $room, 'responsible_id' => $manager->id]);
|
||||
$this->getJson('/parcerias/salas/'.$room)->assertJsonPath('milestones.0.responsible_name', $manager->name)->assertJsonPath('milestones.0.responsible_is_participant', true);
|
||||
}
|
||||
|
||||
public function test_revoked_author_is_historical_but_not_silently_reassigned_or_selectable(): void
|
||||
{
|
||||
$organization = $this->organization('revocation');
|
||||
[$room, $owner] = $this->room($organization);
|
||||
$this->postJson('/parcerias/salas/'.$room.'/marcos', ['title' => 'SYNTHETIC assigned before revocation', 'responsible_id' => $owner->id, 'status' => 'pending'])->assertOk();
|
||||
$milestone = DB::table('partnership_milestones')->where('room_id', $room)->first();
|
||||
$officer = User::factory()->create(['name' => 'SYNTHETIC replacement representative']);
|
||||
$this->member($officer, $organization);
|
||||
DB::table('memberships')->where('user_id', $owner->id)->where('organization_id', $organization)->update(['deleted_at' => now()]);
|
||||
$events = DB::table('partnership_events')->count();
|
||||
$response = $this->actingAs($officer)->getJson('/parcerias/salas/'.$room)->assertOk()->assertJsonPath('milestones.0.responsible_name', $owner->name)->assertJsonPath('milestones.0.responsible_is_participant', false);
|
||||
$this->assertNotContains($owner->id, array_column($response->json('participants'), 'id'));
|
||||
$this->assertDatabaseHas('partnership_milestones', ['id' => $milestone->id, 'responsible_id' => $owner->id, 'version' => 1]);
|
||||
$this->assertSame($events, DB::table('partnership_events')->count());
|
||||
$input = ['version' => 1, 'title' => $milestone->title, 'responsible_id' => $owner->id, 'status' => 'pending'];
|
||||
$this->putJson('/parcerias/salas/'.$room.'/marcos/'.$milestone->id, $input)->assertUnprocessable();
|
||||
$this->putJson('/parcerias/salas/'.$room.'/marcos/'.$milestone->id, [...$input, 'responsible_id' => $officer->id])->assertOk();
|
||||
$this->assertDatabaseHas('partnership_milestones', ['id' => $milestone->id, 'responsible_id' => $officer->id, 'version' => 2]);
|
||||
$event = DB::table('partnership_events')->where('event_type', 'partnership_milestone.changed.v1')->orderByDesc('aggregate_version')->first();
|
||||
$payload = json_decode($event->payload, true)['payload'];
|
||||
$this->assertSame($owner->id, $payload['previous_responsible_id']);
|
||||
$this->assertSame($officer->id, $payload['responsible_id']);
|
||||
$this->actingAs($owner)->getJson('/parcerias/salas/'.$room)->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_personal_parties_are_not_expanded_by_unrelated_memberships_and_dual_representation_is_deduplicated(): void
|
||||
{
|
||||
[$room, $owner, $candidate] = $this->room();
|
||||
$organization = $this->organization('unrelated personal membership');
|
||||
$this->member($owner, $organization);
|
||||
$other = User::factory()->create();
|
||||
$this->member($other, $organization);
|
||||
$response = $this->getJson('/parcerias/salas/'.$room)->assertOk();
|
||||
$this->assertEqualsCanonicalizing([$owner->id, $candidate->id], array_column($response->json('participants'), 'id'));
|
||||
$this->actingAs($other)->getJson('/parcerias/salas/'.$room)->assertForbidden();
|
||||
$a = $this->organization('dual a');
|
||||
$b = $this->organization('dual b');
|
||||
[$secondRoom] = $this->room($a, $b);
|
||||
$dual = User::factory()->create();
|
||||
$this->member($dual, $a);
|
||||
$this->member($dual, $b);
|
||||
$choices = $this->actingAs($dual)->getJson('/parcerias/salas/'.$secondRoom)->assertOk()->json('participants');
|
||||
$matching = array_values(array_filter($choices, fn ($choice) => $choice['id'] === $dual->id));
|
||||
$this->assertCount(1, $matching);
|
||||
$this->assertSame(['proponent', 'candidate'], $matching[0]['parties']);
|
||||
}
|
||||
|
||||
public function test_read_only_and_closed_rooms_do_not_offer_assignment_choices_and_unrelated_users_are_denied(): void
|
||||
{
|
||||
$organization = $this->organization('read only');
|
||||
[$room, $owner] = $this->room($organization);
|
||||
$viewer = User::factory()->create();
|
||||
$this->member($viewer, $organization, 'viewer');
|
||||
$this->actingAs($viewer)->getJson('/parcerias/salas/'.$room)->assertOk()->assertJsonPath('canWrite', false)->assertJsonPath('participants', []);
|
||||
$this->postJson('/parcerias/salas/'.$room.'/marcos', ['title' => 'SYNTHETIC refused', 'responsible_id' => $owner->id, 'status' => 'pending'])->assertForbidden();
|
||||
$this->actingAs(User::factory()->create())->getJson('/parcerias/salas/'.$room)->assertForbidden();
|
||||
$this->actingAs($owner)->postJson('/parcerias/salas/'.$room.'/acordo', ['version' => 2, 'action' => 'cancel', 'reason' => 'SYNTHETIC cancelled'])->assertOk();
|
||||
$this->getJson('/parcerias/salas/'.$room)->assertOk()->assertJsonPath('participants', []);
|
||||
$this->postJson('/parcerias/salas/'.$room.'/marcos', ['title' => 'SYNTHETIC refused', 'responsible_id' => $owner->id, 'status' => 'pending'])->assertConflict();
|
||||
}
|
||||
|
||||
public function test_cached_choices_do_not_authorize_assignment_after_downgrade_and_unrelated_ids_are_refused(): void
|
||||
{
|
||||
$organization = $this->organization('cached selection');
|
||||
[$room, $owner, $candidate] = $this->room($organization);
|
||||
$officer = User::factory()->create();
|
||||
$this->member($officer, $organization);
|
||||
$this->getJson('/parcerias/salas/'.$room)->assertOk()->assertJsonFragment(['id' => $officer->id, 'name' => $officer->name, 'parties' => ['proponent']]);
|
||||
DB::table('memberships')->where('user_id', $officer->id)->where('organization_id', $organization)->update(['role' => 'viewer']);
|
||||
$input = ['title' => 'SYNTHETIC rejected cached assignment', 'responsible_id' => $officer->id, 'status' => 'pending'];
|
||||
$events = DB::table('partnership_events')->count();
|
||||
$this->postJson('/parcerias/salas/'.$room.'/marcos', $input)->assertUnprocessable();
|
||||
$this->postJson('/parcerias/salas/'.$room.'/marcos', [...$input, 'responsible_id' => User::factory()->create()->id])->assertUnprocessable();
|
||||
$this->assertDatabaseCount('partnership_milestones', 0);
|
||||
$this->assertSame($events, DB::table('partnership_events')->count());
|
||||
$this->postJson('/parcerias/salas/'.$room.'/marcos', [...$input, 'responsible_id' => $candidate->id])->assertOk();
|
||||
$milestone = DB::table('partnership_milestones')->where('room_id', $room)->first();
|
||||
$this->putJson('/parcerias/salas/'.$room.'/marcos/'.$milestone->id, [...$input, 'responsible_id' => $owner->id, 'version' => 99])->assertConflict();
|
||||
$this->assertDatabaseHas('partnership_milestones', ['id' => $milestone->id, 'responsible_id' => $candidate->id, 'version' => 1]);
|
||||
}
|
||||
|
||||
public function test_deleted_organizations_are_not_assignment_sources_and_personal_participant_remains_available(): void
|
||||
{
|
||||
$organization = $this->organization('deleted');
|
||||
[$room, $owner, $candidate] = $this->room($organization);
|
||||
DB::table('organizations')->where('id', $organization)->update(['deleted_at' => now()]);
|
||||
$response = $this->actingAs($candidate)->getJson('/parcerias/salas/'.$room)->assertOk();
|
||||
$this->assertSame([['id' => $candidate->id, 'name' => $candidate->name, 'parties' => ['candidate']]], $response->json('participants'));
|
||||
$this->postJson('/parcerias/salas/'.$room.'/marcos', ['title' => 'SYNTHETIC unavailable organization', 'responsible_id' => $owner->id, 'status' => 'pending'])->assertUnprocessable();
|
||||
$this->postJson('/parcerias/salas/'.$room.'/marcos', ['title' => 'SYNTHETIC personal participant', 'responsible_id' => $candidate->id, 'status' => 'pending'])->assertOk();
|
||||
$this->actingAs($owner)->getJson('/parcerias/salas/'.$room)->assertForbidden();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Http\Middleware\HandleInertiaRequests;
|
||||
use App\Models\InvestmentDossier;
|
||||
use App\Models\Project;
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
use App\Services\PartnershipExchange;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Facades\Queue;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class PartnershipPublicationHistoryTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $owner;
|
||||
|
||||
private User $moderator;
|
||||
|
||||
private object $record;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
Http::fake();
|
||||
Mail::fake();
|
||||
Queue::fake();
|
||||
$this->owner = User::factory()->create();
|
||||
$this->moderator = User::factory()->create();
|
||||
config(['portal.managers' => [$this->moderator->email]]);
|
||||
$this->record = app(PartnershipExchange::class)->save($this->owner, ['client_key' => (string) Str::uuid(), 'title' => 'SYNTHETIC original history title', 'kind' => 'seeking', 'partnership_type' => 'joint_venture', 'offer' => 'SYNTHETIC original offer', 'payload' => ['consent' => true, 'confidentiality' => 'private', 'mandatory' => ['capacity']]]);
|
||||
$this->actingAs($this->owner);
|
||||
}
|
||||
|
||||
private function url(?int $id = null): string
|
||||
{
|
||||
return '/parcerias/'.($id ?? $this->record->id).'/historico';
|
||||
}
|
||||
|
||||
private function edit(array $data = []): object
|
||||
{
|
||||
$current = app(PartnershipExchange::class)->find($this->record->id);
|
||||
|
||||
return app(PartnershipExchange::class)->save($this->owner, ['version' => $current->version, 'kind' => 'seeking', ...$data], $current->id);
|
||||
}
|
||||
|
||||
private function organization(User $person, string $role = 'officer'): string
|
||||
{
|
||||
$id = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $id, 'name' => 'SYNTHETIC versions organization', 'organization_type' => 'private']);
|
||||
DB::table('memberships')->insert(['user_id' => $person->id, 'organization_id' => $id, 'role' => $role]);
|
||||
|
||||
return $id;
|
||||
}
|
||||
|
||||
public function test_creation_edit_and_transition_have_real_before_and_after_versions_without_a_placeholder(): void
|
||||
{
|
||||
$edit = $this->edit(['title' => 'SYNTHETIC revised title']);
|
||||
app(PartnershipExchange::class)->transition($this->owner, $edit->id, $edit->version, 'submit', 'SYNTHETIC reviewed content', (string) Str::uuid());
|
||||
$this->getJson($this->url())->assertOk()->assertJsonCount(3, 'entries')->assertJsonPath('entries.0.action', 'submit')->assertJsonPath('entries.0.previous.fields.title', 'SYNTHETIC revised title')->assertJsonPath('entries.0.after.status', 'submitted')->assertJsonPath('entries.1.previous.fields.title', 'SYNTHETIC original history title')->assertJsonPath('entries.1.after.fields.title', 'SYNTHETIC revised title')->assertJsonPath('entries.2.action', 'create')->assertJsonPath('entries.2.previous.availability', 'not_recorded')->assertJsonPath('entries.2.after.version', $this->record->version);
|
||||
}
|
||||
|
||||
public function test_publication_is_not_historical_access_for_another_candidate_or_anonymous_reader(): void
|
||||
{
|
||||
$service = app(PartnershipExchange::class);
|
||||
$record = $service->transition($this->owner, $this->record->id, $this->record->version, 'submit', 'SYNTHETIC submit');
|
||||
$record = $service->transition($this->moderator, $record->id, $record->version, 'publish', 'SYNTHETIC publish');
|
||||
$candidate = User::factory()->create();
|
||||
$service->interest($candidate, $record->id, ['proposal' => 'SYNTHETIC candidate', 'payload' => ['consent' => true]]);
|
||||
$this->actingAs($candidate)->getJson($this->url())->assertForbidden();
|
||||
$this->actingAs($this->moderator)->getJson($this->url())->assertOk();
|
||||
auth()->forgetGuards();
|
||||
$this->getJson($this->url())->assertUnauthorized();
|
||||
}
|
||||
|
||||
public function test_changing_organizations_does_not_transfer_the_prior_private_snapshot(): void
|
||||
{
|
||||
$orgA = $this->organization($this->owner);
|
||||
$this->edit(['organization_id' => $orgA, 'offer' => 'SYNTHETIC A-only offer']);
|
||||
$orgB = $this->organization($this->owner);
|
||||
$this->edit(['organization_id' => $orgB, 'offer' => 'SYNTHETIC B offer']);
|
||||
$viewer = User::factory()->create();
|
||||
DB::table('memberships')->insert(['user_id' => $viewer->id, 'organization_id' => $orgB, 'role' => 'viewer']);
|
||||
$response = $this->actingAs($viewer)->getJson($this->url())->assertOk()->assertJsonPath('entries.0.after.fields.offer', 'SYNTHETIC B offer')->assertJsonPath('entries.0.previous.availability', 'restricted')->assertJsonPath('entries.1.restricted', true)->assertJsonPath('entries.2.restricted', true);
|
||||
$this->assertStringNotContainsString('SYNTHETIC A-only offer', $response->getContent());
|
||||
$this->postJson('/parcerias/'.$this->record->id.'/estado', ['version' => $this->record->version + 2, 'action' => 'archive', 'reason' => 'SYNTHETIC unauthorized action'])->assertForbidden();
|
||||
$this->actingAs($this->moderator)->getJson($this->url())->assertOk()->assertJsonPath('entries.0.previous.fields.offer', 'SYNTHETIC A-only offer');
|
||||
}
|
||||
|
||||
public function test_revoked_author_and_deleted_organization_do_not_keep_owner_history_access(): void
|
||||
{
|
||||
$org = $this->organization($this->owner);
|
||||
$this->edit(['organization_id' => $org]);
|
||||
DB::table('memberships')->where('user_id', $this->owner->id)->where('organization_id', $org)->update(['deleted_at' => now()]);
|
||||
$this->getJson($this->url())->assertForbidden();
|
||||
DB::table('memberships')->where('user_id', $this->owner->id)->where('organization_id', $org)->update(['deleted_at' => null]);
|
||||
DB::table('organizations')->where('id', $org)->update(['deleted_at' => now()]);
|
||||
$this->getJson($this->url())->assertForbidden();
|
||||
$this->actingAs($this->moderator)->getJson($this->url())->assertOk();
|
||||
}
|
||||
|
||||
public function test_legacy_unknown_scope_is_partial_for_moderation_and_not_reconstructed_from_current_content(): void
|
||||
{
|
||||
app(PartnershipExchange::class)->event($this->record, $this->owner, 'partnership_opportunity.changed.v1', ['previous_status' => 'published'], 'SYNTHETIC legacy event');
|
||||
DB::table('portal_partnerships')->where('id', $this->record->id)->update(['title' => 'SYNTHETIC current-only private title']);
|
||||
$this->getJson($this->url())->assertOk()->assertJsonPath('entries.0.restricted', true)->assertJsonPath('entries.0.after.availability', 'scope_unknown');
|
||||
$response = $this->actingAs($this->moderator)->getJson($this->url())->assertOk()->assertJsonPath('entries.0.action', null)->assertJsonPath('entries.0.previous.status', 'published')->assertJsonPath('entries.0.previous.version', null)->assertJsonPath('entries.0.after.complete', false)->assertJsonPath('entries.0.after.status', null)->assertJsonPath('entries.0.after.scope_known', false);
|
||||
$this->assertArrayNotHasKey('title', $response->json('entries.0.after.fields'));
|
||||
$this->assertStringNotContainsString('SYNTHETIC current-only private title', $response->getContent());
|
||||
}
|
||||
|
||||
public function test_known_legacy_context_authorizes_only_a_partial_recorded_state_and_reason(): void
|
||||
{
|
||||
DB::table('portal_partnerships')->where('id', $this->record->id)->update(['status' => 'returned']);
|
||||
$record = app(PartnershipExchange::class)->find($this->record->id);
|
||||
app(PartnershipExchange::class)->event($record, $this->owner, 'partnership_opportunity.returned.v1', ['from' => 'submitted', 'to' => 'returned', 'reason' => 'SYNTHETIC legacy recorded reason'], 'SYNTHETIC legacy notice', [$this->owner->id]);
|
||||
$this->getJson($this->url())->assertOk()->assertJsonPath('entries.0.reason', 'SYNTHETIC legacy recorded reason')->assertJsonPath('entries.0.action', null)->assertJsonPath('entries.0.after.status', 'returned')->assertJsonPath('entries.0.after.complete', false)->assertJsonPath('entries.0.previous.availability', 'scope_unknown');
|
||||
}
|
||||
|
||||
public function test_pagination_is_stable_when_new_versions_arrive_and_never_includes_candidacy_events(): void
|
||||
{
|
||||
for ($i = 1; $i <= 20; $i++) {
|
||||
$this->edit(['title' => 'SYNTHETIC revision '.$i]);
|
||||
}app(PartnershipExchange::class)->event(app(PartnershipExchange::class)->find($this->record->id), $this->owner, 'partnership_interest.changed.v1', [], 'SYNTHETIC other aggregate');
|
||||
$first = $this->getJson($this->url())->assertOk()->assertJsonCount(10, 'entries')->assertJsonPath('entries.0.version', 22)->assertJsonPath('entries.9.version', 13);
|
||||
$next = $first->json('next_url');
|
||||
$this->edit(['title' => 'SYNTHETIC later revision']);
|
||||
$second = $this->getJson($next)->assertOk()->assertJsonCount(10, 'entries')->assertJsonPath('entries.0.version', 12)->assertJsonPath('entries.9.version', 3);
|
||||
$this->getJson($second->json('next_url'))->assertOk()->assertJsonCount(1, 'entries')->assertJsonPath('entries.0.version', 2)->assertJsonPath('next_url', null);
|
||||
$this->getJson($this->url())->assertOk()->assertJsonPath('entries.0.version', 23);
|
||||
}
|
||||
|
||||
public function test_cursor_is_bound_to_actor_process_and_purpose_and_never_grants_access_after_revocation(): void
|
||||
{
|
||||
$org = $this->organization($this->owner);
|
||||
$this->edit(['organization_id' => $org]);
|
||||
for ($i = 0; $i < 10; $i++) {
|
||||
$this->edit(['title' => 'SYNTHETIC cursor revision '.$i]);
|
||||
}$cursor = $this->getJson($this->url())->assertOk()->json('next_url');
|
||||
$this->assertIsString($cursor);
|
||||
$this->actingAs($this->moderator)->getJson($cursor)->assertUnprocessable();
|
||||
$this->actingAs($this->owner);
|
||||
$other = app(PartnershipExchange::class)->save($this->owner, ['client_key' => (string) Str::uuid(), 'kind' => 'seeking']);
|
||||
$this->getJson($this->url($other->id).'?'.parse_url($cursor, PHP_URL_QUERY))->assertUnprocessable();
|
||||
$this->getJson($this->url().'?before=invalid-token')->assertUnprocessable();
|
||||
$token = Crypt::encryptString(json_encode(['actor' => $this->owner->id, 'interest' => $this->record->id, 'before' => 999]));
|
||||
$this->getJson($this->url().'?before='.rawurlencode($token))->assertUnprocessable();
|
||||
DB::table('memberships')->where('organization_id', $org)->where('user_id', $this->owner->id)->update(['deleted_at' => now()]);
|
||||
$this->getJson($cursor)->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_native_history_is_read_only_private_and_does_not_serialize_command_or_event_envelopes(): void
|
||||
{
|
||||
app(PartnershipExchange::class)->transition($this->owner, $this->record->id, $this->record->version, 'archive', 'SYNTHETIC archive', (string) Str::uuid());
|
||||
$row = DB::table('portal_partnerships')->where('id', $this->record->id)->first();
|
||||
$events = DB::table('partnership_events')->count();
|
||||
$audits = DB::table('audit_events')->count();
|
||||
$notices = DB::table('partnership_notifications')->count();
|
||||
$version = app(HandleInertiaRequests::class)->version(Request::create($this->url()));
|
||||
$response = $this->get($this->url(), ['X-Inertia' => 'true', 'X-Inertia-Version' => $version ?? ''])->assertOk()->assertJsonPath('component', 'partnerships/publication-history')->assertJsonPath('encryptHistory', true);
|
||||
$this->assertTrue($response->headers->hasCacheControlDirective('private'));
|
||||
$this->assertTrue($response->headers->hasCacheControlDirective('no-store'));
|
||||
foreach (['command_hash', 'client_key', 'aggregate_version', '_notification_context', '_creation_hash'] as $private) {
|
||||
$this->assertStringNotContainsString($private, $response->getContent());
|
||||
}
|
||||
$this->assertEquals($row, DB::table('portal_partnerships')->where('id', $this->record->id)->first());
|
||||
$this->assertSame($events, DB::table('partnership_events')->count());
|
||||
$this->assertSame($audits, DB::table('audit_events')->count());
|
||||
$this->assertSame($notices, DB::table('partnership_notifications')->count());
|
||||
}
|
||||
|
||||
public function test_recorded_references_and_declarations_survive_current_catalogue_changes_and_explicit_clearing(): void
|
||||
{
|
||||
$place = (string) Str::uuid();
|
||||
DB::table('geo_locations')->insert(['id' => $place, 'code' => $place, 'name' => 'SYNTHETIC location', 'location_type' => 'country', 'data_classification' => 'public', 'source_system' => 'cartografia-workbook', 'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:synthetic-'.substr($place, 0, 8)]);
|
||||
$project = Project::factory()->create();
|
||||
InvestmentDossier::create(['project_id' => $project->id, 'title' => 'SYNTHETIC source', 'source' => 'Synthetic fixture only', 'content' => [], 'publication_status' => 'published', 'published_at' => now()->subMinute(), 'data_classification' => 'public', 'approval_basis' => 'document_owner', 'approval_evidence' => 'Synthetic QA fixture only']);
|
||||
$sector = Sector::create(['name' => 'SYNTHETIC sector', 'slug' => 'synthetic-'.Str::uuid(), 'is_active' => true]);
|
||||
$this->edit(['sector_id' => $sector->id, 'origins' => [['type' => 'project', 'target_id' => $project->id]], 'locations' => [['geo_location_id' => $place, 'role' => 'coverage', 'source_reference' => 'SYNTHETIC original declared source']]]);
|
||||
$this->edit(['sector_id' => null, 'offer' => null, 'origins' => [], 'locations' => [], 'payload' => ['consent' => false, 'mandatory' => []]]);
|
||||
DB::table('geo_locations')->where('id', $place)->update(['name' => 'SYNTHETIC renamed current location']);
|
||||
$sector->update(['is_active' => false]);
|
||||
$response = $this->getJson($this->url())->assertOk()->assertJsonPath('entries.0.previous.sector_id', (string) $sector->id)->assertJsonPath('entries.0.previous.origins.0.target_id', $project->id)->assertJsonPath('entries.0.previous.locations.0.source_reference', 'SYNTHETIC original declared source')->assertJsonPath('entries.0.after.fields.offer', '')->assertJsonPath('entries.0.after.consent', false)->assertJsonPath('entries.0.after.mandatory_known', true)->assertJsonPath('entries.0.after.mandatory', [])->assertJsonPath('entries.0.after.origins', []);
|
||||
$this->assertStringNotContainsString('SYNTHETIC renamed current location', $response->getContent());
|
||||
}
|
||||
|
||||
public function test_malformed_scope_or_references_are_unknown_instead_of_a_different_proposal_or_an_empty_source_list(): void
|
||||
{
|
||||
$event = DB::table('partnership_events')->where('partnership_id', $this->record->id)->first();
|
||||
$payload = json_decode($event->payload, true);
|
||||
$original = $payload['payload']['applied'];
|
||||
$payload['payload']['applied']['id'] = $this->record->id + 999;
|
||||
DB::table('partnership_events')->where('id', $event->id)->update(['payload' => json_encode($payload)]);
|
||||
$this->actingAs($this->moderator)->getJson($this->url())->assertOk()->assertJsonPath('entries.0.after.availability', 'scope_unknown');
|
||||
$payload['payload']['applied'] = $original;
|
||||
$payload['payload']['applied']['origins'] = [['invalid' => true]];
|
||||
$payload['payload']['applied']['locations'] = [['geo_location_id' => 'invalid identity']];
|
||||
$payload['payload']['applied']['sector_id'] = ['invalid'];
|
||||
DB::table('partnership_events')->where('id', $event->id)->update(['payload' => json_encode($payload)]);
|
||||
$this->getJson($this->url())->assertOk()->assertJsonPath('entries.0.after.origins_incomplete', true)->assertJsonPath('entries.0.after.locations_incomplete', true)->assertJsonPath('entries.0.after.complete', false)->assertJsonPath('entries.0.after.sector_recorded', false);
|
||||
}
|
||||
|
||||
public function test_repeating_creation_does_not_add_a_false_revision_or_rewrite_a_snapshot(): void
|
||||
{
|
||||
$service = app(PartnershipExchange::class);
|
||||
$input = ['client_key' => (string) Str::uuid(), 'kind' => 'seeking', 'title' => 'SYNTHETIC replay'];
|
||||
$record = $service->save($this->owner, $input);
|
||||
$before = DB::table('partnership_events')->where('partnership_id', $record->id)->first();
|
||||
$service->save($this->owner, $input);
|
||||
$this->assertSame(1, DB::table('partnership_events')->where('partnership_id', $record->id)->count());
|
||||
$this->assertEquals($before, DB::table('partnership_events')->where('partnership_id', $record->id)->first());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\PartnershipExchange;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Facades\Queue;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class PartnershipPublicationRecoveryTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $owner;
|
||||
|
||||
private User $moderator;
|
||||
|
||||
private object $record;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
Http::fake();
|
||||
Mail::fake();
|
||||
Queue::fake();
|
||||
$this->owner = User::factory()->create();
|
||||
$this->moderator = User::factory()->create();
|
||||
config(['portal.managers' => [$this->moderator->email]]);
|
||||
$this->record = app(PartnershipExchange::class)->save($this->owner, ['client_key' => (string) Str::uuid(), 'title' => 'SYNTHETIC publication proposal', 'kind' => 'seeking', 'partnership_type' => 'joint_venture', 'offer' => 'SYNTHETIC offer', 'payload' => ['consent' => true, 'confidentiality' => 'private']]);
|
||||
$this->actingAs($this->owner);
|
||||
}
|
||||
|
||||
private function command(string $action, ?int $version = null): array
|
||||
{
|
||||
return ['client_key' => (string) Str::uuid(), 'version' => $version ?? $this->record->version, 'action' => $action, 'reason' => 'SYNTHETIC documented action'];
|
||||
}
|
||||
|
||||
private function url(): string
|
||||
{
|
||||
return '/parcerias/'.$this->record->id.'/estado';
|
||||
}
|
||||
|
||||
public function test_repeating_a_committed_transition_is_a_read_after_a_later_transition(): void
|
||||
{
|
||||
$data = $this->command('archive');
|
||||
$this->postJson($this->url(), $data)->assertOk();
|
||||
$version = (int) DB::table('portal_partnerships')->where('id', $this->record->id)->value('version');
|
||||
$this->postJson($this->url(), $this->command('renew', $version))->assertOk();
|
||||
$events = DB::table('partnership_events')->count();
|
||||
$this->postJson($this->url(), $data)->assertOk()->assertJsonPath('replayed', true)->assertJsonPath('status', 'draft');
|
||||
$this->assertSame($events, DB::table('partnership_events')->count());
|
||||
}
|
||||
|
||||
public function test_current_authority_precedes_a_stale_version_conflict(): void
|
||||
{
|
||||
$this->actingAs(User::factory()->create())->postJson($this->url(), $this->command('archive', $this->record->version + 99))->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_publication_actions_match_existing_server_authority_including_suspension(): void
|
||||
{
|
||||
$service = app(PartnershipExchange::class);
|
||||
$submitted = $service->transition($this->owner, $this->record->id, $this->record->version, 'submit', 'SYNTHETIC submit');
|
||||
$published = $service->transition($this->moderator, $this->record->id, $submitted->version, 'publish', 'SYNTHETIC publish');
|
||||
$this->actingAs($this->moderator)->getJson('/parcerias/'.$published->id)->assertOk()->assertJsonPath('publicationActions', ['suspend']);
|
||||
}
|
||||
|
||||
public function test_same_nonce_with_changed_action_or_reason_is_refused_without_new_writes(): void
|
||||
{
|
||||
$data = $this->command('archive');
|
||||
$this->postJson($this->url(), $data)->assertOk()->assertJsonPath('replayed', false);
|
||||
$events = DB::table('partnership_events')->count();
|
||||
$notices = DB::table('partnership_notifications')->count();
|
||||
$this->postJson($this->url(), [...$data, 'reason' => 'SYNTHETIC different reason'])->assertConflict();
|
||||
$this->postJson($this->url(), [...$data, 'action' => 'renew'])->assertConflict();
|
||||
$this->postJson($this->url(), [...$data, 'client_key' => strtoupper($data['client_key']), 'reason' => ' '.$data['reason'].' '])->assertOk()->assertJsonPath('replayed', true);
|
||||
$this->assertSame($events, DB::table('partnership_events')->count());
|
||||
$this->assertSame($notices, DB::table('partnership_notifications')->count());
|
||||
}
|
||||
|
||||
public function test_audit_keeps_the_proposal_used_before_and_after_transition_without_child_cascades(): void
|
||||
{
|
||||
$data = $this->command('submit');
|
||||
$this->postJson($this->url(), $data)->assertOk();
|
||||
$event = DB::table('partnership_events')->where('event_type', 'partnership_opportunity.submitted.v1')->first();
|
||||
$metadata = json_decode($event->payload, true)['payload'];
|
||||
$this->assertSame('SYNTHETIC publication proposal', $metadata['previous']['title']);
|
||||
$this->assertSame('SYNTHETIC offer', $metadata['applied']['offer']);
|
||||
$this->assertSame('draft', $metadata['previous']['status']);
|
||||
$this->assertSame('submitted', $metadata['applied']['status']);
|
||||
$this->assertSame($this->record->version, $metadata['previous']['version']);
|
||||
$this->assertSame($this->record->version + 1, $metadata['result_version']);
|
||||
$this->assertSame('private', $metadata['previous']['payload']['confidentiality']);
|
||||
$this->assertArrayNotHasKey('_creation_hash', $metadata['previous']['payload']);
|
||||
$this->assertSame(0, DB::table('partnership_interests')->count());
|
||||
$this->assertSame(0, DB::table('partnership_rooms')->count());
|
||||
}
|
||||
|
||||
public function test_revoked_organization_author_cannot_replay_even_a_committed_transition(): void
|
||||
{
|
||||
$org = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $org, 'name' => 'SYNTHETIC publisher organization', 'organization_type' => 'private']);
|
||||
DB::table('memberships')->insert(['user_id' => $this->owner->id, 'organization_id' => $org, 'role' => 'officer']);
|
||||
DB::table('portal_partnerships')->where('id', $this->record->id)->update(['organization_id' => $org]);
|
||||
$data = $this->command('archive');
|
||||
$this->postJson($this->url(), $data)->assertOk();
|
||||
DB::table('memberships')->where('user_id', $this->owner->id)->where('organization_id', $org)->update(['deleted_at' => now()]);
|
||||
$this->postJson($this->url(), $data)->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_owner_cannot_publish_their_own_proposal_even_with_the_moderation_gate(): void
|
||||
{
|
||||
$service = app(PartnershipExchange::class);
|
||||
$record = $service->transition($this->owner, $this->record->id, $this->record->version, 'submit', 'SYNTHETIC submit');
|
||||
config(['portal.managers' => [$this->owner->email]]);
|
||||
$this->getJson('/parcerias/'.$record->id)->assertOk()->assertJsonPath('publicationActions', []);
|
||||
$this->postJson($this->url(), $this->command('publish', $record->version))->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_command_keys_are_private_to_the_current_authorized_actor_and_raw_events_stay_private(): void
|
||||
{
|
||||
$data = $this->command('submit');
|
||||
$this->postJson($this->url(), $data)->assertOk();
|
||||
$response = $this->getJson('/parcerias/'.$this->record->id)->assertOk()->assertJsonPath('publicationCommands.0.key', strtolower($data['client_key']));
|
||||
$response->assertJsonMissingPath('history');
|
||||
$summary = $response->json('historySummary.entries.0');
|
||||
$this->assertIsArray($summary);
|
||||
foreach (['payload', 'event_type', 'actor_id', 'command_hash'] as $private) {
|
||||
$this->assertArrayNotHasKey($private, $summary);
|
||||
}
|
||||
$this->assertStringNotContainsString('command_hash', $response->getContent());
|
||||
$this->assertStringNotContainsString('_notification_context', $response->getContent());
|
||||
$this->actingAs($this->moderator)->getJson('/parcerias/'.$this->record->id)->assertOk()->assertJsonPath('publicationCommands', []);
|
||||
$record = app(PartnershipExchange::class)->find($this->record->id);
|
||||
app(PartnershipExchange::class)->transition($this->moderator, $record->id, $record->version, 'publish', 'SYNTHETIC publish');
|
||||
$this->actingAs(User::factory()->create())->getJson('/parcerias/'.$record->id)->assertOk()->assertJsonPath('publicationCommands', [])->assertJsonPath('publicationActions', [])->assertJsonPath('historySummary', null)->assertJsonMissingPath('history');
|
||||
}
|
||||
|
||||
public function test_validation_and_legacy_requests_preserve_existing_submission_requirements(): void
|
||||
{
|
||||
$events = DB::table('partnership_events')->count();
|
||||
$this->postJson($this->url(), [...$this->command('submit'), 'reason' => ' '])->assertUnprocessable();
|
||||
$this->postJson($this->url(), [...$this->command('submit'), 'client_key' => 'invalid'])->assertUnprocessable();
|
||||
DB::table('portal_partnerships')->where('id', $this->record->id)->update(['payload' => json_encode(['consent' => false])]);
|
||||
$this->postJson($this->url(), $this->command('submit'))->assertUnprocessable();
|
||||
$this->assertSame($events, DB::table('partnership_events')->count());
|
||||
DB::table('portal_partnerships')->where('id', $this->record->id)->update(['payload' => json_encode(['consent' => true])]);
|
||||
$legacy = $this->command('submit');
|
||||
unset($legacy['client_key']);
|
||||
$this->postJson($this->url(), $legacy)->assertOk()->assertJsonPath('replayed', false);
|
||||
}
|
||||
|
||||
public function test_losing_moderation_authority_prevents_replay_and_removes_its_command_metadata(): void
|
||||
{
|
||||
$service = app(PartnershipExchange::class);
|
||||
$record = $service->transition($this->owner, $this->record->id, $this->record->version, 'submit', 'SYNTHETIC submit');
|
||||
$data = $this->command('publish', $record->version);
|
||||
$this->actingAs($this->moderator)->postJson($this->url(), $data)->assertOk();
|
||||
config(['portal.managers' => []]);
|
||||
$this->getJson('/parcerias/'.$record->id)->assertOk()->assertJsonPath('publicationCommands', []);
|
||||
$this->postJson($this->url(), $data)->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_stale_version_does_not_write_and_suspension_uses_the_existing_state_graph(): void
|
||||
{
|
||||
$this->postJson($this->url(), $this->command('archive', $this->record->version + 1))->assertConflict();
|
||||
$service = app(PartnershipExchange::class);
|
||||
$record = $service->transition($this->owner, $this->record->id, $this->record->version, 'submit', 'SYNTHETIC submit');
|
||||
$record = $service->transition($this->moderator, $record->id, $record->version, 'publish', 'SYNTHETIC publish');
|
||||
$this->actingAs($this->moderator)->postJson($this->url(), $this->command('suspend', $record->version))->assertOk()->assertJsonPath('status', 'suspended');
|
||||
$this->getJson('/parcerias/'.$record->id)->assertOk()->assertJsonPath('publicationActions', []);
|
||||
$this->actingAs($this->owner)->getJson('/parcerias/'.$record->id)->assertOk()->assertJsonPath('publicationActions', ['archive', 'renew']);
|
||||
}
|
||||
|
||||
public function test_nonce_is_scoped_to_process_and_actor_and_another_owner_cannot_recover_it(): void
|
||||
{
|
||||
$data = $this->command('archive');
|
||||
$this->postJson($this->url(), $data)->assertOk();
|
||||
$other = User::factory()->create();
|
||||
$record = app(PartnershipExchange::class)->save($other, ['client_key' => (string) Str::uuid(), 'kind' => 'seeking']);
|
||||
$this->actingAs($other)->postJson('/parcerias/'.$record->id.'/estado', [...$data, 'version' => $record->version])->assertOk()->assertJsonPath('replayed', false);
|
||||
$this->postJson($this->url(), $data)->assertForbidden();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\PartnershipExchange;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Facades\Queue;
|
||||
use Illuminate\Support\Str;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class PartnershipPublicationSummaryTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $owner;
|
||||
|
||||
private User $moderator;
|
||||
|
||||
private object $record;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
Http::fake();
|
||||
Mail::fake();
|
||||
Queue::fake();
|
||||
$this->owner = User::factory()->create();
|
||||
$this->moderator = User::factory()->create();
|
||||
config(['portal.managers' => [$this->moderator->email]]);
|
||||
$this->record = app(PartnershipExchange::class)->save($this->owner, ['client_key' => (string) Str::uuid(), 'title' => 'SYNTHETIC original history title', 'kind' => 'seeking', 'partnership_type' => 'joint_venture', 'offer' => 'SYNTHETIC original offer', 'payload' => ['consent' => true, 'confidentiality' => 'private', 'mandatory' => ['capacity']]]);
|
||||
$this->actingAs($this->owner);
|
||||
}
|
||||
|
||||
private function url(?int $id = null): string
|
||||
{
|
||||
return '/parcerias/'.($id ?? $this->record->id).'/historico';
|
||||
}
|
||||
|
||||
private function edit(array $data = []): object
|
||||
{
|
||||
$current = app(PartnershipExchange::class)->find($this->record->id);
|
||||
|
||||
return app(PartnershipExchange::class)->save($this->owner, ['version' => $current->version, 'kind' => 'seeking', ...$data], $current->id);
|
||||
}
|
||||
|
||||
private function organization(User $person, string $role = 'officer'): string
|
||||
{
|
||||
$id = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $id, 'name' => 'SYNTHETIC versions organization', 'organization_type' => 'private']);
|
||||
DB::table('memberships')->insert(['user_id' => $person->id, 'organization_id' => $id, 'role' => $role]);
|
||||
|
||||
return $id;
|
||||
}
|
||||
|
||||
public function test_detail_exposes_a_bounded_summary_instead_of_raw_event_rows(): void
|
||||
{
|
||||
for ($i = 0; $i < 9; $i++) {
|
||||
$this->edit(['title' => 'SYNTHETIC revision '.$i]);
|
||||
}
|
||||
$response = $this->getJson('/parcerias/'.$this->record->id)->assertOk()->assertJsonMissingPath('history')->assertJsonPath('historySummary.limit', 5)->assertJsonCount(5, 'historySummary.entries')->assertJsonPath('historySummary.has_more', true);
|
||||
$entries = $response->json('historySummary.entries');
|
||||
$current = app(PartnershipExchange::class)->find($this->record->id);
|
||||
$this->assertSame([(int) $current->version, (int) $current->version - 1, (int) $current->version - 2, (int) $current->version - 3, (int) $current->version - 4], array_column($entries, 'version'));
|
||||
$this->getJson($response->json('historySummary.href'))->assertOk()->assertJsonCount(10, 'entries');
|
||||
}
|
||||
|
||||
public function test_summary_metadata_and_states_match_the_authorized_full_reader_without_snapshots(): void
|
||||
{
|
||||
$record = $this->edit(['title' => 'SYNTHETIC newer title']);
|
||||
app(PartnershipExchange::class)->transition($this->owner, $record->id, $record->version, 'submit', 'SYNTHETIC reviewed reason');
|
||||
$summary = $this->getJson('/parcerias/'.$this->record->id)->assertOk()->json('historySummary');
|
||||
$full = $this->getJson($this->url())->assertOk()->json('entries');
|
||||
foreach ($summary['entries'] as $index => $entry) {
|
||||
foreach (['version', 'restricted', 'action', 'actor_name', 'occurred_at', 'reason'] as $field) {
|
||||
$this->assertSame($full[$index][$field], $entry[$field]);
|
||||
}
|
||||
$this->assertSame(($full[$index]['previous']['availability'] === 'available' ? $full[$index]['previous']['status'] ?? null : null), $entry['status_before']);
|
||||
$this->assertSame(($full[$index]['after']['availability'] === 'available' ? $full[$index]['after']['status'] ?? null : null), $entry['status_after']);
|
||||
}
|
||||
foreach (['event_type', 'actor_id', 'previous', 'after', 'payload', 'offer', 'client_key', 'operation_hash'] as $private) {
|
||||
$this->assertStringNotContainsString('"'.$private.'"', json_encode($summary));
|
||||
}
|
||||
$this->assertSame('SYNTHETIC reviewed reason', $summary['entries'][0]['reason']);
|
||||
$this->assertFalse($summary['has_more']);
|
||||
}
|
||||
|
||||
public function test_a_new_organization_representative_does_not_receive_old_actor_or_decision_metadata(): void
|
||||
{
|
||||
$a = $this->organization($this->owner);
|
||||
$this->edit(['organization_id' => $a]);
|
||||
$oldActor = User::factory()->create(['name' => 'SYNTHETIC OLD PRIVATE ACTOR']);
|
||||
DB::table('memberships')->insert(['user_id' => $oldActor->id, 'organization_id' => $a, 'role' => 'officer']);
|
||||
$current = app(PartnershipExchange::class)->find($this->record->id);
|
||||
app(PartnershipExchange::class)->save($oldActor, ['version' => $current->version, 'kind' => 'seeking', 'title' => 'SYNTHETIC A draft'], $current->id);
|
||||
$b = $this->organization($this->owner);
|
||||
$this->edit(['organization_id' => $b]);
|
||||
$viewer = User::factory()->create();
|
||||
DB::table('memberships')->insert(['user_id' => $viewer->id, 'organization_id' => $b, 'role' => 'viewer']);
|
||||
$response = $this->actingAs($viewer)->getJson('/parcerias/'.$this->record->id)->assertOk()->assertJsonPath('canEdit', false)
|
||||
->assertJsonPath('historySummary.entries.0.restricted', false)->assertJsonPath('historySummary.entries.0.status_before', null)
|
||||
->assertJsonPath('historySummary.entries.1.restricted', true)->assertJsonPath('historySummary.entries.1.actor_name', null)
|
||||
->assertJsonPath('historySummary.entries.1.occurred_at', null)->assertJsonPath('historySummary.entries.1.action', null)->assertJsonPath('historySummary.entries.1.reason', null);
|
||||
$this->assertStringNotContainsString('OLD PRIVATE ACTOR', $response->getContent());
|
||||
$this->postJson('/parcerias/'.$this->record->id.'/estado', ['version' => 99, 'action' => 'archive', 'reason' => 'SYNTHETIC viewer cannot decide'])->assertForbidden();
|
||||
DB::table('memberships')->where('user_id', $viewer->id)->update(['deleted_at' => now()]);
|
||||
$this->getJson('/parcerias/'.$this->record->id)->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_moderation_keeps_its_existing_historical_access(): void
|
||||
{
|
||||
$a = $this->organization($this->owner);
|
||||
$this->edit(['organization_id' => $a]);
|
||||
$b = $this->organization($this->owner);
|
||||
$this->edit(['organization_id' => $b]);
|
||||
$this->actingAs($this->moderator)->getJson('/parcerias/'.$this->record->id)->assertOk()->assertJsonPath('moderator', true)
|
||||
->assertJsonPath('historySummary.entries.1.restricted', false)->assertJsonPath('historySummary.entries.1.actor_name', $this->owner->name);
|
||||
}
|
||||
|
||||
public function test_public_and_candidate_reads_have_no_historical_summary_even_after_publication(): void
|
||||
{
|
||||
$exchange = app(PartnershipExchange::class);
|
||||
$record = $exchange->transition($this->owner, $this->record->id, $this->record->version, 'submit', 'SYNTHETIC submit');
|
||||
$record = $exchange->transition($this->moderator, $record->id, $record->version, 'publish', 'SYNTHETIC publish');
|
||||
$candidate = User::factory()->create();
|
||||
$exchange->interest($candidate, $record->id, ['proposal' => 'SYNTHETIC candidacy', 'payload' => ['consent' => true]]);
|
||||
$this->actingAs($candidate)->getJson('/parcerias/'.$record->id)->assertOk()->assertJsonPath('historySummary', null)->assertJsonMissingPath('history');
|
||||
$this->getJson($this->url())->assertForbidden();
|
||||
auth()->forgetGuards();
|
||||
$this->getJson('/parcerias/'.$record->id)->assertOk()->assertJsonPath('historySummary', null)->assertJsonMissingPath('history');
|
||||
}
|
||||
|
||||
public function test_legacy_scope_unknown_does_not_become_current_authority_or_an_inferred_action(): void
|
||||
{
|
||||
$event = DB::table('partnership_events')->where('partnership_id', $this->record->id)->first();
|
||||
$payload = json_decode($event->payload, true);
|
||||
unset($payload['payload']['previous'],$payload['payload']['applied'],$payload['payload']['_notification_context']);
|
||||
$payload['payload']['reason'] = 'SYNTHETIC RESERVED REASON';
|
||||
DB::table('partnership_events')->where('id', $event->id)->update(['payload' => json_encode($payload)]);
|
||||
$result = $this->getJson('/parcerias/'.$this->record->id)->assertOk()->assertJsonPath('historySummary.entries.0.restricted', true)
|
||||
->assertJsonPath('historySummary.entries.0.action', null)->assertJsonPath('historySummary.entries.0.status_after', null)->assertJsonPath('historySummary.entries.0.actor_name', null);
|
||||
$this->assertStringNotContainsString('RESERVED REASON', $result->getContent());
|
||||
}
|
||||
|
||||
public function test_no_publication_events_is_an_explicit_empty_summary_with_a_valid_history_link(): void
|
||||
{
|
||||
DB::table('partnership_events')->where('partnership_id', $this->record->id)->update(['event_type' => 'synthetic_unrelated.v1']);
|
||||
$response = $this->getJson('/parcerias/'.$this->record->id)->assertOk()->assertJsonCount(0, 'historySummary.entries')->assertJsonPath('historySummary.has_more', false)
|
||||
->assertJsonPath('historySummary.href', '/parcerias/'.$this->record->id.'/historico');
|
||||
$this->getJson($response->json('historySummary.href'))->assertOk()->assertJsonCount(0, 'entries');
|
||||
}
|
||||
|
||||
public function test_native_and_json_summary_reads_do_not_change_versions_audit_or_notifications(): void
|
||||
{
|
||||
$before = DB::table('portal_partnerships')->where('id', $this->record->id)->first();
|
||||
$events = DB::table('partnership_events')->count();
|
||||
$audits = DB::table('audit_events')->count();
|
||||
$notices = DB::table('partnership_notifications')->count();
|
||||
$this->get('/parcerias/'.$this->record->id)->assertOk()->assertInertia(fn (Assert $p) => $p->component('partnerships/detail')->where('historySummary.limit', 5)->missing('history'));
|
||||
$this->getJson('/parcerias/'.$this->record->id)->assertOk();
|
||||
$this->assertEquals($before, DB::table('portal_partnerships')->where('id', $this->record->id)->first());
|
||||
$this->assertSame($events, DB::table('partnership_events')->count());
|
||||
$this->assertSame($audits, DB::table('audit_events')->count());
|
||||
$this->assertSame($notices, DB::table('partnership_notifications')->count());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Jobs\ScanDocumentForMalware;
|
||||
use App\Models\User;
|
||||
use App\Services\PartnershipExchange;
|
||||
use App\Services\PartnershipRoomUploads;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Facades\Queue;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class PartnershipRoomRecoveryTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private int $roomId;
|
||||
|
||||
private User $owner;
|
||||
|
||||
private User $candidate;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
Http::fake();
|
||||
Mail::fake();
|
||||
Queue::fake();
|
||||
Storage::fake('local');
|
||||
$this->owner = User::factory()->create();
|
||||
$this->candidate = User::factory()->create();
|
||||
$service = app(PartnershipExchange::class);
|
||||
$record = $service->save($this->owner, ['client_key' => (string) Str::uuid(), 'title' => 'SYNTHETIC recovery', 'kind' => 'seeking', 'partnership_type' => 'joint_venture', 'offer' => 'SYNTHETIC offer', 'seeking' => 'SYNTHETIC cooperation', 'payload' => ['consent' => true]]);
|
||||
$record = $service->transition($this->owner, $record->id, $record->version, 'submit', 'SYNTHETIC submission');
|
||||
$moderator = User::factory()->create();
|
||||
config(['portal.managers' => [$moderator->email]]);
|
||||
$service->transition($moderator, $record->id, $record->version, 'publish', 'SYNTHETIC moderation');
|
||||
$interest = $service->interest($this->candidate, $record->id, ['proposal' => 'SYNTHETIC proposal', 'payload' => ['consent' => true]]);
|
||||
$interest = $service->decideInterest($this->owner, $interest->id, $interest->version, 'shortlist', 'SYNTHETIC shortlist');
|
||||
$service->decideInterest($this->owner, $interest->id, $interest->version, 'connect', 'SYNTHETIC connection');
|
||||
$this->roomId = (int) DB::table('partnership_rooms')->where('interest_id', $interest->id)->value('id');
|
||||
$this->actingAs($this->owner)->postJson($this->url('acordo'), ['version' => 1, 'action' => 'record', 'title' => 'SYNTHETIC plan', 'terms' => 'SYNTHETIC terms', 'reason' => 'SYNTHETIC record'])->assertOk();
|
||||
}
|
||||
|
||||
private function url(string $suffix = ''): string
|
||||
{
|
||||
return '/parcerias/salas/'.$this->roomId.($suffix ? '/'.$suffix : '');
|
||||
}
|
||||
|
||||
private function milestone(): array
|
||||
{
|
||||
return ['client_key' => (string) Str::uuid(), 'title' => 'SYNTHETIC deliverable', 'responsible_id' => $this->candidate->id, 'due_date' => null, 'status' => 'pending', 'evidence' => null];
|
||||
}
|
||||
|
||||
private function upload(string $key, bool $shared = false, string $content = 'SYNTHETIC PDF', string $name = 'synthetic-proof.pdf'): array
|
||||
{
|
||||
return ['client_key' => $key, 'shared' => $shared, 'file' => UploadedFile::fake()->createWithContent($name, "%PDF-1.4\n".$content."\n%%EOF")];
|
||||
}
|
||||
|
||||
private function closeRoom(): void
|
||||
{
|
||||
$this->postJson($this->url('acordo'), ['version' => 2, 'action' => 'cancel', 'reason' => 'SYNTHETIC closed while response uncertain'])->assertOk();
|
||||
}
|
||||
|
||||
public function test_creation_replay_has_one_milestone_event_audit_and_notification_set(): void
|
||||
{
|
||||
$input = $this->milestone();
|
||||
$events = DB::table('partnership_events')->count();
|
||||
$audits = DB::table('audit_events')->count();
|
||||
$notifications = DB::table('partnership_notifications')->count();
|
||||
$first = $this->postJson($this->url('marcos'), $input)->assertOk()->assertJsonPath('replayed', false)->json('milestone_id');
|
||||
$this->postJson($this->url('marcos'), $input)->assertOk()->assertJsonPath('replayed', true)->assertJsonPath('milestone_id', $first)->assertJsonPath('version', 1);
|
||||
$this->postJson($this->url('marcos'), [...$input, 'client_key' => strtoupper($input['client_key'])])->assertOk()->assertJsonPath('replayed', true)->assertJsonPath('milestone_id', $first);
|
||||
$this->assertDatabaseCount('partnership_milestones', 1);
|
||||
$this->assertSame($events + 1, DB::table('partnership_events')->count());
|
||||
$this->assertSame($audits + 1, DB::table('audit_events')->count());
|
||||
$this->assertSame($notifications + 2, DB::table('partnership_notifications')->count());
|
||||
$this->getJson($this->url())->assertOk()->assertJsonPath('milestones.0.client_key', $input['client_key']);
|
||||
$this->actingAs($this->candidate)->getJson($this->url())->assertOk()->assertJsonPath('milestones.0.client_key', null);
|
||||
}
|
||||
|
||||
public function test_creation_replay_after_update_and_closure_never_rewrites_the_milestone(): void
|
||||
{
|
||||
$input = $this->milestone();
|
||||
$id = $this->postJson($this->url('marcos'), $input)->assertOk()->json('milestone_id');
|
||||
$this->putJson($this->url('marcos/'.$id), [...$input, 'title' => 'SYNTHETIC revised deliverable', 'version' => 1])->assertOk();
|
||||
$this->closeRoom();
|
||||
$events = DB::table('partnership_events')->count();
|
||||
$this->postJson($this->url('marcos'), $input)->assertOk()->assertJsonPath('milestone_id', $id)->assertJsonPath('version', 2)->assertJsonPath('replayed', true);
|
||||
$this->assertDatabaseHas('partnership_milestones', ['id' => $id, 'title' => 'SYNTHETIC revised deliverable', 'version' => 2]);
|
||||
$this->postJson($this->url('marcos'), [...$input, 'client_key' => (string) Str::uuid()])->assertConflict();
|
||||
$this->assertSame($events, DB::table('partnership_events')->count());
|
||||
}
|
||||
|
||||
public function test_milestone_keys_are_content_bound_scoped_per_actor_and_legacy_requests_still_work(): void
|
||||
{
|
||||
$input = $this->milestone();
|
||||
$this->postJson($this->url('marcos'), $input)->assertOk();
|
||||
$this->postJson($this->url('marcos'), [...$input, 'title' => 'SYNTHETIC different command'])->assertConflict();
|
||||
$this->postJson($this->url('marcos'), [...$input, 'client_key' => 'not-a-uuid'])->assertUnprocessable();
|
||||
$this->actingAs($this->candidate)->postJson($this->url('marcos'), $input)->assertOk()->assertJsonPath('replayed', false);
|
||||
unset($input['client_key']);
|
||||
$this->postJson($this->url('marcos'), $input)->assertOk();
|
||||
$this->assertDatabaseCount('partnership_milestones', 3);
|
||||
}
|
||||
|
||||
public function test_recovery_does_not_restore_revoked_representation_or_allow_a_read_only_actor(): void
|
||||
{
|
||||
$input = $this->milestone();
|
||||
$this->postJson($this->url('marcos'), $input)->assertOk();
|
||||
$record = DB::table('partnership_rooms as r')->join('partnership_interests as i', 'i.id', '=', 'r.interest_id')->where('r.id', $this->roomId)->value('i.partnership_id');
|
||||
$org = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $org, 'name' => 'SYNTHETIC new representation', 'organization_type' => 'private']);
|
||||
DB::table('portal_partnerships')->where('id', $record)->update(['organization_id' => $org]);
|
||||
DB::table('memberships')->insert(['organization_id' => $org, 'user_id' => $this->owner->id, 'role' => 'viewer']);
|
||||
$this->getJson($this->url())->assertOk()->assertJsonPath('canWrite', false);
|
||||
$this->postJson($this->url('marcos'), $input)->assertForbidden();
|
||||
DB::table('memberships')->where('user_id', $this->owner->id)->update(['deleted_at' => now()]);
|
||||
$this->postJson($this->url('marcos'), $input)->assertForbidden();
|
||||
$this->assertDatabaseCount('partnership_milestones', 1);
|
||||
}
|
||||
|
||||
public function test_upload_replay_preserves_original_bytes_one_link_and_one_scan_dispatch(): void
|
||||
{
|
||||
$key = (string) Str::uuid();
|
||||
$events = DB::table('partnership_events')->count();
|
||||
$id = $this->postJson($this->url('documentos'), $this->upload($key))->assertOk()->assertJsonPath('replayed', false)->json('document_id');
|
||||
$this->postJson($this->url('documentos'), $this->upload($key))->assertOk()->assertJsonPath('replayed', true)->assertJsonPath('document_id', $id);
|
||||
$this->postJson($this->url('documentos'), $this->upload(strtoupper($key)))->assertOk()->assertJsonPath('replayed', true)->assertJsonPath('document_id', $id);
|
||||
$this->postJson($this->url('documentos'), $this->upload($key, true))->assertConflict();
|
||||
$this->postJson($this->url('documentos'), $this->upload($key, false, 'SYNTHETIC different bytes'))->assertConflict();
|
||||
$this->postJson($this->url('documentos'), $this->upload($key, false, 'SYNTHETIC PDF', 'renamed.pdf'))->assertConflict();
|
||||
$this->assertDatabaseCount('documents', 1);
|
||||
$this->assertDatabaseCount('partnership_documents', 1);
|
||||
$this->assertCount(1, Storage::disk('local')->allFiles());
|
||||
Queue::assertPushed(ScanDocumentForMalware::class, 1);
|
||||
$this->assertSame($events + 1, DB::table('partnership_events')->count());
|
||||
$document = DB::table('documents')->where('id', $id)->first();
|
||||
$this->assertSame('quarantined', $document->status);
|
||||
$this->assertSame($document->sha256, hash_file('sha256', Storage::disk('local')->path($document->storage_key)));
|
||||
}
|
||||
|
||||
public function test_upload_recovery_after_revocation_and_closure_does_not_reshare_or_requeue(): void
|
||||
{
|
||||
$key = (string) Str::uuid();
|
||||
$id = $this->postJson($this->url('documentos'), $this->upload($key, true))->assertOk()->json('document_id');
|
||||
$link = DB::table('partnership_documents')->where('document_id', $id)->first();
|
||||
$this->postJson($this->url('documentos/'.$link->id.'/partilha'), ['shared' => false])->assertOk();
|
||||
$this->closeRoom();
|
||||
$events = DB::table('partnership_events')->count();
|
||||
$this->postJson($this->url('documentos'), $this->upload($key, true))->assertOk()->assertJsonPath('replayed', true)->assertJsonPath('document_id', $id);
|
||||
$this->assertDatabaseHas('partnership_documents', ['id' => $link->id, 'shared' => false]);
|
||||
Queue::assertPushed(ScanDocumentForMalware::class, 1);
|
||||
$this->assertSame($events, DB::table('partnership_events')->count());
|
||||
$this->postJson($this->url('documentos'), $this->upload((string) Str::uuid()))->assertConflict();
|
||||
$this->actingAs($this->candidate)->getJson($this->url())->assertOk()->assertJsonCount(0, 'documents');
|
||||
$this->postJson($this->url('documentos'), $this->upload($key, true))->assertConflict();
|
||||
}
|
||||
|
||||
public function test_message_recovery_after_closure_is_read_only_and_keys_are_not_disclosed_to_the_other_party(): void
|
||||
{
|
||||
$input = ['client_key' => (string) Str::uuid(), 'body' => 'SYNTHETIC uncertain message'];
|
||||
$this->postJson($this->url('mensagens'), $input)->assertOk();
|
||||
$this->getJson($this->url())->assertOk()->assertJsonPath('messages.0.client_key', $input['client_key']);
|
||||
$this->actingAs($this->candidate)->getJson($this->url())->assertOk()->assertJsonPath('messages.0.client_key', null);
|
||||
$this->actingAs($this->owner);
|
||||
$this->closeRoom();
|
||||
$events = DB::table('partnership_events')->count();
|
||||
$this->postJson($this->url('mensagens'), $input)->assertOk();
|
||||
$this->postJson($this->url('mensagens'), [...$input, 'body' => 'SYNTHETIC different content'])->assertConflict();
|
||||
$this->postJson($this->url('mensagens'), [...$input, 'client_key' => (string) Str::uuid()])->assertConflict();
|
||||
$this->assertDatabaseCount('partnership_messages', 1);
|
||||
$this->assertSame($events, DB::table('partnership_events')->count());
|
||||
}
|
||||
|
||||
public function test_stale_agreement_and_milestone_updates_preserve_the_current_state_and_evidence(): void
|
||||
{
|
||||
$input = $this->milestone();
|
||||
$id = $this->postJson($this->url('marcos'), $input)->assertOk()->json('milestone_id');
|
||||
$this->putJson($this->url('marcos/'.$id), [...$input, 'version' => 1, 'status' => 'completed', 'evidence' => 'SYNTHETIC frozen result'])->assertOk();
|
||||
$this->putJson($this->url('marcos/'.$id), [...$input, 'version' => 1])->assertConflict();
|
||||
$this->postJson($this->url('acordo'), ['version' => 1, 'action' => 'record', 'title' => 'SYNTHETIC stale', 'terms' => 'SYNTHETIC stale terms', 'reason' => 'SYNTHETIC stale attempt'])->assertConflict();
|
||||
$this->assertDatabaseHas('partnership_milestones', ['id' => $id, 'version' => 2, 'status' => 'completed', 'evidence' => 'SYNTHETIC frozen result']);
|
||||
$this->assertDatabaseHas('partnership_rooms', ['id' => $this->roomId, 'version' => 2, 'status' => 'agreement_recorded']);
|
||||
}
|
||||
|
||||
public function test_failed_document_event_rolls_back_the_new_file_without_removing_an_existing_original(): void
|
||||
{
|
||||
$id = $this->postJson($this->url('documentos'), $this->upload((string) Str::uuid()))->assertOk()->json('document_id');
|
||||
$original = DB::table('documents')->where('id', $id)->first();
|
||||
$exchange = \Mockery::mock(PartnershipExchange::class)->makePartial();
|
||||
$exchange->shouldReceive('event')->once()->andThrow(new \RuntimeException('SYNTHETIC event failure'));
|
||||
$this->app->instance(PartnershipExchange::class, $exchange);
|
||||
$input = $this->upload((string) Str::uuid(), false, 'SYNTHETIC failed second upload');
|
||||
try {
|
||||
app(PartnershipRoomUploads::class)->save($this->owner, $this->roomId, $input['file'], false, $input['client_key']);
|
||||
$this->fail('The synthetic event failure should abort the new upload.');
|
||||
} catch (\RuntimeException $error) {
|
||||
$this->assertSame('SYNTHETIC event failure', $error->getMessage());
|
||||
}
|
||||
$this->assertDatabaseCount('documents', 1);
|
||||
$this->assertDatabaseCount('partnership_documents', 1);
|
||||
$this->assertCount(1, Storage::disk('local')->allFiles());
|
||||
$this->assertSame($original->sha256, hash_file('sha256', Storage::disk('local')->path($original->storage_key)));
|
||||
Queue::assertPushed(ScanDocumentForMalware::class, 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\ProactiveSupply;
|
||||
use Illuminate\Foundation\Testing\DatabaseTransactions;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Tests\Support\ProactiveInvestmentFixture as F;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class ProactiveSupplyReviewTest extends TestCase
|
||||
{
|
||||
use DatabaseTransactions;
|
||||
|
||||
private User $actor;
|
||||
|
||||
private string $source;
|
||||
|
||||
private string $territory;
|
||||
|
||||
private string $base = '/minhas-oportunidades/oferta-interna/revisao';
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
F::guard();
|
||||
$this->withoutVite();
|
||||
config(['portal.profile_access_enabled' => true, 'portal.managers' => [], 'suitecrm.enabled' => false, 'investmoz_ai.enabled' => false]);
|
||||
$this->actor = F::operator();
|
||||
$this->login($this->actor);
|
||||
$parent = null;
|
||||
foreach (['country', 'province', 'district'] as $level) {
|
||||
$id = (string) Str::uuid();
|
||||
DB::table('geo_locations')->insert(['id' => $id, 'name' => 'SYNTHETIC review '.$level, 'code' => $id, 'location_type' => $level,
|
||||
'parent_id' => $parent, 'data_classification' => 'public', 'source_system' => 'cartografia-workbook',
|
||||
'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:'.$id]);
|
||||
$parent = $id;
|
||||
}
|
||||
$this->territory = $parent;
|
||||
$this->source = hash('sha256', 'SYNTHETIC-SUPPLY-REVIEW-20261102');
|
||||
DB::table('proactive_supply_sources')->insert(['sha256' => $this->source, 'name' => 'SYNTHETIC review source.xlsx', 'period' => 'Synthetic historical data',
|
||||
'limitations' => 'Synthetic observations, not actual establishments', 'receipt' => json_encode(['private_contact' => 'SYNTHETIC PRIVATE CONTACT', 'nuit' => 'SYNTHETIC PRIVATE IDENTIFIER']), 'imported_at' => now()]);
|
||||
$base = ['source_hash' => $this->source, 'sheet' => 'SYNTHETIC QA', 'entity_key' => hash('sha256', 'SYNTHETIC ENTITY'),
|
||||
'name' => 'SYNTHETIC 100% Algodão', 'province' => 'Zambézia', 'district' => 'Gurué', 'cae' => '01610', 'activity' => 'Cultivo de algodão', 'sector' => 'Synthetic agriculture',
|
||||
'source_date' => 'Serial Excel original: 45000', 'duplicate_of' => null, 'identity_conflict' => false, 'territory_id' => $this->territory, 'territory_resolution' => 'exact_normalized_province_district'];
|
||||
foreach ([
|
||||
2 => [], 3 => ['name' => 'SYNTHETIC 1000', 'activity' => '', 'territory_id' => null, 'territory_resolution' => 'unresolved'],
|
||||
4 => ['name' => 'Denominação não indicada', 'territory_id' => null, 'territory_resolution' => 'ambiguous'],
|
||||
5 => ['name' => 'SYNTHETIC other denomination', 'identity_conflict' => true, 'territory_id' => '10000000-0000-4000-8000-000000000001'],
|
||||
6 => ['duplicate_of' => $this->id(2)], 7 => ['name' => 'SYNTHETIC_UNDER_SCORE', 'territory_id' => null, 'territory_resolution' => 'unresolved'],
|
||||
] as $number => $changes) {
|
||||
DB::table('proactive_supply_observations')->insert([...$base, 'id' => $this->id($number), 'row_number' => $number,
|
||||
'fingerprint' => hash('sha256', 'SYNTHETIC-FINGERPRINT-'.($number === 6 ? 2 : $number)), ...$changes]);
|
||||
}
|
||||
}
|
||||
|
||||
private function login(User $actor): void
|
||||
{
|
||||
$this->actingAs($actor)->withSession(['portal.mfa_actor' => $actor->id, 'portal.mfa_at' => time(), 'portal.access_revision' => (int) $actor->portal_access_revision]);
|
||||
}
|
||||
|
||||
private function id(int $row): string
|
||||
{
|
||||
return hash('sha256', $this->source.'|SYNTHETIC QA|'.$row);
|
||||
}
|
||||
|
||||
private function url(array $filters = []): string
|
||||
{
|
||||
return $this->base.'?'.http_build_query(['source_hash' => $this->source, ...$filters]);
|
||||
}
|
||||
|
||||
public function test_unmapped_and_ambiguous_rows_are_recoverable_without_mutation_or_a_guessed_territory(): void
|
||||
{
|
||||
$before = DB::table('proactive_supply_observations')->where('source_hash', $this->source)->orderBy('id')->get()->toJson();
|
||||
$response = $this->getJson($this->url())->assertOk()->assertHeader('Cache-Control', 'no-store, private')
|
||||
->assertJsonPath('total', 3)->assertJsonPath('coverage.observations', 6)->assertJsonPath('coverage.distinct_observations', 5)
|
||||
->assertJsonPath('coverage.repeated', 1)->assertJsonPath('coverage.unmapped', 3)->assertJsonPath('coverage.ambiguous', 1)
|
||||
->assertJsonPath('coverage.territory_unavailable', 1)->assertJsonPath('coverage.identity_conflict', 1)
|
||||
->assertJsonPath('coverage.unclassified', 1)->assertJsonPath('coverage.unnamed', 1);
|
||||
foreach ($response->json('rows') as $row) {
|
||||
$this->assertNull($row['territory_id']);
|
||||
$this->assertNull($row['canonical_territory']);
|
||||
}
|
||||
$this->getJson($this->url(['status' => 'ambiguous']))->assertOk()->assertJsonPath('total', 1)->assertJsonPath('rows.0.id', $this->id(4));
|
||||
$this->getJson($this->url(['status' => 'all', 'observation_id' => $this->id(4)]))->assertOk()
|
||||
->assertJsonPath('rows.0.sheet', 'SYNTHETIC QA')->assertJsonPath('rows.0.row_number', 4)->assertJsonPath('rows.0.source_hash', $this->source)
|
||||
->assertJsonPath('rows.0.source_date', 'Serial Excel original: 45000');
|
||||
$this->assertSame($before, DB::table('proactive_supply_observations')->where('source_hash', $this->source)->orderBy('id')->get()->toJson());
|
||||
}
|
||||
|
||||
public function test_private_receipts_identity_hashes_contacts_and_private_territories_are_not_projected(): void
|
||||
{
|
||||
$response = $this->getJson($this->url(['status' => 'all']))->assertOk()->assertDontSee('SYNTHETIC PRIVATE CONTACT')->assertDontSee('SYNTHETIC PRIVATE IDENTIFIER');
|
||||
foreach ($response->json('rows') as $row) {
|
||||
foreach (['entity_key', 'fingerprint', 'receipt', 'contact', 'nuit', 'geom'] as $key) {
|
||||
$this->assertArrayNotHasKey($key, $row);
|
||||
}
|
||||
}
|
||||
foreach ($response->json('sources') as $source) {
|
||||
$this->assertArrayNotHasKey('receipt', $source);
|
||||
}
|
||||
$this->getJson($this->url(['status' => 'territory_unavailable']))->assertOk()->assertJsonCount(1, 'rows')->assertJsonPath('rows.0.canonical_territory', null);
|
||||
$this->getJson('/minhas-oportunidades/oferta-interna?territory_id='.$this->territory)->assertOk()->assertJsonMissingPath('rows.0.entity_key');
|
||||
}
|
||||
|
||||
public function test_repeated_sightings_identity_conflicts_and_activity_gaps_are_distinct_and_not_consolidated(): void
|
||||
{
|
||||
$this->getJson($this->url(['status' => 'repeated']))->assertOk()->assertJsonPath('total', 1)->assertJsonPath('rows.0.duplicate_of', $this->id(2));
|
||||
$this->getJson($this->url(['status' => 'identity_conflict']))->assertOk()->assertJsonPath('rows.0.id', $this->id(5));
|
||||
$this->getJson($this->url(['status' => 'unclassified']))->assertOk()->assertJsonPath('rows.0.id', $this->id(3));
|
||||
$this->getJson($this->url(['status' => 'unnamed']))->assertOk()->assertJsonPath('rows.0.id', $this->id(4));
|
||||
$this->assertSame(6, DB::table('proactive_supply_observations')->where('source_hash', $this->source)->count());
|
||||
}
|
||||
|
||||
public function test_text_search_is_accent_insensitive_and_wildcards_are_literal(): void
|
||||
{
|
||||
foreach (['algodao', 'ALGODÃO', '100%'] as $q) {
|
||||
$response = $this->getJson($this->url(['status' => 'all', 'q' => $q]))->assertOk();
|
||||
$this->assertGreaterThan(0, $response->json('total'));
|
||||
$this->assertNotContains($this->id(3), array_column($response->json('rows'), 'id'));
|
||||
}
|
||||
$this->getJson($this->url(['status' => 'all', 'q' => 'UNDER_']))->assertOk()->assertJsonPath('total', 1)->assertJsonPath('rows.0.id', $this->id(7));
|
||||
$this->getJson($this->url(['status' => 'all', 'q' => 'NO-SYNTHETIC-MATCH']))->assertOk()->assertJsonPath('total', 0)->assertJsonPath('status', 'Informação insuficiente nesta base e nestes filtros.');
|
||||
}
|
||||
|
||||
public function test_pagination_and_direct_reference_recover_the_same_source_line(): void
|
||||
{
|
||||
$base = (array) DB::table('proactive_supply_observations')->where('id', $this->id(2))->first();
|
||||
for ($row = 100; $row < 126; $row++) {
|
||||
DB::table('proactive_supply_observations')->insert([...$base, 'id' => $this->id($row), 'row_number' => $row,
|
||||
'name' => 'SYNTHETIC PAGE '.$row, 'fingerprint' => hash('sha256', 'SYNTHETIC-PAGE-'.$row)]);
|
||||
}
|
||||
$this->getJson($this->url(['status' => 'all', 'q' => 'SYNTHETIC PAGE']))->assertOk()->assertJsonPath('total', 26)->assertJsonCount(25, 'rows')->assertJsonPath('rows.0.row_number', 100);
|
||||
$this->getJson($this->url(['status' => 'all', 'q' => 'SYNTHETIC PAGE', 'page' => 2]))->assertOk()->assertJsonCount(1, 'rows')->assertJsonPath('rows.0.row_number', 125);
|
||||
$this->getJson($this->url(['status' => 'all', 'observation_id' => $this->id(125), 'page' => 999]))->assertOk()->assertJsonPath('filters.page', 1)->assertJsonPath('rows.0.row_number', 125);
|
||||
}
|
||||
|
||||
public function test_unassigned_users_cannot_enumerate_or_validate_private_inventory_and_invalid_filters_are_explicit(): void
|
||||
{
|
||||
$this->getJson($this->url(['status' => 'not-a-state']))->assertUnprocessable();
|
||||
$this->getJson($this->url(['source_hash' => str_repeat('f', 64)]))->assertUnprocessable()->assertJsonValidationErrors('source_hash');
|
||||
$this->login(User::factory()->create());
|
||||
$this->getJson($this->url())->assertForbidden();
|
||||
$this->getJson($this->base.'?record_id=999999999&source_hash=invalid')->assertForbidden();
|
||||
$this->getJson('/minhas-oportunidades/oferta-interna?record_id=999999999')->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_private_page_is_wired_and_preserves_applied_filters(): void
|
||||
{
|
||||
$this->get($this->url(['status' => 'ambiguous']))->assertOk()->assertHeader('Cache-Control', 'no-store, private')
|
||||
->assertInertia(fn ($page) => $page->component('management/proactive-supply-review')->where('filters.status', 'ambiguous')->where('rows.0.id', $this->id(4)));
|
||||
}
|
||||
|
||||
public function test_existing_comparison_keeps_server_side_lineage_and_rejects_repetitions(): void
|
||||
{
|
||||
$service = app(ProactiveSupply::class);
|
||||
$evidence = $service->evidence($this->actor, $this->id(2), null);
|
||||
$this->assertSame('internal', $evidence['access']);
|
||||
$this->assertStringContainsString($this->source, $evidence['source']);
|
||||
$this->assertSame('SYNTHETIC QA!linha 2', $evidence['locator']);
|
||||
$comparison = ['observation_id' => $this->id(2), 'relationship' => 'uncertain', 'rationale' => 'SYNTHETIC comparison', 'limitations' => 'SYNTHETIC unknown current operation'];
|
||||
$this->assertSame([$comparison], $service->comparisons($this->actor, [$comparison], null));
|
||||
$this->expectException(ValidationException::class);
|
||||
$service->comparisons($this->actor, [[...$comparison, 'observation_id' => $this->id(6)]], null);
|
||||
}
|
||||
|
||||
public function test_database_policy_requires_actor_context_for_sources_and_observations(): void
|
||||
{
|
||||
$role = 'supply_review_qa_'.bin2hex(random_bytes(6));
|
||||
DB::statement('CREATE ROLE '.$role.' NOLOGIN');
|
||||
DB::statement('GRANT USAGE ON SCHEMA public TO '.$role);
|
||||
DB::statement('GRANT SELECT ON proactive_supply_sources,proactive_supply_observations TO '.$role);
|
||||
DB::select("select set_config('app.actor_user_id','',true),set_config('app.proactive_supply_read','',true)");
|
||||
try {
|
||||
DB::statement('SET LOCAL ROLE '.$role);
|
||||
$this->assertSame(0, DB::table('proactive_supply_observations')->count());
|
||||
$this->assertSame(0, DB::table('proactive_supply_sources')->count());
|
||||
DB::select("select set_config('app.actor_user_id',?,true),set_config('app.proactive_supply_read','internal',true)", [(string) $this->actor->id]);
|
||||
$this->assertSame(6, DB::table('proactive_supply_observations')->where('source_hash', $this->source)->count());
|
||||
$this->assertSame(1, DB::table('proactive_supply_sources')->where('sha256', $this->source)->count());
|
||||
} finally {
|
||||
DB::statement('RESET ROLE');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\InterestRequest;
|
||||
use App\Models\User;
|
||||
use App\Services\ProductExperiments;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class ProductExperimentsTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $manager;
|
||||
|
||||
private User $other;
|
||||
|
||||
private string $url = '/management/product-experiments';
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
$this->travelTo(CarbonImmutable::parse('2026-11-03 12:00:00.123456', 'UTC'));
|
||||
Http::preventStrayRequests();
|
||||
$this->manager = User::factory()->create();
|
||||
$this->other = User::factory()->create();
|
||||
config(['portal.managers' => [$this->manager->email], 'investmoz_ai.enabled' => false, 'suitecrm.enabled' => false, 'portal.notifications_enabled' => false]);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$this->travelBack();
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
private function body(array $values = [], int $version = 0, array $extra = []): array
|
||||
{
|
||||
return [...['version' => $version, 'operation_key' => (string) Str::uuid(), 'reason' => $version > 0 ? 'SYNTHETIC revision, no real experiment' : '', 'values' => ['state' => 'draft', 'title' => 'PRIVATE SYNTHETIC experiment', ...$values], 'indicator_definition_version' => config('product-metrics.version')], ...$extra];
|
||||
}
|
||||
|
||||
private function plan(string $state = 'planned'): array
|
||||
{
|
||||
$values = array_fill_keys(['reference', 'hypothesis', 'segment', 'control', 'variant', 'assignment', 'criterion', 'transparency', 'consent', 'security', 'equality'], 'PRIVATE SYNTHETIC description; not production evidence');
|
||||
|
||||
return [...$values, 'title' => 'PRIVATE SYNTHETIC plan', 'state' => $state, 'change_kind' => 'form', 'indicator_id' => 'manual', 'indicator_title' => 'SYNTHETIC proportion', 'indicator_definition' => 'SYNTHETIC numerator / denominator, only observed sample', 'indicator_unit' => '%', 'preserves_requirements' => 'yes', 'period_from' => '2026-11-02', 'period_to' => '2026-11-04'];
|
||||
}
|
||||
|
||||
private function observation(): array
|
||||
{
|
||||
return ['observed_from' => '2026-11-02', 'observed_to' => '2026-11-02', 'control_result' => 'SYNTHETIC 0; not an actual user sample', 'variant_result' => 'SYNTHETIC unknown; no inferred zero', 'result' => 'SYNTHETIC inconclusive comparison', 'limitations' => 'SYNTHETIC fixture, no real allocation or causal claim', 'evidence' => 'SYNTHETIC isolated QA receipt', 'decision' => 'inconclusive', 'decision_reason' => 'No real experiment or customer acceptance is claimed.'];
|
||||
}
|
||||
|
||||
private function create(array $body): string
|
||||
{
|
||||
return $this->actingAs($this->manager)->postJson($this->url, $body)->assertCreated()->json('id');
|
||||
}
|
||||
|
||||
public function test_existing_manager_authority_private_transport_and_read_only_views_are_preserved(): void
|
||||
{
|
||||
$this->getJson($this->url)->assertUnauthorized();
|
||||
$this->actingAs($this->other)->getJson($this->url)->assertForbidden();
|
||||
$this->postJson($this->url, $this->body())->assertForbidden();
|
||||
$this->actingAs($this->manager)->getJson($this->url)->assertOk()->assertHeader('Cache-Control', 'no-store, private')->assertJsonPath('total', 0);
|
||||
$this->get($this->url)->assertOk()->assertInertia(fn ($p) => $p->component('management/experiments/index'));
|
||||
$this->get($this->url.'/new')->assertOk()->assertInertia(fn ($p) => $p->component('management/experiments/edit'));
|
||||
$this->assertDatabaseCount('product_experiments', 0);
|
||||
$this->assertDatabaseCount('product_experiment_revisions', 0);
|
||||
$this->assertSame(0, DB::table('audit_events')->where('source_system', 'product-experiments')->count());
|
||||
config(['portal.managers' => []]);
|
||||
$this->getJson($this->url)->assertForbidden();
|
||||
$this->manager->forceFill(['email_verified_at' => null])->save();
|
||||
config(['portal.managers' => [$this->manager->email]]);
|
||||
$this->getJson($this->url)->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_incomplete_drafts_are_encrypted_replayable_and_version_conflicts_never_overwrite_history(): void
|
||||
{
|
||||
$first = $this->body(['hypothesis' => 'PRIVATE SYNTHETIC original']);
|
||||
$id = $this->create($first);
|
||||
$this->postJson($this->url, $first)->assertCreated()->assertJsonPath('replayed', true)->assertJsonPath('id', $id);
|
||||
$this->postJson($this->url, [...$first, 'values' => [...$first['values'], 'title' => 'Changed']])->assertConflict();
|
||||
$this->assertStringNotContainsString('PRIVATE SYNTHETIC', DB::table('product_experiment_revisions')->value('snapshot'));
|
||||
$this->assertStringNotContainsString('PRIVATE SYNTHETIC', DB::table('audit_events')->where('source_system', 'product-experiments')->get()->toJson());
|
||||
$changed = $this->body(['hypothesis' => 'PRIVATE SYNTHETIC changed'], 1);
|
||||
$this->postJson($this->url.'/'.$id.'/revisions', $changed)->assertOk()->assertJsonPath('version', 2);
|
||||
$this->postJson($this->url.'/'.$id.'/revisions', $changed)->assertOk()->assertJsonPath('replayed', true);
|
||||
$this->postJson($this->url.'/'.$id.'/revisions', $this->body(['title' => 'Stale edit'], 1))->assertConflict();
|
||||
$this->postJson($this->url, $first)->assertCreated()->assertJsonPath('version', 1);
|
||||
$this->getJson($this->url.'/'.$id)->assertOk()->assertJsonPath('values.hypothesis', 'PRIVATE SYNTHETIC changed')->assertJsonPath('currentVersion', 2);
|
||||
$this->getJson($this->url.'/'.$id.'?revision=1')->assertOk()->assertJsonPath('historical', true)->assertJsonPath('values.hypothesis', 'PRIVATE SYNTHETIC original');
|
||||
$this->postJson($this->url.'/'.$id.'/revisions', $this->body($changed['values'], 2))->assertOk()->assertJsonPath('unchanged', true);
|
||||
$this->postJson($this->url, $this->body(['server_snapshot' => 'FORGED']))->assertUnprocessable();
|
||||
$this->assertDatabaseCount('product_experiment_revisions', 2);
|
||||
$this->assertDatabaseCount('desk_cases', 0);
|
||||
DB::statement('SET CONSTRAINTS product_experiment_current_revision IMMEDIATE');
|
||||
}
|
||||
|
||||
public function test_registered_plans_require_actual_definition_and_all_four_protections_without_backdating_authorship(): void
|
||||
{
|
||||
$this->actingAs($this->manager);
|
||||
foreach (['transparency', 'consent', 'security', 'equality', 'preserves_requirements'] as $key) {
|
||||
$this->postJson($this->url, $this->body([...$this->plan(), $key => '']))->assertUnprocessable()->assertJsonValidationErrors('values.'.$key);
|
||||
}
|
||||
$this->postJson($this->url, $this->body(['state' => 'planned']))->assertUnprocessable();
|
||||
$this->assertDatabaseCount('product_experiments', 0);
|
||||
$id = $this->create($this->body($this->plan(), extra: ['actor' => ['id' => $this->other->id], 'registration' => ['first_at' => '2000-01-01']]));
|
||||
$r = $this->getJson($this->url.'/'.$id)->assertOk()->json('document');
|
||||
$this->assertSame('2026-11-03T12:00:00.123456+00:00', $r['registration']['first_at']);
|
||||
$this->assertSame($this->manager->id, $r['actor']['id']);
|
||||
$this->assertSame(0, $r['registration']['amendments']);
|
||||
$this->assertSame(config('product-experiments.fields'), $r['vocabulary']['fields']);
|
||||
$this->assertSame('manual', $r['indicator']['id']);
|
||||
config(['product-experiments.version' => 'SYNTHETIC new registry edition', 'product-experiments.fields.title' => 'SYNTHETIC changed field label']);
|
||||
$this->postJson($this->url.'/'.$id.'/revisions', $this->body([...$this->plan(), 'title' => 'SYNTHETIC title only correction'], 1))->assertOk();
|
||||
$this->assertSame($r['indicator'], $this->getJson($this->url.'/'.$id)->json('document.indicator'));
|
||||
$this->getJson($this->url.'/'.$id.'?revision=1')->assertOk()->assertJsonPath('labels.title', $r['vocabulary']['fields']['title'])->assertJsonPath('document.definition_version', $r['definition_version']);
|
||||
}
|
||||
|
||||
public function test_observation_decision_and_optional_report_preserve_unknowns_and_do_not_claim_variant_measurement(): void
|
||||
{
|
||||
$values = [...$this->plan('reviewed'), ...$this->observation()];
|
||||
$id = $this->create($this->body($values, extra: ['attach_report' => true, 'operational_report' => ['FORGED' => 99]]));
|
||||
$r = $this->getJson($this->url.'/'.$id)->assertOk()->json('document');
|
||||
$this->assertSame('operational_cohort_not_experiment_arm', $r['report_scope']);
|
||||
$this->assertTrue($r['report_matches_observation']);
|
||||
$this->assertNull(collect($r['operational_report']['metrics'])->firstWhere('id', 'submission_rate')['value']);
|
||||
$this->assertSame(0, collect($r['operational_report']['metrics'])->firstWhere('id', 'requests_created')['value']);
|
||||
$this->assertSame('inconclusive', $r['values']['decision']);
|
||||
$this->assertArrayNotHasKey('FORGED', $r['operational_report']);
|
||||
$this->travelTo(CarbonImmutable::parse('2026-11-04 12:00:00', 'UTC'));
|
||||
$values['observed_to'] = '2026-11-03';
|
||||
$this->postJson($this->url.'/'.$id.'/revisions', $this->body($values, 1))->assertOk();
|
||||
$new = $this->getJson($this->url.'/'.$id)->assertOk()->json('document');
|
||||
$this->assertSame($r['operational_report'], $new['operational_report']);
|
||||
$this->assertFalse($new['report_matches_observation']);
|
||||
$this->postJson($this->url.'/'.$id.'/revisions', $this->body($values, 2, ['remove_report' => true]))->assertOk();
|
||||
$this->getJson($this->url.'/'.$id)->assertOk()->assertJsonPath('document.operational_report', null);
|
||||
$this->getJson($this->url.'/'.$id.'?revision=1')->assertOk()->assertJsonPath('document.operational_report.filters.to', '2026-11-02');
|
||||
$this->assertDatabaseCount('desk_cases', 0);
|
||||
$this->assertDatabaseCount('desk_requests', 0);
|
||||
$this->assertSame(0, InterestRequest::query()->count());
|
||||
}
|
||||
|
||||
public function test_amending_a_registered_plan_keeps_prior_observations_bound_until_explicit_review(): void
|
||||
{
|
||||
$values = [...$this->plan('reviewed'), ...$this->observation()];
|
||||
$id = $this->create($this->body($values));
|
||||
$original = $this->getJson($this->url.'/'.$id)->json('document');
|
||||
$values = [...$values, 'state' => 'planned', 'hypothesis' => 'SYNTHETIC changed hypothesis'];
|
||||
$this->postJson($this->url.'/'.$id.'/revisions', $this->body($values, 1))->assertUnprocessable()->assertJsonValidationErrors('confirm_plan_change');
|
||||
$this->postJson($this->url.'/'.$id.'/revisions', $this->body($values, 1, ['confirm_plan_change' => true]))->assertOk();
|
||||
$new = $this->getJson($this->url.'/'.$id)->json('document');
|
||||
$this->assertSame(1, $new['registration']['amendments']);
|
||||
$this->assertTrue($new['registration']['amended_after_observation']);
|
||||
$this->assertSame($original['plan_sha256'], $new['observation_plan_sha256']);
|
||||
$this->assertNotSame($new['plan_sha256'], $new['observation_plan_sha256']);
|
||||
$values['state'] = 'reviewed';
|
||||
$this->postJson($this->url.'/'.$id.'/revisions', $this->body($values, 2))->assertUnprocessable()->assertJsonValidationErrors('values.result');
|
||||
$this->postJson($this->url.'/'.$id.'/revisions', $this->body($values, 2, ['confirm_observation_plan' => true]))->assertOk();
|
||||
$last = $this->getJson($this->url.'/'.$id)->json('document');
|
||||
$this->assertSame($last['plan_sha256'], $last['observation_plan_sha256']);
|
||||
$this->assertTrue($last['observation_reaffirmed_for_plan']);
|
||||
$this->assertSame($original['registration']['first_at'], $last['registration']['first_at']);
|
||||
$this->getJson($this->url.'/'.$id.'?revision=1')->assertOk()->assertJsonPath('values.hypothesis', $original['values']['hypothesis']);
|
||||
}
|
||||
|
||||
public function test_catalogue_definitions_remain_frozen_and_refresh_requires_explicit_plan_revision(): void
|
||||
{
|
||||
$body = $this->body([...$this->plan(), 'indicator_id' => 'submission_rate']);
|
||||
$id = $this->create($body);
|
||||
$old = $this->getJson($this->url.'/'.$id)->json('document.indicator');
|
||||
config(['product-metrics.version' => 'SYNTHETIC new definition edition']);
|
||||
$values = [...$body['values'], 'title' => 'SYNTHETIC title correction'];
|
||||
$this->postJson($this->url.'/'.$id.'/revisions', $this->body($values, 1))->assertOk();
|
||||
$this->assertSame($old, $this->getJson($this->url.'/'.$id)->json('document.indicator'));
|
||||
$this->postJson($this->url, $body)->assertCreated()->assertJsonPath('version', 1)->assertJsonPath('replayed', true);
|
||||
$this->postJson($this->url.'/'.$id.'/revisions', $this->body($values, 2, ['refresh_indicator' => true]))->assertUnprocessable()->assertJsonValidationErrors('confirm_plan_change');
|
||||
$this->postJson($this->url.'/'.$id.'/revisions', $this->body($values, 2, ['refresh_indicator' => true, 'confirm_plan_change' => true]))->assertOk();
|
||||
$this->getJson($this->url.'/'.$id)->assertOk()->assertJsonPath('document.indicator.definition_version', 'SYNTHETIC new definition edition');
|
||||
$this->getJson($this->url.'/'.$id.'?revision=1')->assertOk()->assertJsonPath('document.indicator.definition_version', $old['definition_version']);
|
||||
}
|
||||
|
||||
public function test_amended_period_can_preserve_old_observation_dates_without_reclassifying_them_as_new_results(): void
|
||||
{
|
||||
$values = [...$this->plan('reviewed'), ...$this->observation()];
|
||||
$id = $this->create($this->body($values));
|
||||
$old = $this->getJson($this->url.'/'.$id)->json('document');
|
||||
$values = [...$values, 'state' => 'planned', 'period_from' => '2026-11-03', 'period_to' => '2026-11-05'];
|
||||
$this->postJson($this->url.'/'.$id.'/revisions', $this->body($values, 1, ['confirm_plan_change' => true]))->assertOk();
|
||||
$current = $this->getJson($this->url.'/'.$id)->json('document');
|
||||
$this->assertSame('2026-11-02', $current['values']['observed_from']);
|
||||
$this->assertSame($old['plan_sha256'], $current['observation_plan_sha256']);
|
||||
$this->assertNotSame($current['plan_sha256'], $current['observation_plan_sha256']);
|
||||
$this->postJson($this->url.'/'.$id.'/revisions', $this->body([...$values, 'state' => 'reviewed'], 2, ['confirm_observation_plan' => true]))->assertUnprocessable()->assertJsonValidationErrors('values.observed_from');
|
||||
$this->getJson($this->url.'/'.$id.'?revision=1')->assertOk()->assertJsonPath('values.period_from', '2026-11-02')->assertJsonPath('values.observed_from', '2026-11-02');
|
||||
$this->assertDatabaseCount('product_experiment_revisions', 2);
|
||||
}
|
||||
|
||||
public function test_invalid_dates_unknown_indicators_and_incomplete_results_cannot_be_recorded_as_complete(): void
|
||||
{
|
||||
$this->actingAs($this->manager);
|
||||
foreach ([['period_from' => '2026-11-05'], ['indicator_id' => 'forged'], ['indicator_definition' => ''], ['state' => 'observing', 'observed_from' => '2026-11-04'], ['state' => 'reviewed'], ['observed_from' => '2026-11-01']] as $bad) {
|
||||
$this->postJson($this->url, $this->body([...$this->plan(), ...$bad]))->assertUnprocessable();
|
||||
}
|
||||
$this->postJson($this->url, $this->body($this->plan(), extra: ['attach_report' => true]))->assertUnprocessable();
|
||||
$this->postJson($this->url, $this->body([...$this->plan('reviewed'), ...$this->observation(), 'report_service' => 'invented'], extra: ['attach_report' => true]))->assertUnprocessable();
|
||||
$this->assertDatabaseCount('product_experiments', 0);
|
||||
$this->assertDatabaseCount('product_experiment_revisions', 0);
|
||||
}
|
||||
|
||||
public function test_database_enforces_append_only_history_immutable_origin_and_current_revision_integrity(): void
|
||||
{
|
||||
$id = $this->create($this->body());
|
||||
DB::statement('SET CONSTRAINTS product_experiment_current_revision IMMEDIATE');
|
||||
foreach ([fn () => DB::table('product_experiment_revisions')->where('experiment_id', $id)->update(['snapshot' => 'FORGED']), fn () => DB::table('product_experiments')->where('id', $id)->delete(), fn () => DB::statement('TRUNCATE product_experiment_revisions CASCADE'), fn () => DB::table('product_experiments')->where('id', $id)->update(['version' => 9]), fn () => DB::table('product_experiments')->where('id', $id)->update(['version' => 2, 'created_by' => $this->other->id]), function () use ($id) {
|
||||
DB::table('product_experiments')->where('id', $id)->update(['version' => 2]);
|
||||
DB::statement('SET CONSTRAINTS product_experiment_current_revision IMMEDIATE');
|
||||
}] as $mutation) {
|
||||
try {
|
||||
DB::transaction($mutation);
|
||||
$this->fail('History/identity integrity must reject this mutation.');
|
||||
} catch (QueryException $error) {
|
||||
$this->assertContains($error->getCode(), ['23514', '23503']);
|
||||
}
|
||||
}
|
||||
DB::statement('SET CONSTRAINTS product_experiment_current_revision DEFERRED');
|
||||
$this->postJson($this->url.'/'.$id.'/revisions', $this->body(['title' => 'SYNTHETIC valid next version'], 1))->assertOk()->assertJsonPath('version', 2);
|
||||
DB::statement('SET CONSTRAINTS product_experiment_current_revision IMMEDIATE');
|
||||
$this->assertDatabaseCount('product_experiment_revisions', 2);
|
||||
}
|
||||
|
||||
public function test_history_and_listing_are_paginated_and_historical_reads_do_not_create_revisions(): void
|
||||
{
|
||||
$id = $this->create($this->body());
|
||||
$service = app(ProductExperiments::class);
|
||||
for ($v = 1; $v < 28; $v++) {
|
||||
$service->save($this->manager, $id, $this->body(['title' => 'SYNTHETIC version '.($v + 1)], $v));
|
||||
}
|
||||
for ($v = 1; $v < 26; $v++) {
|
||||
$service->save($this->manager, null, $this->body(['title' => 'SYNTHETIC additional '.$v]));
|
||||
}
|
||||
$this->getJson($this->url.'/'.$id)->assertOk()->assertJsonCount(25, 'history')->assertJsonPath('historyNext', 4)->assertJsonPath('history.0.version', 28);
|
||||
$this->getJson($this->url.'/'.$id.'?history_before=4&revision=1')->assertOk()->assertJsonCount(3, 'history')->assertJsonPath('historyNext', null)->assertJsonPath('historical', true);
|
||||
$this->getJson($this->url.'?page=999')->assertOk()->assertJsonPath('page', 2)->assertJsonPath('total', 26)->assertJsonCount(1, 'items');
|
||||
$this->getJson($this->url.'?state=planned')->assertOk()->assertJsonPath('total', 0);
|
||||
$this->getJson($this->url.'/'.$id.'?revision=999')->assertNotFound();
|
||||
$this->assertDatabaseCount('product_experiment_revisions', 53);
|
||||
}
|
||||
|
||||
public function test_missing_registry_schema_does_not_disable_the_operational_metrics_or_create_records(): void
|
||||
{
|
||||
$this->actingAs($this->manager);
|
||||
Schema::rename('product_experiment_revisions', 'product_experiment_revisions_qa_temporarily_unavailable');
|
||||
try {
|
||||
$this->getJson($this->url)->assertOk()->assertJsonPath('installed', false)->assertJsonCount(0, 'items');
|
||||
$this->getJson($this->url.'/new')->assertOk()->assertJsonPath('installed', false)->assertJsonPath('values.state', 'draft');
|
||||
$this->postJson($this->url, $this->body())->assertStatus(503);
|
||||
$this->getJson('/management/product-usage')->assertOk()->assertJsonCount(13, 'report.unmeasured');
|
||||
$this->assertDatabaseCount('product_experiments', 0);
|
||||
} finally {
|
||||
Schema::rename('product_experiment_revisions_qa_temporarily_unavailable', 'product_experiment_revisions');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\ProductUsageMetrics;
|
||||
use App\Services\VirtualDesk;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class ProductUsageMetricsTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $manager;
|
||||
|
||||
private User $owner;
|
||||
|
||||
private string $service;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
$this->travelTo(CarbonImmutable::parse('2026-11-03 12:00:00.123456', 'UTC'));
|
||||
Http::preventStrayRequests();
|
||||
$this->manager = User::factory()->create();
|
||||
$this->owner = User::factory()->create();
|
||||
config(['portal.managers' => [$this->manager->email], 'portal.notifications_enabled' => false, 'suitecrm.enabled' => false, 'investmoz_ai.enabled' => false]);
|
||||
$this->service = $this->service('synthetic-service', 1);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$this->travelBack();
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
private function service(string $code, int $version): string
|
||||
{
|
||||
$id = (string) Str::uuid();
|
||||
DB::table('desk_service_versions')->insert(['id' => $id, 'code' => $code, 'version' => $version, 'status' => 'published', 'definition' => json_encode(['title' => 'SYNTHETIC service', 'fields' => ['title' => ['type' => 'text', 'label' => 'Title', 'required' => true]]]), 'source' => '{}', 'author_id' => $this->manager->id, 'published_at' => now()->subDays(10), 'created_at' => now()->subDays(10), 'updated_at' => now()->subDays(10)]);
|
||||
|
||||
return $id;
|
||||
}
|
||||
|
||||
/** @param list<array{0:int,1:string,2:string,3?:array<string,mixed>}> $events */
|
||||
private function request(array $events, string $created = '2026-11-02 10:00:00', ?string $service = null, ?int $version = null): string
|
||||
{
|
||||
$case = (string) Str::uuid();
|
||||
$id = (string) Str::uuid();
|
||||
$desk = app(VirtualDesk::class);
|
||||
DB::table('desk_cases')->insert(['id' => $case, 'user_id' => $this->owner->id, 'title' => 'PRIVATE SYNTHETIC title', 'client_key' => (string) Str::uuid(), 'payload' => $desk->encode(['private' => 'PRIVATE SYNTHETIC DATA']), 'workflow' => '[]', 'created_at' => $created, 'updated_at' => $created]);
|
||||
$latest = $events === [] ? $created : $events[array_key_last($events)][2];
|
||||
DB::table('desk_requests')->insert(['id' => $id, 'case_id' => $case, 'service_version_id' => $service ?? $this->service, 'client_key' => (string) Str::uuid(), 'payload' => $desk->encode(['title' => 'PRIVATE SYNTHETIC DATA']), 'version' => $version ?? max(array_column($events, 0) ?: [1]), 'created_at' => $created, 'updated_at' => $latest]);
|
||||
foreach ($events as [$v, $action, $date, $payload]) {
|
||||
$this->event($id, $v, $action, $date, $payload ?? []);
|
||||
}
|
||||
|
||||
return $id;
|
||||
}
|
||||
|
||||
private function event(string $id, int $version, string $action, string $date, array $payload = []): void
|
||||
{
|
||||
DB::table('desk_events')->insert(['id' => (string) Str::uuid(), 'case_id' => DB::table('desk_requests')->where('id', $id)->value('case_id'), 'request_id' => in_array($action, ['company_comparison_saved', 'investment_guide_saved'], true) ? null : $id, 'actor_id' => $this->manager->id, 'action' => $action, 'version' => $version, 'payload' => app(VirtualDesk::class)->encode($payload), 'created_at' => $date]);
|
||||
}
|
||||
|
||||
private function report(array $filters = []): array
|
||||
{
|
||||
return $this->actingAs($this->manager)->getJson('/management/product-usage?'.http_build_query(['from' => '2026-11-02', 'to' => '2026-11-02', ...$filters]))->assertOk()->assertHeader('Cache-Control', 'no-store, private')->json('report');
|
||||
}
|
||||
|
||||
private function metric(array $report, string $id): array
|
||||
{
|
||||
return collect($report['metrics'])->firstWhere('id', $id);
|
||||
}
|
||||
|
||||
public function test_report_is_authorised_read_only_and_contains_no_private_records_or_invented_empty_rates(): void
|
||||
{
|
||||
$this->getJson('/management/product-usage')->assertUnauthorized();
|
||||
$this->actingAs($this->owner)->getJson('/management/product-usage')->assertForbidden();
|
||||
$before = DB::table('audit_events')->count();
|
||||
$r = $this->report();
|
||||
$this->assertSame(0, $this->metric($r, 'requests_created')['value']);
|
||||
$this->assertNull($this->metric($r, 'submission_rate')['value']);
|
||||
$this->assertSame(0, $this->metric($r, 'not_submitted')['value']);
|
||||
$this->assertSame($before, DB::table('audit_events')->count());
|
||||
$this->assertDatabaseCount('desk_cases', 0);
|
||||
$this->assertDatabaseCount('desk_events', 0);
|
||||
$this->assertSame(13, count($r['unmeasured']));
|
||||
$this->get('/management/product-usage')->assertOk()->assertInertia(fn ($page) => $page->component('management/product-usage'));
|
||||
config(['portal.managers' => []]);
|
||||
$this->getJson('/management/product-usage')->assertForbidden();
|
||||
$this->manager->forceFill(['email_verified_at' => null])->save();
|
||||
config(['portal.managers' => [$this->manager->email]]);
|
||||
$this->getJson('/management/product-usage')->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_first_submission_and_return_rates_deduplicate_versions_and_exclude_incomplete_histories(): void
|
||||
{
|
||||
$id = $this->request([[1, 'draft_created', '2026-11-02 10:00:00', []], [2, 'submitted', '2026-11-02 10:01:00', []], [3, 'request_returned', '2026-11-02 10:02:00', ['return_reason_code' => 'missing_documents']], [4, 'submitted', '2026-11-02 11:00:00', []], [4, 'request_context_reviewed', '2026-11-02 11:00:00', []], [5, 'request_returned', '2026-11-02 11:01:00', []]]);
|
||||
// The mutable latest-submission field must never replace the first immutable event.
|
||||
DB::table('desk_requests')->where('id', $id)->update(['submitted_at' => '2026-11-02 11:00:00']);
|
||||
$this->request([[1, 'draft_created', '2026-11-02 10:00:00', []]]);
|
||||
$this->request([[1, 'draft_created', '2026-11-02 10:00:00', []], [3, 'submitted', '2026-11-02 10:02:00', []]]);
|
||||
$legacy = $this->request([[1, 'draft_created', '2026-11-02 10:00:00', []]], version: 3);
|
||||
DB::table('desk_requests')->where('id', $legacy)->update(['updated_at' => null]);
|
||||
$r = $this->report();
|
||||
$this->assertSame(4, $r['coverage']['cohort_requests']);
|
||||
$this->assertSame(2, $r['coverage']['complete_histories']);
|
||||
$this->assertSame(2, $r['coverage']['unknown_histories']);
|
||||
$this->assertEquals(50, $this->metric($r, 'submission_rate')['value']);
|
||||
$this->assertEquals(100, $this->metric($r, 'return_rate')['value']);
|
||||
$this->assertEquals(100, $this->metric($r, 'error_document_return_rate')['value']);
|
||||
$this->assertEquals(60, $this->metric($r, 'first_submission_seconds')['value']);
|
||||
$this->assertSame('partial', $this->metric($r, 'submission_rate')['state']);
|
||||
$this->assertSame(1, $this->metric($r, 'not_submitted')['value']);
|
||||
$this->assertStringNotContainsString('PRIVATE SYNTHETIC', json_encode($r));
|
||||
$this->assertStringNotContainsString($id, json_encode($r));
|
||||
}
|
||||
|
||||
public function test_historical_unclassified_returns_remain_unknown_and_free_text_does_not_classify_them(): void
|
||||
{
|
||||
$this->request([[1, 'draft_created', '2026-11-02 10:00:00', []], [2, 'submitted', '2026-11-02 10:01:00', []], [3, 'request_returned', '2026-11-02 10:02:00', ['reason' => 'Documentação em falta, erro nos dados']]]);
|
||||
$this->request([[1, 'draft_created', '2026-11-02 10:00:00', []], [2, 'submitted', '2026-11-02 10:01:00', []], [3, 'request_returned', '2026-11-02 10:02:00', ['return_reason_code' => 'other']]]);
|
||||
$r = $this->report();
|
||||
$this->assertNull($this->metric($r, 'error_document_return_rate')['value']);
|
||||
$this->assertSame(0, $this->metric($r, 'error_document_return_rate')['numerator']);
|
||||
$this->assertSame(2, $this->metric($r, 'error_document_return_rate')['denominator']);
|
||||
$this->assertSame(1, $r['coverage']['unclassified_returned_requests']);
|
||||
$this->assertEquals(100, $this->metric($r, 'return_rate')['value']);
|
||||
}
|
||||
|
||||
public function test_inclusive_days_cutoff_historical_service_versions_and_distinct_saved_dossiers(): void
|
||||
{
|
||||
$v2 = $this->service('synthetic-service', 2);
|
||||
$other = $this->service('other-service', 1);
|
||||
$a = $this->request([[1, 'draft_created', '2026-11-02 00:00:00', []], [2, 'submitted', '2026-11-03 00:00:00', []]], '2026-11-02 00:00:00');
|
||||
$this->request([[1, 'draft_created', '2026-11-02 23:59:59', []]], '2026-11-02 23:59:59', $v2);
|
||||
$this->request([], '2026-11-01 23:59:59');
|
||||
$this->request([], '2026-11-03 00:00:00');
|
||||
$this->request([], '2026-11-02 12:00:00', $other);
|
||||
$this->event($a, 2, 'company_comparison_saved', '2026-11-02 11:00:00');
|
||||
$this->event($a, 3, 'company_comparison_saved', '2026-11-02 12:00:00');
|
||||
$this->event($a, 3, 'investment_guide_saved', '2026-11-02 13:00:00');
|
||||
$r = $this->report(['service_code' => 'synthetic-service']);
|
||||
$this->assertSame(2, $this->metric($r, 'requests_created')['value']);
|
||||
$this->assertSame(2, $this->metric($r, 'dossiers_created')['value']);
|
||||
$this->assertSame(1, $this->metric($r, 'saved_comparison')['value']);
|
||||
$this->assertSame(1, $this->metric($r, 'saved_guide')['value']);
|
||||
$this->assertSame('2026-11-03T00:00:00.000000+00:00', $r['observed_before']);
|
||||
$this->assertSame(2, collect($r['services'])->firstWhere('code', 'synthetic-service')['version']);
|
||||
$this->assertSame(0, $this->metric($r, 'submission_rate')['numerator']);
|
||||
}
|
||||
|
||||
public function test_negative_event_clock_intervals_are_excluded_without_turning_zero_duration_into_unknown(): void
|
||||
{
|
||||
$this->request([[1, 'draft_created', '2026-11-02 10:00:00', []], [2, 'submitted', '2026-11-02 09:59:59', []]]);
|
||||
$this->request([[1, 'draft_created', '2026-11-02 10:00:00', []], [2, 'submitted', '2026-11-02 10:00:00', []]]);
|
||||
$r = $this->report();
|
||||
$this->assertEquals(0, $this->metric($r, 'first_submission_seconds')['value']);
|
||||
$this->assertSame('partial', $this->metric($r, 'first_submission_seconds')['state']);
|
||||
$this->assertSame(1, $r['coverage']['invalid_duration_requests']);
|
||||
$this->assertSame(1, $r['coverage']['valid_duration_requests']);
|
||||
}
|
||||
|
||||
public function test_transition_keeps_optional_versioned_category_and_application_event_time_without_changing_authority(): void
|
||||
{
|
||||
$id = $this->request([[1, 'draft_created', '2026-11-02 10:00:00', []], [2, 'submitted', '2026-11-02 10:01:00', []]]);
|
||||
DB::table('desk_requests')->where('id', $id)->update(['status' => 'submitted', 'protocol' => 'SYNTHETIC-'.$id, 'submitted_snapshot' => app(VirtualDesk::class)->encode([]), 'submitted_at' => '2026-11-02 10:01:00']);
|
||||
$url = '/balcao-virtual/pedidos/'.$id.'/estado';
|
||||
$data = ['version' => 2, 'status' => 'returned', 'reason' => 'SYNTHETIC correction', 'editable_fields' => ['title'], 'return_reason_code' => 'validation_error'];
|
||||
$this->actingAs($this->owner)->postJson($url, $data)->assertForbidden();
|
||||
$this->actingAs($this->manager)->postJson($url, [...$data, 'return_reason_code' => 'invented'])->assertUnprocessable();
|
||||
$this->postJson($url, $data)->assertOk();
|
||||
$event = DB::table('desk_events')->where('request_id', $id)->where('action', 'request_returned')->first();
|
||||
$p = app(VirtualDesk::class)->decode($event->payload);
|
||||
$this->assertSame('validation_error', $p['return_reason_code']);
|
||||
$this->assertSame(config('product-metrics.return_reasons.validation_error'), $p['return_reason_label']);
|
||||
$this->assertSame(config('product-metrics.version'), $p['return_reason_definition']);
|
||||
$this->assertSame(now()->toDateTimeString(), CarbonImmutable::parse($event->created_at)->toDateTimeString());
|
||||
$this->postJson($url, $data)->assertConflict();
|
||||
$this->assertSame(1, DB::table('desk_events')->where('action', 'request_returned')->count());
|
||||
$other = $this->request([[1, 'draft_created', '2026-11-02 10:00:00', []], [2, 'submitted', '2026-11-02 10:01:00', []]]);
|
||||
DB::table('desk_requests')->where('id', $other)->update(['status' => 'submitted', 'protocol' => 'SYNTHETIC-'.$other, 'submitted_snapshot' => app(VirtualDesk::class)->encode([]), 'submitted_at' => '2026-11-02 10:01:00']);
|
||||
unset($data['return_reason_code']);
|
||||
$this->postJson('/balcao-virtual/pedidos/'.$other.'/estado', $data)->assertOk();
|
||||
$legacy = DB::table('desk_events')->where('request_id', $other)->where('action', 'request_returned')->value('payload');
|
||||
$this->assertSame('unspecified', app(VirtualDesk::class)->decode($legacy)['return_reason_code']);
|
||||
}
|
||||
|
||||
public function test_report_rejects_invalid_periods_services_and_does_not_fall_back_to_another_scope(): void
|
||||
{
|
||||
$this->actingAs($this->manager);
|
||||
foreach ([['from' => 'bad'], ['from' => '2026-11-03', 'to' => '2026-11-02'], ['to' => '2026-11-04'], ['service_code' => 'invented']] as $bad) {
|
||||
$this->getJson('/management/product-usage?'.http_build_query(['from' => '2026-11-02', 'to' => '2026-11-02', ...$bad]))->assertUnprocessable();
|
||||
}
|
||||
$r = app(ProductUsageMetrics::class)->report($this->manager, []);
|
||||
$this->assertSame('existing_transaction', $r['read_consistency']);
|
||||
$this->assertSame('2026-11-03T12:00:00.123456+00:00', $r['observed_before']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
use App\Services\PublicSearchMetrics;
|
||||
use App\Support\IsolatedQaDatabase;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use PDO;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class PublicSearchMetricsTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $manager;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
$this->travelTo(CarbonImmutable::parse('2026-11-02 12:00:00.123456', 'UTC'));
|
||||
Http::preventStrayRequests();
|
||||
$this->manager = User::factory()->create();
|
||||
config(['portal.managers' => [$this->manager->email], 'investmoz_ai.enabled' => false, 'suitecrm.enabled' => false, 'portal.notifications_enabled' => false, 'search-metrics.enabled' => true, 'search-metrics.capture_lock_timeout_ms' => 1500, 'search-metrics.capture_statement_timeout_ms' => 3000]);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$this->travelBack();
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
private function opportunity(string $description = 'Cultivo de algodão'): Opportunity
|
||||
{
|
||||
$sector = Sector::create(['name' => 'SYNTHETIC sector', 'slug' => 'synthetic-'.Str::uuid(), 'is_active' => true, 'published_at' => now()]);
|
||||
|
||||
return Opportunity::create(['sector_id' => $sector->id, 'reference' => 'SYNTHETIC-'.Str::uuid(), 'slug' => 'synthetic-'.Str::uuid(), 'title' => 'SYNTHETIC opportunity', 'summary' => $description, 'status' => 'published', 'published_at' => now()->subDay()]);
|
||||
}
|
||||
|
||||
private function report(array $filters = []): array
|
||||
{
|
||||
return $this->actingAs($this->manager)->getJson('/management/product-usage?'.http_build_query(['from' => '2026-11-02', 'to' => '2026-11-02', ...$filters]))->assertOk()->assertHeader('Cache-Control', 'no-store, private')->json('report');
|
||||
}
|
||||
|
||||
private function legacyFixture(): void
|
||||
{
|
||||
Storage::fake('local');
|
||||
config(['portal.legacy_content_qa_enabled' => true]);
|
||||
$bytes = json_encode(['format' => 'investmoz-legacy-article-v1', 'source_url' => 'https://investemoz.tempo.co.mz/agronegocio', 'title' => 'SYNTHETIC article', 'content_html' => '<p>SYNTHETIC content for isolated QA only</p>', 'author' => 'SYNTHETIC author', 'legacy_id' => 171985, 'legacy_category' => 'SYNTHETIC QA', 'published_at' => '2026-11-02T09:00:00+00:00', 'modified_at' => '2026-11-02T10:00:00+00:00'], JSON_THROW_ON_ERROR);
|
||||
$id = (string) Str::uuid();
|
||||
Storage::disk('local')->put('legacy/'.$id, $bytes);
|
||||
DB::table('documents')->insert(['id' => $id, 'source_system' => 'synthetic-test', 'external_id' => 'legacy-tempo-post-171985-20260420', 'file_name' => 'synthetic.json', 'media_type' => 'application/json', 'storage_key' => 'legacy/'.$id, 'sha256' => hash('sha256', $bytes), 'malware_scanned_sha256' => hash('sha256', $bytes), 'malware_scan_status' => 'clean', 'size_bytes' => strlen($bytes), 'status' => 'active', 'rights_status' => 'authorized', 'data_classification' => 'public']);
|
||||
DB::table('portal_resources')->insert(['document_id' => $id, 'title' => 'SYNTHETIC article', 'category' => 'education', 'topic' => 'agronegocio', 'published' => true, 'rights_status' => 'authorized', 'source_url' => 'https://investemoz.tempo.co.mz/agronegocio', 'source_reference' => 'SYNTHETIC isolated QA fixture; not official.', 'metadata_version' => 1]);
|
||||
}
|
||||
|
||||
public function test_primary_search_totals_are_recorded_without_terms_identifiers_or_changes_to_opportunities(): void
|
||||
{
|
||||
$crop = $this->opportunity();
|
||||
$before = DB::table('opportunities')->orderBy('id')->get()->toJson();
|
||||
$this->getJson('/api/v1/investment/search?q=plantio+de+algodao')->assertOk()->assertJsonPath('total', 1)->assertJsonPath('data.0.id', $crop->id);
|
||||
$this->getJson('/api/v1/opportunities/search?q=PRIVATE-SYNTHETIC-EMAIL%40example.invalid&total=999')->assertOk()->assertJsonPath('total', 0);
|
||||
$this->get('/oportunidades?q=plantio+de+algodao')->assertOk();
|
||||
$api = DB::table('product_search_counts')->where('channel', 'opportunities_api')->first();
|
||||
$this->assertSame(2, $api->responses);
|
||||
$this->assertSame(1, $api->zero_responses);
|
||||
$this->assertSame(1, DB::table('product_search_counts')->where('channel', 'opportunities_page')->value('responses'));
|
||||
$this->assertSame(1, DB::table('product_search_definitions')->count());
|
||||
$this->assertStringNotContainsString('PRIVATE-SYNTHETIC', DB::table('product_search_counts')->get()->toJson().DB::table('product_search_definitions')->get()->toJson());
|
||||
$this->assertEqualsCanonicalizing(['day', 'channel', 'definition_version', 'responses', 'zero_responses', 'first_recorded_at', 'last_recorded_at'], Schema::getColumnListing('product_search_counts'));
|
||||
$this->assertSame($before, DB::table('opportunities')->orderBy('id')->get()->toJson());
|
||||
$this->assertDatabaseCount('interest_requests', 0);
|
||||
}
|
||||
|
||||
public function test_each_instrumented_public_catalogue_records_its_own_actual_primary_total(): void
|
||||
{
|
||||
$this->legacyFixture();
|
||||
foreach (['/oportunidades', '/api/v1/investment/search', '/educacao', '/negocios', '/documentos', '/parcerias', '/carteira', '/zonas', '/explorar/agronegocio'] as $url) {
|
||||
$this->assertSame(200, $this->get($url.'?q=SYNTHETIC')->status(), 'Expected available synthetic public catalogue: '.$url);
|
||||
}
|
||||
$this->assertDatabaseCount('product_search_counts', 9);
|
||||
$this->assertEqualsCanonicalizing(array_keys(config('search-metrics.channels')), DB::table('product_search_counts')->pluck('channel')->all());
|
||||
foreach (['documents', 'sector_content'] as $channel) {
|
||||
$this->assertSame(0, DB::table('product_search_counts')->where('channel', $channel)->value('zero_responses'));
|
||||
}
|
||||
$this->assertSame(9, (int) DB::table('product_search_counts')->sum('responses'));
|
||||
$this->assertSame(7, (int) DB::table('product_search_counts')->sum('zero_responses'));
|
||||
}
|
||||
|
||||
public function test_browsing_pagination_prefetch_privacy_signals_auxiliary_routes_and_failed_responses_are_excluded(): void
|
||||
{
|
||||
$this->get('/oportunidades')->assertOk();
|
||||
$this->get('/oportunidades?sort=title&view=list')->assertOk();
|
||||
$this->get('/oportunidades?q=SYNTHETIC&page=2')->assertOk();
|
||||
foreach (['suggest', 'references', 'map', 'export'] as $action) {
|
||||
$this->get('/api/v1/investment/'.$action.'?q=SYNTHETIC')->assertOk();
|
||||
}
|
||||
$this->call('HEAD', '/oportunidades?q=SYNTHETIC')->assertOk();
|
||||
foreach ([['Purpose' => 'prefetch'], ['Sec-Purpose' => 'prefetch;prerender'], ['X-Inertia-Prefetch' => 'true'], ['DNT' => '1'], ['Sec-GPC' => '1']] as $headers) {
|
||||
$this->withHeaders(['Purpose' => '', 'Sec-Purpose' => '', 'X-Inertia-Prefetch' => '', 'DNT' => '0', 'Sec-GPC' => '0', ...$headers])->get('/oportunidades?q=SYNTHETIC')->assertOk();
|
||||
}
|
||||
$this->withHeaders(['Purpose' => '', 'Sec-Purpose' => '', 'X-Inertia-Prefetch' => '', 'DNT' => '0', 'Sec-GPC' => '0'])->getJson('/api/v1/investment/search?'.http_build_query(['q' => str_repeat('x', 121)]))->assertUnprocessable();
|
||||
$this->assertDatabaseCount('product_search_counts', 0);
|
||||
$this->assertDatabaseCount('product_search_definitions', 0);
|
||||
}
|
||||
|
||||
public function test_related_suggestions_do_not_turn_an_empty_primary_search_into_a_positive_result(): void
|
||||
{
|
||||
$this->opportunity('Descaroçamento e transformação de algodão');
|
||||
$this->get('/oportunidades?q=plantio+de+algodao')->assertOk()->assertInertia(fn ($p) => $p->where('results.total', 0)->has('relatedSearch.items', 1));
|
||||
$this->assertSame(1, DB::table('product_search_counts')->value('zero_responses'));
|
||||
$this->assertSame(1, DB::table('product_search_counts')->value('responses'));
|
||||
}
|
||||
|
||||
public function test_reports_distinguish_no_measurement_zero_results_and_unrelated_service_filters(): void
|
||||
{
|
||||
$r = $this->report();
|
||||
$this->assertNull($r['search']['responses']);
|
||||
$this->assertNull($r['search']['zero_rate']);
|
||||
$this->opportunity();
|
||||
$this->getJson('/api/v1/investment/search?q=algodao')->assertOk();
|
||||
$r = $this->report();
|
||||
$this->assertSame(1, $r['search']['responses']);
|
||||
$this->assertSame(0, $r['search']['zero_responses']);
|
||||
$this->assertEquals(0, $r['search']['zero_rate']);
|
||||
$this->assertFalse($r['search']['definition_conflict_now']);
|
||||
$this->assertSame('daily_aggregate_at_report_snapshot', $r['search']['temporal_basis']);
|
||||
$this->assertSame('partial', collect($r['metrics'])->firstWhere('id', 'recorded_zero_search_rate')['state']);
|
||||
$this->assertNull(collect($r['search']['channels'])->firstWhere('id', 'documents')['responses']);
|
||||
DB::table('desk_service_versions')->insert(['id' => (string) Str::uuid(), 'code' => 'synthetic-service', 'version' => 1, 'definition' => '{"title":"SYNTHETIC service"}', 'source' => '{}', 'author_id' => $this->manager->id]);
|
||||
$filtered = $this->report(['service_code' => 'synthetic-service']);
|
||||
$this->assertFalse($filtered['search']['applicable']);
|
||||
$this->assertNull($filtered['search']['responses']);
|
||||
$this->getJson('/management/product-usage?search_definition=invented')->assertUnprocessable();
|
||||
}
|
||||
|
||||
public function test_missing_collection_schema_preserves_search_and_never_claims_zero_measurement(): void
|
||||
{
|
||||
Schema::rename('product_search_counts', 'product_search_counts_qa_unavailable');
|
||||
try {
|
||||
$this->get('/oportunidades?q=SYNTHETIC')->assertOk();
|
||||
$r = $this->report();
|
||||
$this->assertFalse($r['search']['installed']);
|
||||
$this->assertNull($r['search']['responses']);
|
||||
$this->assertSame(0, DB::table('product_search_counts_qa_unavailable')->count());
|
||||
} finally {
|
||||
Schema::rename('product_search_counts_qa_unavailable', 'product_search_counts');
|
||||
}
|
||||
}
|
||||
|
||||
public function test_collection_and_diagnostic_failures_cannot_poison_a_search_or_its_outer_transaction(): void
|
||||
{
|
||||
$logged = [];
|
||||
Log::shouldReceive('warning')->twice()->andReturnUsing(function ($message, $context) use (&$logged) {
|
||||
$logged[] = [$message, $context];
|
||||
if (count($logged) === 2) {
|
||||
throw new \RuntimeException('SYNTHETIC unavailable log');
|
||||
}
|
||||
});
|
||||
DB::statement('ALTER TABLE product_search_counts ADD CONSTRAINT synthetic_capture_failure CHECK(responses<0) NOT VALID');
|
||||
try {
|
||||
for ($n = 0; $n < 2; $n++) {
|
||||
$this->getJson('/api/v1/investment/search?q=PRIVATE-SYNTHETIC-TERM')->assertOk()->assertJsonPath('total', 0);
|
||||
}
|
||||
$this->assertSame(0, DB::table('opportunities')->count());
|
||||
$this->assertDatabaseCount('product_search_counts', 0);
|
||||
$this->assertDatabaseCount('product_search_definitions', 0);
|
||||
$this->assertCount(2, $logged);
|
||||
$this->assertSame(['channel', 'definition_version', 'exception_class'], array_keys($logged[0][1]));
|
||||
$this->assertStringNotContainsString('PRIVATE-SYNTHETIC', json_encode($logged));
|
||||
} finally {
|
||||
DB::statement('ALTER TABLE product_search_counts DROP CONSTRAINT synthetic_capture_failure');
|
||||
}
|
||||
}
|
||||
|
||||
public function test_editions_are_not_summed_and_registered_definitions_remain_immutable_and_readable(): void
|
||||
{
|
||||
$collector = app(PublicSearchMetrics::class);
|
||||
$v1 = config('search-metrics.version');
|
||||
$oldLabel = config('search-metrics.channels.opportunities_api');
|
||||
$collector->record('opportunities_api', false);
|
||||
config(['search-metrics.version' => 'SYNTHETIC-v2', 'search-metrics.channels.opportunities_api' => 'SYNTHETIC second edition']);
|
||||
$collector->record('opportunities_api', true);
|
||||
$current = $this->report();
|
||||
$this->assertSame(1, $current['search']['responses']);
|
||||
$this->assertEquals(100, $current['search']['zero_rate']);
|
||||
$old = $this->report(['search_definition' => $v1]);
|
||||
$this->assertSame(1, $old['search']['responses']);
|
||||
$this->assertEquals(0, $old['search']['zero_rate']);
|
||||
$this->assertSame($oldLabel, collect($old['search']['channels'])->firstWhere('id', 'opportunities_api')['label']);
|
||||
Log::spy();
|
||||
config(['search-metrics.channels.opportunities_api' => 'SYNTHETIC conflicting unversioned change']);
|
||||
$collector->record('opportunities_api', false);
|
||||
$this->assertSame(1, $this->report()['search']['responses']);
|
||||
$this->assertTrue($this->report()['search']['definition_conflict_now']);
|
||||
Log::shouldHaveReceived('warning')->once();
|
||||
try {
|
||||
DB::transaction(fn () => DB::table('product_search_definitions')->where('version', $v1)->update(['sha256' => str_repeat('0', 64)]));
|
||||
$this->fail('Definitions cannot be rewritten.');
|
||||
} catch (QueryException $error) {
|
||||
$this->assertSame('23514', $error->getCode());
|
||||
}
|
||||
}
|
||||
|
||||
public function test_daily_boundaries_and_disabled_collection_preserve_the_existing_history(): void
|
||||
{
|
||||
$collector = app(PublicSearchMetrics::class);
|
||||
$this->travelTo(CarbonImmutable::parse('2026-11-01 23:59:59.999999', 'UTC'));
|
||||
$collector->record('opportunities_api', false);
|
||||
$this->travelTo(CarbonImmutable::parse('2026-11-02 00:00:00.000001', 'UTC'));
|
||||
$collector->record('opportunities_api', true);
|
||||
$this->travelTo(CarbonImmutable::parse('2026-11-03 00:00:00.000001', 'UTC'));
|
||||
$collector->record('opportunities_api', false);
|
||||
config(['search-metrics.enabled' => false]);
|
||||
$this->get('/oportunidades?q=SYNTHETIC')->assertOk();
|
||||
$r = $this->report();
|
||||
$this->assertFalse($r['search']['enabled_now']);
|
||||
$this->assertSame(1, $r['search']['responses']);
|
||||
$this->assertSame(1, $r['search']['zero_responses']);
|
||||
$this->assertDatabaseCount('product_search_counts', 3);
|
||||
}
|
||||
|
||||
public function test_collector_respects_and_restores_the_callers_stricter_query_budgets(): void
|
||||
{
|
||||
config(['search-metrics.capture_lock_timeout_ms' => 1000, 'search-metrics.capture_statement_timeout_ms' => 2000]);
|
||||
DB::statement("SET LOCAL lock_timeout='500ms'");
|
||||
DB::statement("SET LOCAL statement_timeout='1000ms'");
|
||||
$during = [];
|
||||
DB::listen(function ($event) use (&$during) {
|
||||
if (str_contains($event->sql, 'INSERT INTO product_search_counts')) {
|
||||
$pdo = DB::connection()->getPdo();
|
||||
$during[] = [$pdo->query('SHOW lock_timeout')->fetchColumn(), $pdo->query('SHOW statement_timeout')->fetchColumn()];
|
||||
}
|
||||
});
|
||||
app(PublicSearchMetrics::class)->record('opportunities_api', false);
|
||||
$this->assertSame([['500ms', '1s']], $during);
|
||||
$this->assertSame('500ms', DB::selectOne('SHOW lock_timeout')->lock_timeout);
|
||||
$this->assertSame('1s', DB::selectOne('SHOW statement_timeout')->statement_timeout);
|
||||
$this->assertDatabaseCount('product_search_counts', 1);
|
||||
}
|
||||
|
||||
public function test_a_real_competing_database_lock_does_not_hold_the_collector_indefinitely(): void
|
||||
{
|
||||
$this->assertTrue(IsolatedQaDatabase::allowsSchemaChanges());
|
||||
$c = config('database.connections.pgsql');
|
||||
$other = new PDO('pgsql:host='.$c['host'].';port='.$c['port'].';dbname='.$c['database'], $c['username'], $c['password'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
|
||||
$other->beginTransaction();
|
||||
$other->exec("SET LOCAL lock_timeout='1000ms'");
|
||||
$other->exec('LOCK TABLE product_search_counts IN ACCESS EXCLUSIVE MODE');
|
||||
config(['search-metrics.capture_lock_timeout_ms' => 50, 'search-metrics.capture_statement_timeout_ms' => 500]);
|
||||
Log::spy();
|
||||
$before = microtime(true);
|
||||
try {
|
||||
app(PublicSearchMetrics::class)->record('opportunities_api', true);
|
||||
} finally {
|
||||
$other->rollBack();
|
||||
}
|
||||
$this->assertLessThan(5, microtime(true) - $before);
|
||||
$this->assertDatabaseCount('product_search_counts', 0);
|
||||
$this->assertDatabaseCount('product_search_definitions', 0);
|
||||
Log::shouldHaveReceived('warning')->once();
|
||||
app(PublicSearchMetrics::class)->record('opportunities_api', true);
|
||||
$this->assertSame(1, DB::table('product_search_counts')->value('responses'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Jobs\ScanDocumentForMalware;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\User;
|
||||
use App\Services\OpportunityImageProcessor;
|
||||
use App\Services\OpportunityManagement;
|
||||
use App\Services\OpportunityResourceFileCleanup;
|
||||
use App\Services\OpportunityTechnicalIncidents;
|
||||
use App\Services\PortalProfileAdministration;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Facades\Queue;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use Mockery;
|
||||
use Tests\Support\CleanScannerFixture;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class ResourceTechnicalIncidentsTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $actor;
|
||||
|
||||
private User $support;
|
||||
|
||||
private Opportunity $opportunity;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
Http::fake();
|
||||
Mail::fake();
|
||||
Queue::fake();
|
||||
Storage::fake('local');
|
||||
config(['portal.profile_access_enabled' => true, 'suitecrm.enabled' => false, 'investmoz_ai.enabled' => false]);
|
||||
$this->actor = User::factory()->create();
|
||||
$this->support = User::factory()->create();
|
||||
$approver = User::factory()->create();
|
||||
$organization = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $organization, 'name' => 'SYNTHETIC upload QA organization', 'organization_type' => 'private']);
|
||||
DB::table('memberships')->insert(['id' => (string) Str::uuid(), 'user_id' => $this->actor->id, 'organization_id' => $organization, 'role' => 'officer']);
|
||||
foreach ([[$this->actor, 'promoter'], [$this->support, 'technical_support']] as [$user,$role]) {
|
||||
app(PortalProfileAdministration::class)->insertGrant((string) Str::uuid(), $approver, ['user_id' => $user->id, 'role' => $role, 'organization_id' => $organization, 'opportunity_types' => ['investment_project'], 'source' => 'synthetic-resource-incident-fixture']);
|
||||
}
|
||||
$id = (string) Str::uuid();
|
||||
$this->opportunity = new Opportunity(['reference' => $id, 'slug' => $id, 'title' => 'PRIVATE SYNTHETIC upload investment', 'status' => 'draft']);
|
||||
$this->opportunity->forceFill(['owner_user_id' => $this->actor->id, 'organization_id' => $organization, 'opportunity_category' => 'investment_project', 'management_version' => 4, 'workflow_context' => ['working_state' => 'draft']])->save();
|
||||
$this->actingAs($this->actor);
|
||||
}
|
||||
|
||||
private function url(string $kind = 'documents'): string
|
||||
{
|
||||
return '/minhas-oportunidades/'.$this->opportunity->id.'/resources/'.$kind;
|
||||
}
|
||||
|
||||
private function input(): array
|
||||
{
|
||||
return ['etag' => app(OpportunityManagement::class)->etag($this->opportunity->fresh()), 'creation_key' => (string) Str::uuid(), 'reason' => 'PRIVATE SYNTHETIC upload reason', 'payload' => ['title' => 'PRIVATE SYNTHETIC original', 'classification' => 'confidential'], 'file' => UploadedFile::fake()->createWithContent('PRIVATE-synthetic.pdf', "%PDF-1.7\nSYNTHETIC private bytes\n%%EOF")];
|
||||
}
|
||||
|
||||
private function incidentCount(): int
|
||||
{
|
||||
return DB::table('audit_events')->where('source_system', 'portal-opportunity-incident')->count();
|
||||
}
|
||||
|
||||
public function test_database_failure_rolls_back_upload_preserves_prior_originals_and_routes_private_metadata_to_support(): void
|
||||
{
|
||||
$before = $this->opportunity->fresh()->getRawOriginal();
|
||||
DB::statement("ALTER TABLE audit_events ADD CONSTRAINT qa_upload_failure CHECK (source_system <> 'opportunity-resources')");
|
||||
$response = $this->post($this->url(), $this->input(), ['Accept' => 'application/json'])->assertStatus(503)->assertJsonPath('incident_recorded', true);
|
||||
$reference = $response->json('reference');
|
||||
$this->assertTrue(Str::isUuid($reference));
|
||||
$this->assertStringNotContainsString('SQLSTATE', $response->getContent());
|
||||
$this->assertStringNotContainsString('PRIVATE-synthetic', $response->getContent());
|
||||
$this->assertSame($before, $this->opportunity->fresh()->getRawOriginal());
|
||||
$this->assertSame(0, DB::table('documents')->count());
|
||||
$this->assertSame(0, DB::table('opportunity_documents')->count());
|
||||
$this->assertSame([], Storage::disk('local')->allFiles());
|
||||
$data = json_decode(DB::table('audit_events')->where('id', $reference)->value('after_data'), true)['incident'];
|
||||
$this->assertSame('upload_document', $data['operation']);
|
||||
$this->assertSame(4, $data['observed_version']);
|
||||
$this->assertSame('database_failure', $data['error_code']);
|
||||
$this->assertStringNotContainsString('PRIVATE', json_encode($data));
|
||||
$this->get('/minhas-oportunidades/'.$this->opportunity->id.'/resources')->assertOk()->assertHeader('Cache-Control', 'no-store, private')->assertInertia(fn (Assert $page) => $page->where('technicalIncidents.0.reference', $reference)->where('technicalIncidents.0.operation', 'upload_document'));
|
||||
$this->actingAs($this->support)->get('/suporte-tecnico/incidentes?unread=1')->assertOk()->assertInertia(fn (Assert $page) => $page->where('incidents.total', 1)->where('incidents.data.0.operation', 'upload_document'));
|
||||
$this->get('/minhas-oportunidades/'.$this->opportunity->id.'/resources')->assertForbidden();
|
||||
DB::statement('ALTER TABLE audit_events DROP CONSTRAINT qa_upload_failure');
|
||||
$this->actingAs($this->actor)->post($this->url(), $this->input(), ['Accept' => 'application/json'])->assertCreated();
|
||||
$this->assertSame(1, $this->incidentCount());
|
||||
}
|
||||
|
||||
public function test_expected_validation_scope_version_and_quarantine_errors_do_not_create_incidents(): void
|
||||
{
|
||||
$bad = $this->input();
|
||||
$bad['file'] = UploadedFile::fake()->createWithContent('bad.pdf', 'not a pdf')->mimeType('text/plain');
|
||||
$this->post($this->url(), $bad, ['Accept' => 'application/json'])->assertUnprocessable();
|
||||
$stale = $this->input();
|
||||
$stale['etag'] = str_repeat('0', 64);
|
||||
$this->post($this->url(), $stale, ['Accept' => 'application/json'])->assertConflict();
|
||||
$this->actingAs($this->support)->post($this->url(), $this->input(), ['Accept' => 'application/json'])->assertForbidden();
|
||||
$this->actingAs($this->actor)->postJson($this->url('images').'/'.Str::uuid().'/prepare', ['etag' => app(OpportunityManagement::class)->etag($this->opportunity), 'version' => 1, 'reason' => 'SYNTHETIC missing image request'])->assertStatus(function_exists('imagecreatefromstring') ? 404 : 423);
|
||||
$this->assertSame(0, $this->incidentCount());
|
||||
$this->assertSame([], Storage::disk('local')->allFiles());
|
||||
}
|
||||
|
||||
public function test_partial_storage_failure_is_reported_and_cleanup_failure_does_not_hide_the_original_result(): void
|
||||
{
|
||||
$disk = Storage::disk('local');
|
||||
$fault = Mockery::mock($disk);
|
||||
$fault->shouldReceive('putFileAs')->andReturnUsing(function ($path, $file, $name) use ($disk) {
|
||||
$disk->put($path.'/'.$name, 'SYNTHETIC partial bytes');
|
||||
|
||||
return false;
|
||||
});
|
||||
$fault->shouldReceive('delete')->andThrow(new \RuntimeException('PRIVATE cleanup failure'));
|
||||
Storage::shouldReceive('disk')->with('local')->andReturn($fault);
|
||||
$response = $this->post($this->url(), $this->input(), ['Accept' => 'application/json'])->assertStatus(503)->assertJsonPath('incident_recorded', true);
|
||||
$this->assertStringNotContainsString('PRIVATE', $response->getContent());
|
||||
$this->assertCount(1, $disk->allFiles());
|
||||
$this->assertSame(0, DB::table('documents')->count());
|
||||
$this->assertSame(1, $this->incidentCount());
|
||||
}
|
||||
|
||||
public function test_cleanup_preserves_referenced_originals_uncertain_commit_bytes_and_failed_reference_checks(): void
|
||||
{
|
||||
$cleanup = app(OpportunityResourceFileCleanup::class);
|
||||
$disk = Storage::disk('local');
|
||||
$key = 'opportunity-resources/'.Str::uuid();
|
||||
$disk->put($key, Crypt::encryptString('SYNTHETIC preserved original'));
|
||||
$hash = hash('sha256', $disk->get($key));
|
||||
DB::table('documents')->insert(['id' => (string) Str::uuid(), 'source_system' => 'opportunity-resources', 'file_name' => 'synthetic.pdf', 'media_type' => 'application/pdf', 'storage_key' => $key, 'sha256' => str_repeat('a', 64), 'status' => 'quarantined', 'storage_encryption' => 'laravel', 'data_classification' => 'restricted', 'size_bytes' => 1, 'uploaded_by' => $this->actor->id]);
|
||||
$cleanup->afterFailure([$key], new \RuntimeException('SYNTHETIC failure after committed document'));
|
||||
$this->assertSame($hash, hash('sha256', $disk->get($key)));
|
||||
$unknown = 'opportunity-resources/'.Str::uuid();
|
||||
$disk->put($unknown, 'SYNTHETIC uncertain bytes');
|
||||
$cleanup->afterFailure([$unknown], new \PDOException('server closed the connection unexpectedly'));
|
||||
$this->assertTrue($disk->exists($unknown));
|
||||
DB::statement('ALTER TABLE documents RENAME COLUMN storage_key TO qa_unavailable_storage_key');
|
||||
$cleanup->afterFailure([$unknown], new \RuntimeException('SYNTHETIC failed reference lookup'));
|
||||
$this->assertTrue($disk->exists($unknown));
|
||||
$this->assertGreaterThan(0, DB::table('users')->count());
|
||||
DB::statement('ALTER TABLE documents RENAME COLUMN qa_unavailable_storage_key TO storage_key');
|
||||
$cleanup->afterFailure([$unknown], new \RuntimeException('SYNTHETIC confirmed rollback'));
|
||||
$this->assertFalse($disk->exists($unknown));
|
||||
}
|
||||
|
||||
public function test_failed_incident_persistence_is_reported_honestly_and_does_not_leak_the_upload(): void
|
||||
{
|
||||
DB::statement("ALTER TABLE audit_events ADD CONSTRAINT qa_no_resource_audit CHECK (source_system NOT IN ('opportunity-resources','portal-opportunity-incident'))");
|
||||
$response = $this->post($this->url(), $this->input(), ['Accept' => 'application/json'])->assertStatus(503)->assertJsonPath('incident_recorded', false);
|
||||
$this->assertTrue(Str::isUuid($response->json('reference')));
|
||||
$this->assertSame(0, $this->incidentCount());
|
||||
$this->assertSame([], Storage::disk('local')->allFiles());
|
||||
$this->assertStringNotContainsString('PRIVATE', $response->getContent());
|
||||
}
|
||||
|
||||
public function test_filtered_rls_visibility_never_authorizes_removal_of_a_referenced_original(): void
|
||||
{
|
||||
$key = 'opportunity-resources/'.Str::uuid();
|
||||
$disk = Storage::disk('local');
|
||||
$disk->put($key, 'SYNTHETIC original behind RLS');
|
||||
DB::table('documents')->insert(['id' => (string) Str::uuid(), 'source_system' => 'opportunity-resources', 'file_name' => 'synthetic-rls.pdf', 'media_type' => 'application/pdf', 'storage_key' => $key, 'sha256' => hash('sha256', 'SYNTHETIC original behind RLS'), 'status' => 'quarantined', 'size_bytes' => 1, 'uploaded_by' => $this->actor->id]);
|
||||
DB::statement('ALTER TABLE documents ENABLE ROW LEVEL SECURITY');
|
||||
DB::statement('ALTER TABLE documents FORCE ROW LEVEL SECURITY');
|
||||
DB::statement('SET LOCAL ROLE pg_read_all_data');
|
||||
try {
|
||||
$this->assertTrue(DB::selectOne("SELECT row_security_active('documents'::regclass) AS active")->active);
|
||||
$this->assertSame(0, DB::table('documents')->where('storage_key', $key)->count());
|
||||
app(OpportunityResourceFileCleanup::class)->afterFailure([$key], new \RuntimeException('SYNTHETIC failure with filtered reference visibility'));
|
||||
$this->assertTrue($disk->exists($key));
|
||||
} finally {
|
||||
DB::statement('RESET ROLE');
|
||||
}
|
||||
$this->assertSame(1, DB::table('documents')->where('storage_key', $key)->count());
|
||||
$this->assertSame('investmoz_test', DB::selectOne('SELECT current_user AS role')->role);
|
||||
}
|
||||
|
||||
private function png(): string
|
||||
{
|
||||
$chunk = fn ($name, $bytes) => pack('N', strlen($bytes)).$name.$bytes.pack('N', crc32($name.$bytes));
|
||||
|
||||
return "\x89PNG\r\n\x1a\n".$chunk('IHDR', pack('NNCCCCC', 500, 500, 8, 2, 0, 0, 0)).$chunk('IDAT', gzcompress(str_repeat("\0", 500 * 1501))).$chunk('IEND', '');
|
||||
}
|
||||
|
||||
public function test_image_upload_and_preparation_failures_have_distinct_labels_and_no_automatic_retry(): void
|
||||
{
|
||||
$input = $this->input();
|
||||
$input['payload'] = ['title' => 'SYNTHETIC image', 'alt_text' => 'SYNTHETIC plain image', 'caption' => 'SYNTHETIC image caption', 'rights_status' => 'owned'];
|
||||
$input['file'] = UploadedFile::fake()->createWithContent('synthetic.png', $this->png());
|
||||
DB::statement("ALTER TABLE audit_events ADD CONSTRAINT qa_image_upload_failure CHECK (source_system <> 'opportunity-resources')");
|
||||
$this->post($this->url('images'), $input, ['Accept' => 'application/json'])->assertStatus(503)->assertJsonPath('incident_recorded', true);
|
||||
DB::statement('ALTER TABLE audit_events DROP CONSTRAINT qa_image_upload_failure');
|
||||
$this->assertSame('upload_image', app(OpportunityTechnicalIncidents::class)->recent($this->actor, $this->opportunity)[0]['operation']);
|
||||
$processor = Mockery::mock(OpportunityImageProcessor::class);
|
||||
$processor->shouldReceive('prepare')->once()->andThrow(new \RuntimeException('PRIVATE SYNTHETIC processor failure'));
|
||||
$this->app->instance(OpportunityImageProcessor::class, $processor);
|
||||
$this->postJson($this->url('images').'/'.Str::uuid().'/prepare', ['etag' => app(OpportunityManagement::class)->etag($this->opportunity), 'version' => 1, 'reason' => 'SYNTHETIC explicit image processing'])->assertStatus(503)->assertJsonPath('incident_recorded', true);
|
||||
$operations = array_column(app(OpportunityTechnicalIncidents::class)->recent($this->actor, $this->opportunity), 'operation');
|
||||
$this->assertContains('prepare_image', $operations);
|
||||
$this->assertContains('upload_image', $operations);
|
||||
$this->assertSame(2, $this->incidentCount());
|
||||
}
|
||||
|
||||
public function test_derivative_partial_storage_failure_preserves_original_and_cleans_new_unreferenced_bytes(): void
|
||||
{
|
||||
if (! app(OpportunityImageProcessor::class)->available()) {
|
||||
$this->postJson($this->url('images').'/'.Str::uuid().'/prepare', ['etag' => app(OpportunityManagement::class)->etag($this->opportunity), 'version' => 1, 'reason' => 'SYNTHETIC unavailable processing'])->assertStatus(423);
|
||||
$this->assertSame(0, $this->incidentCount());
|
||||
|
||||
return;
|
||||
}
|
||||
$input = $this->input();
|
||||
$input['payload'] = ['title' => 'SYNTHETIC image', 'alt_text' => 'SYNTHETIC plain image', 'caption' => 'SYNTHETIC image caption', 'rights_status' => 'owned'];
|
||||
$input['file'] = UploadedFile::fake()->createWithContent('synthetic.png', $this->png());
|
||||
$id = $this->post($this->url('images'), $input, ['Accept' => 'application/json'])->assertCreated()->json('id');
|
||||
$image = DB::table('opportunity_images')->where('id', $id)->first();
|
||||
(new ScanDocumentForMalware($image->document_id))->handle(new CleanScannerFixture);
|
||||
$original = DB::table('documents')->where('id', $image->document_id)->first();
|
||||
$disk = Storage::disk('local');
|
||||
$before = $disk->get($original->storage_key);
|
||||
$opportunityBefore = $this->opportunity->fresh()->getRawOriginal();
|
||||
$fault = Mockery::mock($disk);
|
||||
$fault->shouldReceive('put')->andReturnUsing(function ($key, $bytes) use ($disk) {
|
||||
$disk->put($key, $bytes);
|
||||
|
||||
return false;
|
||||
});
|
||||
Storage::shouldReceive('disk')->with('local')->andReturn($fault);
|
||||
$this->postJson($this->url('images').'/'.$id.'/prepare', ['etag' => app(OpportunityManagement::class)->etag($this->opportunity->fresh()), 'version' => 1, 'reason' => 'SYNTHETIC derivative storage failure'])->assertStatus(503)->assertJsonPath('incident_recorded', true);
|
||||
$this->assertSame([$original->storage_key], $disk->allFiles());
|
||||
$this->assertSame($before, $disk->get($original->storage_key));
|
||||
$this->assertEquals($image, DB::table('opportunity_images')->where('id', $id)->first());
|
||||
$this->assertSame($opportunityBefore, $this->opportunity->fresh()->getRawOriginal());
|
||||
$this->assertSame(1, DB::table('documents')->count());
|
||||
$this->assertSame('prepare_image', app(OpportunityTechnicalIncidents::class)->recent($this->actor, $this->opportunity)[0]['operation']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,422 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Jobs\ScanDocumentForMalware;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\User;
|
||||
use App\Services\Malware\MalwareScanner;
|
||||
use App\Services\OpportunityManagement;
|
||||
use App\Services\OpportunityTechnicalIncidents;
|
||||
use App\Services\PortalProfileAdministration;
|
||||
use Illuminate\Contracts\Encryption\DecryptException;
|
||||
use Illuminate\Contracts\Queue\Job as QueueJob;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\Bus;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Facades\Queue;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use Mockery;
|
||||
use Tests\Support\CleanScannerFixture;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class ScanTechnicalIncidentsTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $actor;
|
||||
|
||||
private User $support;
|
||||
|
||||
private Opportunity $opportunity;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
Http::fake();
|
||||
Mail::fake();
|
||||
Queue::fake();
|
||||
Storage::fake('local');
|
||||
config(['portal.profile_access_enabled' => true, 'suitecrm.enabled' => false, 'investmoz_ai.enabled' => false]);
|
||||
$this->actor = User::factory()->create();
|
||||
$this->support = User::factory()->create();
|
||||
$approver = User::factory()->create();
|
||||
$organization = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $organization, 'name' => 'SYNTHETIC upload QA organization', 'organization_type' => 'private']);
|
||||
DB::table('memberships')->insert(['id' => (string) Str::uuid(), 'user_id' => $this->actor->id, 'organization_id' => $organization, 'role' => 'officer']);
|
||||
foreach ([[$this->actor, 'promoter'], [$this->support, 'technical_support']] as [$user,$role]) {
|
||||
app(PortalProfileAdministration::class)->insertGrant((string) Str::uuid(), $approver, ['user_id' => $user->id, 'role' => $role, 'organization_id' => $organization, 'opportunity_types' => ['investment_project'], 'source' => 'synthetic-resource-incident-fixture']);
|
||||
}
|
||||
$id = (string) Str::uuid();
|
||||
$this->opportunity = new Opportunity(['reference' => $id, 'slug' => $id, 'title' => 'PRIVATE SYNTHETIC upload investment', 'status' => 'draft']);
|
||||
$this->opportunity->forceFill(['owner_user_id' => $this->actor->id, 'organization_id' => $organization, 'opportunity_category' => 'investment_project', 'management_version' => 4, 'workflow_context' => ['working_state' => 'draft']])->save();
|
||||
$this->actingAs($this->actor);
|
||||
}
|
||||
|
||||
private function upload(): array
|
||||
{
|
||||
$input = ['etag' => app(OpportunityManagement::class)->etag($this->opportunity->fresh()), 'creation_key' => (string) Str::uuid(), 'reason' => 'PRIVATE SYNTHETIC scan upload reason', 'payload' => ['title' => 'PRIVATE SYNTHETIC scan original', 'classification' => 'confidential'], 'file' => UploadedFile::fake()->createWithContent('PRIVATE-synthetic.pdf', "%PDF-1.7\nSYNTHETIC scan bytes\n%%EOF")];
|
||||
$id = $this->post('/minhas-oportunidades/'.$this->opportunity->id.'/resources/documents', $input, ['Accept' => 'application/json'])->assertCreated()->json('id');
|
||||
$resource = DB::table('opportunity_documents')->where('id', $id)->first();
|
||||
|
||||
return [$resource, DB::table('documents')->where('id', $resource->document_id)->first()];
|
||||
}
|
||||
|
||||
private function queued(): ScanDocumentForMalware
|
||||
{
|
||||
$captured = null;
|
||||
Queue::assertPushed(ScanDocumentForMalware::class, function ($job) use (&$captured) {
|
||||
$captured = $job;
|
||||
|
||||
return true;
|
||||
});
|
||||
$this->assertInstanceOf(ScanDocumentForMalware::class, $captured);
|
||||
|
||||
return $captured;
|
||||
}
|
||||
|
||||
private function scannerResult(string $state = 'clean'): array
|
||||
{
|
||||
return ['result' => $state, 'reason_code' => match ($state) {
|
||||
'clean' => null, 'infected' => 'threat_detected', default => 'scanner_unavailable'
|
||||
}, 'engine' => 'QA-Test-Double', 'engine_version' => 'fixture', 'signatures_at' => null, 'duration_ms' => 1, 'detail' => 'PRIVATE SYNTHETIC engine detail'];
|
||||
}
|
||||
|
||||
private function scanner(\Closure $callback): MalwareScanner
|
||||
{
|
||||
return new class($callback) implements MalwareScanner
|
||||
{
|
||||
public function __construct(private \Closure $callback) {}
|
||||
|
||||
public function scan(string $path, int $fileSizeBytes, string $storageRoot): array
|
||||
{
|
||||
return ($this->callback)($path, $fileSizeBytes, $storageRoot);
|
||||
}
|
||||
|
||||
public function health(): array
|
||||
{
|
||||
return ['available' => true, 'engine' => 'QA-Test-Double', 'engine_version' => 'fixture', 'signatures_at' => null, 'signature_age_hours' => null, 'reason_code' => null];
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private function roots(): int
|
||||
{
|
||||
return DB::table('audit_events')->where('source_system', 'portal-opportunity-incident')->count();
|
||||
}
|
||||
|
||||
private function freshJob(ScanDocumentForMalware $job): ScanDocumentForMalware
|
||||
{
|
||||
return unserialize(serialize($job), ['allowed_classes' => [ScanDocumentForMalware::class]]);
|
||||
}
|
||||
|
||||
private function delivery(int $attempt, string $uuid): QueueJob
|
||||
{
|
||||
$job = Mockery::mock(QueueJob::class);
|
||||
$job->shouldReceive('attempts')->andReturn($attempt);
|
||||
$job->shouldReceive('uuid')->andReturn($uuid);
|
||||
|
||||
return $job;
|
||||
}
|
||||
|
||||
public function test_dispatch_failure_keeps_the_saved_resource_and_notifies_without_impersonating_the_initiator(): void
|
||||
{
|
||||
Bus::shouldReceive('dispatch')->once()->with(Mockery::type(ScanDocumentForMalware::class))->andThrow(new \RuntimeException('PRIVATE queue credentials and body'));
|
||||
[$resource,$document] = $this->upload();
|
||||
$this->assertSame(1, DB::table('documents')->count());
|
||||
$this->assertSame(5, $this->opportunity->fresh()->management_version);
|
||||
$this->assertSame('failed', $document->malware_scan_status);
|
||||
$this->assertSame('quarantined', $document->status);
|
||||
$this->assertStringContainsString('SYNTHETIC scan bytes', Crypt::decryptString(Storage::disk('local')->get($document->storage_key)));
|
||||
$event = DB::table('audit_events')->where('source_system', 'portal-opportunity-incident')->first();
|
||||
$data = json_decode($event->after_data, true)['incident'];
|
||||
$this->assertNull($event->actor_user_id);
|
||||
$this->assertSame($this->actor->id, $data['reported_for_user_id']);
|
||||
$this->assertSame('scan_dispatch_unconfirmed', $data['error_code']);
|
||||
$this->assertSame('scan_document', $data['operation']);
|
||||
$this->assertSame(5, $data['observed_version']);
|
||||
$this->assertStringNotContainsString('PRIVATE', $event->after_data);
|
||||
$this->assertSame('scan_document', app(OpportunityTechnicalIncidents::class)->recent($this->actor, $this->opportunity->fresh())[0]['operation']);
|
||||
$this->actingAs($this->support)->get('/suporte-tecnico/incidentes?unread=1')->assertOk()->assertInertia(fn (Assert $page) => $page->where('incidents.total', 1)->where('incidents.data.0.error_code', 'scan_dispatch_unconfirmed'));
|
||||
$this->get('/minhas-oportunidades/'.$this->opportunity->id.'/resources')->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_an_uncertain_dispatch_after_a_sync_result_never_quarantines_an_already_clean_document(): void
|
||||
{
|
||||
Bus::shouldReceive('dispatch')->once()->with(Mockery::type(ScanDocumentForMalware::class))->andReturnUsing(function ($job) {
|
||||
$job->handle(new CleanScannerFixture);
|
||||
throw new \RuntimeException('PRIVATE dispatch acknowledgement lost');
|
||||
});
|
||||
[$resource,$document] = $this->upload();
|
||||
$this->assertSame('clean', $document->malware_scan_status);
|
||||
$this->assertSame('active', $document->status);
|
||||
$this->assertSame(trim($document->sha256), $document->malware_scanned_sha256);
|
||||
$this->assertSame(1, DB::table('document_malware_scans')->count());
|
||||
$this->assertSame(1, $this->roots());
|
||||
$this->assertSame(5, $this->opportunity->fresh()->management_version);
|
||||
}
|
||||
|
||||
public function test_dispatch_is_deferred_until_commit_and_a_rollback_never_enqueues_the_resource(): void
|
||||
{
|
||||
DB::beginTransaction();
|
||||
$this->upload();
|
||||
Queue::assertNothingPushed();
|
||||
DB::rollBack();
|
||||
$this->assertSame(0, DB::table('documents')->count());
|
||||
$this->assertSame(0, $this->roots());
|
||||
DB::beginTransaction();
|
||||
$this->upload();
|
||||
Queue::assertNothingPushed();
|
||||
DB::commit();
|
||||
$job = $this->queued();
|
||||
$this->assertSame($this->actor->id, $job->opportunityContext['reported_for_user_id']);
|
||||
$this->assertSame(5, $job->opportunityContext['observed_version']);
|
||||
$this->assertSame(0, $this->roots());
|
||||
}
|
||||
|
||||
public function test_inconclusive_scan_is_quarantined_has_one_system_incident_and_replay_does_not_rescan(): void
|
||||
{
|
||||
[$resource,$document] = $this->upload();
|
||||
$job = $this->queued();
|
||||
$before = Storage::disk('local')->get($document->storage_key);
|
||||
$business = $this->opportunity->fresh()->getRawOriginal();
|
||||
$calls = 0;
|
||||
$scanner = $this->scanner(function () use (&$calls) {
|
||||
$calls++;
|
||||
|
||||
return $this->scannerResult('inconclusive');
|
||||
});
|
||||
$job->handle($scanner);
|
||||
$this->freshJob($job)->handle($scanner);
|
||||
$job->failed(new \RuntimeException('PRIVATE late failure'));
|
||||
$current = DB::table('documents')->where('id', $document->id)->first();
|
||||
$this->assertSame(1, $calls);
|
||||
$this->assertSame('inconclusive', $current->malware_scan_status);
|
||||
$this->assertSame('quarantined', $current->status);
|
||||
$this->assertSame(1, $current->malware_scan_attempts);
|
||||
$this->assertSame(1, DB::table('document_malware_scans')->count());
|
||||
$this->assertSame(1, $this->roots());
|
||||
$this->assertSame($before, Storage::disk('local')->get($document->storage_key));
|
||||
$this->assertSame([$document->storage_key], Storage::disk('local')->allFiles());
|
||||
$this->assertSame($business, $this->opportunity->fresh()->getRawOriginal());
|
||||
$root = DB::table('audit_events')->where('id', $job->runIdentifier())->first();
|
||||
$data = json_decode($root->after_data, true)['incident'];
|
||||
$this->assertNull($root->actor_user_id);
|
||||
$this->assertSame('scan_inconclusive', $data['error_code']);
|
||||
$this->assertStringNotContainsString('PRIVATE', $root->after_data);
|
||||
app(OpportunityTechnicalIncidents::class)->recordScan($job->opportunityContext, $job->runIdentifier(), 'scan_worker_failed');
|
||||
$this->assertEquals($root, DB::table('audit_events')->where('id', $job->runIdentifier())->first());
|
||||
$this->get('/minhas-oportunidades/'.$this->opportunity->id.'/resources/documents/'.$resource->id.'/download')->assertStatus(423);
|
||||
}
|
||||
|
||||
public function test_a_late_inconclusive_result_cannot_replace_a_newer_clean_scan(): void
|
||||
{
|
||||
[$resource,$document] = $this->upload();
|
||||
$old = $this->queued();
|
||||
$new = new ScanDocumentForMalware($document->id, $old->opportunityContext);
|
||||
$old->handle($this->scanner(function () use ($new) {
|
||||
$new->handle(new CleanScannerFixture);
|
||||
|
||||
return $this->scannerResult('inconclusive');
|
||||
}));
|
||||
$current = DB::table('documents')->where('id', $document->id)->first();
|
||||
$this->assertSame('clean', $current->malware_scan_status);
|
||||
$this->assertSame('active', $current->status);
|
||||
$this->assertSame(2, $current->malware_scan_attempts);
|
||||
$this->assertSame(trim($current->sha256), $current->malware_scanned_sha256);
|
||||
$this->assertSame(1, DB::table('document_malware_scans')->count());
|
||||
$this->assertSame(0, $this->roots());
|
||||
$this->assertSame(1, DB::table('audit_events')->where('action', 'scan_result_discarded')->where('correlation_id', $old->runIdentifier())->count());
|
||||
$this->freshJob($old)->failed(new \RuntimeException('PRIVATE old failure'));
|
||||
$this->assertEquals($current, DB::table('documents')->where('id', $document->id)->first());
|
||||
}
|
||||
|
||||
public function test_same_queue_execution_different_deliveries_cannot_apply_an_old_failure_to_the_current_attempt(): void
|
||||
{
|
||||
[$resource,$document] = $this->upload();
|
||||
$old = $this->queued();
|
||||
$fresh = $this->freshJob($old);
|
||||
$retry = $this->freshJob($old);
|
||||
$uuid = (string) Str::uuid();
|
||||
$old->setJob($this->delivery(1, $uuid));
|
||||
$fresh->setJob($this->delivery(1, $uuid));
|
||||
$retry->setJob($this->delivery(2, $uuid));
|
||||
$old->handle($this->scanner(function () use ($retry, $fresh, $document) {
|
||||
try {
|
||||
$retry->handle($this->scanner(fn () => throw new \RuntimeException('PRIVATE current worker failed')));
|
||||
} catch (\RuntimeException $error) {
|
||||
$this->assertSame('PRIVATE current worker failed', $error->getMessage());
|
||||
}
|
||||
$fresh->failed(new \RuntimeException('PRIVATE previous delivery failure'));
|
||||
$this->assertSame('scanning', DB::table('documents')->where('id', $document->id)->value('malware_scan_status'));
|
||||
$this->assertSame(0, $this->roots());
|
||||
$retry->failed(new \RuntimeException('PRIVATE current terminal failure'));
|
||||
|
||||
return $this->scannerResult('clean');
|
||||
}));
|
||||
$this->assertSame('failed', DB::table('documents')->where('id', $document->id)->value('malware_scan_status'));
|
||||
$this->assertSame(2, DB::table('documents')->where('id', $document->id)->value('malware_scan_attempts'));
|
||||
$this->assertSame(1, DB::table('document_malware_scans')->count());
|
||||
$this->assertSame(1, $this->roots());
|
||||
}
|
||||
|
||||
public function test_infected_result_and_its_original_are_preserved_against_late_callbacks_and_queued_jobs(): void
|
||||
{
|
||||
[$resource,$document] = $this->upload();
|
||||
$job = $this->queued();
|
||||
$before = Storage::disk('local')->get($document->storage_key);
|
||||
$job->handle($this->scanner(fn () => $this->scannerResult('infected')));
|
||||
$current = DB::table('documents')->where('id', $document->id)->first();
|
||||
$this->freshJob($job)->failed(new \RuntimeException('PRIVATE stale failure'));
|
||||
(new ScanDocumentForMalware($document->id, $job->opportunityContext))->handle($this->scanner(fn () => throw new \RuntimeException('Scanner must not be called for infected bytes')));
|
||||
$this->assertEquals($current, DB::table('documents')->where('id', $document->id)->first());
|
||||
$this->assertSame('infected', $current->malware_scan_status);
|
||||
$this->assertSame('quarantined', $current->status);
|
||||
$this->assertSame($before, Storage::disk('local')->get($document->storage_key));
|
||||
$this->assertSame(0, $this->roots());
|
||||
$this->assertSame(1, DB::table('document_malware_scans')->count());
|
||||
}
|
||||
|
||||
public function test_document_record_changes_during_scan_are_inconclusive_and_history_keeps_the_attempted_hash(): void
|
||||
{
|
||||
[$resource,$document] = $this->upload();
|
||||
$job = $this->queued();
|
||||
$before = Storage::disk('local')->get($document->storage_key);
|
||||
$job->handle($this->scanner(function () use ($document) {
|
||||
DB::table('documents')->where('id', $document->id)->update(['sha256' => str_repeat('b', 64)]);
|
||||
|
||||
return $this->scannerResult('clean');
|
||||
}));
|
||||
$current = DB::table('documents')->where('id', $document->id)->first();
|
||||
$this->assertSame('inconclusive', $current->malware_scan_status);
|
||||
$this->assertSame('document_record_changed_during_scan', $current->malware_failure_reason);
|
||||
$this->assertNull($current->malware_scanned_sha256);
|
||||
$this->assertSame(trim($document->sha256), DB::table('document_malware_scans')->value('file_sha256'));
|
||||
$this->assertSame($before, Storage::disk('local')->get($document->storage_key));
|
||||
$this->assertSame('scan_inconclusive', json_decode(DB::table('audit_events')->where('id', $job->runIdentifier())->value('after_data'), true)['incident']['error_code']);
|
||||
}
|
||||
|
||||
public function test_fresh_serialized_failure_callback_owns_only_its_attempt_and_an_explicit_retry_remains_possible(): void
|
||||
{
|
||||
[$resource,$document] = $this->upload();
|
||||
$job = $this->queued();
|
||||
$fresh = $this->freshJob($job);
|
||||
try {
|
||||
$job->handle($this->scanner(fn () => throw new \RuntimeException('PRIVATE engine failure')));
|
||||
} catch (\RuntimeException $error) {
|
||||
$this->assertSame('PRIVATE engine failure', $error->getMessage());
|
||||
}
|
||||
$fresh->failed(new \RuntimeException('PRIVATE terminal failure'));
|
||||
$fresh->failed(new \RuntimeException('PRIVATE duplicate callback'));
|
||||
$this->assertSame('failed', DB::table('documents')->where('id', $document->id)->value('malware_scan_status'));
|
||||
$this->assertSame(1, $this->roots());
|
||||
$this->assertSame(1, DB::table('document_malware_scans')->count());
|
||||
$fresh->handle(new CleanScannerFixture);
|
||||
$this->assertSame('clean', DB::table('documents')->where('id', $document->id)->value('malware_scan_status'));
|
||||
$this->assertSame(2, DB::table('document_malware_scans')->count());
|
||||
$this->assertSame(1, $this->roots());
|
||||
}
|
||||
|
||||
public function test_legacy_serialized_payload_uses_the_real_queue_uuid_in_a_fresh_failure_callback(): void
|
||||
{
|
||||
[$resource,$document] = $this->upload();
|
||||
$class = ScanDocumentForMalware::class;
|
||||
$payload = 'O:'.strlen($class).':"'.$class.'":1:{s:10:"documentId";s:36:"'.$document->id.'";}';
|
||||
$job = unserialize($payload, ['allowed_classes' => [$class]]);
|
||||
$fresh = unserialize($payload, ['allowed_classes' => [$class]]);
|
||||
$uuid = (string) Str::uuid();
|
||||
$this->assertInstanceOf($class, $job);
|
||||
$this->assertNull($job->executionId);
|
||||
$job->setJob($this->delivery(1, $uuid));
|
||||
$fresh->setJob($this->delivery(1, $uuid));
|
||||
try {
|
||||
$job->handle($this->scanner(fn () => throw new \RuntimeException('SYNTHETIC legacy worker failure')));
|
||||
} catch (\RuntimeException) {
|
||||
}
|
||||
$fresh->failed(new \RuntimeException('SYNTHETIC legacy terminal callback'));
|
||||
$this->assertSame($uuid, $fresh->runIdentifier());
|
||||
$this->assertSame('failed', DB::table('documents')->where('id', $document->id)->value('malware_scan_status'));
|
||||
$this->assertSame(0, $this->roots());
|
||||
}
|
||||
|
||||
public function test_captured_organization_is_not_replaced_when_the_opportunity_moves_before_the_worker_runs(): void
|
||||
{
|
||||
[$resource,$document] = $this->upload();
|
||||
$job = $this->queued();
|
||||
$captured = $job->opportunityContext;
|
||||
$other = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $other, 'name' => 'SYNTHETIC other scan organization', 'organization_type' => 'private']);
|
||||
$this->opportunity->forceFill(['organization_id' => $other])->save();
|
||||
$job->handle($this->scanner(fn () => $this->scannerResult('inconclusive')));
|
||||
$data = json_decode(DB::table('audit_events')->where('id', $job->runIdentifier())->value('after_data'), true)['incident'];
|
||||
$this->assertSame($captured['organization_id'], $data['organization_id']);
|
||||
app(PortalProfileAdministration::class)->insertGrant((string) Str::uuid(), $this->actor, ['user_id' => $this->support->id, 'role' => 'technical_support', 'organization_id' => $other, 'opportunity_types' => ['investment_project']]);
|
||||
$this->actingAs($this->support)->get('/suporte-tecnico/incidentes')->assertOk()->assertInertia(fn (Assert $page) => $page->where('incidents.total', 0)->where('profileAccess.technicalSupportUnread', 0));
|
||||
$this->assertSame(1, $this->roots());
|
||||
}
|
||||
|
||||
public function test_incident_persistence_failure_does_not_release_the_document_or_fail_a_completed_inconclusive_scan(): void
|
||||
{
|
||||
[$resource,$document] = $this->upload();
|
||||
$job = $this->queued();
|
||||
DB::statement("ALTER TABLE audit_events ADD CONSTRAINT qa_reject_scan_incident CHECK (source_system <> 'portal-opportunity-incident')");
|
||||
$job->handle($this->scanner(fn () => $this->scannerResult('inconclusive')));
|
||||
$this->assertSame('quarantined', DB::table('documents')->where('id', $document->id)->value('status'));
|
||||
$this->assertSame('inconclusive', DB::table('documents')->where('id', $document->id)->value('malware_scan_status'));
|
||||
$this->assertSame(1, DB::table('document_malware_scans')->count());
|
||||
$this->assertSame(0, $this->roots());
|
||||
}
|
||||
|
||||
public function test_generic_document_jobs_do_not_invent_an_opportunity_recipient(): void
|
||||
{
|
||||
[$resource,$document] = $this->upload();
|
||||
$job = new ScanDocumentForMalware($document->id);
|
||||
$job->handle($this->scanner(fn () => $this->scannerResult('inconclusive')));
|
||||
$this->assertSame(0, $this->roots());
|
||||
$this->assertSame('inconclusive', DB::table('documents')->where('id', $document->id)->value('malware_scan_status'));
|
||||
}
|
||||
|
||||
public function test_a_fresh_terminal_callback_preserves_the_attempted_byte_descriptor_after_a_record_change(): void
|
||||
{
|
||||
[$resource,$document] = $this->upload();
|
||||
$job = $this->queued();
|
||||
$fresh = $this->freshJob($job);
|
||||
try {
|
||||
$job->handle($this->scanner(fn () => throw new \RuntimeException('SYNTHETIC worker interrupted')));
|
||||
} catch (\RuntimeException) {
|
||||
}
|
||||
DB::table('documents')->where('id', $document->id)->update(['sha256' => str_repeat('b', 64), 'size_bytes' => 999]);
|
||||
$fresh->failed(new \RuntimeException('SYNTHETIC terminal callback after record change'));
|
||||
$result = DB::table('document_malware_scans')->first();
|
||||
$this->assertSame(trim($document->sha256), $result->file_sha256);
|
||||
$this->assertSame($document->size_bytes, $result->file_size_bytes);
|
||||
$this->assertSame('inconclusive', $result->result);
|
||||
$this->assertSame('document_record_changed_during_scan', $result->reason_code);
|
||||
$this->assertSame('quarantined', DB::table('documents')->where('id', $document->id)->value('status'));
|
||||
$this->assertSame('unknown', $result->engine);
|
||||
}
|
||||
|
||||
public function test_failed_decryption_cleans_its_temporary_file_and_retains_the_original_and_attempt_context(): void
|
||||
{
|
||||
[$resource,$document] = $this->upload();
|
||||
$job = $this->queued();
|
||||
Storage::disk('local')->put($document->storage_key, 'PRIVATE SYNTHETIC invalid envelope');
|
||||
try {
|
||||
$job->handle(new CleanScannerFixture);
|
||||
$this->fail('Invalid envelope must not be scanned as clean.');
|
||||
} catch (DecryptException) {
|
||||
}
|
||||
$this->freshJob($job)->failed(new \RuntimeException('PRIVATE terminal decryption failure'));
|
||||
$this->assertSame([$document->storage_key], Storage::disk('local')->allFiles());
|
||||
$this->assertSame('PRIVATE SYNTHETIC invalid envelope', Storage::disk('local')->get($document->storage_key));
|
||||
$this->assertSame('failed', DB::table('documents')->where('id', $document->id)->value('malware_scan_status'));
|
||||
$this->assertSame(1, $this->roots());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\User;
|
||||
use App\Services\OpportunityTechnicalIncidents;
|
||||
use App\Services\OpportunityTechnicalSupport;
|
||||
use App\Services\PortalProfileAccess;
|
||||
use App\Services\PortalProfileAdministration;
|
||||
use App\Services\TechnicalIncidentHandling;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Str;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class SupportIncidentNoticesTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $support;
|
||||
|
||||
private User $colleague;
|
||||
|
||||
private User $reporter;
|
||||
|
||||
private Opportunity $opportunity;
|
||||
|
||||
private string $reference;
|
||||
|
||||
private string $organization;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
Http::fake();
|
||||
Mail::fake();
|
||||
config(['portal.profile_access_enabled' => true, 'suitecrm.enabled' => false, 'investmoz_ai.enabled' => false]);
|
||||
$approver = User::factory()->create();
|
||||
$this->support = User::factory()->create(['name' => 'SYNTHETIC first support']);
|
||||
$this->colleague = User::factory()->create(['name' => 'SYNTHETIC second support']);
|
||||
$this->reporter = User::factory()->create();
|
||||
$this->organization = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $this->organization, 'name' => 'SYNTHETIC incident organization', 'organization_type' => 'private']);
|
||||
foreach ([$this->support, $this->colleague, $this->reporter] as $actor) {
|
||||
app(PortalProfileAdministration::class)->insertGrant((string) Str::uuid(), $approver, ['user_id' => $actor->id, 'role' => $actor === $this->reporter ? 'promoter' : 'technical_support', 'organization_id' => $this->organization, 'opportunity_types' => ['investment_project'], 'source' => 'synthetic-support-treatment-fixture']);
|
||||
}
|
||||
DB::table('memberships')->insert(['id' => (string) Str::uuid(), 'user_id' => $this->reporter->id, 'organization_id' => $this->organization, 'role' => 'officer']);
|
||||
$id = (string) Str::uuid();
|
||||
$this->opportunity = new Opportunity(['title' => 'PRIVATE SYNTHETIC INVESTMENT', 'reference' => $id, 'slug' => $id, 'status' => 'draft']);
|
||||
$this->opportunity->forceFill(['owner_user_id' => $this->reporter->id, 'organization_id' => $this->organization, 'opportunity_category' => 'investment_project', 'management_version' => 4, 'workflow_context' => ['working_state' => 'draft', 'content_revision' => 3]])->save();
|
||||
// Synthetic root metadata fixture. Real failing HTTP submission/publication is covered by OpportunityTechnicalIncidentsTest.
|
||||
$this->reference = app(OpportunityTechnicalIncidents::class)->record($this->reporter, $this->opportunity, 'submit', str_repeat('a', 64), new \RuntimeException('PRIVATE SYNTHETIC FAILURE'))['reference'];
|
||||
$this->actingAs($this->support);
|
||||
}
|
||||
|
||||
private function url(): string
|
||||
{
|
||||
return '/suporte-tecnico/incidentes/'.$this->reference.'/consultado';
|
||||
}
|
||||
|
||||
private function notices(): int
|
||||
{
|
||||
return DB::table('audit_events')->where('source_system', 'portal-opportunity-support-notices')->count();
|
||||
}
|
||||
|
||||
public function test_own_consultation_is_private_idempotent_and_changes_neither_treatment_nor_business(): void
|
||||
{
|
||||
$before = $this->opportunity->fresh()->getRawOriginal();
|
||||
$root = DB::table('audit_events')->where('id', $this->reference)->first();
|
||||
$grantCount = DB::table('portal_role_assignments')->count();
|
||||
$this->get('/suporte-tecnico/incidentes')->assertOk()->assertHeader('Cache-Control', 'no-store, private')->assertInertia(fn (Assert $page) => $page->where('profileAccess.technicalSupportUnread', 1)->where('incidents.data.0.unread', true));
|
||||
$this->get('/suporte-tecnico/incidentes/'.$this->reference)->assertOk()->assertInertia(fn (Assert $page) => $page->where('notice.unread', true));
|
||||
$this->assertSame(0, $this->notices());
|
||||
$first = $this->postJson($this->url(), ['actor_id' => $this->colleague->id])->assertOk()->assertHeader('Cache-Control', 'no-store, private')->assertJsonPath('actor_id', $this->support->id)->assertJsonPath('read', true)->json();
|
||||
$this->postJson($this->url())->assertOk()->assertExactJson($first);
|
||||
$this->assertSame(1, $this->notices());
|
||||
$this->get('/suporte-tecnico/incidentes?unread=1')->assertInertia(fn (Assert $page) => $page->where('incidents.total', 0)->where('profileAccess.technicalSupportUnread', 0));
|
||||
$this->get('/suporte-tecnico/incidentes/'.$this->reference)->assertInertia(fn (Assert $page) => $page->where('notice.unread', false)->where('incident.handling.version', 0)->has('history.data', 0)->has('commands', 0));
|
||||
$this->actingAs($this->colleague)->get('/suporte-tecnico/incidentes?unread=1')->assertInertia(fn (Assert $page) => $page->where('incidents.total', 1)->where('incidents.data.0.unread', true)->where('profileAccess.technicalSupportUnread', 1));
|
||||
$this->assertEquals($root, DB::table('audit_events')->where('id', $this->reference)->first());
|
||||
$this->assertSame($before, $this->opportunity->fresh()->getRawOriginal());
|
||||
$this->assertSame($grantCount, DB::table('portal_role_assignments')->count());
|
||||
$this->assertSame(0, DB::table('tasks')->count());
|
||||
}
|
||||
|
||||
public function test_unread_filter_runs_before_pagination_and_preserves_status_and_return_context(): void
|
||||
{
|
||||
$support = app(OpportunityTechnicalSupport::class);
|
||||
for ($i = 0; $i < 24; $i++) {
|
||||
$reference = app(OpportunityTechnicalIncidents::class)->record($this->reporter, $this->opportunity, 'submit', str_repeat('a', 64), new \RuntimeException('SYNTHETIC recent root'))['reference'];
|
||||
$support->markConsulted($this->support, $reference);
|
||||
}
|
||||
app(TechnicalIncidentHandling::class)->decide($this->support, $this->reference, ['version' => 0, 'action' => 'resolve', 'note' => 'SYNTHETIC explicit technical resolution', 'operation_key' => (string) Str::uuid()]);
|
||||
$this->get('/suporte-tecnico/incidentes?unread=1&status=resolved')->assertOk()->assertInertia(fn (Assert $page) => $page->where('incidents.total', 1)->where('incidents.data.0.reference', $this->reference)->where('incidents.data.0.handling.status', 'resolved')->where('filters.unread', true));
|
||||
$this->get('/suporte-tecnico/incidentes/'.$this->reference.'?unread=1&status=resolved&page=2')->assertInertia(fn (Assert $page) => $page->where('backUrl', '/suporte-tecnico/incidentes?page=2&status=resolved&unread=1')->where('notice.unread', true));
|
||||
$this->postJson($this->url())->assertOk();
|
||||
$this->assertSame(0, $support->unreadCount($this->support));
|
||||
$this->get('/suporte-tecnico/incidentes?unread=1&status=resolved')->assertInertia(fn (Assert $page) => $page->where('incidents.total', 0));
|
||||
$this->getJson('/suporte-tecnico/incidentes?unread=invalid')->assertUnprocessable();
|
||||
}
|
||||
|
||||
public function test_current_scope_revocation_expiry_and_auditor_precedence_apply_to_notices(): void
|
||||
{
|
||||
$support = app(OpportunityTechnicalSupport::class);
|
||||
$this->opportunity->forceFill(['opportunity_category' => 'real_estate'])->save();
|
||||
$this->assertSame(0, $support->unreadCount($this->support));
|
||||
$this->postJson($this->url())->assertNotFound();
|
||||
$this->opportunity->forceFill(['opportunity_category' => 'investment_project', 'organization_id' => null])->save();
|
||||
$this->assertSame(0, $support->unreadCount($this->support));
|
||||
$this->postJson($this->url())->assertNotFound();
|
||||
$this->opportunity->forceFill(['organization_id' => $this->organization])->save();
|
||||
DB::table('portal_role_assignments')->where('user_id', $this->support->id)->update(['starts_at' => now()->subDay(), 'expires_at' => now()->subMinute()]);
|
||||
$this->postJson($this->url())->assertForbidden();
|
||||
DB::table('portal_role_assignments')->where('user_id', $this->support->id)->update(['expires_at' => null, 'revoked_at' => now()]);
|
||||
$this->postJson($this->url())->assertForbidden();
|
||||
DB::table('portal_role_assignments')->where('user_id', $this->support->id)->update(['revoked_at' => null]);
|
||||
app(PortalProfileAdministration::class)->insertGrant((string) Str::uuid(), $this->reporter, ['user_id' => $this->support->id, 'role' => 'auditor', 'opportunity_types' => ['investment_project']]);
|
||||
$this->postJson($this->url())->assertForbidden();
|
||||
$this->assertNull(app(PortalProfileAccess::class)->navigation($this->support)['technicalSupport']);
|
||||
$this->assertNull(app(PortalProfileAccess::class)->navigation($this->support)['technicalSupportUnread']);
|
||||
$this->assertSame(0, $this->notices());
|
||||
}
|
||||
|
||||
public function test_overlapping_grants_count_each_root_once_and_legacy_management_is_not_support(): void
|
||||
{
|
||||
app(PortalProfileAdministration::class)->insertGrant((string) Str::uuid(), $this->reporter, ['user_id' => $this->support->id, 'role' => 'technical_support', 'opportunity_types' => ['investment_project']]);
|
||||
$this->assertSame(1, app(OpportunityTechnicalSupport::class)->unreadCount($this->support));
|
||||
config(['portal.managers' => [$this->reporter->email]]);
|
||||
$this->actingAs($this->reporter)->postJson($this->url())->assertForbidden();
|
||||
$this->assertNull(app(PortalProfileAccess::class)->navigation($this->reporter)['technicalSupportUnread']);
|
||||
$this->actingAs($this->support);
|
||||
$this->support->forceFill(['email_verified_at' => null])->save();
|
||||
$this->postJson($this->url())->assertForbidden();
|
||||
$this->assertSame(0, $this->notices());
|
||||
}
|
||||
|
||||
public function test_failed_acknowledgement_rolls_back_and_explicit_retry_can_confirm_once(): void
|
||||
{
|
||||
DB::statement("ALTER TABLE audit_events ADD CONSTRAINT qa_reject_notice CHECK (source_system <> 'portal-opportunity-support-notices')");
|
||||
$this->postJson($this->url())->assertStatus(503);
|
||||
$this->assertSame(0, $this->notices());
|
||||
$this->assertSame(1, app(OpportunityTechnicalSupport::class)->unreadCount($this->support));
|
||||
DB::statement('ALTER TABLE audit_events DROP CONSTRAINT qa_reject_notice');
|
||||
$this->postJson($this->url())->assertOk();
|
||||
$this->postJson($this->url())->assertOk();
|
||||
$this->assertSame(1, $this->notices());
|
||||
}
|
||||
|
||||
public function test_optional_count_failure_does_not_poison_the_callers_transaction(): void
|
||||
{
|
||||
DB::statement('ALTER TABLE audit_events RENAME COLUMN actor_user_id TO qa_missing_notice_actor');
|
||||
$this->assertNull(app(OpportunityTechnicalSupport::class)->unreadCount($this->support));
|
||||
$this->assertGreaterThan(0, DB::table('users')->count());
|
||||
DB::statement('ALTER TABLE audit_events RENAME COLUMN qa_missing_notice_actor TO actor_user_id');
|
||||
$this->assertSame(1, app(OpportunityTechnicalSupport::class)->unreadCount($this->support));
|
||||
}
|
||||
|
||||
public function test_invalid_treatment_does_not_prevent_consultation_or_expose_other_actors_read_state(): void
|
||||
{
|
||||
DB::table('audit_events')->insert(['id' => (string) Str::uuid(), 'source_system' => 'portal-opportunity-support', 'entity_type' => 'opportunity-technical-incident', 'entity_id' => $this->reference, 'action' => 'incident_handled', 'after_data' => json_encode(['handling' => ['version' => 1, 'status' => 'invalid']], JSON_THROW_ON_ERROR)]);
|
||||
$this->get('/suporte-tecnico/incidentes?unread=1')->assertOk()->assertInertia(fn (Assert $page) => $page->where('incidents.data.0.handling', null)->where('incidents.data.0.unread', true));
|
||||
$this->postJson($this->url())->assertOk();
|
||||
$recent = app(OpportunityTechnicalIncidents::class)->recent($this->reporter, $this->opportunity)[0];
|
||||
$this->assertArrayNotHasKey('unread', $recent);
|
||||
$this->assertArrayNotHasKey('read_at', $recent);
|
||||
$this->assertSame(1, app(OpportunityTechnicalSupport::class)->unreadCount($this->colleague));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\User;
|
||||
use App\Services\OpportunityTechnicalSupport;
|
||||
use App\Services\PortalProfileAdministration;
|
||||
use App\Services\PortalProfileInstallation;
|
||||
use App\Services\TechnicalSupportProfileSchema;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class SupportProfileInstallationTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private const URL = '/management/profile-install/technical-support';
|
||||
|
||||
private User $admin;
|
||||
|
||||
private User $second;
|
||||
|
||||
private User $staff;
|
||||
|
||||
private string $directory;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
Http::fake();
|
||||
Mail::fake();
|
||||
$this->admin = $this->actor();
|
||||
$this->second = $this->actor();
|
||||
$this->staff = $this->actor();
|
||||
DB::table('portal_superuser_pair')->insert(['id' => 1, 'first_user_id' => $this->admin->id, 'second_user_id' => $this->second->id, 'approved_by' => $this->second->id, 'version' => 1, 'created_at' => now(), 'updated_at' => now()]);
|
||||
$this->directory = storage_path('framework/testing/support-profile-install-'.Str::uuid());
|
||||
mkdir($this->directory, 0700, true);
|
||||
config(['portal_profiles.proof_directory' => $this->directory, 'portal.profile_access_enabled' => true, 'portal.managers' => [$this->admin->email, $this->staff->email], 'suitecrm.enabled' => false, 'investmoz_ai.enabled' => false]);
|
||||
$this->login($this->admin);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
foreach (glob($this->directory.'/*') ?: [] as $file) {
|
||||
unlink($file);
|
||||
}rmdir($this->directory);
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
private function actor(): User
|
||||
{
|
||||
return User::factory()->create(['two_factor_secret' => Crypt::encryptString('JBSWY3DPEHPK3PXP'), 'two_factor_confirmed_at' => now()]);
|
||||
}
|
||||
|
||||
private function login(User $actor, bool $mfa = true): static
|
||||
{
|
||||
return $this->actingAs($actor)->withSession(['portal.mfa_actor' => $mfa ? $actor->id : null, 'portal.mfa_at' => $mfa ? time() : 0, 'portal.access_revision' => (int) $actor->fresh()->portal_access_revision]);
|
||||
}
|
||||
|
||||
private function beforeSupport(bool $keepLedger = false): void
|
||||
{
|
||||
(require database_path('migrations/'.TechnicalSupportProfileSchema::MIGRATION.'.php'))->down();
|
||||
if (! $keepLedger) {
|
||||
DB::table('migrations')->where('migration', TechnicalSupportProfileSchema::MIGRATION)->delete();
|
||||
}
|
||||
}
|
||||
|
||||
/** Synthetic files validate the existing readiness contract; these are not real deployment backups. @return array<string,mixed> */
|
||||
private function proof(): array
|
||||
{
|
||||
file_put_contents($this->directory.'/dump', 'SYNTHETIC contract fixture, not a database dump.');
|
||||
file_put_contents($this->directory.'/files', 'SYNTHETIC contract fixture, not a private-file archive.');
|
||||
$proof = ['verified_at' => gmdate('c'), 'target' => DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port'), 'code_hash' => app(PortalProfileInstallation::class)->fingerprint(), 'restore_verified' => true, 'files_verified' => true, 'compatibility_verified' => true, 'qa_passed' => true, 'dump_path' => $this->directory.'/dump', 'dump_sha256' => hash_file('sha256', $this->directory.'/dump'), 'files_path' => $this->directory.'/files', 'files_sha256' => hash_file('sha256', $this->directory.'/files')];
|
||||
$this->writeProof($proof);
|
||||
|
||||
return $proof;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $proof */
|
||||
private function writeProof(array $proof): void
|
||||
{
|
||||
file_put_contents($this->directory.'/readiness.json', json_encode($proof, JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function input(): array
|
||||
{
|
||||
return ['hash' => $this->getJson(self::URL)->assertOk()->json('hash'), 'confirm' => true, 'reason' => 'SYNTHETIC scoped support profile upgrade in isolated QA.', 'idempotency_key' => (string) Str::uuid()];
|
||||
}
|
||||
|
||||
public function test_authenticated_upgrade_preserves_accounts_existing_authority_and_business_data_without_granting_support(): void
|
||||
{
|
||||
$this->beforeSupport();
|
||||
$organization = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $organization, 'name' => 'SYNTHETIC preserved organization', 'organization_type' => 'private']);
|
||||
app(PortalProfileAdministration::class)->insertGrant((string) Str::uuid(), $this->admin, ['user_id' => $this->staff->id, 'role' => 'promoter', 'organization_id' => $organization, 'opportunity_types' => ['investment_project']]);
|
||||
$id = (string) Str::uuid();
|
||||
$opportunity = new Opportunity(['reference' => $id, 'slug' => $id, 'title' => 'PRIVATE SYNTHETIC PRESERVED INVESTMENT', 'status' => 'draft']);
|
||||
$opportunity->forceFill(['owner_user_id' => $this->staff->id, 'organization_id' => $organization, 'opportunity_category' => 'investment_project', 'management_version' => 3, 'workflow_context' => ['working_state' => 'draft', 'history' => ['SYNTHETIC previous version']]])->save();
|
||||
$before = [];
|
||||
foreach (['users', 'organizations', 'portal_role_assignments', 'portal_superuser_pair', 'opportunities', 'tasks'] as $table) {
|
||||
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
|
||||
}
|
||||
$this->proof();
|
||||
$this->getJson(self::URL)->assertOk()->assertHeader('Cache-Control', 'no-store, private')->assertJsonPath('ready', true)->assertJsonPath('action', 'install')->assertJsonPath('schema.state', 'base');
|
||||
$input = $this->input();
|
||||
$result = $this->postJson(self::URL, $input)->assertOk()->assertJsonPath('installed', true)->assertJsonPath('changed', true)->assertJsonPath('privileges_granted', false)->assertJsonPath('mode', 'install')->json();
|
||||
$this->postJson(self::URL, $input)->assertOk()->assertExactJson($result);
|
||||
$this->postJson(self::URL, [...$input, 'reason' => 'SYNTHETIC changed upgrade purpose'])->assertConflict();
|
||||
foreach ($before as $table => $snapshot) {
|
||||
$this->assertSame($snapshot, DB::table($table)->orderBy('id')->get()->toJson());
|
||||
}
|
||||
$this->assertTrue(app(OpportunityTechnicalSupport::class)->installed());
|
||||
$this->assertFalse(app(OpportunityTechnicalSupport::class)->allows($this->staff));
|
||||
$this->assertFalse(config('portal_profiles.authenticated_installation'));
|
||||
$this->assertSame(1, DB::table('migrations')->where('migration', TechnicalSupportProfileSchema::MIGRATION)->count());
|
||||
$this->assertSame(1, DB::table('audit_events')->where('action', 'technical-support-install')->count());
|
||||
}
|
||||
|
||||
public function test_already_installed_update_is_noop_and_receipts_are_visible_only_to_their_actor(): void
|
||||
{
|
||||
$input = $this->input();
|
||||
$this->postJson(self::URL, $input)->assertOk()->assertJsonPath('changed', false)->assertJsonPath('mode', 'already_installed');
|
||||
$this->getJson(self::URL)->assertOk()->assertJsonCount(1, 'commands')->assertJsonPath('commands.0.key', $input['idempotency_key'])->assertJsonMissingPath('commands.0.request_hash');
|
||||
$this->login($this->second)->getJson(self::URL)->assertOk()->assertJsonCount(0, 'commands');
|
||||
$this->login($this->admin, false)->postJson(self::URL, $input)->assertForbidden();
|
||||
DB::table('portal_superuser_pair')->where('id', 1)->update(['first_user_id' => $this->staff->id]);
|
||||
$this->login($this->admin)->getJson(self::URL)->assertForbidden();
|
||||
$this->postJson(self::URL, $input)->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_final_audit_failure_rolls_back_role_constraint_and_migration_ledger_and_allows_explicit_retry(): void
|
||||
{
|
||||
$this->beforeSupport();
|
||||
$this->proof();
|
||||
$input = $this->input();
|
||||
DB::statement("ALTER TABLE audit_events ADD CONSTRAINT qa_reject_support_install CHECK (source_system <> 'portal-profile-installation')");
|
||||
$this->postJson(self::URL, $input)->assertStatus(503);
|
||||
$state = app(TechnicalSupportProfileSchema::class)->inspect();
|
||||
$this->assertSame('base', $state['state']);
|
||||
$this->assertFalse($state['ledger']);
|
||||
$this->assertFalse(config('portal_profiles.authenticated_installation'));
|
||||
DB::statement('ALTER TABLE audit_events DROP CONSTRAINT qa_reject_support_install');
|
||||
$this->postJson(self::URL, $input)->assertOk()->assertJsonPath('changed', true);
|
||||
}
|
||||
|
||||
public function test_readiness_rejects_false_flags_malformed_values_expiry_future_dates_wrong_target_and_tampered_files(): void
|
||||
{
|
||||
$this->beforeSupport();
|
||||
$valid = $this->proof();
|
||||
$target = get_object_vars($valid['target']);
|
||||
$variants = [['restore_verified' => 'false'], ['qa_passed' => 1], ['verified_at' => []], ['verified_at' => gmdate('c', time() + 3600)], ['verified_at' => gmdate('c', time() - 172800)], ['dump_path' => []], ['target' => 'invalid'], ['target' => [...$target, 'port' => 5432]], ['code_hash' => str_repeat('0', 64)]];
|
||||
foreach ($variants as $variant) {
|
||||
$this->writeProof([...$valid, ...$variant]);
|
||||
$this->getJson(self::URL)->assertOk()->assertJsonPath('ready', false);
|
||||
$this->postJson(self::URL, $this->input())->assertUnprocessable();
|
||||
}
|
||||
$this->writeProof($valid);
|
||||
file_put_contents($this->directory.'/files', 'SYNTHETIC tampering');
|
||||
$this->getJson(self::URL)->assertOk()->assertJsonPath('ready', false);
|
||||
$this->postJson(self::URL, $this->input())->assertUnprocessable();
|
||||
$this->assertFalse(app(OpportunityTechnicalSupport::class)->installed());
|
||||
}
|
||||
|
||||
public function test_a_changed_valid_proof_invalidates_the_old_reviewed_plan_and_normalized_retry_keeps_the_same_receipt(): void
|
||||
{
|
||||
$this->beforeSupport();
|
||||
$proof = $this->proof();
|
||||
$stale = $this->input();
|
||||
$this->writeProof([...$proof, 'snapshot_reference' => 'SYNTHETIC newer verified snapshot']);
|
||||
$this->getJson(self::URL)->assertJsonPath('ready', true);
|
||||
$this->postJson(self::URL, $stale)->assertConflict();
|
||||
$input = $this->input();
|
||||
$this->postJson(self::URL, [...$input, 'idempotency_key' => strtoupper($input['idempotency_key']), 'confirm' => 'yes', 'reason' => ' '.$input['reason'].' '])->assertOk();
|
||||
$this->postJson(self::URL, $input)->assertOk();
|
||||
$this->assertSame(1, DB::table('audit_events')->where('action', 'technical-support-install')->count());
|
||||
}
|
||||
|
||||
public function test_known_base_constraint_with_registered_migration_has_a_scoped_authenticated_repair(): void
|
||||
{
|
||||
$ledger = DB::table('migrations')->where('migration', TechnicalSupportProfileSchema::MIGRATION)->first();
|
||||
$this->beforeSupport(true);
|
||||
$this->assertFalse(app(OpportunityTechnicalSupport::class)->installed());
|
||||
$this->getJson(self::URL)->assertOk()->assertJsonPath('consistent', false)->assertJsonPath('repairable', true)->assertJsonPath('ready', false);
|
||||
$this->postJson(self::URL, $this->input())->assertUnprocessable();
|
||||
$this->proof();
|
||||
$this->postJson(self::URL, $this->input())->assertOk()->assertJsonPath('mode', 'repair_known_base')->assertJsonPath('changed', true);
|
||||
$this->assertEquals($ledger, DB::table('migrations')->where('migration', TechnicalSupportProfileSchema::MIGRATION)->first());
|
||||
$this->assertTrue(app(OpportunityTechnicalSupport::class)->installed());
|
||||
$this->assertSame(0, DB::table('portal_role_assignments')->count());
|
||||
}
|
||||
|
||||
public function test_unknown_or_weakened_constraints_are_not_overwritten_or_reported_as_installed(): void
|
||||
{
|
||||
$this->proof();
|
||||
DB::statement("ALTER TABLE portal_role_assignments DROP CONSTRAINT portal_role_name, ADD CONSTRAINT portal_role_name CHECK (role IN ('promoter','validator','publisher','auditor','technical_support') OR TRUE)");
|
||||
$fingerprint = app(TechnicalSupportProfileSchema::class)->inspect()['fingerprint'];
|
||||
$this->getJson(self::URL)->assertOk()->assertJsonPath('schema.state', 'unrecognised')->assertJsonPath('installed', false)->assertJsonPath('repairable', false);
|
||||
$this->postJson(self::URL, $this->input())->assertConflict();
|
||||
$this->assertSame($fingerprint, app(TechnicalSupportProfileSchema::class)->inspect()['fingerprint']);
|
||||
DB::statement('ALTER TABLE portal_role_assignments DROP CONSTRAINT portal_role_name');
|
||||
$this->postJson(self::URL, $this->input())->assertConflict();
|
||||
}
|
||||
|
||||
public function test_missing_ledger_for_existing_support_schema_does_not_implicitly_adopt_authority(): void
|
||||
{
|
||||
DB::table('migrations')->where('migration', TechnicalSupportProfileSchema::MIGRATION)->delete();
|
||||
$this->proof();
|
||||
$this->getJson(self::URL)->assertOk()->assertJsonPath('schema.state', 'support')->assertJsonPath('installed', false)->assertJsonPath('repairable', false);
|
||||
$this->postJson(self::URL, $this->input())->assertConflict();
|
||||
$this->assertFalse(DB::table('migrations')->where('migration', TechnicalSupportProfileSchema::MIGRATION)->exists());
|
||||
}
|
||||
|
||||
public function test_support_role_and_legacy_allowlist_do_not_grant_installation_authority_and_auditor_denial_prevails(): void
|
||||
{
|
||||
app(PortalProfileAdministration::class)->insertGrant((string) Str::uuid(), $this->admin, ['user_id' => $this->staff->id, 'role' => 'technical_support', 'opportunity_types' => ['investment_project']]);
|
||||
$this->login($this->staff)->getJson(self::URL)->assertForbidden();
|
||||
$this->postJson(self::URL, ['hash' => str_repeat('a', 64), 'confirm' => true, 'reason' => 'SYNTHETIC forbidden installation', 'idempotency_key' => (string) Str::uuid()])->assertForbidden();
|
||||
app(PortalProfileAdministration::class)->insertGrant((string) Str::uuid(), $this->second, ['user_id' => $this->admin->id, 'role' => 'auditor', 'opportunity_types' => []]);
|
||||
$this->login($this->admin)->getJson(self::URL)->assertForbidden();
|
||||
$this->postJson(self::URL, [])->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_upgrade_keeps_existing_dependency_and_historical_support_downgrade_controls(): void
|
||||
{
|
||||
$this->beforeSupport();
|
||||
$this->proof();
|
||||
DB::table('migrations')->where('migration', '2026_10_09_030000_extend_opportunity_resources')->delete();
|
||||
$this->getJson(self::URL)->assertJsonPath('ready', false)->assertJsonPath('dependencies.resources_030000', false);
|
||||
$this->postJson(self::URL, $this->input())->assertUnprocessable();
|
||||
DB::table('migrations')->insert(['migration' => '2026_10_09_030000_extend_opportunity_resources', 'batch' => 1]);
|
||||
$this->postJson(self::URL, $this->input())->assertOk();
|
||||
$assignment = app(PortalProfileAdministration::class)->grant($this->admin, ['user_id' => $this->staff->id, 'role' => 'technical_support', 'opportunity_types' => ['investment_project'], 'reason' => 'SYNTHETIC explicit independent support assignment']);
|
||||
app(PortalProfileAdministration::class)->revoke($this->admin, $assignment, 'SYNTHETIC explicit removal; preserve the historical assignment');
|
||||
try {
|
||||
(require database_path('migrations/'.TechnicalSupportProfileSchema::MIGRATION.'.php'))->down();
|
||||
$this->fail('Historical support assignment must survive downgrade.');
|
||||
} catch (\LogicException $error) {
|
||||
$this->assertStringContainsString('Preserve existing and historical', $error->getMessage());
|
||||
}
|
||||
$this->assertTrue(app(OpportunityTechnicalSupport::class)->installed());
|
||||
$this->assertSame(1, DB::table('portal_role_assignments')->count());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\User;
|
||||
use App\Services\OpportunityTechnicalIncidents;
|
||||
use App\Services\PortalProfileAdministration;
|
||||
use App\Services\TechnicalIncidentHandling;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Str;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class TechnicalIncidentHandlingTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $support;
|
||||
|
||||
private User $colleague;
|
||||
|
||||
private User $reporter;
|
||||
|
||||
private Opportunity $opportunity;
|
||||
|
||||
private string $reference;
|
||||
|
||||
private string $organization;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
Http::fake();
|
||||
Mail::fake();
|
||||
config(['portal.profile_access_enabled' => true, 'suitecrm.enabled' => false, 'investmoz_ai.enabled' => false]);
|
||||
$approver = User::factory()->create();
|
||||
$this->support = User::factory()->create(['name' => 'SYNTHETIC first support']);
|
||||
$this->colleague = User::factory()->create(['name' => 'SYNTHETIC second support']);
|
||||
$this->reporter = User::factory()->create();
|
||||
$this->organization = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $this->organization, 'name' => 'SYNTHETIC incident organization', 'organization_type' => 'private']);
|
||||
foreach ([$this->support, $this->colleague, $this->reporter] as $actor) {
|
||||
app(PortalProfileAdministration::class)->insertGrant((string) Str::uuid(), $approver, ['user_id' => $actor->id, 'role' => $actor === $this->reporter ? 'promoter' : 'technical_support', 'organization_id' => $this->organization, 'opportunity_types' => ['investment_project'], 'source' => 'synthetic-support-treatment-fixture']);
|
||||
}
|
||||
DB::table('memberships')->insert(['id' => (string) Str::uuid(), 'user_id' => $this->reporter->id, 'organization_id' => $this->organization, 'role' => 'officer']);
|
||||
$id = (string) Str::uuid();
|
||||
$this->opportunity = new Opportunity(['title' => 'PRIVATE SYNTHETIC INVESTMENT', 'reference' => $id, 'slug' => $id, 'status' => 'draft']);
|
||||
$this->opportunity->forceFill(['owner_user_id' => $this->reporter->id, 'organization_id' => $this->organization, 'opportunity_category' => 'investment_project', 'management_version' => 4, 'workflow_context' => ['working_state' => 'draft', 'content_revision' => 3]])->save();
|
||||
// Synthetic root metadata fixture. Real failing HTTP submission/publication is covered by OpportunityTechnicalIncidentsTest.
|
||||
$this->reference = app(OpportunityTechnicalIncidents::class)->record($this->reporter, $this->opportunity, 'submit', str_repeat('a', 64), new \RuntimeException('PRIVATE SYNTHETIC FAILURE'))['reference'];
|
||||
$this->actingAs($this->support);
|
||||
}
|
||||
|
||||
/** @return array{version:int,action:string,note:string,operation_key:string} */
|
||||
private function input(int $version, string $action = 'note'): array
|
||||
{
|
||||
return ['version' => $version, 'action' => $action, 'note' => 'PRIVATE SYNTHETIC treatment note with evidence.', 'operation_key' => (string) Str::uuid()];
|
||||
}
|
||||
|
||||
private function url(): string
|
||||
{
|
||||
return '/suporte-tecnico/incidentes/'.$this->reference;
|
||||
}
|
||||
|
||||
public function test_team_treatment_preserves_business_data_and_encrypts_notes_with_a_private_history(): void
|
||||
{
|
||||
$before = $this->opportunity->fresh()->getRawOriginal();
|
||||
$grantCount = DB::table('portal_role_assignments')->count();
|
||||
$this->postJson($this->url(), $this->input(0, 'claim'))->assertOk()->assertJsonPath('handling.status', 'in_progress')->assertJsonPath('handling.assignee_user_id', $this->support->id);
|
||||
$this->actingAs($this->colleague)->postJson($this->url(), [...$this->input(1, 'claim'), 'assignee_user_id' => $this->reporter->id])->assertOk()->assertJsonPath('handling.assignee_user_id', $this->colleague->id);
|
||||
$this->postJson($this->url(), $this->input(2))->assertOk();
|
||||
$this->postJson($this->url(), $this->input(3, 'resolve'))->assertOk()->assertJsonPath('handling.status', 'resolved');
|
||||
$this->postJson($this->url(), $this->input(4, 'reopen'))->assertOk()->assertJsonPath('handling.status', 'open')->assertJsonPath('handling.assignee_user_id', null);
|
||||
$this->postJson($this->url(), $this->input(5, 'claim'))->assertOk();
|
||||
$this->postJson($this->url(), $this->input(6, 'release'))->assertOk()->assertJsonPath('handling.status', 'open');
|
||||
$this->assertSame($before, $this->opportunity->fresh()->getRawOriginal());
|
||||
$this->assertSame(0, DB::table('tasks')->count());
|
||||
$this->assertSame($grantCount, DB::table('portal_role_assignments')->count());
|
||||
$raw = DB::table('audit_events')->where('source_system', 'portal-opportunity-support')->get()->toJson();
|
||||
$this->assertStringNotContainsString('PRIVATE SYNTHETIC treatment note', $raw);
|
||||
$this->get($this->url())->assertOk()->assertHeader('Cache-Control', 'no-store, private')->assertInertia(fn (Assert $page) => $page->has('history.data', 7)->where('incident.handling.version', 7)->where('history.data.0.note_available', true)->where('history.data.0.note', 'PRIVATE SYNTHETIC treatment note with evidence.')->missing('history.data.0.operation_key')->missing('history.data.0.hash'));
|
||||
$mine = app(OpportunityTechnicalIncidents::class)->recent($this->reporter, $this->opportunity)[0];
|
||||
$this->assertSame('open', $mine['handling']['status']);
|
||||
$this->assertArrayNotHasKey('note', $mine['handling']);
|
||||
$this->assertArrayNotHasKey('assignee_user_id', $mine['handling']);
|
||||
}
|
||||
|
||||
public function test_repeating_the_original_command_after_later_treatment_is_readonly_and_private_to_its_actor(): void
|
||||
{
|
||||
$input = $this->input(0, 'claim');
|
||||
$this->postJson($this->url(), $input)->assertOk();
|
||||
$this->postJson($this->url(), $this->input(1, 'resolve'))->assertOk();
|
||||
$this->postJson($this->url(), $input)->assertOk()->assertJsonPath('replayed', true)->assertJsonPath('result_version', 1)->assertJsonPath('handling.version', 2)->assertJsonPath('handling.status', 'resolved');
|
||||
$this->assertSame(2, DB::table('audit_events')->where('source_system', 'portal-opportunity-support')->count());
|
||||
$this->get($this->url())->assertInertia(fn (Assert $page) => $page->has('commands', 2)->where('commands.0.key', $input['operation_key'])->missing('commands.0.hash'));
|
||||
$this->actingAs($this->colleague)->get($this->url())->assertInertia(fn (Assert $page) => $page->has('commands', 0)->has('history.data', 2));
|
||||
}
|
||||
|
||||
public function test_changed_command_and_stale_preparation_are_rejected_while_canonical_replay_is_accepted(): void
|
||||
{
|
||||
$input = $this->input(0);
|
||||
$this->postJson($this->url(), [...$input, 'operation_key' => strtoupper($input['operation_key']), 'version' => '0', 'note' => ' '.$input['note'].' '])->assertOk();
|
||||
$this->postJson($this->url(), $input)->assertOk()->assertJsonPath('replayed', true);
|
||||
$this->postJson($this->url(), [...$input, 'note' => 'SYNTHETIC different prepared note'])->assertConflict();
|
||||
$this->postJson($this->url(), $this->input(0, 'resolve'))->assertConflict();
|
||||
$this->assertSame(1, DB::table('audit_events')->where('source_system', 'portal-opportunity-support')->count());
|
||||
}
|
||||
|
||||
public function test_invalid_state_changes_and_whitespace_only_notes_do_not_append_events(): void
|
||||
{
|
||||
$this->postJson($this->url(), $this->input(0, 'reopen'))->assertUnprocessable();
|
||||
$this->postJson($this->url(), $this->input(0, 'release'))->assertUnprocessable();
|
||||
$this->postJson($this->url(), [...$this->input(0), 'note' => str_repeat(' ', 25)])->assertUnprocessable();
|
||||
$this->postJson($this->url(), [...$this->input(0), 'action' => 'publish'])->assertUnprocessable();
|
||||
$this->postJson($this->url(), $this->input(0, 'claim'))->assertOk();
|
||||
$this->postJson($this->url(), $this->input(1, 'claim'))->assertUnprocessable();
|
||||
$this->postJson($this->url(), $this->input(1, 'resolve'))->assertOk();
|
||||
$this->postJson($this->url(), $this->input(2, 'resolve'))->assertUnprocessable();
|
||||
$this->postJson($this->url(), $this->input(2, 'claim'))->assertUnprocessable();
|
||||
$this->postJson($this->url(), $this->input(2))->assertOk()->assertJsonPath('handling.status', 'resolved');
|
||||
}
|
||||
|
||||
public function test_current_scope_revocation_and_auditor_restriction_apply_to_reads_and_replayed_commands(): void
|
||||
{
|
||||
$input = $this->input(0);
|
||||
$this->postJson($this->url(), $input)->assertOk();
|
||||
DB::table('portal_role_assignments')->where('user_id', $this->support->id)->update(['revoked_at' => now()]);
|
||||
$this->get($this->url())->assertForbidden();
|
||||
$this->postJson($this->url(), $input)->assertForbidden();
|
||||
$this->actingAs($this->colleague);
|
||||
$auditor = (string) Str::uuid();
|
||||
app(PortalProfileAdministration::class)->insertGrant($auditor, $this->reporter, ['user_id' => $this->colleague->id, 'role' => 'auditor', 'opportunity_types' => ['investment_project']]);
|
||||
$this->get($this->url())->assertForbidden();
|
||||
$this->postJson($this->url(), $this->input(1))->assertForbidden();
|
||||
DB::table('portal_role_assignments')->where('id', $auditor)->update(['revoked_at' => now()]);
|
||||
DB::table('opportunities')->where('id', $this->opportunity->id)->update(['opportunity_category' => 'real_estate']);
|
||||
$this->get($this->url())->assertNotFound();
|
||||
$this->postJson($this->url(), $this->input(1))->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_reporter_sees_status_without_internal_notes_and_cannot_open_support_detail(): void
|
||||
{
|
||||
$this->postJson($this->url(), $this->input(0, 'resolve'))->assertOk();
|
||||
$this->actingAs($this->reporter)->get($this->url())->assertForbidden();
|
||||
$this->postJson($this->url(), $this->input(1, 'reopen'))->assertForbidden();
|
||||
$rows = app(OpportunityTechnicalIncidents::class)->recent($this->reporter, $this->opportunity);
|
||||
$this->assertSame('resolved', $rows[0]['handling']['status']);
|
||||
$this->assertStringNotContainsString('PRIVATE SYNTHETIC treatment note', json_encode($rows));
|
||||
$this->assertArrayNotHasKey('commands', $rows[0]);
|
||||
}
|
||||
|
||||
public function test_history_pagination_preserves_queue_context_and_an_unreadable_note_is_not_invented(): void
|
||||
{
|
||||
for ($i = 0; $i < 12; $i++) {
|
||||
$this->postJson($this->url(), $this->input($i))->assertOk();
|
||||
}
|
||||
$this->get($this->url().'?page=3')->assertOk()->assertInertia(fn (Assert $page) => $page->has('history.data', 10)->where('history.total', 12)->where('history.data.0.version', 12)->where('backUrl', '/suporte-tecnico/incidentes?page=3')->where('history.next_page_url', fn (string $url) => str_contains($url, 'page=3') && str_contains($url, 'history_page=2')));
|
||||
$this->get($this->url().'?page=3&history_page=2')->assertInertia(fn (Assert $page) => $page->has('history.data', 2)->where('history.data.0.version', 2));
|
||||
DB::table('audit_events')->insert(['source_system' => 'portal-opportunity-support', 'entity_type' => 'opportunity-technical-incident', 'entity_id' => $this->reference, 'action' => 'incident_handled', 'actor_user_id' => $this->support->id, 'data_classification' => 'restricted', 'after_data' => json_encode(['handling' => ['version' => 13, 'status' => 'open', 'assignee_user_id' => null, 'updated_at' => now()->toIso8601String(), 'resolved_at' => null, 'command' => 'note', 'note' => 'SYNTHETIC unreadable envelope']])]);
|
||||
$this->get($this->url())->assertOk()->assertInertia(fn (Assert $page) => $page->where('incident.handling.version', 13)->where('history.data.0.note_available', false)->where('history.data.0.note', null));
|
||||
}
|
||||
|
||||
public function test_invalid_current_state_is_preserved_and_does_not_silently_restart_treatment(): void
|
||||
{
|
||||
DB::table('audit_events')->insert(['source_system' => 'portal-opportunity-support', 'entity_type' => 'opportunity-technical-incident', 'entity_id' => $this->reference, 'action' => 'incident_handled', 'actor_user_id' => $this->support->id, 'data_classification' => 'restricted', 'after_data' => json_encode(['handling' => ['version' => 5, 'status' => 'unrecognized']])]);
|
||||
$this->get($this->url())->assertStatus(503);
|
||||
$this->postJson($this->url(), $this->input(0))->assertStatus(503);
|
||||
$this->get('/suporte-tecnico/incidentes')->assertOk()->assertInertia(fn (Assert $page) => $page->where('incidents.data.0.handling', null));
|
||||
$this->assertNull(app(OpportunityTechnicalIncidents::class)->recent($this->reporter, $this->opportunity)[0]['handling']);
|
||||
$this->actingAs($this->reporter)->get('/minhas-oportunidades/'.$this->opportunity->id.'/view')->assertOk();
|
||||
$this->assertSame(1, DB::table('audit_events')->where('source_system', 'portal-opportunity-support')->count());
|
||||
}
|
||||
|
||||
public function test_queue_filters_use_the_latest_treatment_and_detail_keeps_the_queue_context(): void
|
||||
{
|
||||
$this->postJson($this->url(), $this->input(0, 'claim'))->assertOk();
|
||||
$this->get('/suporte-tecnico/incidentes?status=in_progress')->assertOk()->assertInertia(fn (Assert $page) => $page->where('incidents.total', 1)->where('incidents.data.0.handling.status', 'in_progress'));
|
||||
$this->postJson($this->url(), $this->input(1, 'resolve'))->assertOk();
|
||||
$this->postJson($this->url(), $this->input(2))->assertOk();
|
||||
$this->get('/suporte-tecnico/incidentes?status=open')->assertInertia(fn (Assert $page) => $page->where('incidents.total', 0));
|
||||
$this->get('/suporte-tecnico/incidentes?status=resolved')->assertInertia(fn (Assert $page) => $page->where('incidents.total', 1)->where('incidents.data.0.details_url', $this->url()));
|
||||
$this->get($this->url().'?status=resolved&page=3')->assertInertia(fn (Assert $page) => $page->where('backUrl', '/suporte-tecnico/incidentes?page=3&status=resolved'));
|
||||
}
|
||||
|
||||
public function test_audit_failure_rolls_back_the_treatment_and_the_same_command_can_be_retried_explicitly(): void
|
||||
{
|
||||
DB::unprepared("CREATE FUNCTION qa_fail_handling() RETURNS trigger LANGUAGE plpgsql AS \$\$ BEGIN IF NEW.source_system='portal-opportunity-support' THEN RAISE EXCEPTION 'PRIVATE SYNTHETIC HANDLING FAILURE'; END IF; RETURN NEW; END \$\$; CREATE TRIGGER qa_fail_handling BEFORE INSERT ON audit_events FOR EACH ROW EXECUTE FUNCTION qa_fail_handling();");
|
||||
$input = $this->input(0, 'claim');
|
||||
$response = $this->postJson($this->url(), $input)->assertStatus(503);
|
||||
$this->assertStringNotContainsString('PRIVATE SYNTHETIC HANDLING FAILURE', $response->getContent());
|
||||
$this->assertSame(0, app(TechnicalIncidentHandling::class)->stateFor($this->reference)['version']);
|
||||
DB::unprepared('DROP TRIGGER qa_fail_handling ON audit_events; DROP FUNCTION qa_fail_handling();');
|
||||
$this->postJson($this->url(), $input)->assertOk()->assertJsonPath('result_version',1);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user