db-ministerial/src/app/(frontend)/actions.ts

110 lines
3.0 KiB
TypeScript

'use server'
import { getPayload } from 'payload'
import { revalidatePath } from 'next/cache'
import config from '@/payload.config'
export type PastorUpdateInput = {
name: string
email?: string | null
telephone?: string[]
city?: string | null
state?: string | null
country?: string | null
inTelegram?: boolean
notes?: string | null
}
/** Crea un nuevo pastor desde el modal de creación del frontend. */
export async function createPastor(data: PastorUpdateInput) {
if (!data.name?.trim()) {
return { ok: false, error: 'El nombre es obligatorio.' }
}
const payload = await getPayload({ config: await config })
const doc = await payload.create({
collection: 'pastors',
data: {
name: data.name.trim(),
email: data.email || undefined,
telephone: (data.telephone ?? []).map((t) => t.trim()).filter(Boolean),
city: data.city || undefined,
state: data.state || undefined,
country: data.country ? data.country.trim().toUpperCase() : undefined,
inTelegram: Boolean(data.inTelegram),
notes: data.notes || undefined,
},
})
revalidatePath('/')
return { ok: true, id: doc.id }
}
/** Actualiza un pastor existente desde el modal de edición del frontend. */
export async function updatePastor(id: number, data: PastorUpdateInput) {
const payload = await getPayload({ config: await config })
await payload.update({
collection: 'pastors',
id,
data: {
name: data.name,
email: data.email || undefined,
telephone: (data.telephone ?? []).map((t) => t.trim()).filter(Boolean),
city: data.city || undefined,
state: data.state || undefined,
country: data.country ? data.country.trim().toUpperCase() : undefined,
inTelegram: Boolean(data.inTelegram),
notes: data.notes || undefined,
},
})
revalidatePath('/')
return { ok: true }
}
/**
* Sube una carta (PDF o Word) y la asocia a un pastor. El archivo se guarda en
* la colección de subidas `pastor-letters`, que valida los tipos de archivo
* permitidos, y luego se enlaza desde el campo `letter` del pastor.
*/
export async function uploadLetter(pastorId: number, formData: FormData) {
const file = formData.get('file')
if (!(file instanceof File) || file.size === 0) {
return { ok: false, error: 'No se proporcionó ningún archivo.' }
}
const payload = await getPayload({ config: await config })
const buffer = Buffer.from(await file.arrayBuffer())
try {
const letter = await payload.create({
collection: 'pastor-letters',
data: {},
file: {
data: buffer,
mimetype: file.type,
name: file.name,
size: file.size,
},
})
await payload.update({
collection: 'pastors',
id: pastorId,
data: { letter: letter.id },
})
} catch (err) {
return {
ok: false,
error:
err instanceof Error ? err.message : 'Error al subir. Solo se permiten archivos PDF o Word.',
}
}
revalidatePath('/')
return { ok: true }
}