Files
Investidor-V2/resources/js/pages/investment/business.tsx
T

478 lines
19 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { Link, router } from '@inertiajs/react';
import { useState } from 'react';
import { Frame, Field, input, button, card, api } from './shared';
import { businessModalities, businessStates } from './business-types';
import type { Business } from './business-types';
import BusinessObjects from './business-objects';
import type { BusinessObject } from './business-objects';
import BusinessVerifications from './business-verifications';
import type { BusinessVerification } from './business-verifications';
import BusinessWizard from './business-wizard';
import type { FormSchema } from './business-wizard';
import type { Country } from '@/components/country-select';
import BusinessPointSummary, {
type RegisteredBusinessLocation,
} from '@/components/business-point-summary';
import { businessPointTerritoryLabel } from '@/lib/business-locations';
type Props = {
countries: Country[];
formSchema: FormSchema;
modalityFormType?: string | null;
sectors: { id: number; name: string }[];
record: Business;
canEdit: boolean;
registeredLocation?: RegisteredBusinessLocation | null;
pointPublicationAvailable?: boolean;
owner: boolean;
canReview: boolean;
canTriage: boolean;
canApproveLevelOne: boolean;
canApproveLevelTwo: boolean;
canPublish: boolean;
modalities: string[];
objects: BusinessObject[];
objectKinds: string[];
verificationChecks: string[];
verifications: BusinessVerification[];
history: {
version_no: number;
action: string;
created_at: string;
note: string;
}[];
};
export default function BusinessPage(props: Props) {
if (props.canEdit)
return (
<BusinessWizard
key={props.record.id + ':' + props.record.version_no}
{...props}
/>
);
return (
<Editor
key={`${props.record.id}:${props.record.version_no}`}
{...props}
/>
);
}
function Editor({
record,
canEdit,
owner,
canReview,
canTriage,
canApproveLevelOne,
canApproveLevelTwo,
canPublish,
modalities,
history,
objects,
objectKinds,
verificationChecks,
verifications,
formSchema,
sectors,
registeredLocation,
pointPublicationAvailable,
}: Props) {
const [payload, setPayload] = useState(record.payload);
const [modality, setModality] = useState(record.modality);
const [note, setNote] = useState('');
const [consent, setConsent] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const dirty =
JSON.stringify(payload) !== JSON.stringify(record.payload) ||
modality !== record.modality;
const run = async (action?: string) => {
setBusy(true);
setError('');
try {
await api(
`/api/v1/existing-business/listings/${record.id}${action ? '/transitions' : ''}`,
action
? {
action,
version_no: record.version_no,
note,
review_consent: consent,
}
: {
_method: 'PUT',
modality,
classification: record.classification,
payload,
reason: note,
version_no: record.version_no,
},
);
router.reload();
} catch (err) {
setError(
err instanceof Error
? err.message
: 'Não foi possível guardar. Recarregue se a versão mudou.',
);
} finally {
setBusy(false);
}
};
return (
<Frame title={record.payload.title}>
<p>
<Link
className="underline"
href={`/investidor/negocios/${record.id}/classificacao`}
>
Classificação multidimensional deste anúncio
</Link>
</p>
<Link
className="underline"
href={owner ? '/investidor/negocios' : '/management/negocios'}
>
Voltar à lista
</Link>
<p>
{businessStates[record.status]} · versão {record.version_no} ·
informação reservada
</p>
<BusinessPointSummary
payload={record.payload}
registered={registeredLocation}
available={pointPublicationAvailable}
published={record.status === 'published'}
territoryLabel={businessPointTerritoryLabel(
record.payload,
record.territory_paths,
)}
/>
<p>
Informação declarada, pendente de validação. Não constitui
anúncio público, certificação, avaliação ou autorização de
transmissão.
</p>
{!canEdit && (
<dl className={`${card} space-y-3 break-words`}>
<div>
<dt className="font-bold">Sector</dt>
<dd>
{sectors.find(
(sector) => sector.id === record.sector_id,
)?.name ?? '—'}
</dd>
</div>
{Object.entries(formSchema)
.filter(
([key, field]) =>
!key.startsWith('location_point_') &&
![
'location_latitude',
'location_longitude',
].includes(key) &&
Object.entries(field.when ?? {}).every(
([dependency, values]) =>
values.includes(
record.payload[dependency] ?? '',
),
) &&
![
'title',
'description',
'declared_reason',
'source_reference',
'valid_until',
].includes(key),
)
.map(([key, field]) => (
<div key={key}>
<dt className="font-bold">{field.pt}</dt>
<dd className="whitespace-pre-wrap">
{record.payload[key] || '—'}
</dd>
</div>
))}
</dl>
)}
<form
className={`${card} space-y-4`}
onSubmit={(e) => {
e.preventDefault();
void run();
}}
>
<fieldset disabled={!canEdit || busy} className="space-y-4">
<Field label="Modalidade">
<select
className={input}
value={modality}
onChange={(e) => setModality(e.target.value)}
>
{modalities.map((m) => (
<option value={m} key={m}>
{businessModalities[m] ?? m}
</option>
))}
</select>
</Field>
{(
[
['title', 'Título privado'],
['description', 'Descrição reservada'],
['declared_reason', 'Motivo declarado'],
['source_reference', 'Referência da fonte'],
['valid_until', 'Validade declarada'],
] as const
).map(([key, label]) => (
<Field key={key} label={label}>
{key === 'description' ? (
<textarea
className={input}
rows={5}
maxLength={10000}
value={payload[key] ?? ''}
onChange={(e) =>
setPayload({
...payload,
[key]: e.target.value,
})
}
/>
) : (
<input
className={input}
type={
key === 'valid_until' ? 'date' : 'text'
}
maxLength={key === 'title' ? 200 : 2000}
value={payload[key] ?? ''}
onChange={(e) =>
setPayload({
...payload,
[key]: e.target.value,
})
}
/>
)}
</Field>
))}
</fieldset>
<Field label="Motivo da alteração ou nota para a revisão">
<textarea
className={input}
value={note}
onChange={(e) => setNote(e.target.value)}
aria-describedby="business-transition-help"
minLength={10}
maxLength={1000}
required
/>
</Field>
{error && <p role="alert">{error}</p>}
{canEdit && (
<button
className={button}
disabled={busy || note.trim().length < 10}
>
Guardar rascunho
</button>
)}
{dirty && (
<p role="status">
Guarde as alterações antes de mudar de estado.
</p>
)}
</form>
{owner && canEdit && (
<label className="flex gap-3">
<input
type="checkbox"
checked={consent}
onChange={(e) => setConsent(e.target.checked)}
/>
Autorizo a análise interna desta submissão pelos revisores
designados. Esta autorização não permite publicação.
</label>
)}
{(canTriage ||
canReview ||
canApproveLevelOne ||
canApproveLevelTwo ||
canPublish) && (
<p id="business-transition-help" role="status" className="my-3">
{busy
? 'Aguarde a conclusão da ação em curso.'
: note.trim().length < 10
? 'Para disponibilizar a ação, preencha «Motivo da alteração ou nota para a revisão» com pelo menos 10 caracteres. A nota fica no histórico reservado.'
: 'Nota preenchida. Pode executar a ação disponível para o seu papel e o estado atual.'}
</p>
)}
<div className="flex flex-wrap gap-3">
{owner && canEdit && (
<button
className={button}
disabled={
busy || dirty || !consent || note.trim().length < 10
}
onClick={() => void run('submitted')}
>
Submeter para análise
</button>
)}
{canReview && record.status === 'submitted' && (
<button
className={button}
disabled={busy || note.trim().length < 10}
onClick={() => void run('in_review')}
>
Iniciar revisão
</button>
)}
{canReview && record.status === 'in_review' && (
<button
className={button}
disabled={busy || note.trim().length < 10}
onClick={() => void run('needs_information')}
>
Pedir informação
</button>
)}
{canTriage && record.status === 'submitted' && (
<button
className={button}
disabled={busy || note.trim().length < 10}
aria-describedby="business-transition-help"
onClick={() => void run('triage')}
>
Iniciar triagem
</button>
)}
{canReview && record.status === 'triage' && (
<button
className={button}
disabled={busy || note.trim().length < 10}
onClick={() => void run('in_review')}
>
Encaminhar para revisão
</button>
)}
{canReview && record.status === 'in_review' && (
<>
<button
className={button}
disabled={busy || note.trim().length < 10}
onClick={() => void run('approval_l1')}
>
Enviar para aprovação nível 1
</button>
<button
className={button}
disabled={busy || note.trim().length < 10}
onClick={() => void run('rejected')}
>
Rejeitar
</button>
</>
)}
{canApproveLevelOne && record.status === 'approval_l1' && (
<>
<button
className={button}
disabled={busy || note.trim().length < 10}
onClick={() => void run('approval_l2')}
>
Aprovar nível 1 e enviar ao nível 2
</button>
<button
className={button}
disabled={busy || note.trim().length < 10}
onClick={() => void run('rejected')}
>
Rejeitar
</button>
</>
)}
{canApproveLevelTwo && record.status === 'approval_l2' && (
<>
<button
className={button}
disabled={busy || note.trim().length < 10}
onClick={() => void run('approved')}
>
Aprovar nível 2
</button>
<button
className={button}
disabled={busy || note.trim().length < 10}
onClick={() => void run('rejected')}
>
Rejeitar
</button>
</>
)}
{canPublish && record.status === 'approved' && (
<button
className={button}
disabled={busy || note.trim().length < 10}
onClick={() => void run('published')}
>
Publicar
</button>
)}
{owner && record.status !== 'withdrawn' && (
<button
className={button}
disabled={busy || dirty || note.trim().length < 10}
onClick={() => void run('withdrawn')}
>
Retirar submissão
</button>
)}
</div>
<BusinessObjects
businessId={record.id}
version={record.version_no}
editable={canEdit && !dirty && !busy}
objects={objects}
objectKinds={objectKinds}
/>
<BusinessVerifications
id={record.id}
version={record.version_no}
editable={canReview && record.status === 'in_review' && !busy}
checks={verificationChecks}
findings={verifications}
objects={objects}
/>
<section className={card}>
<h2 className="text-xl font-bold">Histórico</h2>
<ol>
{history.map((h) => (
<li key={h.version_no}>
Versão {h.version_no} ·{' '}
{businessStates[h.action] ??
(
{
created: 'Criado',
updated: 'Alterado',
archived: 'Arquivado',
object_added:
'Elemento declarado acrescentado',
object_updated:
'Elemento declarado alterado',
verification: 'Verificação registada',
} as Record<string, string>
)[h.action] ??
h.action}{' '}
· {new Date(h.created_at).toLocaleString('pt-MZ')}
<p>{h.note}</p>
</li>
))}
</ol>
</section>
</Frame>
);
}