Add creative image upload to the new pipeline piece form.

Agency can pick cover (and carousel slides) when creating a piece instead of only after the card exists.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
4Ventures
2026-10-07 12:14:14 +02:00
parent b4d86e1e28
commit 5b895d830b

View File

@@ -153,11 +153,63 @@ export default function CreativePipelineBoard() {
const [newDate, setNewDate] = useState(''); const [newDate, setNewDate] = useState('');
const [newTime, setNewTime] = useState('10:00'); const [newTime, setNewTime] = useState('10:00');
const [syncCalendar, setSyncCalendar] = useState(true); const [syncCalendar, setSyncCalendar] = useState(true);
const [coverFile, setCoverFile] = useState<File | null>(null);
const [coverPreview, setCoverPreview] = useState<string | null>(null);
const [slideFiles, setSlideFiles] = useState<File[]>([]);
const [slidePreviews, setSlidePreviews] = useState<string[]>([]);
const [creating, setCreating] = useState(false);
const [selectedMonth, setSelectedMonth] = useState<string>('all'); const [selectedMonth, setSelectedMonth] = useState<string>('all');
const [selectedFormat, setSelectedFormat] = useState<string>('all'); const [selectedFormat, setSelectedFormat] = useState<string>('all');
const [previewItem, setPreviewItem] = useState<PipelineItem | null>(null); const [previewItem, setPreviewItem] = useState<PipelineItem | null>(null);
const [viewMode, setViewMode] = useState<'produccion' | 'tablon'>('produccion'); const [viewMode, setViewMode] = useState<'produccion' | 'tablon'>('produccion');
function clearMediaSelection() {
if (coverPreview) URL.revokeObjectURL(coverPreview);
for (const u of slidePreviews) URL.revokeObjectURL(u);
setCoverFile(null);
setCoverPreview(null);
setSlideFiles([]);
setSlidePreviews([]);
}
function pickCover(file: File | null) {
if (coverPreview) URL.revokeObjectURL(coverPreview);
if (!file) {
setCoverFile(null);
setCoverPreview(null);
return;
}
setCoverFile(file);
setCoverPreview(URL.createObjectURL(file));
}
function pickSlides(files: FileList | null) {
for (const u of slidePreviews) URL.revokeObjectURL(u);
const list = files ? Array.from(files).slice(0, 9) : [];
setSlideFiles(list);
setSlidePreviews(list.map((f) => URL.createObjectURL(f)));
}
async function uploadFileToItem(
itemId: string,
file: File,
slot: 'cover' | 'slide',
index = 0
): Promise<string | null> {
const fd = new FormData();
fd.append('file', file);
fd.append('itemId', itemId);
fd.append('slot', slot);
fd.append('index', String(index));
const res = await fetch('/api/creative-pipeline/upload', {
method: 'POST',
body: fd,
});
const data = await res.json();
if (!res.ok) return data.error || 'Error al subir imagen';
return null;
}
async function load() { async function load() {
setLoading(true); setLoading(true);
try { try {
@@ -200,6 +252,7 @@ export default function CreativePipelineBoard() {
setNewMonth(''); setNewMonth('');
setNewDate(''); setNewDate('');
setNewTime('10:00'); setNewTime('10:00');
clearMediaSelection();
return; return;
} }
const p = calPieces.find((x) => x.id === id); const p = calPieces.find((x) => x.id === id);
@@ -227,6 +280,7 @@ export default function CreativePipelineBoard() {
setNewDate(''); setNewDate('');
setNewTime('10:00'); setNewTime('10:00');
setSyncCalendar(true); setSyncCalendar(true);
clearMediaSelection();
setShowForm(false); setShowForm(false);
} }
@@ -283,65 +337,102 @@ export default function CreativePipelineBoard() {
e.preventDefault(); e.preventDefault();
if (!newTitle.trim()) return; if (!newTitle.trim()) return;
setErr(null); setErr(null);
setCreating(true);
let calendarPieceId: string | null = try {
calPick !== '__new__' ? calPick : null; let calendarPieceId: string | null =
calPick !== '__new__' ? calPick : null;
if (syncCalendar) { if (syncCalendar) {
const date = const date =
newDate || newDate ||
(newMonth ? `${newMonth}-01` : new Date().toISOString().slice(0, 10)); (newMonth ? `${newMonth}-01` : new Date().toISOString().slice(0, 10));
const calFmt = mapPipelineFormatToCalendar(newFormat); const calFmt = mapPipelineFormatToCalendar(newFormat);
const calRes = await fetch('/api/calendar/pieces', { const calRes = await fetch('/api/calendar/pieces', {
method: 'PATCH', method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
pieceId: calendarPieceId,
title: newTitle.trim(),
date,
time: newTime || '10:00',
format: calFmt.format,
kind: calFmt.kind,
hook: newHook || undefined,
body: newCaption || undefined,
pillar: newPillar || undefined,
platform: 'instagram',
}),
});
const calData = await calRes.json();
if (!calRes.ok) {
setErr(calData.error || 'No se pudo guardar en el calendario RRSS');
return;
}
calendarPieceId = calData.piece?.id || calendarPieceId;
void loadCalendarPieces();
}
const sched = newDate
? scheduledAtFromPiece({ date: newDate, time: newTime })
: null;
const res = await fetch('/api/creative-pipeline', {
method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ body: JSON.stringify({
pieceId: calendarPieceId,
title: newTitle.trim(), title: newTitle.trim(),
date, format: newFormat,
time: newTime || '10:00', month: newMonth || (newDate ? newDate.slice(0, 7) : null),
format: calFmt.format, caption: newCaption || null,
kind: calFmt.kind, notes: newPillar ? `Pilar: ${newPillar}` : null,
hook: newHook || undefined, calendar_piece_id: calendarPieceId,
body: newCaption || undefined, scheduled_at: sched,
pillar: newPillar || undefined, channels: ['instagram', 'facebook'],
platform: 'instagram',
}), }),
}); });
const calData = await calRes.json(); const data = await res.json();
if (!calRes.ok) { if (!res.ok) {
setErr(calData.error || 'No se pudo guardar en el calendario RRSS'); setErr(data.error || 'Error al crear');
return; return;
} }
calendarPieceId = calData.piece?.id || calendarPieceId;
void loadCalendarPieces();
}
const sched = newDate const newId = data.item?.id as string | undefined;
? scheduledAtFromPiece({ date: newDate, time: newTime }) if (newId && coverFile) {
: null; const upErr = await uploadFileToItem(newId, coverFile, 'cover', 0);
if (upErr) {
setErr(
`Pieza creada, pero falló la portada: ${upErr}. Puedes subirla desde la tarjeta.`
);
resetForm();
await load();
return;
}
}
if (newId && newFormat === 'carrusel' && slideFiles.length) {
for (let i = 0; i < slideFiles.length; i++) {
const upErr = await uploadFileToItem(
newId,
slideFiles[i],
'slide',
i
);
if (upErr) {
setErr(
`Pieza creada; error en slide ${i + 1}: ${upErr}. Completa el resto en la tarjeta.`
);
resetForm();
await load();
return;
}
}
}
const res = await fetch('/api/creative-pipeline', { resetForm();
method: 'POST', await load();
headers: { 'Content-Type': 'application/json' }, } finally {
body: JSON.stringify({ setCreating(false);
title: newTitle.trim(),
format: newFormat,
month: newMonth || (newDate ? newDate.slice(0, 7) : null),
caption: newCaption || null,
notes: newPillar ? `Pilar: ${newPillar}` : null,
calendar_piece_id: calendarPieceId,
scheduled_at: sched,
channels: ['instagram', 'facebook'],
}),
});
const data = await res.json();
if (!res.ok) {
setErr(data.error || 'Error al crear');
return;
} }
resetForm();
await load();
} }
async function setStatus(id: string, status: string) { async function setStatus(id: string, status: string) {
@@ -847,6 +938,92 @@ export default function CreativePipelineBoard() {
placeholder="Texto completo del anuncio" placeholder="Texto completo del anuncio"
/> />
</div> </div>
<div className="sm:col-span-2 lg:col-span-3">
<label className="block text-xs font-semibold text-gray-700">
Creativo / imagen
</label>
<p className="mt-0.5 text-[11px] text-gray-500">
Sube la portada aquí (jpg/png/webp). En carrusel puedes añadir
slides extra.
</p>
<div className="mt-2 flex flex-wrap items-start gap-4">
<label className="relative flex h-36 w-28 cursor-pointer flex-col items-center justify-center overflow-hidden rounded-xl border-2 border-dashed border-gray-300 bg-gray-50 hover:border-brand-500 hover:bg-brand-50/40">
{coverPreview ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={coverPreview}
alt="Portada"
className="h-full w-full object-cover"
/>
) : (
<>
<ImagePlus className="h-7 w-7 text-gray-400" />
<span className="mt-1 px-2 text-center text-[10px] font-medium text-gray-500">
Portada
</span>
</>
)}
<input
type="file"
accept="image/jpeg,image/png,image/webp"
className="absolute inset-0 cursor-pointer opacity-0"
onChange={(e) =>
pickCover(e.target.files?.[0] || null)
}
/>
</label>
{coverFile ? (
<div className="flex min-w-0 flex-1 flex-col gap-1 pt-1">
<p className="truncate text-xs font-medium text-gray-800">
{coverFile.name}
</p>
<p className="text-[11px] text-gray-500">
{(coverFile.size / 1024).toFixed(0)} KB
</p>
<button
type="button"
onClick={() => pickCover(null)}
className="w-fit text-xs font-medium text-red-600 hover:underline"
>
Quitar portada
</button>
</div>
) : null}
</div>
{newFormat === 'carrusel' ? (
<div className="mt-3">
<label className="block text-xs font-medium text-gray-600">
Slides del carrusel (opcionales)
</label>
<input
type="file"
accept="image/jpeg,image/png,image/webp"
multiple
className="mt-1 block w-full text-xs text-gray-600 file:mr-3 file:rounded-lg file:border-0 file:bg-gray-900 file:px-3 file:py-1.5 file:text-xs file:font-medium file:text-white hover:file:bg-gray-800"
onChange={(e) => pickSlides(e.target.files)}
/>
{slidePreviews.length > 0 ? (
<div className="mt-2 flex flex-wrap gap-2">
{slidePreviews.map((src, i) => (
<div
key={i}
className="relative h-16 w-12 overflow-hidden rounded-lg border border-gray-200"
>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={src}
alt={`Slide ${i + 1}`}
className="h-full w-full object-cover"
/>
</div>
))}
</div>
) : null}
</div>
) : null}
</div>
</div> </div>
<label className="flex items-start gap-2 text-xs text-gray-700"> <label className="flex items-start gap-2 text-xs text-gray-700">
@@ -866,16 +1043,22 @@ export default function CreativePipelineBoard() {
<div className="flex flex-wrap gap-2"> <div className="flex flex-wrap gap-2">
<button <button
type="submit" type="submit"
className="rounded-lg bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:bg-gray-800" disabled={creating}
className="rounded-lg bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:bg-gray-800 disabled:opacity-60"
> >
{calPick === '__new__' {creating
? 'Crear en pipeline' ? coverFile
: 'Añadir al pipeline (desde calendario)'} ? 'Creando y subiendo creativo…'
: 'Creando…'
: calPick === '__new__'
? 'Crear en pipeline'
: 'Añadir al pipeline (desde calendario)'}
</button> </button>
<button <button
type="button" type="button"
disabled={creating}
onClick={resetForm} onClick={resetForm}
className="rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-medium text-gray-700" className="rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-medium text-gray-700 disabled:opacity-60"
> >
Cancelar Cancelar
</button> </button>