'use client' import Link from 'next/link' import { useState, type FormEvent } from 'react' import { toast } from 'sonner' import { searchActivityResponsibleOptionsAction } from '@/app/(campaign)/campanha/(app)/atividades/contactSearchActions' import { createActivityInline } from '@/app/(campaign)/campanha/actions/activity' import { ActivityDateTimeField } from '@/components/campaign/activity/ActivityDateTimeField' import { ActivityTagInput } from '@/components/campaign/activity/ActivityTagInput' import type { RelationOption } from '@/components/campaign/shared/RelationMultiSelect' import { ResponsibleMultiSelect } from '@/components/campaign/shared/ResponsibleMultiSelect' import { StrictCombobox } from '@/components/campaign/shared/StrictCombobox' import { Alert, AlertDescription } from '@/components/ui/Alert' import { Button } from '@/components/ui/button' import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle, } from '@/components/ui/Drawer' import { Field, FieldError, FieldLabel } from '@/components/ui/field' import { Input } from '@/components/ui/input' import { Popover, PopoverAnchor, PopoverContent } from '@/components/ui/Popover' import { Spinner } from '@/components/ui/Spinner' import { formatBahiaDateTimeLabel, formatIsoAsBahiaDateTimeInput, parseBahiaDateTimeInput, } from '@/lib/campaignTime' import { activityResponsibleSchema, type ActivityCreateInput } from '@/lib/schemas/activity' import { buildActivityCreateHref, type ActivityAgendaState } from '@/utilities/activityUi' import type { StrictComboboxOption } from '@/utilities/territory/territoryComboboxOptions' /** * C91 — the Google-Calendar-like quick create anchored on a calendar slot. * One content component is rendered inside a Popover (desktop, anchored at the * click) or a bottom Drawer (mobile); saving never navigates and the parent * refetches the visible window (`onCreated`). */ export type ActivityInlineCreateDraft = { startAt: string endAt: string anchor: { x: number; y: number } | null } type ActivityInlineCreateProps = { draft: ActivityInlineCreateDraft | null isNarrow: boolean agendaState: ActivityAgendaState municipalityOptions: RelationOption[] knownTags?: string[] onClose: () => void onCreated: () => void } const inlineMunicipalityOptions = (options: RelationOption[]): StrictComboboxOption[] => options.map((option) => ({ value: String(option.id), label: option.name })) /** * Bounded JSON-array read for the inline sheet's `responsiblesJson` hidden * input: same 4 KB cap as the full form's `boundedJsonFormValue`, fail-closed * on malformed or oversized payloads (the component generates the JSON, so a * violation means tampering, not user input). */ const INLINE_JSON_MAX_BYTES = 4_000 const parseInlineJsonArray = (raw: FormDataEntryValue | null): unknown[] | undefined => { if (typeof raw !== 'string' || raw.length > INLINE_JSON_MAX_BYTES) return undefined try { const parsed: unknown = JSON.parse(raw) return Array.isArray(parsed) && parsed.length > 0 ? parsed : undefined } catch { return undefined } } const parseInlineResponsibles = ( raw: FormDataEntryValue | null, ): ActivityCreateInput['responsible'] => { const parsed = parseInlineJsonArray(raw) if (!parsed) return undefined const entries: Array<{ relationTo: 'campaignUser' | 'leadership' | 'stateDeputy' value: number }> = [] for (const item of parsed) { const result = activityResponsibleSchema.safeParse(item) if (result.success) entries.push(result.data) } return entries.length > 0 ? entries : undefined } const ActivityInlineCreateForm = ({ startAt, endAt, agendaState, municipalityOptions, knownTags, onCreated, }: { startAt: string endAt: string agendaState: ActivityAgendaState municipalityOptions: RelationOption[] knownTags?: string[] onCreated: () => void }) => { const [title, setTitle] = useState('') const [start, setStart] = useState(formatIsoAsBahiaDateTimeInput(startAt)) const [end, setEnd] = useState(formatIsoAsBahiaDateTimeInput(endAt)) const [locality, setLocality] = useState('') const [tags, setTags] = useState([]) const preselectedMunicipalityId = agendaState.municipality && municipalityOptions.some((option) => option.id === agendaState.municipality) ? String(agendaState.municipality) : '' const [municipalityValue, setMunicipalityValue] = useState(preselectedMunicipalityId) const [fieldErrors, setFieldErrors] = useState>({}) const [failedMessage, setFailedMessage] = useState(null) const [saving, setSaving] = useState(false) const errorFor = (name: string) => fieldErrors[name]?.[0] // C105 — the href mirrors the LIVE state (times edited in the sheet, typed // tags), not the slot draft, so "Mais detalhes" carries everything the user // actually filled. const moreDetailsHref = buildActivityCreateHref(agendaState, { startAt: parseBahiaDateTimeInput(start) ?? undefined, endAt: end ? (parseBahiaDateTimeInput(end) ?? undefined) : undefined, municipalityId: municipalityValue ? Number(municipalityValue) : undefined, title: title.trim() || undefined, tags: tags.length > 0 ? tags : undefined, }) const handleSubmit = async (event: FormEvent) => { event.preventDefault() const formData = new FormData(event.currentTarget) const trimmedTitle = title.trim() const municipalityId = Number(municipalityValue) const startIso = parseBahiaDateTimeInput(start) const endIso = end ? parseBahiaDateTimeInput(end) : undefined const nextFieldErrors: Record = {} if (!trimmedTitle) { nextFieldErrors.title = ['Informe o título do compromisso.'] } else if (trimmedTitle.length < 2) { nextFieldErrors.title = ['Informe um título com ao menos 2 caracteres.'] } if (!municipalityId) nextFieldErrors.municipality = ['Informe o município.'] if (!startIso) nextFieldErrors.startAt = ['Informe a data e horário de início do compromisso.'] if (startIso && endIso && new Date(endIso) <= new Date(startIso)) { nextFieldErrors.endAt = ['O horário de término deve ser posterior ao de início.'] } if (Object.keys(nextFieldErrors).length > 0) { setFieldErrors(nextFieldErrors) return } setFieldErrors({}) setFailedMessage(null) setSaving(true) try { const responsible = parseInlineResponsibles(formData.get('responsiblesJson')) const result = await createActivityInline({ title: trimmedTitle, municipality: municipalityId, startAt: startIso as string, ...(endIso ? { endAt: endIso } : {}), ...(locality.trim() ? { locality: locality.trim() } : {}), ...(responsible ? { responsible } : {}), // C105 — the tags mirror state (every chip mutation fires `onChange`), // so the payload reads the same source the "Mais detalhes" href uses. ...(tags.length > 0 ? { tags } : {}), }) if (result.ok) { onCreated() return } setSaving(false) setFieldErrors(result.fieldErrors ?? {}) setFailedMessage(result.message) toast.error(result.message) } catch { setSaving(false) const message = 'Não foi possível criar o compromisso. Tente novamente.' setFailedMessage(message) toast.error(message) } } return (
Título * setTitle(event.target.value)} maxLength={160} minLength={2} placeholder="Ex.: Café com apoiadores" className="min-h-11" autoComplete="off" aria-invalid={Boolean(errorFor('title'))} aria-describedby={errorFor('title') ? 'inline-title-error' : undefined} /> {errorFor('title') ? ( {errorFor('title')} ) : null}
Início * {errorFor('startAt') ? ( {errorFor('startAt')} ) : null} Término {errorFor('endAt') ? ( {errorFor('endAt')} ) : null}
Município * {errorFor('municipality') ? ( {errorFor('municipality')} ) : null} Local (opcional) setLocality(event.target.value)} maxLength={160} placeholder="Bairro, endereço ou referência" className="min-h-11" /> Tags {failedMessage ? ( {failedMessage} ) : null}
) } export const ActivityInlineCreate = ({ draft, isNarrow, agendaState, municipalityOptions, knownTags, onClose, onCreated, }: ActivityInlineCreateProps) => { if (!draft) return null const form = ( ) if (isNarrow) { return ( (next ? undefined : onClose())} showSwipeHandle> Nova atividade {formatBahiaDateTimeLabel(draft.startAt)}
{form}
) } return ( (next ? undefined : onClose())}> {/* C105 — the tags field made the sheet taller. The height is capped at the space Radix computed for the current placement (`--radix-popper-available-height`, set by its `size` middleware): the sheet always fits the viewport on its placed side and scrolls internally instead of clipping fields off-screen (a static cap is not enough — Radix runs shift before flip, so an overflowing popover can end up with its top fields out of view). */} {form} ) }