feat(offers): implement phase four private details and confidentiality in QA
This commit is contained in:
@@ -6,15 +6,84 @@ use App\Models\Opportunity;
|
||||
use App\Services\OpportunityCanonicalContract;
|
||||
use App\Services\OpportunityManagement;
|
||||
use App\Services\OpportunityProfileWorkflow;
|
||||
use App\Services\OpportunityResources;
|
||||
use App\Services\PortalProfileAccess;
|
||||
use App\Services\PrivateOfferConfidentiality;
|
||||
use App\Services\PrivateOfferPreparation;
|
||||
use App\Services\VerifiedDocumentBinary;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
|
||||
final class PrivateOfferPreparationController extends Controller
|
||||
{
|
||||
public function resources(Request $request, PrivateOfferPreparation $service, int $id): JsonResponse
|
||||
{
|
||||
$record = $service->record($request->user(), $id);
|
||||
$resources = [];
|
||||
foreach (['images', 'documents'] as $kind) {
|
||||
$resources[$kind] = array_map(fn ($row) => ['id' => $row->id, 'version' => $row->version, 'deleted' => $row->deleted_at !== null,
|
||||
'caption' => $row->payload['caption'] ?? null, 'digitally_edited' => $row->payload['digitally_edited'] ?? null,
|
||||
'edit_description' => $row->payload['edit_description'] ?? null,
|
||||
'scan' => $row->file->malware_scan_status ?? 'pending'], app(OpportunityResources::class)->listing($id, $kind));
|
||||
}
|
||||
|
||||
return response()->json(['resources' => $resources, 'etag' => app(OpportunityManagement::class)->etag($record),
|
||||
'internalProofAccess' => app(PrivateOfferConfidentiality::class)->internal($request->user(), $record)]);
|
||||
}
|
||||
|
||||
public function attachment(Request $request, PrivateOfferPreparation $service, int $id, string $kind, string $resourceId): \Symfony\Component\HttpFoundation\Response
|
||||
{
|
||||
$record = $service->record($request->user(), $id);
|
||||
abort_unless(in_array($kind, ['documents', 'images'], true), 404);
|
||||
$link = DB::table('opportunity_'.$kind)->where('opportunity_id', $id)->where('id', $resourceId)->whereNull('deleted_at')->first();
|
||||
abort_unless($link !== null, 404);
|
||||
$document = DB::table('documents')->where('id', $link->document_id)->whereNull('deleted_at')->first();
|
||||
abort_unless($document !== null, 404);
|
||||
|
||||
return app(VerifiedDocumentBinary::class)->respond($document);
|
||||
}
|
||||
|
||||
public function confidentiality(Request $request, PrivateOfferConfidentiality $privacy, int $id): JsonResponse|Response
|
||||
{
|
||||
$overview = $privacy->overview($request->user(), $id);
|
||||
|
||||
return $request->expectsJson() ? response()->json($overview) : Inertia::render('offers/confidentiality', ['offerId' => $id]);
|
||||
}
|
||||
|
||||
public function confidentialityAction(Request $request, PrivateOfferConfidentiality $privacy, int $id): JsonResponse
|
||||
{
|
||||
return response()->json($privacy->act($request->user(), $id, $request->all()));
|
||||
}
|
||||
|
||||
public function confidentialRead(Request $request, PrivateOfferConfidentiality $privacy, int $id): JsonResponse
|
||||
{
|
||||
try {
|
||||
$result = $privacy->read($request->user(), $id);
|
||||
} catch (HttpExceptionInterface $error) {
|
||||
app(PortalProfileAccess::class)->audit($request->user(), 'offer_confidential_denied', ['record_id' => $id, 'http_status' => $error->getStatusCode()]);
|
||||
throw $error;
|
||||
}
|
||||
abort_if(isset($result['denied']), 403, 'É necessária aceitação do NDA e autorização expressa do vendedor para esta versão.');
|
||||
|
||||
return response()->json($result);
|
||||
}
|
||||
|
||||
public function nda(Request $request, PrivateOfferConfidentiality $privacy, int $id): \Symfony\Component\HttpFoundation\Response
|
||||
{
|
||||
$overview = $privacy->overview($request->user(), $id);
|
||||
abort_unless($overview['nda'], 409, 'O NDA aprovado ainda não foi disponibilizado.');
|
||||
app(PortalProfileAccess::class)->audit($request->user(), 'offer_nda_access', ['record_id' => $id, 'version_hash' => $overview['version_hash'], 'nda' => $overview['nda']]);
|
||||
|
||||
$document = DB::table('documents')->where('id', $overview['nda']['document_id'])->firstOrFail();
|
||||
abort_unless((int) $document->version_no === $overview['nda']['version'] && hash_equals(trim($document->sha256), $overview['nda']['sha256']), 409, 'O exemplar do NDA mudou; actualize antes de continuar.');
|
||||
|
||||
return app(VerifiedDocumentBinary::class)->respond($document);
|
||||
}
|
||||
|
||||
public function index(Request $request, PortalProfileAccess $access): Response
|
||||
{
|
||||
$filters = $request->validate(['state' => 'nullable|in:draft,submitted,in_review,needs_information,rejected,approved']);
|
||||
@@ -40,7 +109,9 @@ final class PrivateOfferPreparationController extends Controller
|
||||
$options = app(OpportunityCanonicalContract::class)->options($request->user(), $record);
|
||||
|
||||
return Inertia::render('offers/preparation', ['record' => $presentation, 'contexts' => $contexts,
|
||||
'contacts' => $options['contacts'], 'contactInvestors' => $options['contactInvestors']]);
|
||||
'contacts' => $options['contacts'], 'contactInvestors' => $options['contactInvestors'],
|
||||
'sectors' => DB::table('sectors')->where('is_active', true)->orderBy('name')->get(['id', 'name']),
|
||||
'propertyTypes' => array_values(array_filter($options['definitions']['realEstatePatch']['properties']['property_type']['enum'], fn ($type) => is_string($type)))]);
|
||||
}
|
||||
|
||||
public function save(Request $request, PrivateOfferPreparation $service, ?int $id = null): JsonResponse
|
||||
|
||||
@@ -45,6 +45,7 @@ class OpportunityLibrarySupport
|
||||
*/
|
||||
public function attach(User $actor, Opportunity $opportunity, array $input): \stdClass
|
||||
{
|
||||
abort_if($opportunity->isPrivateOfferPreparation(), 422, 'Os comprovativos de Ofertas usam originais reservados à validação interna.');
|
||||
app(PortalProfileAccess::class)->authorize($actor, 'edit', $opportunity);
|
||||
$data = Validator::make($input, ['resource_id' => 'required|integer|min:1', 'creation_key' => 'required|uuid', 'etag' => 'required|string|size:64', 'reason' => 'required|string|min:20|max:1000', 'section' => 'nullable|string|max:255', 'supported_statement' => 'nullable|string|max:2000'])->validate();
|
||||
|
||||
|
||||
@@ -92,7 +92,7 @@ class OpportunityResources
|
||||
}
|
||||
abort_if(! $id && DB::table($table)->where('id', $resourceId)->exists(), 409, 'Esta criação já foi registada; recupere o recurso existente.');
|
||||
$active = DB::table($table)->where('opportunity_id', $opportunityId)->whereNull('deleted_at');
|
||||
abort_if(! $id && $active->count() >= ($kind === 'locations' ? 50 : ($kind === 'images' ? 20 : 100)), 422, 'Limite de recursos atingido.');
|
||||
abort_if(! $id && $active->count() >= $this->limit($opportunity, $kind), 422, 'Limite de recursos atingido.');
|
||||
if ($kind === 'locations') {
|
||||
$others = (clone $active)->when($id, fn ($q) => $q->where('id', '!=', $id))->get();
|
||||
foreach ($others as $other) {
|
||||
@@ -172,7 +172,7 @@ class OpportunityResources
|
||||
abort_if(($data['action'] === 'delete') === ($record->deleted_at !== null), 409, 'Estado já alterado.');
|
||||
$payload = json_decode($record->payload, true);
|
||||
if ($data['action'] === 'restore') {
|
||||
abort_if(DB::table($table)->where('opportunity_id', $opportunityId)->whereNull('deleted_at')->count() >= ($kind === 'locations' ? 50 : ($kind === 'images' ? 20 : 100)), 422, 'Limite de recursos ativos atingido; reconcilie antes de restaurar.');
|
||||
abort_if(DB::table($table)->where('opportunity_id', $opportunityId)->whereNull('deleted_at')->count() >= $this->limit($opportunity, $kind), 422, 'Limite de recursos ativos atingido; reconcilie antes de restaurar.');
|
||||
$this->validatePayload($kind, $payload, $opportunityId);
|
||||
// Restoration never silently reclaims a primary/cover/order occupied by another resource.
|
||||
if ($kind === 'images') {
|
||||
@@ -221,12 +221,22 @@ class OpportunityResources
|
||||
*/
|
||||
private function validatePayload(string $kind, array $payload, int $opportunityId): array
|
||||
{
|
||||
$offer = Opportunity::findOrFail($opportunityId);
|
||||
if ($offer->isPrivateOfferPreparation()) {
|
||||
Validator::make($payload, ['visibility' => 'required|in:internal',
|
||||
...($kind === 'images' ? ['digitally_edited' => 'required|boolean', 'edit_description' => 'nullable|required_if:digitally_edited,true|string|max:1000'] : []),
|
||||
...($kind === 'documents' ? ['category' => 'required|in:real_estate_proof', 'classification' => 'required|in:restricted'] : [])])->validate();
|
||||
abort_if($kind === 'documents' && $offer->opportunity_category !== 'real_estate', 422, 'Este percurso aceita comprovativos imobiliários.');
|
||||
}
|
||||
$rules = ['title' => 'nullable|string|max:120', 'source_reference' => 'nullable|string|max:2000', 'source_date' => 'nullable|date_format:Y-m-d', 'visibility' => 'nullable|in:internal,authenticated,public'];
|
||||
if ($kind === 'locations') {
|
||||
$rules += ['country_code' => ['nullable', app(CountryCatalogue::class)->rule()]];
|
||||
$rules += ['province_id' => 'nullable|uuid', 'district_id' => 'nullable|uuid', 'admin_post_id' => 'nullable|uuid', 'locality_id' => 'nullable|uuid', 'role' => 'nullable|in:headquarters,production,raw_material,storage,logistics,market,support,other', 'role_description' => 'nullable|string|max:1000', 'operational_unit' => 'nullable|string|max:120', 'is_primary' => 'nullable|boolean', 'address' => 'nullable|string|max:300', 'geometry' => 'nullable|array', 'area_value' => 'nullable|numeric|gt:0', 'area_unit' => ['nullable', Rule::in(self::AREA_UNITS)], 'allocation_percentage' => 'nullable|numeric|between:0,100', 'territorial_purpose' => 'nullable|in:implementation,context,impact,coverage', 'multi_district_rationale' => 'nullable|string|max:1000'];
|
||||
} elseif ($kind === 'images') {
|
||||
$rules += ['role' => 'nullable|in:cover,gallery,location,asset,product,plan,rendering,evidence,other', 'role_description' => 'nullable|string|max:1000', 'is_cover' => 'nullable|boolean', 'caption' => 'nullable|string|max:300', 'alt_text' => 'nullable|string|max:250', 'location_id' => ['nullable', 'uuid', Rule::exists('opportunity_location_drafts', 'id')->where('opportunity_id', $opportunityId)->whereNull('deleted_at')], 'captured_at' => 'nullable|date_format:Y-m-d|before_or_equal:today', 'author_source' => 'nullable|string|max:150', 'rights_status' => 'nullable|in:owned,licensed,authorized,public_domain', 'rights_document_id' => ['nullable', 'uuid', Rule::exists('opportunity_documents', 'id')->where('opportunity_id', $opportunityId)->whereNull('deleted_at')], 'rights_valid_until' => 'nullable|date_format:Y-m-d', 'sort_order' => 'nullable|integer|min:0'];
|
||||
if ($offer->isPrivateOfferPreparation()) {
|
||||
$rules += ['digitally_edited' => 'boolean', 'edit_description' => 'nullable|string|max:1000'];
|
||||
}
|
||||
} else {
|
||||
$rules += ['category' => 'nullable|string|max:100', 'issuer' => 'nullable|string|max:255', 'edition' => 'nullable|string|max:120', 'valid_until' => 'nullable|date_format:Y-m-d', 'classification' => 'nullable|in:public,internal,confidential,restricted', 'section' => 'nullable|string|max:255', 'supported_statement' => 'nullable|string|max:2000'];
|
||||
}
|
||||
@@ -257,6 +267,11 @@ class OpportunityResources
|
||||
return $data;
|
||||
}
|
||||
|
||||
private function limit(Opportunity $record, string $kind): int
|
||||
{
|
||||
return $kind === 'locations' ? 50 : ($kind === 'images' ? ($record->isPrivateOfferPreparation() ? 6 : 20) : 100);
|
||||
}
|
||||
|
||||
/** @return array{string,string} */
|
||||
private function store(string $kind, UploadedFile $file): array
|
||||
{
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
|
||||
/** The same opportunity owns consent, grants and history. No automatic publication. */
|
||||
final class PrivateOfferConfidentiality
|
||||
{
|
||||
public function internal(User $actor, Opportunity $record): bool
|
||||
{
|
||||
$access = app(PortalProfileAccess::class);
|
||||
|
||||
return $access->canView($actor, $record) && $access->mfa($actor) && ! $access->has($actor, 'auditor') && ! $access->conflict($actor, $record)
|
||||
&& $access->scoped($actor, 'validator', $record->organization_id, $record->opportunity_category);
|
||||
}
|
||||
|
||||
public function seller(User $actor, Opportunity $record): bool
|
||||
{
|
||||
$access = app(PortalProfileAccess::class);
|
||||
|
||||
return (int) $record->owner_user_id === $actor->id && $access->promoterRecordScope($actor, $record)
|
||||
&& $access->canCreate($actor, $record->organization_id, $record->opportunity_category) && $access->operational($actor, 'edit', $record->id);
|
||||
}
|
||||
|
||||
/** @return array<string,mixed>|null */
|
||||
public function nda(): ?array
|
||||
{
|
||||
$definition = config('private_offers.nda');
|
||||
if (! is_array($definition) || empty($definition['approval_reference']) || empty($definition['document_id']) || empty($definition['version']) || empty($definition['sha256'])) {
|
||||
return null;
|
||||
}
|
||||
$doc = DB::table('documents')->where('id', $definition['document_id'])->whereNull('deleted_at')->first();
|
||||
if (! $doc || $doc->status !== 'active' || $doc->malware_scan_status !== 'clean' || (int) $doc->version_no !== (int) $definition['version']
|
||||
|| ! hash_equals(trim($doc->sha256), $definition['sha256']) || ! hash_equals(trim($doc->sha256), trim((string) $doc->malware_scanned_sha256))) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
app(VerifiedDocumentBinary::class)->respond($doc);
|
||||
} catch (HttpExceptionInterface $error) {
|
||||
return null;
|
||||
}
|
||||
$result = ['document_id' => $doc->id, 'version' => (int) $doc->version_no, 'sha256' => trim($doc->sha256), 'approval_reference' => $definition['approval_reference']];
|
||||
|
||||
return [...$result, 'fingerprint' => hash('sha256', json_encode($result, JSON_THROW_ON_ERROR))];
|
||||
}
|
||||
|
||||
private function company(int $id, bool $lock = false): Opportunity
|
||||
{
|
||||
$record = Opportunity::query()->when($lock, fn ($q) => $q->lockForUpdate())->findOrFail($id);
|
||||
abort_unless($record->isPrivateOfferPreparation() && $record->opportunity_category === 'business_sale', 404);
|
||||
|
||||
return $record;
|
||||
}
|
||||
|
||||
private function approvedHash(Opportunity $record): string
|
||||
{
|
||||
$hash = $record->workflow_context['approval']['hash'] ?? null;
|
||||
abort_unless(is_string($hash) && app(PortalProfileAccess::class)->state($record) === 'approved', 409, 'Esta versão não tem aprovação editorial actual.');
|
||||
try {
|
||||
$snapshot = app(PrivateOfferPreparation::class)->snapshot($record);
|
||||
} catch (ValidationException $error) {
|
||||
abort(409, 'A versão ou os suportes exigem reconferência editorial.');
|
||||
}
|
||||
abort_unless(hash_equals($hash, $snapshot['hash']), 409, 'A versão mudou; é necessária reconferência editorial.');
|
||||
|
||||
return $hash;
|
||||
}
|
||||
|
||||
/** PostgreSQL jsonb reorders object keys; identity is the version and checksum, not array order.
|
||||
* @param array<string,mixed> $nda */
|
||||
private function sameNda(mixed $accepted, array $nda): bool
|
||||
{
|
||||
if (! is_array($accepted)) {
|
||||
return false;
|
||||
}
|
||||
foreach (['document_id', 'version', 'sha256', 'approval_reference', 'fingerprint'] as $key) {
|
||||
if (($accepted[$key] ?? null) !== $nda[$key]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function overview(User $actor, int $id): array
|
||||
{
|
||||
$record = $this->company($id);
|
||||
// An interested party learns no private title, contacts, documents or financial values.
|
||||
$seller = $this->seller($actor, $record);
|
||||
$nda = $this->nda();
|
||||
$context = $record->workflow_context['offer_confidentiality'] ?? [];
|
||||
$currentHash = null;
|
||||
try {
|
||||
$currentHash = $this->approvedHash($record);
|
||||
} catch (HttpExceptionInterface $error) {
|
||||
// A previous acceptance remains withdrawable even if the offer was revised.
|
||||
abort_unless($seller || isset($context['acceptances'][(string) $actor->id]), 404);
|
||||
}
|
||||
$history = array_values(array_filter($context['events'] ?? [], fn ($event) => $seller || $event['interested_user_id'] === $actor->id));
|
||||
|
||||
return ['offer_id' => $id, 'nda' => $nda, 'nda_pending' => $nda === null, 'version_hash' => $record->workflow_context['approval']['hash'] ?? null,
|
||||
'etag' => $seller ? app(OpportunityManagement::class)->etag($record) : null,
|
||||
'can_accept' => ! $seller && $nda !== null && $currentHash !== null && ! app(PortalProfileAccess::class)->conflict($actor, $record),
|
||||
'can_authorize' => $seller && $nda !== null && $currentHash !== null,
|
||||
'seller' => $seller, 'requests' => $seller ? array_values($context['acceptances'] ?? []) : [],
|
||||
'grants' => $seller ? array_values($context['grants'] ?? []) : [],
|
||||
'history' => array_map(fn ($event) => array_intersect_key($event, array_flip(['id', 'action', 'actor_id', 'at', 'version_hash', 'nda'])), $history),
|
||||
'acceptance' => $context['acceptances'][(string) $actor->id] ?? null];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed> */
|
||||
public function act(User $actor, int $id, array $input): array
|
||||
{
|
||||
$data = validator($input, ['action' => 'required|in:accept,authorize,revoke,withdraw', 'version_hash' => 'required|string|size:64',
|
||||
'nda_sha256' => 'required_unless:action,revoke,withdraw|string|size:64', 'acceptance_id' => 'required_if:action,authorize|uuid',
|
||||
'nda_fingerprint' => 'required_if:action,accept,authorize|string|size:64',
|
||||
'interested_user_id' => 'required_if:action,authorize,revoke|integer|min:1', 'confirm' => 'required|accepted',
|
||||
'reason' => ['nullable', 'required_if:action,authorize,revoke', 'string', 'max:1000', ...(in_array($input['action'] ?? null, ['authorize', 'revoke'], true) ? ['min:20'] : [])]])->validate();
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $data) {
|
||||
$record = $this->company($id, true);
|
||||
$context = $record->workflow_context;
|
||||
$privacy = $context['offer_confidentiality'] ?? ['acceptances' => [], 'grants' => [], 'events' => []];
|
||||
$action = $data['action'];
|
||||
$target = in_array($action, ['authorize', 'revoke'], true) ? (string) $data['interested_user_id'] : (string) $actor->id;
|
||||
$before = ['acceptance' => $privacy['acceptances'][$target] ?? null, 'grant' => $privacy['grants'][$target] ?? null];
|
||||
if (in_array($action, ['authorize', 'revoke'], true)) {
|
||||
abort_unless($this->seller($actor, $record), 403);
|
||||
} elseif ($action === 'accept') {
|
||||
abort_if($this->seller($actor, $record) || app(PortalProfileAccess::class)->conflict($actor, $record), 403);
|
||||
}
|
||||
if (in_array($action, ['accept', 'authorize'], true)) {
|
||||
$nda = $this->nda();
|
||||
abort_unless($nda !== null, 409, 'O exemplar aprovado do NDA ainda não foi disponibilizado.');
|
||||
abort_unless(hash_equals($this->approvedHash($record), $data['version_hash']) && hash_equals($nda['sha256'], $data['nda_sha256'])
|
||||
&& hash_equals($nda['fingerprint'], $data['nda_fingerprint']), 409);
|
||||
$subject = User::findOrFail((int) $target);
|
||||
abort_unless($subject->hasVerifiedEmail() && ! app(PortalProfileAccess::class)->conflict($subject, $record), 403);
|
||||
if ($action === 'accept') {
|
||||
$privacy['acceptances'][$target] = ['id' => (string) Str::uuid(), 'actor_id' => $actor->id, 'at' => now()->toIso8601String(),
|
||||
'version_hash' => $data['version_hash'], 'nda' => $nda, 'access_revision' => (int) $subject->portal_access_revision];
|
||||
unset($privacy['grants'][$target]); // A fresh acceptance never reuses a previous seller decision.
|
||||
} else {
|
||||
$acceptance = $privacy['acceptances'][$target] ?? null;
|
||||
abort_unless($acceptance && $acceptance['id'] === $data['acceptance_id'] && $acceptance['version_hash'] === $data['version_hash']
|
||||
&& $this->sameNda($acceptance['nda'], $nda) && $acceptance['access_revision'] === (int) $subject->portal_access_revision, 409);
|
||||
$privacy['grants'][$target] = ['interested_user_id' => (int) $target, 'seller_id' => $actor->id, 'at' => now()->toIso8601String(),
|
||||
'version_hash' => $data['version_hash'], 'acceptance_id' => $acceptance['id'], 'nda' => $nda];
|
||||
}
|
||||
} else {
|
||||
$previous = $privacy[$action === 'withdraw' ? 'acceptances' : 'grants'][$target] ?? null;
|
||||
abort_unless($previous && $previous['version_hash'] === $data['version_hash'], 409);
|
||||
unset($privacy['grants'][$target]);
|
||||
if ($action === 'withdraw') {
|
||||
unset($privacy['acceptances'][$target]);
|
||||
}
|
||||
}
|
||||
$event = ['id' => (string) Str::uuid(), 'action' => $action, 'actor_id' => $actor->id, 'interested_user_id' => (int) $target,
|
||||
'version_hash' => $data['version_hash'], 'at' => now()->toIso8601String(), 'nda_sha256' => $data['nda_sha256'] ?? null,
|
||||
'nda' => $nda ?? ($before['acceptance']['nda'] ?? $before['grant']['nda'] ?? null)];
|
||||
$privacy['events'][] = [...$event, 'reason' => Crypt::encryptString($data['reason'] ?? ''), 'before' => $before,
|
||||
'after' => ['acceptance' => $privacy['acceptances'][$target] ?? null, 'grant' => $privacy['grants'][$target] ?? null]];
|
||||
$context['offer_confidentiality'] = $privacy;
|
||||
$record->workflow_context = $context;
|
||||
$record->management_version++;
|
||||
$record->save();
|
||||
app(PortalProfileAccess::class)->audit($actor, 'offer_confidentiality_'.$action, ['record_id' => $id, ...$event]);
|
||||
|
||||
return ['recorded' => true, 'event_id' => $event['id']];
|
||||
});
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function read(User $actor, int $id): array
|
||||
{
|
||||
return DB::transaction(function () use ($actor, $id) {
|
||||
$record = $this->company($id, true);
|
||||
$nda = $this->nda();
|
||||
$privacy = $record->workflow_context['offer_confidentiality'] ?? [];
|
||||
$accept = $privacy['acceptances'][(string) $actor->id] ?? null;
|
||||
$grant = $privacy['grants'][(string) $actor->id] ?? null;
|
||||
$hash = $this->approvedHash($record);
|
||||
$seller = User::find($record->owner_user_id);
|
||||
$subject = User::find($actor->id);
|
||||
$allowed = $nda && $accept && $grant && $seller && $subject && $this->seller($seller, $record) && $subject->hasVerifiedEmail()
|
||||
&& $accept['access_revision'] === (int) $subject->portal_access_revision && $grant['seller_id'] === $seller->id
|
||||
&& $grant['acceptance_id'] === $accept['id'] && $grant['version_hash'] === $hash && $accept['version_hash'] === $hash
|
||||
&& $this->sameNda($grant['nda'], $nda) && $this->sameNda($accept['nda'], $nda) && ! app(PortalProfileAccess::class)->conflict($actor, $record);
|
||||
app(PortalProfileAccess::class)->audit($actor, $allowed ? 'offer_confidential_access' : 'offer_confidential_denied', ['record_id' => $id, 'version_hash' => $hash,
|
||||
'nda' => $nda, 'acceptance_id' => $accept['id'] ?? null]);
|
||||
// Return the refusal after transaction commit so the denied-access audit survives.
|
||||
if (! $allowed) {
|
||||
return ['denied' => true];
|
||||
}
|
||||
|
||||
$business = $record->workflow_context['submission']['payload']['private_offer']['business'] ?? [];
|
||||
foreach (['sector_id' => 'sector', 'secondary_sector_id' => 'secondary_sector'] as $field => $label) {
|
||||
if (isset($business[$field])) {
|
||||
$business[$label] = DB::table('sectors')->where('id', $business[$field])->value('name');
|
||||
}
|
||||
unset($business[$field]);
|
||||
}
|
||||
|
||||
return ['offer_id' => $id, 'version_hash' => $hash, 'business' => $business];
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/** Optional commercial fields confirmed by Tempo for phase four; no title certification. */
|
||||
final class PrivateOfferDetails
|
||||
{
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed> */
|
||||
public function validate(array $input): array
|
||||
{
|
||||
$bytes = file_get_contents(resource_path('data/investmoz-opportunity-modular.schema.json'));
|
||||
if ($bytes === false) {
|
||||
throw new \RuntimeException('Opportunity schema unavailable.');
|
||||
}
|
||||
$schema = json_decode($bytes, true, 512, JSON_THROW_ON_ERROR);
|
||||
$property = $schema['$defs']['realEstatePatch']['properties'];
|
||||
|
||||
return Validator::make($input, [
|
||||
'business' => 'sometimes|nullable|array:sector_id,secondary_sector_id,revenue,cash_flow,currency,reason,availability',
|
||||
'business.sector_id' => ['nullable', 'integer', Rule::exists('sectors', 'id')->where('is_active', true)],
|
||||
'business.secondary_sector_id' => ['nullable', 'integer', Rule::exists('sectors', 'id')->where('is_active', true)],
|
||||
'business.revenue' => ['nullable', 'string', 'regex:/^\d{1,16}(\.\d{1,2})?$/'],
|
||||
'business.cash_flow' => ['nullable', 'string', 'regex:/^-?\d{1,16}(\.\d{1,2})?$/'],
|
||||
'business.currency' => 'nullable|required_with:business.revenue,business.cash_flow|in:MZN,USD',
|
||||
'business.reason' => 'nullable|string|max:1000', 'business.availability' => 'nullable|in:available,sold',
|
||||
'property' => 'sometimes|nullable|array:transaction_type,property_type,land_area,built_area,area_unit,bedrooms,bathrooms,amenities,availability',
|
||||
'property.transaction_type' => 'nullable|in:sale,lease',
|
||||
'property.property_type' => ['nullable', Rule::in($property['property_type']['enum'])],
|
||||
'property.land_area' => 'nullable|numeric|gt:0', 'property.built_area' => 'nullable|numeric|gt:0',
|
||||
'property.area_unit' => ['nullable', Rule::in(OpportunityResources::AREA_UNITS)],
|
||||
'property.bedrooms' => 'nullable|integer|min:0|max:10000', 'property.bathrooms' => 'nullable|integer|min:0|max:10000',
|
||||
'property.amenities' => 'nullable|array|max:100', 'property.amenities.*' => 'string|max:250',
|
||||
'property.availability' => 'nullable|in:available,sold,leased',
|
||||
])->validate();
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $offer */
|
||||
public function assertCategory(array $offer, string $category): void
|
||||
{
|
||||
Validator::make($offer, [
|
||||
'business' => $category === 'business_sale' ? 'nullable|array' : 'prohibited',
|
||||
'property' => $category === 'real_estate' ? 'nullable|array' : 'prohibited',
|
||||
])->validate();
|
||||
}
|
||||
|
||||
/** Snapshot all active linked originals and metadata in the existing editorial version.
|
||||
* @return array<string,array<string,mixed>> */
|
||||
public function resources(Opportunity $record): array
|
||||
{
|
||||
$result = ['documents' => [], 'images' => [], 'locations' => []];
|
||||
foreach (array_keys($result) as $kind) {
|
||||
foreach (app(OpportunityResources::class)->listing($record->id, $kind) as $row) {
|
||||
if ($row->deleted_at !== null) {
|
||||
continue;
|
||||
}
|
||||
if ($kind !== 'locations') {
|
||||
$file = $row->file;
|
||||
$doc = DB::table('documents')->where('id', $row->document_id)->first();
|
||||
if (! $doc || $doc->deleted_at !== null || $doc->status !== 'active' || $doc->malware_scan_status !== 'clean'
|
||||
|| ! hash_equals(trim($doc->sha256), trim((string) $doc->malware_scanned_sha256))) {
|
||||
throw ValidationException::withMessages(['attachments' => 'Aguarde uma análise de segurança válida dos anexos.']);
|
||||
}
|
||||
$result[$kind][$row->id] = ['version' => $row->version, 'document_id' => $row->document_id, 'payload' => $row->payload, 'file' => $file];
|
||||
} else {
|
||||
$result[$kind][$row->id] = ['version' => $row->version, 'payload' => $row->payload];
|
||||
}
|
||||
}
|
||||
ksort($result[$kind]);
|
||||
}
|
||||
if (count($result['images']) > 6) {
|
||||
throw ValidationException::withMessages(['images' => 'A oferta admite no máximo seis fotografias.']);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -15,13 +15,17 @@ final class PrivateOfferPreparation
|
||||
/** @return array<string,mixed> */
|
||||
public function validate(mixed $input, bool $complete = false): array
|
||||
{
|
||||
return Validator::make(['private_offer' => $input], [
|
||||
'private_offer' => 'present|array:price_mode,amount,currency,contact_id',
|
||||
$validated = Validator::make(['private_offer' => $input], [
|
||||
'private_offer' => 'present|array:price_mode,amount,currency,contact_id,business,property',
|
||||
'private_offer.price_mode' => 'nullable|in:amount,negotiable',
|
||||
'private_offer.amount' => ['nullable', 'string', ...($complete ? ['required_if:private_offer.price_mode,amount'] : []), 'prohibited_unless:private_offer.price_mode,amount', 'regex:/^\d{1,16}(\.\d{1,2})?$/'],
|
||||
'private_offer.currency' => ['nullable', ...($complete ? ['required_if:private_offer.price_mode,amount'] : []), 'prohibited_unless:private_offer.price_mode,amount', 'in:MZN,USD'],
|
||||
'private_offer.contact_id' => 'nullable|uuid',
|
||||
'private_offer.business' => 'sometimes|nullable|array',
|
||||
'private_offer.property' => 'sometimes|nullable|array',
|
||||
])->validate()['private_offer'];
|
||||
|
||||
return array_replace($validated, app(PrivateOfferDetails::class)->validate(array_intersect_key($validated, array_flip(['business', 'property']))));
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
@@ -40,6 +44,8 @@ final class PrivateOfferPreparation
|
||||
|
||||
return DB::transaction(function () use ($actor, $input, $id) {
|
||||
$record = app(OpportunityManagement::class)->save($actor, $input, $id, true);
|
||||
$values = app(OpportunityManagement::class)->values($record);
|
||||
app(PrivateOfferDetails::class)->assertCategory($values['private_offer'] ?? [], $values['opportunity_category']);
|
||||
$contactId = app(OpportunityManagement::class)->values($record)['private_offer']['contact_id'] ?? null;
|
||||
if ($contactId && ! app(OpportunityContacts::class)->related($record, $contactId)) {
|
||||
throw ValidationException::withMessages(['private_offer.contact_id' => 'Seleccione um contacto autorizado do promotor.']);
|
||||
@@ -128,6 +134,8 @@ final class PrivateOfferPreparation
|
||||
Validator::make($values, ['title' => 'required|string|max:150', 'description' => 'required|string|max:50000',
|
||||
'opportunity_category' => 'required', 'private_offer.price_mode' => 'required|in:amount,negotiable', 'private_offer.contact_id' => 'required|uuid'])->validate();
|
||||
$offer = $this->validate($values['private_offer'], true);
|
||||
app(PrivateOfferDetails::class)->assertCategory($offer, $values['opportunity_category']);
|
||||
$resources = app(PrivateOfferDetails::class)->resources($record);
|
||||
if (! app(OpportunityContacts::class)->related($record, $offer['contact_id'])) {
|
||||
throw ValidationException::withMessages(['private_offer.contact_id' => 'O contacto já não está disponível neste âmbito.']);
|
||||
}
|
||||
@@ -142,6 +150,10 @@ final class PrivateOfferPreparation
|
||||
$payload = ['title' => $values['title'], 'description' => $values['description'], 'opportunity_category' => $values['opportunity_category'],
|
||||
'owner_user_id' => $record->owner_user_id, 'organization_id' => $record->organization_id, 'private_offer' => $offer,
|
||||
'contact_fingerprint' => hash('sha256', json_encode($contact, JSON_THROW_ON_ERROR)), 'territory' => $path];
|
||||
$extended = isset($offer['business']) || isset($offer['property']) || array_filter($resources) !== [];
|
||||
if ($extended) {
|
||||
$payload['resources'] = $resources;
|
||||
}
|
||||
$normalize = function (mixed $value) use (&$normalize): mixed {
|
||||
if (is_object($value)) {
|
||||
$value = get_object_vars($value);
|
||||
@@ -157,8 +169,10 @@ final class PrivateOfferPreparation
|
||||
};
|
||||
$payload = $normalize($payload);
|
||||
|
||||
return ['payload' => $payload, 'hash' => hash('sha256', json_encode(['contract' => 'private-offer-editorial-v2', 'payload' => $payload], JSON_THROW_ON_ERROR)),
|
||||
'record_version' => $record->management_version, 'contract_version' => 'private-offer-editorial-v2', 'resources' => ['documents' => [], 'images' => [], 'locations' => []]];
|
||||
$contract = $extended ? 'private-offer-editorial-v3' : 'private-offer-editorial-v2';
|
||||
|
||||
return ['payload' => $payload, 'hash' => hash('sha256', json_encode(['contract' => $contract, 'payload' => $payload], JSON_THROW_ON_ERROR)),
|
||||
'record_version' => $record->management_version, 'contract_version' => $contract, 'resources' => $resources];
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
|
||||
@@ -61,7 +61,11 @@ class VerifiedDocumentBinary
|
||||
if ($table === 'opportunity_images') {
|
||||
$query->orWhereRaw("payload->'derivatives' @> ?::jsonb", [json_encode([['document_id' => $document->id]], JSON_THROW_ON_ERROR)]);
|
||||
}
|
||||
$links = $links->concat($query->get(['opportunity_id', 'deleted_at', 'payload']));
|
||||
$rows = $query->get(['opportunity_id', 'deleted_at', 'payload']);
|
||||
foreach ($rows as $link) {
|
||||
$link->resource_kind = $table;
|
||||
}
|
||||
$links = $links->concat($rows);
|
||||
}
|
||||
$privateOrigin = in_array($document->source_system ?? null, ['opportunity-resources', 'opportunity-image-derivatives'], true);
|
||||
if (! $privateOrigin) {
|
||||
@@ -72,6 +76,15 @@ class VerifiedDocumentBinary
|
||||
}
|
||||
$actor = request()->user();
|
||||
abort_unless($actor instanceof User, 403, 'Anexo privado: é necessário acesso autorizado à oportunidade.');
|
||||
foreach ($links as $link) {
|
||||
$offer = Opportunity::withTrashed()->whereKey($link->opportunity_id)->first();
|
||||
if ($offer?->isPrivateOfferPreparation() && $link->resource_kind === 'opportunity_documents') {
|
||||
$allowed = $link->deleted_at === null && ! $offer->trashed() && app(PrivateOfferConfidentiality::class)->internal($actor, $offer);
|
||||
app(PortalProfileAccess::class)->audit($actor, $allowed ? 'offer_proof_access_authorized' : 'offer_proof_access_denied',
|
||||
['record_id' => $offer->id, 'document_id' => $document->id, 'record_version' => $offer->management_version, 'sha256' => trim($document->sha256)]);
|
||||
abort_unless($allowed, 403, 'Comprovativo reservado à validação interna autorizada.');
|
||||
}
|
||||
}
|
||||
foreach ($links as $link) {
|
||||
$opportunity = Opportunity::whereKey($link->opportunity_id)->first();
|
||||
if ($link->deleted_at === null && $opportunity && $opportunity->status !== 'archived'
|
||||
|
||||
Reference in New Issue
Block a user