import { Head, router } from '@inertiajs/react'; import { useState } from 'react'; import { TerritoryFields, type TerritoryOption, } from '@/components/investment-territory'; import OpportunityContactForm from '@/components/opportunity-contact-form'; import { modalityLabels } from '@/components/opportunity-search-filters'; import { createOperationKey } from '@/lib/operation-key'; import { profileJson, ProfileValidationError } from '@/lib/profile-json'; import OfferEditorialReview from '@/components/offer-editorial-review'; import { type OfferEditorialRecord } from '@/lib/offer-editorial'; import OfferParticularsFields, { type OfferParticulars, } from '@/components/offer-particulars'; import OfferPrivateResources from '@/components/offer-private-resources'; import OfferConfidentialAccess from '@/components/offer-confidential-access'; import OfferOperations from '@/components/offer-operations'; import OfferNavigation from '@/components/offer-navigation'; type Offer = OfferParticulars & { price_mode?: string | null; amount?: string | null; currency?: string | null; contact_id?: string | null; }; type Context = { organization_id: string | null; organization_name: string | null; type: string; }; type RecordData = OfferEditorialRecord & { id: number; reference: string; etag: string; state: string; canEdit: boolean; organization_id: string | null; territory: TerritoryOption[]; contactLabel?: string | null; values: { title?: string; description?: string; opportunity_category: string; private_offer?: Offer; }; }; type Contact = { id: string; full_name: string }; const control = 'w-full rounded-md border bg-background p-2 text-foreground'; const button = 'rounded-md bg-primary px-4 py-2 text-primary-foreground disabled:opacity-50'; const emptyPath: TerritoryOption[] = []; export default function OfferPreparation({ record, contexts, contacts, contactInvestors, sectors, propertyTypes, }: { record: RecordData | null; contexts: Context[]; contacts: Contact[]; contactInvestors: { id: string; legal_name: string }[]; sectors: { id: number; name: string }[]; propertyTypes: string[]; }) { const [saved, setSaved] = useState(record); const [creationKey] = useState(createOperationKey); const [context, setContext] = useState( record ? { organization_id: record.organization_id, organization_name: null, type: record.values.opportunity_category, } : contexts[0], ); const [title, setTitle] = useState(record?.values.title ?? ''); const [description, setDescription] = useState( record?.values.description ?? '', ); const [offer, setOffer] = useState( record?.values.private_offer ?? { price_mode: null, amount: null, currency: null, contact_id: null, }, ); const [territory, setTerritory] = useState(record?.territory ?? emptyPath); const [contactChoices, setContactChoices] = useState(() => { const selected = record?.values.private_offer?.contact_id; return selected && !contacts.some((contact) => contact.id === selected) ? [ ...contacts, { id: selected, full_name: record?.contactLabel ?? 'Contacto indisponível', }, ] : contacts; }); const [dirty, setDirty] = useState(!record); const [busy, setBusy] = useState(false); const [confirmed, setConfirmed] = useState(false); const [errors, setErrors] = useState>({}); const [message, setMessage] = useState(''); const readOnly = saved !== null && !saved.canEdit; function updateOffer(next: Offer) { setOffer(next); setDirty(true); setConfirmed(false); } async function execute(submit: boolean) { if (busy || readOnly || (submit && (!saved || dirty || !confirmed))) return; setBusy(true); setErrors({}); setMessage(''); try { const base = '/minhas-oportunidades/ofertas'; const result = await profileJson( submit ? `${base}/${saved!.id}/submeter` : saved ? `${base}/${saved.id}/guardar` : `${base}/rascunhos`, submit ? { etag: saved!.etag, confirm: confirmed } : { ...(saved ? { etag: saved.etag } : { creation_key: creationKey }), title, description, opportunity_category: context.type, organization_id: context.organization_id, private_offer: offer, province_id: territory[0]?.id ?? null, district_id: territory[1]?.id ?? null, admin_post_id: territory[2]?.id ?? null, locality_id: territory[3]?.id ?? null, reason: 'Preparação privada da oferta pelo promotor autorizado.', }, ); setSaved(result.record); setDirty(false); setConfirmed(false); setMessage( submit ? 'Submissão privada registada. A oferta não está publicada.' : 'Oferta guardada. Pode retomá-la mais tarde.', ); if (!saved) router.visit(`${base}/${result.record.id}`); } catch (error) { setMessage( error instanceof Error ? error.message : 'Não foi possível concluir. Os campos preenchidos foram preservados.', ); if (error instanceof ProfileValidationError) setErrors(error.fields); } finally { setBusy(false); } } return (
0} />

Preparar oferta

{saved?.state === 'submitted' ? 'Submissão privada registada. A oferta permanece sem publicação.' : 'Complete os dados ao seu ritmo. A gravação e a submissão mantêm a oferta privada.'}

{saved &&

{saved.reference}

}
{saved && ( { setSaved(next); setDirty(false); setConfirmed(false); }} /> )}
{message}
{saved && ( { void profileJson( `/minhas-oportunidades/ofertas/${saved.id}`, {}, 'GET', ) .then((result) => { setSaved(result.record); setConfirmed(false); }) .catch((error) => setMessage(error.message)); }} /> )} {Object.keys(errors).length > 0 && (

Confira os seguintes campos:

    {Object.entries(errors).map(([key, value]) => (
  • {value}
  • ))}
)}
{ event.preventDefault(); void execute(false); }} className="space-y-6" >
1. Identificação