oportunidades 6
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-10-10 21:17:46 +02:00
parent 01405cbf8a
commit 20971d523f
126 changed files with 44362 additions and 3496 deletions
@@ -195,6 +195,7 @@ export default function InteractiveInvestmentMap({
<div
ref={element}
className="relative z-0 h-[460px] w-full rounded"
role="region"
aria-label="Mapa; navegação por setas e teclas mais e menos"
/>
{points === null ? (
@@ -255,7 +256,9 @@ export default function InteractiveInvestmentMap({
<a className="underline" href={area.url}>
{area.title}
</a>{' '}
· Polígono cadastrado, limites oficiais por verificar ·
· {area.purpose === 'administrative_boundary'
? 'Limite administrativo da edição indicada; não representa um local de investimento'
: 'Polígono cadastrado; comparação com limite administrativo pendente'} ·
Fonte: {area.source_reference ?? 'Não indicada'} · Data:{' '}
{area.source_date ?? 'Não documentada'}
</p>
@@ -27,6 +27,8 @@ function resourceTerritory(resource?: Resource) {
}
export type CanonicalOptions = {
version: string;
modularProfiles?: Record<string, string>;
historyVersion?: string | null;
schema: Schema;
definitions: Record<string, Schema>;
contacts: { id: string; full_name: string }[];
@@ -70,6 +72,53 @@ const labels: Record<string, string> = {
real_estate: "Imobiliário",
land_rights: "DUAT e direitos fundiários",
business_transaction: "Negócio",
module_profile_version: "Versão do contrato QA (seleção explícita)",
module_details: "Condições do módulo",
mode: "Percurso: procura, oferta ou modalidade",
conditions_status: "Condições propostas ou compromisso documentado",
object: "Objeto",
representation_document_id: "Documento de representação",
object_document_id: "Documento do objeto/procedimento",
disclosure_authorization_document_id: "Autorização de divulgação da intenção/chamada",
external_decision_document_id: "Ato competente do direito atribuído",
granting_entity: "Entidade concedente declarada",
procedure_regime: "Regime/procedimento declarado",
scope: "Âmbito territorial ou digital",
term_value: "Duração ou prazo",
term_unit: "Unidade da duração",
remuneration_obligations: "Remuneração e obrigações",
participation_conditions: "Condições de participação",
land_required: "Precisa de terra?",
construction_required: "Inclui construção?",
applicable_authorizations: "Autorizações aplicáveis e situação",
instrument: "Instrumento de financiamento",
offered_capacity: "Capacidade oferecida pelo financiador",
eligibility_criteria: "Critérios declarados do financiador",
capacity_document_id: "Evidência da capacidade declarada",
financial_plan_document_id: "Plano financeiro do projeto",
secured_evidence_document_id: "Evidência do financiamento assegurado",
use_of_funds: "Finalidade do financiamento procurado",
disbursement_calendar: "Calendário proposto de desembolso",
repayment_periodicity: "Periodicidade de reembolso",
proposed_rights: "Direitos propostos",
equity_percentage: "Percentagem de capital proposta",
terms: "Condições",
scenario: "Cenário identificado",
source: "Fonte identificada",
terms_date: "Data da fonte/condições",
commitment_document_id: "Documento do compromisso assumido",
acceptance_criteria: "Critérios de aceitação do fornecimento",
quotation_method: "Método de cotação",
total_price: "Preço total (impostos identificados separadamente)",
declared_taxes: "Impostos declarados, sem cálculo implícito",
advance_or_guarantee: "Há adiantamento ou garantia?",
subtype: "Subtipo para classificação funcional",
recipients: "Destinatários",
expected_output: "Resultado esperado",
history_status: "Situação do histórico financeiro",
history_declaration: "Declaração de ausência de exercícios completos",
history_declaration_document_id: "Documento da declaração",
projections: "Projeções identificadas — não são contas realizadas",
transaction_type: "Modalidade",
property_type: "Tipo de imóvel",
construction_status: "Estado construtivo",
@@ -173,12 +222,10 @@ const labels: Record<string, string> = {
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)",
@@ -568,7 +615,7 @@ export default function OpportunityCanonicalFields({
: ["business_sale", "business_partnership", "franchise"].includes(
category,
)
? ["business_transaction"]
? ["module_profile_version", "business_transaction"]
: category === "investment_project"
? [
"opportunity_type",
@@ -594,7 +641,18 @@ export default function OpportunityCanonicalFields({
"risks",
"relations",
]
: ["module_profile_version"];
: ["module_profile_version", "module_details", ...(category === "financing" ? ["total_investment", "investment_breakdown", "secured_financing", "funding_sought"] : [])];
const details = (value.module_details ?? {}) as Data;
const mode = String(details.mode ?? "");
const modularFields = ["mode", "object", "representation_document_id", "object_document_id",
...(category === "concession" ? ["granting_entity", "procedure_regime", "scope", "term_value", "term_unit", "remuneration_obligations", "participation_conditions", "land_required", "construction_required", "applicable_authorizations", "start_date", "end_date", "disclosure_authorization_document_id", "external_decision_document_id", "territorial_right_document_id", "construction_license_document_id"] : []),
...(["financing", "supply"].includes(category) ? ["conditions_status", "terms", "scenario", "source", "terms_date", "commitment_document_id"] : []),
...(category === "financing" ? ["instrument", "disbursement_calendar", "term_value", "term_unit", "repayment_periodicity", "equity_percentage", "proposed_rights",
...(mode === "funding_offer" ? ["offered_capacity", "eligibility_criteria", "capacity_document_id"] : ["use_of_funds", "financial_plan_document_id", "secured_evidence_document_id"])] : []),
...(category === "supply" ? ["quantity", "unit", "destination", "start_date", "end_date", "acceptance_criteria", "quotation_method", "unit_price", "total_price", "declared_taxes", "advance_or_guarantee", ...(mode === "supply_offer" ? ["capacity_document_id"] : [])] : []),
...(category === "other" ? ["subtype", "purpose", "recipients", "expected_output", "risks"] : []),
];
const modes = category === "concession" ? ["intention_call", "awarded_right"] : category === "financing" ? ["seeking_funding", "funding_offer"] : category === "supply" ? ["purchase_request", "supply_offer"] : ["classified_other"];
return (
<fieldset disabled={disabled} className="space-y-4 rounded border p-4">
<legend>Contrato da oportunidade — {category}</legend>
@@ -603,7 +661,23 @@ export default function OpportunityCanonicalFields({
aplicáveis e os recursos guardados. Validação interna não
equivale a autorização externa.
</p>
{options.modularProfiles?.[category] && (
<p className="rounded border border-amber-400 p-3">
Primeira versão QA: {options.modularProfiles[category]}. Selecione-a explicitamente no campo de versão.
Financiamento distingue procura do projeto de oferta do financiador; fornecimento distingue pedido de compra de oferta.
Condições propostas não representam compromisso nem decisão externa.
</p>
)}
{Array.from(new Set([...common, ...specialized])).map((key) => {
if (key === "module_profile_version") {
const current = String(value[key] ?? "");
const version = options.modularProfiles?.[category] ?? (["business_sale", "business_partnership", "franchise"].includes(category) ? options.historyVersion : null);
return <label key={key} className="block">{labels[key]}<select className={control} value={current} onChange={(e) => set(key, e.target.value || null)}>
<option value="">Contrato original / por selecionar</option>
{current && current !== version && <option value={current}>{current} — versão existente preservada</option>}
{version && <option value={version}>{version}</option>}
</select><FieldErrors path={"canonical." + key} errors={errors} /></label>;
}
if (
[
"sector_id",
@@ -731,7 +805,11 @@ export default function OpportunityCanonicalFields({
</fieldset>
);
}
const schema = options.schema.properties?.[key];
let schema = options.schema.properties?.[key];
if (key === "module_details" && schema?.properties) {
schema = { ...schema, properties: Object.fromEntries(Object.entries(schema.properties).filter(([field]) => modularFields.includes(field))) };
schema.properties!.mode = { enum: modes };
}
return schema ? (
<Editor
key={key}
@@ -1,5 +1,7 @@
import type { ProfileAccess } from '@/types/profile-access';
import { Link, usePage } from '@inertiajs/react';
import { Link, router, usePage } from '@inertiajs/react';
import { LogOut } from 'lucide-react';
import { logout } from '@/routes';
import { useEffect, useId, useRef, useState } from 'react';
import type { OpportunityManagementAccess } from '@/types/opportunity-management';
import {
@@ -11,10 +13,14 @@ import {
export function PortalGroupedMenu() {
const { props, url } = usePage<{
auth: { user: unknown; canManagePortal: boolean };
auth: {
user: { name?: string; email?: string } | null;
canManagePortal: boolean;
};
existingBusinessEnabled?: boolean;
educationEnabled?: boolean;
aiEnabled?: boolean;
legacyContentEnabled?: boolean;
portalOperator?: string | null;
profileAccess?: ProfileAccess | null;
opportunityManagement?: OpportunityManagementAccess | null;
@@ -25,6 +31,7 @@ export function PortalGroupedMenu() {
businesses: props.existingBusinessEnabled,
education: props.educationEnabled,
ai: props.aiEnabled,
legacyContent: props.legacyContentEnabled,
opportunityManagement: props.opportunityManagement,
profileAccess: props.profileAccess,
});
@@ -33,6 +40,7 @@ export function PortalGroupedMenu() {
const [open, setOpen] = useState<string | null>(null);
const [branch, setBranch] = useState<string | null>(null);
const [offset, setOffset] = useState(0);
const [loggingOut, setLoggingOut] = useState(false);
const root = useRef<HTMLElement>(null);
const id = useId();
useEffect(() => {
@@ -150,6 +158,33 @@ export function PortalGroupedMenu() {
)}
</p>
</div>
{props.auth?.user && (
<nav
aria-label="Sessão da conta"
className="mb-3 flex flex-wrap items-center justify-between gap-3 rounded-lg bg-slate-50 px-3 py-2"
>
<p className="min-w-0 break-words text-sm text-slate-700 [overflow-wrap:anywhere]">
Sessão: {props.auth.user.name || props.auth.user.email}
</p>
<Link
href={logout()}
as="button"
type="button"
disabled={loggingOut}
onClick={() => {
close();
router.flushAll();
}}
onStart={() => setLoggingOut(true)}
onFinish={() => setLoggingOut(false)}
data-test="portal-logout-button"
className="inline-flex min-h-11 shrink-0 items-center gap-2 rounded-lg border border-slate-400 bg-white px-3 py-2 text-sm font-semibold text-slate-900 hover:bg-slate-100 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-emerald-700 disabled:cursor-wait disabled:opacity-60"
>
<LogOut aria-hidden="true" className="size-4" />
{loggingOut ? 'A terminar sessão…' : 'Terminar sessão'}
</Link>
</nav>
)}
<nav aria-label="Áreas do portal">
<ul className="flex flex-wrap gap-2">
{groups.map((group) => (
@@ -293,7 +293,7 @@ export function SimulationCashflowPlanner({
{projection.vatRefundRecognized}. Estes valores não
foram somados à caixa.
</p>
<div className="overflow-x-auto">
<div className="overflow-x-auto focus-visible:outline-2" tabIndex={0} role="region" aria-label="Tabela do fluxo de caixa">
<table className="min-w-full text-sm">
<caption className="sr-only">
Projecção mensal de tesouraria
@@ -369,7 +369,7 @@ export function SimulationFinancialTools({
efectiva converte a taxa anual para a
periodicidade indicada.
</p>
<div className="max-h-64 overflow-auto">
<div className="max-h-64 overflow-auto focus-visible:outline-2" tabIndex={0} role="region" aria-label="Plano de reembolso indicativo">
<table className="min-w-full text-xs">
<caption className="sr-only">
Plano de reembolso indicativo
+19 -3
View File
@@ -1154,6 +1154,7 @@ export function SimulationForm() {
useEffect(() => {
let cancelled = false;
setReady(false);
void (async () => {
let local: SimulationDraft = {};
const requestedDraftId = new URLSearchParams(
@@ -1229,6 +1230,7 @@ export function SimulationForm() {
}
}
if (payload.data) {
if (cancelled) return;
draftIdRef.current = payload.data.id;
draftEtagRef.current = response.headers.get('ETag');
setDraftVersionNo(payload.data.version_no);
@@ -1475,7 +1477,7 @@ export function SimulationForm() {
]);
async function returnToInvestment() {
if (!contextId || !draftIdRef.current) return;
if (!ready || !contextId || !draftIdRef.current) return;
setContinuityError('');
try {
await saveQueueRef.current;
@@ -1496,8 +1498,14 @@ export function SimulationForm() {
'Não foi possível recuperar o rascunho guardado.',
);
if (
saved.data.economic_snapshot.financial_tools_snapshot !==
draft.financial_tools_snapshot
simulationDraftFingerprint(
restoreSimulationDraft(
saved.data.economic_snapshot,
Array.isArray(saved.data.personal_snapshot)
? {}
: saved.data.personal_snapshot,
),
) !== simulationDraftFingerprint(draft)
)
throw new Error(
'Aguarde a gravação das entradas da ferramenta e tente novamente.',
@@ -1912,6 +1920,7 @@ export function SimulationForm() {
value: string | string[],
label?: string | string[],
) {
if (!ready) return;
setContinueLaterSaved(false);
setServerFieldErrors((previous) => {
const next = { ...previous };
@@ -2035,6 +2044,7 @@ export function SimulationForm() {
}
function navigate(nextStep: number) {
if (!ready) return;
setOpenedTool(null);
if (nextStep > step) {
for (let index = step; index < nextStep; index++) {
@@ -2390,7 +2400,12 @@ export function SimulationForm() {
<section
className="space-y-6 rounded-xl border bg-white p-4 sm:p-6"
aria-labelledby="simulator-step-title"
aria-busy={!ready}
>
{!ready && (
<p role="status">A recuperar o rascunho. Aguarde para editar.</p>
)}
<fieldset disabled={!ready} className="min-w-0 space-y-6">
{canSavePersonalData && draftVersionNo && draftIdRef.current && (
<a
className="inline-block underline"
@@ -4336,6 +4351,7 @@ export function SimulationForm() {
associados à conta. A submissão formal ainda não está disponível
neste formulário.
</p>
</fieldset>
</section>
);
}
+8 -4
View File
@@ -165,6 +165,8 @@ function Sidebar({
return (
<div
data-slot="sidebar"
role="complementary"
aria-label="Navegação da conta"
className={cn(
"bg-sidebar text-sidebar-foreground flex h-full w-(--sidebar-width) flex-col",
className
@@ -179,10 +181,6 @@ function Sidebar({
if (isMobile) {
return (
<Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
<SheetHeader className="sr-only">
<SheetTitle>Sidebar</SheetTitle>
<SheetDescription>Displays the mobile sidebar.</SheetDescription>
</SheetHeader>
<SheetContent
data-sidebar="sidebar"
data-slot="sidebar"
@@ -195,6 +193,10 @@ function Sidebar({
}
side={side}
>
<SheetHeader className="sr-only">
<SheetTitle>Navegação da conta</SheetTitle>
<SheetDescription>Menu móvel do portal.</SheetDescription>
</SheetHeader>
<div className="flex h-full w-full flex-col">{children}</div>
</SheetContent>
</Sheet>
@@ -209,6 +211,8 @@ function Sidebar({
data-variant={variant}
data-side={side}
data-slot="sidebar"
role="complementary"
aria-label="Navegação da conta"
>
{/* This is what handles the sidebar gap on desktop */}
<div
@@ -55,7 +55,7 @@ export function UserMenuContent({ user }: Props) {
data-test="logout-button"
>
<LogOut className="mr-2" />
Log out
Terminar sessão
</Link>
</DropdownMenuItem>
</>
+7 -1
View File
@@ -18,6 +18,8 @@ export const portalLinks = [
['/apoio', 'Apoio ao Investidor'],
] as const;
const names: Record<string, string> = {
'/explorar/agronegocio': 'Explorar agronegócio',
'/agronegocio': 'Artigo de agronegócio',
'/investidor/negocios': 'Os meus negócios',
'/management/negocios': 'Revisão de negócios',
...Object.fromEntries(portalLinks),
@@ -92,13 +94,15 @@ export default function PortalNavigation({
return (
<MenuPlacement.Provider value={true}>
<div className="pb-8 lg:pb-24 [&_button]:scroll-mb-24 [&_input]:scroll-mb-24 [&_select]:scroll-mb-24 [&_textarea]:scroll-mb-24">
{portalShell && <PortalMenu primary />}
<nav aria-label="Atalho para o conteúdo">
<a
href="#portal-content"
className="sr-only focus:not-sr-only focus:block focus:bg-white focus:p-4 focus:text-emerald-900"
>
Saltar para o conteúdo
</a>
</nav>
{portalShell && <PortalMenu primary />}
<nav
aria-label="Caminho de navegação"
className="bg-background text-foreground flex flex-wrap items-center gap-2 border-b px-5 py-3 text-sm"
@@ -127,12 +131,14 @@ export default function PortalNavigation({
{portalShell && <JourneyCompanion />}
{children}
</div>
<aside aria-label="Contacto de apoio ao investidor">
<a
href="/apoio"
className="mx-3 mt-4 block max-w-[calc(100%-1.5rem)] rounded-xl bg-emerald-800 px-5 py-3 text-center text-sm font-semibold text-white shadow-xl focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-emerald-600"
>
Contactar Apoio ao Investidor
</a>
</aside>
</div>
</MenuPlacement.Provider>
);
+68 -8
View File
@@ -13,6 +13,7 @@ export type PortalNavAccess = {
businesses?: boolean;
education?: boolean;
ai?: boolean;
legacyContent?: boolean;
profileAccess?: ProfileAccess | null;
opportunityManagement?: OpportunityManagementAccess | null;
};
@@ -32,6 +33,15 @@ export function portalNavigation(access: PortalNavAccess): PortalNavItem[] {
children: [
link('opportunities', 'Oportunidades', '/oportunidades'),
link('sectors', 'Sectores', '/sectores'),
...(access.legacyContent
? [
link(
'legacy-agronegocio',
'Explorar agronegócio',
'/explorar/agronegocio',
),
]
: []),
{
id: 'structures',
label: 'Carteira e estruturas',
@@ -279,14 +289,64 @@ 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)] : []),
]});
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;
}
+6 -3
View File
@@ -102,7 +102,7 @@ function TopBar({
requestCount: number;
}) {
return (
<header className="sticky top-0 z-30 border-b border-slate-200 bg-white/95 backdrop-blur">
<nav aria-label="Navegação das manifestações" className="sticky top-0 z-30 border-b border-slate-200 bg-white/95 backdrop-blur">
<div className="mx-auto flex max-w-6xl flex-wrap items-center justify-between gap-3 px-5 py-4">
<button
onClick={() => onNavigate('home')}
@@ -129,7 +129,7 @@ function TopBar({
</button>
</div>
</div>
</header>
</nav>
);
}
@@ -863,6 +863,7 @@ function InterestForm({
<Field label="País" error={errors.country}>
<CountrySelect
countries={countries}
label="País do requerente"
value={form.country}
onChange={(value) => update('country', value)}
required
@@ -876,6 +877,7 @@ function InterestForm({
>
<CountrySelect
countries={countries}
label="País de origem declarado desta solicitação"
value={form.declared_origin_country_code ?? ''}
onChange={(value) =>
update('declared_origin_country_code', value)
@@ -1100,7 +1102,7 @@ export default function PortalInvestidorApp({
<div className="min-h-screen bg-slate-50 font-sans text-slate-900">
<TopBar onNavigate={navigate} requestCount={requestCount} />
<PortalMenu />
<main>
{view === 'home' && (
<>
<Hero
@@ -1329,6 +1331,7 @@ export default function PortalInvestidorApp({
/>
)}
</main>
<Footer />
<style>{`
+2 -2
View File
@@ -47,7 +47,7 @@ export default function Dashboard({
} | null;
}) {
return (
<main className="space-y-8 p-4 md:p-8">
<div className="space-y-8 p-4 md:p-8">
<Head title="Painel" />
<h1 className="text-2xl font-semibold">Painel do portal</h1>
<ProfileNavigation />
@@ -305,7 +305,7 @@ export default function Dashboard({
<Link href="/" className="inline-block underline">
Voltar ao portal público
</Link>
</main>
</div>
);
}
Dashboard.layout = { breadcrumbs: [{ title: 'Painel', href: dashboard() }] };
+30
View File
@@ -38,6 +38,7 @@ export default function RequestPage({
payments,
caseVersion,
countries,
toolPrefill,
}: {
request: {
id: string;
@@ -80,6 +81,12 @@ export default function RequestPage({
payments: DeskPayment[];
caseVersion: number;
countries: Country[];
toolPrefill: {
description: string;
draft_id: string;
draft_version: number;
snapshot_sha256: string;
} | null;
events: {
id: string;
action: string;
@@ -142,6 +149,29 @@ export default function RequestPage({
</a>
)}
</section>
{canEdit && toolPrefill && (
<section className={card + ' space-y-3'} aria-label="Descrição guardada no projeto">
<h2 className="text-xl font-bold">Reutilizar dados do projeto</h2>
<p>A descrição está vazia neste pedido. Pode reutilizar o resumo já guardado na ferramenta deste dossier, versão {toolPrefill.draft_version}.</p>
<blockquote className="rounded border p-3 whitespace-pre-wrap">{toolPrefill.description}</blockquote>
<p>Esta ação guarda o rascunho com os dados preenchidos nesta página. Reveja-os antes de submeter.</p>
<button
type="button"
className={button}
disabled={form.processing || !!form.data.payload.description?.trim()}
onClick={() => {
form.transform((data) => ({
...data,
version: request.version,
submit: false,
payload: {...data.payload, description: toolPrefill.description},
tool_prefill: {draft_id:toolPrefill.draft_id, draft_version:toolPrefill.draft_version, snapshot_sha256:toolPrefill.snapshot_sha256},
}));
form.put(`/balcao-virtual/pedidos/${request.id}`, {onSuccess: () => form.setData('payload', {...form.data.payload, description:toolPrefill.description})});
}}
>Reutilizar descrição guardada e guardar rascunho</button>
</section>
)}
<section className={card + ' space-y-3'}>
<h2 className="text-xl font-bold">
Verificações automáticas de preparação
+36 -2
View File
@@ -1,5 +1,6 @@
import { Head, Link, useForm } from '@inertiajs/react';
import { Head, Link, router, useForm } from '@inertiajs/react';
import { useState } from 'react';
import type { LegacyArticle } from '@/pages/portal/legacy';
export type InvestmentContext = {
id: string;
@@ -10,15 +11,31 @@ export type InvestmentContext = {
export default function InvestmentContexts({
contexts,
contentSource,
}: {
contexts: InvestmentContext[];
contentSource?: LegacyArticle;
}) {
const [key] = useState(() => globalThis.crypto.randomUUID());
const form = useForm({ title: '', client_key: key, reuse_consent: false });
const form = useForm({
title: '',
client_key: key,
reuse_consent: false,
content_resource_id: contentSource?.id,
});
return (
<main className="mx-auto max-w-5xl space-y-6 p-4 md:p-8">
<Head title="Os meus investimentos" />
<h1 className="text-2xl font-semibold">Os meus investimentos</h1>
{contentSource && (
<p>
Preparar a partir de{' '}
<Link className="underline" href={contentSource.href}>
{contentSource.title}
</Link>
. A fonte e a versão serão guardadas no dossier escolhido.
</p>
)}
<p>
Prepare cada investimento no seu dossier. Pode trabalhar em
várias etapas em paralelo.
@@ -36,6 +53,23 @@ export default function InvestmentContexts({
Guardado em{' '}
{new Date(item.updated_at).toLocaleString('pt-MZ')}
</p>
{contentSource && (
<button
type="button"
className="mt-3 rounded border p-2"
onClick={() =>
router.post(
`/investimentos/${item.id}/conteudos`,
{
version: item.version,
resource_id: contentSource.id,
},
)
}
>
Continuar neste dossier com o artigo
</button>
)}
</li>
))}
</ul>
+41 -3
View File
@@ -31,6 +31,13 @@ type Path = {
next: { code: string; title: string; href: string; action: string } | null;
tools: Record<string, string | null>;
results: PathResult[];
content_sources: {
resource_id: number;
title: string;
return_href: string;
source_url: string;
metadata_version: number;
}[];
documents: {
id: string;
document_id: string;
@@ -349,12 +356,43 @@ export default function InvestmentPath(path: Path) {
);
}
return (
<main className="mx-auto max-w-6xl space-y-6 p-4 md:p-8">
<main className="mx-auto min-w-0 max-w-6xl space-y-6 p-4 [overflow-wrap:anywhere] [&_label]:min-w-0 [&_select]:min-w-0 [&_select]:max-w-full [&_input]:min-w-0 [&_input]:max-w-full md:p-8">
<Head title={path.case.title} />
<Link className="underline" href="/investimentos">
Os meus investimentos
</Link>
<h1 className="text-2xl font-semibold">{path.case.title}</h1>
{!!path.content_sources?.length && (
<section
className="space-y-2 rounded-xl border p-4"
aria-label="Fontes da ideia"
>
<h2 className="font-semibold">
Conteúdos associados à ideia
</h2>
<ul>
{path.content_sources.map((source) => (
<li
key={`${source.resource_id}-${source.metadata_version}`}
>
<Link
className="underline"
href={`${source.return_href}?context=${path.case.id}`}
>
{source.title}
</Link>{' '}
·{' '}
<Link
className="underline"
href={`/documentos/${source.resource_id}`}
>
Exemplar e origem
</Link>
</li>
))}
</ul>
</section>
)}
{flash?.success && <output>{flash.success}</output>}
{error && <p role="alert">{error}</p>}
<section className="rounded-xl border p-4">
@@ -580,7 +618,7 @@ export default function InvestmentPath(path: Path) {
</h2>
{path.canWrite && (
<form
className="grid gap-3"
className="grid min-w-0 gap-3 [&_label]:min-w-0 [&_select]:min-w-0 [&_select]:max-w-full [&_input]:min-w-0 [&_input]:max-w-full"
onSubmit={(event) => {
event.preventDefault();
task.transform((data) => ({
@@ -630,7 +668,7 @@ export default function InvestmentPath(path: Path) {
<input
required
type="datetime-local"
className="rounded border p-2"
className="w-full min-w-0 rounded border p-2"
value={task.data.due_at}
onChange={(e) =>
task.setData('due_at', e.target.value)
@@ -157,6 +157,7 @@ export default function OpportunityResources({
const [busy, setBusy] = useState(false);
const [message, setMessage] = useState('');
const [errors, setErrors] = useState<Record<string, string>>({});
const foreignCountry = Boolean(payload.country_code && payload.country_code !== 'MZ');
const set = (name: string, value: Payload[string]) =>
setPayload((previous) => ({ ...previous, [name]: value }));
function select(nextKind: Kind, record: Resource | null = null) {
@@ -239,7 +240,7 @@ export default function OpportunityResources({
}
setMessage(data.message);
setEditing(null);
setPayload({});
setPayload(kind === 'locations' ? {country_code:'MZ'} : {});
setPath([]);
setGeometry('');
setFile(null);
@@ -272,8 +273,9 @@ export default function OpportunityResources({
</Link>
<p>
Recursos de preparação. Não alteram automaticamente a ficha
pública ou relações territoriais aceites. ClamD real pendente;
scan simulado nunca verifica ficheiros reais.
pública ou relações territoriais aceites. O estado e o motor
do scan são apresentados por ficheiro e versão; um scan
simulado nunca verifica ficheiros reais.
</p>
<div
id="resource-result"
@@ -300,9 +302,8 @@ export default function OpportunityResources({
<p className="rounded border p-3">
Pode guardar anexos para preparação. Cada ficheiro permanece
sem download ou pré-visualização enquanto o seu scan não
estiver concluído. ClamD pendente não impede guardar
metadados, locais ou rascunhos; testes com scanner simulado
não verificam os seus ficheiros.
estiver concluído. Guardar metadados, locais ou rascunhos
é independente do scan e não publica ficheiros.
</p>
)}
<section>
@@ -411,10 +412,37 @@ 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>}
<Field label="País da localização" error={errors.country_code}>
<select
className={control}
disabled={readOnly}
value={String(payload.country_code ?? '')}
onChange={(event) => {
const country = event.target.value;
set('country_code', country || null);
if (country && country !== 'MZ' && path.length) {
setPath([]);
setMessage('A seleção territorial de Moçambique foi retirada do preenchimento ao mudar de país. Guarde para registar a alteração; a geometria própria foi preservada.');
}
}}
>
<option value="">Por indicar</option>
{countries.map(c=><option key={c.code} value={c.code}>{c.name}</option>)}
</select>
</Field>
{foreignCountry && (
<p>A hierarquia abaixo corresponde a Moçambique e não é aplicável ao país escolhido. Pode guardar uma localização incompleta noutro país sem esta hierarquia.</p>
)}
{foreignCountry && path.length > 0 && (
<p role="alert">
Este registo conserva uma seleção territorial de Moçambique incompatível com o país. Escolha Moçambique ou{' '}
<button type="button" className="underline" disabled={readOnly} onClick={() => setPath([])}>
retirar a seleção territorial deste preenchimento
</button>. O registo guardado só muda quando guardar.
</p>
)}
<TerritoryGeometryPreview
territoryId={path.at(-1)?.id}
territoryId={foreignCountry ? undefined : path.at(-1)?.id}
management
endpoint={basePath === '/minhas-oportunidades' ? '/minhas-oportunidades/territory-geometries' : undefined}
/>
@@ -424,6 +452,7 @@ export default function OpportunityResources({
index={index}
parent={path[index - 1]?.id ?? ''}
selected={path[index]}
disabled={readOnly || foreignCountry}
endpoint={basePath === '/minhas-oportunidades' ? '/minhas-oportunidades/territory-options' : '/management/territory-options'}
onChange={(value) =>
setPath((previous) =>
+2 -2
View File
@@ -55,7 +55,7 @@ export function Management({
aiEnabled?: boolean;
}>().props;
return (
<main className="space-y-6 p-4 md:p-8">
<div className="space-y-6 p-4 md:p-8">
<Head title={title} />
{auth?.canManagePortal && basePath !== '/minhas-oportunidades' ? <nav
className="flex flex-wrap gap-4 text-sm underline"
@@ -116,7 +116,7 @@ export function Management({
</p>
)}
{children}
</main>
</div>
);
}
+301
View File
@@ -0,0 +1,301 @@
import { Head, Link, useForm } from '@inertiajs/react';
export type LegacyArticle = {
id: number;
title: string;
author: string;
legacy_id: number;
legacy_category: string;
published_at: string;
modified_at: string;
source_url: string;
href: string;
landing_href: string;
start_href: string;
group: { label: string; heading: string };
related_articles: { id: number; slug: string; title: string; href: string }[];
html: string;
library_href: string;
image: { href: string; alt: string; source_url: string } | null;
sector: { name: string; slug: string } | null;
territorial_references: string[];
territorial_status: string;
opportunities: {
title: string;
slug: string;
province: string;
summary: string;
}[];
};
export default function LegacySector({
article,
articles = [article],
view,
query = '',
match = true,
contentContext,
}: {
article: LegacyArticle;
articles?: LegacyArticle[];
view: 'landing' | 'article';
query?: string;
match?: boolean;
contentContext?: { id: string; title: string } | null;
}) {
const search = useForm({ q: query });
return (
<main className="legacy-agronegocio mx-auto max-w-6xl space-y-8 rounded-2xl bg-[#f6f3ea] p-4 sm:p-8">
<Head
title={
view === 'landing' ? `Explorar ${article.group.label}` : article.title
}
/>
<style>{`
.legacy-agronegocio { color: #10352b; font-family: 'Noto Sans', system-ui, sans-serif; }
.legacy-agronegocio h1, .legacy-agronegocio h2 { font-family: 'Noto Serif', Georgia, serif; }
.legacy-agronegocio a, .legacy-agronegocio button { outline-offset: 4px; }
.legacy-agronegocio a:focus-visible, .legacy-agronegocio button:focus-visible { outline: 3px solid #b22222; }
.legacy-article { font-size: 1.0625rem; line-height: 1.8; overflow-wrap: anywhere; }
.legacy-article p, .legacy-article ul, .legacy-article ol { margin-block: 1.2em; }
.legacy-article ul { list-style: disc; padding-inline-start: 1.6em; }
.legacy-article ol { list-style: decimal; padding-inline-start: 1.6em; }
.legacy-article a { text-decoration: underline; }
`}</style>
<nav className="flex flex-wrap gap-4" aria-label={article.group.label}>
<Link href={article.landing_href} className="underline">
Explorar {article.group.label}
</Link>
<Link href="/sectores" className="underline">
Todos os setores
</Link>
<Link href={article.library_href} className="underline">
Exemplar na biblioteca
</Link>
</nav>
<header className="overflow-hidden rounded-2xl border bg-white">
{article.image && (
<img
className="aspect-video w-full object-cover"
src={article.image.href}
alt={article.image.alt}
width={900}
height={506}
/>
)}
<div className="space-y-3 p-5 sm:p-8">
<p className="text-sm font-semibold tracking-wide text-[#b22222] uppercase">
Conhecer · preparar · acompanhar
</p>
<h1 className="text-3xl font-semibold sm:text-4xl">
{view === 'landing'
? article.group.heading
: article.title}
</h1>
<p>
Explore o setor e prepare a sua ideia com o contexto
guardado no dossier.
</p>
<p className="text-sm">
Fonte: {article.author} · Publicado em{' '}
<time dateTime={article.published_at}>
{article.published_at.slice(0, 10)}
</time>{' '}
· Atualizado em{' '}
<time dateTime={article.modified_at}>
{article.modified_at.slice(0, 10)}
</time>
</p>
</div>
</header>
{view === 'landing' ? (
<section className="space-y-4" aria-labelledby="learn-title">
<h2 id="learn-title" className="text-2xl font-semibold">
Compreender o setor
</h2>
<form
onSubmit={(e) => {
e.preventDefault();
search.get(article.landing_href);
}}
className="flex flex-wrap gap-3"
>
<label className="grid flex-1 gap-1">
Pesquisar no conteúdo
<input
className="min-w-0 rounded border p-3"
value={search.data.q}
onChange={(e) =>
search.setData('q', e.target.value)
}
maxLength={120}
type="search"
/>
</label>
<button
className="self-end rounded bg-[#b22222] px-5 py-3 text-white"
disabled={search.processing}
>
Pesquisar
</button>
</form>
{match ? (
<div className="grid gap-4 sm:grid-cols-2">
{articles.map((item) => (
<article key={item.id} className="space-y-3 rounded-xl border bg-white p-5">
<h3 className="text-xl font-semibold">
<Link className="underline" href={item.href}>
{item.title}
</Link>
</h3>
<p>
Conteúdo editorial preservado do portal Tempo.
</p>
<Link
className="inline-block rounded bg-[#10352b] px-5 py-3 text-white"
href={item.href}
>
Ler o artigo
</Link>
</article>
))}
</div>
) : (
<p role="status">
Nenhum conteúdo corresponde à pesquisa.
</p>
)}
</section>
) : (
<section
aria-label="Artigo educativo"
className="legacy-article max-w-3xl"
dangerouslySetInnerHTML={{ __html: article.html }}
/>
)}
{view === 'article' && article.related_articles.length > 0 && (
<section className="space-y-3" aria-labelledby="related-title">
<h2 id="related-title" className="text-2xl font-semibold">Outras leituras no setor</h2>
<ul className="grid gap-3 sm:grid-cols-2">
{article.related_articles.map((item) => (
<li key={item.id}><Link className="underline" href={item.href}>{item.title}</Link></li>
))}
</ul>
</section>
)}
<section
className="space-y-4 rounded-xl border bg-white p-5"
aria-labelledby="locations-title"
>
<h2 id="locations-title" className="text-2xl font-semibold">
Contexto territorial
</h2>
<ul className="flex flex-wrap gap-3">
{article.territorial_references.map((name) => (
<li key={name} className="rounded border px-3 py-2">
{name}
</li>
))}
</ul>
<p>{article.territorial_status}</p>
<div className="flex flex-wrap gap-4">
<Link href="/carteira?kind=corridor" className="underline">
Consultar os corredores cadastrados
</Link>
<Link href="/zonas" className="underline">
Consultar localizações e mapas disponíveis
</Link>
</div>
</section>
<section
className="space-y-4"
aria-labelledby="opportunities-title"
>
<h2 id="opportunities-title" className="text-2xl font-semibold">
Oportunidades publicadas no setor
</h2>
<p>
Cadastros independentes do artigo, com a sua própria autoria
e situação de publicação.
</p>
{article.opportunities.length ? (
<ul className="grid gap-4 sm:grid-cols-2">
{article.opportunities.map((o) => (
<li
key={o.slug}
className="rounded-xl border bg-white p-5"
>
<h3 className="font-semibold">
<Link
className="underline"
href={`/oportunidades/${o.slug}`}
>
{o.title}
</Link>
</h3>
<p>{o.province}</p>
<p>{o.summary}</p>
</li>
))}
</ul>
) : (
<p>
Ainda não há oportunidades publicadas neste setor. Pode
desenvolver uma ideia no seu dossier.
</p>
)}
</section>
<section
className="space-y-3 rounded-xl bg-[#10352b] p-6 text-white"
aria-labelledby="prepare-title"
>
<h2 id="prepare-title" className="text-2xl font-semibold">
Preparar a sua ideia
</h2>
<p>
A leitura é pública. Para guardar dados pessoais, escolha ou
crie um dossier na sua conta.
</p>
<Link
className="inline-block rounded bg-white px-5 py-3 font-semibold text-[#10352b]"
href={
contentContext
? `/investimentos/${contentContext.id}`
: article.start_href
}
>
{contentContext
? `Continuar: ${contentContext.title}`
: 'Iniciar ou continuar uma ideia'}
</Link>
</section>
<footer className="space-y-2 border-t pt-4 text-sm">
<p>
Conteúdo editorial de {article.author}. Categoria original:{' '}
{article.legacy_category}. Não representa uma oportunidade
concreta, autorização de investimento ou cálculo.
</p>
<a
className="underline"
href={article.source_url}
rel="noopener noreferrer"
>
Consultar a página original
</a>
{article.image && (
<p>
<a
className="underline"
href={article.image.source_url}
rel="noopener noreferrer"
>
Origem da imagem
</a>{' '}
· Autoria individual e data de criação não indicadas no
legado.
</p>
)}
</footer>
</main>
);
}
+4 -2
View File
@@ -161,7 +161,9 @@ export default function Manage({
requirementCatalogue,
requirementAssociationsEnabled,
disclosureAuthorization,
legacyContentEnabled = false,
}: {
legacyContentEnabled?: boolean;
documents: DocumentFile[];
resources: Resource[];
requirementCatalogue: { key: string; label: string; tax: string }[];
@@ -533,9 +535,9 @@ export default function Manage({
}
/>
</Field>
<Field label="Assunto">
<Field label={legacyContentEnabled ? 'Assunto (opcional)' : 'Assunto'}>
<input
required
required={!legacyContentEnabled}
className={control}
value={form.data.topic}
onChange={(e) =>
+2
View File
@@ -264,6 +264,7 @@ function RequestForm({
{field === 'country' ? (
<CountrySelect
countries={countries}
label="País do requerente"
value={form.data.country}
onChange={(value) =>
form.setData('country', value)
@@ -290,6 +291,7 @@ function RequestForm({
País de origem declarado desta solicitação
<CountrySelect
countries={countries}
label="País de origem declarado desta solicitação"
value={form.data.declared_origin_country_code}
onChange={(value) =>
form.setData('declared_origin_country_code', value)
+1 -1
View File
@@ -1,5 +1,5 @@
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}" @class(['dark' => ($appearance ?? 'system') == 'dark'])>
<html lang="{{ str_replace('_', '-', config('portal.interface_language', app()->getLocale())) }}" @class(['dark' => ($appearance ?? 'system') == 'dark'])>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">