teqo-backup/src/collections/AllocationDecision.ts
Francisco Ignácio Fontoura Solla c7001b75f0 E14: engagement levels N0-N4 and the first allocationDecision writer.
`municipality.engagementLevel` (staff-only, no default) records what the
campaign decided to invest in a município, next to the E8/E10 metrics that
describe what it knows. Moving it is a reallocation decision, so only
unrestricted staff may, every move carries a rationale plus the signals that
would reverse it, and the write files an `allocationDecision` in the same
transaction under an advisory lock taken before the current level is read —
otherwise the snapshot's `from` is a guess. The enum gains `movimento`: a level
move is neither `aceita` nor `descarta`.

No backfill. Null is "Sem nível", and filtering by it is the triage queue.
That is also why the list sorts `nivel` in memory rather than in the query:
Postgres puts NULLs first on DESC, so a native sort would open "N4 primeiro"
on a page of municípios nobody has decided about yet. The filter stays native.

The hysteresis rules from research §6.8 are pure and client-safe, so the
Popover explains a block before submitting and the server re-runs them anyway;
a blocked move answers 409 with typed violations and the override is recorded
with exactly the rules it contradicted.
2026-07-27 21:19:33 -03:00

151 lines
3.8 KiB
TypeScript

import { Buffer } from 'node:buffer'
import type {
CollectionBeforeChangeHook,
CollectionBeforeValidateHook,
CollectionConfig,
} from 'payload'
import { APIError } from 'payload'
import {
canCreateAllocationDecision,
canMutateAllocationDecision,
canReadAllocationDecision,
canSetCampaignSystemField,
} from '@/utilities/campaignAccess'
const MAX_SERIALIZED_SNAPSHOT_BYTES = 16_000
const validateAllocationDecision: CollectionBeforeValidateHook = ({
data,
operation,
originalDoc,
}) => {
if (!data) return data
const nextData = operation === 'update' ? { ...originalDoc, ...data } : data
if (
nextData.outcome === 'descarta' &&
(typeof nextData.alternativeReading !== 'string' || !nextData.alternativeReading.trim())
) {
throw new APIError('Informe a leitura alternativa ao descartar a sugestão.', 400)
}
try {
const serializedSnapshot = JSON.stringify(nextData.snapshot)
if (
typeof nextData.snapshot !== 'object' ||
nextData.snapshot === null ||
Array.isArray(nextData.snapshot) ||
Buffer.byteLength(serializedSnapshot, 'utf8') > MAX_SERIALIZED_SNAPSHOT_BYTES
) {
throw new APIError('O recorte da decisão está grande demais.', 400)
}
} catch (error) {
if (error instanceof APIError) throw error
throw new APIError('O recorte da decisão é inválido.', 400)
}
return data
}
const deriveDecisionAuthor: CollectionBeforeChangeHook = ({ data, operation, req }) => {
if (operation === 'create' && req.user?.collection === 'campaignUser') {
data.decidedBy = req.user.id
}
return data
}
export const AllocationDecision: CollectionConfig = {
slug: 'allocationDecision',
labels: {
singular: 'Decisão de alocação',
plural: 'Decisões de alocação',
},
admin: {
group: 'Campanha',
hidden: true,
useAsTitle: 'patternId',
},
access: {
create: canCreateAllocationDecision,
read: canReadAllocationDecision,
update: canMutateAllocationDecision,
delete: canMutateAllocationDecision,
},
hooks: {
beforeValidate: [validateAllocationDecision],
beforeChange: [deriveDecisionAuthor],
},
fields: [
{
name: 'municipality',
type: 'relationship',
relationTo: 'municipality',
label: 'Município',
required: true,
index: true,
},
{
name: 'patternId',
type: 'text',
label: 'Padrão avaliado',
required: true,
maxLength: 120,
index: true,
},
{
name: 'outcome',
type: 'select',
label: 'Decisão',
required: true,
// `aceita`/`descarta` is the triage of a SUGGESTED pattern (E11). A level
// movement (E14) is neither — it is a decision taken outright — so it
// gets its own value instead of masquerading as an acceptance.
options: [
{ label: 'Aceita', value: 'aceita' },
{ label: 'Descarta', value: 'descarta' },
{ label: 'Movimento', value: 'movimento' },
],
},
{
name: 'rationale',
type: 'textarea',
label: 'Justificativa',
required: true,
maxLength: 2000,
},
{
name: 'alternativeReading',
type: 'textarea',
label: 'Leitura alternativa',
maxLength: 2000,
admin: {
condition: (_, siblingData) => siblingData.outcome === 'descarta',
},
},
{
name: 'snapshot',
type: 'json',
label: 'Recorte da decisão',
required: true,
admin: {
description: 'Somente os números e classificações usados no momento da decisão.',
},
},
{
name: 'decidedBy',
type: 'relationship',
relationTo: 'campaignUser',
label: 'Decidido por',
index: true,
admin: {
readOnly: true,
},
access: {
create: canSetCampaignSystemField,
update: canSetCampaignSystemField,
},
},
],
}