File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"source_document_sha256": "9f173ed3024d2beddef7888b692d8b81fc5e4700249955f2bae9bdd2eb2be504",
|
||||
"source_paragraphs": "2110–14681 (§26)",
|
||||
"artifact_sha256": "9ce0acfa5df1f81a3357dee9e5a9a1c4e77e4eefc8bce294497d18f4caa8e5c0",
|
||||
"definitions": 110,
|
||||
"schema_dialect": "https://json-schema.org/draft/2020-12/schema",
|
||||
"core_id_compatibility": "Normative UUID examples retained; existing opportunity bigint IDs must use an explicit adapter, never a renumbering migration.",
|
||||
"contracts": [
|
||||
"realEstateCreate",
|
||||
"realEstatePatch",
|
||||
"realEstateResponse",
|
||||
"landRightsCreate",
|
||||
"landRightsPatch",
|
||||
"landRightsResponse",
|
||||
"businessTransactionCreate",
|
||||
"businessTransactionPatch",
|
||||
"businessTransactionResponse"
|
||||
],
|
||||
"runtime_validation_implemented": false,
|
||||
"workflow_implemented": false,
|
||||
"qa_activation": false,
|
||||
"active_writes": 0,
|
||||
"state_scope": "Historical extraction snapshot before the runtime adapter. These booleans are not current runtime/installation flags.",
|
||||
"current_runtime_reference": "docs/investmoz/v2/auditoria-portal/workflow-oportunidades-qa.md"
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import { profileLinks } from '@/components/profile-navigation';
|
||||
import type { ProfileAccess } from '@/types/profile-access';
|
||||
import { Link, usePage } from '@inertiajs/react';
|
||||
import { LayoutGrid } from 'lucide-react';
|
||||
import { portalNavigation } from '@/lib/portal-navigation';
|
||||
@@ -15,27 +17,52 @@ import {
|
||||
} from '@/components/ui/sidebar';
|
||||
import { dashboard } from '@/routes';
|
||||
import type { Auth } from '@/types';
|
||||
import type { OpportunityManagementAccess } from '@/types/opportunity-management';
|
||||
|
||||
export function AppSidebar() {
|
||||
const { auth, existingBusinessEnabled, educationEnabled, aiEnabled } =
|
||||
usePage<{
|
||||
auth: Auth;
|
||||
existingBusinessEnabled?: boolean;
|
||||
educationEnabled?: boolean;
|
||||
aiEnabled?: boolean;
|
||||
}>().props;
|
||||
const {
|
||||
auth,
|
||||
existingBusinessEnabled,
|
||||
educationEnabled,
|
||||
aiEnabled,
|
||||
opportunityManagement,
|
||||
profileAccess,
|
||||
} = usePage<{
|
||||
auth: Auth;
|
||||
existingBusinessEnabled?: boolean;
|
||||
educationEnabled?: boolean;
|
||||
aiEnabled?: boolean;
|
||||
profileAccess?: ProfileAccess | null;
|
||||
opportunityManagement?: OpportunityManagementAccess | null;
|
||||
}>().props;
|
||||
const groups = portalNavigation({
|
||||
authenticated: !!auth.user,
|
||||
manager: auth.canManagePortal,
|
||||
businesses: existingBusinessEnabled,
|
||||
education: educationEnabled,
|
||||
ai: aiEnabled,
|
||||
opportunityManagement,
|
||||
});
|
||||
const items = groups.map((group) => ({
|
||||
title: group.label,
|
||||
href: group.children?.find((item) => item.href)?.href ?? '/',
|
||||
icon: LayoutGrid,
|
||||
}));
|
||||
if (auth.canManagePortal && opportunityManagement) {
|
||||
items.push({
|
||||
title: opportunityManagement.manage.label,
|
||||
href: opportunityManagement.manage.href,
|
||||
icon: LayoutGrid,
|
||||
});
|
||||
if (opportunityManagement.installed) {
|
||||
items.push({
|
||||
title: opportunityManagement.create.label,
|
||||
href: opportunityManagement.create.href,
|
||||
icon: LayoutGrid,
|
||||
});
|
||||
}
|
||||
}
|
||||
items.push(...profileLinks(profileAccess).map(link => ({...link, icon: LayoutGrid})));
|
||||
return (
|
||||
<Sidebar collapsible="icon" variant="inset">
|
||||
<SidebarHeader>
|
||||
|
||||
@@ -40,6 +40,30 @@ export function ProvinceSelect({
|
||||
const [error, setError] = useState('');
|
||||
const [retry, setRetry] = useState(0);
|
||||
const [search, setSearch] = useState('');
|
||||
const [geometrySelection, setGeometrySelection] = useState<{ value: string; id: string } | null>(null);
|
||||
const [geometryFeedback, setGeometryFeedback] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setGeometrySelection(null);
|
||||
setGeometryFeedback('');
|
||||
if (!value) return;
|
||||
// Preserve historical text. Only one exact catalogue match supplies a map ID.
|
||||
void fetch(`${endpoint}?${new URLSearchParams({ type: 'province', page: '1', q: value })}`, {
|
||||
signal: controller.signal, headers: { Accept: 'application/json' },
|
||||
}).then(async (response) => {
|
||||
if (!response.ok) throw new Error('Não foi possível consultar a correspondência cartográfica.');
|
||||
const data = await response.json();
|
||||
const matches = (data.data as Option[]).filter((option) => option.name === value);
|
||||
if (controller.signal.aborted) return;
|
||||
if (matches.length === 1 && !data.next_page_url)
|
||||
setGeometrySelection({ value, id: matches[0].id });
|
||||
else setGeometryFeedback('Seleção guardada preservada; sem correspondência cartográfica inequívoca neste cadastro.');
|
||||
}).catch((cause: unknown) => {
|
||||
if (!controller.signal.aborted) setGeometryFeedback(cause instanceof Error ? cause.message : 'Erro de ligação.');
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [endpoint, value, retry]);
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
@@ -127,6 +151,12 @@ export function ProvinceSelect({
|
||||
</button>
|
||||
</span>
|
||||
)}
|
||||
{geometryFeedback && <p role="status">{geometryFeedback}</p>}
|
||||
<TerritoryGeometryPreview
|
||||
territoryId={geometrySelection && geometrySelection.value === value ? geometrySelection.id : undefined}
|
||||
management={endpoint.startsWith('/management/')}
|
||||
endpoint={endpoint.startsWith('/minhas-oportunidades/') ? '/minhas-oportunidades/territory-geometries' : undefined}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -181,6 +211,7 @@ export function TerritoryFields({
|
||||
<TerritoryGeometryPreview
|
||||
territoryId={path.at(-1)?.id}
|
||||
management={endpoint.startsWith('/management/')}
|
||||
endpoint={endpoint.startsWith('/minhas-oportunidades/') ? '/minhas-oportunidades/territory-geometries' : undefined}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,750 @@
|
||||
import OpportunityParcelGeometry from "./opportunity-parcel-geometry";
|
||||
import TerritoryGeometryPreview from "./territory-geometry-preview";
|
||||
import { control } from "@/pages/management/shared";
|
||||
|
||||
type Data = Record<string, unknown>;
|
||||
type Schema = {
|
||||
$ref?: string;
|
||||
type?: string | string[];
|
||||
properties?: Record<string, Schema>;
|
||||
items?: Schema;
|
||||
enum?: unknown[];
|
||||
const?: unknown;
|
||||
format?: string;
|
||||
maxLength?: number;
|
||||
required?: string[];
|
||||
};
|
||||
type Resource = {
|
||||
id: string;
|
||||
payload: { title?: string; role?: string; [key: string]: unknown };
|
||||
file?: { file_name: string };
|
||||
};
|
||||
function resourceTerritory(resource?: Resource) {
|
||||
const p = resource?.payload;
|
||||
const id =
|
||||
p?.locality_id ?? p?.admin_post_id ?? p?.district_id ?? p?.province_id;
|
||||
return typeof id === "string" ? id : undefined;
|
||||
}
|
||||
export type CanonicalOptions = {
|
||||
version: string;
|
||||
schema: Schema;
|
||||
definitions: Record<string, Schema>;
|
||||
contacts: { id: string; full_name: string }[];
|
||||
activities: {
|
||||
id: string;
|
||||
parent_id: string | null;
|
||||
sector_id: number;
|
||||
label_pt_mz: string;
|
||||
}[];
|
||||
resources: Record<string, Resource[]>;
|
||||
gates: string[];
|
||||
countries: { code: string; name: string }[];
|
||||
authorities: { id: string; label_pt_mz: string }[];
|
||||
};
|
||||
const labels: Record<string, string> = {
|
||||
official_title: "Título oficial",
|
||||
promoter_type: "Tipo de Promotor",
|
||||
internal_contact_id: "Contacto interno",
|
||||
sector_id: "Sector",
|
||||
subsector_id: "Subsector",
|
||||
economic_activity_id: "Atividade económica",
|
||||
location_mode: "Uma ou várias localizações",
|
||||
geographic_scope: "Âmbito geográfico",
|
||||
multi_district_rationale: "Justificação territorial",
|
||||
locations: "Localizações guardadas",
|
||||
executive_summary: "Resumo executivo",
|
||||
demand_statement: "Necessidade e proposta",
|
||||
visibility: "Visibilidade após publicação",
|
||||
truth_declaration: "Declaração de veracidade",
|
||||
publication_languages: "Versões por idioma",
|
||||
language_code: "Idioma",
|
||||
title: "Título",
|
||||
summary: "Resumo",
|
||||
documents: "Documentos guardados",
|
||||
evidences: "Evidências",
|
||||
document_id: "Documento associado",
|
||||
evidence_type: "Tipo de evidência",
|
||||
description: "Descrição",
|
||||
images: "Imagens guardadas",
|
||||
review_due_date: "Data de revisão editorial",
|
||||
real_estate: "Imobiliário",
|
||||
land_rights: "DUAT e direitos fundiários",
|
||||
business_transaction: "Negócio",
|
||||
transaction_type: "Modalidade",
|
||||
property_type: "Tipo de imóvel",
|
||||
construction_status: "Estado construtivo",
|
||||
property_condition: "Condição do imóvel",
|
||||
land_area: "Área do terreno",
|
||||
built_area: "Área construída",
|
||||
area_unit: "Unidade da área",
|
||||
units: "Unidades",
|
||||
rooms: "Compartimentos",
|
||||
floors: "Pisos",
|
||||
amenities: "Comodidades",
|
||||
utilities: "Serviços e acessos",
|
||||
occupancy_status: "Ocupação",
|
||||
title_type: "Tipo de título",
|
||||
registration_number: "Número de registo",
|
||||
encumbrances: "Ónus e restrições",
|
||||
price: "Preço do imóvel",
|
||||
rent: "Renda",
|
||||
rent_periodicity: "Periodicidade",
|
||||
deposit: "Caução",
|
||||
valuation: "Avaliação",
|
||||
viewing: "Visitas",
|
||||
planning_permit_document_id: "Licença de construção",
|
||||
use_license_document_id: "Licença de utilização",
|
||||
operation_type: "Operação fundiária admissível",
|
||||
duat_status: "Situação do DUAT",
|
||||
duat_number: "Número do DUAT",
|
||||
holder_id: "Titular cadastrado",
|
||||
holder_name: "Nome do titular",
|
||||
issuing_authority_id: "Entidade emissora",
|
||||
issue_date: "Data de emissão",
|
||||
expiry_date: "Data de validade",
|
||||
authorized_purpose: "Finalidade autorizada",
|
||||
exploitation_plan_document_id: "Plano de exploração",
|
||||
parcels: "Parcelas",
|
||||
location_id: "Localização associada",
|
||||
area: "Área",
|
||||
cadastral_number: "Número cadastral",
|
||||
overlap_status: "Sobreposição",
|
||||
improvements: "Benfeitorias",
|
||||
communities: "Comunidades",
|
||||
community_consultation: "Consulta comunitária",
|
||||
overlaps_conflicts: "Sobreposições e conflitos",
|
||||
required_authorizations: "Autorizações necessárias",
|
||||
consideration: "Contraprestação",
|
||||
legal_entity_id: "Entidade representada",
|
||||
legal_form: "Forma jurídica",
|
||||
percentage_offered: "Percentagem oferecida",
|
||||
asking_price: "Valor solicitado",
|
||||
financial_periods: "Exercícios financeiros",
|
||||
assets_liabilities: "Ativos e passivos",
|
||||
employees: "Empregos e obrigações",
|
||||
contracts_licenses: "Contratos e licenças",
|
||||
litigation_contingencies: "Litígios e contingências",
|
||||
reason_for_transaction: "Fundamentação da operação",
|
||||
partner_contribution: "Contribuição do parceiro",
|
||||
governance_rights: "Direitos de governação",
|
||||
franchise_terms: "Condições da franquia",
|
||||
confidentiality_level: "Confidencialidade",
|
||||
due_diligence_status: "Preparação da análise",
|
||||
opportunity_type: "Tipo de investimento",
|
||||
maturity_stage: "Etapa de maturidade",
|
||||
investment_modalities: "Modalidades de investimento",
|
||||
investor_profiles: "Perfis de investidor",
|
||||
products: "Produtos",
|
||||
assets: "Ativos",
|
||||
inputs: "Insumos",
|
||||
markets: "Mercados",
|
||||
competitive_advantage: "Vantagem competitiva",
|
||||
employment: "Emprego",
|
||||
impact_indicators: "Impactos",
|
||||
total_investment: "Investimento total",
|
||||
currency: "Moeda",
|
||||
investment_breakdown: "Rubricas de investimento",
|
||||
secured_financing: "Financiamento assegurado",
|
||||
funding_sought: "Financiamento procurado",
|
||||
financial_indicators: "Indicadores financeiros",
|
||||
milestones: "Marcos",
|
||||
licenses: "Licenças",
|
||||
environmental_social: "Aspetos ambientais e sociais",
|
||||
risks: "Riscos",
|
||||
relations: "Relações",
|
||||
amount: "Montante",
|
||||
name: "Nome",
|
||||
label: "Designação",
|
||||
status: "Estado",
|
||||
date: "Data",
|
||||
method: "Método",
|
||||
appraiser: "Avaliador",
|
||||
year: "Exercício",
|
||||
revenue: "Receita",
|
||||
profit: "Resultado",
|
||||
type: "Tipo",
|
||||
value: "Valor",
|
||||
details: "Detalhes",
|
||||
mitigation: "Mitigação",
|
||||
due_date: "Prazo",
|
||||
authority: "Entidade competente",
|
||||
assessment_status: "Estado da avaliação",
|
||||
environmental_category: "Categoria ambiental",
|
||||
direct_jobs: "Empregos diretos",
|
||||
employment_type: "Tipo de emprego",
|
||||
geometry: "Geometria da parcela",
|
||||
module_profile_version: "Perfil modular aprovado",
|
||||
start_date: "Data de início",
|
||||
end_date: "Data de fim",
|
||||
responsible_name: "Responsável declarado",
|
||||
dependencies: "Marcos dos quais depende",
|
||||
scenario: "Cenário analisado",
|
||||
npv: "Valor atual líquido",
|
||||
irr: "Taxa interna de retorno (%)",
|
||||
payback_years: "Prazo de retorno (anos)",
|
||||
horizon_years: "Horizonte (anos)",
|
||||
discount_rate: "Taxa de desconto (%)",
|
||||
model_document_id: "Modelo financeiro associado",
|
||||
title_holder_name: "Titular do título",
|
||||
title_document_id: "Documento do título",
|
||||
holder_document_id: "Documento do titular",
|
||||
expected_completion_date: "Conclusão prevista",
|
||||
occupancy_details: "Condições de ocupação",
|
||||
occupancy_document_id: "Contrato de ocupação",
|
||||
urban_limit_document_id: "Fonte do limite urbanístico",
|
||||
max_built_area: "Área edificável máxima declarada",
|
||||
amenities_other: "Outra comodidade",
|
||||
communities_affected: "Existem comunidades afetadas?",
|
||||
exploitation_plan_required: "Plano de exploração aplicável?",
|
||||
entity_registration: "Registo e beneficiário efetivo",
|
||||
tax_identifier: "Identificação fiscal",
|
||||
legal_document_id: "Documento de constituição/registo",
|
||||
beneficial_owner_document_id: "Documento do beneficiário efetivo",
|
||||
available_financial_years: "Exercícios financeiros existentes",
|
||||
liabilities: "Passivos",
|
||||
cash_flow: "Fluxo de caixa",
|
||||
excluded_assets: "Ativos excluídos",
|
||||
guarantees: "Garantias",
|
||||
reconciliation_document_id: "Documento de reconciliação",
|
||||
obligations: "Obrigações",
|
||||
labor_liabilities: "Passivos laborais",
|
||||
transferability: "Transmissibilidade",
|
||||
consent_document_id: "Consentimento de transmissão",
|
||||
nda_document_id: "Acordo de confidencialidade",
|
||||
teaser: "Resumo autorizado para publicação",
|
||||
board: "Órgãos de gestão",
|
||||
reserved_matters: "Matérias reservadas",
|
||||
dividends: "Dividendos",
|
||||
exit: "Saída",
|
||||
deadlock: "Resolução de impasse",
|
||||
initial_fee: "Encargo inicial",
|
||||
royalties: "Royalties e encargos",
|
||||
support: "Apoio",
|
||||
exclusivity: "Exclusividade",
|
||||
renewal: "Renovação",
|
||||
termination: "Cessação",
|
||||
brand_license_document_id: "Licença da marca",
|
||||
publish_contact: "Autoriza publicar o contacto?",
|
||||
public_contact_id: "Contacto para divulgação",
|
||||
};
|
||||
function FieldErrors({
|
||||
path,
|
||||
errors,
|
||||
}: {
|
||||
path: string;
|
||||
errors: Record<string, string>;
|
||||
}) {
|
||||
const message = errors[path];
|
||||
return message ? (
|
||||
<p id={path + "-error"} className="text-red-700" role="alert">
|
||||
{message}
|
||||
</p>
|
||||
) : null;
|
||||
}
|
||||
function Editor({
|
||||
name,
|
||||
path,
|
||||
schema,
|
||||
value,
|
||||
onChange,
|
||||
options,
|
||||
errors,
|
||||
}: {
|
||||
name: string;
|
||||
path: string;
|
||||
schema: Schema;
|
||||
value: unknown;
|
||||
onChange: (v: unknown) => void;
|
||||
options: CanonicalOptions;
|
||||
errors: Record<string, string>;
|
||||
}) {
|
||||
if (schema.$ref)
|
||||
schema = options.definitions[schema.$ref.split("/").pop()!] ?? schema;
|
||||
const types = Array.isArray(schema.type) ? schema.type : [schema.type];
|
||||
const label = labels[name] ?? name.replaceAll("_", " ");
|
||||
const props = {
|
||||
id: path,
|
||||
"aria-invalid": !!errors[path],
|
||||
"aria-describedby": errors[path] ? path + "-error" : undefined,
|
||||
};
|
||||
let input;
|
||||
if (name === "geometry")
|
||||
input = <OpportunityParcelGeometry value={value} onChange={onChange} />;
|
||||
else if (
|
||||
name.endsWith("document_id") ||
|
||||
name === "location_id" ||
|
||||
name === "image_id"
|
||||
) {
|
||||
const kind =
|
||||
name === "location_id"
|
||||
? "locations"
|
||||
: name === "image_id"
|
||||
? "images"
|
||||
: "documents";
|
||||
const rows = options.resources[kind] ?? [];
|
||||
input = (
|
||||
<>
|
||||
<select
|
||||
{...props}
|
||||
className={control}
|
||||
value={String(value ?? "")}
|
||||
onChange={(e) => onChange(e.target.value || null)}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{rows.map((r) => (
|
||||
<option key={r.id} value={r.id}>
|
||||
{r.payload.title ??
|
||||
r.payload.role ??
|
||||
r.file?.file_name ??
|
||||
r.id}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{name === "location_id" && !!value && (
|
||||
<TerritoryGeometryPreview
|
||||
territoryId={resourceTerritory(
|
||||
rows.find((r) => r.id === value),
|
||||
)}
|
||||
endpoint="/minhas-oportunidades/territory-geometries"
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
} else if (name === "country_code")
|
||||
input = (
|
||||
<select
|
||||
{...props}
|
||||
className={control}
|
||||
value={String(value ?? "")}
|
||||
onChange={(e) => onChange(e.target.value || null)}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{options.countries.map((c) => (
|
||||
<option key={c.code} value={c.code}>
|
||||
{c.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
);
|
||||
else if (name === "issuing_authority_id" || name === "authority_id")
|
||||
input = (
|
||||
<select
|
||||
{...props}
|
||||
className={control}
|
||||
value={String(value ?? "")}
|
||||
onChange={(e) => onChange(e.target.value || null)}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{options.authorities.map((a) => (
|
||||
<option key={a.id} value={a.id}>
|
||||
{a.label_pt_mz}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
);
|
||||
else if (schema.enum)
|
||||
input = (
|
||||
<select
|
||||
{...props}
|
||||
className={control}
|
||||
value={String(value ?? "")}
|
||||
onChange={(e) => onChange(e.target.value || null)}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{schema.enum
|
||||
.filter((v) => v !== null)
|
||||
.map((v) => (
|
||||
<option key={String(v)} value={String(v)}>
|
||||
{String(v).replaceAll("_", " ")}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
);
|
||||
else if (types.includes("boolean") || schema.const === true)
|
||||
input = (
|
||||
<select
|
||||
{...props}
|
||||
className={control}
|
||||
value={value === true ? "true" : value === false ? "false" : ""}
|
||||
onChange={(e) =>
|
||||
onChange(
|
||||
e.target.value === ""
|
||||
? null
|
||||
: e.target.value === "true",
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
<option value="true">Sim</option>
|
||||
<option value="false">Não</option>
|
||||
</select>
|
||||
);
|
||||
else if (types.includes("array")) {
|
||||
const rows = Array.isArray(value) ? value : [];
|
||||
let item = schema.items ?? { type: "string" };
|
||||
if (item.$ref)
|
||||
item = options.definitions[item.$ref.split("/").pop()!] ?? item;
|
||||
const itemTypes = Array.isArray(item.type) ? item.type : [item.type];
|
||||
return (
|
||||
<fieldset className="space-y-2 rounded border p-3">
|
||||
<legend>{label}</legend>
|
||||
<FieldErrors path={path} errors={errors} />
|
||||
{rows.map((v, i) => (
|
||||
<div key={i} className="space-y-2">
|
||||
<Editor
|
||||
name={name}
|
||||
path={path + "." + i}
|
||||
schema={schema.items ?? { type: "string" }}
|
||||
value={v}
|
||||
options={options}
|
||||
errors={errors}
|
||||
onChange={(next) =>
|
||||
onChange(
|
||||
rows.map((r, j) => (j === i ? next : r)),
|
||||
)
|
||||
}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
onClick={() =>
|
||||
onChange(rows.filter((_, j) => j !== i))
|
||||
}
|
||||
>
|
||||
Retirar linha {i + 1}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
onClick={() =>
|
||||
onChange([
|
||||
...rows,
|
||||
itemTypes.includes("object")
|
||||
? {}
|
||||
: itemTypes.includes("array")
|
||||
? []
|
||||
: "",
|
||||
])
|
||||
}
|
||||
>
|
||||
Adicionar linha
|
||||
</button>
|
||||
</fieldset>
|
||||
);
|
||||
} else if (types.includes("object") || schema.properties) {
|
||||
const fields = schema.properties ?? {};
|
||||
const data =
|
||||
value && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Data)
|
||||
: {};
|
||||
return (
|
||||
<fieldset className="space-y-2 rounded border p-3">
|
||||
<legend>{label}</legend>
|
||||
<FieldErrors path={path} errors={errors} />
|
||||
{Object.entries(fields).map(([key, s]) => (
|
||||
<Editor
|
||||
key={key}
|
||||
name={key}
|
||||
path={path + "." + key}
|
||||
schema={s}
|
||||
value={data[key]}
|
||||
options={options}
|
||||
errors={errors}
|
||||
onChange={(v) => onChange({ ...data, [key]: v })}
|
||||
/>
|
||||
))}
|
||||
{!Object.keys(fields).length && (
|
||||
<p>
|
||||
Este detalhe exige definição contratual antes da
|
||||
submissão.
|
||||
</p>
|
||||
)}
|
||||
</fieldset>
|
||||
);
|
||||
} else {
|
||||
const numeric = types.includes("number") || types.includes("integer");
|
||||
input =
|
||||
numeric || schema.format === "date" ? (
|
||||
<input
|
||||
{...props}
|
||||
className={control}
|
||||
type={numeric ? "number" : "date"}
|
||||
step={types.includes("integer") ? 1 : "any"}
|
||||
value={String(value ?? "")}
|
||||
onChange={(e) =>
|
||||
onChange(
|
||||
e.target.value === ""
|
||||
? null
|
||||
: numeric
|
||||
? Number(e.target.value)
|
||||
: e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<textarea
|
||||
{...props}
|
||||
className={control}
|
||||
value={String(value ?? "")}
|
||||
maxLength={schema.maxLength}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div>
|
||||
<label htmlFor={path} className="block">
|
||||
{label}
|
||||
</label>
|
||||
{input}
|
||||
<FieldErrors path={path} errors={errors} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
export default function OpportunityCanonicalFields({
|
||||
value,
|
||||
onChange,
|
||||
options,
|
||||
category,
|
||||
organization,
|
||||
actorId,
|
||||
sectors,
|
||||
disabled = false,
|
||||
errors = {},
|
||||
}: {
|
||||
value: Data;
|
||||
onChange: (v: Data) => void;
|
||||
options: CanonicalOptions;
|
||||
category: string;
|
||||
organization: string | null;
|
||||
actorId: number;
|
||||
sectors: { id: number; name: string }[];
|
||||
disabled?: boolean;
|
||||
errors?: Record<string, string>;
|
||||
}) {
|
||||
const set = (key: string, v: unknown) =>
|
||||
onChange({
|
||||
...value,
|
||||
[key]: v,
|
||||
...(key === "sector_id"
|
||||
? { subsector_id: null, economic_activity_id: null }
|
||||
: key === "subsector_id"
|
||||
? { economic_activity_id: null }
|
||||
: {}),
|
||||
opportunity_category: category,
|
||||
promoter_id: organization ?? actorId,
|
||||
});
|
||||
const common = [
|
||||
"official_title",
|
||||
"promoter_type",
|
||||
"internal_contact_id",
|
||||
"publish_contact",
|
||||
"public_contact_id",
|
||||
"sector_id",
|
||||
"subsector_id",
|
||||
"economic_activity_id",
|
||||
"location_mode",
|
||||
"geographic_scope",
|
||||
"multi_district_rationale",
|
||||
"locations",
|
||||
"executive_summary",
|
||||
"demand_statement",
|
||||
"documents",
|
||||
"evidences",
|
||||
"publication_languages",
|
||||
"visibility",
|
||||
"currency",
|
||||
"review_due_date",
|
||||
"images",
|
||||
"truth_declaration",
|
||||
];
|
||||
const specialized =
|
||||
category === "real_estate"
|
||||
? ["real_estate"]
|
||||
: category === "land_rights"
|
||||
? ["land_rights"]
|
||||
: ["business_sale", "business_partnership", "franchise"].includes(
|
||||
category,
|
||||
)
|
||||
? ["business_transaction"]
|
||||
: category === "investment_project"
|
||||
? [
|
||||
"opportunity_type",
|
||||
"maturity_stage",
|
||||
"investment_modalities",
|
||||
"investor_profiles",
|
||||
"products",
|
||||
"assets",
|
||||
"inputs",
|
||||
"markets",
|
||||
"competitive_advantage",
|
||||
"employment",
|
||||
"impact_indicators",
|
||||
"total_investment",
|
||||
"currency",
|
||||
"investment_breakdown",
|
||||
"secured_financing",
|
||||
"funding_sought",
|
||||
"financial_indicators",
|
||||
"milestones",
|
||||
"licenses",
|
||||
"environmental_social",
|
||||
"risks",
|
||||
"relations",
|
||||
]
|
||||
: ["module_profile_version"];
|
||||
return (
|
||||
<fieldset disabled={disabled} className="space-y-4 rounded border p-4">
|
||||
<legend>Contrato da oportunidade — {category}</legend>
|
||||
<p>
|
||||
O rascunho pode ficar incompleto. A submissão verifica os campos
|
||||
aplicáveis e os recursos guardados. Validação interna não
|
||||
equivale a autorização externa.
|
||||
</p>
|
||||
{Array.from(new Set([...common, ...specialized])).map((key) => {
|
||||
if (
|
||||
[
|
||||
"sector_id",
|
||||
"subsector_id",
|
||||
"economic_activity_id",
|
||||
"internal_contact_id",
|
||||
"public_contact_id",
|
||||
].includes(key)
|
||||
) {
|
||||
const rows =
|
||||
key === "sector_id"
|
||||
? sectors.map((s) => ({ id: s.id, label: s.name }))
|
||||
: [
|
||||
"internal_contact_id",
|
||||
"public_contact_id",
|
||||
].includes(key)
|
||||
? options.contacts.map((c) => ({
|
||||
id: c.id,
|
||||
label: c.full_name,
|
||||
}))
|
||||
: options.activities
|
||||
.filter((a) =>
|
||||
key === "subsector_id"
|
||||
? options.activities.some(
|
||||
(root) =>
|
||||
root.sector_id ===
|
||||
Number(
|
||||
value.sector_id,
|
||||
) &&
|
||||
a.parent_id === root.id,
|
||||
)
|
||||
: a.parent_id ===
|
||||
value.subsector_id,
|
||||
)
|
||||
.map((a) => ({
|
||||
id: a.id,
|
||||
label: a.label_pt_mz,
|
||||
}));
|
||||
return (
|
||||
<label key={key} className="block">
|
||||
{labels[key]}
|
||||
<FieldErrors
|
||||
path={"canonical." + key}
|
||||
errors={errors}
|
||||
/>
|
||||
<select
|
||||
className={control}
|
||||
value={String(value[key] ?? "")}
|
||||
onChange={(e) =>
|
||||
set(
|
||||
key,
|
||||
e.target.value === ""
|
||||
? null
|
||||
: key === "sector_id"
|
||||
? Number(e.target.value)
|
||||
: e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{rows.map((r) => (
|
||||
<option key={r.id} value={r.id}>
|
||||
{r.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
if (["locations", "documents", "images"].includes(key)) {
|
||||
const selected = Array.isArray(value[key])
|
||||
? (value[key] as string[])
|
||||
: [];
|
||||
return (
|
||||
<fieldset key={key}>
|
||||
<legend>{labels[key]}</legend>
|
||||
<FieldErrors
|
||||
path={"canonical." + key}
|
||||
errors={errors}
|
||||
/>
|
||||
{(options.resources[key] ?? []).map((r) => (
|
||||
<label key={r.id} className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selected.includes(r.id)}
|
||||
onChange={(e) =>
|
||||
set(
|
||||
key,
|
||||
e.target.checked
|
||||
? [...selected, r.id]
|
||||
: selected.filter(
|
||||
(id) => id !== r.id,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>{" "}
|
||||
{r.payload.title ??
|
||||
r.payload.role ??
|
||||
r.file?.file_name ??
|
||||
r.id}
|
||||
<FieldErrors
|
||||
path={`canonical.${key}.${r.id}`}
|
||||
errors={errors}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
{key === "locations" &&
|
||||
selected.map((id) => (
|
||||
<TerritoryGeometryPreview
|
||||
key={id}
|
||||
territoryId={resourceTerritory(
|
||||
options.resources.locations?.find(
|
||||
(r) => r.id === id,
|
||||
),
|
||||
)}
|
||||
endpoint="/minhas-oportunidades/territory-geometries"
|
||||
/>
|
||||
))}
|
||||
{!options.resources[key]?.length && (
|
||||
<p>
|
||||
Guarde primeiro em Recursos e regresse a
|
||||
este contrato.
|
||||
</p>
|
||||
)}
|
||||
</fieldset>
|
||||
);
|
||||
}
|
||||
const schema = options.schema.properties?.[key];
|
||||
return schema ? (
|
||||
<Editor
|
||||
key={key}
|
||||
name={key}
|
||||
path={"canonical." + key}
|
||||
errors={errors}
|
||||
schema={schema}
|
||||
value={value[key]}
|
||||
options={options}
|
||||
onChange={(v) => set(key, v)}
|
||||
/>
|
||||
) : null;
|
||||
})}
|
||||
</fieldset>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
import InteractiveInvestmentMap from "./interactive-investment-map";
|
||||
import { control } from "@/pages/management/shared";
|
||||
import type { MultiPolygon } from "geojson";
|
||||
|
||||
type Point = [number | null, number | null];
|
||||
export default function OpportunityParcelGeometry({
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
value: unknown;
|
||||
onChange: (v: unknown) => void;
|
||||
}) {
|
||||
const data =
|
||||
value && typeof value === "object"
|
||||
? (value as { coordinates?: Point[][][] })
|
||||
: {};
|
||||
const polygons = Array.isArray(data.coordinates) ? data.coordinates : [];
|
||||
function replace(p: number, r: number, points: Point[]) {
|
||||
onChange({
|
||||
type: "MultiPolygon",
|
||||
coordinates: polygons.map((poly, i) =>
|
||||
i === p
|
||||
? poly.map((ring, j) => (j === r ? points : ring))
|
||||
: poly,
|
||||
),
|
||||
});
|
||||
}
|
||||
const valid =
|
||||
polygons.length > 0 &&
|
||||
polygons.every(
|
||||
(poly) =>
|
||||
poly.length > 0 &&
|
||||
poly.every(
|
||||
(ring) =>
|
||||
ring.length >= 4 &&
|
||||
ring.every(
|
||||
(point) =>
|
||||
point.length === 2 &&
|
||||
point.every(
|
||||
(c) =>
|
||||
typeof c === "number" &&
|
||||
Number.isFinite(c),
|
||||
),
|
||||
) &&
|
||||
ring[0][0] === ring.at(-1)?.[0] &&
|
||||
ring[0][1] === ring.at(-1)?.[1],
|
||||
),
|
||||
);
|
||||
return (
|
||||
<section className="space-y-2">
|
||||
<p>
|
||||
Indique longitude e latitude do perímetro declarado. O limite
|
||||
administrativo serve de contexto; não define a parcela.
|
||||
</p>
|
||||
{polygons.map((poly, p) => (
|
||||
<fieldset key={p} className="rounded border p-2">
|
||||
<legend>Polígono {p + 1}</legend>
|
||||
{poly.map((ring, r) => (
|
||||
<section key={r}>
|
||||
<h4>
|
||||
{r === 0
|
||||
? "Anel exterior"
|
||||
: `Anel interior ${r}`}
|
||||
</h4>
|
||||
{ring.map((point, i) => (
|
||||
<div key={i} className="flex flex-wrap gap-2">
|
||||
{[0, 1].map((axis) => (
|
||||
<label key={axis}>
|
||||
{axis === 0
|
||||
? "Longitude"
|
||||
: "Latitude"}
|
||||
<input
|
||||
className={control}
|
||||
type="number"
|
||||
step="any"
|
||||
min={axis === 0 ? -180 : -90}
|
||||
max={axis === 0 ? 180 : 90}
|
||||
value={point[axis] ?? ""}
|
||||
onChange={(e) =>
|
||||
replace(
|
||||
p,
|
||||
r,
|
||||
ring.map((v, j) =>
|
||||
j === i
|
||||
? (v.map(
|
||||
(c, k) =>
|
||||
k ===
|
||||
axis
|
||||
? e
|
||||
.target
|
||||
.value ===
|
||||
""
|
||||
? null
|
||||
: Number(
|
||||
e
|
||||
.target
|
||||
.value,
|
||||
)
|
||||
: c,
|
||||
) as Point)
|
||||
: v,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
replace(
|
||||
p,
|
||||
r,
|
||||
ring.filter((_, j) => j !== i),
|
||||
)
|
||||
}
|
||||
>
|
||||
Retirar vértice {i + 1}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className="underline mr-4"
|
||||
onClick={() =>
|
||||
replace(p, r, [...ring, [null, null]])
|
||||
}
|
||||
>
|
||||
Adicionar vértice
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="underline mr-4"
|
||||
disabled={
|
||||
!ring.length ||
|
||||
ring[0].some((c) => c === null)
|
||||
}
|
||||
onClick={() =>
|
||||
replace(p, r, [
|
||||
...ring,
|
||||
[...ring[0]] as Point,
|
||||
])
|
||||
}
|
||||
>
|
||||
Fechar anel
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
onChange({
|
||||
type: "MultiPolygon",
|
||||
coordinates: polygons.map((v, i) =>
|
||||
i === p
|
||||
? v.filter((_, j) => j !== r)
|
||||
: v,
|
||||
),
|
||||
})
|
||||
}
|
||||
>
|
||||
Retirar anel
|
||||
</button>
|
||||
</section>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className="underline mr-4"
|
||||
onClick={() =>
|
||||
onChange({
|
||||
type: "MultiPolygon",
|
||||
coordinates: polygons.map((v, i) =>
|
||||
i === p ? [...v, []] : v,
|
||||
),
|
||||
})
|
||||
}
|
||||
>
|
||||
Adicionar anel interior
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
onChange({
|
||||
type: "MultiPolygon",
|
||||
coordinates: polygons.filter((_, i) => i !== p),
|
||||
})
|
||||
}
|
||||
>
|
||||
Retirar polígono
|
||||
</button>
|
||||
</fieldset>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
onClick={() =>
|
||||
onChange({
|
||||
type: "MultiPolygon",
|
||||
coordinates: [...polygons, [[]]],
|
||||
})
|
||||
}
|
||||
>
|
||||
Adicionar polígono
|
||||
</button>
|
||||
{valid && (
|
||||
<InteractiveInvestmentMap
|
||||
points={[]}
|
||||
contextOnly
|
||||
areas={[
|
||||
{
|
||||
purpose: "declared_parcel",
|
||||
title: "Perímetro declarado pelo Promotor",
|
||||
source_reference:
|
||||
"Declaração do Promotor; revisão cadastral pendente",
|
||||
url: "#",
|
||||
geometry: {
|
||||
type: "MultiPolygon",
|
||||
coordinates: polygons as [number, number][][][],
|
||||
} as MultiPolygon,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
import { router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { profileJson, ProfileValidationError } from '@/lib/profile-json';
|
||||
import { button, control } from '@/pages/management/shared';
|
||||
|
||||
export default function OpportunityProfileActions({
|
||||
id,
|
||||
etag,
|
||||
actions,
|
||||
gates,
|
||||
documents,
|
||||
approvalHash,
|
||||
onErrors,
|
||||
participants = [],
|
||||
publishers = [],
|
||||
opinions = [],
|
||||
publicationVisibility,
|
||||
}: {
|
||||
id: number;
|
||||
etag: string;
|
||||
actions: string[];
|
||||
gates: string[];
|
||||
documents: { id: string; title: string }[];
|
||||
approvalHash?: string;
|
||||
publicationVisibility?: string;
|
||||
onErrors?: (errors: Record<string, string>) => void;
|
||||
publishers?: { id: number; name: string }[];
|
||||
participants?: {
|
||||
id: number;
|
||||
name: string;
|
||||
technical: boolean;
|
||||
legal: boolean;
|
||||
}[];
|
||||
opinions?: {
|
||||
id: string;
|
||||
gate: string;
|
||||
recipient_id: number;
|
||||
status: string;
|
||||
}[];
|
||||
}) {
|
||||
const [reason, setReason] = useState('');
|
||||
const [items, setItems] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
const [gate, setGate] = useState(gates[0] ?? '');
|
||||
const [decision, setDecision] = useState('approved');
|
||||
const [evidence, setEvidence] = useState<string[]>([]);
|
||||
const [assignee, setAssignee] = useState('');
|
||||
const [confirmed, setConfirmed] = useState(false);
|
||||
const [recipient, setRecipient] = useState('');
|
||||
const [opinion, setOpinion] = useState('');
|
||||
const [actionErrors, setActionErrors] = useState<Record<string, string>>(
|
||||
{},
|
||||
);
|
||||
const labels: Record<string, string> = {
|
||||
submit: 'Submeter para validação',
|
||||
approve: 'Aprovar versão',
|
||||
publish:
|
||||
publicationVisibility === 'public'
|
||||
? 'Publicar no catálogo público'
|
||||
: 'Disponibilizar com acesso restrito',
|
||||
request_revision: 'Preparar alteração material',
|
||||
review_gate: 'Guardar revisão especializada',
|
||||
assign_review: 'Atribuir validação',
|
||||
assign_publication: 'Atribuir publicação',
|
||||
appeal_uphold: 'Manter rejeição após recurso',
|
||||
appeal_reopen: 'Reabrir para correção',
|
||||
request_archive: 'Solicitar arquivo',
|
||||
appeal: 'Apresentar recurso',
|
||||
start_review: 'Iniciar validação',
|
||||
request_correction: 'Solicitar correções',
|
||||
pending_opinion: 'Solicitar parecer',
|
||||
respond_opinion: 'Responder ao parecer',
|
||||
reject: 'Rejeitar com fundamento',
|
||||
suspend: 'Suspender',
|
||||
archive: 'Arquivar',
|
||||
};
|
||||
async function send(action: string) {
|
||||
setBusy(true);
|
||||
setActionErrors({});
|
||||
onErrors?.({});
|
||||
try {
|
||||
const result = await profileJson(
|
||||
`/minhas-oportunidades/${id}/workflow`,
|
||||
{
|
||||
etag,
|
||||
action,
|
||||
reason,
|
||||
correction_items: items
|
||||
.split('\n')
|
||||
.map((v) => v.trim())
|
||||
.filter(Boolean),
|
||||
...(['review_gate', 'respond_opinion'].includes(action)
|
||||
? {
|
||||
gate,
|
||||
gate_decision: decision,
|
||||
evidence_document_ids: evidence,
|
||||
}
|
||||
: {}),
|
||||
...(action === 'pending_opinion'
|
||||
? { gate, recipient_user_id: Number(recipient) }
|
||||
: {}),
|
||||
...(action === 'respond_opinion'
|
||||
? { opinion_id: opinion }
|
||||
: {}),
|
||||
...(['assign_review', 'assign_publication'].includes(action)
|
||||
? { assignee_user_id: Number(assignee) }
|
||||
: {}),
|
||||
...(action === 'publish'
|
||||
? {
|
||||
confirm_publication: confirmed,
|
||||
preview_hash: approvalHash,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
);
|
||||
setMessage(result.message);
|
||||
router.visit(`/minhas-oportunidades/${id}/view`);
|
||||
} catch (error) {
|
||||
if (error instanceof ProfileValidationError) {
|
||||
setActionErrors(error.fields);
|
||||
onErrors?.(error.fields);
|
||||
}
|
||||
setMessage(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Resposta indisponível. Confira o estado antes de repetir.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<section
|
||||
className="space-y-3 rounded border p-4"
|
||||
aria-label="Workflow interno"
|
||||
>
|
||||
<h2 className="text-lg font-semibold">Workflow interno</h2>
|
||||
<p>
|
||||
Guarde o contrato antes de submeter. Aprovação exige revisões
|
||||
especializadas desta versão; publicação exige outro utilizador
|
||||
autorizado. Uma decisão interna não substitui decisão externa.
|
||||
</p>
|
||||
<p>
|
||||
Aprovação interna confirma a revisão desta versão.
|
||||
Disponibilização restrita não aparece no catálogo público nem dá
|
||||
acesso a todas as contas. A publicação pública exige âmbito
|
||||
público e ação independente do Publicador; não representa uma
|
||||
decisão externa.
|
||||
</p>
|
||||
{!!actions.length && (
|
||||
<>
|
||||
<label className="block">
|
||||
Fundamentação
|
||||
<textarea
|
||||
className={control}
|
||||
minLength={20}
|
||||
maxLength={1000}
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
{actions.includes('request_correction') && (
|
||||
<label className="block">
|
||||
Campos ou documentos a corrigir, um por linha
|
||||
<textarea
|
||||
className={control}
|
||||
value={items}
|
||||
onChange={(e) => setItems(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
{(actions.includes('review_gate') ||
|
||||
actions.includes('pending_opinion') ||
|
||||
actions.includes('respond_opinion')) && (
|
||||
<fieldset>
|
||||
<legend>Revisão especializada</legend>
|
||||
<label>
|
||||
Revisão
|
||||
<select
|
||||
className={control}
|
||||
value={gate}
|
||||
onChange={(e) => setGate(e.target.value)}
|
||||
>
|
||||
{gates.map((g) => (
|
||||
<option key={g} value={g}>
|
||||
{g.replaceAll('_', ' ')}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Decisão
|
||||
<select
|
||||
className={control}
|
||||
value={decision}
|
||||
onChange={(e) =>
|
||||
setDecision(e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="approved">Aprovada</option>
|
||||
<option value="rejected">Rejeitada</option>
|
||||
</select>
|
||||
</label>
|
||||
{documents.map((d) => (
|
||||
<label key={d.id} className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={evidence.includes(d.id)}
|
||||
onChange={(e) =>
|
||||
setEvidence(
|
||||
e.target.checked
|
||||
? [...evidence, d.id]
|
||||
: evidence.filter(
|
||||
(id) => id !== d.id,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>{' '}
|
||||
{d.title}
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
)}
|
||||
{(actions.includes('assign_review') ||
|
||||
actions.includes('assign_publication')) && (
|
||||
<label className="block">
|
||||
Responsável a designar
|
||||
<select
|
||||
className={control}
|
||||
value={assignee}
|
||||
onChange={(e) => setAssignee(e.target.value)}
|
||||
>
|
||||
<option value="">Por atribuir</option>
|
||||
{(actions.includes('assign_publication')
|
||||
? publishers
|
||||
: participants
|
||||
).map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<span>
|
||||
O servidor verifica o papel, âmbito e
|
||||
independência. Nenhum responsável é atribuído
|
||||
automaticamente.
|
||||
</span>
|
||||
</label>
|
||||
)}
|
||||
{actions.includes('pending_opinion') && (
|
||||
<label className="block">
|
||||
Destinatário do parecer
|
||||
<select
|
||||
className={control}
|
||||
value={recipient}
|
||||
onChange={(e) => setRecipient(e.target.value)}
|
||||
>
|
||||
<option value="">Por designar</option>
|
||||
{participants
|
||||
.filter((p) =>
|
||||
/legal|registry|authority|confidentiality|license/.test(
|
||||
gate,
|
||||
)
|
||||
? p.legal
|
||||
: p.technical,
|
||||
)
|
||||
.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
{actions.includes('respond_opinion') && (
|
||||
<label className="block">
|
||||
Parecer atribuído
|
||||
<select
|
||||
className={control}
|
||||
value={opinion}
|
||||
onChange={(e) => setOpinion(e.target.value)}
|
||||
>
|
||||
<option value="">Selecione</option>
|
||||
{opinions
|
||||
.filter((o) => o.status === 'pending')
|
||||
.map((o) => (
|
||||
<option key={o.id} value={o.id}>
|
||||
{o.gate.replaceAll('_', ' ')} —
|
||||
conta {o.recipient_id}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
{Object.entries(actionErrors)
|
||||
.filter(([key]) => !key.startsWith('canonical'))
|
||||
.map(([key, msg]) => (
|
||||
<p key={key} role="alert">
|
||||
{key}: {msg}
|
||||
</p>
|
||||
))}
|
||||
{actions.includes('publish') && (
|
||||
<label className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={confirmed}
|
||||
onChange={(e) => setConfirmed(e.target.checked)}
|
||||
/>{' '}
|
||||
Confirmei a pré-visualização e o âmbito de
|
||||
divulgação desta versão.
|
||||
</label>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{actions.map((action) => (
|
||||
<button
|
||||
key={action}
|
||||
className={button}
|
||||
disabled={
|
||||
busy || (action === 'publish' && !confirmed)
|
||||
}
|
||||
onClick={() => void send(action)}
|
||||
>
|
||||
{labels[action] ?? action}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<p role="status" aria-live="polite">
|
||||
{message}
|
||||
</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
import type { ProfileAccess } from '@/types/profile-access';
|
||||
import { Link, usePage } from '@inertiajs/react';
|
||||
import { useEffect, useId, useRef, useState } from 'react';
|
||||
import type { OpportunityManagementAccess } from '@/types/opportunity-management';
|
||||
import {
|
||||
portalNavigation,
|
||||
currentNavigationGroup,
|
||||
@@ -14,6 +16,8 @@ export function PortalGroupedMenu() {
|
||||
educationEnabled?: boolean;
|
||||
aiEnabled?: boolean;
|
||||
portalOperator?: string | null;
|
||||
profileAccess?: ProfileAccess | null;
|
||||
opportunityManagement?: OpportunityManagementAccess | null;
|
||||
}>();
|
||||
const groups = portalNavigation({
|
||||
authenticated: !!props.auth?.user,
|
||||
@@ -21,6 +25,8 @@ export function PortalGroupedMenu() {
|
||||
businesses: props.existingBusinessEnabled,
|
||||
education: props.educationEnabled,
|
||||
ai: props.aiEnabled,
|
||||
opportunityManagement: props.opportunityManagement,
|
||||
profileAccess: props.profileAccess,
|
||||
});
|
||||
const current = currentNavigationGroup(groups, url);
|
||||
const currentItem = currentNavigationItem(groups, url);
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { Link, usePage } from '@inertiajs/react';
|
||||
import type { ProfileAccess } from '@/types/profile-access';
|
||||
|
||||
export function profileLinks(access: ProfileAccess | null | undefined) {
|
||||
if (!access) return [];
|
||||
return [
|
||||
...(access.mine
|
||||
? [{ title: 'Minhas oportunidades', href: access.mine }]
|
||||
: []),
|
||||
...(access.create
|
||||
? [{ title: 'Nova oportunidade', href: access.create }]
|
||||
: []),
|
||||
{
|
||||
title: access.mine
|
||||
? 'Autorizações de Promotor'
|
||||
: 'Solicitar perfil de Promotor',
|
||||
href: access.request,
|
||||
},
|
||||
...(!access.mine && access.review
|
||||
? [{ title: 'Revisão de oportunidades', href: access.review }]
|
||||
: []),
|
||||
...(access.audit
|
||||
? [{ title: 'Auditoria de acessos', href: access.audit }]
|
||||
: []),
|
||||
...(access.administration
|
||||
? [{ title: 'Gestão de perfis', href: access.administration }]
|
||||
: []),
|
||||
...(access.administration
|
||||
? [
|
||||
{
|
||||
title: 'Instalação dos perfis 040000',
|
||||
href: '/management/profile-install',
|
||||
},
|
||||
]
|
||||
: []),
|
||||
];
|
||||
}
|
||||
|
||||
export default function ProfileNavigation() {
|
||||
const { profileAccess } = usePage<{
|
||||
profileAccess?: ProfileAccess | null;
|
||||
}>().props;
|
||||
if (!profileAccess) return null;
|
||||
return (
|
||||
<nav
|
||||
aria-label="Perfil e oportunidades"
|
||||
className="flex flex-wrap gap-4 rounded border p-4"
|
||||
>
|
||||
{profileLinks(profileAccess).map((link) => (
|
||||
<Link key={link.href} href={link.href} className="underline">
|
||||
{link.title}
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
@@ -13,9 +13,11 @@ type Context = {
|
||||
export default function TerritoryGeometryPreview({
|
||||
territoryId,
|
||||
management = false,
|
||||
endpoint: suppliedEndpoint,
|
||||
}: {
|
||||
territoryId?: string;
|
||||
management?: boolean;
|
||||
endpoint?: string;
|
||||
}) {
|
||||
const [context, setContext] = useState<Context | null>(null);
|
||||
const [error, setError] = useState('');
|
||||
@@ -24,9 +26,9 @@ export default function TerritoryGeometryPreview({
|
||||
setError('');
|
||||
if (!territoryId) return;
|
||||
const controller = new AbortController();
|
||||
const endpoint = management
|
||||
const endpoint = suppliedEndpoint ?? (management
|
||||
? '/management/territory-geometries'
|
||||
: '/api/v1/investment/territory-geometries';
|
||||
: '/api/v1/investment/territory-geometries');
|
||||
void fetch(
|
||||
`${endpoint}?${new URLSearchParams({ territory_id: territoryId })}`,
|
||||
{
|
||||
@@ -51,7 +53,7 @@ export default function TerritoryGeometryPreview({
|
||||
);
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [territoryId, management]);
|
||||
}, [territoryId, management, suppliedEndpoint]);
|
||||
if (!territoryId) return null;
|
||||
return (
|
||||
<section
|
||||
@@ -66,7 +68,7 @@ export default function TerritoryGeometryPreview({
|
||||
<p role="status">
|
||||
{context.selected_geometry_available
|
||||
? 'Limite administrativo disponível para este território.'
|
||||
: 'Sem limite administrativo disponível para este território.'}
|
||||
: 'Sem limite administrativo acessível para este território neste perfil.'}
|
||||
</p>
|
||||
<p>
|
||||
{context.context_geometry_count} limites disponíveis na
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import type { ProfileAccess } from '@/types/profile-access';
|
||||
import type { OpportunityManagementAccess } from '@/types/opportunity-management';
|
||||
|
||||
export type PortalNavItem = {
|
||||
id: string;
|
||||
label: string;
|
||||
@@ -10,6 +13,8 @@ export type PortalNavAccess = {
|
||||
businesses?: boolean;
|
||||
education?: boolean;
|
||||
ai?: boolean;
|
||||
profileAccess?: ProfileAccess | null;
|
||||
opportunityManagement?: OpportunityManagementAccess | null;
|
||||
};
|
||||
const link = (id: string, label: string, href: string): PortalNavItem => ({
|
||||
id,
|
||||
@@ -19,6 +24,7 @@ const link = (id: string, label: string, href: string): PortalNavItem => ({
|
||||
|
||||
/** One route catalogue for the public shell and authenticated pages. */
|
||||
export function portalNavigation(access: PortalNavAccess): PortalNavItem[] {
|
||||
const opportunities = access.manager ? access.opportunityManagement : null;
|
||||
const groups: PortalNavItem[] = [
|
||||
{
|
||||
id: 'explore',
|
||||
@@ -124,7 +130,11 @@ export function portalNavigation(access: PortalNavAccess): PortalNavItem[] {
|
||||
label: 'A minha área',
|
||||
children: access.authenticated
|
||||
? [
|
||||
link('dashboard', 'Painel', '/investidor'),
|
||||
link(
|
||||
'dashboard',
|
||||
opportunities ? 'Painel da gestão' : 'Painel',
|
||||
opportunities ? '/dashboard' : '/investidor',
|
||||
),
|
||||
link(
|
||||
'profile',
|
||||
'Perfil e empresas',
|
||||
@@ -164,6 +174,24 @@ export function portalNavigation(access: PortalNavAccess): PortalNavItem[] {
|
||||
'/management/interests',
|
||||
),
|
||||
link('crm', 'CRM interno', '/management/crm/leads'),
|
||||
...(opportunities
|
||||
? [
|
||||
link(
|
||||
'manage-opportunities',
|
||||
opportunities.manage.label,
|
||||
opportunities.manage.href,
|
||||
),
|
||||
...(opportunities.installed
|
||||
? [
|
||||
link(
|
||||
'create-opportunity',
|
||||
opportunities.create.label,
|
||||
opportunities.create.href,
|
||||
),
|
||||
]
|
||||
: []),
|
||||
]
|
||||
: []),
|
||||
{
|
||||
id: 'manage-catalogue',
|
||||
label: 'Catálogo de investimento',
|
||||
@@ -173,11 +201,15 @@ export function portalNavigation(access: PortalNavAccess): PortalNavItem[] {
|
||||
'Sectores',
|
||||
'/management/sectors',
|
||||
),
|
||||
link(
|
||||
'manage-opportunities',
|
||||
'Oportunidades',
|
||||
'/management/opportunities',
|
||||
),
|
||||
...(!opportunities
|
||||
? [
|
||||
link(
|
||||
'manage-opportunities',
|
||||
'Oportunidades',
|
||||
'/management/opportunities',
|
||||
),
|
||||
]
|
||||
: []),
|
||||
link(
|
||||
'manage-projects',
|
||||
'Projectos',
|
||||
@@ -245,6 +277,17 @@ export function portalNavigation(access: PortalNavAccess): PortalNavItem[] {
|
||||
: []),
|
||||
],
|
||||
});
|
||||
if (access.authenticated && access.profileAccess) {
|
||||
const profile = access.profileAccess;
|
||||
groups.push({id: 'profile-opportunities', label: 'Perfil e oportunidades', children: [
|
||||
...(profile.mine ? [link('my-opportunities', 'Minhas oportunidades', profile.mine)] : []),
|
||||
...(profile.create ? [link('new-my-opportunity', 'Nova oportunidade', profile.create)] : []),
|
||||
link('promoter-profile', profile.mine ? 'Autorizações de Promotor' : 'Solicitar perfil de Promotor', profile.request),
|
||||
...(!profile.mine && profile.review ? [link('profile-review', 'Revisão de oportunidades', profile.review)] : []),
|
||||
...(profile.audit ? [link('profile-audit', 'Auditoria de acessos', profile.audit)] : []),
|
||||
...(profile.administration ? [link('profile-administration', 'Gestão de perfis', profile.administration)] : []),
|
||||
]});
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
export class ProfileValidationError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly fields: Record<string, string>,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
export async function profileJson(
|
||||
url: string,
|
||||
data: object = {},
|
||||
method: 'GET' | 'POST' = 'POST',
|
||||
) {
|
||||
const cookie = document.cookie
|
||||
.split('; ')
|
||||
.find((c) => c.startsWith('XSRF-TOKEN='));
|
||||
const response = await fetch(url, {
|
||||
method,
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-XSRF-TOKEN': cookie ? decodeURIComponent(cookie.slice(11)) : '',
|
||||
},
|
||||
body: method === 'GET' ? undefined : JSON.stringify(data),
|
||||
});
|
||||
const result = await response.json();
|
||||
if (!response.ok)
|
||||
throw new ProfileValidationError(
|
||||
result.message ?? 'A ação não foi concluída.',
|
||||
Object.fromEntries(
|
||||
Object.entries(result.errors ?? {}).map(([key, value]) => [
|
||||
key,
|
||||
Array.isArray(value) ? value.join(' ') : String(value),
|
||||
]),
|
||||
),
|
||||
);
|
||||
return result;
|
||||
}
|
||||
@@ -1,8 +1,11 @@
|
||||
import ProfileNavigation from '@/components/profile-navigation';
|
||||
import { Head, Link } from '@inertiajs/react';
|
||||
import { dashboard } from '@/routes';
|
||||
import type { InvestmentContext } from '@/pages/investor-path/index';
|
||||
import type { OpportunityManagementAccess } from '@/types/opportunity-management';
|
||||
|
||||
type Summary = {
|
||||
canCreateOpportunity?: boolean;
|
||||
requestsByStatus: Record<string, number>;
|
||||
publishedOpportunities: number;
|
||||
draftOpportunities: number;
|
||||
@@ -27,8 +30,10 @@ const card =
|
||||
export default function Dashboard({
|
||||
summary,
|
||||
investorPath,
|
||||
opportunityManagement,
|
||||
}: {
|
||||
summary: Summary | null;
|
||||
opportunityManagement?: OpportunityManagementAccess | null;
|
||||
investorPath?: {
|
||||
contexts: InvestmentContext[];
|
||||
current: {
|
||||
@@ -45,8 +50,53 @@ export default function Dashboard({
|
||||
<main className="space-y-8 p-4 md:p-8">
|
||||
<Head title="Painel" />
|
||||
<h1 className="text-2xl font-semibold">Painel do portal</h1>
|
||||
<ProfileNavigation />
|
||||
{summary ? (
|
||||
<>
|
||||
{opportunityManagement && (
|
||||
<section
|
||||
aria-label="Gestão de Oportunidades"
|
||||
className="space-y-4 rounded-xl border p-5"
|
||||
>
|
||||
<h2 className="text-lg font-semibold">
|
||||
Gestão de Oportunidades
|
||||
</h2>
|
||||
<nav
|
||||
aria-label="Ações de oportunidades"
|
||||
className="flex flex-wrap gap-3"
|
||||
>
|
||||
<Link
|
||||
className="rounded-lg border px-4 py-2 underline"
|
||||
href={opportunityManagement.manage.href}
|
||||
>
|
||||
{opportunityManagement.manage.label}
|
||||
</Link>
|
||||
{opportunityManagement.installed ? (
|
||||
<Link
|
||||
className="bg-primary text-primary-foreground rounded-lg px-4 py-2"
|
||||
href={opportunityManagement.create.href}
|
||||
>
|
||||
{opportunityManagement.create.label}
|
||||
</Link>
|
||||
) : (
|
||||
<Link
|
||||
className="underline"
|
||||
href={
|
||||
opportunityManagement.installationHref
|
||||
}
|
||||
>
|
||||
Preparar instalação da gestão de
|
||||
rascunhos
|
||||
</Link>
|
||||
)}
|
||||
</nav>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Os rascunhos de oportunidades não publicam o
|
||||
dossier privado do investidor. Publicação exige
|
||||
uma ação própria.
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
<section className="space-y-4">
|
||||
<h2 className="text-lg font-semibold">
|
||||
Manifestações de interesse
|
||||
@@ -71,7 +121,9 @@ export default function Dashboard({
|
||||
<section className="space-y-4">
|
||||
<h2 className="text-lg font-semibold">
|
||||
<Link href="/management/opportunities">
|
||||
Gestão de Oportunidades
|
||||
{opportunityManagement
|
||||
? 'Indicadores de oportunidades'
|
||||
: 'Gestão de Oportunidades'}
|
||||
</Link>
|
||||
</h2>
|
||||
<div className="grid gap-4 sm:grid-cols-3">
|
||||
@@ -163,12 +215,13 @@ export default function Dashboard({
|
||||
aria-label="Acções rápidas"
|
||||
className="flex flex-wrap gap-4"
|
||||
>
|
||||
<Link
|
||||
{summary.canCreateOpportunity !== false && <Link
|
||||
className="underline"
|
||||
href="/management/opportunities/create"
|
||||
>
|
||||
Criar oportunidade
|
||||
</Link>
|
||||
{opportunityManagement?.create.label ??
|
||||
'Criar oportunidade'}
|
||||
</Link>}
|
||||
<Link
|
||||
className="underline"
|
||||
href="/management/sectors/create"
|
||||
|
||||
@@ -16,6 +16,10 @@ type Entry = {
|
||||
opportunity_category: string | null;
|
||||
updated_at: string;
|
||||
deleted_at: string | null;
|
||||
can_edit?: boolean;
|
||||
working_status?: string;
|
||||
draft_title?: string;
|
||||
publication?: { scope: string; label: string; public_catalog: boolean };
|
||||
};
|
||||
export default function Opportunities({
|
||||
records,
|
||||
@@ -24,10 +28,13 @@ export default function Opportunities({
|
||||
categories,
|
||||
sectors,
|
||||
geographyReviewCount,
|
||||
basePath = '/management/opportunities',
|
||||
canCreate = true,
|
||||
}: {
|
||||
records: Paginated<Entry>;
|
||||
filters: {
|
||||
q?: string;
|
||||
queue?: string;
|
||||
status?: string;
|
||||
category?: string;
|
||||
deleted?: boolean;
|
||||
@@ -38,9 +45,12 @@ export default function Opportunities({
|
||||
categories: string[];
|
||||
sectors: { id: number; name: string }[];
|
||||
geographyReviewCount: number;
|
||||
basePath?: string;
|
||||
canCreate?: boolean;
|
||||
}) {
|
||||
const form = useForm({
|
||||
q: filters.q ?? '',
|
||||
queue: filters.queue ?? '',
|
||||
status: filters.status ?? '',
|
||||
category: filters.category ?? '',
|
||||
deleted: Boolean(filters.deleted),
|
||||
@@ -48,10 +58,18 @@ export default function Opportunities({
|
||||
geography_scope: filters.geography_scope ?? '',
|
||||
});
|
||||
return (
|
||||
<Management title="Gestão de Oportunidades">
|
||||
<Link className={button} href="/management/opportunities/create">
|
||||
Nova oportunidade
|
||||
</Link>
|
||||
<Management
|
||||
title={
|
||||
basePath === '/minhas-oportunidades'
|
||||
? 'Minhas oportunidades'
|
||||
: 'Gestão de Oportunidades'
|
||||
}
|
||||
>
|
||||
{canCreate && (
|
||||
<Link className={button} href={`${basePath}/create`}>
|
||||
Nova oportunidade
|
||||
</Link>
|
||||
)}
|
||||
<p>
|
||||
{geographyReviewCount} registos com âmbito por indicar;
|
||||
referências existentes permanecem aceites.
|
||||
@@ -72,7 +90,7 @@ export default function Opportunities({
|
||||
<Link
|
||||
className="rounded border p-3"
|
||||
key={s}
|
||||
href={`/management/opportunities?status=${s}`}
|
||||
href={`${basePath}?status=${s}`}
|
||||
>
|
||||
{states[s] ?? s}: {counts[s] ?? 0}
|
||||
</Link>
|
||||
@@ -82,9 +100,31 @@ export default function Opportunities({
|
||||
className="flex flex-wrap gap-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.get('/management/opportunities');
|
||||
form.get(basePath);
|
||||
}}
|
||||
>
|
||||
{basePath === '/minhas-oportunidades' && (
|
||||
<label>
|
||||
Fila
|
||||
<select
|
||||
className={control}
|
||||
value={form.data.queue}
|
||||
onChange={(e) =>
|
||||
form.setData('queue', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Todas as autorizadas</option>
|
||||
<option value="assigned">Atribuídas a mim</option>
|
||||
<option value="review">
|
||||
Validação e pareceres
|
||||
</option>
|
||||
<option value="publication">
|
||||
Preparação editorial
|
||||
</option>
|
||||
<option value="appeal">Recursos pendentes</option>
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
<input
|
||||
aria-label="Pesquisa global"
|
||||
placeholder="Título ou referência"
|
||||
@@ -166,7 +206,7 @@ export default function Opportunities({
|
||||
{records.data.map((r) => (
|
||||
<article key={r.id} className="rounded border p-4">
|
||||
<h2 className="font-semibold">
|
||||
{r.title ?? 'Rascunho sem título'}
|
||||
{r.draft_title ?? r.title ?? 'Rascunho sem título'}
|
||||
</h2>
|
||||
<p>
|
||||
ID {r.id} · {r.reference} ·{' '}
|
||||
@@ -174,24 +214,25 @@ export default function Opportunities({
|
||||
·{' '}
|
||||
{r.deleted_at
|
||||
? 'Eliminado logicamente'
|
||||
: (states[r.status] ?? r.status)}
|
||||
: (r.working_status ?? r.status) === 'published'
|
||||
? 'Versão disponibilizada'
|
||||
: (states[r.working_status ?? r.status] ??
|
||||
r.working_status ??
|
||||
r.status)}
|
||||
</p>
|
||||
{r.publication && <p>{r.publication.label}</p>}
|
||||
<p>Atualizado: {r.updated_at}</p>
|
||||
<div className="flex flex-wrap gap-4">
|
||||
<Link
|
||||
href={`/management/opportunities/${r.id}/view`}
|
||||
>
|
||||
Ver
|
||||
</Link>
|
||||
<Link
|
||||
href={`/management/opportunities/${r.id}/edit`}
|
||||
>
|
||||
{r.deleted_at || r.status === 'archived'
|
||||
? 'Restaurar'
|
||||
: r.status === 'draft'
|
||||
? 'Continuar preenchimento'
|
||||
: 'Editar nova versão'}
|
||||
</Link>
|
||||
<Link href={`${basePath}/${r.id}/view`}>Ver</Link>
|
||||
{r.can_edit !== false && (
|
||||
<Link href={`${basePath}/${r.id}/edit`}>
|
||||
{r.deleted_at || r.status === 'archived'
|
||||
? 'Restaurar'
|
||||
: r.status === 'draft'
|
||||
? 'Continuar preenchimento'
|
||||
: 'Editar nova versão'}
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import OpportunityProfileActions from '@/components/opportunity-profile-actions';
|
||||
import OpportunityCanonicalFields, {
|
||||
type CanonicalOptions,
|
||||
} from '@/components/opportunity-canonical-fields';
|
||||
import { Link, router, usePage } from '@inertiajs/react';
|
||||
import TerritoryGeometryPreview from '@/components/territory-geometry-preview';
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
TerritoryLevel,
|
||||
type TerritoryOption,
|
||||
} from '@/components/investment-territory';
|
||||
import { Management, Field, button, control } from './shared';
|
||||
type Values = Record<string, string | number | null>;
|
||||
import { Management, Field, button, control, states } from './shared';
|
||||
type Values = Record<string, unknown>;
|
||||
type Entry = {
|
||||
id: number;
|
||||
reference: string;
|
||||
@@ -51,8 +55,74 @@ export default function OpportunityDraft({
|
||||
occurred_at: string;
|
||||
}[];
|
||||
}) {
|
||||
const {
|
||||
basePath = '/management/opportunities',
|
||||
profileMode = false,
|
||||
profileOrganization,
|
||||
profileContext,
|
||||
profileAccess,
|
||||
profileActions = [],
|
||||
canonicalOptions,
|
||||
workflowState,
|
||||
workflowTasks = [],
|
||||
workflowParticipants,
|
||||
publicationPreview,
|
||||
publicationState,
|
||||
auth,
|
||||
canEditDraft = false,
|
||||
} = usePage<{
|
||||
basePath?: string;
|
||||
profileMode?: boolean;
|
||||
profileOrganization?: string | null;
|
||||
profileActions?: string[];
|
||||
profileContext?: Record<string, unknown> | null;
|
||||
profileAccess?: {
|
||||
contexts: { organization_id: string | null; type: string }[];
|
||||
} | null;
|
||||
publicationPreview?: {
|
||||
title: string;
|
||||
summary: string;
|
||||
description: string;
|
||||
};
|
||||
workflowParticipants?: {
|
||||
publishers: { id: number; name: string }[];
|
||||
validators: {
|
||||
id: number;
|
||||
name: string;
|
||||
technical: boolean;
|
||||
legal: boolean;
|
||||
}[];
|
||||
};
|
||||
canonicalOptions?: CanonicalOptions;
|
||||
workflowState?: string;
|
||||
publicationState?: {
|
||||
scope: string;
|
||||
label: string;
|
||||
public_catalog: boolean;
|
||||
};
|
||||
workflowTasks?: {
|
||||
id: string;
|
||||
title: string;
|
||||
status: string;
|
||||
assignee_user_id: number | null;
|
||||
due_at: string | null;
|
||||
}[];
|
||||
auth: { user: { id: number } };
|
||||
canEditDraft?: boolean;
|
||||
}>().props;
|
||||
const [data, setData] = useState<Values>({
|
||||
...values,
|
||||
...(profileMode
|
||||
? {
|
||||
organization_id: record
|
||||
? (profileOrganization ?? null)
|
||||
: (profileAccess?.contexts[0]?.organization_id ?? null),
|
||||
opportunity_category:
|
||||
values.opportunity_category ??
|
||||
profileAccess?.contexts[0]?.type ??
|
||||
'',
|
||||
}
|
||||
: {}),
|
||||
creation_key: crypto.randomUUID(),
|
||||
});
|
||||
const [busy, setBusy] = useState(false),
|
||||
@@ -66,9 +136,10 @@ export default function OpportunityDraft({
|
||||
const unavailable = Boolean(
|
||||
record?.deleted_at || record?.status === 'archived',
|
||||
);
|
||||
const archiveAvailable = Boolean(usePage().props.opportunityManagement);
|
||||
const set = (key: string, value: string) =>
|
||||
setData((d) => ({ ...d, [key]: value }));
|
||||
async function send(action: 'save' | 'delete' | 'restore') {
|
||||
async function send(action: 'save' | 'delete' | 'archive' | 'restore') {
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
setErrors({});
|
||||
@@ -80,9 +151,9 @@ export default function OpportunityDraft({
|
||||
const url =
|
||||
action === 'save'
|
||||
? record
|
||||
? `/management/opportunities/${record.id}/draft`
|
||||
: '/management/opportunities/drafts'
|
||||
: `/management/opportunities/${record!.id}/lifecycle`;
|
||||
? `${basePath}/${record.id}/draft`
|
||||
: `${basePath}/drafts`
|
||||
: `${basePath}/${record!.id}/lifecycle`;
|
||||
const response = await fetch(url, {
|
||||
method: action === 'save' && record ? 'PUT' : 'POST',
|
||||
headers: {
|
||||
@@ -116,8 +187,7 @@ export default function OpportunityDraft({
|
||||
}
|
||||
setMessage(result.message);
|
||||
if (result.etag) setToken(result.etag);
|
||||
if (!record)
|
||||
router.visit(`/management/opportunities/${result.id}/edit`);
|
||||
if (!record) router.visit(`${basePath}/${result.id}/edit`);
|
||||
else if (action !== 'save') router.reload();
|
||||
} catch {
|
||||
setMessage(
|
||||
@@ -138,7 +208,61 @@ export default function OpportunityDraft({
|
||||
: 'Nova oportunidade'
|
||||
}
|
||||
>
|
||||
<Link href="/management/opportunities">Voltar à gestão</Link>
|
||||
<Link href={basePath}>
|
||||
{profileMode ? 'Minhas oportunidades' : 'Voltar à gestão'}
|
||||
</Link>
|
||||
{profileMode && record && readOnly && canEditDraft && (
|
||||
<Link
|
||||
className="block underline"
|
||||
href={`${basePath}/${record.id}/edit`}
|
||||
>
|
||||
Editar proposta privada
|
||||
</Link>
|
||||
)}
|
||||
{profileMode && !record && (
|
||||
<label className="block">
|
||||
Organização e tipo autorizados
|
||||
<select
|
||||
className={control}
|
||||
value={`${String(data.organization_id ?? '')}|${String(data.opportunity_category ?? '')}`}
|
||||
onChange={(e) => {
|
||||
const [organization, type] =
|
||||
e.target.value.split('|');
|
||||
setData((d) => ({
|
||||
...d,
|
||||
organization_id: organization || null,
|
||||
opportunity_category: type,
|
||||
}));
|
||||
}}
|
||||
>
|
||||
{(profileAccess?.contexts ?? []).map((c) => (
|
||||
<option
|
||||
key={`${c.organization_id}|${c.type}`}
|
||||
value={`${c.organization_id ?? ''}|${c.type}`}
|
||||
>
|
||||
{c.organization_id ?? 'Âmbito individual'} —{' '}
|
||||
{c.type}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
{profileMode && record && (
|
||||
<p>
|
||||
Estado da preparação:{' '}
|
||||
{(workflowState ?? record.status) === 'published'
|
||||
? 'Versão disponibilizada'
|
||||
: (states[workflowState ?? record.status] ??
|
||||
workflowState ??
|
||||
record.status)}
|
||||
. {publicationState?.label}.{' '}
|
||||
{profileContext?.request_archive
|
||||
? 'Pedido de arquivo registado; aguarda decisão independente.'
|
||||
: ''}{' '}
|
||||
O Promotor solicita arquivo; não elimina nem restaura
|
||||
oportunidades.
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
Classificação de origem: {classification}. Esta classificação
|
||||
não cria associações territoriais.
|
||||
@@ -147,7 +271,8 @@ export default function OpportunityDraft({
|
||||
<p>
|
||||
Versão anterior fechada. As alterações são guardadas numa
|
||||
nova versão de rascunho; a ficha publicada permanece
|
||||
intacta. Este incremento não submete, aprova ou publica.
|
||||
intacta. Guardar não submete: use as ações do workflow para
|
||||
revisão, aprovação e publicação independentes.
|
||||
</p>
|
||||
)}
|
||||
<div
|
||||
@@ -163,7 +288,7 @@ export default function OpportunityDraft({
|
||||
<a
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
href={`/management/opportunities/${record?.id}/view`}
|
||||
href={`${basePath}/${record?.id}/view`}
|
||||
>
|
||||
Abrir versão atual
|
||||
</a>
|
||||
@@ -177,119 +302,153 @@ export default function OpportunityDraft({
|
||||
void send('save');
|
||||
}}
|
||||
>
|
||||
<fieldset
|
||||
disabled={busy || readOnly || unavailable}
|
||||
className="space-y-4"
|
||||
>
|
||||
<section aria-label="Localização registada">
|
||||
<TerritoryGeometryPreview
|
||||
territoryId={path.at(-1)?.id}
|
||||
management
|
||||
/>
|
||||
<p>
|
||||
Hierarquia do cadastro territorial existente.
|
||||
Alterar esta seleção não cria relações com
|
||||
projetos/clusters.
|
||||
</p>
|
||||
{(
|
||||
[
|
||||
'province_id',
|
||||
'district_id',
|
||||
'admin_post_id',
|
||||
'locality_id',
|
||||
] as const
|
||||
).map((key, index) => (
|
||||
<TerritoryLevel
|
||||
key={`${key}-${path[index - 1]?.id ?? ''}`}
|
||||
index={index}
|
||||
parent={path[index - 1]?.id ?? ''}
|
||||
selected={path[index]}
|
||||
endpoint="/management/territory-options"
|
||||
fieldError={errors[key]}
|
||||
onChange={(value) => {
|
||||
const next = [
|
||||
...path.slice(0, index),
|
||||
...(value ? [value] : []),
|
||||
];
|
||||
setPath(next);
|
||||
setData((previous) => ({
|
||||
...previous,
|
||||
province_id: next[0]?.id ?? '',
|
||||
district_id: next[1]?.id ?? '',
|
||||
admin_post_id: next[2]?.id ?? '',
|
||||
locality_id: next[3]?.id ?? '',
|
||||
}));
|
||||
}}
|
||||
{!profileMode && (
|
||||
<fieldset
|
||||
disabled={busy || readOnly || unavailable}
|
||||
className="space-y-4"
|
||||
>
|
||||
<section aria-label="Localização registada">
|
||||
<TerritoryGeometryPreview
|
||||
territoryId={path.at(-1)?.id}
|
||||
management
|
||||
endpoint={
|
||||
profileMode
|
||||
? '/minhas-oportunidades/territory-geometries'
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</section>
|
||||
<Field
|
||||
label="Categoria"
|
||||
error={errors.opportunity_category}
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={String(data.opportunity_category ?? '')}
|
||||
onChange={(e) =>
|
||||
set('opportunity_category', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{categories.map((c) => (
|
||||
<option key={c}>{c}</option>
|
||||
<p>
|
||||
Hierarquia do cadastro territorial existente.
|
||||
Alterar esta seleção não cria relações com
|
||||
projetos/clusters.
|
||||
</p>
|
||||
{(
|
||||
[
|
||||
'province_id',
|
||||
'district_id',
|
||||
'admin_post_id',
|
||||
'locality_id',
|
||||
] as const
|
||||
).map((key, index) => (
|
||||
<TerritoryLevel
|
||||
key={`${key}-${path[index - 1]?.id ?? ''}`}
|
||||
index={index}
|
||||
parent={path[index - 1]?.id ?? ''}
|
||||
selected={path[index]}
|
||||
endpoint={
|
||||
profileMode
|
||||
? '/minhas-oportunidades/territory-options'
|
||||
: '/management/territory-options'
|
||||
}
|
||||
fieldError={errors[key]}
|
||||
onChange={(value) => {
|
||||
const next = [
|
||||
...path.slice(0, index),
|
||||
...(value ? [value] : []),
|
||||
];
|
||||
setPath(next);
|
||||
setData((previous) => ({
|
||||
...previous,
|
||||
province_id: next[0]?.id ?? '',
|
||||
district_id: next[1]?.id ?? '',
|
||||
admin_post_id: next[2]?.id ?? '',
|
||||
locality_id: next[3]?.id ?? '',
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
{Object.entries({
|
||||
title: 'Título oficial',
|
||||
summary: 'Resumo',
|
||||
description: 'Descrição',
|
||||
promoter_name: 'Promotor',
|
||||
}).map(([key, label]) => (
|
||||
<Field key={key} label={label} error={errors[key]}>
|
||||
{key === 'description' || key === 'summary' ? (
|
||||
<textarea
|
||||
className={control}
|
||||
value={String(data[key] ?? '')}
|
||||
onChange={(e) => set(key, e.target.value)}
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
className={control}
|
||||
value={String(data[key] ?? '')}
|
||||
onChange={(e) => set(key, e.target.value)}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
<Field
|
||||
label="Categoria"
|
||||
error={errors.opportunity_category}
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={String(data.opportunity_category ?? '')}
|
||||
onChange={(e) =>
|
||||
set('opportunity_category', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{categories.map((c) => (
|
||||
<option key={c}>{c}</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
))}
|
||||
<Field label="Sector" error={errors.sector_id}>
|
||||
<select
|
||||
className={control}
|
||||
value={String(data.sector_id ?? '')}
|
||||
onChange={(e) => set('sector_id', e.target.value)}
|
||||
{Object.entries({
|
||||
title: 'Título oficial',
|
||||
summary: 'Resumo',
|
||||
description: 'Descrição',
|
||||
promoter_name: 'Promotor',
|
||||
}).map(([key, label]) => (
|
||||
<Field key={key} label={label} error={errors[key]}>
|
||||
{key === 'description' || key === 'summary' ? (
|
||||
<textarea
|
||||
className={control}
|
||||
value={String(data[key] ?? '')}
|
||||
onChange={(e) =>
|
||||
set(key, e.target.value)
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
className={control}
|
||||
value={String(data[key] ?? '')}
|
||||
onChange={(e) =>
|
||||
set(key, e.target.value)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</Field>
|
||||
))}
|
||||
<Field label="Sector" error={errors.sector_id}>
|
||||
<select
|
||||
className={control}
|
||||
value={String(data.sector_id ?? '')}
|
||||
onChange={(e) =>
|
||||
set('sector_id', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{sectors.map((s) => (
|
||||
<option key={s.id} value={s.id}>
|
||||
{s.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field
|
||||
label="Tipo de promotor"
|
||||
error={errors.promoter_type}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{sectors.map((s) => (
|
||||
<option key={s.id} value={s.id}>
|
||||
{s.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field
|
||||
label="Tipo de promotor"
|
||||
error={errors.promoter_type}
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={String(data.promoter_type ?? '')}
|
||||
onChange={(e) =>
|
||||
set('promoter_type', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{values.promoter_type &&
|
||||
![
|
||||
<select
|
||||
className={control}
|
||||
value={String(data.promoter_type ?? '')}
|
||||
onChange={(e) =>
|
||||
set('promoter_type', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{Boolean(values.promoter_type) &&
|
||||
![
|
||||
'public',
|
||||
'private',
|
||||
'ppp',
|
||||
'cooperative',
|
||||
'association',
|
||||
'community',
|
||||
'other',
|
||||
].includes(
|
||||
String(values.promoter_type),
|
||||
) && (
|
||||
<option
|
||||
value={String(values.promoter_type)}
|
||||
>
|
||||
{String(values.promoter_type)}{' '}
|
||||
(valor existente)
|
||||
</option>
|
||||
)}
|
||||
{[
|
||||
'public',
|
||||
'private',
|
||||
'ppp',
|
||||
@@ -297,174 +456,170 @@ export default function OpportunityDraft({
|
||||
'association',
|
||||
'community',
|
||||
'other',
|
||||
].includes(String(values.promoter_type)) && (
|
||||
<option
|
||||
value={String(values.promoter_type)}
|
||||
>
|
||||
{String(values.promoter_type)} (valor
|
||||
existente)
|
||||
</option>
|
||||
)}
|
||||
{[
|
||||
'public',
|
||||
'private',
|
||||
'ppp',
|
||||
'cooperative',
|
||||
'association',
|
||||
'community',
|
||||
'other',
|
||||
].map((c) => (
|
||||
<option key={c}>{c}</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field
|
||||
label="Etapa de maturidade"
|
||||
error={errors.maturity_stage ?? errors.maturity_level}
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={
|
||||
data.maturity_catalogue_version ===
|
||||
maturityCatalogue.version
|
||||
? String(data.maturity_stage ?? '')
|
||||
: data.maturity_level
|
||||
? `legacy:${data.maturity_level}`
|
||||
: ''
|
||||
].map((c) => (
|
||||
<option key={c}>{c}</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field
|
||||
label="Etapa de maturidade"
|
||||
error={
|
||||
errors.maturity_stage ?? errors.maturity_level
|
||||
}
|
||||
onChange={(e) => {
|
||||
const stage = e.target.value;
|
||||
if (stage.startsWith('legacy:')) {
|
||||
setData((d) => ({
|
||||
...d,
|
||||
maturity_catalogue_version:
|
||||
maturityCatalogue.legacyVersion,
|
||||
maturity_level: Number(stage.slice(7)),
|
||||
maturity_stage: null,
|
||||
}));
|
||||
} else {
|
||||
setData((d) => ({
|
||||
...d,
|
||||
maturity_catalogue_version:
|
||||
maturityCatalogue.version,
|
||||
maturity_stage: stage || null,
|
||||
maturity_level: stage
|
||||
? Object.keys(
|
||||
maturityCatalogue.stages,
|
||||
).indexOf(stage) + 1
|
||||
: null,
|
||||
}));
|
||||
}
|
||||
}}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{values.maturity_level &&
|
||||
values.maturity_catalogue_version !==
|
||||
maturityCatalogue.version && (
|
||||
<option
|
||||
value={`legacy:${values.maturity_level}`}
|
||||
>
|
||||
{
|
||||
maturityCatalogue.legacyLabels[
|
||||
String(values.maturity_level)
|
||||
]
|
||||
}{' '}
|
||||
(catálogo histórico; sem conversão)
|
||||
</option>
|
||||
<select
|
||||
className={control}
|
||||
value={
|
||||
data.maturity_catalogue_version ===
|
||||
maturityCatalogue.version
|
||||
? String(data.maturity_stage ?? '')
|
||||
: data.maturity_level
|
||||
? `legacy:${data.maturity_level}`
|
||||
: ''
|
||||
}
|
||||
onChange={(e) => {
|
||||
const stage = e.target.value;
|
||||
if (stage.startsWith('legacy:')) {
|
||||
setData((d) => ({
|
||||
...d,
|
||||
maturity_catalogue_version:
|
||||
maturityCatalogue.legacyVersion,
|
||||
maturity_level: Number(
|
||||
stage.slice(7),
|
||||
),
|
||||
maturity_stage: null,
|
||||
}));
|
||||
} else {
|
||||
setData((d) => ({
|
||||
...d,
|
||||
maturity_catalogue_version:
|
||||
maturityCatalogue.version,
|
||||
maturity_stage: stage || null,
|
||||
maturity_level: stage
|
||||
? Object.keys(
|
||||
maturityCatalogue.stages,
|
||||
).indexOf(stage) + 1
|
||||
: null,
|
||||
}));
|
||||
}
|
||||
}}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{Boolean(values.maturity_level) &&
|
||||
values.maturity_catalogue_version !==
|
||||
maturityCatalogue.version && (
|
||||
<option
|
||||
value={`legacy:${values.maturity_level}`}
|
||||
>
|
||||
{
|
||||
maturityCatalogue.legacyLabels[
|
||||
String(
|
||||
values.maturity_level,
|
||||
)
|
||||
]
|
||||
}{' '}
|
||||
(catálogo histórico; sem conversão)
|
||||
</option>
|
||||
)}
|
||||
{Object.entries(maturityCatalogue.stages).map(
|
||||
([code, label], index) => (
|
||||
<option key={code} value={code}>
|
||||
{index + 1}. {label}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
{Object.entries(maturityCatalogue.stages).map(
|
||||
([code, label], index) => (
|
||||
<option key={code} value={code}>
|
||||
{index + 1}. {label}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
<p>
|
||||
O catálogo de oito etapas é guardado com a sua
|
||||
versão. Os valores históricos conservam o
|
||||
significado anterior.
|
||||
</p>
|
||||
</Field>
|
||||
<Field
|
||||
label="Modalidade de financiamento existente"
|
||||
error={errors.financing_modality}
|
||||
>
|
||||
<input
|
||||
className={control}
|
||||
value={String(data.financing_modality ?? '')}
|
||||
onChange={(e) =>
|
||||
set('financing_modality', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field
|
||||
label="Impacto esperado"
|
||||
error={errors.expected_impact}
|
||||
>
|
||||
<textarea
|
||||
className={control}
|
||||
value={String(data.expected_impact ?? '')}
|
||||
onChange={(e) =>
|
||||
set('expected_impact', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
{(data.opportunity_category === 'investment_project' ||
|
||||
(!data.opportunity_category &&
|
||||
data.estimated_investment_amount != null)) && (
|
||||
<>
|
||||
<Field
|
||||
label="Investimento estimado"
|
||||
error={errors.estimated_investment_amount}
|
||||
>
|
||||
<input
|
||||
className={control}
|
||||
value={String(
|
||||
data.estimated_investment_amount ?? '',
|
||||
)}
|
||||
onChange={(e) =>
|
||||
set(
|
||||
'estimated_investment_amount',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field
|
||||
label="Moeda"
|
||||
error={errors.estimated_investment_currency}
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={String(
|
||||
data.estimated_investment_currency ??
|
||||
'',
|
||||
)}
|
||||
onChange={(e) =>
|
||||
set(
|
||||
'estimated_investment_currency',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{['MZN', 'USD', 'EUR', 'ZAR'].map((c) => (
|
||||
<option key={c}>{c}</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
</>
|
||||
)}
|
||||
{data.opportunity_category &&
|
||||
data.opportunity_category !== 'investment_project' && (
|
||||
</select>
|
||||
<p>
|
||||
O módulo especializado desta categoria permanece
|
||||
pendente. Pode guardar a identificação
|
||||
incompleta; não será submetida nem publicada.
|
||||
O catálogo de oito etapas é guardado com a sua
|
||||
versão. Os valores históricos conservam o
|
||||
significado anterior.
|
||||
</p>
|
||||
</Field>
|
||||
<Field
|
||||
label="Modalidade de financiamento existente"
|
||||
error={errors.financing_modality}
|
||||
>
|
||||
<input
|
||||
className={control}
|
||||
value={String(data.financing_modality ?? '')}
|
||||
onChange={(e) =>
|
||||
set('financing_modality', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field
|
||||
label="Impacto esperado"
|
||||
error={errors.expected_impact}
|
||||
>
|
||||
<textarea
|
||||
className={control}
|
||||
value={String(data.expected_impact ?? '')}
|
||||
onChange={(e) =>
|
||||
set('expected_impact', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
{(data.opportunity_category === 'investment_project' ||
|
||||
(!data.opportunity_category &&
|
||||
data.estimated_investment_amount != null)) && (
|
||||
<>
|
||||
<Field
|
||||
label="Investimento estimado"
|
||||
error={errors.estimated_investment_amount}
|
||||
>
|
||||
<input
|
||||
className={control}
|
||||
value={String(
|
||||
data.estimated_investment_amount ??
|
||||
'',
|
||||
)}
|
||||
onChange={(e) =>
|
||||
set(
|
||||
'estimated_investment_amount',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field
|
||||
label="Moeda"
|
||||
error={errors.estimated_investment_currency}
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={String(
|
||||
data.estimated_investment_currency ??
|
||||
'',
|
||||
)}
|
||||
onChange={(e) =>
|
||||
set(
|
||||
'estimated_investment_currency',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{['MZN', 'USD', 'EUR', 'ZAR'].map(
|
||||
(c) => (
|
||||
<option key={c}>{c}</option>
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
</Field>
|
||||
</>
|
||||
)}
|
||||
</fieldset>
|
||||
{Boolean(data.opportunity_category) &&
|
||||
data.opportunity_category !==
|
||||
'investment_project' && (
|
||||
<p>
|
||||
Guarde o rascunho incompleto e complete o
|
||||
contrato aplicável abaixo. Submissão e
|
||||
publicação exigem os documentos e as
|
||||
revisões desta categoria.
|
||||
</p>
|
||||
)}
|
||||
</fieldset>
|
||||
)}
|
||||
{!readOnly && (
|
||||
<>
|
||||
<Field
|
||||
@@ -484,7 +639,7 @@ export default function OpportunityDraft({
|
||||
Guardar rascunho
|
||||
</button>
|
||||
)}
|
||||
{record && (
|
||||
{record && !profileMode && (
|
||||
<>
|
||||
<label className="block">
|
||||
<input
|
||||
@@ -497,7 +652,7 @@ export default function OpportunityDraft({
|
||||
Confirmo a{' '}
|
||||
{unavailable
|
||||
? 'restauração'
|
||||
: 'exclusão lógica/arquivo'}
|
||||
: 'operação indicada, preservando o registo'}
|
||||
, preservando histórico e relações
|
||||
</label>
|
||||
<button
|
||||
@@ -506,16 +661,32 @@ export default function OpportunityDraft({
|
||||
disabled={busy || !confirm}
|
||||
onClick={() =>
|
||||
void send(
|
||||
unavailable ? 'restore' : 'delete',
|
||||
unavailable
|
||||
? 'restore'
|
||||
: archiveAvailable
|
||||
? 'archive'
|
||||
: 'delete',
|
||||
)
|
||||
}
|
||||
>
|
||||
{unavailable
|
||||
? 'Restaurar'
|
||||
: closedVersion
|
||||
: archiveAvailable || closedVersion
|
||||
? 'Arquivar'
|
||||
: 'Excluir rascunho'}
|
||||
</button>
|
||||
{archiveAvailable &&
|
||||
!unavailable &&
|
||||
!closedVersion && (
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy || !confirm}
|
||||
onClick={() => void send('delete')}
|
||||
>
|
||||
Excluir rascunho
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
@@ -525,7 +696,7 @@ export default function OpportunityDraft({
|
||||
<Link
|
||||
href={
|
||||
resourcesInstalled
|
||||
? `/management/opportunities/${record.id}/resources`
|
||||
? `${basePath}/${record.id}/resources`
|
||||
: '/management/opportunity-resources-install'
|
||||
}
|
||||
>
|
||||
@@ -534,11 +705,131 @@ export default function OpportunityDraft({
|
||||
: 'Plano de ativação de imagens, documentos e localizações'}
|
||||
</Link>
|
||||
)}
|
||||
{record && (
|
||||
<Link href={`/management/opportunities/${record.id}/context`}>
|
||||
{record && !profileMode && (
|
||||
<Link href={`${basePath}/${record.id}/context`}>
|
||||
Consultar projetos, clusters e relações existentes
|
||||
</Link>
|
||||
)}
|
||||
{profileMode && canonicalOptions && (
|
||||
<section>
|
||||
<OpportunityCanonicalFields
|
||||
value={
|
||||
(data.canonical ?? {}) as Record<string, unknown>
|
||||
}
|
||||
onChange={(v) =>
|
||||
setData((d) => ({ ...d, canonical: v }))
|
||||
}
|
||||
options={canonicalOptions}
|
||||
errors={errors}
|
||||
category={String(data.opportunity_category ?? '')}
|
||||
organization={
|
||||
(data.organization_id ?? null) as string | null
|
||||
}
|
||||
actorId={auth.user.id}
|
||||
sectors={sectors}
|
||||
disabled={busy || readOnly || unavailable}
|
||||
/>
|
||||
{!readOnly && !unavailable && (
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={() => void send('save')}
|
||||
>
|
||||
Guardar contrato no rascunho
|
||||
</button>
|
||||
)}
|
||||
{Object.entries(errors)
|
||||
.filter(([key]) => key.startsWith('canonical'))
|
||||
.map(([key, msg]) => (
|
||||
<p key={key} role="alert">
|
||||
{key}: {msg}
|
||||
</p>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
{profileMode && record && profileActions.includes('publish') && (
|
||||
<section className="rounded border p-3">
|
||||
<h2>Pré-visualização da publicação</h2>
|
||||
<p>
|
||||
Âmbito solicitado:{' '}
|
||||
{(data.canonical as Record<string, unknown> | undefined)
|
||||
?.visibility === 'public'
|
||||
? 'Catálogo público, após ação do Publicador'
|
||||
: 'Acesso restrito aos perfis e à organização autorizados'}
|
||||
</p>
|
||||
<h3>{publicationPreview?.title}</h3>
|
||||
<p>{publicationPreview?.summary}</p>
|
||||
<p>{publicationPreview?.description}</p>
|
||||
<p>
|
||||
A ficha partilha apenas título, resumo, proposta, sector
|
||||
e território. Contactos, avaliações, evidências e
|
||||
originais conservam o acesso restrito.
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
{profileMode && record && etag && (
|
||||
<OpportunityProfileActions
|
||||
participants={workflowParticipants?.validators}
|
||||
publishers={workflowParticipants?.publishers}
|
||||
opinions={Object.values(
|
||||
(profileContext?.opinions ?? {}) as Record<
|
||||
string,
|
||||
{
|
||||
id: string;
|
||||
gate: string;
|
||||
recipient_id: number;
|
||||
status: string;
|
||||
}
|
||||
>,
|
||||
)}
|
||||
onErrors={setErrors}
|
||||
id={record.id}
|
||||
etag={token ?? etag}
|
||||
actions={profileActions}
|
||||
publicationVisibility={String(
|
||||
(data.canonical as Record<string, unknown> | undefined)
|
||||
?.visibility ?? 'internal',
|
||||
)}
|
||||
gates={canonicalOptions?.gates ?? []}
|
||||
documents={(
|
||||
canonicalOptions?.resources.documents ?? []
|
||||
).map((d) => ({
|
||||
id: d.id,
|
||||
title: d.payload.title ?? d.file?.file_name ?? d.id,
|
||||
}))}
|
||||
approvalHash={
|
||||
(
|
||||
profileContext?.approval as
|
||||
| { hash?: string }
|
||||
| undefined
|
||||
)?.hash
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{profileMode && record && (
|
||||
<section className="space-y-2 rounded border p-3">
|
||||
<h2>
|
||||
Acompanhamento interno —{' '}
|
||||
{(workflowState ?? record.status) === 'published'
|
||||
? 'Versão disponibilizada'
|
||||
: (states[workflowState ?? record.status] ??
|
||||
workflowState ??
|
||||
record.status)}
|
||||
</h2>
|
||||
<p>
|
||||
SLA: sem política/prazo aprovado; as tarefas podem ser
|
||||
preparadas em paralelo.
|
||||
</p>
|
||||
{workflowTasks.map((t) => (
|
||||
<p key={t.id}>
|
||||
{t.title} — {t.status}; responsável:{' '}
|
||||
{t.assignee_user_id ?? 'por atribuir'}; prazo:{' '}
|
||||
{t.due_at ?? 'não definido'}
|
||||
</p>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
<section aria-label="Histórico de gestão">
|
||||
<h2>Histórico</h2>
|
||||
{history.length ? (
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import { Link, router, usePage } from '@inertiajs/react';
|
||||
import TerritoryGeometryPreview from '@/components/territory-geometry-preview';
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
@@ -144,9 +144,10 @@ export default function OpportunityResources({
|
||||
assessment: string[];
|
||||
imageProcessingAvailable: boolean;
|
||||
}) {
|
||||
const { basePath = '/management/opportunities', readOnly = false, countries = [] } = usePage<{basePath?: string; readOnly?: boolean; countries?: {code:string;name:string}[]}>().props;
|
||||
const [kind, setKind] = useState<Kind>('locations');
|
||||
const [editing, setEditing] = useState<Resource | null>(null);
|
||||
const [payload, setPayload] = useState<Payload>({});
|
||||
const [payload, setPayload] = useState<Payload>({country_code:'MZ'});
|
||||
const [path, setPath] = useState<TerritoryOption[]>([]);
|
||||
const [geometry, setGeometry] = useState('');
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
@@ -161,7 +162,7 @@ export default function OpportunityResources({
|
||||
function select(nextKind: Kind, record: Resource | null = null) {
|
||||
setKind(nextKind);
|
||||
setEditing(record);
|
||||
setPayload(record?.payload ?? {});
|
||||
setPayload(record?.payload ?? (nextKind === 'locations' ? {country_code:'MZ'} : {}));
|
||||
setPath(record?.territoryPath ?? []);
|
||||
setGeometry(
|
||||
record?.payload.geometry
|
||||
@@ -174,7 +175,7 @@ export default function OpportunityResources({
|
||||
setErrors({});
|
||||
}
|
||||
async function execute(action: 'save' | 'delete' | 'restore' | 'prepare') {
|
||||
if (busy) return;
|
||||
if (busy || readOnly) return;
|
||||
setBusy(true);
|
||||
setErrors({});
|
||||
setMessage('');
|
||||
@@ -204,7 +205,7 @@ export default function OpportunityResources({
|
||||
form.set('action', action);
|
||||
form.set('confirm', confirm ? '1' : '0');
|
||||
}
|
||||
const url = `/management/opportunities/${opportunity.id}/resources/${kind}${editing ? `/${editing.id}` : ''}${action === 'save' ? '' : action === 'prepare' ? '/prepare' : '/lifecycle'}`;
|
||||
const url = `${basePath}/${opportunity.id}/resources/${kind}${editing ? `/${editing.id}` : ''}${action === 'save' ? '' : action === 'prepare' ? '/prepare' : '/lifecycle'}`;
|
||||
const csrf =
|
||||
document.cookie
|
||||
.split('; ')
|
||||
@@ -266,7 +267,7 @@ export default function OpportunityResources({
|
||||
!!opportunity.deleted_at || opportunity.status === 'archived';
|
||||
return (
|
||||
<Management title="Imagens, documentos e localizações">
|
||||
<Link href={`/management/opportunities/${opportunity.id}/edit`}>
|
||||
<Link href={`${basePath}/${opportunity.id}/edit`}>
|
||||
Regressar ao rascunho #{opportunity.id}
|
||||
</Link>
|
||||
<p>
|
||||
@@ -327,7 +328,7 @@ export default function OpportunityResources({
|
||||
<button
|
||||
className={button}
|
||||
key={k}
|
||||
disabled={busy}
|
||||
disabled={busy || readOnly}
|
||||
onClick={() => select(k)}
|
||||
>
|
||||
{k === 'locations'
|
||||
@@ -388,7 +389,7 @@ export default function OpportunityResources({
|
||||
{r.file?.malware_scan_status === 'clean' &&
|
||||
!r.deleted_at && (
|
||||
<a
|
||||
href={`/management/opportunities/${opportunity.id}/resources/${kind}/${r.id}/download`}
|
||||
href={`${basePath}/${opportunity.id}/resources/${kind}/${r.id}/download`}
|
||||
>
|
||||
Consultar original autorizado
|
||||
</a>
|
||||
@@ -410,9 +411,12 @@ export default function OpportunityResources({
|
||||
</h2>
|
||||
{kind === 'locations' && (
|
||||
<div>
|
||||
<Field label="País da localização" error={errors.country_code}><select className={control} disabled={readOnly} value={String(payload.country_code ?? '')} onChange={e=>set('country_code',e.target.value)}><option value="">Por indicar</option>{countries.map(c=><option key={c.code} value={c.code}>{c.name}</option>)}</select></Field>
|
||||
{payload.country_code !== 'MZ' && <p>A hierarquia abaixo corresponde a Moçambique. Uma localização noutro país requer o seu próprio cadastro; não use territórios moçambicanos para a representar.</p>}
|
||||
<TerritoryGeometryPreview
|
||||
territoryId={path.at(-1)?.id}
|
||||
management
|
||||
endpoint={basePath === '/minhas-oportunidades' ? '/minhas-oportunidades/territory-geometries' : undefined}
|
||||
/>
|
||||
{[0, 1, 2, 3].map((index) => (
|
||||
<TerritoryLevel
|
||||
@@ -420,6 +424,7 @@ export default function OpportunityResources({
|
||||
index={index}
|
||||
parent={path[index - 1]?.id ?? ''}
|
||||
selected={path[index]}
|
||||
endpoint={basePath === '/minhas-oportunidades' ? '/minhas-oportunidades/territory-options' : '/management/territory-options'}
|
||||
onChange={(value) =>
|
||||
setPath((previous) =>
|
||||
value
|
||||
@@ -638,7 +643,7 @@ export default function OpportunityResources({
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={
|
||||
busy || unavailable || !imageProcessingAvailable
|
||||
busy || readOnly || unavailable || !imageProcessingAvailable
|
||||
}
|
||||
onClick={() => void execute('prepare')}
|
||||
>
|
||||
@@ -647,7 +652,7 @@ export default function OpportunityResources({
|
||||
)}
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || unavailable || !!editing?.deleted_at}
|
||||
disabled={busy || readOnly || unavailable || !!editing?.deleted_at}
|
||||
>
|
||||
Guardar recurso
|
||||
</button>
|
||||
@@ -655,7 +660,7 @@ export default function OpportunityResources({
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy || unavailable}
|
||||
disabled={busy || readOnly || unavailable}
|
||||
onClick={() =>
|
||||
void execute(
|
||||
editing.deleted_at ? 'restore' : 'delete',
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import ProfileNavigation from '@/components/profile-navigation';
|
||||
import { Head, Link, usePage } from '@inertiajs/react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { cloneElement, isValidElement, useId } from 'react';
|
||||
@@ -46,7 +47,9 @@ export function Management({
|
||||
title: string;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const { flash, educationEnabled, aiEnabled } = usePage<{
|
||||
const { flash, educationEnabled, aiEnabled, auth, basePath } = usePage<{
|
||||
auth?: {canManagePortal?: boolean};
|
||||
basePath?: string;
|
||||
flash?: { success?: string };
|
||||
educationEnabled?: boolean;
|
||||
aiEnabled?: boolean;
|
||||
@@ -54,7 +57,7 @@ export function Management({
|
||||
return (
|
||||
<main className="space-y-6 p-4 md:p-8">
|
||||
<Head title={title} />
|
||||
<nav
|
||||
{auth?.canManagePortal && basePath !== '/minhas-oportunidades' ? <nav
|
||||
className="flex flex-wrap gap-4 text-sm underline"
|
||||
aria-label="Gestão do portal"
|
||||
>
|
||||
@@ -102,7 +105,7 @@ export function Management({
|
||||
Referências e formulários
|
||||
</Link>
|
||||
<a href="/">Portal público</a>
|
||||
</nav>
|
||||
</nav> : <ProfileNavigation />}
|
||||
<h1 className="text-2xl font-semibold break-words">{title}</h1>
|
||||
{flash?.success && (
|
||||
<p
|
||||
|
||||
@@ -10,12 +10,14 @@ type Plan = {
|
||||
hash: string;
|
||||
scan_ready: boolean;
|
||||
source_sha256: string;
|
||||
correspondence_version: string;
|
||||
rows: {
|
||||
external_id: string;
|
||||
name: string;
|
||||
parent_name: string | null;
|
||||
location_id: string | null;
|
||||
status: string;
|
||||
correspondence: { target_name: string; target_source_code: string; basis: string } | null;
|
||||
}[];
|
||||
};
|
||||
export default function GeometryImport({ plan }: { plan: Plan }) {
|
||||
@@ -73,7 +75,8 @@ export default function GeometryImport({ plan }: { plan: Plan }) {
|
||||
<Management title="Importação cartográfica">
|
||||
<p>
|
||||
Exemplar INE de 07/06/2019 aceite. Correspondência exata de nome
|
||||
e pai; sem alterações de classificações territoriais,
|
||||
e pai, ou correspondência explícita fundamentada abaixo;
|
||||
sem alterações de classificações territoriais,
|
||||
disponibilidade fundiária ou cálculos.
|
||||
</p>
|
||||
<Field label="Nível">
|
||||
@@ -105,6 +108,12 @@ export default function GeometryImport({ plan }: { plan: Plan }) {
|
||||
<p className="break-all">
|
||||
SHA-256 do original: {plan.source_sha256}
|
||||
</p>
|
||||
<p>Versão das correspondências: {plan.correspondence_version}.</p>
|
||||
<button className={button} disabled={busy} onClick={() => {
|
||||
setApplyKey(crypto.randomUUID());
|
||||
setConfirmed(false);
|
||||
router.reload({ only: ["plan"] });
|
||||
}}>Atualizar pré-visualização</button>
|
||||
<div className="overflow-x-auto">
|
||||
<table>
|
||||
<thead>
|
||||
@@ -113,6 +122,7 @@ export default function GeometryImport({ plan }: { plan: Plan }) {
|
||||
<th>Nome</th>
|
||||
<th>Pai</th>
|
||||
<th>Correspondência</th>
|
||||
<th>Fundamento</th>
|
||||
<th>Ação prevista</th>
|
||||
</tr>
|
||||
</thead>
|
||||
@@ -123,6 +133,10 @@ export default function GeometryImport({ plan }: { plan: Plan }) {
|
||||
<td>{r.name}</td>
|
||||
<td>{r.parent_name ?? "—"}</td>
|
||||
<td>{r.location_id ?? "Pendente"}</td>
|
||||
<td>{r.correspondence ? <>
|
||||
{r.correspondence.target_name} (código {r.correspondence.target_source_code})
|
||||
<p>{r.correspondence.basis}</p>
|
||||
</> : "Nome único sob o pai correspondido"}</td>
|
||||
<td>{r.status}</td>
|
||||
</tr>
|
||||
))}
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import { Head, Link, router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import ProfileNavigation from '@/components/profile-navigation';
|
||||
import { profileJson } from '@/lib/profile-json';
|
||||
import { button, control } from '@/pages/management/shared';
|
||||
|
||||
type Entry = {id: string; user_id: number; status: string; version: number; opportunity_types: string; document_ids: string; reason: string};
|
||||
type SecurityEntry = {id: string; kind: string; requested_by: number; subject_user_id: number; scope: string; reason: string; approved_by: number | null; consumed_at: string | null; expires_at: string};
|
||||
type Pair = {first_user_id: number; second_user_id: number; version: number};
|
||||
function Grant({types, organizations}: {types: string[]; organizations: {id: string; name: string}[]}) {
|
||||
const [user, setUser] = useState(''); const [role, setRole] = useState('validator'); const [organization, setOrganization] = useState('');
|
||||
const [selected, setSelected] = useState<string[]>([]); const [responsibilities, setResponsibilities] = useState<string[]>([]);
|
||||
const [reason, setReason] = useState(''); const [expires, setExpires] = useState(''); const [message, setMessage] = useState(''); const [busy, setBusy] = useState(false);
|
||||
const available = role === 'validator' ? ['validation_coordinator','technical_reviewer','legal_reviewer','appeal_reviewer'] : role === 'publisher' ? ['publication_coordinator'] : [];
|
||||
const toggle = (values: string[], value: string) => values.includes(value) ? values.filter(v => v !== value) : [...values,value];
|
||||
async function send() { setBusy(true); try { await profileJson('/perfis/atribuicoes', {user_id: Number(user), role, organization_id: organization || null, opportunity_types: selected, responsibilities, expires_at: expires || null, reason}); setMessage('Atribuição registada.'); router.reload(); } catch(error) {setMessage(error instanceof Error ? error.message : 'Resposta indisponível.');} finally {setBusy(false);} }
|
||||
return <section className="space-y-3"><h2 className="text-xl font-semibold">Atribuir papel operacional</h2><p>Promotor exige pedido documental independente. Superutilizador é gerido pela dupla, sem terceira atribuição.</p>
|
||||
<form className="max-w-2xl space-y-3" onSubmit={e => {e.preventDefault(); void send();}}>
|
||||
<label className="block">ID da conta existente<input className={control} type="number" min={1} required value={user} onChange={e => setUser(e.target.value)} /></label>
|
||||
<label className="block">Papel<select className={control} value={role} onChange={e => {setRole(e.target.value); setResponsibilities([]);}}>{['validator','publisher','auditor'].map(v => <option key={v}>{v}</option>)}</select></label>
|
||||
<label className="block">Âmbito organizacional<select className={control} value={organization} onChange={e => setOrganization(e.target.value)}><option value="">Todos os âmbitos para os tipos selecionados</option>{organizations.map(o => <option key={o.id} value={o.id}>{o.name}</option>)}</select></label>
|
||||
<fieldset><legend>Tipos autorizados</legend>{types.map(v => <label className="block" key={v}><input type="checkbox" checked={selected.includes(v)} onChange={() => setSelected(toggle(selected,v))} /> {v}</label>)}</fieldset>
|
||||
<fieldset><legend>Responsabilidades adicionais</legend>{available.map(v => <label className="block" key={v}><input type="checkbox" checked={responsibilities.includes(v)} onChange={() => setResponsibilities(toggle(responsibilities,v))} /> {v}</label>)}<p>Atribuir a responsabilidade não conclui filas, recursos ou escalamentos ainda em desenvolvimento.</p></fieldset>
|
||||
<label className="block">Validade opcional<input className={control} type="datetime-local" value={expires} onChange={e => setExpires(e.target.value)} /></label>
|
||||
<label className="block">Fundamento<textarea required className={control} minLength={20} maxLength={1000} value={reason} onChange={e => setReason(e.target.value)} /></label>
|
||||
<button className={button} disabled={busy}>Atribuir com auditoria</button><p role="status">{message}</p>
|
||||
</form></section>;
|
||||
}
|
||||
function Security({pair, entries, actorId}: {pair: Pair; entries: SecurityEntry[]; actorId: number}) {
|
||||
const [old, setOld] = useState(String(pair.second_user_id)); const [candidate, setCandidate] = useState(''); const [reason, setReason] = useState('');
|
||||
const [action, setAction] = useState('edit'); const [record, setRecord] = useState(''); const [message, setMessage] = useState(''); const [busy, setBusy] = useState(false);
|
||||
async function send(path: string, data: object) {setBusy(true); try {const result = await profileJson(path, data); setMessage(result.message ?? `Pedido registado: ${result.id}`); router.reload();} catch(error) {setMessage(error instanceof Error ? error.message : 'Resposta indisponível.');} finally {setBusy(false);}}
|
||||
return <section className="space-y-3"><h2 className="text-xl font-semibold">Operações críticas</h2>
|
||||
<label className="block">Fundamento<textarea className={control} minLength={20} maxLength={1000} value={reason} onChange={e => setReason(e.target.value)} /></label>
|
||||
<form className="max-w-2xl space-y-3" onSubmit={e => {e.preventDefault(); void send('/perfis/substituicoes', {old_user_id: Number(old), new_user_id: Number(candidate), reason});}}>
|
||||
<label className="block">Titular a substituir<select className={control} value={old} onChange={e => setOld(e.target.value)}>{[pair.first_user_id,pair.second_user_id].map(v => <option key={v}>{v}</option>)}</select></label>
|
||||
<label className="block">ID do candidato com MFA confirmado<input className={control} type="number" min={1} required value={candidate} onChange={e => setCandidate(e.target.value)} /></label><button className={button} disabled={busy}>Preparar substituição atómica</button>
|
||||
</form>
|
||||
<form className="max-w-2xl space-y-3" onSubmit={e => {e.preventDefault(); void send('/perfis/elevacoes', {action, record_id: record ? Number(record) : null, reason});}}>
|
||||
<label className="block">Operação a elevar<select className={control} value={action} onChange={e => setAction(e.target.value)}>{['create','edit','validate','publish','archive'].map(v => <option key={v}>{v}</option>)}</select></label>
|
||||
<label className="block">ID da oportunidade<input className={control} type="number" min={1} required={action !== 'create'} value={record} onChange={e => setRecord(e.target.value)} /></label><button className={button} disabled={busy}>Pedir elevação temporária</button><p>Exige aprovação do outro titular e papel operacional válido. Não remove impedimentos de autoria ou Auditor.</p>
|
||||
</form>
|
||||
{entries.map(entry => <article key={entry.id} className="space-y-2 border p-3"><p>{entry.kind} — {entry.id} — solicitante {entry.requested_by}, destinatário {entry.subject_user_id}</p><p>{entry.reason}; validade: {entry.expires_at}</p><p>Âmbito: {entry.scope}</p>
|
||||
{!entry.consumed_at && !entry.approved_by && entry.requested_by !== actorId && entry.subject_user_id !== actorId && <button disabled={busy} className={button} onClick={() => void send(`/perfis/seguranca/${entry.id}/aprovar`, {})}>Aprovar independentemente</button>}
|
||||
{!entry.consumed_at && entry.approved_by && entry.requested_by === actorId && entry.kind === 'replacement' && <button disabled={busy} className={button} onClick={() => void send(`/perfis/substituicoes/${entry.id}/aplicar`, {})}>Aplicar substituição aprovada</button>}
|
||||
<p>{entry.consumed_at ? 'Aplicado' : entry.approved_by ? `Aprovado pela conta ${entry.approved_by}` : 'Aguarda aprovação independente'}</p>
|
||||
</article>)}<p role="status">{message}</p></section>;
|
||||
}
|
||||
function Decision({ entry }: {entry: Entry}) {
|
||||
const [reason, setReason] = useState(''); const [verified, setVerified] = useState(false); const [message, setMessage] = useState(''); const [busy, setBusy] = useState(false);
|
||||
const types: string[] = JSON.parse(entry.opportunity_types);
|
||||
const [approved, setApproved] = useState<string[]>([]);
|
||||
async function send(decision: string) {
|
||||
setBusy(true); try { await profileJson(`/perfis/pedidos/${entry.id}/decisao`, {version: entry.version, decision, reason, approved_types: approved,
|
||||
verified_identity: verified, verified_representation: verified, verified_documents: verified}); router.reload(); }
|
||||
catch(error) { setMessage(error instanceof Error ? error.message : 'Resposta indisponível.'); } finally { setBusy(false); }
|
||||
}
|
||||
return <article className="space-y-2 rounded border p-4"><h3>Pedido {entry.id} — conta {entry.user_id} — {entry.status}</h3><p>{entry.reason}</p><p>Comprovativos canónicos: {(JSON.parse(entry.document_ids) as string[]).map(id => <Link className="mr-3 underline" key={id} href={`/perfis/pedidos/${entry.id}/documentos/${id}`} target="_blank">Consultar {id}</Link>)}</p>
|
||||
{entry.status === 'pending' && <><fieldset><legend>Tipos efetivamente aprovados</legend>{types.map(type => <label className="block" key={type}><input type="checkbox" checked={approved.includes(type)} onChange={() => setApproved(v => v.includes(type) ? v.filter(x => x !== type) : [...v,type])} /> {type}</label>)}</fieldset>
|
||||
<label className="block"><input type="checkbox" checked={verified} onChange={e => setVerified(e.target.checked)} /> Conferi identidade, representação e comprovativos; esta declaração fica auditada.</label>
|
||||
<label className="block">Fundamento<textarea className={control} minLength={20} maxLength={1000} value={reason} onChange={e => setReason(e.target.value)} /></label>
|
||||
<button className={button} disabled={busy} onClick={() => void send('approved')}>Aprovar tipos selecionados</button> <button className={button} disabled={busy} onClick={() => void send('rejected')}>Rejeitar pedido</button></>}
|
||||
<p role="status">{message}</p></article>;
|
||||
}
|
||||
export default function Administration({requests, pair, assignments, securityAlerts, actorId, types, organizations, securityRequests}: {actorId: number; types: string[]; organizations: {id: string; name: string}[]; securityRequests: SecurityEntry[]; securityAlerts: {id: string; action: string; actor_user_id: number; occurred_at: string}[]; requests: Entry[]; pair: Pair; assignments: {id: string; user_id: number; role: string; revoked_at: string | null}[]}) {
|
||||
const [message, setMessage] = useState(''); const [reason, setReason] = useState('');
|
||||
async function revoke(id: string) { try { await profileJson(`/perfis/atribuicoes/${id}/revogar`, {reason}); router.reload(); } catch(error) { setMessage(error instanceof Error ? error.message : 'Resposta indisponível.'); } }
|
||||
return <main className="space-y-6 p-6"><Head title="Gestão de perfis" /><ProfileNavigation /><h1 className="text-2xl font-semibold">Gestão de perfis</h1>
|
||||
<p>Dupla de superutilizadores: contas {pair.first_user_id} e {pair.second_user_id}; versão {pair.version}. Substituição exige operação atómica e aprovação independente. Não há remoção isolada.</p>
|
||||
<section aria-label="Alertas de segurança"><h2 className="text-xl font-semibold">Alertas de segurança</h2>{securityAlerts.map(a => <p key={a.id}>{a.occurred_at}: {a.action} — conta {a.actor_user_id}</p>)}</section>
|
||||
<section><h2 className="text-xl font-semibold">Pedidos de Promotor</h2>{requests.map(r => <Decision key={r.id} entry={r} />)}</section>
|
||||
<Grant types={types} organizations={organizations} /><Security pair={pair} entries={securityRequests} actorId={actorId} />
|
||||
<section><h2 className="text-xl font-semibold">Atribuições e revogação</h2><label>Motivo de revogação<textarea className={control} minLength={20} maxLength={1000} value={reason} onChange={e => setReason(e.target.value)} /></label>
|
||||
{assignments.map(a => <p key={a.id}>Conta {a.user_id}: {a.role} — {a.revoked_at ? 'revogado' : 'atribuído'} {!a.revoked_at && <button className={button} onClick={() => void revoke(a.id)}>Revogar e invalidar sessões</button>}</p>)}<p role="status">{message}</p></section>
|
||||
</main>;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { Head, useForm } from '@inertiajs/react';
|
||||
import ProfileNavigation from '@/components/profile-navigation';
|
||||
import { button, control, Pagination, type Paginated } from '@/pages/management/shared';
|
||||
|
||||
type Event = {id: string; action: string; actor_user_id: number | null; entity_type: string; source_system: string; occurred_at: string};
|
||||
export default function Audit({records, filters}: {records: Paginated<Event>; filters: Record<string,string>}) {
|
||||
const form = useForm({actor_id: filters.actor_id ?? '', action: filters.action ?? '', record_id: filters.record_id ?? '', from: filters.from ?? '', until: filters.until ?? ''});
|
||||
const search = new URLSearchParams(Object.entries(form.data).filter(([,value]) => value !== ''));
|
||||
search.set('format', 'json');
|
||||
return <main className="space-y-6 p-6"><Head title="Auditoria de acessos" /><ProfileNavigation /><h1 className="text-2xl font-semibold">Auditoria de acessos e decisões</h1>
|
||||
<p>Consulta somente de leitura. A exportação contém metadados; não inclui credenciais, documentos nem snapshots privados decifrados. Cada exportação apresenta o limite aplicado.</p>
|
||||
<form className="grid gap-3 sm:grid-cols-3" onSubmit={e => {e.preventDefault(); form.get('/perfis/auditoria');}}>
|
||||
{(['actor_id','action','record_id','from','until'] as const).map(field => <label key={field}>{field}<input className={control} type={field === 'from' || field === 'until' ? 'datetime-local' : 'text'} value={form.data[field]} onChange={e => form.setData(field,e.target.value)} /></label>)}
|
||||
<button className={button}>Filtrar</button>
|
||||
</form>
|
||||
{Object.values(form.errors).map(error => <p role="alert" key={error}>{error}</p>)}
|
||||
<a className="underline" href={`/perfis/auditoria?${search}`}>Exportar metadados JSON, até 1.000 eventos</a>
|
||||
<div className="overflow-auto"><table className="w-full"><thead><tr><th>Data UTC</th><th>Conta</th><th>Ação</th><th>Recurso</th><th>Origem</th></tr></thead><tbody>{records.data.map(e => <tr key={e.id}><td>{e.occurred_at}</td><td>{e.actor_user_id}</td><td>{e.action}</td><td>{e.entity_type}</td><td>{e.source_system}</td></tr>)}</tbody></table></div>
|
||||
{!records.data.length && <p>Nenhum evento corresponde aos filtros.</p>}<Pagination page={records} />
|
||||
</main>;
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
import { useState } from 'react';
|
||||
import { Management, button, control } from '@/pages/management/shared';
|
||||
import { profileJson } from '@/lib/profile-json';
|
||||
|
||||
type Plan = {
|
||||
installed: boolean;
|
||||
consistent: boolean;
|
||||
ready: boolean;
|
||||
target: { database: string; port: number };
|
||||
hash: string;
|
||||
dependencies: Record<string, boolean>;
|
||||
changes: string[];
|
||||
backupDate: string | null;
|
||||
rollback: string;
|
||||
bootstrap: {
|
||||
initialized: boolean;
|
||||
holders: number[];
|
||||
version: number | null;
|
||||
rule: string;
|
||||
};
|
||||
};
|
||||
export default function Installation(initial: Plan) {
|
||||
const [plan, setPlan] = useState(initial);
|
||||
const [reason, setReason] = useState('');
|
||||
const [confirmed, setConfirmed] = useState(false);
|
||||
const [first, setFirst] = useState('');
|
||||
const [second, setSecond] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
async function run(bootstrap = false) {
|
||||
setBusy(true);
|
||||
setMessage('');
|
||||
try {
|
||||
const result = await profileJson(
|
||||
'/management/profile-install' + (bootstrap ? '/bootstrap' : ''),
|
||||
{
|
||||
hash: plan.hash,
|
||||
confirm: confirmed,
|
||||
reason,
|
||||
idempotency_key: crypto.randomUUID(),
|
||||
...(bootstrap
|
||||
? {
|
||||
first_user_id: Number(first),
|
||||
second_user_id: Number(second),
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
);
|
||||
setMessage(
|
||||
bootstrap
|
||||
? 'Dupla inicializada. Inicie uma nova sessão como um dos titulares designados; MFA permanece obrigatório.'
|
||||
: result.changed
|
||||
? 'Schema instalado. Perfis ainda não disponibilizados; nenhuma conta ou atribuição criada.'
|
||||
: 'Schema já instalado. Nenhuma reinstalação ou duplicação.',
|
||||
);
|
||||
if (!bootstrap)
|
||||
setPlan(
|
||||
(await profileJson(
|
||||
'/management/profile-install',
|
||||
{},
|
||||
'GET',
|
||||
)) as Plan,
|
||||
);
|
||||
setConfirmed(false);
|
||||
} catch (error) {
|
||||
setMessage(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Resposta indisponível; consulte o estado antes de repetir.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<Management title="Instalação dos perfis — 040000">
|
||||
<p>
|
||||
Base {plan.target.database}:{plan.target.port} ·{' '}
|
||||
{plan.installed ? 'Schema instalado' : 'Schema por instalar'}
|
||||
</p>
|
||||
<p>
|
||||
Preparação:{' '}
|
||||
{plan.ready
|
||||
? 'Provas atuais verificadas'
|
||||
: 'Dependências ou provas por completar'}
|
||||
. Preparação não significa instalação ou disponibilização dos
|
||||
perfis.
|
||||
</p>
|
||||
{!plan.consistent && (
|
||||
<p role="alert">
|
||||
Ledger e schema divergem. Recuperar a consistência antes de
|
||||
instalar.
|
||||
</p>
|
||||
)}
|
||||
<ul>
|
||||
{Object.entries(plan.dependencies).map(([key, ok]) => (
|
||||
<li key={key}>
|
||||
{key}: {ok ? 'presente' : 'pendente'}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<ul>
|
||||
{plan.changes.map((c) => (
|
||||
<li key={c}>{c}</li>
|
||||
))}
|
||||
</ul>
|
||||
<p>Backup/restauro: {plan.backupDate ?? 'Prova atual pendente'}</p>
|
||||
<p>{plan.rollback}</p>
|
||||
<label className="block">
|
||||
Fundamento
|
||||
<textarea
|
||||
className={control}
|
||||
value={reason}
|
||||
minLength={20}
|
||||
maxLength={1000}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={confirmed}
|
||||
onChange={(e) => setConfirmed(e.target.checked)}
|
||||
/>{' '}
|
||||
Confirmo exclusivamente a ação indicada nesta base
|
||||
</label>
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
busy ||
|
||||
!confirmed ||
|
||||
!plan.ready ||
|
||||
plan.installed ||
|
||||
!plan.consistent ||
|
||||
reason.length < 20
|
||||
}
|
||||
onClick={() => void run()}
|
||||
>
|
||||
Instalar schema 040000
|
||||
</button>
|
||||
<section className="space-y-3 rounded border p-4">
|
||||
<h2>Inicialização separada dos dois superutilizadores</h2>
|
||||
<p>{plan.bootstrap.rule}</p>
|
||||
{plan.bootstrap.initialized ? (
|
||||
<p>
|
||||
Dupla já inicializada:{' '}
|
||||
{plan.bootstrap.holders.join(' e ')}; versão{' '}
|
||||
{plan.bootstrap.version}. Use a substituição atómica
|
||||
autorizada; não reinicialize.
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<label className="block">
|
||||
ID da primeira conta explicitamente designada
|
||||
<input
|
||||
className={control}
|
||||
type="number"
|
||||
min={1}
|
||||
value={first}
|
||||
onChange={(e) => setFirst(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
ID da segunda conta explicitamente designada
|
||||
<input
|
||||
className={control}
|
||||
type="number"
|
||||
min={1}
|
||||
value={second}
|
||||
onChange={(e) => setSecond(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
busy ||
|
||||
!confirmed ||
|
||||
!plan.installed ||
|
||||
!first ||
|
||||
!second ||
|
||||
first === second ||
|
||||
reason.length < 20
|
||||
}
|
||||
onClick={() => void run(true)}
|
||||
>
|
||||
Inicializar apenas estas duas contas
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
<p role="status">{message}</p>
|
||||
</Management>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { Head, Link, router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import ProfileNavigation from '@/components/profile-navigation';
|
||||
import { profileJson } from '@/lib/profile-json';
|
||||
import { button, control } from '@/pages/management/shared';
|
||||
|
||||
type RequestEntry = { id: string; status: string; reason: string; decision_reason: string | null; created_at: string };
|
||||
export default function RequestProfile({ requests, types, organizations, documents }: {
|
||||
requests: RequestEntry[]; types: string[]; organizations: {id: string; name: string}[]; documents: {id: string; file_name: string}[];
|
||||
}) {
|
||||
const [representation, setRepresentation] = useState('individual');
|
||||
const [organization, setOrganization] = useState('');
|
||||
const [selected, setSelected] = useState<string[]>([]);
|
||||
const [proofs, setProofs] = useState<string[]>([]);
|
||||
const [reason, setReason] = useState('');
|
||||
const [key, setKey] = useState(() => crypto.randomUUID());
|
||||
const [message, setMessage] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
async function send() {
|
||||
setBusy(true); setMessage('');
|
||||
try {
|
||||
const result = await profileJson('/perfil/promotor', { creation_key: key, representation_type: representation, organization_id: representation === 'individual' ? null : organization,
|
||||
opportunity_types: selected, document_ids: proofs, reason });
|
||||
setMessage(result.message); setKey(crypto.randomUUID()); router.reload();
|
||||
} catch (error) { setMessage(error instanceof Error ? error.message : 'Resposta indisponível. Confira o acompanhamento antes de repetir.'); }
|
||||
finally { setBusy(false); }
|
||||
}
|
||||
const toggle = (values: string[], id: string) => values.includes(id) ? values.filter(v => v !== id) : [...values, id];
|
||||
return <main className="space-y-6 p-6"><Head title="Perfil de Promotor" /><ProfileNavigation />
|
||||
<h1 className="text-2xl font-semibold">Solicitar perfil de Promotor</h1>
|
||||
<p>A aprovação confirma identidade, representação e comprovativos. Só os tipos aprovados ficam disponíveis; o pedido não ativa o perfil.</p>
|
||||
<form className="max-w-2xl space-y-4" onSubmit={e => { e.preventDefault(); void send(); }}>
|
||||
<label className="block">Representação<select className={control} value={representation} onChange={e => setRepresentation(e.target.value)}>
|
||||
{['individual','company','public_entity','association','partner'].map(v => <option key={v}>{v}</option>)}
|
||||
</select></label>
|
||||
{representation !== 'individual' && <label className="block">Organização representada<select required className={control} value={organization} onChange={e => setOrganization(e.target.value)}>
|
||||
<option value="">Selecionar</option>{organizations.map(o => <option key={o.id} value={o.id}>{o.name}</option>)}
|
||||
</select></label>}
|
||||
<fieldset><legend>Tipos pretendidos</legend>{types.map(type => <label key={type} className="block"><input type="checkbox" checked={selected.includes(type)} onChange={() => setSelected(toggle(selected,type))} /> {type}</label>)}</fieldset>
|
||||
<fieldset><legend>Comprovativos próprios analisados</legend>{documents.map(d => <label key={d.id} className="block"><input type="checkbox" checked={proofs.includes(d.id)} onChange={() => setProofs(toggle(proofs,d.id))} /> {d.file_name}</label>)}</fieldset>
|
||||
{!documents.length && <p>Sem comprovativos próprios disponíveis. Pode anexar ao seu dossier no <Link className="underline" href="/balcao-virtual/painel">Balcão</Link>; o ficheiro precisa de análise antimalware concluída.</p>}
|
||||
<label className="block">Fundamentação<textarea required minLength={20} maxLength={1000} className={control} value={reason} onChange={e => setReason(e.target.value)} /></label>
|
||||
<button disabled={busy} className={button}>Submeter pedido de perfil</button>
|
||||
</form>
|
||||
<p role="status" aria-live="polite">{message}</p>
|
||||
<section><h2 className="text-xl font-semibold">Acompanhamento dos meus pedidos</h2>{requests.map(r => <article key={r.id} className="border-b py-3"><p>{r.id} — {r.status}</p><p>{r.decision_reason ?? 'Aguarda revisão independente.'}</p></article>)}{!requests.length && <p>Nenhum pedido recebido.</p>}</section>
|
||||
</main>;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
export type OpportunityManagementAccess = {
|
||||
installed: boolean;
|
||||
manage: { label: string; href: string };
|
||||
create: { label: string; href: string };
|
||||
installationHref: string;
|
||||
};
|
||||
@@ -0,0 +1,9 @@
|
||||
export type ProfileAccess = {
|
||||
contexts: { organization_id: string | null; type: string }[];
|
||||
mine: string | null;
|
||||
create: string | null;
|
||||
request: string;
|
||||
review: string | null;
|
||||
audit?: string | null;
|
||||
administration: string | null;
|
||||
};
|
||||
Reference in New Issue
Block a user