+962
@@ -0,0 +1,962 @@
|
||||
import { valueText } from '@/lib/value-text';
|
||||
import OpportunityParcelGeometry from './opportunity-parcel-geometry';
|
||||
import TerritoryGeometryPreview from './territory-geometry-preview';
|
||||
import { control } from '@/pages/management/shared';
|
||||
|
||||
type Data = Record<string, unknown>;
|
||||
type Schema = {
|
||||
$ref?: string;
|
||||
type?: string | string[];
|
||||
properties?: Record<string, Schema>;
|
||||
items?: Schema;
|
||||
enum?: unknown[];
|
||||
const?: unknown;
|
||||
format?: string;
|
||||
maxLength?: number;
|
||||
required?: string[];
|
||||
};
|
||||
type Resource = {
|
||||
id: string;
|
||||
payload: { title?: string; role?: string; [key: string]: unknown };
|
||||
file?: { file_name: string };
|
||||
};
|
||||
function resourceTerritory(resource?: Resource) {
|
||||
const p = resource?.payload;
|
||||
const id =
|
||||
p?.locality_id ?? p?.admin_post_id ?? p?.district_id ?? p?.province_id;
|
||||
return typeof id === 'string' ? id : undefined;
|
||||
}
|
||||
export type CanonicalOptions = {
|
||||
version: string;
|
||||
modularProfiles?: Record<string, string>;
|
||||
historyVersion?: string | null;
|
||||
schema: Schema;
|
||||
definitions: Record<string, Schema>;
|
||||
contacts: { id: string; full_name: string }[];
|
||||
activities: {
|
||||
id: string;
|
||||
parent_id: string | null;
|
||||
sector_id: number;
|
||||
label_pt_mz: string;
|
||||
}[];
|
||||
resources: Record<string, Resource[]>;
|
||||
gates: string[];
|
||||
countries: { code: string; name: string }[];
|
||||
authorities: { id: string; label_pt_mz: string }[];
|
||||
};
|
||||
const labels: Record<string, string> = {
|
||||
official_title: 'Título oficial',
|
||||
promoter_type: 'Tipo de Promotor',
|
||||
internal_contact_id: 'Contacto interno',
|
||||
sector_id: 'Sector',
|
||||
subsector_id: 'Subsector',
|
||||
economic_activity_id: 'Atividade económica',
|
||||
location_mode: 'Uma ou várias localizações',
|
||||
geographic_scope: 'Âmbito geográfico',
|
||||
multi_district_rationale: 'Justificação territorial',
|
||||
locations: 'Localizações guardadas',
|
||||
executive_summary: 'Resumo executivo',
|
||||
demand_statement: 'Necessidade e proposta',
|
||||
visibility: 'Visibilidade após publicação',
|
||||
truth_declaration: 'Declaração de veracidade',
|
||||
publication_languages: 'Versões por idioma',
|
||||
language_code: 'Idioma',
|
||||
title: 'Título',
|
||||
summary: 'Resumo',
|
||||
documents: 'Documentos guardados',
|
||||
evidences: 'Evidências',
|
||||
document_id: 'Documento associado',
|
||||
evidence_type: 'Tipo de evidência',
|
||||
description: 'Descrição',
|
||||
images: 'Imagens guardadas',
|
||||
review_due_date: 'Data de revisão editorial',
|
||||
real_estate: 'Imobiliário',
|
||||
land_rights: 'DUAT e direitos fundiários',
|
||||
business_transaction: 'Negócio',
|
||||
module_profile_version: 'Versão do contrato QA (seleção explícita)',
|
||||
module_details: 'Condições do módulo',
|
||||
mode: 'Percurso: procura, oferta ou modalidade',
|
||||
conditions_status: 'Condições propostas ou compromisso documentado',
|
||||
object: 'Objeto',
|
||||
representation_document_id: 'Documento de representação',
|
||||
object_document_id: 'Documento do objeto/procedimento',
|
||||
disclosure_authorization_document_id:
|
||||
'Autorização de divulgação da intenção/chamada',
|
||||
external_decision_document_id: 'Ato competente do direito atribuído',
|
||||
granting_entity: 'Entidade concedente declarada',
|
||||
procedure_regime: 'Regime/procedimento declarado',
|
||||
scope: 'Âmbito territorial ou digital',
|
||||
term_value: 'Duração ou prazo',
|
||||
term_unit: 'Unidade da duração',
|
||||
remuneration_obligations: 'Remuneração e obrigações',
|
||||
participation_conditions: 'Condições de participação',
|
||||
land_required: 'Precisa de terra?',
|
||||
construction_required: 'Inclui construção?',
|
||||
applicable_authorizations: 'Autorizações aplicáveis e situação',
|
||||
instrument: 'Instrumento de financiamento',
|
||||
offered_capacity: 'Capacidade oferecida pelo financiador',
|
||||
eligibility_criteria: 'Critérios declarados do financiador',
|
||||
capacity_document_id: 'Evidência da capacidade declarada',
|
||||
financial_plan_document_id: 'Plano financeiro do projeto',
|
||||
secured_evidence_document_id: 'Evidência do financiamento assegurado',
|
||||
use_of_funds: 'Finalidade do financiamento procurado',
|
||||
disbursement_calendar: 'Calendário proposto de desembolso',
|
||||
repayment_periodicity: 'Periodicidade de reembolso',
|
||||
proposed_rights: 'Direitos propostos',
|
||||
equity_percentage: 'Percentagem de capital proposta',
|
||||
terms: 'Condições',
|
||||
scenario: 'Cenário identificado',
|
||||
source: 'Fonte identificada',
|
||||
terms_date: 'Data da fonte/condições',
|
||||
commitment_document_id: 'Documento do compromisso assumido',
|
||||
acceptance_criteria: 'Critérios de aceitação do fornecimento',
|
||||
quotation_method: 'Método de cotação',
|
||||
total_price: 'Preço total (impostos identificados separadamente)',
|
||||
declared_taxes: 'Impostos declarados, sem cálculo implícito',
|
||||
advance_or_guarantee: 'Há adiantamento ou garantia?',
|
||||
subtype: 'Subtipo para classificação funcional',
|
||||
recipients: 'Destinatários',
|
||||
expected_output: 'Resultado esperado',
|
||||
history_status: 'Situação do histórico financeiro',
|
||||
history_declaration: 'Declaração de ausência de exercícios completos',
|
||||
history_declaration_document_id: 'Documento da declaração',
|
||||
projections: 'Projeções identificadas — não são contas realizadas',
|
||||
transaction_type: 'Modalidade',
|
||||
property_type: 'Tipo de imóvel',
|
||||
construction_status: 'Estado construtivo',
|
||||
property_condition: 'Condição do imóvel',
|
||||
land_area: 'Área do terreno',
|
||||
built_area: 'Área construída',
|
||||
area_unit: 'Unidade da área',
|
||||
units: 'Unidades',
|
||||
rooms: 'Compartimentos',
|
||||
floors: 'Pisos',
|
||||
amenities: 'Comodidades',
|
||||
utilities: 'Serviços e acessos',
|
||||
occupancy_status: 'Ocupação',
|
||||
title_type: 'Tipo de título',
|
||||
registration_number: 'Número de registo',
|
||||
encumbrances: 'Ónus e restrições',
|
||||
price: 'Preço do imóvel',
|
||||
rent: 'Renda',
|
||||
rent_periodicity: 'Periodicidade',
|
||||
deposit: 'Caução',
|
||||
valuation: 'Avaliação',
|
||||
viewing: 'Visitas',
|
||||
planning_permit_document_id: 'Licença de construção',
|
||||
use_license_document_id: 'Licença de utilização',
|
||||
operation_type: 'Operação fundiária admissível',
|
||||
duat_status: 'Situação do DUAT',
|
||||
duat_number: 'Número do DUAT',
|
||||
holder_id: 'Titular cadastrado',
|
||||
holder_name: 'Nome do titular',
|
||||
issuing_authority_id: 'Entidade emissora',
|
||||
issue_date: 'Data de emissão',
|
||||
expiry_date: 'Data de validade',
|
||||
authorized_purpose: 'Finalidade autorizada',
|
||||
exploitation_plan_document_id: 'Plano de exploração',
|
||||
parcels: 'Parcelas',
|
||||
location_id: 'Localização associada',
|
||||
area: 'Área',
|
||||
cadastral_number: 'Número cadastral',
|
||||
overlap_status: 'Sobreposição',
|
||||
improvements: 'Benfeitorias',
|
||||
communities: 'Comunidades',
|
||||
community_consultation: 'Consulta comunitária',
|
||||
overlaps_conflicts: 'Sobreposições e conflitos',
|
||||
required_authorizations: 'Autorizações necessárias',
|
||||
consideration: 'Contraprestação',
|
||||
legal_entity_id: 'Entidade representada',
|
||||
legal_form: 'Forma jurídica',
|
||||
percentage_offered: 'Percentagem oferecida',
|
||||
asking_price: 'Valor solicitado',
|
||||
financial_periods: 'Exercícios financeiros',
|
||||
assets_liabilities: 'Ativos e passivos',
|
||||
employees: 'Empregos e obrigações',
|
||||
contracts_licenses: 'Contratos e licenças',
|
||||
litigation_contingencies: 'Litígios e contingências',
|
||||
reason_for_transaction: 'Fundamentação da operação',
|
||||
partner_contribution: 'Contribuição do parceiro',
|
||||
governance_rights: 'Direitos de governação',
|
||||
franchise_terms: 'Condições da franquia',
|
||||
confidentiality_level: 'Confidencialidade',
|
||||
due_diligence_status: 'Preparação da análise',
|
||||
opportunity_type: 'Tipo de investimento',
|
||||
maturity_stage: 'Etapa de maturidade',
|
||||
investment_modalities: 'Modalidades de investimento',
|
||||
investor_profiles: 'Perfis de investidor',
|
||||
products: 'Produtos',
|
||||
assets: 'Ativos',
|
||||
inputs: 'Insumos',
|
||||
markets: 'Mercados',
|
||||
competitive_advantage: 'Vantagem competitiva',
|
||||
employment: 'Emprego',
|
||||
impact_indicators: 'Impactos',
|
||||
total_investment: 'Investimento total',
|
||||
currency: 'Moeda',
|
||||
investment_breakdown: 'Rubricas de investimento',
|
||||
secured_financing: 'Financiamento assegurado',
|
||||
funding_sought: 'Financiamento procurado',
|
||||
financial_indicators: 'Indicadores financeiros',
|
||||
milestones: 'Marcos',
|
||||
licenses: 'Licenças',
|
||||
environmental_social: 'Aspetos ambientais e sociais',
|
||||
risks: 'Riscos',
|
||||
relations: 'Relações',
|
||||
amount: 'Montante',
|
||||
name: 'Nome',
|
||||
label: 'Designação',
|
||||
status: 'Estado',
|
||||
date: 'Data',
|
||||
method: 'Método',
|
||||
appraiser: 'Avaliador',
|
||||
year: 'Exercício',
|
||||
revenue: 'Receita',
|
||||
profit: 'Resultado',
|
||||
type: 'Tipo',
|
||||
value: 'Valor',
|
||||
details: 'Detalhes',
|
||||
mitigation: 'Mitigação',
|
||||
due_date: 'Prazo',
|
||||
authority: 'Entidade competente',
|
||||
assessment_status: 'Estado da avaliação',
|
||||
environmental_category: 'Categoria ambiental',
|
||||
direct_jobs: 'Empregos diretos',
|
||||
employment_type: 'Tipo de emprego',
|
||||
geometry: 'Geometria da parcela',
|
||||
start_date: 'Data de início',
|
||||
end_date: 'Data de fim',
|
||||
responsible_name: 'Responsável declarado',
|
||||
dependencies: 'Marcos dos quais depende',
|
||||
npv: 'Valor atual líquido',
|
||||
irr: 'Taxa interna de retorno (%)',
|
||||
payback_years: 'Prazo de retorno (anos)',
|
||||
horizon_years: 'Horizonte (anos)',
|
||||
discount_rate: 'Taxa de desconto (%)',
|
||||
model_document_id: 'Modelo financeiro associado',
|
||||
title_holder_name: 'Titular do título',
|
||||
title_document_id: 'Documento do título',
|
||||
territorial_right_document_id: 'Documento do direito territorial aplicável',
|
||||
construction_license_document_id:
|
||||
'Documento da licença de construção aplicável',
|
||||
holder_document_id: 'Documento do titular',
|
||||
expected_completion_date: 'Conclusão prevista',
|
||||
occupancy_details: 'Condições de ocupação',
|
||||
occupancy_document_id: 'Contrato de ocupação',
|
||||
urban_limit_document_id: 'Fonte do limite urbanístico',
|
||||
max_built_area: 'Área edificável máxima declarada',
|
||||
amenities_other: 'Outra comodidade',
|
||||
communities_affected: 'Existem comunidades afetadas?',
|
||||
exploitation_plan_required: 'Plano de exploração aplicável?',
|
||||
entity_registration: 'Registo e beneficiário efetivo',
|
||||
tax_identifier: 'Identificação fiscal',
|
||||
legal_document_id: 'Documento de constituição/registo',
|
||||
beneficial_owner_document_id: 'Documento do beneficiário efetivo',
|
||||
available_financial_years: 'Exercícios financeiros existentes',
|
||||
liabilities: 'Passivos',
|
||||
cash_flow: 'Fluxo de caixa',
|
||||
excluded_assets: 'Ativos excluídos',
|
||||
guarantees: 'Garantias',
|
||||
reconciliation_document_id: 'Documento de reconciliação',
|
||||
obligations: 'Obrigações',
|
||||
labor_liabilities: 'Passivos laborais',
|
||||
transferability: 'Transmissibilidade',
|
||||
consent_document_id: 'Consentimento de transmissão',
|
||||
nda_document_id: 'Acordo de confidencialidade',
|
||||
teaser: 'Resumo autorizado para publicação',
|
||||
board: 'Órgãos de gestão',
|
||||
reserved_matters: 'Matérias reservadas',
|
||||
dividends: 'Dividendos',
|
||||
exit: 'Saída',
|
||||
deadlock: 'Resolução de impasse',
|
||||
initial_fee: 'Encargo inicial',
|
||||
royalties: 'Royalties e encargos',
|
||||
support: 'Apoio',
|
||||
exclusivity: 'Exclusividade',
|
||||
renewal: 'Renovação',
|
||||
termination: 'Cessação',
|
||||
brand_license_document_id: 'Licença da marca',
|
||||
publish_contact: 'Autoriza publicar o contacto?',
|
||||
public_contact_id: 'Contacto para divulgação',
|
||||
};
|
||||
function FieldErrors({
|
||||
path,
|
||||
errors,
|
||||
}: {
|
||||
path: string;
|
||||
errors: Record<string, string>;
|
||||
}) {
|
||||
const message = errors[path];
|
||||
return message ? (
|
||||
<p id={path + '-error'} className="text-red-700" role="alert">
|
||||
{message}
|
||||
</p>
|
||||
) : null;
|
||||
}
|
||||
function Editor({
|
||||
name,
|
||||
path,
|
||||
schema,
|
||||
value,
|
||||
onChange,
|
||||
options,
|
||||
errors,
|
||||
}: {
|
||||
name: string;
|
||||
path: string;
|
||||
schema: Schema;
|
||||
value: unknown;
|
||||
onChange: (v: unknown) => void;
|
||||
options: CanonicalOptions;
|
||||
errors: Record<string, string>;
|
||||
}) {
|
||||
if (schema.$ref)
|
||||
schema = options.definitions[schema.$ref.split('/').pop()!] ?? schema;
|
||||
const types = Array.isArray(schema.type) ? schema.type : [schema.type];
|
||||
const label = labels[name] ?? name.replaceAll('_', ' ');
|
||||
const props = {
|
||||
id: path,
|
||||
'aria-invalid': !!errors[path],
|
||||
'aria-describedby': errors[path] ? path + '-error' : undefined,
|
||||
};
|
||||
let input;
|
||||
if (name === 'geometry')
|
||||
input = <OpportunityParcelGeometry value={value} onChange={onChange} />;
|
||||
else if (
|
||||
name.endsWith('document_id') ||
|
||||
name === 'location_id' ||
|
||||
name === 'image_id'
|
||||
) {
|
||||
const kind =
|
||||
name === 'location_id'
|
||||
? 'locations'
|
||||
: name === 'image_id'
|
||||
? 'images'
|
||||
: 'documents';
|
||||
const rows = options.resources[kind] ?? [];
|
||||
input = (
|
||||
<>
|
||||
<select
|
||||
{...props}
|
||||
className={control}
|
||||
value={valueText(value ?? '')}
|
||||
onChange={(e) => onChange(e.target.value || null)}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{rows.map((r) => (
|
||||
<option key={r.id} value={r.id}>
|
||||
{r.payload.title ??
|
||||
r.payload.role ??
|
||||
r.file?.file_name ??
|
||||
r.id}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{name === 'location_id' && !!value && (
|
||||
<TerritoryGeometryPreview
|
||||
territoryId={resourceTerritory(
|
||||
rows.find((r) => r.id === value),
|
||||
)}
|
||||
endpoint="/minhas-oportunidades/territory-geometries"
|
||||
label={`Limite administrativo associado à parcela ${Number(path.match(/parcels\.(\d+)\./)?.[1] ?? 0) + 1}`}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
} else if (name === 'country_code')
|
||||
input = (
|
||||
<select
|
||||
{...props}
|
||||
className={control}
|
||||
value={valueText(value ?? '')}
|
||||
onChange={(e) => onChange(e.target.value || null)}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{options.countries.map((c) => (
|
||||
<option key={c.code} value={c.code}>
|
||||
{c.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
);
|
||||
else if (name === 'issuing_authority_id' || name === 'authority_id')
|
||||
input = (
|
||||
<select
|
||||
{...props}
|
||||
className={control}
|
||||
value={valueText(value ?? '')}
|
||||
onChange={(e) => onChange(e.target.value || null)}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{options.authorities.map((a) => (
|
||||
<option key={a.id} value={a.id}>
|
||||
{a.label_pt_mz}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
);
|
||||
else if (schema.enum)
|
||||
input = (
|
||||
<select
|
||||
{...props}
|
||||
className={control}
|
||||
value={valueText(value ?? '')}
|
||||
onChange={(e) => onChange(e.target.value || null)}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{schema.enum
|
||||
.filter((v) => v !== null)
|
||||
.map((v) => (
|
||||
<option key={valueText(v)} value={valueText(v)}>
|
||||
{valueText(v).replaceAll('_', ' ')}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
);
|
||||
else if (types.includes('boolean') || schema.const === true)
|
||||
input = (
|
||||
<select
|
||||
{...props}
|
||||
className={control}
|
||||
value={value === true ? 'true' : value === false ? 'false' : ''}
|
||||
onChange={(e) =>
|
||||
onChange(
|
||||
e.target.value === ''
|
||||
? null
|
||||
: e.target.value === 'true',
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
<option value="true">Sim</option>
|
||||
<option value="false">Não</option>
|
||||
</select>
|
||||
);
|
||||
else if (types.includes('array')) {
|
||||
const rows = Array.isArray(value) ? value : [];
|
||||
let item = schema.items ?? { type: 'string' };
|
||||
if (item.$ref)
|
||||
item = options.definitions[item.$ref.split('/').pop()!] ?? item;
|
||||
const itemTypes = Array.isArray(item.type) ? item.type : [item.type];
|
||||
return (
|
||||
<fieldset className="space-y-2 rounded border p-3">
|
||||
<legend>{label}</legend>
|
||||
<FieldErrors path={path} errors={errors} />
|
||||
{rows.map((v, i) => (
|
||||
<div key={i} className="space-y-2">
|
||||
<Editor
|
||||
name={name}
|
||||
path={path + '.' + i}
|
||||
schema={schema.items ?? { type: 'string' }}
|
||||
value={v}
|
||||
options={options}
|
||||
errors={errors}
|
||||
onChange={(next) =>
|
||||
onChange(
|
||||
rows.map((r, j) => (j === i ? next : r)),
|
||||
)
|
||||
}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
onClick={() =>
|
||||
onChange(rows.filter((_, j) => j !== i))
|
||||
}
|
||||
>
|
||||
Retirar linha {i + 1}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
onClick={() =>
|
||||
onChange([
|
||||
...rows,
|
||||
itemTypes.includes('object')
|
||||
? {}
|
||||
: itemTypes.includes('array')
|
||||
? []
|
||||
: '',
|
||||
])
|
||||
}
|
||||
>
|
||||
Adicionar linha
|
||||
</button>
|
||||
</fieldset>
|
||||
);
|
||||
} else if (types.includes('object') || schema.properties) {
|
||||
const fields = schema.properties ?? {};
|
||||
const data =
|
||||
value && typeof value === 'object' && !Array.isArray(value)
|
||||
? (value as Data)
|
||||
: {};
|
||||
return (
|
||||
<fieldset className="space-y-2 rounded border p-3">
|
||||
<legend>{label}</legend>
|
||||
<FieldErrors path={path} errors={errors} />
|
||||
{Object.entries(fields).map(([key, s]) => (
|
||||
<Editor
|
||||
key={key}
|
||||
name={key}
|
||||
path={path + '.' + key}
|
||||
schema={s}
|
||||
value={data[key]}
|
||||
options={options}
|
||||
errors={errors}
|
||||
onChange={(v) => onChange({ ...data, [key]: v })}
|
||||
/>
|
||||
))}
|
||||
{!Object.keys(fields).length && (
|
||||
<p>
|
||||
Este detalhe exige definição contratual antes da
|
||||
submissão.
|
||||
</p>
|
||||
)}
|
||||
</fieldset>
|
||||
);
|
||||
} else {
|
||||
const numeric = types.includes('number') || types.includes('integer');
|
||||
input =
|
||||
numeric || schema.format === 'date' ? (
|
||||
<input
|
||||
{...props}
|
||||
className={control}
|
||||
type={numeric ? 'number' : 'date'}
|
||||
step={types.includes('integer') ? 1 : 'any'}
|
||||
value={valueText(value ?? '')}
|
||||
onChange={(e) =>
|
||||
onChange(
|
||||
e.target.value === ''
|
||||
? null
|
||||
: numeric
|
||||
? Number(e.target.value)
|
||||
: e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<textarea
|
||||
{...props}
|
||||
className={control}
|
||||
value={valueText(value ?? '')}
|
||||
maxLength={schema.maxLength}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div>
|
||||
<label htmlFor={path} className="block">
|
||||
{label}
|
||||
</label>
|
||||
{input}
|
||||
<FieldErrors path={path} errors={errors} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
export default function OpportunityCanonicalFields({
|
||||
value,
|
||||
onChange,
|
||||
options,
|
||||
category,
|
||||
organization,
|
||||
actorId,
|
||||
sectors,
|
||||
disabled = false,
|
||||
errors = {},
|
||||
}: {
|
||||
value: Data;
|
||||
onChange: (v: Data) => void;
|
||||
options: CanonicalOptions;
|
||||
category: string;
|
||||
organization: string | null;
|
||||
actorId: number;
|
||||
sectors: { id: number; name: string }[];
|
||||
disabled?: boolean;
|
||||
errors?: Record<string, string>;
|
||||
}) {
|
||||
const set = (key: string, v: unknown) =>
|
||||
onChange({
|
||||
...value,
|
||||
[key]: v,
|
||||
...(key === 'sector_id'
|
||||
? { subsector_id: null, economic_activity_id: null }
|
||||
: key === 'subsector_id'
|
||||
? { economic_activity_id: null }
|
||||
: {}),
|
||||
opportunity_category: category,
|
||||
promoter_id: organization ?? actorId,
|
||||
});
|
||||
const common = [
|
||||
'official_title',
|
||||
'promoter_type',
|
||||
'internal_contact_id',
|
||||
'publish_contact',
|
||||
'public_contact_id',
|
||||
'sector_id',
|
||||
'subsector_id',
|
||||
'economic_activity_id',
|
||||
'location_mode',
|
||||
'geographic_scope',
|
||||
'multi_district_rationale',
|
||||
'locations',
|
||||
'executive_summary',
|
||||
'demand_statement',
|
||||
'documents',
|
||||
'evidences',
|
||||
'publication_languages',
|
||||
'visibility',
|
||||
'currency',
|
||||
'review_due_date',
|
||||
'images',
|
||||
'truth_declaration',
|
||||
];
|
||||
const specialized =
|
||||
category === 'real_estate'
|
||||
? ['real_estate']
|
||||
: category === 'land_rights'
|
||||
? ['land_rights']
|
||||
: ['business_sale', 'business_partnership', 'franchise'].includes(
|
||||
category,
|
||||
)
|
||||
? ['module_profile_version', 'business_transaction']
|
||||
: category === 'investment_project'
|
||||
? [
|
||||
'opportunity_type',
|
||||
'maturity_stage',
|
||||
'investment_modalities',
|
||||
'investor_profiles',
|
||||
'products',
|
||||
'assets',
|
||||
'inputs',
|
||||
'markets',
|
||||
'competitive_advantage',
|
||||
'employment',
|
||||
'impact_indicators',
|
||||
'total_investment',
|
||||
'currency',
|
||||
'investment_breakdown',
|
||||
'secured_financing',
|
||||
'funding_sought',
|
||||
'financial_indicators',
|
||||
'milestones',
|
||||
'licenses',
|
||||
'environmental_social',
|
||||
'risks',
|
||||
'relations',
|
||||
]
|
||||
: [
|
||||
'module_profile_version',
|
||||
'module_details',
|
||||
...(category === 'financing'
|
||||
? [
|
||||
'total_investment',
|
||||
'investment_breakdown',
|
||||
'secured_financing',
|
||||
'funding_sought',
|
||||
]
|
||||
: []),
|
||||
];
|
||||
const details = (value.module_details ?? {}) as Data;
|
||||
const mode = valueText(details.mode ?? '');
|
||||
const modularFields = [
|
||||
'mode',
|
||||
'object',
|
||||
'representation_document_id',
|
||||
'object_document_id',
|
||||
...(category === 'concession'
|
||||
? [
|
||||
'granting_entity',
|
||||
'procedure_regime',
|
||||
'scope',
|
||||
'term_value',
|
||||
'term_unit',
|
||||
'remuneration_obligations',
|
||||
'participation_conditions',
|
||||
'land_required',
|
||||
'construction_required',
|
||||
'applicable_authorizations',
|
||||
'start_date',
|
||||
'end_date',
|
||||
'disclosure_authorization_document_id',
|
||||
'external_decision_document_id',
|
||||
'territorial_right_document_id',
|
||||
'construction_license_document_id',
|
||||
]
|
||||
: []),
|
||||
...(['financing', 'supply'].includes(category)
|
||||
? [
|
||||
'conditions_status',
|
||||
'terms',
|
||||
'scenario',
|
||||
'source',
|
||||
'terms_date',
|
||||
'commitment_document_id',
|
||||
]
|
||||
: []),
|
||||
...(category === 'financing'
|
||||
? [
|
||||
'instrument',
|
||||
'disbursement_calendar',
|
||||
'term_value',
|
||||
'term_unit',
|
||||
'repayment_periodicity',
|
||||
'equity_percentage',
|
||||
'proposed_rights',
|
||||
...(mode === 'funding_offer'
|
||||
? [
|
||||
'offered_capacity',
|
||||
'eligibility_criteria',
|
||||
'capacity_document_id',
|
||||
]
|
||||
: [
|
||||
'use_of_funds',
|
||||
'financial_plan_document_id',
|
||||
'secured_evidence_document_id',
|
||||
]),
|
||||
]
|
||||
: []),
|
||||
...(category === 'supply'
|
||||
? [
|
||||
'quantity',
|
||||
'unit',
|
||||
'destination',
|
||||
'start_date',
|
||||
'end_date',
|
||||
'acceptance_criteria',
|
||||
'quotation_method',
|
||||
'unit_price',
|
||||
'total_price',
|
||||
'declared_taxes',
|
||||
'advance_or_guarantee',
|
||||
...(mode === 'supply_offer' ? ['capacity_document_id'] : []),
|
||||
]
|
||||
: []),
|
||||
...(category === 'other'
|
||||
? ['subtype', 'purpose', 'recipients', 'expected_output', 'risks']
|
||||
: []),
|
||||
];
|
||||
const modes =
|
||||
category === 'concession'
|
||||
? ['intention_call', 'awarded_right']
|
||||
: category === 'financing'
|
||||
? ['seeking_funding', 'funding_offer']
|
||||
: category === 'supply'
|
||||
? ['purchase_request', 'supply_offer']
|
||||
: ['classified_other'];
|
||||
return (
|
||||
<fieldset disabled={disabled} className="space-y-4 rounded border p-4">
|
||||
<legend>Contrato da oportunidade — {category}</legend>
|
||||
<p>
|
||||
O rascunho pode ficar incompleto. A submissão verifica os campos
|
||||
aplicáveis e os recursos guardados. Validação interna não
|
||||
equivale a autorização externa.
|
||||
</p>
|
||||
{options.modularProfiles?.[category] && (
|
||||
<p className="rounded border border-amber-400 p-3">
|
||||
Primeira versão QA: {options.modularProfiles[category]}.
|
||||
Selecione-a explicitamente no campo de versão. Financiamento
|
||||
distingue procura do projeto de oferta do financiador;
|
||||
fornecimento distingue pedido de compra de oferta. Condições
|
||||
propostas não representam compromisso nem decisão externa.
|
||||
</p>
|
||||
)}
|
||||
{Array.from(new Set([...common, ...specialized])).map((key) => {
|
||||
if (key === 'module_profile_version') {
|
||||
const current = valueText(value[key] ?? '');
|
||||
const version =
|
||||
options.modularProfiles?.[category] ??
|
||||
([
|
||||
'business_sale',
|
||||
'business_partnership',
|
||||
'franchise',
|
||||
].includes(category)
|
||||
? options.historyVersion
|
||||
: null);
|
||||
return (
|
||||
<label key={key} className="block">
|
||||
{labels[key]}
|
||||
<select
|
||||
className={control}
|
||||
value={current}
|
||||
onChange={(e) =>
|
||||
set(key, e.target.value || null)
|
||||
}
|
||||
>
|
||||
<option value="">
|
||||
Contrato original / por selecionar
|
||||
</option>
|
||||
{current && current !== version && (
|
||||
<option value={current}>
|
||||
{current} — versão existente preservada
|
||||
</option>
|
||||
)}
|
||||
{version && (
|
||||
<option value={version}>{version}</option>
|
||||
)}
|
||||
</select>
|
||||
<FieldErrors
|
||||
path={'canonical.' + key}
|
||||
errors={errors}
|
||||
/>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
if (
|
||||
[
|
||||
'sector_id',
|
||||
'subsector_id',
|
||||
'economic_activity_id',
|
||||
'internal_contact_id',
|
||||
'public_contact_id',
|
||||
].includes(key)
|
||||
) {
|
||||
const rows =
|
||||
key === 'sector_id'
|
||||
? sectors.map((s) => ({ id: s.id, label: s.name }))
|
||||
: [
|
||||
'internal_contact_id',
|
||||
'public_contact_id',
|
||||
].includes(key)
|
||||
? options.contacts.map((c) => ({
|
||||
id: c.id,
|
||||
label: c.full_name,
|
||||
}))
|
||||
: options.activities
|
||||
.filter((a) =>
|
||||
key === 'subsector_id'
|
||||
? options.activities.some(
|
||||
(root) =>
|
||||
root.sector_id ===
|
||||
Number(
|
||||
value.sector_id,
|
||||
) &&
|
||||
a.parent_id === root.id,
|
||||
)
|
||||
: a.parent_id ===
|
||||
value.subsector_id,
|
||||
)
|
||||
.map((a) => ({
|
||||
id: a.id,
|
||||
label: a.label_pt_mz,
|
||||
}));
|
||||
return (
|
||||
<label key={key} className="block">
|
||||
{labels[key]}
|
||||
<FieldErrors
|
||||
path={'canonical.' + key}
|
||||
errors={errors}
|
||||
/>
|
||||
<select
|
||||
className={control}
|
||||
value={valueText(value[key] ?? '')}
|
||||
onChange={(e) =>
|
||||
set(
|
||||
key,
|
||||
e.target.value === ''
|
||||
? null
|
||||
: key === 'sector_id'
|
||||
? Number(e.target.value)
|
||||
: e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{rows.map((r) => (
|
||||
<option key={r.id} value={r.id}>
|
||||
{r.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
if (['locations', 'documents', 'images'].includes(key)) {
|
||||
const selected = Array.isArray(value[key])
|
||||
? (value[key] as string[])
|
||||
: [];
|
||||
return (
|
||||
<fieldset key={key}>
|
||||
<legend>{labels[key]}</legend>
|
||||
<FieldErrors
|
||||
path={'canonical.' + key}
|
||||
errors={errors}
|
||||
/>
|
||||
{(options.resources[key] ?? []).map((r) => (
|
||||
<label key={r.id} className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selected.includes(r.id)}
|
||||
onChange={(e) =>
|
||||
set(
|
||||
key,
|
||||
e.target.checked
|
||||
? [...selected, r.id]
|
||||
: selected.filter(
|
||||
(id) => id !== r.id,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>{' '}
|
||||
{r.payload.title ??
|
||||
r.payload.role ??
|
||||
r.file?.file_name ??
|
||||
r.id}
|
||||
<FieldErrors
|
||||
path={`canonical.${key}.${r.id}`}
|
||||
errors={errors}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
{key === 'locations' &&
|
||||
selected.map((id) => (
|
||||
<TerritoryGeometryPreview
|
||||
key={id}
|
||||
territoryId={resourceTerritory(
|
||||
options.resources.locations?.find(
|
||||
(r) => r.id === id,
|
||||
),
|
||||
)}
|
||||
endpoint="/minhas-oportunidades/territory-geometries"
|
||||
label={`Cobertura cartográfica da localização ${options.resources.locations?.find((r) => r.id === id)?.payload.title ?? selected.indexOf(id) + 1}`}
|
||||
/>
|
||||
))}
|
||||
{!options.resources[key]?.length && (
|
||||
<p>
|
||||
Guarde primeiro em Recursos e regresse a
|
||||
este contrato.
|
||||
</p>
|
||||
)}
|
||||
</fieldset>
|
||||
);
|
||||
}
|
||||
let schema = options.schema.properties?.[key];
|
||||
if (key === 'module_details' && schema?.properties) {
|
||||
schema = {
|
||||
...schema,
|
||||
properties: Object.fromEntries(
|
||||
Object.entries(schema.properties).filter(
|
||||
([field]) => modularFields.includes(field),
|
||||
),
|
||||
),
|
||||
};
|
||||
schema.properties!.mode = { enum: modes };
|
||||
}
|
||||
return schema ? (
|
||||
<Editor
|
||||
key={key}
|
||||
name={key}
|
||||
path={'canonical.' + key}
|
||||
errors={errors}
|
||||
schema={schema}
|
||||
value={value[key]}
|
||||
options={options}
|
||||
onChange={(v) => set(key, v)}
|
||||
/>
|
||||
) : null;
|
||||
})}
|
||||
</fieldset>
|
||||
);
|
||||
}
|
||||
+224
@@ -0,0 +1,224 @@
|
||||
import InteractiveInvestmentMap from './interactive-investment-map';
|
||||
import { control } from '@/pages/management/shared';
|
||||
import type { MultiPolygon } from 'geojson';
|
||||
|
||||
type Point = [number | null, number | null];
|
||||
export default function OpportunityParcelGeometry({
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
value: unknown;
|
||||
onChange: (v: unknown) => void;
|
||||
}) {
|
||||
const data =
|
||||
value && typeof value === 'object'
|
||||
? (value as { coordinates?: Point[][][] })
|
||||
: {};
|
||||
const polygons = Array.isArray(data.coordinates) ? data.coordinates : [];
|
||||
function replace(p: number, r: number, points: Point[]) {
|
||||
onChange({
|
||||
type: 'MultiPolygon',
|
||||
coordinates: polygons.map((poly, i) =>
|
||||
i === p
|
||||
? poly.map((ring, j) => (j === r ? points : ring))
|
||||
: poly,
|
||||
),
|
||||
});
|
||||
}
|
||||
const valid =
|
||||
polygons.length > 0 &&
|
||||
polygons.every(
|
||||
(poly) =>
|
||||
poly.length > 0 &&
|
||||
poly.every(
|
||||
(ring) =>
|
||||
ring.length >= 4 &&
|
||||
ring.every(
|
||||
(point) =>
|
||||
point.length === 2 &&
|
||||
point.every(
|
||||
(c) =>
|
||||
typeof c === 'number' &&
|
||||
Number.isFinite(c),
|
||||
),
|
||||
) &&
|
||||
ring[0][0] === ring.at(-1)?.[0] &&
|
||||
ring[0][1] === ring.at(-1)?.[1],
|
||||
),
|
||||
);
|
||||
return (
|
||||
<section className="space-y-2">
|
||||
<p>
|
||||
Indique longitude e latitude do perímetro declarado. O limite
|
||||
administrativo serve de contexto; não define a parcela.
|
||||
</p>
|
||||
{polygons.map((poly, p) => (
|
||||
<fieldset key={p} className="rounded border p-2">
|
||||
<legend>Polígono {p + 1}</legend>
|
||||
{poly.map((ring, r) => (
|
||||
<section key={r}>
|
||||
<p className="font-medium">
|
||||
{r === 0
|
||||
? 'Anel exterior'
|
||||
: `Anel interior ${r}`}
|
||||
</p>
|
||||
{ring.map((point, i) => (
|
||||
<div key={i} className="flex flex-wrap gap-2">
|
||||
{[0, 1].map((axis) => (
|
||||
<label key={axis}>
|
||||
{axis === 0
|
||||
? 'Longitude'
|
||||
: 'Latitude'}
|
||||
<input
|
||||
className={control}
|
||||
type="number"
|
||||
step="any"
|
||||
min={axis === 0 ? -180 : -90}
|
||||
max={axis === 0 ? 180 : 90}
|
||||
value={point[axis] ?? ''}
|
||||
onChange={(e) =>
|
||||
replace(
|
||||
p,
|
||||
r,
|
||||
ring.map((v, j) =>
|
||||
j === i
|
||||
? (v.map(
|
||||
(c, k) =>
|
||||
k ===
|
||||
axis
|
||||
? e
|
||||
.target
|
||||
.value ===
|
||||
''
|
||||
? null
|
||||
: Number(
|
||||
e
|
||||
.target
|
||||
.value,
|
||||
)
|
||||
: c,
|
||||
) as Point)
|
||||
: v,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
replace(
|
||||
p,
|
||||
r,
|
||||
ring.filter((_, j) => j !== i),
|
||||
)
|
||||
}
|
||||
>
|
||||
Retirar vértice {i + 1}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className="mr-4 underline"
|
||||
onClick={() =>
|
||||
replace(p, r, [...ring, [null, null]])
|
||||
}
|
||||
>
|
||||
Adicionar vértice
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="mr-4 underline"
|
||||
disabled={
|
||||
!ring.length ||
|
||||
ring[0].some((c) => c === null)
|
||||
}
|
||||
onClick={() =>
|
||||
replace(p, r, [
|
||||
...ring,
|
||||
[...ring[0]] as Point,
|
||||
])
|
||||
}
|
||||
>
|
||||
Fechar anel
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
onChange({
|
||||
type: 'MultiPolygon',
|
||||
coordinates: polygons.map((v, i) =>
|
||||
i === p
|
||||
? v.filter((_, j) => j !== r)
|
||||
: v,
|
||||
),
|
||||
})
|
||||
}
|
||||
>
|
||||
Retirar anel
|
||||
</button>
|
||||
</section>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className="mr-4 underline"
|
||||
onClick={() =>
|
||||
onChange({
|
||||
type: 'MultiPolygon',
|
||||
coordinates: polygons.map((v, i) =>
|
||||
i === p ? [...v, []] : v,
|
||||
),
|
||||
})
|
||||
}
|
||||
>
|
||||
Adicionar anel interior
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
onChange({
|
||||
type: 'MultiPolygon',
|
||||
coordinates: polygons.filter((_, i) => i !== p),
|
||||
})
|
||||
}
|
||||
>
|
||||
Retirar polígono
|
||||
</button>
|
||||
</fieldset>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
onClick={() =>
|
||||
onChange({
|
||||
type: 'MultiPolygon',
|
||||
coordinates: [...polygons, [[]]],
|
||||
})
|
||||
}
|
||||
>
|
||||
Adicionar polígono
|
||||
</button>
|
||||
{valid && (
|
||||
<InteractiveInvestmentMap
|
||||
points={[]}
|
||||
contextOnly
|
||||
areas={[
|
||||
{
|
||||
purpose: 'declared_parcel',
|
||||
title: 'Perímetro declarado pelo Promotor',
|
||||
source_reference:
|
||||
'Declaração do Promotor; revisão cadastral pendente',
|
||||
url: '#',
|
||||
geometry: {
|
||||
type: 'MultiPolygon',
|
||||
coordinates: polygons as [number, number][][][],
|
||||
} as MultiPolygon,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
+559
@@ -0,0 +1,559 @@
|
||||
import { router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { profileJson, ProfileValidationError } from '@/lib/profile-json';
|
||||
import { button, control } from '@/pages/management/shared';
|
||||
|
||||
export default function OpportunityProfileActions({
|
||||
id,
|
||||
etag,
|
||||
actions,
|
||||
gates,
|
||||
documents,
|
||||
approvalHash,
|
||||
onErrors,
|
||||
participants = [],
|
||||
publishers = [],
|
||||
opinions = [],
|
||||
publicationVisibility,
|
||||
conditions = [],
|
||||
conditionResponsibles = [],
|
||||
}: {
|
||||
id: number;
|
||||
etag: string;
|
||||
actions: string[];
|
||||
gates: string[];
|
||||
documents: { id: string; title: string }[];
|
||||
approvalHash?: string;
|
||||
publicationVisibility?: string;
|
||||
conditions?: {
|
||||
id: string;
|
||||
gate: string;
|
||||
description: string;
|
||||
responsible_name: string;
|
||||
due_on: string | null;
|
||||
blocking_action: string;
|
||||
status: string;
|
||||
}[];
|
||||
conditionResponsibles?: { id: number; name: string }[];
|
||||
onErrors?: (errors: Record<string, string>) => void;
|
||||
publishers?: { id: number; name: string }[];
|
||||
participants?: {
|
||||
id: number;
|
||||
name: string;
|
||||
technical: boolean;
|
||||
legal: boolean;
|
||||
}[];
|
||||
opinions?: {
|
||||
id: string;
|
||||
gate: string;
|
||||
recipient_id: number;
|
||||
status: string;
|
||||
}[];
|
||||
}) {
|
||||
const [reason, setReason] = useState('');
|
||||
const [items, setItems] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
const [gate, setGate] = useState(gates[0] ?? '');
|
||||
const [decision, setDecision] = useState('approved');
|
||||
const [evidence, setEvidence] = useState<string[]>([]);
|
||||
const [assignee, setAssignee] = useState('');
|
||||
const [confirmed, setConfirmed] = useState(false);
|
||||
const [recipient, setRecipient] = useState('');
|
||||
const [opinion, setOpinion] = useState('');
|
||||
const [conditionDescription, setConditionDescription] = useState('');
|
||||
const [conditionResponsible, setConditionResponsible] = useState('');
|
||||
const [conditionDue, setConditionDue] = useState('');
|
||||
const [conditionBlocking, setConditionBlocking] = useState('approve');
|
||||
const [resolvedConditions, setResolvedConditions] = useState<string[]>([]);
|
||||
const [actionErrors, setActionErrors] = useState<Record<string, string>>(
|
||||
{},
|
||||
);
|
||||
const labels: Record<string, string> = {
|
||||
submit: 'Submeter para validação',
|
||||
approve: 'Aprovar versão',
|
||||
publish:
|
||||
publicationVisibility === 'public'
|
||||
? 'Publicar no catálogo público'
|
||||
: 'Disponibilizar com acesso restrito',
|
||||
request_revision: 'Preparar alteração material',
|
||||
review_gate: 'Guardar revisão especializada',
|
||||
assign_review: 'Atribuir validação',
|
||||
assign_publication: 'Atribuir publicação',
|
||||
appeal_uphold: 'Manter rejeição após recurso',
|
||||
appeal_reopen: 'Reabrir para correção',
|
||||
request_archive: 'Solicitar arquivo',
|
||||
appeal: 'Apresentar recurso',
|
||||
start_review: 'Iniciar validação',
|
||||
request_correction: 'Solicitar correções',
|
||||
pending_opinion: 'Solicitar parecer',
|
||||
respond_opinion: 'Responder ao parecer',
|
||||
reject: 'Rejeitar com fundamento',
|
||||
suspend: 'Suspender',
|
||||
archive: 'Arquivar',
|
||||
};
|
||||
async function send(action: string) {
|
||||
setBusy(true);
|
||||
setActionErrors({});
|
||||
onErrors?.({});
|
||||
try {
|
||||
const result = await profileJson(
|
||||
`/minhas-oportunidades/${id}/workflow`,
|
||||
{
|
||||
etag,
|
||||
action,
|
||||
reason,
|
||||
correction_items: items
|
||||
.split('\n')
|
||||
.map((v) => v.trim())
|
||||
.filter(Boolean),
|
||||
...(['review_gate', 'respond_opinion'].includes(action)
|
||||
? {
|
||||
gate,
|
||||
gate_decision: decision,
|
||||
evidence_document_ids: evidence,
|
||||
}
|
||||
: {}),
|
||||
...(action === 'review_gate'
|
||||
? {
|
||||
resolve_condition_ids: resolvedConditions,
|
||||
...(conditionDescription.trim()
|
||||
? {
|
||||
condition: {
|
||||
description:
|
||||
conditionDescription.trim(),
|
||||
responsible_user_id:
|
||||
Number(conditionResponsible),
|
||||
due_on: conditionDue || null,
|
||||
blocking_action: conditionBlocking,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
}
|
||||
: {}),
|
||||
...(action === 'pending_opinion'
|
||||
? { gate, recipient_user_id: Number(recipient) }
|
||||
: {}),
|
||||
...(action === 'respond_opinion'
|
||||
? { opinion_id: opinion }
|
||||
: {}),
|
||||
...(['assign_review', 'assign_publication'].includes(action)
|
||||
? { assignee_user_id: Number(assignee) }
|
||||
: {}),
|
||||
...(action === 'publish'
|
||||
? {
|
||||
confirm_publication: confirmed,
|
||||
preview_hash: approvalHash,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
);
|
||||
setMessage(result.message);
|
||||
router.visit(`/minhas-oportunidades/${id}/view`);
|
||||
} catch (error) {
|
||||
if (error instanceof ProfileValidationError) {
|
||||
setActionErrors(error.fields);
|
||||
onErrors?.(error.fields);
|
||||
const first = Object.keys(error.fields)[0];
|
||||
requestAnimationFrame(() =>
|
||||
document
|
||||
.getElementById(
|
||||
`workflow-${id}-${first?.startsWith('conditions.') ? 'conditions' : first}`,
|
||||
)
|
||||
?.focus(),
|
||||
);
|
||||
}
|
||||
setMessage(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Resposta indisponível. Confira o estado antes de repetir.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<section
|
||||
className="space-y-3 rounded border p-4"
|
||||
aria-label="Workflow interno"
|
||||
>
|
||||
<h2 className="text-lg font-semibold">Workflow interno</h2>
|
||||
<p>
|
||||
Guarde o contrato antes de submeter. Aprovação exige revisões
|
||||
especializadas desta versão; publicação exige outro utilizador
|
||||
autorizado. Uma decisão interna não substitui decisão externa.
|
||||
</p>
|
||||
<p>
|
||||
Aprovação interna confirma a revisão desta versão.
|
||||
Disponibilização restrita não aparece no catálogo público nem dá
|
||||
acesso a todas as contas. A publicação pública exige âmbito
|
||||
público e ação independente do Publicador; não representa uma
|
||||
decisão externa.
|
||||
</p>
|
||||
{conditions.length > 0 && (
|
||||
<section
|
||||
aria-label="Condições de revisão"
|
||||
id={`workflow-${id}-conditions`}
|
||||
tabIndex={-1}
|
||||
>
|
||||
<h3>Condições e evidências</h3>
|
||||
{conditions.map((c) => (
|
||||
<p key={c.id}>
|
||||
{c.description} —{' '}
|
||||
{c.status === 'resolved'
|
||||
? 'Verificada internamente'
|
||||
: 'Pendente'}
|
||||
; responsável: {c.responsible_name}; prazo:{' '}
|
||||
{c.due_on ?? 'não definido'}; impede:{' '}
|
||||
{c.blocking_action === 'approve'
|
||||
? 'aprovação'
|
||||
: 'publicação'}
|
||||
. A verificação interna não constitui decisão
|
||||
externa.
|
||||
</p>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
{!!actions.length && (
|
||||
<>
|
||||
<label className="block">
|
||||
Fundamentação
|
||||
<textarea
|
||||
id={`workflow-${id}-reason`}
|
||||
aria-invalid={!!actionErrors.reason}
|
||||
aria-describedby={
|
||||
actionErrors.reason
|
||||
? `workflow-${id}-reason-error`
|
||||
: undefined
|
||||
}
|
||||
className={control}
|
||||
minLength={20}
|
||||
maxLength={1000}
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
/>
|
||||
{actionErrors.reason && (
|
||||
<span
|
||||
id={`workflow-${id}-reason-error`}
|
||||
role="alert"
|
||||
>
|
||||
{actionErrors.reason}
|
||||
</span>
|
||||
)}
|
||||
</label>
|
||||
{actions.includes('request_correction') && (
|
||||
<label className="block">
|
||||
Campos ou documentos a corrigir, um por linha
|
||||
<textarea
|
||||
className={control}
|
||||
value={items}
|
||||
onChange={(e) => setItems(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
{(actions.includes('review_gate') ||
|
||||
actions.includes('pending_opinion') ||
|
||||
actions.includes('respond_opinion')) && (
|
||||
<fieldset>
|
||||
<legend>Revisão especializada</legend>
|
||||
<label>
|
||||
Revisão
|
||||
<select
|
||||
id={`workflow-${id}-gate`}
|
||||
className={control}
|
||||
value={gate}
|
||||
onChange={(e) => setGate(e.target.value)}
|
||||
>
|
||||
{gates.map((g) => (
|
||||
<option key={g} value={g}>
|
||||
{g.replaceAll('_', ' ')}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Decisão
|
||||
<select
|
||||
className={control}
|
||||
value={decision}
|
||||
onChange={(e) =>
|
||||
setDecision(e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="approved">Aprovada</option>
|
||||
<option value="rejected">Rejeitada</option>
|
||||
</select>
|
||||
</label>
|
||||
{documents.map((d) => (
|
||||
<label key={d.id} className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={evidence.includes(d.id)}
|
||||
onChange={(e) =>
|
||||
setEvidence(
|
||||
e.target.checked
|
||||
? [...evidence, d.id]
|
||||
: evidence.filter(
|
||||
(id) => id !== d.id,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>{' '}
|
||||
{d.title}
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
)}
|
||||
{actions.includes('review_gate') && (
|
||||
<fieldset className="space-y-2">
|
||||
<legend>Condição explícita desta revisão</legend>
|
||||
<p>
|
||||
Opcional. Só bloqueia a ação indicada. Sem prazo
|
||||
automático ou responsabilidade externa
|
||||
atribuída.
|
||||
</p>
|
||||
<label className="block">
|
||||
Descrição da condição
|
||||
<textarea
|
||||
className={control}
|
||||
id={`workflow-${id}-condition.description`}
|
||||
value={conditionDescription}
|
||||
onChange={(e) =>
|
||||
setConditionDescription(e.target.value)
|
||||
}
|
||||
aria-invalid={
|
||||
!!actionErrors['condition.description']
|
||||
}
|
||||
aria-describedby={
|
||||
actionErrors['condition.description']
|
||||
? `workflow-${id}-condition.description-error`
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
{actionErrors['condition.description'] && (
|
||||
<span
|
||||
id={`workflow-${id}-condition.description-error`}
|
||||
role="alert"
|
||||
>
|
||||
{actionErrors['condition.description']}
|
||||
</span>
|
||||
)}
|
||||
</label>
|
||||
<label className="block">
|
||||
Responsável pela preparação da evidência
|
||||
<select
|
||||
className={control}
|
||||
id={`workflow-${id}-condition.responsible_user_id`}
|
||||
value={conditionResponsible}
|
||||
onChange={(e) =>
|
||||
setConditionResponsible(e.target.value)
|
||||
}
|
||||
aria-invalid={
|
||||
!!actionErrors[
|
||||
'condition.responsible_user_id'
|
||||
]
|
||||
}
|
||||
aria-describedby={
|
||||
actionErrors[
|
||||
'condition.responsible_user_id'
|
||||
]
|
||||
? `workflow-${id}-condition.responsible_user_id-error`
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<option value="">Selecione</option>
|
||||
{conditionResponsibles.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{actionErrors[
|
||||
'condition.responsible_user_id'
|
||||
] && (
|
||||
<span
|
||||
id={`workflow-${id}-condition.responsible_user_id-error`}
|
||||
role="alert"
|
||||
>
|
||||
{
|
||||
actionErrors[
|
||||
'condition.responsible_user_id'
|
||||
]
|
||||
}
|
||||
</span>
|
||||
)}
|
||||
</label>
|
||||
<label className="block">
|
||||
Prazo específico da condição, se definido
|
||||
<input
|
||||
className={control}
|
||||
type="date"
|
||||
id={`workflow-${id}-condition.due_on`}
|
||||
value={conditionDue}
|
||||
onChange={(e) =>
|
||||
setConditionDue(e.target.value)
|
||||
}
|
||||
aria-invalid={
|
||||
!!actionErrors['condition.due_on']
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
Ação impedida até verificação
|
||||
<select
|
||||
className={control}
|
||||
value={conditionBlocking}
|
||||
onChange={(e) =>
|
||||
setConditionBlocking(e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="approve">Aprovação</option>
|
||||
<option value="publish">Publicação</option>
|
||||
</select>
|
||||
</label>
|
||||
{conditions
|
||||
.filter(
|
||||
(c) =>
|
||||
c.gate === gate && c.status === 'open',
|
||||
)
|
||||
.map((c) => (
|
||||
<label key={c.id} className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={resolvedConditions.includes(
|
||||
c.id,
|
||||
)}
|
||||
onChange={(e) =>
|
||||
setResolvedConditions(
|
||||
e.target.checked
|
||||
? [
|
||||
...resolvedConditions,
|
||||
c.id,
|
||||
]
|
||||
: resolvedConditions.filter(
|
||||
(id) =>
|
||||
id !== c.id,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
Verifiquei com os documentos
|
||||
selecionados: {c.description}
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
)}
|
||||
{(actions.includes('assign_review') ||
|
||||
actions.includes('assign_publication')) && (
|
||||
<label className="block">
|
||||
Responsável a designar
|
||||
<select
|
||||
className={control}
|
||||
value={assignee}
|
||||
onChange={(e) => setAssignee(e.target.value)}
|
||||
>
|
||||
<option value="">Por atribuir</option>
|
||||
{(actions.includes('assign_publication')
|
||||
? publishers
|
||||
: participants
|
||||
).map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<span>
|
||||
O servidor verifica o papel, âmbito e
|
||||
independência. Nenhum responsável é atribuído
|
||||
automaticamente.
|
||||
</span>
|
||||
</label>
|
||||
)}
|
||||
{actions.includes('pending_opinion') && (
|
||||
<label className="block">
|
||||
Destinatário do parecer
|
||||
<select
|
||||
className={control}
|
||||
value={recipient}
|
||||
onChange={(e) => setRecipient(e.target.value)}
|
||||
>
|
||||
<option value="">Por designar</option>
|
||||
{participants
|
||||
.filter((p) =>
|
||||
/legal|registry|authority|confidentiality|license/.test(
|
||||
gate,
|
||||
)
|
||||
? p.legal
|
||||
: p.technical,
|
||||
)
|
||||
.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
{actions.includes('respond_opinion') && (
|
||||
<label className="block">
|
||||
Parecer atribuído
|
||||
<select
|
||||
className={control}
|
||||
value={opinion}
|
||||
onChange={(e) => setOpinion(e.target.value)}
|
||||
>
|
||||
<option value="">Selecione</option>
|
||||
{opinions
|
||||
.filter((o) => o.status === 'pending')
|
||||
.map((o) => (
|
||||
<option key={o.id} value={o.id}>
|
||||
{o.gate.replaceAll('_', ' ')} —
|
||||
conta {o.recipient_id}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
{Object.entries(actionErrors)
|
||||
.filter(([key]) => !key.startsWith('canonical'))
|
||||
.map(([key, msg]) => (
|
||||
<p key={key} role="alert">
|
||||
{key.startsWith('conditions.')
|
||||
? 'Condição de revisão'
|
||||
: key}
|
||||
: {msg}
|
||||
</p>
|
||||
))}
|
||||
{actions.includes('publish') && (
|
||||
<label className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={confirmed}
|
||||
onChange={(e) => setConfirmed(e.target.checked)}
|
||||
/>{' '}
|
||||
Confirmei a pré-visualização e o âmbito de
|
||||
divulgação desta versão.
|
||||
</label>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{actions.map((action) => (
|
||||
<button
|
||||
key={action}
|
||||
className={button}
|
||||
disabled={
|
||||
busy || (action === 'publish' && !confirmed)
|
||||
}
|
||||
onClick={() => void send(action)}
|
||||
>
|
||||
{labels[action] ?? action}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<p role="status" aria-live="polite">
|
||||
{message}
|
||||
</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import InteractiveInvestmentMap, {
|
||||
type InvestmentMapArea,
|
||||
} from './interactive-investment-map';
|
||||
|
||||
const noPoints: [] = [];
|
||||
type Context = {
|
||||
selected_geometry_available: boolean;
|
||||
context_geometry_count: number;
|
||||
areas: InvestmentMapArea[];
|
||||
truncated: boolean;
|
||||
};
|
||||
export default function TerritoryGeometryPreview({
|
||||
territoryId,
|
||||
management = false,
|
||||
endpoint: suppliedEndpoint,
|
||||
label = 'Cobertura cartográfica da seleção',
|
||||
}: {
|
||||
territoryId?: string;
|
||||
management?: boolean;
|
||||
endpoint?: string;
|
||||
label?: string;
|
||||
}) {
|
||||
const [context, setContext] = useState<Context | null>(null);
|
||||
const [error, setError] = useState('');
|
||||
useEffect(() => {
|
||||
setContext(null);
|
||||
setError('');
|
||||
if (!territoryId) return;
|
||||
const controller = new AbortController();
|
||||
const endpoint =
|
||||
suppliedEndpoint ??
|
||||
(management
|
||||
? '/management/territory-geometries'
|
||||
: '/api/v1/investment/territory-geometries');
|
||||
void fetch(
|
||||
`${endpoint}?${new URLSearchParams({ territory_id: territoryId })}`,
|
||||
{
|
||||
signal: controller.signal,
|
||||
headers: { Accept: 'application/json' },
|
||||
},
|
||||
)
|
||||
.then(async (response) => {
|
||||
if (!response.ok)
|
||||
throw new Error(
|
||||
'Não foi possível consultar os limites administrativos.',
|
||||
);
|
||||
return response.json() as Promise<Context>;
|
||||
})
|
||||
.then((data) => {
|
||||
if (!controller.signal.aborted) setContext(data);
|
||||
})
|
||||
.catch((e: unknown) => {
|
||||
if (!controller.signal.aborted)
|
||||
setError(
|
||||
e instanceof Error ? e.message : 'Erro de ligação.',
|
||||
);
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [territoryId, management, suppliedEndpoint]);
|
||||
if (!territoryId) return null;
|
||||
return (
|
||||
<section className="space-y-2 md:col-span-full" aria-label={label}>
|
||||
<p>Território selecionado no cadastro.</p>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{!context && !error && <p role="status">A consultar geometria…</p>}
|
||||
{context && (
|
||||
<>
|
||||
<p role="status">
|
||||
{context.selected_geometry_available
|
||||
? 'Limite administrativo disponível para este território.'
|
||||
: 'Sem limite administrativo acessível para este território neste perfil.'}
|
||||
</p>
|
||||
<p>
|
||||
{context.context_geometry_count} limites disponíveis na
|
||||
hierarquia selecionada. São contexto administrativo, não
|
||||
perímetro nem disponibilidade de investimento. A edição
|
||||
e a atualidade jurídica são informações distintas.
|
||||
</p>
|
||||
{context.truncated && (
|
||||
<p role="alert">
|
||||
Exibidos os primeiros 100 limites; cobertura
|
||||
incompleta.
|
||||
</p>
|
||||
)}
|
||||
{context.areas.length > 0 && (
|
||||
<InteractiveInvestmentMap
|
||||
points={noPoints}
|
||||
areas={context.areas}
|
||||
contextOnly
|
||||
/>
|
||||
)}
|
||||
<ul>
|
||||
{context.areas.map((area, index) => (
|
||||
<li key={index}>
|
||||
{area.title} · Fonte:{' '}
|
||||
{area.source_reference ?? 'Não indicada'} ·
|
||||
Edição: {area.source_date ?? 'Não indicada'}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
+252
@@ -0,0 +1,252 @@
|
||||
import { Link, useForm } from '@inertiajs/react';
|
||||
import {
|
||||
Management,
|
||||
Pagination,
|
||||
button,
|
||||
control,
|
||||
states,
|
||||
type Paginated,
|
||||
} from './shared';
|
||||
|
||||
type Entry = {
|
||||
id: number;
|
||||
reference: string;
|
||||
title: string | null;
|
||||
status: string;
|
||||
opportunity_category: string | null;
|
||||
updated_at: string;
|
||||
deleted_at: string | null;
|
||||
can_edit?: boolean;
|
||||
working_status?: string;
|
||||
draft_title?: string;
|
||||
publication?: { scope: string; label: string; public_catalog: boolean };
|
||||
};
|
||||
export default function Opportunities({
|
||||
records,
|
||||
filters,
|
||||
counts,
|
||||
categories,
|
||||
sectors,
|
||||
geographyReviewCount,
|
||||
basePath = '/management/opportunities',
|
||||
canCreate = true,
|
||||
}: {
|
||||
records: Paginated<Entry>;
|
||||
filters: {
|
||||
q?: string;
|
||||
queue?: string;
|
||||
status?: string;
|
||||
category?: string;
|
||||
deleted?: boolean;
|
||||
sector_id?: string;
|
||||
geography_scope?: string;
|
||||
};
|
||||
counts: Record<string, number>;
|
||||
categories: string[];
|
||||
sectors: { id: number; name: string }[];
|
||||
geographyReviewCount: number;
|
||||
basePath?: string;
|
||||
canCreate?: boolean;
|
||||
}) {
|
||||
const form = useForm({
|
||||
q: filters.q ?? '',
|
||||
queue: filters.queue ?? '',
|
||||
status: filters.status ?? '',
|
||||
category: filters.category ?? '',
|
||||
deleted: Boolean(filters.deleted),
|
||||
sector_id: String(filters.sector_id ?? ''),
|
||||
geography_scope: filters.geography_scope ?? '',
|
||||
});
|
||||
return (
|
||||
<Management
|
||||
title={
|
||||
basePath === '/minhas-oportunidades'
|
||||
? 'Minhas oportunidades'
|
||||
: 'Gestão de Oportunidades'
|
||||
}
|
||||
>
|
||||
{canCreate && (
|
||||
<Link className={button} href={`${basePath}/create`}>
|
||||
Nova oportunidade
|
||||
</Link>
|
||||
)}
|
||||
<p>
|
||||
{geographyReviewCount} registos com âmbito por indicar;
|
||||
referências existentes permanecem aceites.
|
||||
</p>
|
||||
<section
|
||||
aria-label="Indicadores autorizados"
|
||||
className="grid gap-3 sm:grid-cols-3"
|
||||
>
|
||||
{[
|
||||
'draft',
|
||||
'submitted',
|
||||
'needs_information',
|
||||
'in_review',
|
||||
'information_pending',
|
||||
'returned',
|
||||
'approved',
|
||||
'published',
|
||||
'suspended',
|
||||
'rejected',
|
||||
'archived',
|
||||
].map((s) => (
|
||||
<Link
|
||||
className="rounded border p-3"
|
||||
key={s}
|
||||
href={`${basePath}?status=${s}`}
|
||||
>
|
||||
{states[s] ?? s}: {counts[s] ?? 0}
|
||||
</Link>
|
||||
))}
|
||||
</section>
|
||||
<form
|
||||
className="flex flex-wrap gap-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.transform((data) => ({
|
||||
...data,
|
||||
deleted: data.deleted ? '1' : '0',
|
||||
}));
|
||||
form.get(basePath);
|
||||
}}
|
||||
>
|
||||
{basePath === '/minhas-oportunidades' && (
|
||||
<label>
|
||||
Fila
|
||||
<select
|
||||
className={control}
|
||||
value={form.data.queue}
|
||||
onChange={(e) =>
|
||||
form.setData('queue', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Todas as autorizadas</option>
|
||||
<option value="assigned">Atribuídas a mim</option>
|
||||
<option value="review">
|
||||
Validação e pareceres
|
||||
</option>
|
||||
<option value="publication">
|
||||
Preparação editorial
|
||||
</option>
|
||||
<option value="appeal">Recursos pendentes</option>
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
<input
|
||||
aria-label="Pesquisa global"
|
||||
placeholder="Título ou referência"
|
||||
className={control}
|
||||
value={form.data.q}
|
||||
onChange={(e) => form.setData('q', e.target.value)}
|
||||
/>
|
||||
<select
|
||||
aria-label="Estado"
|
||||
className={control}
|
||||
value={form.data.status}
|
||||
onChange={(e) => form.setData('status', e.target.value)}
|
||||
>
|
||||
<option value="">Todos os estados</option>
|
||||
{Object.keys(counts).map((s) => (
|
||||
<option key={s} value={s}>
|
||||
{states[s] ?? s}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<select
|
||||
aria-label="Categoria"
|
||||
className={control}
|
||||
value={form.data.category}
|
||||
onChange={(e) => form.setData('category', e.target.value)}
|
||||
>
|
||||
<option value="">Todas as categorias</option>
|
||||
{categories.map((s) => (
|
||||
<option key={s}>{s}</option>
|
||||
))}
|
||||
</select>
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.data.deleted}
|
||||
onChange={(e) =>
|
||||
form.setData('deleted', e.target.checked)
|
||||
}
|
||||
/>{' '}
|
||||
Rascunhos eliminados logicamente
|
||||
</label>
|
||||
<select
|
||||
aria-label="Sector"
|
||||
className={control}
|
||||
value={form.data.sector_id}
|
||||
onChange={(e) => form.setData('sector_id', e.target.value)}
|
||||
>
|
||||
<option value="">Todos os sectores</option>
|
||||
{sectors.map((s) => (
|
||||
<option key={s.id} value={s.id}>
|
||||
{s.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<select
|
||||
aria-label="Âmbito geográfico"
|
||||
className={control}
|
||||
value={form.data.geography_scope}
|
||||
onChange={(e) =>
|
||||
form.setData('geography_scope', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Todos os âmbitos</option>
|
||||
{[
|
||||
'unspecified',
|
||||
'specific',
|
||||
'multiple',
|
||||
'national',
|
||||
'digital',
|
||||
].map((s) => (
|
||||
<option key={s}>{s}</option>
|
||||
))}
|
||||
</select>
|
||||
<button className={button} disabled={form.processing}>
|
||||
Pesquisar
|
||||
</button>
|
||||
</form>
|
||||
<div className="space-y-3">
|
||||
{records.data.map((r) => (
|
||||
<article key={r.id} className="rounded border p-4">
|
||||
<h2 className="font-semibold">
|
||||
{r.draft_title ?? r.title ?? 'Rascunho sem título'}
|
||||
</h2>
|
||||
<p>
|
||||
ID {r.id} · {r.reference} ·{' '}
|
||||
{r.opportunity_category ?? 'Categoria por indicar'}{' '}
|
||||
·{' '}
|
||||
{r.deleted_at
|
||||
? 'Eliminado logicamente'
|
||||
: (r.working_status ?? r.status) === 'published'
|
||||
? 'Versão disponibilizada'
|
||||
: (states[r.working_status ?? r.status] ??
|
||||
r.working_status ??
|
||||
r.status)}
|
||||
</p>
|
||||
{r.publication && <p>{r.publication.label}</p>}
|
||||
<p>Atualizado: {r.updated_at}</p>
|
||||
<div className="flex flex-wrap gap-4">
|
||||
<Link href={`${basePath}/${r.id}/view`}>Ver</Link>
|
||||
{r.can_edit !== false && (
|
||||
<Link href={`${basePath}/${r.id}/edit`}>
|
||||
{r.deleted_at || r.status === 'archived'
|
||||
? 'Restaurar'
|
||||
: r.status === 'draft'
|
||||
? 'Continuar preenchimento'
|
||||
: 'Editar nova versão'}
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
{!records.data.length && <p>Nenhum registo encontrado.</p>}
|
||||
<Pagination page={records} />
|
||||
</Management>
|
||||
);
|
||||
}
|
||||
+959
@@ -0,0 +1,959 @@
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { valueText } from '@/lib/value-text';
|
||||
import OpportunityProfileActions from '@/components/opportunity-profile-actions';
|
||||
import OpportunityCanonicalFields, {
|
||||
type CanonicalOptions,
|
||||
} from '@/components/opportunity-canonical-fields';
|
||||
import { Link, router, usePage } from '@inertiajs/react';
|
||||
import TerritoryGeometryPreview from '@/components/territory-geometry-preview';
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
TerritoryLevel,
|
||||
type TerritoryOption,
|
||||
} from '@/components/investment-territory';
|
||||
import { Management, Field, button, control, states } from './shared';
|
||||
type Values = Record<string, unknown>;
|
||||
type Entry = {
|
||||
id: number;
|
||||
reference: string;
|
||||
status: string;
|
||||
deleted_at: string | null;
|
||||
management_version: number;
|
||||
};
|
||||
export default function OpportunityDraft({
|
||||
record,
|
||||
values,
|
||||
etag,
|
||||
readOnly,
|
||||
closedVersion,
|
||||
classification,
|
||||
sectors,
|
||||
categories,
|
||||
history,
|
||||
territoryPath,
|
||||
resourcesInstalled = false,
|
||||
maturityCatalogue,
|
||||
}: {
|
||||
record: Entry | null;
|
||||
values: Values;
|
||||
etag: string | null;
|
||||
readOnly: boolean;
|
||||
closedVersion: boolean;
|
||||
classification: string;
|
||||
sectors: { id: number; name: string }[];
|
||||
categories: string[];
|
||||
territoryPath: TerritoryOption[];
|
||||
resourcesInstalled?: boolean;
|
||||
maturityCatalogue: {
|
||||
version: string;
|
||||
stages: Record<string, string>;
|
||||
legacyVersion: string;
|
||||
legacyLabels: Record<string, string>;
|
||||
};
|
||||
history: {
|
||||
id: string;
|
||||
action: string;
|
||||
actor_user_id: number;
|
||||
occurred_at: string;
|
||||
}[];
|
||||
}) {
|
||||
const {
|
||||
basePath = '/management/opportunities',
|
||||
profileMode = false,
|
||||
profileOrganization,
|
||||
profileContext,
|
||||
profileAccess,
|
||||
profileActions = [],
|
||||
canonicalOptions,
|
||||
workflowState,
|
||||
canonicalResponse,
|
||||
workflowTasks = [],
|
||||
workflowParticipants,
|
||||
publicationPreview,
|
||||
publicationState,
|
||||
auth,
|
||||
canEditDraft = false,
|
||||
} = usePage<{
|
||||
basePath?: string;
|
||||
profileMode?: boolean;
|
||||
profileOrganization?: string | null;
|
||||
profileActions?: string[];
|
||||
profileContext?: Record<string, unknown> | null;
|
||||
profileAccess?: {
|
||||
contexts: { organization_id: string | null; type: string }[];
|
||||
} | null;
|
||||
publicationPreview?: {
|
||||
title: string;
|
||||
summary: string;
|
||||
description: string;
|
||||
};
|
||||
workflowParticipants?: {
|
||||
condition_responsibles?: { id: number; name: string }[];
|
||||
publishers: { id: number; name: string }[];
|
||||
validators: {
|
||||
id: number;
|
||||
name: string;
|
||||
technical: boolean;
|
||||
legal: boolean;
|
||||
}[];
|
||||
};
|
||||
canonicalOptions?: CanonicalOptions;
|
||||
workflowState?: string;
|
||||
canonicalResponse?: {
|
||||
completion: {
|
||||
percentage: number;
|
||||
filled: number;
|
||||
applicable: number;
|
||||
missing_paths: string[];
|
||||
};
|
||||
materiality?: { reopened: string[]; retained: string[] } | null;
|
||||
};
|
||||
publicationState?: {
|
||||
scope: string;
|
||||
label: string;
|
||||
public_catalog: boolean;
|
||||
};
|
||||
workflowTasks?: {
|
||||
id: string;
|
||||
title: string;
|
||||
status: string;
|
||||
assignee_user_id: number | null;
|
||||
due_at: string | null;
|
||||
}[];
|
||||
auth: { user: { id: number } };
|
||||
canEditDraft?: boolean;
|
||||
}>().props;
|
||||
const [data, setData] = useState<Values>({
|
||||
...values,
|
||||
...(profileMode
|
||||
? {
|
||||
organization_id: record
|
||||
? (profileOrganization ?? null)
|
||||
: (profileAccess?.contexts[0]?.organization_id ?? null),
|
||||
opportunity_category:
|
||||
values.opportunity_category ??
|
||||
profileAccess?.contexts[0]?.type ??
|
||||
'',
|
||||
}
|
||||
: {}),
|
||||
creation_key: createOperationKey(),
|
||||
});
|
||||
const [busy, setBusy] = useState(false),
|
||||
[errors, setErrors] = useState<Record<string, string>>({}),
|
||||
[message, setMessage] = useState(''),
|
||||
[reason, setReason] = useState(''),
|
||||
[confirm, setConfirm] = useState(false),
|
||||
[token, setToken] = useState(etag);
|
||||
useEffect(() => setToken(etag), [etag]);
|
||||
const [path, setPath] = useState(territoryPath);
|
||||
const unavailable = Boolean(
|
||||
record?.deleted_at || record?.status === 'archived',
|
||||
);
|
||||
const archiveAvailable = Boolean(usePage().props.opportunityManagement);
|
||||
const set = (key: string, value: string) =>
|
||||
setData((d) => ({ ...d, [key]: value }));
|
||||
async function send(action: 'save' | 'delete' | 'archive' | 'restore') {
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
setErrors({});
|
||||
setMessage('');
|
||||
try {
|
||||
const cookie = document.cookie
|
||||
.split('; ')
|
||||
.find((c) => c.startsWith('XSRF-TOKEN='));
|
||||
const url =
|
||||
action === 'save'
|
||||
? record
|
||||
? `${basePath}/${record.id}/draft`
|
||||
: `${basePath}/drafts`
|
||||
: `${basePath}/${record!.id}/lifecycle`;
|
||||
const response = await fetch(url, {
|
||||
method: action === 'save' && record ? 'PUT' : 'POST',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-XSRF-TOKEN': cookie
|
||||
? decodeURIComponent(cookie.slice(11))
|
||||
: '',
|
||||
},
|
||||
body: JSON.stringify(
|
||||
action === 'save'
|
||||
? { ...data, etag: token, reason }
|
||||
: { etag: token, action, reason, confirm },
|
||||
),
|
||||
});
|
||||
const result = await response.json();
|
||||
if (!response.ok) {
|
||||
setErrors(
|
||||
Object.fromEntries(
|
||||
Object.entries(result.errors ?? {}).map(([k, v]) => [
|
||||
k,
|
||||
Array.isArray(v) ? v.join(' ') : valueText(v),
|
||||
]),
|
||||
),
|
||||
);
|
||||
setMessage(
|
||||
result.message ??
|
||||
'Operação falhou; os dados preenchidos foram preservados.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
setMessage(result.message);
|
||||
if (result.etag) setToken(result.etag);
|
||||
if (!record) router.visit(`${basePath}/${result.id}/edit`);
|
||||
else if (action !== 'save') router.reload();
|
||||
} catch {
|
||||
setMessage(
|
||||
'Resposta indisponível. Os dados foram preservados; confira o registo no servidor antes de repetir.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
requestAnimationFrame(() =>
|
||||
document.getElementById('opportunity-result')?.focus(),
|
||||
);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<Management
|
||||
title={
|
||||
record
|
||||
? `${readOnly ? 'Ver' : 'Editar'} oportunidade ${record.reference}`
|
||||
: 'Nova oportunidade'
|
||||
}
|
||||
>
|
||||
<Link href={basePath}>
|
||||
{profileMode ? 'Minhas oportunidades' : 'Voltar à gestão'}
|
||||
</Link>
|
||||
{profileMode && (
|
||||
<section aria-label="Âmbito desta entrega" className="rounded border p-3">
|
||||
<h2>Âmbito desta entrega</h2>
|
||||
<p>Seis categorias base: projeto de investimento, imobiliário, fundiário, venda de negócio, parceria e franquia. Rascunho, correção, revisão independente e publicação são ações distintas; uma aprovação interna não atribui direitos nem substitui uma decisão externa.</p>
|
||||
<p>No imobiliário, a submissão inclui venda e arrendamento de imóvel concluído, desocupado e sem encargos ou limitações urbanísticas adicionais. Pode guardar e recuperar as outras variantes em preparação; a sua submissão permanece indisponível.</p>
|
||||
<p>Concessão, financiamento, fornecimento e outros, partilha individual de anexos, restauração de oportunidades e exportação normativa integral Response/§27 não estão incluídos. O Response disponível conserva o contrato de compatibilidade e o histórico.</p>
|
||||
<p>As restantes variantes económicas, societárias, territoriais, de contribuições e licenças exigem documentação e revisão aplicáveis. Esta entrega não certifica a viabilidade, a titularidade ou a decisão externa de cada caso.</p>
|
||||
</section>
|
||||
)}
|
||||
{profileMode && record && readOnly && canEditDraft && (
|
||||
<Link
|
||||
className="block underline"
|
||||
href={`${basePath}/${record.id}/edit`}
|
||||
>
|
||||
Editar proposta privada
|
||||
</Link>
|
||||
)}
|
||||
{profileMode && !record && (
|
||||
<label className="block">
|
||||
Organização e tipo autorizados
|
||||
<select
|
||||
className={control}
|
||||
value={`${valueText(data.organization_id ?? '')}|${valueText(data.opportunity_category ?? '')}`}
|
||||
onChange={(e) => {
|
||||
const [organization, type] =
|
||||
e.target.value.split('|');
|
||||
setData((d) => ({
|
||||
...d,
|
||||
organization_id: organization || null,
|
||||
opportunity_category: type,
|
||||
}));
|
||||
}}
|
||||
>
|
||||
{(profileAccess?.contexts ?? []).map((c) => (
|
||||
<option
|
||||
key={`${c.organization_id}|${c.type}`}
|
||||
value={`${c.organization_id ?? ''}|${c.type}`}
|
||||
>
|
||||
{c.organization_id ?? 'Âmbito individual'} —{' '}
|
||||
{c.type}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
{profileMode && record && (
|
||||
<p
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
aria-label="Estado da oportunidade"
|
||||
>
|
||||
Estado da preparação:{' '}
|
||||
{(workflowState ?? record.status) === 'published'
|
||||
? 'Versão disponibilizada'
|
||||
: ((
|
||||
{
|
||||
draft: 'Rascunho',
|
||||
submitted: 'Submetida para validação',
|
||||
needs_information: 'Correções solicitadas',
|
||||
information_pending: 'Aguarda parecer',
|
||||
in_review: 'Em validação interna',
|
||||
approved: 'Aprovada internamente',
|
||||
rejected: 'Rejeitada',
|
||||
suspended: 'Suspensa',
|
||||
archived: 'Arquivada',
|
||||
} as Record<string, string>
|
||||
)[workflowState ?? record.status] ??
|
||||
states[workflowState ?? record.status] ??
|
||||
workflowState ??
|
||||
record.status)}
|
||||
. {publicationState?.label}.{' '}
|
||||
{profileContext?.review_cycle != null && (
|
||||
<>
|
||||
Ciclo de revisão interna:{' '}
|
||||
{valueText(profileContext.review_cycle)}.{' '}
|
||||
</>
|
||||
)}
|
||||
{profileContext?.request_archive
|
||||
? 'Pedido de arquivo registado; aguarda decisão independente.'
|
||||
: ''}{' '}
|
||||
O Promotor solicita arquivo; não elimina nem restaura
|
||||
oportunidades.
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
Classificação de origem:{' '}
|
||||
{(
|
||||
{
|
||||
real: 'Oportunidade real',
|
||||
example: 'Exemplo demonstrativo',
|
||||
undetermined: 'Origem ainda indeterminada',
|
||||
} as Record<string, string>
|
||||
)[classification] ?? classification}
|
||||
. Esta classificação não cria associações territoriais.
|
||||
</p>
|
||||
{closedVersion && (
|
||||
<p>
|
||||
Versão anterior fechada. As alterações são guardadas numa
|
||||
nova versão de rascunho; a ficha publicada permanece
|
||||
intacta. Guardar não submete: use as ações do workflow para
|
||||
revisão, aprovação e publicação independentes.
|
||||
</p>
|
||||
)}
|
||||
{profileMode && record && canonicalResponse && (
|
||||
<section
|
||||
aria-label="Preenchimento e revisões"
|
||||
aria-live="polite"
|
||||
className="rounded border p-3"
|
||||
>
|
||||
<p>
|
||||
Preenchimento gravado:{' '}
|
||||
{canonicalResponse.completion.percentage}% (
|
||||
{canonicalResponse.completion.filled}/
|
||||
{canonicalResponse.completion.applicable} campos
|
||||
aplicáveis). Não equivale a validação ou aprovação.
|
||||
</p>
|
||||
{canonicalResponse.materiality && (
|
||||
<>
|
||||
<p>
|
||||
Revisões reabertas:{' '}
|
||||
{canonicalResponse.materiality.reopened.join(
|
||||
', ',
|
||||
) || 'Nenhuma'}
|
||||
.
|
||||
</p>
|
||||
<p>
|
||||
Revisões conservadas:{' '}
|
||||
{canonicalResponse.materiality.retained.join(
|
||||
', ',
|
||||
) || 'Nenhuma'}
|
||||
.
|
||||
</p>
|
||||
<p>
|
||||
A versão alterada exige nova aprovação
|
||||
independente; as assinaturas dos pareceres
|
||||
conservados permanecem no histórico.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
<a href={`${basePath}/${record.id}/response`}>
|
||||
Abrir resposta canónica gravada
|
||||
</a>
|
||||
</section>
|
||||
)}
|
||||
<div
|
||||
id="opportunity-result"
|
||||
tabIndex={-1}
|
||||
role={Object.keys(errors).length ? 'alert' : 'status'}
|
||||
className="rounded border p-3"
|
||||
>
|
||||
{message}
|
||||
{errors.etag && (
|
||||
<p>
|
||||
{errors.etag}{' '}
|
||||
<a
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
href={`${basePath}/${record?.id}/view`}
|
||||
>
|
||||
Abrir versão atual
|
||||
</a>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<form
|
||||
className="max-w-3xl space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void send('save');
|
||||
}}
|
||||
>
|
||||
{!profileMode && (
|
||||
<fieldset
|
||||
disabled={busy || readOnly || unavailable}
|
||||
className="space-y-4"
|
||||
>
|
||||
<section aria-label="Localização registada">
|
||||
<TerritoryGeometryPreview
|
||||
territoryId={path.at(-1)?.id}
|
||||
management
|
||||
endpoint={
|
||||
profileMode
|
||||
? '/minhas-oportunidades/territory-geometries'
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
<p>
|
||||
Hierarquia do cadastro territorial existente.
|
||||
Alterar esta seleção não cria relações com
|
||||
projetos/clusters.
|
||||
</p>
|
||||
{(
|
||||
[
|
||||
'province_id',
|
||||
'district_id',
|
||||
'admin_post_id',
|
||||
'locality_id',
|
||||
] as const
|
||||
).map((key, index) => (
|
||||
<TerritoryLevel
|
||||
key={`${key}-${path[index - 1]?.id ?? ''}`}
|
||||
index={index}
|
||||
parent={path[index - 1]?.id ?? ''}
|
||||
selected={path[index]}
|
||||
endpoint={
|
||||
profileMode
|
||||
? '/minhas-oportunidades/territory-options'
|
||||
: '/management/territory-options'
|
||||
}
|
||||
fieldError={errors[key]}
|
||||
onChange={(value) => {
|
||||
const next = [
|
||||
...path.slice(0, index),
|
||||
...(value ? [value] : []),
|
||||
];
|
||||
setPath(next);
|
||||
setData((previous) => ({
|
||||
...previous,
|
||||
province_id: next[0]?.id ?? '',
|
||||
district_id: next[1]?.id ?? '',
|
||||
admin_post_id: next[2]?.id ?? '',
|
||||
locality_id: next[3]?.id ?? '',
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</section>
|
||||
<Field
|
||||
label="Categoria"
|
||||
error={errors.opportunity_category}
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={valueText(
|
||||
data.opportunity_category ?? '',
|
||||
)}
|
||||
onChange={(e) =>
|
||||
set('opportunity_category', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{categories.map((c) => (
|
||||
<option key={c}>{c}</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
{Object.entries({
|
||||
title: 'Título oficial',
|
||||
summary: 'Resumo',
|
||||
description: 'Descrição',
|
||||
promoter_name: 'Promotor',
|
||||
}).map(([key, label]) => (
|
||||
<Field key={key} label={label} error={errors[key]}>
|
||||
{key === 'description' || key === 'summary' ? (
|
||||
<textarea
|
||||
className={control}
|
||||
value={valueText(data[key] ?? '')}
|
||||
onChange={(e) =>
|
||||
set(key, e.target.value)
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
className={control}
|
||||
value={valueText(data[key] ?? '')}
|
||||
onChange={(e) =>
|
||||
set(key, e.target.value)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</Field>
|
||||
))}
|
||||
<Field label="Sector" error={errors.sector_id}>
|
||||
<select
|
||||
className={control}
|
||||
value={valueText(data.sector_id ?? '')}
|
||||
onChange={(e) =>
|
||||
set('sector_id', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{sectors.map((s) => (
|
||||
<option key={s.id} value={s.id}>
|
||||
{s.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field
|
||||
label="Tipo de promotor"
|
||||
error={errors.promoter_type}
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={valueText(data.promoter_type ?? '')}
|
||||
onChange={(e) =>
|
||||
set('promoter_type', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{Boolean(values.promoter_type) &&
|
||||
![
|
||||
'public',
|
||||
'private',
|
||||
'ppp',
|
||||
'cooperative',
|
||||
'association',
|
||||
'community',
|
||||
'other',
|
||||
].includes(
|
||||
valueText(values.promoter_type),
|
||||
) && (
|
||||
<option
|
||||
value={valueText(
|
||||
values.promoter_type,
|
||||
)}
|
||||
>
|
||||
{valueText(values.promoter_type)}{' '}
|
||||
(valor existente)
|
||||
</option>
|
||||
)}
|
||||
{[
|
||||
'public',
|
||||
'private',
|
||||
'ppp',
|
||||
'cooperative',
|
||||
'association',
|
||||
'community',
|
||||
'other',
|
||||
].map((c) => (
|
||||
<option key={c}>{c}</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field
|
||||
label="Etapa de maturidade"
|
||||
error={
|
||||
errors.maturity_stage ?? errors.maturity_level
|
||||
}
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={
|
||||
data.maturity_catalogue_version ===
|
||||
maturityCatalogue.version
|
||||
? valueText(data.maturity_stage ?? '')
|
||||
: data.maturity_level
|
||||
? `legacy:${valueText(data.maturity_level)}`
|
||||
: ''
|
||||
}
|
||||
onChange={(e) => {
|
||||
const stage = e.target.value;
|
||||
if (stage.startsWith('legacy:')) {
|
||||
setData((d) => ({
|
||||
...d,
|
||||
maturity_catalogue_version:
|
||||
maturityCatalogue.legacyVersion,
|
||||
maturity_level: Number(
|
||||
stage.slice(7),
|
||||
),
|
||||
maturity_stage: null,
|
||||
}));
|
||||
} else {
|
||||
setData((d) => ({
|
||||
...d,
|
||||
maturity_catalogue_version:
|
||||
maturityCatalogue.version,
|
||||
maturity_stage: stage || null,
|
||||
maturity_level: stage
|
||||
? Object.keys(
|
||||
maturityCatalogue.stages,
|
||||
).indexOf(stage) + 1
|
||||
: null,
|
||||
}));
|
||||
}
|
||||
}}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{Boolean(values.maturity_level) &&
|
||||
values.maturity_catalogue_version !==
|
||||
maturityCatalogue.version && (
|
||||
<option
|
||||
value={`legacy:${valueText(values.maturity_level)}`}
|
||||
>
|
||||
{
|
||||
maturityCatalogue.legacyLabels[
|
||||
valueText(
|
||||
values.maturity_level,
|
||||
)
|
||||
]
|
||||
}{' '}
|
||||
(catálogo histórico; sem conversão)
|
||||
</option>
|
||||
)}
|
||||
{Object.entries(maturityCatalogue.stages).map(
|
||||
([code, label], index) => (
|
||||
<option key={code} value={code}>
|
||||
{index + 1}. {label}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
<p>
|
||||
O catálogo de oito etapas é guardado com a sua
|
||||
versão. Os valores históricos conservam o
|
||||
significado anterior.
|
||||
</p>
|
||||
</Field>
|
||||
<Field
|
||||
label="Modalidade de financiamento existente"
|
||||
error={errors.financing_modality}
|
||||
>
|
||||
<input
|
||||
className={control}
|
||||
value={valueText(data.financing_modality ?? '')}
|
||||
onChange={(e) =>
|
||||
set('financing_modality', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field
|
||||
label="Impacto esperado"
|
||||
error={errors.expected_impact}
|
||||
>
|
||||
<textarea
|
||||
className={control}
|
||||
value={valueText(data.expected_impact ?? '')}
|
||||
onChange={(e) =>
|
||||
set('expected_impact', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
{(data.opportunity_category === 'investment_project' ||
|
||||
(!data.opportunity_category &&
|
||||
data.estimated_investment_amount != null)) && (
|
||||
<>
|
||||
<Field
|
||||
label="Investimento estimado"
|
||||
error={errors.estimated_investment_amount}
|
||||
>
|
||||
<input
|
||||
className={control}
|
||||
value={valueText(
|
||||
data.estimated_investment_amount ??
|
||||
'',
|
||||
)}
|
||||
onChange={(e) =>
|
||||
set(
|
||||
'estimated_investment_amount',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field
|
||||
label="Moeda"
|
||||
error={errors.estimated_investment_currency}
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={valueText(
|
||||
data.estimated_investment_currency ??
|
||||
'',
|
||||
)}
|
||||
onChange={(e) =>
|
||||
set(
|
||||
'estimated_investment_currency',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{['MZN', 'USD', 'EUR', 'ZAR'].map(
|
||||
(c) => (
|
||||
<option key={c}>{c}</option>
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
</Field>
|
||||
</>
|
||||
)}
|
||||
{Boolean(data.opportunity_category) &&
|
||||
data.opportunity_category !==
|
||||
'investment_project' && (
|
||||
<p>
|
||||
Guarde o rascunho incompleto e complete o
|
||||
contrato aplicável abaixo. Submissão e
|
||||
publicação exigem os documentos e as
|
||||
revisões desta categoria.
|
||||
</p>
|
||||
)}
|
||||
</fieldset>
|
||||
)}
|
||||
{!readOnly && (
|
||||
<>
|
||||
<Field
|
||||
label="Motivo da alteração"
|
||||
error={errors.reason}
|
||||
>
|
||||
<textarea
|
||||
className={control}
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
minLength={20}
|
||||
maxLength={1000}
|
||||
/>
|
||||
</Field>
|
||||
{!unavailable && (
|
||||
<button className={button} disabled={busy}>
|
||||
Guardar rascunho
|
||||
</button>
|
||||
)}
|
||||
{record && !profileMode && (
|
||||
<>
|
||||
<label className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={confirm}
|
||||
onChange={(e) =>
|
||||
setConfirm(e.target.checked)
|
||||
}
|
||||
/>{' '}
|
||||
Confirmo a{' '}
|
||||
{unavailable
|
||||
? 'restauração'
|
||||
: 'operação indicada, preservando o registo'}
|
||||
, preservando histórico e relações
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy || !confirm}
|
||||
onClick={() =>
|
||||
void send(
|
||||
unavailable
|
||||
? 'restore'
|
||||
: archiveAvailable
|
||||
? 'archive'
|
||||
: 'delete',
|
||||
)
|
||||
}
|
||||
>
|
||||
{unavailable
|
||||
? 'Restaurar'
|
||||
: archiveAvailable || closedVersion
|
||||
? 'Arquivar'
|
||||
: 'Excluir rascunho'}
|
||||
</button>
|
||||
{archiveAvailable &&
|
||||
!unavailable &&
|
||||
!closedVersion && (
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy || !confirm}
|
||||
onClick={() => void send('delete')}
|
||||
>
|
||||
Excluir rascunho
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</form>
|
||||
{record && (
|
||||
<Link
|
||||
href={
|
||||
resourcesInstalled
|
||||
? `${basePath}/${record.id}/resources`
|
||||
: '/management/opportunity-resources-install'
|
||||
}
|
||||
>
|
||||
{resourcesInstalled
|
||||
? 'Imagens, documentos e localizações'
|
||||
: 'Plano de ativação de imagens, documentos e localizações'}
|
||||
</Link>
|
||||
)}
|
||||
{record && !profileMode && (
|
||||
<Link href={`${basePath}/${record.id}/context`}>
|
||||
Consultar projetos, clusters e relações existentes
|
||||
</Link>
|
||||
)}
|
||||
{profileMode && canonicalOptions && (
|
||||
<section>
|
||||
<OpportunityCanonicalFields
|
||||
value={
|
||||
(data.canonical ?? {}) as Record<string, unknown>
|
||||
}
|
||||
onChange={(v) =>
|
||||
setData((d) => ({ ...d, canonical: v }))
|
||||
}
|
||||
options={canonicalOptions}
|
||||
errors={errors}
|
||||
category={valueText(data.opportunity_category ?? '')}
|
||||
organization={
|
||||
(data.organization_id ?? null) as string | null
|
||||
}
|
||||
actorId={auth.user.id}
|
||||
sectors={sectors}
|
||||
disabled={busy || readOnly || unavailable}
|
||||
/>
|
||||
{!readOnly && !unavailable && (
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={() => void send('save')}
|
||||
>
|
||||
Guardar contrato no rascunho
|
||||
</button>
|
||||
)}
|
||||
{Object.entries(errors)
|
||||
.filter(([key]) => key.startsWith('canonical'))
|
||||
.map(([key, msg]) => (
|
||||
<p key={key} role="alert">
|
||||
{key}: {msg}
|
||||
</p>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
{profileMode && record && profileActions.includes('publish') && (
|
||||
<section className="rounded border p-3">
|
||||
<h2>Pré-visualização da publicação</h2>
|
||||
<p>
|
||||
Âmbito solicitado:{' '}
|
||||
{(data.canonical as Record<string, unknown> | undefined)
|
||||
?.visibility === 'public'
|
||||
? 'Catálogo público, após ação do Publicador'
|
||||
: 'Acesso restrito aos perfis e à organização autorizados'}
|
||||
</p>
|
||||
<h3>{publicationPreview?.title}</h3>
|
||||
<p>{publicationPreview?.summary}</p>
|
||||
<p>{publicationPreview?.description}</p>
|
||||
<p>
|
||||
A ficha partilha apenas título, resumo, proposta, sector
|
||||
e território. Contactos, avaliações, evidências e
|
||||
originais conservam o acesso restrito.
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
{profileMode && record && etag && (
|
||||
<OpportunityProfileActions
|
||||
conditions={
|
||||
Object.values(profileContext?.conditions ?? {}) as {
|
||||
id: string;
|
||||
gate: string;
|
||||
description: string;
|
||||
responsible_name: string;
|
||||
due_on: string | null;
|
||||
blocking_action: string;
|
||||
status: string;
|
||||
}[]
|
||||
}
|
||||
conditionResponsibles={
|
||||
workflowParticipants?.condition_responsibles
|
||||
}
|
||||
participants={workflowParticipants?.validators}
|
||||
publishers={workflowParticipants?.publishers}
|
||||
opinions={Object.values(
|
||||
(profileContext?.opinions ?? {}) as Record<
|
||||
string,
|
||||
{
|
||||
id: string;
|
||||
gate: string;
|
||||
recipient_id: number;
|
||||
status: string;
|
||||
}
|
||||
>,
|
||||
)}
|
||||
onErrors={setErrors}
|
||||
id={record.id}
|
||||
etag={token ?? etag}
|
||||
actions={profileActions}
|
||||
publicationVisibility={valueText(
|
||||
(data.canonical as Record<string, unknown> | undefined)
|
||||
?.visibility ?? 'internal',
|
||||
)}
|
||||
gates={canonicalOptions?.gates ?? []}
|
||||
documents={(
|
||||
canonicalOptions?.resources.documents ?? []
|
||||
).map((d) => ({
|
||||
id: d.id,
|
||||
title: d.payload.title ?? d.file?.file_name ?? d.id,
|
||||
}))}
|
||||
approvalHash={
|
||||
(
|
||||
profileContext?.approval as
|
||||
| { hash?: string }
|
||||
| undefined
|
||||
)?.hash
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{profileMode && record && (
|
||||
<section className="space-y-2 rounded border p-3">
|
||||
<h2>
|
||||
Acompanhamento interno —{' '}
|
||||
{(workflowState ?? record.status) === 'published'
|
||||
? 'Versão disponibilizada'
|
||||
: (states[workflowState ?? record.status] ??
|
||||
workflowState ??
|
||||
record.status)}
|
||||
</h2>
|
||||
<p>
|
||||
SLA: sem política/prazo aprovado; as tarefas podem ser
|
||||
preparadas em paralelo.
|
||||
</p>
|
||||
{workflowTasks.map((t) => (
|
||||
<p key={t.id}>
|
||||
{t.title} — {t.status}; responsável:{' '}
|
||||
{t.assignee_user_id ?? 'por atribuir'}; prazo:{' '}
|
||||
{t.due_at ?? 'não definido'}
|
||||
</p>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
<section aria-label="Histórico de gestão">
|
||||
<h2>Histórico</h2>
|
||||
{history.length ? (
|
||||
history.map((e) => (
|
||||
<p key={e.id}>
|
||||
{e.action} · conta {e.actor_user_id} ·{' '}
|
||||
{e.occurred_at}
|
||||
</p>
|
||||
))
|
||||
) : (
|
||||
<p>Sem eventos deste incremento.</p>
|
||||
)}
|
||||
</section>
|
||||
</Management>
|
||||
);
|
||||
}
|
||||
+778
@@ -0,0 +1,778 @@
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { valueText } from '@/lib/value-text';
|
||||
import { Link, router, usePage } from '@inertiajs/react';
|
||||
import TerritoryGeometryPreview from '@/components/territory-geometry-preview';
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
TerritoryLevel,
|
||||
type TerritoryOption,
|
||||
} from '@/components/investment-territory';
|
||||
import { Management, Field, button, control } from './shared';
|
||||
|
||||
type Payload = Record<string, string | number | boolean | null | object>;
|
||||
type Resource = {
|
||||
id: string;
|
||||
version: number;
|
||||
deleted_at: string | null;
|
||||
payload: Payload;
|
||||
territoryPath?: TerritoryOption[];
|
||||
derivativePreviews?: {
|
||||
document_id: string;
|
||||
url: string;
|
||||
width: number;
|
||||
height: number;
|
||||
}[];
|
||||
file?: {
|
||||
file_name: string;
|
||||
malware_scan_status: string;
|
||||
malware_engine: string | null;
|
||||
sha256: string;
|
||||
};
|
||||
};
|
||||
type Kind = 'locations' | 'images' | 'documents';
|
||||
const fields: Record<Kind, string[]> = {
|
||||
locations: [
|
||||
'title',
|
||||
'address',
|
||||
'operational_unit',
|
||||
'role_description',
|
||||
'area_value',
|
||||
'area_unit',
|
||||
'allocation_percentage',
|
||||
'multi_district_rationale',
|
||||
'source_reference',
|
||||
'source_date',
|
||||
],
|
||||
images: [
|
||||
'title',
|
||||
'caption',
|
||||
'alt_text',
|
||||
'author_source',
|
||||
'captured_at',
|
||||
'rights_valid_until',
|
||||
'role_description',
|
||||
'sort_order',
|
||||
'source_reference',
|
||||
],
|
||||
documents: [
|
||||
'title',
|
||||
'category',
|
||||
'issuer',
|
||||
'edition',
|
||||
'source_date',
|
||||
'valid_until',
|
||||
'source_reference',
|
||||
'section',
|
||||
'supported_statement',
|
||||
],
|
||||
};
|
||||
const labels: Record<string, string> = {
|
||||
role: 'Papel da localização',
|
||||
imageRole: 'Tipo de imagem',
|
||||
territorial_purpose: 'Natureza da relação territorial',
|
||||
rights_status: 'Direitos de utilização',
|
||||
visibility: 'Âmbito de consulta',
|
||||
classification: 'Classificação documental',
|
||||
location_id: 'Localização associada',
|
||||
rights_document_id: 'Comprovativo de direitos',
|
||||
title: 'Título',
|
||||
address: 'Referência física',
|
||||
operational_unit: 'Unidade operacional',
|
||||
role_description: 'Descrição do papel outro',
|
||||
area_value: 'Área',
|
||||
area_unit: 'Unidade de área',
|
||||
allocation_percentage: 'Distribuição (%)',
|
||||
multi_district_rationale: 'Fundamento multidistrito/interprovincial',
|
||||
source_reference: 'Fonte / referência',
|
||||
source_date: 'Data da fonte',
|
||||
caption: 'Legenda',
|
||||
alt_text: 'Texto alternativo',
|
||||
author_source: 'Autor / fonte',
|
||||
captured_at: 'Data da imagem',
|
||||
rights_valid_until: 'Validade dos direitos',
|
||||
sort_order: 'Ordem',
|
||||
category: 'Categoria documental',
|
||||
issuer: 'Emissor',
|
||||
edition: 'Edição / versão',
|
||||
valid_until: 'Validade',
|
||||
section: 'Página / secção',
|
||||
supported_statement: 'Afirmação fundamentada',
|
||||
};
|
||||
const choices: Record<string, string[]> = {
|
||||
role: [
|
||||
'headquarters',
|
||||
'production',
|
||||
'raw_material',
|
||||
'storage',
|
||||
'logistics',
|
||||
'market',
|
||||
'support',
|
||||
'other',
|
||||
],
|
||||
imageRole: [
|
||||
'cover',
|
||||
'gallery',
|
||||
'location',
|
||||
'asset',
|
||||
'product',
|
||||
'plan',
|
||||
'rendering',
|
||||
'evidence',
|
||||
'other',
|
||||
],
|
||||
territorial_purpose: ['implementation', 'context', 'impact', 'coverage'],
|
||||
rights_status: ['owned', 'licensed', 'authorized', 'public_domain'],
|
||||
visibility: ['internal', 'authenticated', 'public'],
|
||||
classification: ['public', 'internal', 'confidential', 'restricted'],
|
||||
};
|
||||
|
||||
export default function OpportunityResources({
|
||||
opportunity,
|
||||
etag,
|
||||
resources,
|
||||
existingLocations,
|
||||
assessment,
|
||||
imageProcessingAvailable,
|
||||
}: {
|
||||
opportunity: {
|
||||
id: number;
|
||||
title: string | null;
|
||||
status: string;
|
||||
deleted_at: string | null;
|
||||
};
|
||||
etag: string;
|
||||
resources: Record<Kind, Resource[]>;
|
||||
existingLocations: { id: string; name: string; location_type: string }[];
|
||||
assessment: string[];
|
||||
imageProcessingAvailable: boolean;
|
||||
}) {
|
||||
const {
|
||||
basePath = '/management/opportunities',
|
||||
readOnly = false,
|
||||
countries = [],
|
||||
} = usePage<{
|
||||
basePath?: string;
|
||||
readOnly?: boolean;
|
||||
countries?: { code: string; name: string }[];
|
||||
}>().props;
|
||||
const [kind, setKind] = useState<Kind>('locations');
|
||||
const [editing, setEditing] = useState<Resource | null>(null);
|
||||
const [payload, setPayload] = useState<Payload>({ country_code: 'MZ' });
|
||||
const [path, setPath] = useState<TerritoryOption[]>([]);
|
||||
const [geometry, setGeometry] = useState('');
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [reason, setReason] = useState('');
|
||||
const [confirm, setConfirm] = useState(false);
|
||||
const [key, setKey] = useState(() => createOperationKey());
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
const foreignCountry = Boolean(
|
||||
payload.country_code && payload.country_code !== 'MZ',
|
||||
);
|
||||
const set = (name: string, value: Payload[string]) =>
|
||||
setPayload((previous) => ({ ...previous, [name]: value }));
|
||||
function select(nextKind: Kind, record: Resource | null = null) {
|
||||
setKind(nextKind);
|
||||
setEditing(record);
|
||||
setPayload(
|
||||
record?.payload ??
|
||||
(nextKind === 'locations' ? { country_code: 'MZ' } : {}),
|
||||
);
|
||||
setPath(record?.territoryPath ?? []);
|
||||
setGeometry(
|
||||
record?.payload.geometry
|
||||
? JSON.stringify(record.payload.geometry)
|
||||
: '',
|
||||
);
|
||||
setFile(null);
|
||||
setKey(createOperationKey());
|
||||
setConfirm(false);
|
||||
setErrors({});
|
||||
}
|
||||
async function execute(action: 'save' | 'delete' | 'restore' | 'prepare') {
|
||||
if (busy || readOnly) return;
|
||||
setBusy(true);
|
||||
setErrors({});
|
||||
setMessage('');
|
||||
try {
|
||||
const form = new FormData();
|
||||
form.set('etag', etag);
|
||||
form.set('reason', reason);
|
||||
form.set('creation_key', key);
|
||||
if (editing) form.set('version', valueText(editing.version));
|
||||
if (action === 'save') {
|
||||
const values = { ...payload };
|
||||
if (kind === 'locations') {
|
||||
[
|
||||
'province_id',
|
||||
'district_id',
|
||||
'admin_post_id',
|
||||
'locality_id',
|
||||
].forEach(
|
||||
(name, index) =>
|
||||
(values[name] = path[index]?.id ?? null),
|
||||
);
|
||||
values.geometry = geometry ? JSON.parse(geometry) : null;
|
||||
}
|
||||
form.set('payload', JSON.stringify(values));
|
||||
if (file) form.set('file', file);
|
||||
} else {
|
||||
form.set('action', action);
|
||||
form.set('confirm', confirm ? '1' : '0');
|
||||
}
|
||||
const url = `${basePath}/${opportunity.id}/resources/${kind}${editing ? `/${editing.id}` : ''}${action === 'save' ? '' : action === 'prepare' ? '/prepare' : '/lifecycle'}`;
|
||||
const csrf =
|
||||
document.cookie
|
||||
.split('; ')
|
||||
.find((v) => v.startsWith('XSRF-TOKEN='))
|
||||
?.split('=')
|
||||
.slice(1)
|
||||
.join('=') ?? '';
|
||||
const result = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'X-XSRF-TOKEN': decodeURIComponent(csrf),
|
||||
},
|
||||
body: form,
|
||||
});
|
||||
const data = await result.json();
|
||||
if (!result.ok) {
|
||||
setErrors(
|
||||
Object.fromEntries(
|
||||
Object.entries(data.errors ?? {}).map(
|
||||
([name, value]) => [
|
||||
name,
|
||||
Array.isArray(value)
|
||||
? value.join(' ')
|
||||
: valueText(value),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
throw new Error(data.message ?? `Falha HTTP ${result.status}`);
|
||||
}
|
||||
setMessage(data.message);
|
||||
setEditing(null);
|
||||
setPayload(kind === 'locations' ? { country_code: 'MZ' } : {});
|
||||
setPath([]);
|
||||
setGeometry('');
|
||||
setFile(null);
|
||||
setKey(createOperationKey());
|
||||
setConfirm(false);
|
||||
router.reload({
|
||||
onFinish: () =>
|
||||
document.getElementById('resource-result')?.focus(),
|
||||
});
|
||||
} catch (error) {
|
||||
setMessage(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Falha de ligação; preenchimento preservado.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
setTimeout(
|
||||
() => document.getElementById('resource-result')?.focus(),
|
||||
0,
|
||||
);
|
||||
}
|
||||
}
|
||||
const unavailable =
|
||||
!!opportunity.deleted_at || opportunity.status === 'archived';
|
||||
return (
|
||||
<Management title="Imagens, documentos e localizações">
|
||||
<Link href={`${basePath}/${opportunity.id}/edit`}>
|
||||
Regressar ao rascunho #{opportunity.id}
|
||||
</Link>
|
||||
<p>
|
||||
Recursos de preparação. Não alteram automaticamente a ficha
|
||||
pública ou relações territoriais aceites. O estado e o motor do
|
||||
scan são apresentados por ficheiro e versão; um scan simulado
|
||||
nunca verifica ficheiros reais.
|
||||
</p>
|
||||
<div
|
||||
id="resource-result"
|
||||
role="status"
|
||||
tabIndex={-1}
|
||||
className="rounded border p-3"
|
||||
>
|
||||
{message ||
|
||||
'Guardar é independente de validar, submeter e publicar.'}
|
||||
{errors.etag && <p>{errors.etag}</p>}
|
||||
</div>
|
||||
{kind === 'images' && !imageProcessingAvailable && (
|
||||
<p
|
||||
role="status"
|
||||
className="rounded border border-amber-500 p-3"
|
||||
>
|
||||
Processamento de imagens indisponível: GD/WebP não está
|
||||
carregado no servidor. Pode guardar o original e os
|
||||
metadados; miniaturas e imagens para divulgação ficam
|
||||
pendentes.
|
||||
</p>
|
||||
)}
|
||||
{kind !== 'locations' && (
|
||||
<p className="rounded border p-3">
|
||||
Pode guardar anexos para preparação. Cada ficheiro permanece
|
||||
sem download ou pré-visualização enquanto o seu scan não
|
||||
estiver concluído. Guardar metadados, locais ou rascunhos é
|
||||
independente do scan e não publica ficheiros.
|
||||
</p>
|
||||
)}
|
||||
{kind !== 'locations' && (
|
||||
<section aria-label="Privacidade dos anexos" className="rounded border p-3">
|
||||
<h2>Privacidade dos anexos</h2>
|
||||
<p>Os anexos pertencem à oportunidade. Podem ser consultados pelos Promotores autorizados da organização e pelos Validadores e Publicadores com acesso ao tipo e âmbito, além dos Auditores e Superutilizadores autorizados. O gestor da biblioteca, por si só, não obtém esse acesso.</p>
|
||||
<p>Classificação e âmbito de consulta são metadados; escolher «public» ou «authenticated» não divulga o ficheiro. Publicar o anúncio não publica os anexos. A retirada lógica impede a entrega do ficheiro; a revogação do perfil impede acessos futuros.</p>
|
||||
<p>Partilhar um anexo com um destinatário individual ou restringi-lo a alguns membros da organização permanece indisponível. Não guarde neste fluxo um ficheiro que exija essa restrição individual. Não é possível retirar cópias já descarregadas.</p>
|
||||
</section>
|
||||
)}
|
||||
<section>
|
||||
<h2>Conferência e pendências</h2>
|
||||
<ul>
|
||||
{assessment.map((item) => (
|
||||
<li key={item}>{item}</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
{existingLocations.length > 0 && (
|
||||
<section>
|
||||
<h2>Ligações territoriais existentes preservadas</h2>
|
||||
{existingLocations.map((r) => (
|
||||
<p key={r.id}>
|
||||
{r.name} · {r.location_type}
|
||||
</p>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
<nav className="flex flex-wrap gap-3">
|
||||
{(['locations', 'images', 'documents'] as Kind[]).map((k) => (
|
||||
<button
|
||||
className={button}
|
||||
key={k}
|
||||
disabled={busy}
|
||||
onClick={() => select(k)}
|
||||
>
|
||||
{k === 'locations'
|
||||
? 'Localizações'
|
||||
: k === 'images'
|
||||
? 'Imagens'
|
||||
: 'Documentos'}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
<section>
|
||||
{resources[kind].map((r) => (
|
||||
<article key={r.id} className="my-3 rounded border p-3">
|
||||
<p>
|
||||
{valueText(
|
||||
r.payload.title ??
|
||||
r.file?.file_name ??
|
||||
'Recurso incompleto',
|
||||
)}{' '}
|
||||
· v{r.version} ·{' '}
|
||||
{r.deleted_at
|
||||
? 'eliminado logicamente'
|
||||
: 'rascunho'}
|
||||
</p>
|
||||
{r.file && (
|
||||
<p className="break-all">
|
||||
Scan: {r.file.malware_scan_status} · motor:{' '}
|
||||
{r.file.malware_engine ?? 'não executado'} ·
|
||||
hash: {r.file.sha256}
|
||||
</p>
|
||||
)}
|
||||
{kind === 'images' &&
|
||||
!r.deleted_at &&
|
||||
!!r.derivativePreviews?.length && (
|
||||
<img
|
||||
className="max-w-full"
|
||||
src={r.derivativePreviews[0].url}
|
||||
srcSet={r.derivativePreviews
|
||||
.map((p) => `${p.url} ${p.width}w`)
|
||||
.join(', ')}
|
||||
alt={valueText(
|
||||
r.payload.alt_text ??
|
||||
'Pré-visualização interna pendente de descrição',
|
||||
)}
|
||||
onError={() =>
|
||||
setMessage(
|
||||
'Pré-visualização indisponível ou endereço expirado; recarregue. Dados preservados.',
|
||||
)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
<button
|
||||
className={button}
|
||||
onClick={() => select(kind, r)}
|
||||
>
|
||||
{readOnly
|
||||
? 'Ver recurso'
|
||||
: 'Ver / editar / restaurar'}
|
||||
</button>
|
||||
{r.file?.malware_scan_status === 'clean' &&
|
||||
!r.deleted_at && (
|
||||
<a
|
||||
href={`${basePath}/${opportunity.id}/resources/${kind}/${r.id}/download`}
|
||||
>
|
||||
Consultar original autorizado
|
||||
</a>
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
<form
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
void execute('save');
|
||||
}}
|
||||
className="space-y-3"
|
||||
>
|
||||
<h2>
|
||||
{editing
|
||||
? 'Editar recurso / nova versão'
|
||||
: 'Novo recurso incompleto'}
|
||||
</h2>
|
||||
{kind === 'locations' && (
|
||||
<div>
|
||||
<Field
|
||||
label="País da localização"
|
||||
error={errors.country_code}
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
disabled={readOnly}
|
||||
value={valueText(payload.country_code ?? '')}
|
||||
onChange={(event) => {
|
||||
const country = event.target.value;
|
||||
set('country_code', country || null);
|
||||
if (
|
||||
country &&
|
||||
country !== 'MZ' &&
|
||||
path.length
|
||||
) {
|
||||
setPath([]);
|
||||
setMessage(
|
||||
'A seleção territorial de Moçambique foi retirada do preenchimento ao mudar de país. Guarde para registar a alteração; a geometria própria foi preservada.',
|
||||
);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{countries.map((c) => (
|
||||
<option key={c.code} value={c.code}>
|
||||
{c.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
{foreignCountry && (
|
||||
<p>
|
||||
A hierarquia abaixo corresponde a Moçambique e
|
||||
não é aplicável ao país escolhido. Pode guardar
|
||||
uma localização incompleta noutro país sem esta
|
||||
hierarquia.
|
||||
</p>
|
||||
)}
|
||||
{foreignCountry && path.length > 0 && (
|
||||
<p role="alert">
|
||||
Este registo conserva uma seleção territorial de
|
||||
Moçambique incompatível com o país. Escolha
|
||||
Moçambique ou{' '}
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
disabled={readOnly}
|
||||
onClick={() => setPath([])}
|
||||
>
|
||||
retirar a seleção territorial deste
|
||||
preenchimento
|
||||
</button>
|
||||
. O registo guardado só muda quando guardar.
|
||||
</p>
|
||||
)}
|
||||
<TerritoryGeometryPreview
|
||||
territoryId={
|
||||
foreignCountry ? undefined : path.at(-1)?.id
|
||||
}
|
||||
management
|
||||
endpoint={
|
||||
basePath === '/minhas-oportunidades'
|
||||
? '/minhas-oportunidades/territory-geometries'
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
{[0, 1, 2, 3].map((index) => (
|
||||
<TerritoryLevel
|
||||
key={index}
|
||||
index={index}
|
||||
parent={path[index - 1]?.id ?? ''}
|
||||
selected={path[index]}
|
||||
disabled={readOnly || foreignCountry}
|
||||
endpoint={
|
||||
basePath === '/minhas-oportunidades'
|
||||
? '/minhas-oportunidades/territory-options'
|
||||
: '/management/territory-options'
|
||||
}
|
||||
onChange={(value) =>
|
||||
setPath((previous) =>
|
||||
value
|
||||
? [
|
||||
...previous.slice(0, index),
|
||||
value,
|
||||
]
|
||||
: previous.slice(0, index),
|
||||
)
|
||||
}
|
||||
fieldError={
|
||||
errors[
|
||||
[
|
||||
'province_id',
|
||||
'district_id',
|
||||
'admin_post_id',
|
||||
'locality_id',
|
||||
][index]
|
||||
]
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{kind !== 'locations' && (
|
||||
<Field
|
||||
label="Original / substituir por nova versão"
|
||||
error={errors.file}
|
||||
>
|
||||
<input
|
||||
key={key}
|
||||
aria-label="Original / substituir por nova versão"
|
||||
type="file"
|
||||
accept={
|
||||
kind === 'images'
|
||||
? '.jpg,.jpeg,.png,.webp'
|
||||
: '.pdf,.docx,.xlsx,.png,.jpg,.jpeg'
|
||||
}
|
||||
onChange={(event) =>
|
||||
setFile(event.target.files?.[0] ?? null)
|
||||
}
|
||||
/>
|
||||
<p>
|
||||
Armazenamento privado cifrado, original e versões
|
||||
preservados; sem acesso até scan limpo.
|
||||
</p>
|
||||
</Field>
|
||||
)}
|
||||
{fields[kind].map((name) => (
|
||||
<Field
|
||||
key={name}
|
||||
label={labels[name]}
|
||||
error={errors[name] ?? errors[`payload.${name}`]}
|
||||
>
|
||||
<input
|
||||
aria-label={labels[name]}
|
||||
className={control}
|
||||
value={valueText(payload[name] ?? '')}
|
||||
type={
|
||||
name.includes('date') ||
|
||||
name.endsWith('_at') ||
|
||||
name.endsWith('_until')
|
||||
? 'date'
|
||||
: 'text'
|
||||
}
|
||||
onChange={(event) =>
|
||||
set(name, event.target.value || null)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
))}
|
||||
{(kind === 'locations'
|
||||
? ['role', 'territorial_purpose']
|
||||
: kind === 'images'
|
||||
? ['imageRole', 'rights_status', 'visibility']
|
||||
: ['classification', 'visibility']
|
||||
).map((name) => (
|
||||
<Field
|
||||
key={name}
|
||||
label={labels[name] ?? name}
|
||||
error={
|
||||
errors[name === 'imageRole' ? 'role' : name] ??
|
||||
errors[
|
||||
`payload.${name === 'imageRole' ? 'role' : name}`
|
||||
]
|
||||
}
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
aria-label={labels[name] ?? name}
|
||||
value={valueText(
|
||||
payload[name === 'imageRole' ? 'role' : name] ??
|
||||
'',
|
||||
)}
|
||||
onChange={(event) =>
|
||||
set(
|
||||
name === 'imageRole' ? 'role' : name,
|
||||
event.target.value || null,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Pendente</option>
|
||||
{choices[name].map((option) => (
|
||||
<option key={option}>{option}</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
))}
|
||||
{kind === 'locations' && (
|
||||
<Field
|
||||
label="GeoJSON documentado (opcional)"
|
||||
error={errors.geometry}
|
||||
>
|
||||
<textarea
|
||||
className={control}
|
||||
value={geometry}
|
||||
onChange={(event) =>
|
||||
setGeometry(event.target.value)
|
||||
}
|
||||
/>
|
||||
<p>
|
||||
Sem coordenadas continua consultável. Limite oficial
|
||||
em falta aparece como pendência espacial.
|
||||
</p>
|
||||
</Field>
|
||||
)}
|
||||
{kind === 'images' &&
|
||||
(['location_id', 'rights_document_id'] as const).map(
|
||||
(name) => (
|
||||
<Field
|
||||
key={name}
|
||||
label={labels[name] ?? name}
|
||||
error={
|
||||
errors[name] ?? errors[`payload.${name}`]
|
||||
}
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={valueText(payload[name] ?? '')}
|
||||
onChange={(event) =>
|
||||
set(name, event.target.value || null)
|
||||
}
|
||||
>
|
||||
<option value="">Pendente</option>
|
||||
{resources[
|
||||
name === 'location_id'
|
||||
? 'locations'
|
||||
: 'documents'
|
||||
]
|
||||
.filter((r) => !r.deleted_at)
|
||||
.map((r) => (
|
||||
<option value={r.id} key={r.id}>
|
||||
{valueText(
|
||||
r.payload.title ??
|
||||
r.file?.file_name ??
|
||||
r.id,
|
||||
)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
),
|
||||
)}
|
||||
{kind !== 'documents' && (
|
||||
<label>
|
||||
<input
|
||||
key={key}
|
||||
type="checkbox"
|
||||
checked={
|
||||
!!payload[
|
||||
kind === 'images'
|
||||
? 'is_cover'
|
||||
: 'is_primary'
|
||||
]
|
||||
}
|
||||
onChange={(event) =>
|
||||
set(
|
||||
kind === 'images'
|
||||
? 'is_cover'
|
||||
: 'is_primary',
|
||||
event.target.checked,
|
||||
)
|
||||
}
|
||||
/>
|
||||
{kind === 'images'
|
||||
? 'Selecionar capa de preparação'
|
||||
: 'Localização principal'}
|
||||
</label>
|
||||
)}
|
||||
<Field
|
||||
label="Motivo (20–1000 caracteres)"
|
||||
error={errors.reason}
|
||||
>
|
||||
<textarea
|
||||
className={control}
|
||||
aria-label="Motivo (20–1000 caracteres)"
|
||||
value={reason}
|
||||
onChange={(event) => setReason(event.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
{editing && (
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={confirm}
|
||||
onChange={(event) =>
|
||||
setConfirm(event.target.checked)
|
||||
}
|
||||
/>
|
||||
Confirmar exclusão lógica / restauração
|
||||
</label>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{kind === 'images' && editing && !editing.deleted_at && (
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={
|
||||
busy ||
|
||||
readOnly ||
|
||||
unavailable ||
|
||||
!imageProcessingAvailable
|
||||
}
|
||||
onClick={() => void execute('prepare')}
|
||||
>
|
||||
Preparar WebP e miniaturas
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
busy ||
|
||||
readOnly ||
|
||||
unavailable ||
|
||||
!!editing?.deleted_at
|
||||
}
|
||||
>
|
||||
Guardar recurso
|
||||
</button>
|
||||
{editing && (
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy || readOnly || unavailable}
|
||||
onClick={() =>
|
||||
void execute(
|
||||
editing.deleted_at ? 'restore' : 'delete',
|
||||
)
|
||||
}
|
||||
>
|
||||
{editing.deleted_at
|
||||
? 'Restaurar recurso'
|
||||
: 'Excluir recurso logicamente'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
</Management>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user