mirror of
https://github.com/fsolla/teqo.git
synced 2026-11-30 02:03:05 +00:00
Collection actionPlan -> activity (labels "Atividade"/"Atividades"), campo
campaignDemand.actionPlan -> activity, rota /campanha/planos ->
/campanha/atividades (criacao em atividades/nova), sidebar "Atividades" e
rotulos alinhados a entidade ("Tipo de atividade", "Origem da atividade",
"Resultado da atividade"). Valores de enum kind/status/origin inalterados.
Schema movido por migration data-preserving escrita a mao
(20260725_213000_rename_action_plan_to_activity): 4 tabelas, 3 enums, 2
colunas, 39 indices (4 pkeys inclusos), 14 FKs e 2 sequences, cada statement
guardado na existencia do objeto de origem, com down() simetrico. O gerador do
Payload emitiria DROP+CREATE e nao ve o indice parcial escrito a mao
action_plan_upcoming_start_at_idx, entao a lista veio de
pg_indexes/pg_constraint/pg_type/pg_sequences e o snapshot .json foi derivado
do anterior por transformacao textual -- validado por migrate:create __probe
sem mudanca de schema. A mesma migration alinha os 8 indices fosseis %plaza%
que a remodelagem de municipios deixou (renomeou as colunas plaza_id, nao os
indices).
Guard: o describe "banned campaign terminology" de
codebaseConventions.unit.spec.ts virou tabela de termos varrendo src+tests+
scripts (migrations fora -- historia congelada), banindo os compostos
actionPlan, a copy "plano de acao" e a rota antiga, mas nao plan/plano isolado
(colidiria com os planos de assinatura da Fase 2). Allowlist: o proprio spec,
scripts/generate-remodel-municipalities-migration.mjs e o comentario historico
em campaignMigrationReconciliation.int.spec.ts.
Plano: docs/plans/renomear-plano-acao-para-atividade.md
396 lines
10 KiB
TypeScript
396 lines
10 KiB
TypeScript
import type {
|
|
CollectionBeforeChangeHook,
|
|
CollectionBeforeValidateHook,
|
|
CollectionConfig,
|
|
} from 'payload'
|
|
import { APIError } from 'payload'
|
|
|
|
import {
|
|
campaignDemandKindLabels,
|
|
campaignDemandKinds,
|
|
campaignDemandStatusLabels,
|
|
campaignDemandStatuses,
|
|
campaignDemandTransitions,
|
|
type CampaignDemandStatus,
|
|
} from '@/lib/schemas/campaignDemand'
|
|
import { slugify } from '@/lib/slug'
|
|
import {
|
|
canCreateCampaignDemand,
|
|
canDeleteCampaignDemand,
|
|
canManageCampaignStaffField,
|
|
canReadCampaignDemand,
|
|
canReadCampaignStaffField,
|
|
canSetCampaignSystemField,
|
|
canUpdateCampaignDemand,
|
|
isCampaignUnrestricted,
|
|
} from '@/utilities/campaignAccess'
|
|
import { relationshipId } from '@/utilities/relationship'
|
|
|
|
const trimmedText = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')
|
|
|
|
const DEMAND_KIND_OPTIONS = campaignDemandKinds.map((value) => ({
|
|
value,
|
|
label: campaignDemandKindLabels[value],
|
|
}))
|
|
|
|
const DEMAND_STATUS_OPTIONS = campaignDemandStatuses.map((value) => ({
|
|
value,
|
|
label: campaignDemandStatusLabels[value],
|
|
}))
|
|
|
|
const setCanonicalDemandSlug: CollectionBeforeValidateHook = ({ data, operation, originalDoc }) => {
|
|
if (!data) return data
|
|
const title = trimmedText(data.title ?? originalDoc?.title)
|
|
const slug = slugify(title)
|
|
if (!slug) {
|
|
throw new APIError('Informe um título com letras ou números.', 400)
|
|
}
|
|
data.title = title
|
|
data.slug = operation === 'create' ? slug : originalDoc?.slug
|
|
return data
|
|
}
|
|
|
|
const isDemandStatus = (value: unknown): value is CampaignDemandStatus =>
|
|
typeof value === 'string' && (campaignDemandStatuses as readonly string[]).includes(value)
|
|
|
|
/**
|
|
* Workflow + authorship rules (staff-only creation):
|
|
* - status moves follow campaignDemandTransitions; decisions on "escalada"
|
|
* demands are coordinator/candidate-only;
|
|
* - every status move appends a server-derived statusHistory entry.
|
|
*/
|
|
const enforceDemandWorkflow: CollectionBeforeChangeHook = async ({
|
|
data,
|
|
operation,
|
|
originalDoc,
|
|
req,
|
|
}) => {
|
|
const actor = req.user?.collection === 'campaignUser' ? req.user : null
|
|
|
|
if (operation === 'create') {
|
|
if (actor) data.createdBy = actor.id
|
|
|
|
const initialStatus = isDemandStatus(data.status) ? data.status : 'aberta'
|
|
data.status = initialStatus
|
|
data.statusHistory = [
|
|
{
|
|
status: initialStatus,
|
|
note: trimmedText(data.decisionNote) || null,
|
|
author: actor?.id ?? null,
|
|
createdAt: new Date().toISOString(),
|
|
},
|
|
]
|
|
|
|
return data
|
|
}
|
|
|
|
const previousStatus: CampaignDemandStatus = isDemandStatus(originalDoc?.status)
|
|
? originalDoc.status
|
|
: 'aberta'
|
|
const rawNextStatus: unknown = data.status === undefined ? previousStatus : data.status
|
|
|
|
if (!isDemandStatus(rawNextStatus)) {
|
|
throw new APIError('Status de demanda inválido.', 400)
|
|
}
|
|
const nextStatus: CampaignDemandStatus = rawNextStatus
|
|
|
|
if (nextStatus !== previousStatus) {
|
|
const allowed = campaignDemandTransitions[previousStatus] ?? []
|
|
if (!allowed.includes(nextStatus)) {
|
|
throw new APIError(
|
|
`Transição de status inválida: ${campaignDemandStatusLabels[previousStatus]} → ${campaignDemandStatusLabels[nextStatus]}.`,
|
|
409,
|
|
)
|
|
}
|
|
|
|
if (
|
|
previousStatus === 'escalada' &&
|
|
(nextStatus === 'aprovada' || nextStatus === 'rejeitada') &&
|
|
actor &&
|
|
!isCampaignUnrestricted(actor)
|
|
) {
|
|
throw new APIError(
|
|
'Demandas escaladas são decididas pelo Coordenador Geral ou Candidato.',
|
|
403,
|
|
)
|
|
}
|
|
|
|
const history = Array.isArray(originalDoc?.statusHistory) ? [...originalDoc.statusHistory] : []
|
|
history.push({
|
|
status: nextStatus,
|
|
note: trimmedText(data.decisionNote ?? originalDoc?.decisionNote) || null,
|
|
author: actor?.id ?? null,
|
|
createdAt: new Date().toISOString(),
|
|
})
|
|
data.statusHistory = history
|
|
|
|
if (nextStatus === 'aprovada' || nextStatus === 'rejeitada') {
|
|
data.decidedBy = actor?.id ?? null
|
|
data.decidedAt = new Date().toISOString()
|
|
}
|
|
} else if (data.statusHistory !== undefined) {
|
|
// History is append-only and server-derived.
|
|
data.statusHistory = originalDoc?.statusHistory ?? []
|
|
}
|
|
|
|
return data
|
|
}
|
|
|
|
const validateDemandActivityMunicipality: CollectionBeforeValidateHook = async ({
|
|
data,
|
|
operation,
|
|
originalDoc,
|
|
req,
|
|
}) => {
|
|
if (!data) return data
|
|
|
|
const municipalityID = relationshipId(data.municipality ?? originalDoc?.municipality)
|
|
const activityID = relationshipId(data.activity ?? originalDoc?.activity)
|
|
if (!activityID) return data
|
|
if (!municipalityID) throw new APIError('Município da demanda inválido.', 400)
|
|
if (
|
|
operation === 'update' &&
|
|
municipalityID === relationshipId(originalDoc?.municipality) &&
|
|
activityID === relationshipId(originalDoc?.activity)
|
|
) {
|
|
return data
|
|
}
|
|
|
|
const requestContext = req.context as Record<string, unknown>
|
|
const cacheKey = `campaignDemand:activityMunicipality:${activityID}`
|
|
let activityMunicipalityID = requestContext[cacheKey]
|
|
if (typeof activityMunicipalityID !== 'number') {
|
|
const activity = await req.payload.findByID({
|
|
collection: 'activity',
|
|
id: activityID,
|
|
depth: 0,
|
|
select: { municipality: true },
|
|
overrideAccess: true,
|
|
req,
|
|
})
|
|
activityMunicipalityID = relationshipId(activity.municipality)
|
|
requestContext[cacheKey] = activityMunicipalityID
|
|
}
|
|
if (activityMunicipalityID !== municipalityID) {
|
|
throw new APIError('A demanda e a atividade devem pertencer ao mesmo município.', 409)
|
|
}
|
|
|
|
return data
|
|
}
|
|
|
|
export const CampaignDemand: CollectionConfig = {
|
|
slug: 'campaignDemand',
|
|
labels: {
|
|
singular: 'Demanda',
|
|
plural: 'Demandas',
|
|
},
|
|
admin: {
|
|
group: 'Campanha',
|
|
useAsTitle: 'title',
|
|
defaultColumns: ['title', 'kind', 'municipality', 'status', 'updatedAt'],
|
|
description:
|
|
'Necessidades operacionais da campanha. Custo e comprovantes são controle interno — não substituem a prestação de contas oficial (SPCE/TSE).',
|
|
},
|
|
access: {
|
|
create: canCreateCampaignDemand,
|
|
read: canReadCampaignDemand,
|
|
update: canUpdateCampaignDemand,
|
|
delete: canDeleteCampaignDemand,
|
|
},
|
|
hooks: {
|
|
beforeValidate: [setCanonicalDemandSlug, validateDemandActivityMunicipality],
|
|
beforeChange: [enforceDemandWorkflow],
|
|
},
|
|
fields: [
|
|
{
|
|
name: 'title',
|
|
type: 'text',
|
|
label: 'Título',
|
|
required: true,
|
|
minLength: 2,
|
|
maxLength: 160,
|
|
index: true,
|
|
},
|
|
{
|
|
name: 'slug',
|
|
type: 'text',
|
|
label: 'Slug',
|
|
required: true,
|
|
unique: true,
|
|
index: true,
|
|
admin: {
|
|
readOnly: true,
|
|
},
|
|
access: {
|
|
create: canSetCampaignSystemField,
|
|
update: canSetCampaignSystemField,
|
|
},
|
|
},
|
|
{
|
|
name: 'kind',
|
|
type: 'select',
|
|
label: 'Tipo',
|
|
required: true,
|
|
index: true,
|
|
options: [...DEMAND_KIND_OPTIONS],
|
|
},
|
|
{
|
|
name: 'description',
|
|
type: 'textarea',
|
|
label: 'Descrição',
|
|
maxLength: 4000,
|
|
},
|
|
{
|
|
name: 'municipality',
|
|
type: 'relationship',
|
|
relationTo: 'municipality',
|
|
label: 'Município',
|
|
required: true,
|
|
index: true,
|
|
},
|
|
{
|
|
name: 'activity',
|
|
type: 'relationship',
|
|
relationTo: 'activity',
|
|
label: 'Atividade',
|
|
index: true,
|
|
},
|
|
{
|
|
name: 'leadership',
|
|
type: 'relationship',
|
|
relationTo: 'leadership',
|
|
label: 'Liderança solicitante',
|
|
index: true,
|
|
},
|
|
{
|
|
name: 'status',
|
|
type: 'select',
|
|
label: 'Status',
|
|
required: true,
|
|
defaultValue: 'aberta',
|
|
index: true,
|
|
access: {
|
|
create: canManageCampaignStaffField,
|
|
update: canManageCampaignStaffField,
|
|
},
|
|
options: [...DEMAND_STATUS_OPTIONS],
|
|
},
|
|
{
|
|
name: 'decisionNote',
|
|
type: 'textarea',
|
|
label: 'Nota da decisão',
|
|
maxLength: 2000,
|
|
access: {
|
|
create: canManageCampaignStaffField,
|
|
update: canManageCampaignStaffField,
|
|
},
|
|
},
|
|
{
|
|
name: 'decidedBy',
|
|
type: 'relationship',
|
|
relationTo: 'campaignUser',
|
|
label: 'Decidida por',
|
|
admin: {
|
|
readOnly: true,
|
|
},
|
|
access: {
|
|
create: canSetCampaignSystemField,
|
|
update: canSetCampaignSystemField,
|
|
},
|
|
},
|
|
{
|
|
name: 'decidedAt',
|
|
type: 'date',
|
|
label: 'Decidida em',
|
|
admin: {
|
|
readOnly: true,
|
|
},
|
|
access: {
|
|
create: canSetCampaignSystemField,
|
|
update: canSetCampaignSystemField,
|
|
},
|
|
},
|
|
{
|
|
name: 'cost',
|
|
type: 'number',
|
|
label: 'Custo estimado (R$)',
|
|
min: 0,
|
|
access: {
|
|
create: canManageCampaignStaffField,
|
|
read: canReadCampaignStaffField,
|
|
update: canManageCampaignStaffField,
|
|
},
|
|
admin: {
|
|
description: 'Controle interno de gastos. Não substitui a prestação de contas oficial.',
|
|
},
|
|
},
|
|
{
|
|
name: 'receipts',
|
|
type: 'upload',
|
|
relationTo: 'media',
|
|
label: 'Comprovantes',
|
|
hasMany: true,
|
|
access: {
|
|
create: canManageCampaignStaffField,
|
|
read: canReadCampaignStaffField,
|
|
update: canManageCampaignStaffField,
|
|
},
|
|
admin: {
|
|
description:
|
|
'Documentos fiscais podem conter CPF/CNPJ — acesso restrito ao staff. Não substitui o SPCE.',
|
|
},
|
|
},
|
|
{
|
|
name: 'statusHistory',
|
|
type: 'array',
|
|
label: 'Histórico de status',
|
|
access: {
|
|
read: canReadCampaignStaffField,
|
|
update: canSetCampaignSystemField,
|
|
},
|
|
admin: {
|
|
readOnly: true,
|
|
},
|
|
fields: [
|
|
{
|
|
name: 'status',
|
|
type: 'select',
|
|
label: 'Status',
|
|
required: true,
|
|
options: [...DEMAND_STATUS_OPTIONS],
|
|
},
|
|
{
|
|
name: 'note',
|
|
type: 'textarea',
|
|
label: 'Nota',
|
|
maxLength: 2000,
|
|
},
|
|
{
|
|
name: 'author',
|
|
type: 'relationship',
|
|
relationTo: 'campaignUser',
|
|
label: 'Autor',
|
|
},
|
|
{
|
|
name: 'createdAt',
|
|
type: 'date',
|
|
label: 'Registrado em',
|
|
},
|
|
],
|
|
},
|
|
{
|
|
name: 'createdBy',
|
|
type: 'relationship',
|
|
relationTo: 'campaignUser',
|
|
label: 'Criado por',
|
|
index: true,
|
|
admin: {
|
|
readOnly: true,
|
|
},
|
|
access: {
|
|
create: canSetCampaignSystemField,
|
|
update: canSetCampaignSystemField,
|
|
},
|
|
},
|
|
],
|
|
}
|