@@ -1,4 +1,5 @@
|
||||
import ProfileNavigation from '@/components/profile-navigation';
|
||||
import ContentManagementEntry from '@/components/content-management-entry';
|
||||
import { Head, Link } from '@inertiajs/react';
|
||||
import { dashboard } from '@/routes';
|
||||
import type { InvestmentContext } from '@/pages/investor-path/index';
|
||||
@@ -51,6 +52,7 @@ export default function Dashboard({
|
||||
<Head title="Painel" />
|
||||
<h1 className="text-2xl font-semibold">Painel do portal</h1>
|
||||
<ProfileNavigation />
|
||||
<ContentManagementEntry />
|
||||
{summary ? (
|
||||
<>
|
||||
{opportunityManagement && (
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import ContentManagementEntry from '@/components/content-management-entry';
|
||||
import { Link, useForm, usePage } from '@inertiajs/react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Frame, input, button, card } from '@/pages/investment/shared';
|
||||
@@ -84,6 +85,7 @@ export default function Panel({
|
||||
}, [contextTitle, form.data.title]);
|
||||
return (
|
||||
<Frame title="Balcão Virtual — acompanhamento">
|
||||
<ContentManagementEntry />
|
||||
<nav className="flex flex-wrap gap-4">
|
||||
<Link href="/balcao-virtual/servicos" className="underline">
|
||||
Serviços
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import EducationalGuides from '@/components/educational-guides';
|
||||
import OpportunityCorridorGroups, { type CorridorGroup } from '@/components/opportunity-corridor-groups';
|
||||
import { searchTerritoryHref } from '@/lib/search-territory';
|
||||
import type { EducationalArticle } from '@/components/educational-article-card';
|
||||
import OpportunitySearchFilters from '@/components/opportunity-search-filters';
|
||||
@@ -25,8 +26,10 @@ export default function Catalogue({
|
||||
territorial,
|
||||
territorySelection,
|
||||
catalogueUrl,
|
||||
corridorGroups = [],
|
||||
}: {
|
||||
guides?: EducationalArticle[];
|
||||
corridorGroups?: CorridorGroup[];
|
||||
filters: Record<string, string | string[] | boolean>;
|
||||
references: References;
|
||||
results: {
|
||||
@@ -49,6 +52,13 @@ export default function Catalogue({
|
||||
}) {
|
||||
const page = usePage<{ auth: { user: unknown } }>();
|
||||
const { auth } = page.props;
|
||||
const [investmentSelection, setInvestmentSelection] = useState<number[]>(() => {
|
||||
try { return JSON.parse(sessionStorage.getItem('investment-opportunity-selection') ?? '[]'); } catch { return []; }
|
||||
});
|
||||
function selectInvestment(id: number, checked: boolean) {
|
||||
const next = checked ? [...new Set([...investmentSelection, id])] : investmentSelection.filter(x => x !== id);
|
||||
setInvestmentSelection(next); sessionStorage.setItem('investment-opportunity-selection', JSON.stringify(next));
|
||||
}
|
||||
const form = useForm({
|
||||
association_type: String(filters.association_type ?? ''),
|
||||
association_target: String(filters.association_target ?? ''),
|
||||
@@ -116,6 +126,10 @@ export default function Catalogue({
|
||||
const [saved, setSaved] = useState(favourites);
|
||||
const [selected, setSelected] = useState<number[]>([]);
|
||||
const [comparison, setComparison] = useState<{ record: Opportunity }[]>([]);
|
||||
const comparisonRef = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
if (view === 'corridors' && comparison.length) comparisonRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||
}, [comparison, view]);
|
||||
const [points, setPoints] = useState<Feature[] | null>(null);
|
||||
const [areas, setAreas] = useState<InvestmentMapArea[]>([]);
|
||||
const [unlocated, setUnlocated] = useState<
|
||||
@@ -411,7 +425,7 @@ export default function Catalogue({
|
||||
Alargar pesquisa (remover localização)
|
||||
</button>
|
||||
)}
|
||||
{['grid', 'list', 'map', 'combined'].map((value, i) => (
|
||||
{['grid', 'list', 'map', 'combined', 'corridors'].map((value, i) => (
|
||||
<button
|
||||
key={value}
|
||||
disabled={searchLoading || !!searchError}
|
||||
@@ -427,7 +441,7 @@ export default function Catalogue({
|
||||
);
|
||||
}}
|
||||
>
|
||||
{['Grelha', 'Lista', 'Mapa', 'Lista e mapa'][i]}
|
||||
{['Grelha', 'Lista', 'Mapa', 'Lista e mapa', 'Por corredor'][i]}
|
||||
</button>
|
||||
))}
|
||||
<a
|
||||
@@ -561,7 +575,8 @@ export default function Catalogue({
|
||||
</ul>
|
||||
</section>
|
||||
)}
|
||||
{!searchLoading &&
|
||||
{view === 'corridors' && !searchLoading && !searchError && <OpportunityCorridorGroups groups={corridorGroups} selected={investmentSelection} onSelect={selectInvestment} onClear={()=>{setInvestmentSelection([]);sessionStorage.removeItem('investment-opportunity-selection');}} onCompare={ids=>void api('/api/v1/investment/compare?'+ids.map(id=>'ids[]='+id).join('&')).then(data=>setComparison(data.records)).catch(e=>setError(e.message))}/>}
|
||||
{view !== 'corridors' && !searchLoading &&
|
||||
!searchError &&
|
||||
(view !== 'map' || error || points?.length === 0) && (
|
||||
<div
|
||||
@@ -603,6 +618,7 @@ export default function Catalogue({
|
||||
? 'Retirar favorito'
|
||||
: 'Guardar favorito'}
|
||||
</button>
|
||||
<label className="flex gap-2"><input type="checkbox" checked={investmentSelection.includes(r.id)} onChange={e => selectInvestment(r.id,e.target.checked)} />Escolher para preparar investimento</label>
|
||||
<label className="flex gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
@@ -639,7 +655,7 @@ export default function Catalogue({
|
||||
.
|
||||
</p>
|
||||
)}
|
||||
<nav aria-label="Paginação" className="flex gap-6">
|
||||
<nav aria-label="Paginação" className={view === 'corridors' ? 'hidden' : 'flex gap-6'}>
|
||||
{results.prev_page_url && (
|
||||
<Link href={results.prev_page_url}>Anterior</Link>
|
||||
)}
|
||||
@@ -662,8 +678,9 @@ export default function Catalogue({
|
||||
Comparar {selected.length} oportunidades
|
||||
</button>
|
||||
)}
|
||||
{view !== 'corridors' && !!investmentSelection.length && <section className={card}><p>{investmentSelection.length} oportunidades escolhidas, conservadas ao mudar de página.</p><Link className={button} href={'/investimentos/iniciar?' + investmentSelection.map(id => 'opportunities[]='+id).join('&')}>Preparar investimento com as oportunidades escolhidas</Link><button className="ml-4 underline" onClick={() => {setInvestmentSelection([]);sessionStorage.removeItem('investment-opportunity-selection');}}>Limpar escolha</button></section>}
|
||||
{comparison.length > 0 && (
|
||||
<div className="overflow-x-auto">
|
||||
<div ref={comparisonRef} className="overflow-x-auto">
|
||||
<table className="w-full border-collapse text-left">
|
||||
<caption className="p-3 text-left font-bold">
|
||||
Comparação — montantes nas moedas de origem
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import EducationalGuides from '@/components/educational-guides';
|
||||
import { searchTerritoryHref } from '@/lib/search-territory';
|
||||
import { searchTerritoryHref, investmentPreparationHref } from '@/lib/search-territory';
|
||||
import type { EducationalArticle } from '@/components/educational-article-card';
|
||||
import { ClassificationSummary } from '@/components/opportunity-classification';
|
||||
import { Link, router, usePage } from '@inertiajs/react';
|
||||
@@ -32,9 +32,10 @@ export default function Detail({
|
||||
const [sharing, setSharing] = useState('');
|
||||
return (
|
||||
<Frame title={r.title}>
|
||||
{r.maturity_label === 'Em preparação' && <p className="rounded border border-amber-700 bg-amber-50 p-4"><strong>Em preparação.</strong> Consulte a oportunidade e prepare o seu investimento. A execução depende das condições e autorizações aplicáveis ao projecto.</p>}
|
||||
<Link
|
||||
className={button}
|
||||
href={'/investimentos/iniciar?source=opportunity:' + r.id}
|
||||
href={investmentPreparationHref(r.id, page.url, dossierOrigin?.id)}
|
||||
>
|
||||
Iniciar ou continuar investimento com esta oportunidade
|
||||
</Link>
|
||||
@@ -55,14 +56,6 @@ export default function Detail({
|
||||
<p>
|
||||
{r.reference} · {r.sector?.name} · {r.province} {r.district}
|
||||
</p>
|
||||
{!r.last_validated_at && (
|
||||
<p className="rounded border border-amber-700 bg-amber-50 p-4">
|
||||
Esta ficha não regista data de validação documental.
|
||||
Confirme a origem e as condições antes de agir. Preparar uma
|
||||
manifestação expressa interesse; não confirma a oferta nem
|
||||
representa aprovação.
|
||||
</p>
|
||||
)}
|
||||
<p className="text-xl">{r.summary}</p>
|
||||
<ClassificationSummary rows={c.classification ?? []} />
|
||||
<TerritorialSources sources={c.source_evidence} />
|
||||
@@ -97,6 +90,9 @@ export default function Detail({
|
||||
</p>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-4">
|
||||
<Link className={button} href={investmentPreparationHref(r.id, page.url, dossierOrigin?.id)}>
|
||||
Iniciar ou continuar o roteiro deste investimento
|
||||
</Link>
|
||||
{auth.user ? (
|
||||
<button
|
||||
className={button}
|
||||
|
||||
@@ -2,42 +2,44 @@ import ContextDocuments from '@/components/context-documents';
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { Frame, card, input, button } from '@/pages/investment/shared';
|
||||
import { contextApi, type ContextReference } from '@/lib/investor-context';
|
||||
import { contextApi, type ContextReference, type OpportunityChoice } from '@/lib/investor-context';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
export default function ContextStart({
|
||||
contexts,
|
||||
source,
|
||||
opportunityChoices = [],
|
||||
step = null,
|
||||
entryQuery = {},
|
||||
}: {
|
||||
contexts: { id: string; title: string; version: number }[];
|
||||
source: ContextReference | null;
|
||||
opportunityChoices?: OpportunityChoice[];
|
||||
step?: string | null;
|
||||
entryQuery?: Record<string, string>;
|
||||
}) {
|
||||
const [chosen, setChosen] = useState('');
|
||||
const [title, setTitle] = useState(source?.title ?? '');
|
||||
const [title, setTitle] = useState(source?.title ?? opportunityChoices[0]?.opportunity.title ?? '');
|
||||
const [consent, setConsent] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [key] = useState(createOperationKey);
|
||||
const suffix = source ? '?source=' + encodeURIComponent(source.key) : '';
|
||||
const sourceSuffix = opportunityChoices.length ? '?' + opportunityChoices.map(c => `opportunities[]=${encodeURIComponent(c.opportunity.id)}`).join('&') : source ? '?source=' + encodeURIComponent(source.key) : '';
|
||||
const suffix = sourceSuffix ? sourceSuffix+'&selection_key='+encodeURIComponent(key)+'&'+new URLSearchParams(entryQuery).toString() : '';
|
||||
return (
|
||||
<Frame title="Iniciar ou continuar um investimento">
|
||||
{!!opportunityChoices.length && <section className={card}><h2 className="font-bold">Oportunidades escolhidas</h2><ul>{opportunityChoices.map(c => <li key={c.opportunity.key}><Link className="underline" href={c.opportunity.href}>{c.opportunity.title}</Link> · {c.territory?.title ?? 'Localização por escolher'}{c.portfolio_origins?.map(origin=><p key={origin.id}>Associação escolhida: <Link className="underline" href={origin.href}>{origin.title}</Link></p>)}</li>)}</ul><p>Confirme a localização de cada ficha na comparação do dossier. Ao continuar um dossier, as escolhas já guardadas conservam-se.</p></section>}
|
||||
<p>
|
||||
Ideia, oportunidade, sector e localização convergem no mesmo
|
||||
dossier. A referência é para preparação e não confirma direitos
|
||||
ou benefícios.
|
||||
</p>
|
||||
<ContextDocuments source={source ?? undefined} />
|
||||
{source && (
|
||||
{source && !opportunityChoices.length && (
|
||||
<section className={card}>
|
||||
<h2 className="font-bold">Origem consultada</h2>
|
||||
<h2 className="font-bold">A sua escolha</h2>
|
||||
<Link className="underline" href={source.href}>
|
||||
{source.title}
|
||||
</Link>
|
||||
<p>
|
||||
{source.kind} · v{source.version ?? 'não exposta'} ·{' '}
|
||||
{source.key}
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
<section className={card + ' space-y-3'}>
|
||||
@@ -63,14 +65,14 @@ export default function ContextStart({
|
||||
<Link
|
||||
className={button}
|
||||
href={
|
||||
step && !source
|
||||
step && !source && !opportunityChoices.length
|
||||
? `/investimentos/${chosen}#${step}`
|
||||
: `/investimentos/${chosen}/contexto/editar${suffix}`
|
||||
}
|
||||
>
|
||||
{step && !source
|
||||
{step && !source && !opportunityChoices.length
|
||||
? 'Abrir ' + step + ' no mesmo dossier'
|
||||
: 'Comparar no mesmo dossier'}
|
||||
: 'Preparar neste dossier'}
|
||||
</Link>
|
||||
)}
|
||||
<p>
|
||||
@@ -100,7 +102,7 @@ export default function ContextStart({
|
||||
>
|
||||
<h2 className="text-xl font-bold">Iniciar uma nova ideia</h2>
|
||||
<p>
|
||||
Utiliza o cadastro e as cinco fases/19 etapas já existentes.
|
||||
Organize a sua ideia e acompanhe a preparação do investimento.
|
||||
</p>
|
||||
<label className="grid gap-1">
|
||||
Título do investimento
|
||||
@@ -121,7 +123,7 @@ export default function ContextStart({
|
||||
Autorizo reutilizar o meu perfil neste dossier privado.
|
||||
</label>
|
||||
<button className={button} disabled={!consent || busy}>
|
||||
Criar dossier e comparar a referência
|
||||
Criar dossier e preparar investimento
|
||||
</button>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
</form>
|
||||
|
||||
@@ -2,10 +2,9 @@ import {
|
||||
PreparationEditor,
|
||||
PreparationImpact,
|
||||
} from '@/components/private-investment-preparation';
|
||||
import { InvestmentContextAssessment } from '@/components/investment-context-assessment';
|
||||
import ContextDocuments from '@/components/context-documents';
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Frame, button, card, input } from '@/pages/investment/shared';
|
||||
import {
|
||||
TerritoryFields,
|
||||
@@ -20,6 +19,10 @@ import {
|
||||
} from '@/lib/investor-context';
|
||||
import { useNavigationContext } from '@/components/navigation-context';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import OpportunityChoices from '@/components/investment-opportunity-choices';
|
||||
import InvestmentRequirements from '@/components/investment-requirements';
|
||||
import type { OpportunityChoice } from '@/lib/investor-context';
|
||||
import type { CorridorOption } from '@/components/investment-opportunity-choices';
|
||||
type Options = {
|
||||
opportunities: { key: string; title: string; kind: string }[];
|
||||
sectors: { id: number; name: string }[];
|
||||
@@ -32,36 +35,93 @@ export default function ContextEditor({
|
||||
options: initialOptions,
|
||||
source,
|
||||
territorySelection = [],
|
||||
requestedChoices = null,
|
||||
draft = null,
|
||||
entrySources = [],
|
||||
entryLocationDifferences = [],
|
||||
}: {
|
||||
initial: ContextView;
|
||||
options: Options;
|
||||
source: ContextReference | null;
|
||||
territorySelection?: TerritoryOption[];
|
||||
requestedChoices?: OpportunityChoice[] | null;
|
||||
entrySources?: string[];
|
||||
entryLocationDifferences?: {title:string;saved:string;requested:string}[];
|
||||
draft?: {draft_sequence?:number;needs_review?:boolean;selection?:Partial<Record<Slot,string>>;declarations?:Record<string,string>;replace_fields?:string[];document_links?:Record<string,string|null>}|null;
|
||||
}) {
|
||||
const navigation = useNavigationContext();
|
||||
const [choices, setChoices] = useState<OpportunityChoice[]>(requestedChoices ?? initial.context.opportunity_choices ?? []);
|
||||
const [manageChoices, setManageChoices] = useState(requestedChoices !== null || !!initial.context.opportunity_choices?.length);
|
||||
const [view, setView] = useState(initial);
|
||||
const [preparation, setPreparation] = useState(initial.private_investment);
|
||||
const [options, setOptions] = useState(initialOptions);
|
||||
const [query, setQuery] = useState('');
|
||||
const [changes, setChanges] = useState<Partial<Record<Slot, string>>>(() =>
|
||||
source
|
||||
draft?.selection ?? (source
|
||||
? {
|
||||
[source.kind === 'business' ? 'opportunity' : source.kind]:
|
||||
source.key,
|
||||
}
|
||||
: {},
|
||||
: {}),
|
||||
);
|
||||
const [declarations, setDeclarations] = useState<Record<string, string>>(
|
||||
{},
|
||||
draft?.declarations ?? {},
|
||||
);
|
||||
const [documentLinks, setDocumentLinks] = useState<
|
||||
Record<string, string | null>
|
||||
>({});
|
||||
const [replace, setReplace] = useState<string[]>([]);
|
||||
>(draft?.document_links ?? {});
|
||||
const [replace, setReplace] = useState<string[]>(draft?.replace_fields ?? []);
|
||||
const [plan, setPlan] = useState<ContextPlan | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [message, setMessage] = useState('');
|
||||
const [corridors,setCorridors]=useState<CorridorOption[]>([]);
|
||||
const [parks,setParks]=useState<Options['parks']>([]);
|
||||
const [corridorLoading,setCorridorLoading]=useState(true);
|
||||
const [corridorError,setCorridorError]=useState('');
|
||||
const [corridorRetry,setCorridorRetry]=useState(0);
|
||||
const [draftStatus,setDraftStatus]=useState('');
|
||||
const [draftRetry,setDraftRetry]=useState(0);
|
||||
const queue=useRef<Promise<unknown>>(Promise.resolve());
|
||||
const firstCorridor=choices[0]?.corridor_key ?? corridors.find(c=>c.name===choices[0]?.coverage)?.key;
|
||||
const firstTerritory=choices[0]?.territory?.id;
|
||||
useEffect(()=>{
|
||||
let active=true;setCorridorLoading(true);setCorridorError('');
|
||||
const params=new URLSearchParams();if(firstCorridor)params.set('corridor',firstCorridor);if(firstTerritory)params.set('territory',firstTerritory);
|
||||
void contextApi<{corridors:CorridorOption[];parks:Options['parks']}>('/investimentos/opcoes-corredor?'+params).then(data=>{
|
||||
if(!active)return;setCorridors(data.corridors);setParks(data.parks);
|
||||
const park=Object.hasOwn(changes,'park')?changes.park:view.context.selection.park?.key;
|
||||
if(firstCorridor&&park&&!data.parks.some(p=>'park:'+p.id===park)){
|
||||
setChanges(old=>({...old,park:''}));setPlan(null);setMessage('A zona ou parque anterior foi retirado porque não tem enquadramento compatível com a localização escolhida.');
|
||||
}
|
||||
}).catch(e=>{if(active)setCorridorError(e.message)}).finally(()=>{if(active)setCorridorLoading(false)});
|
||||
return()=>{active=false};
|
||||
},[firstCorridor,firstTerritory,corridorRetry]);
|
||||
const draftBody=JSON.stringify({entry_sources:entrySources,version:view.case.version,selection:changes,declarations,replace_fields:replace,document_links:documentLinks,
|
||||
...(manageChoices?{opportunity_choices:choices.map(c=>({source:c.opportunity.key,portfolio_origins:(c.portfolio_origins??[]).map(r=>r.id),corridor_key:c.corridor_key,territory:c.territory?.key??null,location_reason:c.location_reason,confirm_location_change:!!c.confirm_location_change,activities:c.activities??[]}))}:{})});
|
||||
const latestDraft=useRef(draftBody);latestDraft.current=draftBody;
|
||||
const skipNextDraft=useRef(false);
|
||||
const confirmedDraftBody=useRef<string|null>(null);
|
||||
const sequence=useRef({body:'',value:Math.max(Date.now(),draft?.draft_sequence??0)});
|
||||
if(sequence.current.body!==draftBody)sequence.current={body:draftBody,value:Math.max(Date.now(),sequence.current.value+1)};
|
||||
useEffect(()=>{
|
||||
if(busy||corridorLoading||corridorError)return;
|
||||
if(skipNextDraft.current){skipNextDraft.current=false;confirmedDraftBody.current=draftBody;setDraftStatus('Dados confirmados.');return;}
|
||||
if(draftBody===confirmedDraftBody.current)return;
|
||||
setDraftStatus('A guardar rascunho…');
|
||||
const timer=setTimeout(()=>{
|
||||
const savedSequence=sequence.current.value;
|
||||
queue.current=queue.current.catch(()=>{}).then(()=>contextApi('/investimentos/'+view.case.id+'/contexto/rascunho',{...JSON.parse(draftBody),draft_sequence:savedSequence},'POST',draftBody.length<60000))
|
||||
.then(()=>{if(latestDraft.current===draftBody)setDraftStatus('Rascunho guardado.');})
|
||||
.catch(e=>{if(latestDraft.current===draftBody)setDraftStatus('Rascunho não guardado: '+e.message)});
|
||||
},400);
|
||||
return()=>clearTimeout(timer);
|
||||
},[draftBody,busy,corridorLoading,corridorError,draftRetry]);
|
||||
useEffect(()=>{
|
||||
const flush=()=>{const body=latestDraft.current;if(body!==confirmedDraftBody.current&&body.length<60000)void contextApi('/investimentos/'+initial.case.id+'/contexto/rascunho',{...JSON.parse(body),draft_sequence:sequence.current.value},'POST',true).catch(()=>{});};
|
||||
window.addEventListener('pagehide',flush);
|
||||
return()=>{window.removeEventListener('pagehide',flush);flush();};
|
||||
},[initial.case.id]);
|
||||
const [operation, setOperation] = useState(createOperationKey);
|
||||
const [requestBody, setRequestBody] = useState<Record<
|
||||
string,
|
||||
@@ -107,6 +167,7 @@ export default function ContextEditor({
|
||||
setError('');
|
||||
setMessage('');
|
||||
const body = {
|
||||
...(manageChoices ? {opportunity_choices: choices.map(c => ({source:c.opportunity.key,portfolio_origins:(c.portfolio_origins??[]).map(r=>r.id),corridor_key:c.corridor_key,territory:c.territory?.key ?? null,location_reason:c.location_reason,confirm_location_change:!!c.confirm_location_change,activities:c.activities??[]}))} : {}),
|
||||
version: view.case.version,
|
||||
selection: changes,
|
||||
declarations,
|
||||
@@ -134,6 +195,7 @@ export default function ContextEditor({
|
||||
async function confirm() {
|
||||
if (!plan || !requestBody) return;
|
||||
setBusy(true);
|
||||
await queue.current.catch(()=>{});
|
||||
setError('');
|
||||
try {
|
||||
await contextApi(
|
||||
@@ -148,7 +210,11 @@ export default function ContextEditor({
|
||||
const next = await contextApi<ContextView>(
|
||||
`/investimentos/${view.case.id}/contexto`,
|
||||
);
|
||||
skipNextDraft.current=true;
|
||||
// The entry has been consumed: refreshing must recover saved choices, not reapply a removed association.
|
||||
window.history.replaceState(window.history.state, '', `/investimentos/${view.case.id}/contexto/editar${window.location.hash}`);
|
||||
setView(next);
|
||||
setChoices(next.context.opportunity_choices ?? []);
|
||||
setPreparation(next.private_investment);
|
||||
navigation.refresh();
|
||||
setChanges({});
|
||||
@@ -158,7 +224,7 @@ export default function ContextEditor({
|
||||
setPlan(null);
|
||||
setOperation(createOperationKey());
|
||||
setMessage(
|
||||
'Contexto guardado no mesmo dossier. Resultados afetados identificados para revisão; conteúdo submetido e histórico preservados.',
|
||||
'Dados guardados. Pode continuar a preparação do investimento.',
|
||||
);
|
||||
} catch (e) {
|
||||
setError(
|
||||
@@ -171,28 +237,19 @@ export default function ContextEditor({
|
||||
}
|
||||
}
|
||||
return (
|
||||
<Frame title="Contexto do investimento">
|
||||
<InvestmentContextAssessment
|
||||
contextId={view.case.id}
|
||||
raw={view.prefill.simulator?.context_applicability_snapshot}
|
||||
/>
|
||||
<ContextDocuments source={view.context.selection.opportunity} />
|
||||
<Frame title="Preparar investimento">
|
||||
<div className="space-y-5 [overflow-wrap:anywhere]">
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/investimentos/${view.case.id}`}
|
||||
>
|
||||
Voltar ao mesmo dossier
|
||||
Voltar ao dossier
|
||||
</Link>
|
||||
<p>
|
||||
{view.case.title} · UUID {view.case.id} · dossier v
|
||||
{view.case.version} · contexto v{view.context.revision}
|
||||
</p>
|
||||
<p className="rounded border border-emerald-300 bg-emerald-50 p-3">
|
||||
As referências apoiam a preparação. Associar uma
|
||||
oportunidade, sector ou localização não confirma incentivos,
|
||||
licença, terra disponível, reserva ou autorização.
|
||||
{view.case.title}
|
||||
</p>
|
||||
<p>Confirme as oportunidades e a localização, complete os dados disponíveis e reveja antes de guardar.</p>
|
||||
{!!entryLocationDifferences.length && <aside className="rounded border border-amber-500 p-3" aria-label="Localização anterior conservada">{entryLocationDifferences.map(row=><p key={row.title}>{row.title}: a localização recebida ({row.requested}) não substituiu a escolha guardada ({row.saved}). Pode rever a localização abaixo antes de confirmar.</p>)}</aside>}
|
||||
{error && (
|
||||
<div
|
||||
role="alert"
|
||||
@@ -210,8 +267,17 @@ export default function ContextEditor({
|
||||
)}
|
||||
{message && <p role="status">{message}</p>}
|
||||
<section className={card + ' space-y-4'}>
|
||||
{corridorError&&<p role="alert">{corridorError} <button className="underline" onClick={()=>setCorridorRetry(v=>v+1)}>Tentar novamente</button></p>}
|
||||
{corridorLoading&&<p role="status">A carregar opções do corredor…</p>}
|
||||
<p role="status">{draftStatus}</p>
|
||||
{draft?.needs_review&&<p role="status">O rascunho foi recuperado, mas o dossier recebeu outras alterações. Reveja os dados antes de confirmar.</p>}
|
||||
{draftStatus.startsWith('Rascunho não guardado')&&<button type="button" className="underline" onClick={()=>setDraftRetry(v=>v+1)}>Tentar guardar novamente</button>}
|
||||
<OpportunityChoices corridors={corridors} choices={choices} disabled={busy||corridorLoading||!!corridorError} onChange={next=>{setChoices(next);setManageChoices(true);setPlan(null);}}/>
|
||||
<ContextDocuments source={source ?? view.context.selection.opportunity} />
|
||||
{view.context.revision > 0 && !Object.keys(changes).length && JSON.stringify(choices) === JSON.stringify(view.context.opportunity_choices ?? []) && <InvestmentRequirements assessment={view.context.requirements_assessment} contextId={view.case.id}/>}
|
||||
<label className="block">Acrescentar uma oportunidade à escolha<select className={input} value="" onChange={e=>{const o=options.opportunities.find(o=>o.key===e.target.value);if(o && !choices.some(c=>c.opportunity.key===o.key)){setChoices([...choices,{opportunity:{...o,id:o.key.split(':')[1],href:'/oportunidades',version:null,sha256:'',fields:{}},territory:null,location_reason:'',location_state:'undetermined'}]);setManageChoices(true);setPlan(null);}}}><option value="">Seleccionar ficha</option>{options.opportunities.filter(o=>o.kind==='opportunity'&&!choices.some(c=>c.opportunity.key===o.key)).map(o=><option key={o.key} value={o.key}>{o.title}</option>)}</select></label>
|
||||
<h2 className="text-xl font-bold">
|
||||
Escolher referências existentes
|
||||
Dados do investimento
|
||||
</h2>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<label className="min-w-0 flex-1">
|
||||
@@ -241,11 +307,11 @@ export default function ContextEditor({
|
||||
</button>
|
||||
</div>
|
||||
<label className="grid min-w-0 gap-1">
|
||||
Oportunidade
|
||||
Referência individual (sem selecção múltipla)
|
||||
<select
|
||||
className={input + ' max-w-full min-w-0'}
|
||||
value={selected('opportunity')}
|
||||
disabled={busy}
|
||||
disabled={busy || manageChoices}
|
||||
onChange={(e) =>
|
||||
change('opportunity', e.target.value)
|
||||
}
|
||||
@@ -331,29 +397,30 @@ export default function ContextEditor({
|
||||
</select>
|
||||
</label>
|
||||
<label className="grid min-w-0 gap-1">
|
||||
ZEE, ZFI ou parque consultado
|
||||
{choices.length>1?'Zona ou parque da primeira oportunidade':'ZEE, ZFI ou parque consultado'}
|
||||
<select
|
||||
className={input + ' max-w-full min-w-0'}
|
||||
disabled={busy}
|
||||
disabled={busy||corridorLoading||!!corridorError||(!!firstCorridor&&!firstTerritory)}
|
||||
value={selected('park')}
|
||||
onChange={(e) => change('park', e.target.value)}
|
||||
>
|
||||
<option value="">
|
||||
Sem ZEE, ZFI ou parque seleccionado
|
||||
</option>
|
||||
{options.parks.map((p) => (
|
||||
{(firstCorridor?parks:options.parks).map((p) => (
|
||||
<option key={p.id} value={'park:' + p.id}>
|
||||
{p.name} · v{p.version_no}
|
||||
{p.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<h3 className="font-semibold">
|
||||
{firstCorridor&&!corridorLoading&&!corridorError&&<p>{!firstTerritory?'Escolha a localização para consultar zonas e parques.':!parks.length?'Não existem zonas ou parques com enquadramento documentado compatível nesta localização.':'A consulta não confirma disponibilidade de lotes, admissão ou incentivos.'}</p>}
|
||||
{!manageChoices&&<><h3 className="font-semibold">
|
||||
Localização — escolher até ao nível conhecido
|
||||
</h3>
|
||||
<TerritoryFields
|
||||
initial={territorySelection}
|
||||
disabled={busy}
|
||||
disabled={busy || manageChoices}
|
||||
endpoint="/api/v1/investment/territory-options"
|
||||
onChange={(path) =>
|
||||
change(
|
||||
@@ -367,10 +434,10 @@ export default function ContextEditor({
|
||||
{view.context.selection.territory && (
|
||||
<p>
|
||||
Referência guardada:{' '}
|
||||
{view.context.selection.territory.title} · v
|
||||
{view.context.selection.territory.version}.
|
||||
{view.context.selection.territory.title}
|
||||
</p>
|
||||
)}
|
||||
</>}
|
||||
</section>
|
||||
<section className={card + ' space-y-3'}>
|
||||
<h2 className="text-xl font-bold">
|
||||
@@ -563,7 +630,7 @@ export default function ContextEditor({
|
||||
disabled={busy}
|
||||
onClick={() => void preview()}
|
||||
>
|
||||
Comparar impacto antes de guardar
|
||||
Rever dados antes de guardar
|
||||
</button>
|
||||
</section>
|
||||
{plan && (
|
||||
@@ -574,6 +641,8 @@ export default function ContextEditor({
|
||||
<h2 className="text-xl font-bold">
|
||||
Comparação antes da confirmação
|
||||
</h2>
|
||||
{!!plan.opportunity_choices?.length && <OpportunityChoices choices={plan.opportunity_choices}/>}
|
||||
<InvestmentRequirements assessment={plan.requirements_assessment} contextId={view.case.id}/>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full min-w-[36rem] table-fixed text-left">
|
||||
<thead>
|
||||
@@ -588,10 +657,9 @@ export default function ContextEditor({
|
||||
Mantido
|
||||
</th>
|
||||
<td className="p-2">
|
||||
UUID, identidade e{' '}
|
||||
{plan.documents_preserved}{' '}
|
||||
documentos.{' '}
|
||||
{plan.maintained.map((x) => (
|
||||
{plan.maintained.filter(x=>!x.field.endsWith('_id')).map((x) => (
|
||||
<p key={x.field}>
|
||||
{contextFieldNames[
|
||||
x.field
|
||||
@@ -607,7 +675,7 @@ export default function ContextEditor({
|
||||
Atualizado pela nova seleção
|
||||
</th>
|
||||
<td className="p-2">
|
||||
{plan.updated.map((x) => (
|
||||
{plan.updated.filter(x=>!x.field.endsWith('_id')).map((x) => (
|
||||
<p key={x.field}>
|
||||
{contextFieldNames[
|
||||
x.field
|
||||
@@ -633,11 +701,7 @@ export default function ContextEditor({
|
||||
href={r.href}
|
||||
>
|
||||
{r.title}
|
||||
</Link>{' '}
|
||||
· {r.kind} · v
|
||||
{r.version ??
|
||||
'não exposta'}{' '}
|
||||
· origem {r.key}
|
||||
</Link>
|
||||
</p>
|
||||
),
|
||||
)}
|
||||
@@ -649,14 +713,7 @@ export default function ContextEditor({
|
||||
</th>
|
||||
<td className="p-2">
|
||||
{plan.dependent_results.length}{' '}
|
||||
resultados financeiros acessíveis
|
||||
afetados:{' '}
|
||||
{plan.dependent_results
|
||||
.map((r) => r.id)
|
||||
.join(', ') || 'nenhum'}
|
||||
. Etapas:{' '}
|
||||
{plan.review_steps.join(', ') ||
|
||||
'nenhuma alteração de dependências'}
|
||||
resultados financeiros afectados. Etapas a rever: {plan.review_steps.length}
|
||||
. Dados já preenchidos nos
|
||||
formulários conservam-se até à sua
|
||||
conferência.
|
||||
@@ -668,12 +725,11 @@ export default function ContextEditor({
|
||||
</th>
|
||||
<td className="p-2">
|
||||
{plan.requests.length} pedidos e os
|
||||
snapshots, decisões e resultados
|
||||
dados, decisões e resultados
|
||||
anteriores.{' '}
|
||||
{plan.requests.map((r) => (
|
||||
<p key={r.id}>
|
||||
{r.protocol || r.id} · v
|
||||
{r.version} · {r.status}
|
||||
{r.protocol || 'Pedido guardado'}
|
||||
</p>
|
||||
))}
|
||||
</td>
|
||||
@@ -706,7 +762,7 @@ export default function ContextEditor({
|
||||
disabled={busy}
|
||||
onClick={() => void confirm()}
|
||||
>
|
||||
Confirmar e guardar o contexto
|
||||
Guardar dados do investimento
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
@@ -717,7 +773,7 @@ export default function ContextEditor({
|
||||
</h2>
|
||||
{view.results.map((r) => (
|
||||
<p key={r.id}>
|
||||
{r.id} · {r.engine} ·{' '}
|
||||
Resultado guardado —{' '}
|
||||
{r.context_state === 'review_required'
|
||||
? 'Desatualizado para o contexto atual — exige revisão/recálculo'
|
||||
: 'Guardado para o contexto indicado no dossier'}
|
||||
@@ -729,7 +785,7 @@ export default function ContextEditor({
|
||||
className="underline"
|
||||
href={'/balcao-virtual/pedidos/' + r.id}
|
||||
>
|
||||
{r.protocol || r.id}
|
||||
{r.protocol || 'Consultar pedido'}
|
||||
</Link>{' '}
|
||||
· {r.status} ·{' '}
|
||||
{r.context_state === 'historical_submission'
|
||||
|
||||
@@ -36,7 +36,7 @@ export default function InvestmentContexts({
|
||||
<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>
|
||||
{zoneSource && <section className="rounded border p-4"><h2>Parque consultado: {zoneSource.title} · versão {zoneSource.consulted_public_version}</h2><p>{zoneSource.notice}</p><Link className="underline" href={zoneSource.href}>Voltar à ficha pública</Link></section>}
|
||||
{zoneSource && <section className="rounded border p-4"><h2>Parque escolhido: {zoneSource.title}</h2><Link className="underline" href={zoneSource.href}>Consultar parque</Link></section>}
|
||||
{sectorSource && (
|
||||
<p>
|
||||
Preparar uma ideia em{' '}
|
||||
@@ -53,7 +53,7 @@ export default function InvestmentContexts({
|
||||
<Link className="underline" href={contentSource.href}>
|
||||
{contentSource.title}
|
||||
</Link>
|
||||
. A fonte e a versão serão guardadas no dossier escolhido.
|
||||
.
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
|
||||
@@ -3,6 +3,8 @@ import {
|
||||
type Preparation,
|
||||
} from '@/components/private-investment-preparation';
|
||||
import ContextDocuments from '@/components/context-documents';
|
||||
import InvestmentRequirements from '@/components/investment-requirements';
|
||||
import OpportunityChoices from '@/components/investment-opportunity-choices';
|
||||
import type { DossierContext } from '@/lib/investor-context';
|
||||
import FintechInvestment, {
|
||||
type FintechView,
|
||||
@@ -117,12 +119,9 @@ function Result({ result }: { result: PathResult }) {
|
||||
</p>
|
||||
<p className="text-sm">
|
||||
Estimativa recalculada pelas fórmulas da ferramenta a partir
|
||||
das entradas guardadas, versão {result.draft_version}. Não
|
||||
dos dados preenchidos. Não
|
||||
constitui decisão de financiamento.
|
||||
</p>
|
||||
<p className="text-xs break-all">
|
||||
Evidência {result.id} · {result.engine}
|
||||
</p>
|
||||
</li>
|
||||
);
|
||||
} catch (error) {
|
||||
@@ -449,16 +448,14 @@ export default function InvestmentPath(path: Path) {
|
||||
{path.investment_context && (
|
||||
<section className="space-y-2 rounded border border-emerald-300 bg-emerald-50 p-4">
|
||||
<h2 className="font-semibold">
|
||||
Contexto atual — revisão{' '}
|
||||
{path.investment_context.revision}
|
||||
As suas escolhas
|
||||
</h2>
|
||||
{Object.values(path.investment_context.selection).map(
|
||||
(ref) => (
|
||||
<p key={ref.key}>
|
||||
<Link className="underline" href={ref.href}>
|
||||
{ref.title}
|
||||
</Link>{' '}
|
||||
· versão {ref.version ?? 'não exposta'}
|
||||
</Link>
|
||||
</p>
|
||||
),
|
||||
)}
|
||||
@@ -490,15 +487,9 @@ export default function InvestmentPath(path: Path) {
|
||||
{zone.title}
|
||||
</Link>
|
||||
<p>
|
||||
UUID {zone.zone_id} · versão consultada{' '}
|
||||
{zone.consulted_public_version} ·{' '}
|
||||
{zone.selected_at}
|
||||
</p>
|
||||
<p>{zone.notice}</p>
|
||||
<p>
|
||||
A ficha atual pode ter uma versão diferente;
|
||||
esta referência conserva a consulta registada.
|
||||
</p>
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
@@ -539,6 +530,8 @@ export default function InvestmentPath(path: Path) {
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{!!path.investment_context?.opportunity_choices?.length && <OpportunityChoices choices={path.investment_context.opportunity_choices}/>}
|
||||
<InvestmentRequirements assessment={path.investment_context?.requirements_assessment} contextId={path.case.id} excludedSteps={path.steps.filter((step) => !step.preparation_allowed).map((step) => step.code)}/>
|
||||
{!!path.content_sources?.length && (
|
||||
<section
|
||||
className="space-y-2 rounded-xl border p-4"
|
||||
@@ -576,15 +569,14 @@ export default function InvestmentPath(path: Path) {
|
||||
<h2 className="font-semibold">Próxima acção</h2>
|
||||
{path.next ? (
|
||||
<a className="underline" href={path.next.href}>
|
||||
{path.next.action}: {path.next.code} · {path.next.title}
|
||||
{path.next.action}: {path.next.title}
|
||||
</a>
|
||||
) : (
|
||||
<p>Reveja as pendências e o acompanhamento.</p>
|
||||
)}
|
||||
<p className="text-sm">
|
||||
Pode preparar etapas independentes enquanto aguarda
|
||||
informação. Percurso v{path.definition_version}; os outros
|
||||
roteiros mantêm a numeração original.
|
||||
informação. As etapas abaixo adaptam-se às suas escolhas.
|
||||
</p>
|
||||
</section>
|
||||
<nav
|
||||
@@ -693,14 +685,25 @@ export default function InvestmentPath(path: Path) {
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
{Object.entries(path.phases).map(([number, label]) => (
|
||||
{path.steps.some((step) => !step.preparation_allowed) && (
|
||||
<section className="rounded-xl border p-4" aria-label="Etapas sem aplicação">
|
||||
<h2 className="font-semibold">Não precisa de preparar neste contexto</h2>
|
||||
<ul>
|
||||
{path.steps.filter((step) => !step.preparation_allowed).map((step) => (
|
||||
<li key={step.code}>{step.title}: {step.reason || 'Conforme as escolhas guardadas.'}</li>
|
||||
))}
|
||||
</ul>
|
||||
<p className="text-sm">Pode rever estas escolhas acima. Os dados e o histórico destas etapas ficam conservados.</p>
|
||||
</section>
|
||||
)}
|
||||
{Object.entries(path.phases).filter(([number]) => path.steps.some((step) => step.phase === Number(number) && step.preparation_allowed)).map(([number, label]) => (
|
||||
<section className="space-y-3" key={number}>
|
||||
<h2 className="text-lg font-semibold">
|
||||
Fase {number} · {label}
|
||||
</h2>
|
||||
<div className="grid items-start gap-3 md:grid-cols-2">
|
||||
{path.steps
|
||||
.filter((step) => step.phase === Number(number))
|
||||
.filter((step) => step.phase === Number(number) && step.preparation_allowed)
|
||||
.map((step) => (
|
||||
<Stage
|
||||
key={step.code}
|
||||
|
||||
@@ -6,7 +6,7 @@ export default function ManagementAccess({
|
||||
}: {
|
||||
registrationEnabled: boolean;
|
||||
}) {
|
||||
const { auth } = usePage<{ auth: Auth }>().props;
|
||||
const { auth, contentManagementHref } = usePage<{ auth: Auth; contentManagementHref?: string | null }>().props;
|
||||
const user = auth.user;
|
||||
const action =
|
||||
'inline-flex rounded-lg bg-slate-900 px-5 py-3 font-medium text-white';
|
||||
@@ -29,7 +29,7 @@ export default function ManagementAccess({
|
||||
<h2 className="text-xl font-semibold">
|
||||
{!user
|
||||
? 'Preparar a sua conta'
|
||||
: auth.canManagePortal
|
||||
: contentManagementHref || auth.canManagePortal
|
||||
? 'Acesso disponível'
|
||||
: !user.email_verified_at
|
||||
? 'Verificar o seu email'
|
||||
@@ -53,6 +53,11 @@ export default function ManagementAccess({
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
) : contentManagementHref ? (
|
||||
<>
|
||||
<p>Abra a entrada de gestão para cadastrar oportunidades e gerir documentos e legislação, conforme as funções já atribuídas à sua conta.</p>
|
||||
<Link className={action} href={contentManagementHref}>Abrir gestão de conteúdos e oportunidades</Link>
|
||||
</>
|
||||
) : auth.canManagePortal ? (
|
||||
<>
|
||||
<p>
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { Frame, card, button } from '@/pages/investment/shared';
|
||||
import { states } from './shared';
|
||||
|
||||
type Access = {
|
||||
procurement?: {index:string;create:string};
|
||||
opportunities?: {index: string; create: string | null; profileWorkflow: boolean};
|
||||
documents?: {index: string; edit: boolean};
|
||||
};
|
||||
export default function ContentHub({access, counts}: {access: Access; counts: Record<string, Record<string, number>>}) {
|
||||
return <Frame title="Gestão de conteúdos e oportunidades">
|
||||
<p>Use os cadastros e a biblioteca existentes. Guardar um rascunho, analisar um ficheiro e publicar são operações distintas. Cada acção respeita a sua autorização actual.</p>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{access.procurement && <section className={card}><h2 className="text-xl font-semibold">Concursos e anúncios</h2><p>Cadastre o procedimento e os lotes, guarde e recupere a preparação, reveja a prévia e publique os actos autorizados. Esclarecimentos, prorrogações, resultados e cancelamentos conservam versões e histórico. Divulgação de oportunidade e abertura de concurso são operações distintas.</p><Link className={button} href={access.procurement.create}>Novo concurso/anúncio</Link><Link className="block underline" href={access.procurement.index}>Gerir concursos e anúncios</Link><Link className="block underline" href="/concursos">Catálogo público</Link></section>}
|
||||
{access.opportunities && <section className={card}>
|
||||
<h2 className="text-xl font-semibold">Oportunidades</h2>
|
||||
<p>Escolha a modalidade, o sector e a localização; preencha, guarde o rascunho e siga as acções de submissão, revisão e publicação disponíveis no seu perfil.</p>
|
||||
<p>Sector económico e modalidade são escolhas distintas. Pode guardar preparação incompleta; o editor identifica os campos e variantes ainda sem suporte de submissão.</p>
|
||||
{access.opportunities.create && <Link className={button} href={access.opportunities.create}>Nova oportunidade</Link>}
|
||||
<Link className="block underline" href={access.opportunities.index}>Gerir oportunidades e histórico</Link>
|
||||
{access.opportunities.profileWorkflow && <Link className="block underline" href="/minhas-oportunidades/lotes/agronegocio">Rever o lote das 34 oportunidades de Agronegócio</Link>}
|
||||
<p>Para divulgar um resumo ainda em preparação, abra a ficha e escolha <strong>Divulgação promocional</strong>: prepare o texto público, reveja a prévia e confirme divulgar, actualizar ou retirar. Esta operação não conclui a validação do investimento.</p>
|
||||
<ul>{Object.entries(counts.opportunities ?? {}).map(([state, total]) => <li key={state}><Link className="underline" href={`${access.opportunities!.index}?status=${state}`}>{states[state] ?? state}: {total}</Link></li>)}</ul>
|
||||
<p className="text-sm">As etapas e a independência já definidas para oportunidades mantêm-se. Esta entrada não atribui autorização para rever ou publicar.</p>
|
||||
{!access.opportunities.profileWorkflow && <p>O seu acesso actual abre o cadastro legado de rascunhos. A submissão, revisão e publicação de novas oportunidades utilizam os perfis operacionais já existentes; a administração de conteúdos não substitui essa designação. Esta entrada não apresenta o rascunho legado como percurso completo de publicação.</p>}
|
||||
</section>}
|
||||
{access.documents && <section className={card}>
|
||||
<h2 className="text-xl font-semibold">Documentos e legislação</h2>
|
||||
<p>Carregue o original ou reutilize um ficheiro existente; acompanhe a análise, complete os metadados e associações e defina o acesso. Depois publique explicitamente, se autorizado.</p>
|
||||
<div className="flex flex-wrap gap-3"><Link className={button} href={`${access.documents.index}?intent=document#receber`}>Novo documento</Link>
|
||||
{access.documents.edit && <Link className={button} href={`${access.documents.index}?intent=legislation#receber`}>Nova legislação</Link>}</div>
|
||||
<Link className="block underline" href={`${access.documents.index}#conteudos`}>Gerir conteúdos, versões e histórico</Link>
|
||||
{!access.documents.edit && <p>O seu acesso permite carregar e analisar ficheiros próprios; não inclui cadastro editorial nem publicação.</p>}
|
||||
<p>Publicados: {counts.documents?.published ?? 0} · Não publicados: {counts.documents?.unpublished ?? 0}. A lista distingue rascunhos de conteúdos retirados através do histórico.</p>
|
||||
<p className="text-sm">Publicar legislação permite consultá-la. Não a activa como regra executável no simulador.</p>
|
||||
</section>}
|
||||
</div>
|
||||
<section className={card}><h2 className="font-semibold">Como concluir sem apoio técnico</h2>
|
||||
<ol className="list-decimal space-y-2 pl-5"><li>Abra a acção pretendida e use os campos do editor existente.</li><li>Guarde a preparação. As mensagens indicam o estado e o que precisa de corrigir.</li><li>Reabra pela gestão, pesquise o título e consulte o histórico.</li><li>Use as acções autorizadas de publicação ou retirada. Os originais e as revisões são preservados.</li></ol>
|
||||
</section>
|
||||
</Frame>;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { profileJson } from '@/lib/profile-json';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { Management, button, control } from './shared';
|
||||
|
||||
type Entry = {key:string;id:number|null;title:string;summary:string;description:string;corridor:string;status:string|null;href:string|null};
|
||||
type Preview = {id:number;token:string;projection:{title:string;summary:string;description:string};operation_key:string};
|
||||
export default function AgribusinessBatch({entries,manifestHash,canRegister}:{entries:Entry[];manifestHash:string;canRegister:boolean}) {
|
||||
const [previews,setPreviews]=useState<Preview[]>([]); const [reason,setReason]=useState(''); const [confirmed,setConfirmed]=useState(false); const [busy,setBusy]=useState(false); const [message,setMessage]=useState('');
|
||||
const base='/minhas-oportunidades/lotes/agronegocio';
|
||||
async function run(action:'register'|'preview'|'disclose') {setBusy(true);setMessage('');try {
|
||||
if(action==='register'){await profileJson(base+'/cadastrar',{manifest_hash:manifestHash,confirm:true});router.reload();}
|
||||
if(action==='preview'){const result=await profileJson(base+'/previa',{}) as {previews:Preview[]};setPreviews(result.previews.map(p=>({...p,operation_key:createOperationKey()})));setConfirmed(false);}
|
||||
if(action==='disclose'){await profileJson(base+'/divulgar',{previews:previews.map(({id,token,operation_key})=>({id,token,operation_key})),reason,confirm:confirmed});setPreviews([]);setMessage('As 34 fichas foram divulgadas como Em preparação; a execução não foi autorizada.');router.reload();}
|
||||
}catch(e){setMessage(e instanceof Error?e.message:'Operação não concluída. A versão anterior foi preservada.');}finally{setBusy(false);}}
|
||||
return <Management title="Oportunidades de Agronegócio"><p>Reveja as oportunidades, complete a informação disponível e confira a prévia antes de divulgar.</p>
|
||||
<p>{entries.filter(e=>e.id).length} cadastradas · {entries.filter(e=>e.status==='published').length} divulgadas</p>
|
||||
{canRegister && <button className={button} disabled={busy} onClick={()=>void run('register')}>Cadastrar ou recuperar as 34 fichas privadamente</button>}
|
||||
{entries.every(e=>e.id) && <button className={button+' ml-3'} disabled={busy} onClick={()=>void run('preview')}>Pré-visualizar divulgação das 34 fichas</button>}
|
||||
<ul className="my-5 space-y-3">{entries.map(e=><li key={e.key} className="rounded border p-3"><h2>{e.title}</h2><p>{e.summary}</p><p>{e.corridor} · {e.status??'Por cadastrar'}</p>{e.id&&<Link className="underline" href={`/minhas-oportunidades/${e.id}/edit`}>Rever e editar a ficha</Link>}</li>)}</ul>
|
||||
{!!previews.length && <section aria-label="Prévia pública das 34 fichas"><h2>Conteúdo a divulgar — Em preparação</h2>{previews.map(p=><details key={p.id} className="my-3 rounded border p-3"><summary>{p.projection.title}</summary><p>{p.projection.summary}</p><p className="whitespace-pre-line">{p.projection.description}</p></details>)}<label className="block">Motivo<textarea className={control} value={reason} onChange={e=>setReason(e.target.value)}/></label><label className="block"><input type="checkbox" checked={confirmed} onChange={e=>setConfirmed(e.target.checked)}/>Confirmo a divulgação destes resumos em preparação; não é autorização de execução.</label><button className={button} disabled={busy||!confirmed||reason.trim().length<20} onClick={()=>void run('disclose')}>Divulgar as 34 oportunidades no catálogo</button></section>}
|
||||
{message&&<p role="status">{message}</p>}<Link className="block underline" href="/oportunidades?sector=agronegocio">Consultar catálogo de Agronegócio</Link>
|
||||
</Management>;
|
||||
}
|
||||
@@ -17,6 +17,7 @@ type Entry = {
|
||||
updated_at: string;
|
||||
deleted_at: string | null;
|
||||
can_edit?: boolean;
|
||||
can_promote?: boolean;
|
||||
working_status?: string;
|
||||
draft_title?: string;
|
||||
publication?: { scope: string; label: string; public_catalog: boolean };
|
||||
@@ -232,6 +233,7 @@ export default function Opportunities({
|
||||
<p>Atualizado: {r.updated_at}</p>
|
||||
<div className="flex flex-wrap gap-4">
|
||||
<Link href={`${basePath}/${r.id}/view`}>Ver</Link>
|
||||
{r.can_promote && <Link href={`/minhas-oportunidades/${r.id}/divulgacao`}>Divulgação promocional</Link>}
|
||||
{r.can_edit !== false && (
|
||||
<Link href={`${basePath}/${r.id}/edit`}>
|
||||
{r.deleted_at || r.status === 'archived'
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { ClassificationReview } from '@/components/opportunity-classification';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { valueText } from '@/lib/value-text';
|
||||
import { modalityLabels } from '@/components/opportunity-search-filters';
|
||||
import OpportunityProfileActions from '@/components/opportunity-profile-actions';
|
||||
import OpportunityContactForm from '@/components/opportunity-contact-form';
|
||||
import OpportunityCanonicalFields, {
|
||||
@@ -74,9 +75,11 @@ export default function OpportunityDraft({
|
||||
workflowParticipants,
|
||||
publicationPreview,
|
||||
publicationState,
|
||||
promotionHref,
|
||||
auth,
|
||||
canEditDraft = false,
|
||||
} = usePage<{
|
||||
promotionHref?: string | null;
|
||||
basePath?: string;
|
||||
profileMode?: boolean;
|
||||
profileOrganization?: string | null;
|
||||
@@ -245,6 +248,15 @@ export default function OpportunityDraft({
|
||||
<Link href={basePath}>
|
||||
{profileMode ? 'Minhas oportunidades' : 'Voltar à gestão'}
|
||||
</Link>
|
||||
{promotionHref && <Link className="ml-3 underline" href={promotionHref}>Divulgação promocional — Em preparação</Link>}
|
||||
{!!profileContext?.corridor_agribusiness && (
|
||||
<section className="my-4 space-y-2 rounded border p-4">
|
||||
<h2 className="font-semibold">Origem e enquadramento da oportunidade</h2>
|
||||
<p>{valueText((profileContext.corridor_agribusiness as Record<string, unknown>).corridor)}</p>
|
||||
<p>Fonte: {valueText((profileContext.corridor_agribusiness as Record<string, unknown>).source)}</p>
|
||||
<p>Em preparação. O corredor indicado na fonte não confirma implantação, promotor, viabilidade ou financiamento. Complete a ficha e reveja a prévia antes de divulgar.</p>
|
||||
</section>
|
||||
)}
|
||||
{record && (
|
||||
<Link
|
||||
href={`/investimentos/iniciar?source=opportunity:${record.id}`}
|
||||
@@ -330,7 +342,7 @@ export default function OpportunityDraft({
|
||||
{c.organization_name ??
|
||||
c.organization_id ??
|
||||
'Âmbito individual'}{' '}
|
||||
— {c.type}
|
||||
— {modalityLabels[c.type] ?? c.type}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { profileJson, ProfileValidationError } from '@/lib/profile-json';
|
||||
import { Management, Field, control, button } from './shared';
|
||||
|
||||
type Draft = {title: string; summary: string; description: string; limitations: string; source_reference: string; edition: string; source_date: string; sector_id: number | null; territory_ids: string[]};
|
||||
type Projection = {title: string; summary: string; description: string; sector_id: number | null; maturity_label: string; territories: {id: string; label: string}[]};
|
||||
type Preview = {token: string; action: 'disclose' | 'withdraw'; projection: Projection; current: {title: string; summary: string; description: string; status: string}};
|
||||
|
||||
export default function OpportunityPromotion({record, initial, etag, publicNow, reauthenticationRequired, sectors, territories, history}: {
|
||||
record: {id: number; reference: string}; initial: Draft; etag: string; publicNow: boolean; reauthenticationRequired: boolean;
|
||||
sectors: {id: number; name: string}[]; territories: {id: string; name: string; location_type: string}[];
|
||||
history: {id: string; action: string; actor_user_id: number; occurred_at: string}[];
|
||||
}) {
|
||||
const [draft, setDraft] = useState<Draft>({...initial, source_date: initial.source_date ?? ''});
|
||||
const [preview, setPreview] = useState<Preview | null>(null);
|
||||
const [operationKey, setOperationKey] = useState(createOperationKey);
|
||||
const [reason, setReason] = useState('');
|
||||
const [confirmed, setConfirmed] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
const [errors, setErrors] = useState<Record<string,string>>({});
|
||||
const [needsMfa, setNeedsMfa] = useState(reauthenticationRequired);
|
||||
function change<K extends keyof Draft>(key: K, value: Draft[K]) { setDraft(current => ({...current, [key]:value})); setPreview(null); setConfirmed(false); }
|
||||
function report(error: unknown) {setMessage(error instanceof Error ? error.message : 'Não foi possível concluir. A ficha anterior foi preservada.'); setErrors(error instanceof ProfileValidationError ? error.fields : {}); if(error instanceof ProfileValidationError && error.reauthenticate)setNeedsMfa(true);}
|
||||
function renewAuthentication() { router.post('/logout', {}, {onSuccess:()=>router.visit(`/minhas-oportunidades/${record.id}/divulgacao`)}); }
|
||||
async function prepare(action: 'disclose' | 'withdraw') {
|
||||
setBusy(true); setMessage(''); setErrors({}); setPreview(null); setConfirmed(false);
|
||||
try { const result = await profileJson(`/minhas-oportunidades/${record.id}/divulgacao/previa`, {...draft, etag, action}); setPreview(result); setOperationKey(createOperationKey()); }
|
||||
catch (error) { report(error); } finally { setBusy(false); }
|
||||
}
|
||||
async function publish() {
|
||||
if (!preview || !confirmed) return;
|
||||
setBusy(true); setErrors({});
|
||||
try {const result = await profileJson(`/minhas-oportunidades/${record.id}/divulgacao/confirmar`, {token:preview.token, operation_key:operationKey, reason, confirm:confirmed});
|
||||
setMessage(result.message); setPreview(null); setConfirmed(false); router.reload();
|
||||
} catch (error) { report(error); } finally {setBusy(false);}
|
||||
}
|
||||
const labels: Record<string,string> = {promotional_summary_published:'Resumo divulgado', promotional_summary_updated:'Resumo actualizado', promotional_summary_withdrawn:'Resumo retirado'};
|
||||
return <Management title={`Divulgação promocional — ${record.reference}`}>
|
||||
<Link className="underline" href={`/minhas-oportunidades/${record.id}/view`}>Voltar à oportunidade</Link>
|
||||
<p>Prepare o resumo público e reveja a prévia antes de confirmar. A divulgação fica identificada como <strong>Em preparação</strong> e não autoriza a execução do investimento. Documentos e contactos do cadastro continuam privados.</p>
|
||||
<p role="status">{publicNow ? 'Resumo actualmente divulgado.' : 'Resumo não divulgado.'} {message}</p>
|
||||
{needsMfa && <p role="alert">Entre novamente com a sua conta e MFA para confirmar esta operação. O cadastro guardado permanece disponível; a prévia ainda não confirmada terá de ser preparada novamente. <button className="underline" onClick={renewAuthentication}>Renovar entrada com MFA</button></p>}
|
||||
{Object.entries(errors).map(([key,value]) => <p role="alert" key={key}>{key}: {value}</p>)}
|
||||
<form className="space-y-4 rounded border p-5" onSubmit={e=>{e.preventDefault(); void prepare('disclose');}}>
|
||||
<Field label="Título público"><input required className={control} maxLength={255} value={draft.title} onChange={e=>change('title',e.target.value)}/></Field>
|
||||
<Field label="Resumo público"><textarea required className={control} maxLength={499} value={draft.summary} onChange={e=>change('summary',e.target.value)}/></Field>
|
||||
<Field label="Descrição pública"><textarea className={control} maxLength={6000} value={draft.description} onChange={e=>change('description',e.target.value)}/></Field>
|
||||
<Field label="Limitações e lacunas conhecidas"><textarea className={control} value={draft.limitations} onChange={e=>change('limitations',e.target.value)}/></Field>
|
||||
<Field label="Fonte do resumo"><textarea className={control} value={draft.source_reference} onChange={e=>change('source_reference',e.target.value)}/></Field>
|
||||
<Field label="Edição"><input className={control} value={draft.edition} onChange={e=>change('edition',e.target.value)}/></Field>
|
||||
<Field label="Data-base"><input className={control} type="date" value={draft.source_date} onChange={e=>change('source_date',e.target.value)}/></Field>
|
||||
<Field label="Sector divulgado"><select className={control} value={draft.sector_id ?? ''} onChange={e=>change('sector_id',e.target.value ? Number(e.target.value):null)}><option value="">Por indicar</option>{sectors.map(s=><option key={s.id} value={s.id}>{s.name}</option>)}</select></Field>
|
||||
<Field label="Acrescentar abrangência territorial documentada"><select className={control} value="" onChange={e=>{if(e.target.value && !draft.territory_ids.includes(e.target.value))change('territory_ids',[...draft.territory_ids,e.target.value]);}}><option value="">Seleccionar território existente</option>{territories.map(t=><option key={t.id} value={t.id}>{t.name} · {t.location_type}</option>)}</select></Field>
|
||||
<p>Seleccione apenas a abrangência que pretende divulgar e cuja origem está identificada. Abrangência não comprova implantação ou disponibilidade de terreno. Sem selecção, a localização fica por indicar.</p>
|
||||
<ul>{draft.territory_ids.map(id=><li key={id}>{territories.find(t=>t.id===id)?.name ?? 'Referência anterior indisponível'} <button type="button" className="underline" onClick={()=>change('territory_ids',draft.territory_ids.filter(t=>t!==id))}>Remover abrangência</button></li>)}</ul>
|
||||
<button className={button} disabled={busy || needsMfa}>{publicNow ? 'Rever actualização do resumo' : 'Preparar prévia de divulgação'}</button>
|
||||
{publicNow && <button type="button" className={`${button} ml-3`} disabled={busy || needsMfa} onClick={()=>void prepare('withdraw')}>Preparar retirada do resumo</button>}
|
||||
</form>
|
||||
{preview && <section className="space-y-4 rounded border p-5" aria-label="Prévia da divulgação">
|
||||
<h2 className="text-xl font-semibold">{preview.action === 'withdraw' ? 'Rever retirada do catálogo' : 'Prévia do conteúdo público'}</h2>
|
||||
<p><strong>{preview.projection.maturity_label}</strong></p>
|
||||
<h3>{preview.projection.title}</h3><p>{preview.projection.summary}</p><p className="whitespace-pre-wrap">{preview.projection.description}</p>
|
||||
<p>Sector: {sectors.find(s=>s.id===preview.projection.sector_id)?.name ?? 'Por indicar'}</p>
|
||||
<ul>{preview.projection.territories.map(t=><li key={t.id}>{t.label}</li>)}</ul>
|
||||
{!preview.projection.territories.length && <p>Abrangência territorial por indicar.</p>}
|
||||
<p>Esta prévia ainda não alterou o portal público. {preview.action === 'withdraw' ? 'A confirmação retira o resumo da consulta pública e preserva o cadastro.' : 'Só este texto e o enquadramento apresentado serão divulgados; os anexos e contactos não são incluídos.'}</p>
|
||||
<Field label="Motivo da divulgação, alteração ou retirada"><textarea required className={control} minLength={10} maxLength={1000} value={reason} onChange={e=>setReason(e.target.value)}/></Field>
|
||||
<label className="block"><input type="checkbox" checked={confirmed} onChange={e=>setConfirmed(e.target.checked)}/> Confirmo o conteúdo público desta prévia e a operação indicada.</label>
|
||||
<button className={button} disabled={busy || !confirmed || reason.trim().length<10} onClick={()=>void publish()}>{preview.action === 'withdraw' ? 'Confirmar retirada do resumo' : 'Confirmar divulgação do resumo'}</button>
|
||||
<button className="ml-3 underline" disabled={busy} onClick={()=>{setPreview(null);setConfirmed(false);}}>Cancelar prévia</button>
|
||||
</section>}
|
||||
<section aria-label="Histórico da divulgação"><h2 className="text-xl font-semibold">Histórico da divulgação</h2><ul>{history.map(h=><li key={h.id}>{labels[h.action] ?? h.action} · {h.occurred_at} · responsável {h.actor_user_id}</li>)}</ul></section>
|
||||
</Management>;
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import ProfileNavigation from '@/components/profile-navigation';
|
||||
import ContentManagementEntry from '@/components/content-management-entry';
|
||||
import { Head, Link, usePage } from '@inertiajs/react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { cloneElement, isValidElement, useId } from 'react';
|
||||
@@ -60,6 +61,7 @@ export function Management({
|
||||
return (
|
||||
<div className="space-y-6 p-4 md:p-8">
|
||||
<Head title={title} />
|
||||
<ContentManagementEntry />
|
||||
{auth?.canManagePortal && basePath !== '/minhas-oportunidades' ? (
|
||||
<nav
|
||||
className="flex flex-wrap gap-4 text-sm underline"
|
||||
|
||||
@@ -1,14 +1,35 @@
|
||||
import { Link, useForm } from '@inertiajs/react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Management, Field, button, control } from '../management/shared';
|
||||
type Content = { body: string; image_resource_id: number | null };
|
||||
import EditorialReading, {
|
||||
type EditorialArticle,
|
||||
} from '@/components/editorial-reading';
|
||||
type Content = {
|
||||
body: string;
|
||||
image_resource_id: number | null;
|
||||
image_mode?: string;
|
||||
};
|
||||
export default function ArticleEditor({
|
||||
resource,
|
||||
content,
|
||||
source,
|
||||
images,
|
||||
revisions,
|
||||
}: {
|
||||
resource: { id: number; title: string; metadata_version: number };
|
||||
resource: {
|
||||
id: number;
|
||||
title: string;
|
||||
metadata_version: number;
|
||||
published: boolean;
|
||||
};
|
||||
content: Content | null;
|
||||
source?: {
|
||||
source_url?: string;
|
||||
image_source_url?: string;
|
||||
published_at?: string;
|
||||
modified_at?: string;
|
||||
legacy_id?: number;
|
||||
} | null;
|
||||
images: { id: number; title: string }[];
|
||||
revisions: {
|
||||
revision_no: number;
|
||||
@@ -16,28 +37,107 @@ export default function ArticleEditor({
|
||||
created_at: string;
|
||||
}[];
|
||||
}) {
|
||||
const form = useForm({
|
||||
const initial = () => ({
|
||||
body: content?.body ?? '',
|
||||
image_resource_id: content?.image_resource_id
|
||||
? String(content.image_resource_id)
|
||||
: '',
|
||||
image_mode:
|
||||
content?.image_mode ??
|
||||
(content?.image_resource_id ? 'selected' : 'none'),
|
||||
metadata_version: resource.metadata_version,
|
||||
});
|
||||
const form = useForm(initial());
|
||||
const [preview, setPreview] = useState<EditorialArticle | null>(null);
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
useEffect(() => {
|
||||
form.setData(initial());
|
||||
setPreview(null);
|
||||
setError('');
|
||||
}, [resource.id, resource.metadata_version]);
|
||||
useEffect(() => {
|
||||
setPreview(null);
|
||||
}, [form.data.body, form.data.image_mode, form.data.image_resource_id]);
|
||||
const showPreview = async () => {
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
const token = document.cookie
|
||||
.split('; ')
|
||||
.find((v) => v.startsWith('XSRF-TOKEN='))
|
||||
?.slice(11);
|
||||
const response = await fetch(
|
||||
`/management/portal-services/resources/${resource.id}/article/preview`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
'X-XSRF-TOKEN': decodeURIComponent(token ?? ''),
|
||||
},
|
||||
body: JSON.stringify(form.data),
|
||||
},
|
||||
);
|
||||
const data = await response
|
||||
.json()
|
||||
.catch(() => ({
|
||||
message:
|
||||
'Não foi possível abrir a prévia. Recupere o editor e confirme a sessão e o MFA existentes.',
|
||||
}));
|
||||
if (!response.ok)
|
||||
throw new Error(
|
||||
Object.values(data.errors ?? {})
|
||||
.flat()
|
||||
.join(' ') ||
|
||||
data.message ||
|
||||
'Não foi possível preparar a prévia.',
|
||||
);
|
||||
setPreview(data.article);
|
||||
} catch (e) {
|
||||
setError(
|
||||
e instanceof Error
|
||||
? e.message
|
||||
: 'Não foi possível preparar a prévia.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<Management title={`Editar artigo — ${resource.title}`}>
|
||||
<p>
|
||||
O original permanece intacto na biblioteca. Guardar o corpo
|
||||
retira a publicação até à sua ação expressa no acervo.
|
||||
O original, a origem e as versões permanecem na biblioteca.
|
||||
Guardar cria uma revisão editorial e retira a publicação até à
|
||||
sua acção expressa no acervo.
|
||||
</p>
|
||||
<p role="status">
|
||||
Revisão guardada {resource.metadata_version} ·{' '}
|
||||
{resource.published ? 'Publicado' : 'Rascunho privado'}
|
||||
</p>
|
||||
{source && (
|
||||
<p>
|
||||
Original {source.legacy_id} · publicado em{' '}
|
||||
{source.published_at} · modificado em {source.modified_at}.
|
||||
A imagem de origem mantém a sua referência mesmo quando não
|
||||
existe exemplar disponível.
|
||||
</p>
|
||||
)}
|
||||
<form
|
||||
className="max-w-3xl space-y-5"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
form.put(
|
||||
`/management/portal-services/resources/${resource.id}/article`,
|
||||
);
|
||||
}}
|
||||
>
|
||||
{!!Object.keys(form.errors).length && (
|
||||
<div role="alert">
|
||||
{Object.values(form.errors).join(' ')}
|
||||
</div>
|
||||
)}
|
||||
<Field label="Corpo do artigo" error={form.errors.body}>
|
||||
<textarea
|
||||
className={control}
|
||||
@@ -46,36 +146,93 @@ export default function ArticleEditor({
|
||||
onChange={(e) => form.setData('body', e.target.value)}
|
||||
/>
|
||||
<p>
|
||||
Texto simples. Separe os parágrafos com uma linha em
|
||||
branco.
|
||||
Texto simples, com uma linha em branco entre parágrafos.
|
||||
Se mantiver o texto original, a leitura conserva também
|
||||
a sua formatação; as correcções ficam numa edição
|
||||
separada.
|
||||
</p>
|
||||
</Field>
|
||||
<Field
|
||||
label="Imagem da biblioteca"
|
||||
error={form.errors.image_resource_id}
|
||||
label="Tratamento da imagem"
|
||||
error={form.errors.image_mode}
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={form.data.image_resource_id}
|
||||
value={form.data.image_mode}
|
||||
onChange={(e) =>
|
||||
form.setData('image_resource_id', e.target.value)
|
||||
form.setData('image_mode', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Sem imagem</option>
|
||||
{images.map((i) => (
|
||||
<option key={i.id} value={i.id}>
|
||||
{i.title}
|
||||
</option>
|
||||
))}
|
||||
<option value="original">
|
||||
Manter referência e imagem de origem disponível
|
||||
</option>
|
||||
<option value="selected">
|
||||
Escolher imagem pública da biblioteca
|
||||
</option>
|
||||
<option value="none">
|
||||
Não mostrar imagem nesta edição
|
||||
</option>
|
||||
</select>
|
||||
</Field>
|
||||
<button className={button} disabled={form.processing}>
|
||||
Guardar artigo como rascunho
|
||||
</button>{' '}
|
||||
<Link className="underline" href="/management/portal-services">
|
||||
Voltar ao acervo
|
||||
</Link>
|
||||
{form.data.image_mode === 'selected' && (
|
||||
<Field
|
||||
label="Imagem da biblioteca"
|
||||
error={form.errors.image_resource_id}
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={form.data.image_resource_id}
|
||||
onChange={(e) =>
|
||||
form.setData(
|
||||
'image_resource_id',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Seleccione uma imagem</option>
|
||||
{images.map((i) => (
|
||||
<option key={i.id} value={i.id}>
|
||||
{i.title}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-4">
|
||||
<button className={button} disabled={form.processing}>
|
||||
Guardar artigo como rascunho
|
||||
</button>
|
||||
<button
|
||||
className={button}
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void showPreview()}
|
||||
>
|
||||
Pré-visualizar alterações
|
||||
</button>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/management/portal-services/resources/${resource.id}/article/preview`}
|
||||
>
|
||||
Ler revisão guardada
|
||||
</Link>
|
||||
<Link
|
||||
className="underline"
|
||||
href="/management/portal-services"
|
||||
>
|
||||
Voltar ao acervo para metadados e publicação
|
||||
</Link>
|
||||
</div>
|
||||
</form>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{preview && (
|
||||
<section
|
||||
aria-label="Prévia das alterações"
|
||||
className="my-6 max-w-3xl rounded border p-5"
|
||||
>
|
||||
<EditorialReading article={preview} />
|
||||
</section>
|
||||
)}
|
||||
<h2>Histórico</h2>
|
||||
<ul>
|
||||
{revisions.map((r) => (
|
||||
@@ -86,8 +243,10 @@ export default function ArticleEditor({
|
||||
))}
|
||||
</ul>
|
||||
<p>
|
||||
Título, descrição, autor e fonte são editados em Editar
|
||||
metadados no acervo.
|
||||
Título, descrição, autor, fonte, direitos e acesso são
|
||||
corrigidos em Editar metadados no acervo. Carregue e analise
|
||||
imagens na biblioteca antes de as seleccionar. Publicar continua
|
||||
a ser uma acção separada.
|
||||
</p>
|
||||
</Management>
|
||||
);
|
||||
|
||||
@@ -1,42 +1,27 @@
|
||||
import { Head, Link } from '@inertiajs/react';
|
||||
import { PortalMenu } from '@/layouts/portal-navigation';
|
||||
export default function Article({
|
||||
article,
|
||||
}: {
|
||||
article: {
|
||||
id: number;
|
||||
title: string;
|
||||
description: string | null;
|
||||
author: string | null;
|
||||
body: string;
|
||||
image_url: string | null;
|
||||
original_url: string;
|
||||
};
|
||||
}) {
|
||||
import EditorialReading, {
|
||||
type EditorialArticle,
|
||||
} from '@/components/editorial-reading';
|
||||
export default function Article({ article }: { article: EditorialArticle }) {
|
||||
return (
|
||||
<>
|
||||
<Head title={article.title} />
|
||||
<PortalMenu />
|
||||
<main className="mx-auto max-w-3xl space-y-6 p-6">
|
||||
<h1 className="text-3xl font-bold">{article.title}</h1>
|
||||
{article.description && <p>{article.description}</p>}
|
||||
{article.author && <p>Autor / entidade: {article.author}</p>}
|
||||
{article.image_url && (
|
||||
<img src={article.image_url} alt="Imagem do artigo" />
|
||||
)}
|
||||
<article className="space-y-5">
|
||||
{article.body.split(/\n\s*\n/).map((p, i) => (
|
||||
<p className="whitespace-pre-wrap" key={i}>
|
||||
{p}
|
||||
</p>
|
||||
))}
|
||||
</article>
|
||||
<Link href={article.original_url} className="underline">
|
||||
Consultar documento original
|
||||
</Link>
|
||||
<EditorialReading article={article} />
|
||||
<p>
|
||||
<Link href="/documentos" className="underline">
|
||||
Voltar à biblioteca
|
||||
<Link
|
||||
href={
|
||||
article.private_preview
|
||||
? `/management/portal-services/resources/${article.id}/article`
|
||||
: '/documentos'
|
||||
}
|
||||
className="underline"
|
||||
>
|
||||
{article.private_preview
|
||||
? 'Voltar ao editor'
|
||||
: 'Voltar à biblioteca'}
|
||||
</Link>
|
||||
</p>
|
||||
</main>
|
||||
|
||||
@@ -105,6 +105,7 @@ export default function LegacySector({
|
||||
? article.group.heading
|
||||
: article.title}
|
||||
</h1>
|
||||
{article.sector?.slug === 'agronegocio' && <Link className="inline-flex rounded-lg bg-emerald-800 px-5 py-3 font-semibold text-white" href="/oportunidades?sector=agronegocio&view=corridors">Explorar oportunidades por corredor</Link>}
|
||||
<p>
|
||||
Explore o setor e prepare a sua ideia com o contexto
|
||||
guardado no dossier.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { router, useForm } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { router, useForm, usePage } from '@inertiajs/react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Management, Field, control, button } from '../management/shared';
|
||||
|
||||
type DocumentFile = {
|
||||
@@ -164,7 +164,11 @@ export default function Manage({
|
||||
legacyContentEnabled = false,
|
||||
documentAccessOnly = false,
|
||||
editorialScopeOnly = false,
|
||||
managementFilters = {},
|
||||
associationOptions = {},
|
||||
}: {
|
||||
managementFilters?: {q?: string; state?: string; intent?: string};
|
||||
associationOptions?: Record<string, {value: string | number; label: string}[]>;
|
||||
legacyContentEnabled?: boolean;
|
||||
documentAccessOnly?: boolean;
|
||||
editorialScopeOnly?: boolean;
|
||||
@@ -206,12 +210,26 @@ export default function Manage({
|
||||
}) {
|
||||
const [editingId, setEditingId] = useState<number | null>(null);
|
||||
const [actionError, setActionError] = useState('');
|
||||
const [query, setQuery] = useState(managementFilters.q ?? '');
|
||||
const [stateFilter, setStateFilter] = useState(managementFilters.state ?? '');
|
||||
const { flash } = usePage<{flash?: {uploaded_document_id?: string}}>().props;
|
||||
const upload = useForm<{
|
||||
file: File | null;
|
||||
original_source: string;
|
||||
issuer: string;
|
||||
}>({ file: null, original_source: '', issuer: '' });
|
||||
const form = useForm<ResourceForm>(emptyResource());
|
||||
intent: string;
|
||||
}>({ file: null, original_source: '', issuer: '', intent: managementFilters.intent ?? 'document' });
|
||||
const form = useForm<ResourceForm>({...emptyResource(), ...(managementFilters.intent === 'legislation' ? {document_type: 'legislation', legislation: true} : {})});
|
||||
const chooseDocument = (id: string) => {
|
||||
const document = documents.find((item) => item.id === id);
|
||||
form.setData((current) => ({...current, document_id: id,
|
||||
issuer: current.issuer || document?.issuer || '',
|
||||
title: current.title || document?.file_name || '',
|
||||
}));
|
||||
};
|
||||
useEffect(() => {
|
||||
if (flash?.uploaded_document_id && !editingId && !form.data.document_id) chooseDocument(flash.uploaded_document_id);
|
||||
}, [flash?.uploaded_document_id]);
|
||||
const setAssociation = (
|
||||
index: number,
|
||||
key: keyof Association,
|
||||
@@ -361,6 +379,7 @@ export default function Manage({
|
||||
))}
|
||||
</section>
|
||||
<form
|
||||
id="receber"
|
||||
className="space-y-4 rounded border p-5"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
@@ -420,6 +439,7 @@ export default function Manage({
|
||||
</form>
|
||||
|
||||
{!documentAccessOnly && <>
|
||||
{managementFilters.intent === 'legislation' && <p className="rounded border p-4">Nova legislação: reutilize o original, complete diploma/tipo, entidade emitente, número, datas e âmbito. Registe alterações e revogações nas associações. Publicar para consulta não activa cálculos no simulador.</p>}
|
||||
<form
|
||||
className="space-y-4 rounded border p-5"
|
||||
onSubmit={(e) => {
|
||||
@@ -458,9 +478,7 @@ export default function Manage({
|
||||
required
|
||||
className={control}
|
||||
value={form.data.document_id}
|
||||
onChange={(e) =>
|
||||
form.setData('document_id', e.target.value)
|
||||
}
|
||||
onChange={(e) => chooseDocument(e.target.value)}
|
||||
>
|
||||
<option value="">
|
||||
Seleccionar ficheiro ou registo existente
|
||||
@@ -925,6 +943,8 @@ export default function Manage({
|
||||
'document',
|
||||
'investment_type',
|
||||
'legal_source',
|
||||
'sector',
|
||||
'opportunity',
|
||||
'requirement',
|
||||
]
|
||||
.filter(
|
||||
@@ -934,8 +954,8 @@ export default function Manage({
|
||||
requirementAssociationsEnabled,
|
||||
)
|
||||
.map((v) => (
|
||||
<option key={v}>
|
||||
{v}
|
||||
<option key={v} value={v}>
|
||||
{({theme:'Tema', module:'Módulo',activity:'Actividade',stage:'Etapa',procedure:'Procedimento',entity:'Entidade',territory:'Território',document:'Documento / diploma',investment_type:'Modalidade de investimento',legal_source:'Fonte legal',requirement:'Requisito',sector:'Sector',opportunity:'Oportunidade'} as Record<string,string>)[v] ?? v}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
@@ -974,6 +994,12 @@ export default function Manage({
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
) : associationOptions[association.target_type] ? (
|
||||
<select className={control} required value={association.target_key} onChange={(e) => setAssociation(index, 'target_key', e.target.value)}>
|
||||
<option value="">Seleccione um registo existente</option>
|
||||
{association.target_key && !associationOptions[association.target_type].some((o) => String(o.value) === association.target_key) && <option value={association.target_key}>Referência histórica guardada</option>}
|
||||
{associationOptions[association.target_type].map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
|
||||
</select>
|
||||
) : (
|
||||
<input
|
||||
required
|
||||
@@ -1221,13 +1247,20 @@ export default function Manage({
|
||||
</section>
|
||||
)}
|
||||
|
||||
<h2 className="text-xl font-bold">
|
||||
<h2 id="conteudos" className="text-xl font-bold">
|
||||
Registos, pendências e duplicados por rever
|
||||
</h2>
|
||||
<form className="flex flex-wrap gap-3 rounded border p-4" aria-label="Pesquisar conteúdos" onSubmit={(e) => {e.preventDefault(); router.get('/management/portal-services', {q:query,state:stateFilter}, {preserveState:true,preserveScroll:true});}}>
|
||||
<Field label="Pesquisar título, ficheiro, número ou entidade"><input className={control} value={query} onChange={(e) => setQuery(e.target.value)} /></Field>
|
||||
<Field label="Estado do conteúdo"><select className={control} value={stateFilter} onChange={(e) => setStateFilter(e.target.value)}><option value="">Todos</option><option value="draft">Rascunhos</option><option value="published">Publicados</option><option value="withdrawn">Retirados</option></select></Field>
|
||||
<button className={button}>Pesquisar conteúdos</button>
|
||||
</form>
|
||||
<p>Mostram-se até 200 registos por pesquisa. Refine o título ou o estado para localizar conteúdos anteriores.</p>
|
||||
{!resources.length && <p role="status">Sem conteúdos correspondentes no seu âmbito de acesso.</p>}
|
||||
{resources.map((r) => (
|
||||
<article key={r.id} className="space-y-3 rounded border p-4">
|
||||
<h3 className="font-bold">
|
||||
{r.title} · {r.published ? 'Publicado' : 'Rascunho'}
|
||||
{r.title} · {r.published ? 'Publicado' : r.revisions.some((v) => ['unpublished', 'withdrawn'].includes(v.change_type)) ? 'Retirado' : 'Rascunho'}
|
||||
</h3>
|
||||
<p>
|
||||
Ficheiro: {r.file_name} · {r.file_status} ·{' '}
|
||||
@@ -1352,6 +1385,7 @@ export default function Manage({
|
||||
>
|
||||
Editar artigo
|
||||
</a>
|
||||
<a className={button} href={`/management/portal-services/resources/${r.id}/article/preview`}>Ler / pré-visualizar artigo</a>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
|
||||
@@ -0,0 +1,832 @@
|
||||
import { Link, router, useForm } from '@inertiajs/react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Frame, card, button } from '@/pages/investment/shared';
|
||||
import {
|
||||
Field,
|
||||
control,
|
||||
labels,
|
||||
acts,
|
||||
NoticeContent,
|
||||
type Draft,
|
||||
type Lot,
|
||||
type Attachment,
|
||||
type Payload,
|
||||
} from './shared';
|
||||
type Choice = {
|
||||
id: string | number;
|
||||
name?: string;
|
||||
title?: string;
|
||||
location_type?: string;
|
||||
published?: boolean;
|
||||
malware_scan_status?: string;
|
||||
};
|
||||
type References = {
|
||||
regimes: Record<string, string>;
|
||||
acts: Record<string, string>;
|
||||
organizations: Choice[];
|
||||
sectors: Choice[];
|
||||
territories: Choice[];
|
||||
opportunities: Choice[];
|
||||
projects: Choice[];
|
||||
documents: Choice[];
|
||||
};
|
||||
type RecordData = {
|
||||
id: string;
|
||||
version: number;
|
||||
draft: Draft;
|
||||
published: boolean;
|
||||
};
|
||||
type Plan = {
|
||||
id: string;
|
||||
version: number;
|
||||
act: string;
|
||||
payload: Payload;
|
||||
hash: string;
|
||||
};
|
||||
const dates = [
|
||||
'origin_published_at',
|
||||
'clarifications_at',
|
||||
'deadline',
|
||||
'opening_at',
|
||||
];
|
||||
const groups: [string, string[]][] = [
|
||||
[
|
||||
'Identificação e objecto',
|
||||
['title', 'reference', 'modality', 'object', 'quantities'],
|
||||
],
|
||||
[
|
||||
'Regime e financiamento',
|
||||
[
|
||||
'financier',
|
||||
'instrument',
|
||||
'edition',
|
||||
'rule_source',
|
||||
'financing_agreement',
|
||||
],
|
||||
],
|
||||
['Participação', ['eligibility', 'requirements', 'proposal_validity']],
|
||||
[
|
||||
'Calendário e entrega',
|
||||
[
|
||||
'origin_published_at',
|
||||
'clarifications_at',
|
||||
'deadline',
|
||||
'opening_at',
|
||||
'delivery_channel',
|
||||
'delivery_address',
|
||||
'delivery_url',
|
||||
],
|
||||
],
|
||||
['Divulgação e contacto', ['origin_url', 'dissemination']],
|
||||
];
|
||||
export default function Edit({
|
||||
record,
|
||||
references,
|
||||
history,
|
||||
}: {
|
||||
record: RecordData | null;
|
||||
references: References;
|
||||
history: {
|
||||
version: number;
|
||||
act: string;
|
||||
reason: string;
|
||||
actor_id: number;
|
||||
published_at: string | null;
|
||||
created_at: string;
|
||||
}[];
|
||||
}) {
|
||||
const empty: Draft = {
|
||||
timezone: 'Africa/Maputo',
|
||||
lots: [],
|
||||
attachments: [],
|
||||
contact_authorized: false,
|
||||
};
|
||||
const form = useForm({
|
||||
version: record?.version ?? 0,
|
||||
reason: '',
|
||||
draft: record?.draft ?? empty,
|
||||
});
|
||||
const [act, setAct] = useState(
|
||||
record?.published ? 'clarification' : 'initial',
|
||||
);
|
||||
const [preview, setPreview] = useState<Plan | null>(null);
|
||||
const [message, setMessage] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [saved, setSaved] = useState(true);
|
||||
useEffect(() => {
|
||||
form.setData({
|
||||
version: record?.version ?? 0,
|
||||
reason: '',
|
||||
draft: record?.draft ?? empty,
|
||||
});
|
||||
setPreview(null);
|
||||
setSaved(true);
|
||||
}, [record?.id, record?.version]); // A server version is the recovery boundary.
|
||||
const change = (key: string, value: Draft[string]) => {
|
||||
form.setData('draft', { ...form.data.draft, [key]: value });
|
||||
setPreview(null);
|
||||
setSaved(false);
|
||||
};
|
||||
const value = (key: string) => String(form.data.draft[key] ?? '');
|
||||
const select = (key: string, label: string, choices: Choice[]) => (
|
||||
<Field label={label}>
|
||||
<select
|
||||
className={control}
|
||||
value={value(key)}
|
||||
onChange={(e) =>
|
||||
change(
|
||||
key,
|
||||
e.target.value
|
||||
? key === 'sector_id' || key === 'opportunity_id'
|
||||
? Number(e.target.value)
|
||||
: e.target.value
|
||||
: null,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{choices.map((o) => (
|
||||
<option key={o.id} value={o.id}>
|
||||
{o.name ?? o.title}
|
||||
{o.location_type ? ` · ${o.location_type}` : ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
);
|
||||
const input = (key: string, label?: string) => (
|
||||
<Field key={key} label={label ?? labels[key] ?? key}>
|
||||
{dates.includes(key) ? (
|
||||
<input
|
||||
type="datetime-local"
|
||||
className={control}
|
||||
value={value(key)}
|
||||
onChange={(e) => change(key, e.target.value)}
|
||||
/>
|
||||
) : (
|
||||
<textarea
|
||||
className={control}
|
||||
rows={key === 'object' ? 4 : 2}
|
||||
value={value(key)}
|
||||
onChange={(e) => change(key, e.target.value)}
|
||||
/>
|
||||
)}
|
||||
</Field>
|
||||
);
|
||||
const lots = (form.data.draft.lots ?? []) as Lot[];
|
||||
const attachments = (form.data.draft.attachments ?? []) as Attachment[];
|
||||
const makePreview = async () => {
|
||||
setBusy(true);
|
||||
setMessage('');
|
||||
try {
|
||||
const token = document.cookie
|
||||
.split('; ')
|
||||
.find((v) => v.startsWith('XSRF-TOKEN='))
|
||||
?.slice(11);
|
||||
const response = await fetch(
|
||||
`/management/concursos/${record!.id}/previa`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
'X-XSRF-TOKEN': decodeURIComponent(token ?? ''),
|
||||
},
|
||||
body: JSON.stringify({ act }),
|
||||
},
|
||||
);
|
||||
const body = await response.json();
|
||||
if (!response.ok)
|
||||
throw new Error(
|
||||
Object.values(body.errors ?? {})
|
||||
.flat()
|
||||
.join(' ') ||
|
||||
body.message ||
|
||||
'Não foi possível preparar a prévia.',
|
||||
);
|
||||
setPreview(body);
|
||||
} catch (error) {
|
||||
setMessage(
|
||||
error instanceof Error ? error.message : 'Erro de ligação.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<Frame
|
||||
title={record ? 'Editar concurso/anúncio' : 'Novo concurso/anúncio'}
|
||||
>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<Link className="underline" href="/management/concursos">
|
||||
Recuperar concursos
|
||||
</Link>
|
||||
<Link className="underline" href="/gestao-conteudos">
|
||||
Entrada única de gestão
|
||||
</Link>
|
||||
<a
|
||||
className="underline"
|
||||
href="/management/portal-services?intent=document#receber"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Carregar / gerir documentos e scan na biblioteca (outra
|
||||
página)
|
||||
</a>
|
||||
<button
|
||||
className="underline"
|
||||
type="button"
|
||||
onClick={() => router.reload({ only: ['references'] })}
|
||||
>
|
||||
Actualizar opções da biblioteca
|
||||
</button>
|
||||
</div>
|
||||
<p>
|
||||
Os campos destinam-se à divulgação após revisão da prévia,
|
||||
excepto as notas internas, os anexos não públicos e o contacto
|
||||
sem autorização. O vínculo a um cadastro privado não publica os
|
||||
seus dados.
|
||||
</p>
|
||||
<p>
|
||||
O rascunho pode ficar incompleto. Alterações guardadas não
|
||||
substituem o acto público; reveja a prévia e publique
|
||||
explicitamente. Publicar concurso não publica a oportunidade nem
|
||||
recebe propostas.
|
||||
</p>
|
||||
<p role="status">
|
||||
{record
|
||||
? `Versão guardada ${record.version}. ${saved ? 'Preparação recuperada do servidor.' : 'Há alterações por guardar.'}`
|
||||
: 'Preparação ainda não guardada.'}
|
||||
</p>
|
||||
{!!Object.keys(form.errors).length && (
|
||||
<div role="alert">
|
||||
{Object.values(form.errors).map((error, i) => (
|
||||
<p key={i}>{error}</p>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<form
|
||||
className="space-y-5"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
setPreview(null);
|
||||
record
|
||||
? form.put(`/management/concursos/${record.id}`)
|
||||
: form.post('/management/concursos');
|
||||
}}
|
||||
>
|
||||
<section className={`${card} grid gap-3 md:grid-cols-2`}>
|
||||
{select(
|
||||
'organization_id',
|
||||
'Entidade contratante existente',
|
||||
references.organizations,
|
||||
)}
|
||||
{select(
|
||||
'opportunity_id',
|
||||
'Oportunidade relacionada existente',
|
||||
references.opportunities,
|
||||
)}
|
||||
{select(
|
||||
'project_id',
|
||||
'Projecto existente',
|
||||
references.projects,
|
||||
)}
|
||||
{select('sector_id', 'Sector', references.sectors)}
|
||||
{select(
|
||||
'territory_id',
|
||||
'Localização existente',
|
||||
references.territories,
|
||||
)}
|
||||
<p>
|
||||
Os vínculos reutilizam os cadastros; não criam nova
|
||||
entidade, oportunidade, projecto ou limite. Referências
|
||||
privadas não são transformadas em conteúdo público.
|
||||
</p>
|
||||
</section>
|
||||
<section className={card}>
|
||||
<h2 className="text-xl font-semibold">
|
||||
Regime do procedimento
|
||||
</h2>
|
||||
<Field label="Regime">
|
||||
<select
|
||||
className={control}
|
||||
value={value('regime')}
|
||||
onChange={(e) => change('regime', e.target.value)}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{Object.entries(references.regimes).map(
|
||||
([v, l]) => (
|
||||
<option key={v} value={v}>
|
||||
{l}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
</Field>
|
||||
{value('regime') === 'state' ? (
|
||||
<>
|
||||
<p>
|
||||
Contratação do Estado: identifique a modalidade,
|
||||
o instrumento e a edição aplicáveis.{' '}
|
||||
<a
|
||||
className="underline"
|
||||
href="https://www.ufsa.gov.mz/divnovoreg.php"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
UFSA — Decreto n.º 79/2022
|
||||
</a>
|
||||
. A referência não atribui automaticamente
|
||||
requisitos ou prazos a todos os procedimentos.
|
||||
</p>
|
||||
{input(
|
||||
'responsible_unit',
|
||||
'UGEA / unidade responsável quando aplicável',
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p>
|
||||
{value('regime') === 'external' ? (
|
||||
<>
|
||||
<a
|
||||
className="underline"
|
||||
href="https://www.worldbank.org/ext/en/what-we-do/project-procurement/framework"
|
||||
>
|
||||
Quadro e documentos normalizados do
|
||||
Banco Mundial
|
||||
</a>{' '}
|
||||
são referências; indique a edição e o
|
||||
acordo efectivamente aplicáveis.
|
||||
</>
|
||||
) : (
|
||||
'Use as regras documentadas da entidade e deste procedimento.'
|
||||
)}{' '}
|
||||
UGEA, Cadastro Único, garantias e abertura
|
||||
pública não são impostos a este regime.
|
||||
</p>
|
||||
{input(
|
||||
'responsible_unit',
|
||||
'Unidade responsável (quando aplicável)',
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<Field label="Obras, bens ou serviços">
|
||||
<select
|
||||
className={control}
|
||||
value={value('object_kind')}
|
||||
onChange={(e) =>
|
||||
change('object_kind', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{Object.entries({
|
||||
works: 'Obras',
|
||||
goods: 'Bens',
|
||||
services: 'Serviços',
|
||||
mixed: 'Misto',
|
||||
other: 'Outro',
|
||||
}).map(([v, l]) => (
|
||||
<option key={v} value={v}>
|
||||
{l}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
</section>
|
||||
{groups.map(([title, fields]) => (
|
||||
<section className={card} key={title}>
|
||||
<h2 className="mb-3 text-xl font-semibold">{title}</h2>
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
{fields.map((key) =>
|
||||
input(
|
||||
key,
|
||||
key === 'title'
|
||||
? 'Título do concurso/anúncio'
|
||||
: undefined,
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
))}
|
||||
<section className={`${card} space-y-3`}>
|
||||
<h2 className="text-xl font-semibold">
|
||||
Garantias e prazo mínimo documentado
|
||||
</h2>
|
||||
<Field label="Garantias exigidas neste procedimento">
|
||||
<select
|
||||
className={control}
|
||||
value={value('guarantee_status')}
|
||||
onChange={(e) =>
|
||||
change('guarantee_status', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="unknown">
|
||||
Por determinar nos documentos
|
||||
</option>
|
||||
<option value="required">
|
||||
Exigidas nos documentos
|
||||
</option>
|
||||
<option value="not_required">Não exigidas</option>
|
||||
</select>
|
||||
</Field>
|
||||
{value('guarantee_status') === 'required' &&
|
||||
input('guarantees')}
|
||||
<Field label="Fuso horário IANA do procedimento">
|
||||
<input
|
||||
className={control}
|
||||
value={value('timezone')}
|
||||
onChange={(e) => change('timezone', e.target.value)}
|
||||
placeholder="Africa/Maputo"
|
||||
/>
|
||||
</Field>
|
||||
<p>
|
||||
As datas e horas introduzidas pertencem a este fuso.
|
||||
Publicação no InvesteMoz é registada separadamente pelo
|
||||
servidor; não reinicia o prazo.
|
||||
</p>
|
||||
<Field label="Prazo mínimo documentado em dias (opcional)">
|
||||
<input
|
||||
className={control}
|
||||
type="number"
|
||||
min="0"
|
||||
value={value('minimum_days')}
|
||||
onChange={(e) =>
|
||||
change(
|
||||
'minimum_days',
|
||||
e.target.value === ''
|
||||
? null
|
||||
: Number(e.target.value),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
{form.data.draft.minimum_days !== null &&
|
||||
form.data.draft.minimum_days !== undefined && (
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
{input('minimum_source')}
|
||||
{input('minimum_edition')}
|
||||
{input('minimum_modality')}
|
||||
<Field label="Contagem documentada">
|
||||
<select
|
||||
className={control}
|
||||
value={value('minimum_day_basis')}
|
||||
onChange={(e) =>
|
||||
change(
|
||||
'minimum_day_basis',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
<option value="calendar">
|
||||
Dias corridos
|
||||
</option>
|
||||
<option value="business">
|
||||
Dias úteis — calendário documentado
|
||||
</option>
|
||||
</select>
|
||||
</Field>
|
||||
{value('minimum_day_basis') === 'business' && (
|
||||
<>
|
||||
{input(
|
||||
'minimum_calendar_source',
|
||||
'Fonte do calendário aplicável e abrangência de feriados',
|
||||
)}
|
||||
{input(
|
||||
'minimum_working_days',
|
||||
'Dias de trabalho documentados: 1=segunda a 7=domingo, separados por vírgula',
|
||||
)}
|
||||
{input(
|
||||
'minimum_holidays',
|
||||
'Feriados / exclusões documentados (AAAA-MM-DD, separados por espaço ou vírgula)',
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<p>
|
||||
Sem prazo parametrizado não é presumido um mínimo geral.
|
||||
A contagem em dias úteis usa exclusivamente os dias de
|
||||
trabalho e exclusões do calendário documentado neste
|
||||
registo; não adopta um calendário nacional por
|
||||
suposição.
|
||||
</p>
|
||||
</section>
|
||||
<section className={`${card} space-y-3`}>
|
||||
<h2 className="text-xl font-semibold">Lotes</h2>
|
||||
{lots.map((lot, i) => (
|
||||
<fieldset
|
||||
className="grid gap-3 rounded border p-3 md:grid-cols-3"
|
||||
key={i}
|
||||
>
|
||||
<legend>Lote {i + 1}</legend>
|
||||
{(
|
||||
['code', 'description', 'quantities'] as const
|
||||
).map((key) => (
|
||||
<Field
|
||||
key={key}
|
||||
label={
|
||||
{
|
||||
code: 'Referência do lote',
|
||||
description: 'Objecto do lote',
|
||||
quantities: 'Quantidades do lote',
|
||||
}[key]
|
||||
}
|
||||
>
|
||||
<textarea
|
||||
className={control}
|
||||
value={lot[key]}
|
||||
onChange={(e) =>
|
||||
change(
|
||||
'lots',
|
||||
lots.map((r, n) =>
|
||||
n === i
|
||||
? {
|
||||
...r,
|
||||
[key]: e.target
|
||||
.value,
|
||||
}
|
||||
: r,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
onClick={() =>
|
||||
change(
|
||||
'lots',
|
||||
lots.filter((_, n) => n !== i),
|
||||
)
|
||||
}
|
||||
>
|
||||
Retirar lote do rascunho
|
||||
</button>
|
||||
</fieldset>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={() =>
|
||||
change('lots', [
|
||||
...lots,
|
||||
{ code: '', description: '', quantities: '' },
|
||||
])
|
||||
}
|
||||
>
|
||||
Acrescentar lote
|
||||
</button>
|
||||
</section>
|
||||
<section className={`${card} space-y-3`}>
|
||||
<h2 className="text-xl font-semibold">
|
||||
Documentos e anexos
|
||||
</h2>
|
||||
<p>
|
||||
Carregue e classifique os originais na biblioteca
|
||||
existente pelo link acima. Reutilize-os aqui: anúncio,
|
||||
caderno, termos de referência, formulários, anexos ou
|
||||
comprovativos. Publicar exige que cada anexo marcado
|
||||
público já esteja autorizado, publicado e com scan limpo
|
||||
na biblioteca. Os restantes ficam privados no cadastro.
|
||||
</p>
|
||||
{attachments.map((item, i) => (
|
||||
<fieldset
|
||||
key={i}
|
||||
className="space-y-2 rounded border p-3"
|
||||
>
|
||||
<legend>Anexo {i + 1}</legend>
|
||||
<Field label={`Documento do anexo ${i + 1}`}>
|
||||
<select
|
||||
className={control}
|
||||
value={item.resource_id || ''}
|
||||
onChange={(e) =>
|
||||
change(
|
||||
'attachments',
|
||||
attachments.map((r, n) =>
|
||||
n === i
|
||||
? {
|
||||
...r,
|
||||
resource_id: Number(
|
||||
e.target.value,
|
||||
),
|
||||
}
|
||||
: r,
|
||||
),
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">
|
||||
Seleccione da biblioteca
|
||||
</option>
|
||||
{references.documents.map((d) => (
|
||||
<option key={d.id} value={d.id}>
|
||||
{d.title} · {d.malware_scan_status}{' '}
|
||||
·{' '}
|
||||
{d.published
|
||||
? 'publicado'
|
||||
: 'privado / rascunho'}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label={`Finalidade do anexo ${i + 1}`}>
|
||||
<input
|
||||
className={control}
|
||||
value={item.purpose}
|
||||
onChange={(e) =>
|
||||
change(
|
||||
'attachments',
|
||||
attachments.map((r, n) =>
|
||||
n === i
|
||||
? {
|
||||
...r,
|
||||
purpose:
|
||||
e.target.value,
|
||||
}
|
||||
: r,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={item.public}
|
||||
onChange={(e) =>
|
||||
change(
|
||||
'attachments',
|
||||
attachments.map((r, n) =>
|
||||
n === i
|
||||
? {
|
||||
...r,
|
||||
public: e.target
|
||||
.checked,
|
||||
}
|
||||
: r,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>{' '}
|
||||
Incluir este anexo na divulgação pública
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
className="ml-3 underline"
|
||||
onClick={() =>
|
||||
change(
|
||||
'attachments',
|
||||
attachments.filter((_, n) => n !== i),
|
||||
)
|
||||
}
|
||||
>
|
||||
Retirar anexo do rascunho
|
||||
</button>
|
||||
</fieldset>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={() =>
|
||||
change('attachments', [
|
||||
...attachments,
|
||||
{ resource_id: 0, purpose: '', public: false },
|
||||
])
|
||||
}
|
||||
>
|
||||
Reutilizar documento
|
||||
</button>
|
||||
</section>
|
||||
<section className={`${card} space-y-3`}>
|
||||
<h2 className="text-xl font-semibold">
|
||||
Contacto e acto a divulgar
|
||||
</h2>
|
||||
{input('public_contact')}
|
||||
<label className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={Boolean(
|
||||
form.data.draft.contact_authorized,
|
||||
)}
|
||||
onChange={(e) =>
|
||||
change('contact_authorized', e.target.checked)
|
||||
}
|
||||
/>{' '}
|
||||
Contacto autorizado para divulgação pública
|
||||
</label>
|
||||
{input('result')}
|
||||
{input(
|
||||
'public_reason',
|
||||
'Motivo público do acto — aparece na prévia e no histórico público',
|
||||
)}
|
||||
{input(
|
||||
'internal_notes',
|
||||
'Notas internas — nunca incluídas na divulgação',
|
||||
)}
|
||||
<Field label="Motivo interno da gravação (20–1000 caracteres)">
|
||||
<textarea
|
||||
className={control}
|
||||
value={form.data.reason}
|
||||
onChange={(e) =>
|
||||
form.setData('reason', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<button className={button} disabled={form.processing}>
|
||||
Guardar rascunho
|
||||
</button>
|
||||
</section>
|
||||
</form>
|
||||
{record && (
|
||||
<section className={`${card} my-5 space-y-3`}>
|
||||
<h2 className="text-xl font-semibold">
|
||||
Pré-visualizar e publicar
|
||||
</h2>
|
||||
<Field label="Acto a publicar">
|
||||
<select
|
||||
className={control}
|
||||
value={act}
|
||||
onChange={(e) => {
|
||||
setAct(e.target.value);
|
||||
setPreview(null);
|
||||
}}
|
||||
>
|
||||
{Object.entries(references.acts).map(([v, l]) => (
|
||||
<option key={v} value={v}>
|
||||
{l}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<button
|
||||
className={button}
|
||||
disabled={!saved || busy}
|
||||
onClick={makePreview}
|
||||
>
|
||||
Preparar prévia pública
|
||||
</button>
|
||||
<p>
|
||||
Guarde antes da prévia. Uma prorrogação identifica o
|
||||
prazo anterior e o novo; o fim do prazo não é
|
||||
adjudicação.
|
||||
</p>
|
||||
{message && <p role="alert">{message}</p>}
|
||||
{preview && (
|
||||
<div className="space-y-3 rounded border p-4">
|
||||
<h3 className="text-xl font-semibold">
|
||||
Prévia do conteúdo público — {acts[preview.act]}
|
||||
</h3>
|
||||
<p>
|
||||
Motivo público:{' '}
|
||||
{String(preview.payload.public_reason)}
|
||||
</p>
|
||||
<NoticeContent p={preview.payload} />
|
||||
<button
|
||||
className={button}
|
||||
onClick={() =>
|
||||
router.post(
|
||||
`/management/concursos/${record.id}/publicar`,
|
||||
{
|
||||
act: preview.act,
|
||||
hash: preview.hash,
|
||||
reason: String(
|
||||
preview.payload.public_reason,
|
||||
),
|
||||
},
|
||||
{ onSuccess: () => setPreview(null) },
|
||||
)
|
||||
}
|
||||
>
|
||||
Publicar este acto
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{record.published && (
|
||||
<Link
|
||||
className="block underline"
|
||||
href={`/concursos/${record.id}`}
|
||||
>
|
||||
Consultar anúncio público
|
||||
</Link>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
<section className={card}>
|
||||
<h2 className="text-xl font-semibold">
|
||||
Histórico de preparação e publicação
|
||||
</h2>
|
||||
{history.map((v) => (
|
||||
<p key={v.version}>
|
||||
Versão {v.version} ·{' '}
|
||||
{v.act === 'draft' ? 'Rascunho' : acts[v.act]} ·
|
||||
responsável {v.actor_id} ·{' '}
|
||||
{v.published_at ?? v.created_at} · {v.reason}
|
||||
</p>
|
||||
))}
|
||||
</section>
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
import { Link, useForm } from '@inertiajs/react';
|
||||
import { Frame, card, button } from '@/pages/investment/shared';
|
||||
import { Field, control, states, type Publication } from './shared';
|
||||
type Choice = { id: string; name: string };
|
||||
export default function Index({
|
||||
items,
|
||||
filters,
|
||||
options,
|
||||
regimes,
|
||||
management,
|
||||
}: {
|
||||
items: {
|
||||
data: { id: string; publication: Publication; state: string }[];
|
||||
current_page: number;
|
||||
links: { url: string | null; label: string; active: boolean }[];
|
||||
};
|
||||
filters: Record<string, string>;
|
||||
options: Record<string, Choice[]>;
|
||||
regimes: Record<string, string>;
|
||||
management: boolean;
|
||||
}) {
|
||||
const form = useForm({
|
||||
q: filters.q ?? '',
|
||||
entity: filters.entity ?? '',
|
||||
sector: filters.sector ?? '',
|
||||
territory: filters.territory ?? '',
|
||||
modality: filters.modality ?? '',
|
||||
financier: filters.financier ?? '',
|
||||
state: filters.state ?? '',
|
||||
deadline_before: filters.deadline_before ?? '',
|
||||
regime: filters.regime ?? '',
|
||||
});
|
||||
const query = new URLSearchParams(
|
||||
Object.entries({ ...filters, page: String(items.current_page) }).filter(
|
||||
([, v]) => v != null && v !== '',
|
||||
),
|
||||
).toString();
|
||||
return (
|
||||
<Frame title="Concursos e anúncios">
|
||||
<p>
|
||||
Procedimentos e actos divulgados pelas entidades responsáveis.
|
||||
Uma oportunidade divulgada não é, por si, um concurso aberto.
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<Link className="underline" href="/concursos/acompanhar">
|
||||
Os concursos que acompanho
|
||||
</Link>
|
||||
{management && (
|
||||
<Link className={button} href="/management/concursos">
|
||||
Gerir concursos e anúncios
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
<form
|
||||
className={`${card} grid gap-3 md:grid-cols-3`}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.get('/concursos', { preserveState: true });
|
||||
}}
|
||||
>
|
||||
<Field label="Palavras-chave">
|
||||
<input
|
||||
className={control}
|
||||
value={form.data.q}
|
||||
onChange={(e) => form.setData('q', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
{(
|
||||
[
|
||||
'entity',
|
||||
'sector',
|
||||
'territory',
|
||||
'modality',
|
||||
'financier',
|
||||
] as const
|
||||
).map((key) => (
|
||||
<Field
|
||||
key={key}
|
||||
label={
|
||||
{
|
||||
entity: 'Entidade',
|
||||
sector: 'Sector',
|
||||
territory: 'Localização',
|
||||
modality: 'Modalidade',
|
||||
financier: 'Financiador',
|
||||
}[key]
|
||||
}
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={form.data[key]}
|
||||
onChange={(e) => form.setData(key, e.target.value)}
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
{(options[key] ?? []).map((o) => (
|
||||
<option key={o.id} value={o.id}>
|
||||
{o.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
))}
|
||||
<Field label="Regime">
|
||||
<select
|
||||
className={control}
|
||||
value={form.data.regime}
|
||||
onChange={(e) => form.setData('regime', e.target.value)}
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
{Object.entries(regimes).map(([v, l]) => (
|
||||
<option key={v} value={v}>
|
||||
{l}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Estado">
|
||||
<select
|
||||
className={control}
|
||||
value={form.data.state}
|
||||
onChange={(e) => form.setData('state', e.target.value)}
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
{Object.entries(states).map(([v, l]) => (
|
||||
<option key={v} value={v}>
|
||||
{l}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Prazo até (data local do procedimento)">
|
||||
<input
|
||||
className={control}
|
||||
type="date"
|
||||
value={form.data.deadline_before}
|
||||
onChange={(e) =>
|
||||
form.setData('deadline_before', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<button className={button}>Pesquisar</button>
|
||||
</form>
|
||||
{!items.data.length && (
|
||||
<p role="status">Nenhum anúncio corresponde aos filtros.</p>
|
||||
)}
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{items.data.map((item) => (
|
||||
<article key={item.id} className={card}>
|
||||
<h2 className="text-xl font-semibold">
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/concursos/${item.id}${query ? '?' + query : ''}`}
|
||||
>
|
||||
{String(item.publication.payload.title)}
|
||||
</Link>
|
||||
</h2>
|
||||
<p>
|
||||
{String(item.publication.payload.organization_name)}{' '}
|
||||
· {states[item.state]}
|
||||
</p>
|
||||
<p>
|
||||
Entrega:{' '}
|
||||
{String(item.publication.payload.deadline).replace(
|
||||
'T',
|
||||
' ',
|
||||
)}{' '}
|
||||
· {String(item.publication.payload.timezone)}
|
||||
</p>
|
||||
<p>{String(item.publication.payload.object)}</p>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
<nav aria-label="Paginação">
|
||||
{items.links.map((link, i) =>
|
||||
link.url ? (
|
||||
<Link
|
||||
key={i}
|
||||
className={`mx-2 underline ${link.active ? 'font-bold' : ''}`}
|
||||
href={link.url}
|
||||
>
|
||||
{link.label
|
||||
.replace('«', '«')
|
||||
.replace('»', '»')}
|
||||
</Link>
|
||||
) : (
|
||||
<span key={i} className="mx-2">
|
||||
{link.label
|
||||
.replace('«', '«')
|
||||
.replace('»', '»')}
|
||||
</span>
|
||||
),
|
||||
)}
|
||||
</nav>
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { Frame, card, button } from '@/pages/investment/shared';
|
||||
import { states, type Publication } from './shared';
|
||||
export default function Manage({
|
||||
items,
|
||||
watched = false,
|
||||
}: {
|
||||
items: {
|
||||
id: string;
|
||||
title?: string;
|
||||
version?: number;
|
||||
published?: boolean;
|
||||
publication?: Publication;
|
||||
state?: string;
|
||||
changed?: boolean;
|
||||
}[];
|
||||
watched?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<Frame
|
||||
title={
|
||||
watched
|
||||
? 'Concursos que acompanho'
|
||||
: 'Gestão de concursos e anúncios'
|
||||
}
|
||||
>
|
||||
<Link className="underline" href="/concursos">
|
||||
Catálogo público
|
||||
</Link>
|
||||
{!watched && (
|
||||
<>
|
||||
<Link className={button} href="/management/concursos/novo">
|
||||
Novo concurso/anúncio
|
||||
</Link>
|
||||
<Link className="ml-3 underline" href="/gestao-conteudos">
|
||||
Entrada única de gestão
|
||||
</Link>
|
||||
<p>
|
||||
Guardar → recuperar → pré-visualizar → publicar →
|
||||
actualizar/prorrogar → publicar resultado ou
|
||||
cancelamento. Carregue documentos na biblioteca
|
||||
existente, acompanhe o scan e autorize separadamente os
|
||||
anexos públicos. O rascunho pode ficar incompleto.
|
||||
</p>
|
||||
<p>
|
||||
Para actualizar, reabra o concurso, guarde as
|
||||
alterações, escolha o acto e confira a prévia. A data de
|
||||
publicação no portal não substitui a data de origem.
|
||||
Acompanhar não apresenta proposta.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
{!items.length && <p>Sem registos.</p>}
|
||||
{items.map((item) => (
|
||||
<article key={item.id} className={`${card} my-3`}>
|
||||
<h2 className="font-semibold">
|
||||
{item.title ?? String(item.publication?.payload.title)}
|
||||
</h2>
|
||||
{watched ? (
|
||||
<>
|
||||
<p>
|
||||
{states[item.state ?? '']} ·{' '}
|
||||
{item.changed
|
||||
? 'Há novos actos desde que começou a acompanhar'
|
||||
: 'Sem novos actos desde o registo de acompanhamento'}
|
||||
</p>
|
||||
<p>
|
||||
O acompanhamento é consultado nesta área; não
|
||||
afirma envio de alertas por email.
|
||||
</p>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/concursos/${item.id}`}
|
||||
>
|
||||
Consultar concurso
|
||||
</Link>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p>
|
||||
Versão {item.version} ·{' '}
|
||||
{item.published
|
||||
? 'Com acto publicado; alterações em preparação são separadas'
|
||||
: 'Rascunho privado'}
|
||||
</p>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/management/concursos/${item.id}`}
|
||||
>
|
||||
Recuperar e editar
|
||||
</Link>
|
||||
{item.published && (
|
||||
<Link
|
||||
className="ml-3 underline"
|
||||
href={`/concursos/${item.id}`}
|
||||
>
|
||||
Consultar publicação
|
||||
</Link>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
export type Lot = { code: string; description: string; quantities: string };
|
||||
export type Attachment = {
|
||||
resource_id: number;
|
||||
public: boolean;
|
||||
purpose: string;
|
||||
title?: string;
|
||||
available?: boolean;
|
||||
};
|
||||
export type Draft = {
|
||||
[key: string]: string | number | boolean | null | Lot[] | Attachment[];
|
||||
};
|
||||
export type Payload = Draft & {
|
||||
opportunity?: { title: string; url: string } | null;
|
||||
};
|
||||
export type Publication = {
|
||||
id: string;
|
||||
version: number;
|
||||
act: string;
|
||||
payload: Payload;
|
||||
published_at: string;
|
||||
reason: string;
|
||||
};
|
||||
export const states: Record<string, string> = {
|
||||
open: 'Aberto',
|
||||
extended: 'Prorrogado',
|
||||
deadline_ended: 'Prazo de propostas terminado',
|
||||
cancelled: 'Cancelado',
|
||||
results: 'Resultados publicados',
|
||||
};
|
||||
export const acts: Record<string, string> = {
|
||||
initial: 'Anúncio inicial',
|
||||
clarification: 'Esclarecimento',
|
||||
correction: 'Rectificação',
|
||||
extension: 'Prorrogação',
|
||||
award: 'Resultado / adjudicação',
|
||||
cancellation: 'Cancelamento',
|
||||
other: 'Outro acto',
|
||||
};
|
||||
export const labels: Record<string, string> = {
|
||||
reference: 'Referência',
|
||||
object: 'Objecto',
|
||||
responsible_unit: 'Unidade responsável / UGEA quando aplicável',
|
||||
modality: 'Modalidade',
|
||||
object_kind: 'Natureza do objecto',
|
||||
quantities: 'Quantidades essenciais',
|
||||
financier: 'Financiador',
|
||||
instrument: 'Instrumento aplicável',
|
||||
edition: 'Edição aplicável',
|
||||
rule_source: 'Fonte das regras',
|
||||
financing_agreement: 'Acordo de financiamento',
|
||||
eligibility: 'Elegibilidade',
|
||||
requirements: 'Requisitos de participação',
|
||||
proposal_validity: 'Validade da proposta',
|
||||
guarantee_status: 'Aplicabilidade de garantias',
|
||||
guarantees: 'Garantias documentadas',
|
||||
delivery_channel: 'Canal de entrega',
|
||||
delivery_address: 'Endereço / instruções para apresentar proposta',
|
||||
delivery_url: 'Plataforma de entrega',
|
||||
public_contact: 'Contacto público autorizado',
|
||||
dissemination: 'Meios de divulgação exigidos / adoptados e comprovativos',
|
||||
origin_url: 'Anúncio de origem',
|
||||
origin_published_at: 'Publicação de origem — referência do prazo',
|
||||
clarifications_at: 'Limite para esclarecimentos',
|
||||
deadline: 'Entrega de propostas',
|
||||
opening_at: 'Abertura (quando aplicável)',
|
||||
timezone: 'Fuso horário do procedimento',
|
||||
minimum_days: 'Prazo mínimo documentado (dias)',
|
||||
minimum_source: 'Fonte / citação do prazo mínimo',
|
||||
minimum_edition: 'Edição da regra de prazo',
|
||||
minimum_modality: 'Modalidade da regra de prazo',
|
||||
minimum_day_basis: 'Base de contagem do prazo',
|
||||
minimum_calendar_source: 'Fonte do calendário de dias úteis',
|
||||
minimum_working_days: 'Dias de trabalho (1=segunda, 7=domingo)',
|
||||
minimum_holidays: 'Feriados e exclusões documentados',
|
||||
result: 'Acto ou resultado documentado',
|
||||
};
|
||||
export const control =
|
||||
'w-full rounded border border-slate-400 bg-background p-2 text-foreground';
|
||||
export function Field({
|
||||
label,
|
||||
children,
|
||||
}: {
|
||||
label: string;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<label className="block space-y-1">
|
||||
<span className="font-medium">{label}</span>
|
||||
{children}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
export function NoticeContent({ p }: { p: Payload }) {
|
||||
const links = ['rule_source', 'origin_url', 'delivery_url'];
|
||||
const names: Record<string, string> = {
|
||||
works: 'Obras',
|
||||
goods: 'Bens',
|
||||
services: 'Serviços',
|
||||
mixed: 'Misto',
|
||||
other: 'Outro',
|
||||
required: 'Exigidas',
|
||||
not_required: 'Não exigidas',
|
||||
unknown: 'Por determinar',
|
||||
calendar: 'Dias corridos',
|
||||
business: 'Dias úteis',
|
||||
};
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<h2 className="text-2xl font-semibold">{String(p.title ?? '')}</h2>
|
||||
<p>
|
||||
<strong>Entidade:</strong>{' '}
|
||||
{String(p.organization_name ?? 'Por indicar')}
|
||||
</p>
|
||||
<p>
|
||||
Regime:{' '}
|
||||
{(
|
||||
{
|
||||
state: 'Contratação pública do Estado',
|
||||
external: 'Financiamento externo',
|
||||
private: 'Concurso privado',
|
||||
other: 'Outro regime documentado',
|
||||
} as Record<string, string>
|
||||
)[String(p.regime)] ?? 'Por indicar'}
|
||||
</p>
|
||||
<section>
|
||||
<h3 className="text-lg font-semibold">
|
||||
Objecto e como participar
|
||||
</h3>
|
||||
<p className="whitespace-pre-wrap">{String(p.object ?? '')}</p>
|
||||
<p className="my-2 rounded border p-3">
|
||||
<strong>Entrega:</strong>{' '}
|
||||
{String(p.deadline ?? 'Por indicar').replace('T', ' ')} ·{' '}
|
||||
{String(p.timezone ?? '')}
|
||||
<br />
|
||||
{String(p.delivery_channel ?? '')} ·{' '}
|
||||
{String(p.delivery_address ?? '')}
|
||||
</p>
|
||||
<p>
|
||||
Sector: {String(p.sector_name ?? 'Por indicar')} ·
|
||||
Localização: {String(p.territory_name ?? 'Por indicar')}
|
||||
</p>
|
||||
{p.project_name && (
|
||||
<p>
|
||||
Projecto relacionado: {String(p.project_name)}. Esta
|
||||
relação não confirma execução ou contratação.
|
||||
</p>
|
||||
)}
|
||||
{p.opportunity && (
|
||||
<a className="underline" href={p.opportunity.url}>
|
||||
Oportunidade relacionada: {p.opportunity.title}
|
||||
</a>
|
||||
)}
|
||||
</section>
|
||||
{p.deadline_previous && (
|
||||
<p className="rounded border p-3">
|
||||
<strong>Prorrogação:</strong> prazo anterior{' '}
|
||||
{String(p.deadline_previous).replace('T', ' ')} (
|
||||
{String(p.timezone_previous)}) → novo prazo{' '}
|
||||
{String(p.deadline).replace('T', ' ')} ({String(p.timezone)}
|
||||
).
|
||||
</p>
|
||||
)}
|
||||
<dl className="grid gap-3 md:grid-cols-2">
|
||||
{Object.entries(labels)
|
||||
.filter(
|
||||
([key]) =>
|
||||
p[key] !== null &&
|
||||
p[key] !== undefined &&
|
||||
p[key] !== '',
|
||||
)
|
||||
.map(([key, label]) => (
|
||||
<div
|
||||
key={key}
|
||||
className="rounded border p-3 break-words"
|
||||
>
|
||||
<dt className="font-semibold">{label}</dt>
|
||||
<dd className="whitespace-pre-wrap">
|
||||
{links.includes(key) ? (
|
||||
<a
|
||||
className="underline"
|
||||
href={String(p[key])}
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
{String(p[key])}
|
||||
</a>
|
||||
) : (
|
||||
(
|
||||
names[String(p[key])] ?? String(p[key])
|
||||
).replace(/^(\d{4}-\d{2}-\d{2})T/, '$1 ')
|
||||
)}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
<section>
|
||||
<h3 className="text-lg font-semibold">Lotes</h3>
|
||||
{((p.lots ?? []) as Lot[]).length ? (
|
||||
<ul>
|
||||
{(p.lots as Lot[]).map((lot, i) => (
|
||||
<li key={i}>
|
||||
{lot.code} — {lot.description} ·{' '}
|
||||
{lot.quantities}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p>Sem lotes indicados.</p>
|
||||
)}
|
||||
</section>
|
||||
<section>
|
||||
<h3 className="text-lg font-semibold">
|
||||
Documentos do concurso
|
||||
</h3>
|
||||
<ul>
|
||||
{((p.attachments ?? []) as Attachment[]).map((item, i) => (
|
||||
<li key={i}>
|
||||
{item.available === false ? (
|
||||
<span>
|
||||
{item.title} — documento actualmente
|
||||
indisponível
|
||||
</span>
|
||||
) : (
|
||||
<a
|
||||
className="underline"
|
||||
href={`/documentos/${item.resource_id}/download`}
|
||||
>
|
||||
{item.title ??
|
||||
`Documento ${item.resource_id}`}{' '}
|
||||
— {item.purpose}
|
||||
</a>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{!((p.attachments as Attachment[]) ?? []).length && (
|
||||
<p>
|
||||
Sem anexos públicos neste acto. Consulte o canal e o
|
||||
anúncio de origem.
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
<p className="rounded border p-3">
|
||||
O InvesteMoz divulga este acto e não recebe propostas nesta
|
||||
secção. Apresente a proposta no canal indicado nos documentos.
|
||||
Esta divulgação não substitui os meios oficiais exigidos,
|
||||
não comprova envio à UFSA ou ao financiador e não equivale à
|
||||
execução do investimento.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { Head, Link, router, usePage } from '@inertiajs/react';
|
||||
import { Frame, card, button } from '@/pages/investment/shared';
|
||||
import { NoticeContent, states, acts, type Publication } from './shared';
|
||||
export default function Show({
|
||||
id,
|
||||
publication,
|
||||
state,
|
||||
history,
|
||||
watching,
|
||||
backUrl,
|
||||
printMode,
|
||||
}: {
|
||||
id: string;
|
||||
publication: Publication;
|
||||
state: string;
|
||||
history: Publication[];
|
||||
watching: boolean;
|
||||
backUrl: string;
|
||||
printMode: boolean;
|
||||
}) {
|
||||
const { auth } = usePage<{ auth: { user: unknown | null } }>().props;
|
||||
return (
|
||||
<Frame title="Concurso e anúncio">
|
||||
<Head title={String(publication.payload.title)} />
|
||||
<style>
|
||||
{
|
||||
'@media print { nav, header, aside, footer, [data-slot="sidebar"], .no-print {display:none!important} main {margin:0!important; width:100%!important} details {display:block} }'
|
||||
}
|
||||
</style>
|
||||
<div className="no-print flex flex-wrap gap-4">
|
||||
<Link className="underline" href={backUrl}>
|
||||
Voltar aos resultados
|
||||
</Link>
|
||||
<Link className="underline" href={`/concursos/${id}/imprimir`}>
|
||||
Relatório imprimível
|
||||
</Link>
|
||||
{printMode && (
|
||||
<button className={button} onClick={() => window.print()}>
|
||||
Imprimir anúncio
|
||||
</button>
|
||||
)}
|
||||
{auth?.user ? (
|
||||
<button
|
||||
className={button}
|
||||
onClick={() =>
|
||||
watching
|
||||
? router.delete(`/concursos/${id}/acompanhar`)
|
||||
: router.put(`/concursos/${id}/acompanhar`)
|
||||
}
|
||||
>
|
||||
{watching
|
||||
? 'Deixar de acompanhar'
|
||||
: 'Acompanhar concurso'}
|
||||
</button>
|
||||
) : (
|
||||
<Link className="underline" href="/login">
|
||||
Entrar para acompanhar — conta simples
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
<p className="rounded border p-3">
|
||||
<strong>{states[state]}</strong> · {acts[publication.act]} ·
|
||||
Versão {publication.version}
|
||||
</p>
|
||||
<p>
|
||||
Publicação deste acto no InvesteMoz: {publication.published_at}{' '}
|
||||
(UTC). Esta data não reinicia o prazo de origem.
|
||||
</p>
|
||||
<article className={card}>
|
||||
<NoticeContent p={publication.payload} />
|
||||
</article>
|
||||
<section className={card}>
|
||||
<h2 className="text-xl font-semibold">
|
||||
Actos publicados e histórico
|
||||
</h2>
|
||||
{history.map((v) => (
|
||||
<details key={v.id} open={printMode}>
|
||||
<summary>
|
||||
{acts[v.act]} · versão {v.version} ·{' '}
|
||||
{v.published_at} (UTC)
|
||||
</summary>
|
||||
<p className="my-2">Motivo público: {v.reason}</p>
|
||||
<NoticeContent p={v.payload} />
|
||||
</details>
|
||||
))}
|
||||
</section>
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user