feat: integrate opportunity draft management with audited lifecycle

This commit is contained in:
2026-10-09 08:16:51 +02:00
parent ebfc188240
commit 7ecfe3d543
20 changed files with 1459 additions and 22 deletions
@@ -0,0 +1,94 @@
<?php
namespace App\Http\Controllers;
use App\Domain\Opportunities\Enums\OpportunityStatus;
use App\Models\Opportunity;
use App\Models\Sector;
use App\Services\InvestmentGeography;
use App\Services\OpportunityManagement;
use App\Services\OpportunityManagementInstallation;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Inertia\Inertia;
use Inertia\Response;
class OpportunityManagementController extends Controller
{
public function installation(Request $request, OpportunityManagementInstallation $service): JsonResponse|Response
{
return $request->expectsJson() ? response()->json($service->preview()) : Inertia::render('management/opportunity-install', $service->preview());
}
public function applyInstallation(Request $request, OpportunityManagementInstallation $service): RedirectResponse
{
$data = $request->validate(['hash' => 'required|string|size:64', 'confirm' => 'required|accepted']);
$service->apply($request->user(), $data['hash']);
return back()->with('success', 'Gestão instalada; nenhuma oportunidade foi submetida ou publicada.');
}
public function index(Request $request, OpportunityManagement $service): Response
{
if (! $service->installed()) {
return app(PortalManagementController::class)->catalog($request, 'opportunities');
}
$filters = $request->validate(['q' => 'nullable|string|max:150', 'status' => ['nullable', Rule::in([...array_column(OpportunityStatus::cases(), 'value'), 'returned', 'auto_validation_failed', 'technical_review', 'legal_territorial_review', 'approval_pending', 'publication_pending'])], 'sector_id' => ['nullable', 'integer', Rule::exists('sectors', 'id')->whereNull('deleted_at')], 'geography_scope' => ['nullable', Rule::in(['unspecified', 'specific', 'multiple', 'national', 'digital'])], 'category' => ['nullable', Rule::in(OpportunityManagement::CATEGORIES)], 'deleted' => 'nullable|boolean', 'page' => 'nullable|integer|min:1']);
$query = Opportunity::query();
if ($filters['deleted'] ?? false) {
$query->onlyTrashed();
}
if ($filters['q'] ?? null) {
$query->where(fn ($q) => $q->whereLike('title', '%'.$filters['q'].'%')->orWhereLike('reference', '%'.$filters['q'].'%'));
}
if ($filters['status'] ?? null) {
$query->where('status', $filters['status']);
}
if ($filters['category'] ?? null) {
$query->where('opportunity_category', $filters['category']);
}
if ($filters['sector_id'] ?? null) {
$query->where('sector_id', $filters['sector_id']);
}
if ($filters['geography_scope'] ?? null) {
$query->where('geography_scope', $filters['geography_scope']);
}
return Inertia::render('management/opportunities', ['records' => $query->orderByDesc('id')->paginate(20)->withQueryString(), 'filters' => $filters, 'counts' => Opportunity::selectRaw('status,count(*) AS total')->groupBy('status')->pluck('total', 'status'), 'categories' => OpportunityManagement::CATEGORIES, 'geographyReviewCount' => Opportunity::where('geography_scope', 'unspecified')->count(), 'sectors' => Sector::orderBy('name')->get(['id', 'name'])]);
}
public function edit(Request $request, OpportunityManagement $service, ?int $id = null): Response
{
if (! $service->installed()) {
return app(PortalManagementController::class)->edit('opportunities', $id);
}
$record = $id ? Opportunity::withTrashed()->findOrFail($id) : null;
$values = $record ? ($record->management_draft ? json_decode($record->management_draft, true) : $record->only(OpportunityManagement::FIELDS)) : [];
$classification = $id ? DB::table('audit_events')->where('source_system', 'opportunity-origin-review')->where('after_data->opportunity_id', $id)->orderByDesc('occurred_at')->orderByDesc('id')->value('after_data') : null;
return Inertia::render('management/opportunity-draft', ['record' => $record, 'values' => $values, 'etag' => $record ? $service->etag($record) : null, 'readOnly' => str_ends_with($request->path(), '/view'), 'closedVersion' => $record ? $service->closed($record) : false, 'classification' => $classification ? json_decode($classification, true)['classification'] : 'undetermined', 'sectors' => Sector::where('is_active', true)->orderBy('name')->get(['id', 'name']), 'categories' => OpportunityManagement::CATEGORIES,
'territoryPath' => app(InvestmentGeography::class)->path($values['primary_territory_id'] ?? null, true),
'history' => $id ? DB::table('audit_events')->where('source_system', 'opportunity-management')->where('after_data->record_id', $id)->orderByDesc('occurred_at')->get(['id', 'action', 'actor_user_id', 'occurred_at']) : []]);
}
public function save(Request $request, OpportunityManagement $service, ?int $id = null): JsonResponse
{
$record = $service->save($request->user(), $request->all(), $id);
if (! $id) {
$request->session()->flash('success', 'Rascunho guardado no servidor. Pode continuar o preenchimento; não foi submetido.');
}
return response()->json(['id' => $record->id, 'etag' => $service->etag($record), 'message' => 'Rascunho guardado no servidor. Não foi submetido, aprovado ou publicado.'], $id ? 200 : 201)->header('ETag', '"'.$service->etag($record).'"');
}
public function lifecycle(Request $request, int $id, OpportunityManagement $service): JsonResponse
{
abort_unless($service->installed(), 503);
$record = $service->lifecycle($request->user(), $id, $request->all());
return response()->json(['id' => $record->id, 'message' => $request->input('action') === 'restore' ? 'Restaurado como rascunho; nova revisão necessária antes de publicar.' : 'Exclusão lógica/arquivo registado; histórico e relações preservados.']);
}
}
@@ -10,6 +10,7 @@ use App\Models\User;
use App\Services\InterestWorkflow;
use App\Services\InvestmentGeography;
use App\Services\InvestmentWorkspace;
use App\Services\OpportunityManagement;
use App\Services\PortalAudit;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse;
@@ -257,6 +258,9 @@ class PortalManagementController extends Controller
public function save(Request $request, string $resource, ?int $id = null): RedirectResponse
{
if ($resource === 'opportunities' && app(OpportunityManagement::class)->installed()) {
throw ValidationException::withMessages(['status' => 'Use Gestão de Oportunidades para guardar uma versão de rascunho; publicação não é uma edição.']);
}
$model = $resource === 'sectors' ? Sector::class : Opportunity::class;
$record = $id ? $model::findOrFail($id) : new $model;
$rules = $resource === 'sectors' ? [
+9
View File
@@ -11,11 +11,20 @@ use Illuminate\Database\Eloquent\SoftDeletes;
/**
* @property string|null $primary_territory_id
* @property int $territory_version
* @property int $management_version
* @property string|null $management_draft
* @property string|null $management_creation_key
* @property string|null $first_submitted_at
* @property bool $management_closed_once
* @property string|null $opportunity_category
* @property string|null $estimated_investment_currency
*/
class Opportunity extends Model
{
use SoftDeletes;
protected $hidden = ['management_draft', 'management_creation_key', 'management_version', 'first_submitted_at', 'management_closed_once'];
protected $fillable = [
'sector_id', 'reference', 'title', 'slug', 'summary', 'description',
'province', 'district', 'promoter_name', 'promoter_type',
+166
View File
@@ -0,0 +1,166 @@
<?php
namespace App\Services;
use App\Models\Opportunity;
use App\Models\User;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
class OpportunityManagement
{
public const CATEGORIES = ['investment_project', 'real_estate', 'land_rights', 'business_sale', 'business_partnership', 'franchise', 'concession', 'financing', 'supply', 'other'];
public const FIELDS = ['title', 'summary', 'description', 'sector_id', 'promoter_name', 'promoter_type', 'maturity_level', 'maturity_label', 'financing_modality', 'expected_impact', 'estimated_investment_amount', 'estimated_investment_currency', 'opportunity_category', 'primary_territory_id', 'province', 'district', 'geography_scope'];
public function installed(): bool
{
return Schema::hasColumn('opportunities', 'management_version');
}
public function etag(Opportunity $record): string
{
return hash('sha256', json_encode($record->fresh()->getRawOriginal(), JSON_THROW_ON_ERROR));
}
public function closed(Opportunity $record): bool
{
return $record->first_submitted_at !== null || $record->management_closed_once || ! in_array($record->status, ['draft'], true);
}
/** @param array<string,mixed> $input */
public function save(User $actor, array $input, ?int $id = null): Opportunity
{
abort_unless($actor->can('manage-portal'), 403);
abort_unless($this->installed(), 503, 'Instalação autenticada ainda necessária.');
$data = Validator::make($input, [
'etag' => [$id ? 'required' : 'nullable', 'string', 'size:64'],
'creation_key' => [$id ? 'nullable' : 'required', 'uuid'],
'title' => ['nullable', 'string', 'max:150'], 'summary' => ['nullable', 'string', 'max:500'],
'description' => ['nullable', 'string', 'max:50000'], 'promoter_name' => ['nullable', 'string', 'max:200'],
'promoter_type' => ['nullable', Rule::in(['public', 'private', 'ppp', 'cooperative', 'association', 'community', 'other', $id ? Opportunity::withTrashed()->findOrFail($id)->promoter_type : null])],
'maturity_level' => ['nullable', 'integer', 'between:1,6'],
'financing_modality' => ['nullable', 'string', 'max:120'],
'expected_impact' => ['nullable', 'string', 'max:10000'],
'sector_id' => ['nullable', 'integer', Rule::exists('sectors', 'id')->whereNull('deleted_at')->where('is_active', true)],
'opportunity_category' => ['nullable', Rule::in(self::CATEGORIES)],
'estimated_investment_amount' => ['nullable', 'regex:/^\d{1,16}(\.\d{1,2})?$/'],
'estimated_investment_currency' => ['nullable', 'in:MZN,USD,EUR,ZAR'],
'reason' => ['required', 'string', 'min:20', 'max:1000'],
'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid'],
])->validate();
return DB::transaction(function () use ($actor, $data, $id) {
DB::select('SELECT pg_advisory_xact_lock(91026, 100000)');
if (! $id && ($existing = Opportunity::withTrashed()->where('management_creation_key', $data['creation_key'])->first())) {
$snapshot = $existing->management_draft ? json_decode($existing->management_draft, true) : $existing->only(self::FIELDS);
foreach (array_intersect_key($data, array_flip(self::FIELDS)) as $key => $value) {
if (($snapshot[$key] ?? null) != $value) {
throw ValidationException::withMessages(['creation_key' => 'Esta chave já foi utilizada com dados diferentes.']);
}
}
return $existing;
}
$record = $id ? Opportunity::withTrashed()->whereKey($id)->lockForUpdate()->firstOrFail() : new Opportunity;
if ($id) {
$this->check($record, $data['etag']);
abort_if($record->trashed() || $record->status === 'archived', 409, 'Restaure antes de editar.');
}
$before = $record->getAttributes();
$changes = array_intersect_key($data, array_flip(self::FIELDS));
if (array_key_exists('maturity_level', $changes)) {
$labels = [1 => 'Ideia identificada', 'Pré-estudo disponível', 'Estudo de viabilidade em curso', 'Projecto estruturado', 'Pronto para investimento', 'Em negociação ou implementação'];
$changes['maturity_label'] = $labels[$changes['maturity_level'] ?? 0] ?? null;
}
if (array_intersect_key($data, InvestmentGeography::FIELDS) !== []) {
$path = app(InvestmentGeography::class)->selection($data, true);
$changes['primary_territory_id'] = $path === [] ? null : $path[array_key_last($path)]->id;
$changes['province'] = $path[0]->name ?? null;
$changes['district'] = $path[1]->name ?? null;
$changes['geography_scope'] = $path === [] ? 'unspecified' : 'specific';
}
if (! $id) {
$record->reference = 'INV-MZ-GEN-'.random_int(1000000000000000, 9999999999999999);
$record->slug = strtolower($record->reference);
$record->status = 'draft';
$record->management_creation_key = $data['creation_key'];
$record->management_version = 1;
$record->estimated_investment_currency = null;
} else {
$record->management_version++;
}
if ($id && $this->closed($record)) {
$record->management_closed_once = true;
$previous = $record->management_draft ? json_decode($record->management_draft, true) : $record->only(self::FIELDS);
$record->management_draft = json_encode([...$previous, ...$changes], JSON_THROW_ON_ERROR);
} else {
foreach ($changes as $key => $value) {
$record->{$key} = $value;
}
}
$record->save();
$this->audit($record, $actor, $before, $id ? 'draft_updated' : 'draft_created', $data['reason']);
return $record;
});
}
/** @param array<string,mixed> $input */
public function lifecycle(User $actor, int $id, array $input): Opportunity
{
abort_unless($actor->can('manage-portal'), 403);
$data = Validator::make($input, ['etag' => ['required', 'string', 'size:64'], 'action' => ['required', 'in:delete,restore'], 'reason' => ['required', 'string', 'min:20', 'max:1000'], 'confirm' => ['required', 'accepted']])->validate();
return DB::transaction(function () use ($actor, $id, $data) {
$record = Opportunity::withTrashed()->whereKey($id)->lockForUpdate()->firstOrFail();
$this->check($record, $data['etag']);
$before = $record->getAttributes();
if ($data['action'] === 'restore') {
abort_unless($record->trashed() || $record->status === 'archived', 409, 'Registo não está eliminado/arquivado.');
if ($record->sector_id) {
Validator::make(['sector_id' => $record->sector_id], ['sector_id' => [Rule::exists('sectors', 'id')->whereNull('deleted_at')->where('is_active', true)]])->validate();
}
$record->deleted_at = null;
$record->status = 'draft';
$record->published_at = null;
if ($this->closed($record) && ! $record->management_draft) {
$record->management_draft = json_encode($record->only(self::FIELDS), JSON_THROW_ON_ERROR);
}
} else {
abort_if($record->trashed() || $record->status === 'archived', 409, 'Registo já eliminado/arquivado.');
if ($this->closed($record)) {
$record->management_closed_once = true;
$record->status = 'archived';
} else {
$record->deleted_at = now();
}
}
$record->management_version++;
$record->save();
$this->audit($record, $actor, $before, $data['action'], $data['reason']);
return $record;
});
}
private function check(Opportunity $record, string $etag): void
{
if (! hash_equals($this->etag($record), $etag)) {
throw new HttpResponseException(response()->json(['message' => 'Conflito de versão.', 'errors' => ['etag' => ['O registo mudou. Os dados preenchidos foram preservados; abra a versão atual noutra aba antes de reconciliar.']]], 409));
}
}
/** @param array<string,mixed> $before */
private function audit(Opportunity $record, User $actor, array $before, string $action, string $reason): void
{
DB::table('audit_events')->insert(['source_system' => 'opportunity-management', 'entity_type' => 'opportunities', 'actor_user_id' => $actor->id, 'action' => $action, 'data_classification' => 'restricted',
'before_data' => json_encode(['record_id' => $record->id, 'snapshot' => Crypt::encryptString(json_encode($before, JSON_THROW_ON_ERROR))], JSON_THROW_ON_ERROR),
'after_data' => json_encode(['record_id' => $record->id, 'version' => $record->management_version, 'reason' => Crypt::encryptString($reason), 'snapshot' => Crypt::encryptString(json_encode($record->getAttributes(), JSON_THROW_ON_ERROR))], JSON_THROW_ON_ERROR)]);
}
}
@@ -0,0 +1,54 @@
<?php
namespace App\Services;
use App\Models\User;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
class OpportunityManagementInstallation
{
public const MIGRATION = '2026_10_09_020000_extend_opportunity_management';
public function fingerprint(): string
{
$files = [__FILE__, app_path('Models/Opportunity.php'), app_path('Services/OpportunityManagement.php'), app_path('Http/Controllers/OpportunityManagementController.php'), app_path('Http/Controllers/PortalManagementController.php'), database_path('migrations/'.self::MIGRATION.'.php'), base_path('routes/web.php'), resource_path('js/pages/management/opportunity-draft.tsx'), resource_path('js/pages/management/opportunities.tsx')];
return hash('sha256', json_encode(array_map(fn ($file) => hash_file('sha256', $file), $files), JSON_THROW_ON_ERROR));
}
/** @return array<string,mixed> */
public function preview(): array
{
$path = storage_path('app/private/investmoz-v2/opportunity-management-activation-proof.json');
$proof = is_file($path) ? json_decode(file_get_contents($path) ?: '{}', true) : [];
$identity = DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');
$code = $this->fingerprint();
$ready = ($proof['restore_verified'] ?? false) && ($proof['compatibility_verified'] ?? false) && ($proof['reversal_verified'] ?? false) && ($proof['qa_passed'] ?? false) && ($proof['code_hash'] ?? '') === $code && ($proof['target']['database'] ?? '') === $identity->database && (int) ($proof['target']['port'] ?? 0) === (int) $identity->port && strtotime($proof['verified_at'] ?? '') >= time() - 86400 && is_file($proof['dump_path'] ?? '') && hash_file('sha256', $proof['dump_path']) === ($proof['sha256'] ?? null);
$installed = app(OpportunityManagement::class)->installed();
return ['installed' => $installed, 'ready' => $ready, 'target' => $identity, 'code_hash' => $code, 'hash' => hash('sha256', json_encode([$identity, $code, $ready, $installed], JSON_THROW_ON_ERROR)), 'migration' => self::MIGRATION, 'backupDate' => $proof['verified_at'] ?? null, 'changes' => ['Permitir setor, título e moeda ausentes em rascunhos; nenhum preenchimento fictício.', 'Acrescentar versão, categoria opcional, rascunho de revisão, chave idempotente e marca de primeira submissão à entidade existente.', 'Impedir eliminação física de versões submetidas; preservar relações e classificações.', 'Nenhuma submissão, aprovação ou publicação automática.'], 'rollback' => 'Down apenas antes de novos eventos/rascunhos incompletos. Depois preservar e reconciliar dados; restauro integral requer janela autorizada e reconciliação de alterações posteriores.'];
}
public function apply(User $actor, string $hash): void
{
abort_unless($actor->can('manage-portal'), 403);
DB::transaction(function () use ($actor, $hash) {
DB::select('SELECT pg_advisory_xact_lock(91026, 100000)');
$preview = $this->preview();
abort_unless(hash_equals($preview['hash'], $hash), 409, 'Plano mudou; reveja.');
if ($preview['installed']) {
return;
}
abort_unless($preview['ready'], 422, 'Backup/restauro, QA, compatibilidade e reversão desta versão necessários.');
config(['opportunity_management.authenticated_installation' => true]);
try {
$exit = Artisan::call('migrate', ['--path' => 'database/migrations/'.self::MIGRATION.'.php', '--force' => true]);
abort_unless($exit === 0, 500, 'Migração falhou.');
} finally {
config(['opportunity_management.authenticated_installation' => false]);
}
DB::table('audit_events')->insert(['source_system' => 'opportunity-management-install', 'entity_type' => 'installation', 'action' => 'opportunity_management_installed', 'actor_user_id' => $actor->id, 'after_data' => json_encode(['code_hash' => $preview['code_hash'], 'migration' => self::MIGRATION], JSON_THROW_ON_ERROR)]);
});
}
}