From 03e54c7a8529bd00c874758c04ea937d18054aa4 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 13:43:11 +0200 Subject: [PATCH] =?UTF-8?q?Avisa=20a=20equipa=20de=20novos=20interesses=20?= =?UTF-8?q?e=20pedidos=20do=20Balc=C3=A3o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Em produção, os pedidos de interesse feitos em /apoio nunca foram vistos: só o caminho da API enfileirava o aviso à equipa. O aviso passa para o InterestSubmission::receive, por onde passam todos os caminhos de entrada, e a submissão de um pedido no Balcão Virtual passa a avisar também a equipa (até aqui só o proponente e um analista já atribuído recebiam aviso interno). - TeamNotifications: fila transaccional comum (só existe aviso se o registo ficou gravado); destinatários de PORTAL_NOTIFICATION_RECIPIENTS, sem dados pessoais nas mensagens. - NotifyDeskRequestSubmitted: protocolo e ligações protegidas de triagem. - DemographicInstallation aceita também o domínio público como a mesma instalação de produção, para o APP_URL poder passar a investemoz.tempo.co.mz. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MzJmxFy3izprXr5dSq91jm --- .../Api/V1/InterestRequestController.php | 14 ---- app/Jobs/NotifyDeskRequestSubmitted.php | 41 +++++++++ app/Services/DemographicInstallation.php | 3 +- app/Services/InterestSubmission.php | 4 + app/Services/TeamNotifications.php | 32 +++++++ app/Services/VirtualDesk.php | 6 ++ .../Feature/DeskSubmissionTeamNoticeTest.php | 84 +++++++++++++++++++ tests/Feature/PortalOperationsTest.php | 26 ++++++ tests/Unit/DemographicTargetTest.php | 15 ++++ 9 files changed, 210 insertions(+), 15 deletions(-) create mode 100644 app/Jobs/NotifyDeskRequestSubmitted.php create mode 100644 app/Services/TeamNotifications.php create mode 100644 tests/Feature/DeskSubmissionTeamNoticeTest.php diff --git a/app/Http/Controllers/Api/V1/InterestRequestController.php b/app/Http/Controllers/Api/V1/InterestRequestController.php index a06cf795..08bb1aaa 100644 --- a/app/Http/Controllers/Api/V1/InterestRequestController.php +++ b/app/Http/Controllers/Api/V1/InterestRequestController.php @@ -5,7 +5,6 @@ namespace App\Http\Controllers\Api\V1; use App\Domain\Interests\Enums\InterestStatus; use App\Http\Controllers\Controller; use App\Http\Requests\StoreInterestRequestRequest; -use App\Jobs\NotifyInterestReceived; use App\Models\ExistingBusiness; use App\Models\InterestRequest; use App\Models\InvestmentSubmission; @@ -16,7 +15,6 @@ use Illuminate\Database\QueryException; use Illuminate\Http\JsonResponse; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; -use Illuminate\Support\Facades\Queue; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Str; use Illuminate\Validation\ValidationException; @@ -68,18 +66,6 @@ class InterestRequestController extends Controller 'ip_address' => $request->ip(), 'user_agent' => $request->userAgent(), ]); - if (config('portal.notifications_enabled')) { - $connection = config('queue.connections.database.connection'); - if (config('queue.connections.database.after_commit') || ($connection && $connection !== config('database.default'))) { - throw new \RuntimeException('Portal notifications require the transactional database queue.'); - } - foreach (array_unique(config('portal.notification_recipients')) as $recipient) { - if (filter_var($recipient, FILTER_VALIDATE_EMAIL)) { - Queue::connection('database')->push(new NotifyInterestReceived($interest->id, $recipient)); - } - } - } - $row = InvestmentSubmission::create([ 'user_id' => $request->user()->id, 'opportunity_id' => $opportunity?->id, 'interest_request_id' => $interest->id, 'status' => 'submitted', 'version' => 1, diff --git a/app/Jobs/NotifyDeskRequestSubmitted.php b/app/Jobs/NotifyDeskRequestSubmitted.php new file mode 100644 index 00000000..7ac766c5 --- /dev/null +++ b/app/Jobs/NotifyDeskRequestSubmitted.php @@ -0,0 +1,41 @@ + */ + public function backoff(): array + { + return [60, 300, 900]; + } + + public function handle(): void + { + if (! config('portal.notifications_enabled') || ! in_array($this->recipient, config('portal.notification_recipients'), true)) { + return; + } + $request = DB::table('desk_requests')->where('id', $this->requestId)->first(['id', 'protocol', 'status', 'analyst_id']); + if (! $request || $request->status !== 'submitted') { + return; // Already picked up, returned or withdrawn before the notice left. + } + $assignment = $request->analyst_id ? 'Já tem responsável atribuído.' : 'Ainda sem responsável: atribua-o na triagem.'; + $body = "Foi submetido um pedido no Balcão Virtual: {$request->protocol}.\n{$assignment}\n\n" + ."Triagem e atribuição:\n".url('/management/balcao/atribuicoes')."\n\nPedido:\n".url('/balcao-virtual/pedidos/'.$request->id); + Mail::raw($body, fn ($message) => $message->to($this->recipient)->subject('Novo pedido no Balcão Virtual — '.$request->protocol)); + } +} diff --git a/app/Services/DemographicInstallation.php b/app/Services/DemographicInstallation.php index 9555ca88..349e6031 100644 --- a/app/Services/DemographicInstallation.php +++ b/app/Services/DemographicInstallation.php @@ -76,7 +76,8 @@ final class DemographicInstallation public function activeTarget(): bool { $c = config('database.connections.pgsql'); - $homologation = config('app.url') === 'https://teste-investidor.tempo.co.mz' + // The production install answers on both names (public domain and the original homologation one). + $homologation = in_array(config('app.url'), ['https://teste-investidor.tempo.co.mz', 'https://investemoz.tempo.co.mz'], true) && config('demography.enabled', false) && $c['database'] === 'teste_investidor'; if (app()->environment('testing') || config('database.default') !== 'pgsql' || ! empty($c['url']) || ! in_array($c['host'], ['127.0.0.1', 'localhost'], true) || (int) $c['port'] !== 5432 diff --git a/app/Services/InterestSubmission.php b/app/Services/InterestSubmission.php index b4b6bb42..648b7840 100644 --- a/app/Services/InterestSubmission.php +++ b/app/Services/InterestSubmission.php @@ -2,6 +2,7 @@ namespace App\Services; +use App\Jobs\NotifyInterestReceived; use App\Models\InterestRequest; use Closure; use Illuminate\Support\Facades\DB; @@ -62,6 +63,9 @@ final class InterestSubmission 'interest_request_id' => $interest->id, 'created_at' => now(), ]); } + // Every intake path (public support form, investor workspace, investment and land + // submissions, API) passes here, so the team is told about each new interest once. + TeamNotifications::queue(fn (string $recipient) => new NotifyInterestReceived($interest->id, $recipient)); return $interest; }); diff --git a/app/Services/TeamNotifications.php b/app/Services/TeamNotifications.php new file mode 100644 index 00000000..921e773e --- /dev/null +++ b/app/Services/TeamNotifications.php @@ -0,0 +1,32 @@ +push($jobFor($recipient)); + } + } + } +} diff --git a/app/Services/VirtualDesk.php b/app/Services/VirtualDesk.php index d9158c45..d7a65455 100644 --- a/app/Services/VirtualDesk.php +++ b/app/Services/VirtualDesk.php @@ -2,6 +2,7 @@ namespace App\Services; +use App\Jobs\NotifyDeskRequestSubmitted; use App\Models\InvestmentSubmission; use App\Models\Investor; use App\Models\InvestorJourney; @@ -556,9 +557,14 @@ class VirtualDesk if ($submit) { $updates = [...$updates, 'status' => 'submitted', 'protocol' => $request->protocol ?? 'BV-'.date('Y').'-'.strtoupper(str_replace('-', '', $id)), 'submitted_at' => now(), 'submitted_snapshot' => $this->encode($snapshot)]; } + $previousStatus = $request->status; DB::table('desk_requests')->where('id', $id)->update($updates); $request = DB::table('desk_requests')->where('id', $id)->firstOrFail(); $this->event($case, $actor, $submit ? 'submitted' : 'draft_saved', ['reason' => $data['reason'] ?? '', 'findings' => $findings], $request); + if ($submit && $previousStatus !== 'submitted') { + // The in-app notice reaches only the owner and an analyst already assigned; tell the team. + TeamNotifications::queue(fn (string $recipient) => new NotifyDeskRequestSubmitted($id, $recipient)); + } if (($data['context_reviewed'] ?? false) && ! $submit) { $this->event($case, $actor, 'request_context_reviewed', ['investment_context_revision' => app(InvestorContext::class)->state($case)['revision']], $request); } diff --git a/tests/Feature/DeskSubmissionTeamNoticeTest.php b/tests/Feature/DeskSubmissionTeamNoticeTest.php new file mode 100644 index 00000000..11d11228 --- /dev/null +++ b/tests/Feature/DeskSubmissionTeamNoticeTest.php @@ -0,0 +1,84 @@ + 'SYNTHETIC project', 'description' => 'SYNTHETIC private preparation', + 'original_reference' => 'SYNTHETIC-REF', 'change_reason' => 'SYNTHETIC confidential change']; + + protected function setUp(): void + { + parent::setUp(); + $this->withoutVite(); + $this->owner = User::factory()->create(['email' => 'investidor-sintetico@example.invalid']); + $manager = User::factory()->create(); + config(['portal.managers' => [$manager->email], 'investmoz_ai.enabled' => false, 'suitecrm.enabled' => false, + 'portal.notifications_enabled' => true, 'portal.notification_recipients' => ['balcao@example.invalid']]); + $edition = $this->actingAs($manager)->putJson('/management/balcao/servicos/project-change', ['base_version' => 0, 'definition' => config('virtual-desk.services.project-change'), 'confirm' => true, 'reason' => 'SYNTHETIC team notice acceptance QA'])->assertCreated()->json('id'); + $case = $this->actingAs($this->owner)->postJson('/balcao-virtual/dossiers', ['title' => 'SYNTHETIC dossier', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertCreated()->json('id'); + $this->requestId = $this->postJson('/balcao-virtual/dossiers/'.$case.'/pedidos', ['service_version_id' => $edition, 'client_key' => (string) Str::uuid()])->assertCreated()->json('id'); + } + + private function deskNotices(): int + { + return DB::table('jobs')->where('payload', 'like', '%NotifyDeskRequestSubmitted%')->count(); + } + + public function test_drafts_do_not_notify_and_submission_notifies_once_without_personal_data(): void + { + $this->putJson('/balcao-virtual/pedidos/'.$this->requestId, ['version' => 1, 'payload' => $this->answers])->assertOk(); + $this->assertSame(0, $this->deskNotices()); + + $this->putJson('/balcao-virtual/pedidos/'.$this->requestId, ['version' => 2, 'payload' => $this->answers, 'submit' => true, 'consent' => true])->assertOk()->assertJsonPath('status', 'submitted'); + $this->assertSame(1, $this->deskNotices()); + $queued = DB::table('jobs')->pluck('payload')->implode(' '); + $this->assertStringNotContainsString('investidor-sintetico@example.invalid', $queued); + $this->assertStringNotContainsString('confidential change', $queued); + + // Replaying the same submission does not send a second notice. + $this->putJson('/balcao-virtual/pedidos/'.$this->requestId, ['version' => 2, 'payload' => $this->answers, 'submit' => true, 'consent' => true])->assertOk(); + $this->assertSame(1, $this->deskNotices()); + } + + public function test_notice_names_the_protocol_and_triage_link_only(): void + { + $this->putJson('/balcao-virtual/pedidos/'.$this->requestId, ['version' => 1, 'payload' => $this->answers, 'submit' => true, 'consent' => true])->assertOk(); + $protocol = DB::table('desk_requests')->where('id', $this->requestId)->value('protocol'); + $job = new NotifyDeskRequestSubmitted($this->requestId, 'balcao@example.invalid'); + Mail::swap(\Mockery::mock(MailManager::class)); + Mail::shouldReceive('raw')->once()->withArgs(function ($body, $callback) use ($protocol) { + $this->assertStringContainsString($protocol, $body); + $this->assertStringContainsString('/management/balcao/atribuicoes', $body); + $this->assertStringContainsString('sem responsável', $body); + $this->assertStringNotContainsString('SYNTHETIC', $body); + $this->assertStringNotContainsString('investidor-sintetico', $body); + + return is_callable($callback); + }); + $job->handle(); + + // A recipient removed from the configuration, or a request already in review, gets nothing. + Mail::swap(\Mockery::mock(MailManager::class)); + Mail::shouldReceive('raw')->never(); + (new NotifyDeskRequestSubmitted($this->requestId, 'outro@example.invalid'))->handle(); + DB::table('desk_requests')->where('id', $this->requestId)->update(['status' => 'reviewing']); + $job->handle(); + } +} diff --git a/tests/Feature/PortalOperationsTest.php b/tests/Feature/PortalOperationsTest.php index 25feaf1a..426baa1f 100644 --- a/tests/Feature/PortalOperationsTest.php +++ b/tests/Feature/PortalOperationsTest.php @@ -70,6 +70,32 @@ class PortalOperationsTest extends TestCase $this->assertDatabaseCount('interest_requests', 2); } + public function test_public_support_form_notifies_the_team_once_per_new_interest(): void + { + // Production received interests through /apoio for months without anyone being told. + $payload = ['fullName' => 'Pessoa sintética QA', 'email' => 'portal-integration-test@gmail.com', + 'investorType' => 'individual', 'country' => 'Moçambique', 'sectorInterest' => 'Energia', + 'message' => 'Pedido exclusivamente sintético na base QA.', 'privacyConsent' => true, 'kind' => 'support']; + config(['portal.notifications_enabled' => true, 'portal.notification_recipients' => ['equipa@example.invalid', 'gestao@example.invalid', 'equipa@example.invalid']]); + $key = (string) Str::uuid(); + $this->post('/apoio', [...$payload, 'submission_key' => $key])->assertSessionHasNoErrors()->assertRedirect(); + $this->assertDatabaseCount('interest_requests', 1); + $this->assertDatabaseCount('jobs', 2); // one per distinct recipient + $queued = DB::table('jobs')->pluck('payload')->implode(' '); + $this->assertStringContainsString('NotifyInterestReceived', $queued); + $this->assertStringNotContainsString('portal-integration-test@gmail.com', $queued); + + // Replaying the same submission returns the stored interest and does not notify again. + $this->post('/apoio', [...$payload, 'submission_key' => $key])->assertSessionHasNoErrors()->assertRedirect(); + $this->assertDatabaseCount('interest_requests', 1); + $this->assertDatabaseCount('jobs', 2); + + config(['portal.notifications_enabled' => false]); + $this->post('/apoio', [...$payload, 'submission_key' => (string) Str::uuid()])->assertSessionHasNoErrors(); + $this->assertDatabaseCount('interest_requests', 2); + $this->assertDatabaseCount('jobs', 2); + } + public function test_job_checks_current_configuration_and_excludes_personal_data(): void { $interest = InterestRequest::create(['reference' => 'IR-TEST', 'full_name' => 'Pessoa confidencial', diff --git a/tests/Unit/DemographicTargetTest.php b/tests/Unit/DemographicTargetTest.php index 396fc2d7..a1800940 100644 --- a/tests/Unit/DemographicTargetTest.php +++ b/tests/Unit/DemographicTargetTest.php @@ -27,4 +27,19 @@ final class DemographicTargetTest extends TestCase config(['app.url' => 'https://teste-investidor.tempo.co.mz', 'database.connections.pgsql.host' => 'remote.example']); $this->assertFalse($service->activeTarget()); } + + public function test_the_public_domain_is_the_same_production_installation(): void + { + // Production answers on investemoz.tempo.co.mz; moving APP_URL there must not disable the installation. + app()->instance('env', 'production'); + config(['app.url' => 'https://investemoz.tempo.co.mz', 'demography.enabled' => true, + 'database.default' => 'pgsql', 'database.connections.pgsql.host' => '127.0.0.1', + 'database.connections.pgsql.port' => 5432, 'database.connections.pgsql.database' => 'teste_investidor', + 'database.connections.pgsql.url' => null]); + DB::shouldReceive('selectOne')->once()->with('SELECT current_database() AS database,inet_server_port() AS port') + ->andReturn((object) ['database' => 'teste_investidor', 'port' => 5432]); + $this->assertTrue(app(DemographicInstallation::class)->activeTarget()); + config(['app.url' => 'https://investemoz.tempo.co.mz.example']); + $this->assertFalse(app(DemographicInstallation::class)->activeTarget()); + } }