Add scoped private business verification evidence and expiry
This commit is contained in:
@@ -7,6 +7,7 @@ use App\Models\ExistingBusinessObject;
|
|||||||
use App\Services\ExistingBusinessDrafts;
|
use App\Services\ExistingBusinessDrafts;
|
||||||
use App\Services\ExistingBusinessIntake;
|
use App\Services\ExistingBusinessIntake;
|
||||||
use App\Services\ExistingBusinessObjects;
|
use App\Services\ExistingBusinessObjects;
|
||||||
|
use App\Services\ExistingBusinessVerification;
|
||||||
use Illuminate\Http\JsonResponse;
|
use Illuminate\Http\JsonResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Support\Facades\Crypt;
|
use Illuminate\Support\Facades\Crypt;
|
||||||
@@ -41,6 +42,8 @@ class ExistingBusinessController extends Controller
|
|||||||
'owner' => $request->user()->can('owns', $business), 'canReview' => $request->user()->can('review', $business),
|
'owner' => $request->user()->can('owns', $business), 'canReview' => $request->user()->can('review', $business),
|
||||||
'modalities' => ExistingBusinessDrafts::MODALITIES,
|
'modalities' => ExistingBusinessDrafts::MODALITIES,
|
||||||
'objectKinds' => ExistingBusinessObjects::KINDS,
|
'objectKinds' => ExistingBusinessObjects::KINDS,
|
||||||
|
'verificationChecks' => ExistingBusinessVerification::CHECKS,
|
||||||
|
'verifications' => app(ExistingBusinessVerification::class)->findings($business),
|
||||||
'objects' => ExistingBusinessObject::where('business_id', $id)->orderBy('created_at')->get()->map(fn ($object) => [
|
'objects' => ExistingBusinessObject::where('business_id', $id)->orderBy('created_at')->get()->map(fn ($object) => [
|
||||||
...$object->only(['id', 'kind', 'verification_status']), 'payload' => $object->payload]),
|
...$object->only(['id', 'kind', 'verification_status']), 'payload' => $object->payload]),
|
||||||
'history' => DB::table('existing_business_revisions')->where('business_id', $id)->orderByDesc('version_no')->limit(50)
|
'history' => DB::table('existing_business_revisions')->where('business_id', $id)->orderByDesc('version_no')->limit(50)
|
||||||
@@ -66,6 +69,11 @@ class ExistingBusinessController extends Controller
|
|||||||
return response()->json($this->record($business));
|
return response()->json($this->record($business));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function verify(Request $request, ExistingBusinessVerification $verification, string $id): JsonResponse
|
||||||
|
{
|
||||||
|
return response()->json($this->record($verification->save($request->user(), $id, $request->all())));
|
||||||
|
}
|
||||||
|
|
||||||
public function saveObject(Request $request, ExistingBusinessObjects $objects, string $id, ?string $object = null): JsonResponse
|
public function saveObject(Request $request, ExistingBusinessObjects $objects, string $id, ?string $object = null): JsonResponse
|
||||||
{
|
{
|
||||||
$saved = $objects->save($request->user(), $id, $request->all(), $object);
|
$saved = $objects->save($request->user(), $id, $request->all(), $object);
|
||||||
|
|||||||
@@ -70,9 +70,10 @@ final class ExistingBusinessDrafts
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public function snapshot(ExistingBusiness $business, User $actor, string $action, string $reason): void
|
/** @param array<string,mixed> $context */
|
||||||
|
public function snapshot(ExistingBusiness $business, User $actor, string $action, string $reason, array $context = []): void
|
||||||
{
|
{
|
||||||
$snapshot = json_encode(['record' => $business->attributesToArray(), 'payload' => $business->payload,
|
$snapshot = json_encode(['context' => $context, 'record' => $business->attributesToArray(), 'payload' => $business->payload,
|
||||||
'objects' => ExistingBusinessObject::where('business_id', $business->id)->orderBy('id')->get()
|
'objects' => ExistingBusinessObject::where('business_id', $business->id)->orderBy('id')->get()
|
||||||
->map(fn ($object) => [...$object->attributesToArray(), 'payload' => $object->payload])->all(),
|
->map(fn ($object) => [...$object->attributesToArray(), 'payload' => $object->payload])->all(),
|
||||||
], JSON_THROW_ON_ERROR);
|
], JSON_THROW_ON_ERROR);
|
||||||
|
|||||||
@@ -0,0 +1,78 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services;
|
||||||
|
|
||||||
|
use App\Models\ExistingBusiness;
|
||||||
|
use App\Models\ExistingBusinessObject;
|
||||||
|
use App\Models\User;
|
||||||
|
use Illuminate\Support\Facades\Crypt;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Gate;
|
||||||
|
use Illuminate\Support\Facades\Validator;
|
||||||
|
|
||||||
|
final class ExistingBusinessVerification
|
||||||
|
{
|
||||||
|
public const CHECKS = ['identity', 'representation', 'declared_ownership', 'documentary_ownership', 'document_received', 'document_validated', 'independent_valuation', 'land_right_documented', 'license_confirmed', 'validity', 'legal_transfer', 'prior_authorization'];
|
||||||
|
|
||||||
|
private function contentVersion(string $id): int
|
||||||
|
{
|
||||||
|
return (int) DB::table('existing_business_revisions')->where('business_id', $id)
|
||||||
|
->whereIn('action', ['created', 'updated', 'object_added', 'object_updated'])->max('version_no');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array<string,mixed> $input */
|
||||||
|
public function save(User $actor, string $id, array $input): ExistingBusiness
|
||||||
|
{
|
||||||
|
$data = Validator::make($input, [
|
||||||
|
'version_no' => ['required', 'integer', 'min:1'],
|
||||||
|
'object_id' => ['nullable', 'uuid'],
|
||||||
|
'check' => ['required', 'in:'.implode(',', self::CHECKS)],
|
||||||
|
'outcome' => ['required', 'in:confirmed,rejected,inconclusive,revoked'],
|
||||||
|
'evidence_reference' => ['required', 'string', 'min:10', 'max:2000'],
|
||||||
|
'note' => ['required', 'string', 'min:10', 'max:2000'],
|
||||||
|
'valid_until' => ['required_if:outcome,confirmed', 'nullable', 'date_format:Y-m-d', 'after_or_equal:today'],
|
||||||
|
])->validate();
|
||||||
|
|
||||||
|
return DB::transaction(function () use ($actor, $id, $data) {
|
||||||
|
$business = ExistingBusiness::whereKey($id)->lockForUpdate()->firstOrFail();
|
||||||
|
Gate::forUser($actor)->authorize('review', $business);
|
||||||
|
abort_unless($business->status === 'in_review' && $business->version_no === $data['version_no'], 409, 'Reabra a versão actual em revisão.');
|
||||||
|
if (! empty($data['object_id'])) {
|
||||||
|
ExistingBusinessObject::where('business_id', $id)->whereKey($data['object_id'])->firstOrFail();
|
||||||
|
}
|
||||||
|
$data['content_version'] = $this->contentVersion($id);
|
||||||
|
$business->version_no++;
|
||||||
|
$business->save();
|
||||||
|
app(ExistingBusinessDrafts::class)->snapshot($business, $actor, 'verification', $data['note'], $data);
|
||||||
|
|
||||||
|
return $business;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Latest finding for each check/subject; complete evidence remains in immutable revisions.
|
||||||
|
* @return array<int,array<string,mixed>>
|
||||||
|
*/
|
||||||
|
public function findings(ExistingBusiness $business): array
|
||||||
|
{
|
||||||
|
$contentVersion = $this->contentVersion($business->id);
|
||||||
|
$findings = [];
|
||||||
|
foreach (DB::table('existing_business_revisions')->where('business_id', $business->id)
|
||||||
|
->where('action', 'verification')->orderByDesc('version_no')->cursor() as $revision) {
|
||||||
|
$data = json_decode(Crypt::decryptString($revision->snapshot), true, 512, JSON_THROW_ON_ERROR)['context'];
|
||||||
|
$key = ($data['object_id'] ?? 'business').':'.$data['check'];
|
||||||
|
if (isset($findings[$key])) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$effective = $data['outcome'];
|
||||||
|
if ($data['content_version'] !== $contentVersion) {
|
||||||
|
$effective = 'stale';
|
||||||
|
} elseif (! empty($data['valid_until']) && $data['valid_until'] < today()->toDateString()) {
|
||||||
|
$effective = 'expired';
|
||||||
|
}
|
||||||
|
$findings[$key] = [...$data, 'effective_outcome' => $effective,
|
||||||
|
'version_no' => $revision->version_no, 'created_at' => $revision->created_at];
|
||||||
|
}
|
||||||
|
|
||||||
|
return array_values($findings);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"date": "2026-09-28T18:25:03.759Z",
|
"date": "2026-09-29T06:39:38.960Z",
|
||||||
"scope": "Synthetic private create/save and responsive layout in isolated QA; institutional review covered by integration tests",
|
"scope": "Synthetic private create/save and responsive layout in isolated QA; institutional review covered by integration tests",
|
||||||
"observations": [
|
"observations": [
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
# Estado actual — Mercado de Negócios Existentes
|
# Estado actual — Mercado de Negócios Existentes
|
||||||
|
|
||||||
|
Actualização 29/09/2026: [revisão granular com evidência, validade e invalidação por alteração](verification-evidence.md) implementada na ficha privada. Suite: 173 testes / 1785 verificações aprovadas. Os limites e contagens abaixo descrevem a entrega anterior; o módulo integral continua incompleto.
|
||||||
|
|
||||||
28/09/2026. A instrução mais recente autoriza executar todas as fases e avançar automaticamente. Substitui a paragem entre fases do prompt inicial. Não presume evidências jurídicas, nomeação de revisores, publicação ou integração externa efectiva.
|
28/09/2026. A instrução mais recente autoriza executar todas as fases e avançar automaticamente. Substitui a paragem entre fases do prompt inicial. Não presume evidências jurídicas, nomeação de revisores, publicação ou integração externa efectiva.
|
||||||
|
|
||||||
## Entrega utilizável localmente
|
## Entrega utilizável localmente
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
"openapi": "3.1.0",
|
"openapi": "3.1.0",
|
||||||
"info": {
|
"info": {
|
||||||
"title": "InvestMoz — private existing-business intake",
|
"title": "InvestMoz — private existing-business intake",
|
||||||
"version": "1.0.0",
|
"version": "1.1.0",
|
||||||
"description": "Internal preparation and review only. No publication, certification, legal transfer, NDA, payment or external CRM operation."
|
"description": "Internal preparation and review only. No publication, certification, legal transfer, NDA, payment or external CRM operation."
|
||||||
},
|
},
|
||||||
"servers": [
|
"servers": [
|
||||||
@@ -320,6 +320,90 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"verifications": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"type": "object",
|
||||||
|
"required": [
|
||||||
|
"version_no",
|
||||||
|
"check",
|
||||||
|
"outcome",
|
||||||
|
"evidence_reference",
|
||||||
|
"note"
|
||||||
|
],
|
||||||
|
"properties": {
|
||||||
|
"version_no": {
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": 1
|
||||||
|
},
|
||||||
|
"object_id": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
],
|
||||||
|
"format": "uuid"
|
||||||
|
},
|
||||||
|
"check": {
|
||||||
|
"enum": [
|
||||||
|
"identity",
|
||||||
|
"representation",
|
||||||
|
"declared_ownership",
|
||||||
|
"documentary_ownership",
|
||||||
|
"document_received",
|
||||||
|
"document_validated",
|
||||||
|
"independent_valuation",
|
||||||
|
"land_right_documented",
|
||||||
|
"license_confirmed",
|
||||||
|
"validity",
|
||||||
|
"legal_transfer",
|
||||||
|
"prior_authorization"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"outcome": {
|
||||||
|
"enum": [
|
||||||
|
"confirmed",
|
||||||
|
"rejected",
|
||||||
|
"inconclusive",
|
||||||
|
"revoked"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"evidence_reference": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 10,
|
||||||
|
"maxLength": 2000
|
||||||
|
},
|
||||||
|
"note": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 10,
|
||||||
|
"maxLength": 2000
|
||||||
|
},
|
||||||
|
"valid_until": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
],
|
||||||
|
"format": "date",
|
||||||
|
"description": "Required for confirmed findings; must be today or later."
|
||||||
|
},
|
||||||
|
"effective_outcome": {
|
||||||
|
"enum": [
|
||||||
|
"confirmed",
|
||||||
|
"rejected",
|
||||||
|
"inconclusive",
|
||||||
|
"revoked",
|
||||||
|
"stale",
|
||||||
|
"expired"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"content_version": {
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
"created_at": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1088,6 +1172,130 @@
|
|||||||
},
|
},
|
||||||
"description": "Session authentication and Laravel CSRF/origin protection apply. Use X-XSRF-TOKEN for browser clients."
|
"description": "Session authentication and Laravel CSRF/origin protection apply. Use X-XSRF-TOKEN for browser clients."
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"/listings/{id}/verifications": {
|
||||||
|
"post": {
|
||||||
|
"summary": "Record independent finding while in_review; immutable encrypted evidence, optimistic version and scoped object. Does not publish or certify the business.",
|
||||||
|
"parameters": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"in": "path",
|
||||||
|
"required": true,
|
||||||
|
"schema": {
|
||||||
|
"type": "string",
|
||||||
|
"format": "uuid"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"security": [
|
||||||
|
{
|
||||||
|
"session": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"description": "Private response; Cache-Control private, no-store",
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/Business"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"401": {
|
||||||
|
"description": "Authentication required"
|
||||||
|
},
|
||||||
|
"403": {
|
||||||
|
"description": "Account, ownership or current reviewer/MFA policy rejected"
|
||||||
|
},
|
||||||
|
"404": {
|
||||||
|
"description": "Module disabled or resource unavailable"
|
||||||
|
},
|
||||||
|
"409": {
|
||||||
|
"description": "Stale version or invalid transition"
|
||||||
|
},
|
||||||
|
"422": {
|
||||||
|
"description": "Validation error"
|
||||||
|
},
|
||||||
|
"429": {
|
||||||
|
"description": "Rate limited"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"requestBody": {
|
||||||
|
"required": true,
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"type": "object",
|
||||||
|
"required": [
|
||||||
|
"version_no",
|
||||||
|
"check",
|
||||||
|
"outcome",
|
||||||
|
"evidence_reference",
|
||||||
|
"note"
|
||||||
|
],
|
||||||
|
"properties": {
|
||||||
|
"version_no": {
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": 1
|
||||||
|
},
|
||||||
|
"object_id": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
],
|
||||||
|
"format": "uuid"
|
||||||
|
},
|
||||||
|
"check": {
|
||||||
|
"enum": [
|
||||||
|
"identity",
|
||||||
|
"representation",
|
||||||
|
"declared_ownership",
|
||||||
|
"documentary_ownership",
|
||||||
|
"document_received",
|
||||||
|
"document_validated",
|
||||||
|
"independent_valuation",
|
||||||
|
"land_right_documented",
|
||||||
|
"license_confirmed",
|
||||||
|
"validity",
|
||||||
|
"legal_transfer",
|
||||||
|
"prior_authorization"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"outcome": {
|
||||||
|
"enum": [
|
||||||
|
"confirmed",
|
||||||
|
"rejected",
|
||||||
|
"inconclusive",
|
||||||
|
"revoked"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"evidence_reference": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 10,
|
||||||
|
"maxLength": 2000
|
||||||
|
},
|
||||||
|
"note": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 10,
|
||||||
|
"maxLength": 2000
|
||||||
|
},
|
||||||
|
"valid_until": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
],
|
||||||
|
"format": "date",
|
||||||
|
"description": "Required for confirmed findings; must be today or later."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"description": "Session authentication and Laravel CSRF/origin protection apply. Use X-XSRF-TOKEN for browser clients."
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"components": {
|
"components": {
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# Revisão granular — 29/09/2026
|
||||||
|
|
||||||
|
## Entrega e diagnóstico
|
||||||
|
|
||||||
|
A ficha privada passa a mostrar verificações separadas de identidade, representação, titularidade declarada e documental, recepção e validação documental, avaliação independente, direito fundiário, licença, validade, transmissibilidade e autorização prévia. A ausência anterior deste registo era uma lacuna funcional, não falta de autorização genérica do proprietário do projecto.
|
||||||
|
|
||||||
|
## Implementação e rastreabilidade
|
||||||
|
|
||||||
|
`ExistingBusinessVerification` aplica a política de revisor designado com MFA, impede auto-revisão, exige estado `in_review`, versão actual, referência da evidência e fundamentação. Uma conclusão confirmada exige validade. Elementos de outro negócio são recusados. `ExistingBusinessController`, `routes/existing-business.php` e `business-verifications.tsx` disponibilizam o formulário e a leitura na ficha existente.
|
||||||
|
|
||||||
|
O endpoint `POST /api/v1/existing-business/listings/{id}/verifications` tem contrato em `openapi.json`. A leitura inclui a última conclusão por aspecto/elemento. O histórico completo permanece nas revisões imutáveis; evidência, conclusão e contexto são encriptados. Cada registo incrementa a versão do agregado e identifica a versão dos dados analisados. Alterações aos dados invalidam conservadoramente todas as conclusões anteriores; expiração é calculada em cada leitura. É possível registar conclusão revogada sem apagar a anterior.
|
||||||
|
|
||||||
|
Não há migration, importação ou alteração dos dados de negócio locais. Reutiliza-se a tabela de revisões e o seu bloqueio de UPDATE/DELETE. A evolução acrescenta `context` aos novos snapshots; snapshots antigos continuam legíveis. Os estados declarativos dos objectos não são convertidos em certificação global.
|
||||||
|
|
||||||
|
## Validação executada
|
||||||
|
|
||||||
|
- Testes focados MNE: 10 testes, 86 verificações.
|
||||||
|
- Suite completa em PostgreSQL isolado: 173 testes, 1785 verificações aprovadas.
|
||||||
|
- PHPStan, Pint, TypeScript e lint dos componentes aprovados.
|
||||||
|
- `npm run build`: 2371 módulos, 9,16 s.
|
||||||
|
- Navegador QA: criação, gravação, submissão e layout a 390/1440 px; quatro observações, zero erros JavaScript. O formulário do revisor ainda não tem teste de navegador específico; a autorização e a gravação são verificadas por integração.
|
||||||
|
- Casos novos: auto-revisão, estado inválido, versão desactualizada, objecto fora do negócio, validade obrigatória, cifragem, expiração, invalidação após edição e acesso de terceiro.
|
||||||
|
|
||||||
|
## Operação, riscos e decisão
|
||||||
|
|
||||||
|
**Go condicionado para revisão privada; No-Go para o módulo completo.** O formulário está na ficha `/investidor/negocios/{id}` para revisores já designados, depois de iniciarem a revisão pela fila `/management/negocios`. Não foram atribuídos papéis a contas reais. O proprietário vê as conclusões mas não pode emitir verificações sobre o seu negócio.
|
||||||
|
|
||||||
|
Referências são texto reservado, não anexos carregados nem prova de autenticação externa. Ainda faltam upload/scanner, mandatos verificáveis, duas aprovações de publicação, catálogo anonimizado, compradores/interesses, CRM MNE, sala documental/diligência, negociação e validação operacional das fases seguintes. Esta entrega não satisfaz, por si só, o prompt integral.
|
||||||
|
|
||||||
|
Para suspensão, usar a flag existente `INVESTMOZ_MNE_ENABLED=false` e limpar a cache de configuração, preservando revisões. Não reverter a base nem apagar evidências. Uma reversão de código deve conservar a leitura dos novos contextos para não ocultar o histórico.
|
||||||
|
|
||||||
|
Próxima dependência funcional: recepção privada de documentos, quarentena e análise de ficheiros, vinculadas ao negócio e à revisão. A autorização geral para continuar mantém-se; informação institucional ausente deve permanecer pendente e não ser inventada.
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
import { router } from "@inertiajs/react";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { api, button, card, Field, input } from "./shared";
|
||||||
|
import type { BusinessObject } from "./business-objects";
|
||||||
|
|
||||||
|
const labels: Record<string, string> = {
|
||||||
|
identity: "Identidade",
|
||||||
|
representation: "Representação",
|
||||||
|
declared_ownership: "Titularidade declarada",
|
||||||
|
documentary_ownership: "Titularidade documental",
|
||||||
|
document_received: "Documento recebido",
|
||||||
|
document_validated: "Documento validado",
|
||||||
|
independent_valuation: "Avaliação independente",
|
||||||
|
land_right_documented: "Direito fundiário documentado",
|
||||||
|
license_confirmed: "Licença confirmada",
|
||||||
|
validity: "Validade",
|
||||||
|
legal_transfer: "Transmissibilidade jurídica",
|
||||||
|
prior_authorization: "Autorização prévia",
|
||||||
|
confirmed: "Confirmado pelo revisor",
|
||||||
|
rejected: "Não confirmado",
|
||||||
|
inconclusive: "Inconclusivo",
|
||||||
|
revoked: "Revogado",
|
||||||
|
stale: "Rever após alteração dos dados",
|
||||||
|
expired: "Expirado",
|
||||||
|
};
|
||||||
|
export type BusinessVerification = {
|
||||||
|
check: string;
|
||||||
|
object_id?: string | null;
|
||||||
|
outcome: string;
|
||||||
|
effective_outcome: string;
|
||||||
|
evidence_reference: string;
|
||||||
|
note: string;
|
||||||
|
valid_until?: string | null;
|
||||||
|
version_no: number;
|
||||||
|
};
|
||||||
|
export default function BusinessVerifications({
|
||||||
|
id,
|
||||||
|
version,
|
||||||
|
editable,
|
||||||
|
checks,
|
||||||
|
findings,
|
||||||
|
objects,
|
||||||
|
}: {
|
||||||
|
id: string;
|
||||||
|
version: number;
|
||||||
|
editable: boolean;
|
||||||
|
checks: string[];
|
||||||
|
findings: BusinessVerification[];
|
||||||
|
objects: BusinessObject[];
|
||||||
|
}) {
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
const [outcome, setOutcome] = useState("inconclusive");
|
||||||
|
return (
|
||||||
|
<section className={`${card} space-y-4`}>
|
||||||
|
<h2 className="text-xl font-bold">Verificações e evidências</h2>
|
||||||
|
<p>
|
||||||
|
Cada conclusão corresponde apenas ao aspecto e à versão analisados. Não constitui
|
||||||
|
certificação global, autorização de publicação ou garantia de transmissão.
|
||||||
|
Alterações aos dados exigem nova revisão.
|
||||||
|
</p>
|
||||||
|
{findings.length === 0 && <p>Ainda não existem verificações registadas.</p>}
|
||||||
|
<ul className="space-y-4">
|
||||||
|
{findings.map((finding) => (
|
||||||
|
<li key={finding.version_no} className="break-words">
|
||||||
|
<strong>
|
||||||
|
{labels[finding.check]} · {labels[finding.effective_outcome]}
|
||||||
|
</strong>
|
||||||
|
<p>
|
||||||
|
{objects.find((object) => object.id === finding.object_id)?.payload
|
||||||
|
.label ?? "Negócio"}{" "}
|
||||||
|
· versão {finding.version_no}
|
||||||
|
</p>
|
||||||
|
<p>Evidência: {finding.evidence_reference}</p>
|
||||||
|
<p>{finding.note}</p>
|
||||||
|
{finding.valid_until && <p>Válido até {finding.valid_until}</p>}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
{editable && (
|
||||||
|
<form
|
||||||
|
className="space-y-4"
|
||||||
|
onSubmit={async (event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
const data = Object.fromEntries(new FormData(event.currentTarget));
|
||||||
|
setBusy(true);
|
||||||
|
setError("");
|
||||||
|
try {
|
||||||
|
await api(`/api/v1/existing-business/listings/${id}/verifications`, {
|
||||||
|
...data,
|
||||||
|
version_no: version,
|
||||||
|
});
|
||||||
|
router.reload();
|
||||||
|
} catch (failure) {
|
||||||
|
setError(
|
||||||
|
failure instanceof Error
|
||||||
|
? failure.message
|
||||||
|
: "Não foi possível registar a verificação.",
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<fieldset disabled={busy} className="space-y-4">
|
||||||
|
<Field label="Elemento analisado">
|
||||||
|
<select className={input} name="object_id">
|
||||||
|
<option value="">Negócio</option>
|
||||||
|
{objects.map((object) => (
|
||||||
|
<option key={object.id} value={object.id}>
|
||||||
|
{object.payload.label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</Field>
|
||||||
|
<Field label="Aspecto verificado">
|
||||||
|
<select className={input} name="check">
|
||||||
|
{checks.map((check) => (
|
||||||
|
<option key={check} value={check}>
|
||||||
|
{labels[check]}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</Field>
|
||||||
|
<Field label="Conclusão">
|
||||||
|
<select
|
||||||
|
className={input}
|
||||||
|
name="outcome"
|
||||||
|
value={outcome}
|
||||||
|
onChange={(event) => setOutcome(event.target.value)}
|
||||||
|
>
|
||||||
|
{["inconclusive", "confirmed", "rejected", "revoked"].map(
|
||||||
|
(value) => (
|
||||||
|
<option key={value} value={value}>
|
||||||
|
{labels[value]}
|
||||||
|
</option>
|
||||||
|
),
|
||||||
|
)}
|
||||||
|
</select>
|
||||||
|
</Field>
|
||||||
|
<Field label="Referência da evidência consultada">
|
||||||
|
<textarea
|
||||||
|
className={input}
|
||||||
|
name="evidence_reference"
|
||||||
|
required
|
||||||
|
minLength={10}
|
||||||
|
maxLength={2000}
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
<Field label="Fundamentação e limites da conclusão">
|
||||||
|
<textarea
|
||||||
|
className={input}
|
||||||
|
name="note"
|
||||||
|
required
|
||||||
|
minLength={10}
|
||||||
|
maxLength={2000}
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
<Field label="Validade da conclusão">
|
||||||
|
<input
|
||||||
|
className={input}
|
||||||
|
type="date"
|
||||||
|
name="valid_until"
|
||||||
|
required={outcome === "confirmed"}
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
<button className={button} disabled={busy}>
|
||||||
|
Registar verificação
|
||||||
|
</button>
|
||||||
|
</fieldset>
|
||||||
|
{error && <p role="alert">{error}</p>}
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -5,6 +5,8 @@ import { businessModalities, businessStates } from "./business-types";
|
|||||||
import type { Business } from "./business-types";
|
import type { Business } from "./business-types";
|
||||||
import BusinessObjects from "./business-objects";
|
import BusinessObjects from "./business-objects";
|
||||||
import type { BusinessObject } from "./business-objects";
|
import type { BusinessObject } from "./business-objects";
|
||||||
|
import BusinessVerifications from "./business-verifications";
|
||||||
|
import type { BusinessVerification } from "./business-verifications";
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
record: Business;
|
record: Business;
|
||||||
@@ -14,6 +16,8 @@ type Props = {
|
|||||||
modalities: string[];
|
modalities: string[];
|
||||||
objects: BusinessObject[];
|
objects: BusinessObject[];
|
||||||
objectKinds: string[];
|
objectKinds: string[];
|
||||||
|
verificationChecks: string[];
|
||||||
|
verifications: BusinessVerification[];
|
||||||
history: { version_no: number; action: string; created_at: string; note: string }[];
|
history: { version_no: number; action: string; created_at: string; note: string }[];
|
||||||
};
|
};
|
||||||
export default function BusinessPage(props: Props) {
|
export default function BusinessPage(props: Props) {
|
||||||
@@ -28,6 +32,8 @@ function Editor({
|
|||||||
history,
|
history,
|
||||||
objects,
|
objects,
|
||||||
objectKinds,
|
objectKinds,
|
||||||
|
verificationChecks,
|
||||||
|
verifications,
|
||||||
}: Props) {
|
}: Props) {
|
||||||
const [payload, setPayload] = useState(record.payload);
|
const [payload, setPayload] = useState(record.payload);
|
||||||
const [modality, setModality] = useState(record.modality);
|
const [modality, setModality] = useState(record.modality);
|
||||||
@@ -209,6 +215,14 @@ function Editor({
|
|||||||
objects={objects}
|
objects={objects}
|
||||||
objectKinds={objectKinds}
|
objectKinds={objectKinds}
|
||||||
/>
|
/>
|
||||||
|
<BusinessVerifications
|
||||||
|
id={record.id}
|
||||||
|
version={record.version_no}
|
||||||
|
editable={canReview && record.status === "in_review" && !busy}
|
||||||
|
checks={verificationChecks}
|
||||||
|
findings={verifications}
|
||||||
|
objects={objects}
|
||||||
|
/>
|
||||||
<section className={card}>
|
<section className={card}>
|
||||||
<h2 className="text-xl font-bold">Histórico</h2>
|
<h2 className="text-xl font-bold">Histórico</h2>
|
||||||
<ol>
|
<ol>
|
||||||
@@ -223,6 +237,7 @@ function Editor({
|
|||||||
archived: "Arquivado",
|
archived: "Arquivado",
|
||||||
object_added: "Elemento declarado acrescentado",
|
object_added: "Elemento declarado acrescentado",
|
||||||
object_updated: "Elemento declarado alterado",
|
object_updated: "Elemento declarado alterado",
|
||||||
|
verification: "Verificação registada",
|
||||||
} as Record<string, string>
|
} as Record<string, string>
|
||||||
)[h.action] ??
|
)[h.action] ??
|
||||||
h.action}{" "}
|
h.action}{" "}
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ Route::middleware(['auth', 'verified', PrivateInvestmentResponse::class, 'thrott
|
|||||||
Route::get('/listings/{id}', [ExistingBusinessController::class, 'show'])->whereUuid('id');
|
Route::get('/listings/{id}', [ExistingBusinessController::class, 'show'])->whereUuid('id');
|
||||||
Route::put('/listings/{id}', [ExistingBusinessController::class, 'save'])->whereUuid('id');
|
Route::put('/listings/{id}', [ExistingBusinessController::class, 'save'])->whereUuid('id');
|
||||||
Route::post('/listings/{id}/transitions', [ExistingBusinessController::class, 'transition'])->whereUuid('id');
|
Route::post('/listings/{id}/transitions', [ExistingBusinessController::class, 'transition'])->whereUuid('id');
|
||||||
|
Route::post('/listings/{id}/verifications', [ExistingBusinessController::class, 'verify'])->whereUuid('id');
|
||||||
Route::post('/listings/{id}/objects', [ExistingBusinessController::class, 'saveObject'])->whereUuid('id');
|
Route::post('/listings/{id}/objects', [ExistingBusinessController::class, 'saveObject'])->whereUuid('id');
|
||||||
Route::put('/listings/{id}/objects/{object}', [ExistingBusinessController::class, 'saveObject'])->whereUuid(['id', 'object']);
|
Route::put('/listings/{id}/objects/{object}', [ExistingBusinessController::class, 'saveObject'])->whereUuid(['id', 'object']);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -64,6 +64,36 @@ class ExistingBusinessIntakeTest extends TestCase
|
|||||||
$this->assertStringNotContainsString('Please clarify', DB::table('existing_business_reviews')->where('action', 'needs_information')->value('note'));
|
$this->assertStringNotContainsString('Please clarify', DB::table('existing_business_reviews')->where('action', 'needs_information')->value('note'));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function test_granular_verification_requires_independent_review_and_invalidates_after_changes(): void
|
||||||
|
{
|
||||||
|
$owner = User::factory()->create();
|
||||||
|
$reviewer = $this->reviewer();
|
||||||
|
$this->actingAs($owner);
|
||||||
|
$id = $this->postJson($this->base, $this->draft())->assertCreated()->json('id');
|
||||||
|
$url = $this->base.'/'.$id;
|
||||||
|
$finding = ['version_no' => 3, 'check' => 'identity', 'outcome' => 'confirmed',
|
||||||
|
'evidence_reference' => 'Synthetic identity evidence', 'note' => 'Synthetic independent review',
|
||||||
|
'valid_until' => today()->addDay()->toDateString()];
|
||||||
|
$this->postJson($url.'/transitions', ['version_no' => 1, 'action' => 'submitted', 'note' => 'Synthetic review requested', 'review_consent' => true])->assertOk();
|
||||||
|
$this->postJson($url.'/verifications', $finding)->assertForbidden();
|
||||||
|
$this->actingAs($reviewer)->postJson($url.'/verifications', [...$finding, 'version_no' => 2])->assertConflict();
|
||||||
|
$this->postJson($url.'/transitions', ['version_no' => 2, 'action' => 'in_review', 'note' => 'Synthetic review started'])->assertOk();
|
||||||
|
$this->postJson($url.'/verifications', [...$finding, 'valid_until' => null])->assertUnprocessable();
|
||||||
|
$this->postJson($url.'/verifications', [...$finding, 'object_id' => '00000000-0000-4000-8000-000000000001'])->assertNotFound();
|
||||||
|
$this->postJson($url.'/verifications', $finding)->assertOk()->assertJsonPath('version_no', 4);
|
||||||
|
$this->postJson($url.'/verifications', $finding)->assertConflict();
|
||||||
|
$this->getJson($url)->assertOk()->assertJsonPath('verifications.0.effective_outcome', 'confirmed');
|
||||||
|
$raw = DB::table('existing_business_revisions')->where('business_id', $id)->where('action', 'verification')->value('snapshot');
|
||||||
|
$this->assertStringNotContainsString('Synthetic identity evidence', $raw);
|
||||||
|
$this->travel(2)->days();
|
||||||
|
$this->getJson($url)->assertOk()->assertJsonPath('verifications.0.effective_outcome', 'expired');
|
||||||
|
$this->travelBack();
|
||||||
|
$this->postJson($url.'/transitions', ['version_no' => 4, 'action' => 'needs_information', 'note' => 'Synthetic clarification requested'])->assertOk();
|
||||||
|
$this->actingAs($owner)->putJson($url, [...$this->draft(), 'version_no' => 5])->assertOk();
|
||||||
|
$this->getJson($url)->assertJsonPath('verifications.0.effective_outcome', 'stale');
|
||||||
|
$this->actingAs(User::factory()->create())->getJson($url)->assertForbidden();
|
||||||
|
}
|
||||||
|
|
||||||
public function test_flag_mfa_and_current_designation_are_required(): void
|
public function test_flag_mfa_and_current_designation_are_required(): void
|
||||||
{
|
{
|
||||||
$this->getJson($this->base)->assertUnauthorized();
|
$this->getJson($this->base)->assertUnauthorized();
|
||||||
|
|||||||
@@ -35,5 +35,17 @@ document.paths['/listings/{id}/objects'] = { post: operation('Declare a separate
|
|||||||
document.paths['/listings/{id}/objects'].post.responses['201'] = document.paths['/listings/{id}/objects'].post.responses['200'];
|
document.paths['/listings/{id}/objects'].post.responses['201'] = document.paths['/listings/{id}/objects'].post.responses['200'];
|
||||||
delete document.paths['/listings/{id}/objects'].post.responses['200'];
|
delete document.paths['/listings/{id}/objects'].post.responses['200'];
|
||||||
document.paths['/listings/{id}/objects/{object}'] = { put: operation('Update scoped object with immutable kind; amount requires currency and value kind; area requires unit', objectResponse, objectInput, [id, { ...id, name: 'object' }]) };
|
document.paths['/listings/{id}/objects/{object}'] = { put: operation('Update scoped object with immutable kind; amount requires currency and value kind; area requires unit', objectResponse, objectInput, [id, { ...id, name: 'object' }]) };
|
||||||
|
const verification = { type: 'object', required: ['version_no', 'check', 'outcome', 'evidence_reference', 'note'], properties: {
|
||||||
|
version_no: { type: 'integer', minimum: 1 }, object_id: { type: ['string', 'null'], format: 'uuid' },
|
||||||
|
check: { enum: ['identity', 'representation', 'declared_ownership', 'documentary_ownership', 'document_received', 'document_validated', 'independent_valuation', 'land_right_documented', 'license_confirmed', 'validity', 'legal_transfer', 'prior_authorization'] },
|
||||||
|
outcome: { enum: ['confirmed', 'rejected', 'inconclusive', 'revoked'] },
|
||||||
|
evidence_reference: { type: 'string', minLength: 10, maxLength: 2000 }, note: { type: 'string', minLength: 10, maxLength: 2000 },
|
||||||
|
valid_until: { type: ['string', 'null'], format: 'date', description: 'Required for confirmed findings; must be today or later.' },
|
||||||
|
} };
|
||||||
|
document.paths['/listings/{id}/verifications'] = { post: operation('Record independent finding while in_review; immutable encrypted evidence, optimistic version and scoped object. Does not publish or certify the business.', ref('Business'), verification, [id]) };
|
||||||
|
document.paths['/listings/{id}'].get.responses['200'].content['application/json'].schema.properties.verifications = {
|
||||||
|
type: 'array', items: { ...verification, properties: { ...verification.properties, effective_outcome: { enum: ['confirmed', 'rejected', 'inconclusive', 'revoked', 'stale', 'expired'] }, content_version: { type: 'integer' }, created_at: text } },
|
||||||
|
};
|
||||||
|
document.info.version = '1.1.0';
|
||||||
fs.writeFileSync('docs/investmoz/existing-business/openapi.json', JSON.stringify(document, null, 2) + '\n');
|
fs.writeFileSync('docs/investmoz/existing-business/openapi.json', JSON.stringify(document, null, 2) + '\n');
|
||||||
console.log('OpenAPI written: 8 operations, private session API.');
|
console.log('OpenAPI written: 9 operations, private session API.');
|
||||||
|
|||||||
Reference in New Issue
Block a user