mirror of
https://github.com/fsolla/teqo.git
synced 2026-11-27 06:13:06 +00:00
Add baseUpdatedAt CAS on domain staff writes, assertCampaignDocCas helper, opsDomainOutbox with hybrid forms (Manter/Usar), and int/unit pins. Closes #176. Co-authored-by: Francisco Solla <fsolla@users.noreply.github.com>
234 lines
8.3 KiB
TypeScript
234 lines
8.3 KiB
TypeScript
'use client'
|
|
|
|
import { useActionState, useState, type FormEvent } from 'react'
|
|
|
|
import { enqueueLeadershipCreate } from '@/components/campaign/opsSync/opsDomainOutbox'
|
|
import { CampaignFormActionMessage } from '@/components/campaign/shared/CampaignFormActionMessage'
|
|
import {
|
|
RelationMultiSelect,
|
|
type RelationOption,
|
|
} from '@/components/campaign/shared/RelationMultiSelect'
|
|
import { Badge } from '@/components/ui/Badge'
|
|
import { Button } from '@/components/ui/button'
|
|
import { Checkbox } from '@/components/ui/Checkbox'
|
|
import { Field, FieldError, FieldLabel } from '@/components/ui/field'
|
|
import { Input } from '@/components/ui/input'
|
|
import { NativeSelect, NativeSelectOption } from '@/components/ui/native-select'
|
|
import { Spinner } from '@/components/ui/Spinner'
|
|
import { Textarea } from '@/components/ui/textarea'
|
|
import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
|
|
import {
|
|
isSupportStatus,
|
|
leadershipSupportStatuses,
|
|
type SupportStatus,
|
|
} from '@/lib/schemas/leadership'
|
|
import type { CampaignFormActionState } from '@/utilities/campaignFormActionError'
|
|
import { fieldError } from '@/utilities/campaignFormFields'
|
|
import { supportStatusLabels } from '@/utilities/leadership/leadershipLabels'
|
|
|
|
type LeadershipFormProps = {
|
|
municipalityOptions: RelationOption[]
|
|
organizationOptions: RelationOption[]
|
|
stateDeputyOptions: RelationOption[]
|
|
initialMunicipalityIDs: number[]
|
|
formAction: (
|
|
state: CampaignFormActionState,
|
|
formData: FormData,
|
|
) => Promise<CampaignFormActionState>
|
|
opsHybridEnabled?: boolean
|
|
}
|
|
|
|
const readRelationshipIds = (data: FormData, name: string): number[] => {
|
|
const ids: number[] = []
|
|
for (const raw of data.getAll(name)) {
|
|
if (typeof raw !== 'string' || raw.trim() === '') continue
|
|
const value = Number(raw)
|
|
if (Number.isInteger(value) && value > 0) ids.push(value)
|
|
}
|
|
return [...new Set(ids)]
|
|
}
|
|
|
|
export const LeadershipForm = ({
|
|
municipalityOptions,
|
|
organizationOptions,
|
|
stateDeputyOptions,
|
|
initialMunicipalityIDs,
|
|
formAction,
|
|
opsHybridEnabled = resolveOpsHybridEnabled(),
|
|
}: LeadershipFormProps) => {
|
|
const [state, submitAction, isPending] = useActionState(formAction, {})
|
|
const [hybridPending, setHybridPending] = useState(false)
|
|
const [hybridMessage, setHybridMessage] = useState<string | null>(null)
|
|
|
|
const onHybridSubmit = (event: FormEvent<HTMLFormElement>) => {
|
|
event.preventDefault()
|
|
const form = event.currentTarget
|
|
const data = new FormData(form)
|
|
const name = data.get('name')
|
|
const phone = data.get('phone')
|
|
if (typeof name !== 'string' || name.trim().length < 2) {
|
|
setHybridMessage('Informe o nome completo.')
|
|
return
|
|
}
|
|
if (typeof phone !== 'string' || phone.trim() === '') {
|
|
setHybridMessage('Informe o celular.')
|
|
return
|
|
}
|
|
const supportStatusRaw = data.get('supportStatus')
|
|
const supportStatus =
|
|
typeof supportStatusRaw === 'string' && isSupportStatus(supportStatusRaw)
|
|
? (supportStatusRaw as SupportStatus)
|
|
: 'a_abordar'
|
|
const exclusiveValues = data.getAll('exclusive')
|
|
const emailRaw = data.get('email')
|
|
const notesRaw = data.get('notes')
|
|
|
|
setHybridPending(true)
|
|
setHybridMessage(null)
|
|
void enqueueLeadershipCreate({
|
|
clientId: crypto.randomUUID(),
|
|
name: name.trim(),
|
|
phone: phone.trim(),
|
|
email: typeof emailRaw === 'string' && emailRaw.trim() !== '' ? emailRaw.trim() : null,
|
|
municipalities: readRelationshipIds(data, 'municipalities'),
|
|
organizations: readRelationshipIds(data, 'organizations'),
|
|
stateDeputies: readRelationshipIds(data, 'stateDeputies'),
|
|
exclusive: exclusiveValues.length === 0 ? true : exclusiveValues.at(-1) === 'true',
|
|
supportStatus,
|
|
notes: typeof notesRaw === 'string' && notesRaw.trim() !== '' ? notesRaw.trim() : undefined,
|
|
}).then(
|
|
() => {
|
|
setHybridPending(false)
|
|
setHybridMessage(
|
|
'Cadastro enfileirado. Será enviado ao reconectar — a ficha aparece depois da sincronização.',
|
|
)
|
|
form.reset()
|
|
},
|
|
(error: unknown) => {
|
|
setHybridPending(false)
|
|
setHybridMessage(
|
|
error instanceof Error ? error.message : 'Não foi possível enfileirar o cadastro.',
|
|
)
|
|
},
|
|
)
|
|
}
|
|
|
|
const pending = opsHybridEnabled ? hybridPending : isPending
|
|
|
|
return (
|
|
<form
|
|
action={opsHybridEnabled ? undefined : submitAction}
|
|
onSubmit={opsHybridEnabled ? onHybridSubmit : undefined}
|
|
className="flex max-w-2xl flex-col gap-4"
|
|
>
|
|
<div className="flex flex-wrap items-center gap-2">
|
|
{hybridPending ? <Badge variant="estimate-pending">Pendente</Badge> : null}
|
|
</div>
|
|
<Field>
|
|
<FieldLabel htmlFor="leadership-name">Nome completo</FieldLabel>
|
|
<Input
|
|
id="leadership-name"
|
|
name="name"
|
|
required
|
|
minLength={2}
|
|
maxLength={120}
|
|
className="min-h-11"
|
|
/>
|
|
{fieldError(state.fieldErrors, 'name') ? (
|
|
<FieldError>{fieldError(state.fieldErrors, 'name')}</FieldError>
|
|
) : null}
|
|
</Field>
|
|
<div className="grid gap-4 sm:grid-cols-2">
|
|
<Field>
|
|
<FieldLabel htmlFor="leadership-phone">Celular (com DDD)</FieldLabel>
|
|
<Input
|
|
id="leadership-phone"
|
|
name="phone"
|
|
type="tel"
|
|
required
|
|
autoComplete="tel-national"
|
|
className="min-h-11"
|
|
/>
|
|
{fieldError(state.fieldErrors, 'phone') ? (
|
|
<FieldError>{fieldError(state.fieldErrors, 'phone')}</FieldError>
|
|
) : null}
|
|
</Field>
|
|
<Field>
|
|
<FieldLabel htmlFor="leadership-email">E-mail (opcional)</FieldLabel>
|
|
<Input id="leadership-email" name="email" type="email" className="min-h-11" />
|
|
{fieldError(state.fieldErrors, 'email') ? (
|
|
<FieldError>{fieldError(state.fieldErrors, 'email')}</FieldError>
|
|
) : null}
|
|
</Field>
|
|
</div>
|
|
|
|
<RelationMultiSelect
|
|
name="municipalities"
|
|
label="Municípios em que atua"
|
|
options={municipalityOptions}
|
|
initialSelectedIDs={initialMunicipalityIDs}
|
|
error={fieldError(state.fieldErrors, 'municipalities')}
|
|
placeholder="Adicionar município…"
|
|
/>
|
|
|
|
<RelationMultiSelect
|
|
name="organizations"
|
|
label="Organizações (sindicatos, associações…)"
|
|
options={organizationOptions}
|
|
error={fieldError(state.fieldErrors, 'organizations')}
|
|
placeholder="Adicionar organização…"
|
|
/>
|
|
|
|
<RelationMultiSelect
|
|
name="stateDeputies"
|
|
label="Dobradinhas"
|
|
options={stateDeputyOptions}
|
|
error={fieldError(state.fieldErrors, 'stateDeputies')}
|
|
placeholder="Adicionar dobradinha…"
|
|
/>
|
|
|
|
<div className="grid gap-4 sm:grid-cols-2">
|
|
<Field>
|
|
<FieldLabel htmlFor="leadership-status">Status de apoio</FieldLabel>
|
|
<NativeSelect
|
|
id="leadership-status"
|
|
name="supportStatus"
|
|
defaultValue="a_abordar"
|
|
className="min-h-11 w-full"
|
|
>
|
|
{leadershipSupportStatuses.map((status) => (
|
|
<NativeSelectOption key={status} value={status}>
|
|
{supportStatusLabels[status]}
|
|
</NativeSelectOption>
|
|
))}
|
|
</NativeSelect>
|
|
</Field>
|
|
<Field orientation="horizontal" className="items-center gap-2 self-end pb-2">
|
|
<input type="hidden" name="exclusive" value="false" />
|
|
<Checkbox id="leadership-exclusive" name="exclusive" value="true" defaultChecked />
|
|
<FieldLabel htmlFor="leadership-exclusive" className="font-normal">
|
|
Apoio exclusivo
|
|
</FieldLabel>
|
|
</Field>
|
|
</div>
|
|
|
|
<Field>
|
|
<FieldLabel htmlFor="leadership-notes">Observações internas</FieldLabel>
|
|
<Textarea id="leadership-notes" name="notes" rows={3} maxLength={3000} />
|
|
</Field>
|
|
|
|
{!opsHybridEnabled && state.status !== 'success' ? (
|
|
<CampaignFormActionMessage state={state} />
|
|
) : null}
|
|
{hybridMessage ? (
|
|
<p className="text-sm text-muted-foreground" role="status">
|
|
{hybridMessage}
|
|
</p>
|
|
) : null}
|
|
<Button type="submit" disabled={pending} className="min-h-11 self-start">
|
|
{pending ? <Spinner data-icon="inline-start" aria-hidden="true" /> : null}
|
|
Cadastrar liderança
|
|
</Button>
|
|
</form>
|
|
)
|
|
}
|