Enable in-place pipeline edits with calendar sync and timed publish cron.

Agency can edit title/copy on existing cards (optional RRSS sync); Dokploy runs pipeline-publish every 10 minutes with daily-sync as backup.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
4Ventures
2026-10-06 18:33:10 +02:00
parent ade2762b01
commit b4d86e1e28
4 changed files with 536 additions and 8 deletions

View File

@@ -9,10 +9,110 @@ import {
} from '@/lib/superhuman-docs';
import { syncAllClientifyTenants } from '@/lib/clientify-sync';
import { syncAllGhlTenants } from '@/lib/gohighlevel-sync';
import { serviceHeaders, supabaseUrl } from '@/lib/agency';
import {
mergePermalinkNotes,
publishPipelineItem,
type PipelinePublishRow,
} from '@/lib/meta-publish';
export const dynamic = 'force-dynamic';
export const maxDuration = 300;
const PIPELINE_SELECT =
'id,tenant_id,title,format,status,scheduled_at,channels,publish_status,publish_attempts,cover_path,cover_mime,slide_paths,caption,notes,meta_ig_media_id,meta_fb_post_id';
async function runDuePipelinePublish(limit = 5): Promise<Record<string, unknown>> {
const headers = serviceHeaders();
const base = supabaseUrl();
if (!headers || !base) {
return { ok: false, error: 'Service role required' };
}
const now = new Date().toISOString();
const url =
`${base}/rest/v1/creative_pipeline?status=eq.aprobado` +
`&scheduled_at=lte.${encodeURIComponent(now)}` +
`&publish_status=in.(idle,queued,failed)` +
`&select=${PIPELINE_SELECT}&order=scheduled_at.asc&limit=${limit}`;
const list = await fetch(url, { headers, cache: 'no-store' });
if (!list.ok) {
return { ok: false, error: (await list.text()).slice(0, 200) };
}
const due = (await list.json()) as (PipelinePublishRow & {
title: string;
notes?: string | null;
})[];
const results: { id: string; ok: boolean; detail: string }[] = [];
for (const item of due) {
if (!item.cover_path) {
results.push({ id: item.id, ok: false, detail: 'missing cover' });
continue;
}
await fetch(`${base}/rest/v1/creative_pipeline?id=eq.${item.id}`, {
method: 'PATCH',
headers: {
...headers,
'Content-Type': 'application/json',
Prefer: 'return=minimal',
},
body: JSON.stringify({
publish_status: 'publishing',
publish_attempts: (item.publish_attempts || 0) + 1,
publish_error: null,
updated_at: new Date().toISOString(),
}),
});
const result = await publishPipelineItem(item);
if (!result.ok) {
await fetch(`${base}/rest/v1/creative_pipeline?id=eq.${item.id}`, {
method: 'PATCH',
headers: {
...headers,
'Content-Type': 'application/json',
Prefer: 'return=minimal',
},
body: JSON.stringify({
publish_status: 'failed',
publish_error: result.error || 'Error Meta',
meta_ig_media_id: result.igMediaId || item.meta_ig_media_id || null,
meta_fb_post_id: result.fbPostId || item.meta_fb_post_id || null,
updated_at: new Date().toISOString(),
}),
});
results.push({
id: item.id,
ok: false,
detail: result.error || 'failed',
});
continue;
}
await fetch(`${base}/rest/v1/creative_pipeline?id=eq.${item.id}`, {
method: 'PATCH',
headers: {
...headers,
'Content-Type': 'application/json',
Prefer: 'return=minimal',
},
body: JSON.stringify({
publish_status: 'published',
publish_error: null,
published_at: new Date().toISOString(),
status: 'publicado',
meta_ig_media_id: result.igMediaId || null,
meta_fb_post_id: result.fbPostId || null,
notes: mergePermalinkNotes(
item.notes,
result.igPermalink,
result.fbPermalink
),
updated_at: new Date().toISOString(),
}),
});
results.push({ id: item.id, ok: true, detail: 'published' });
}
return { ok: true, due: due.length, results };
}
/**
* Master daily job: organic + ads + superhuman.
* Dokploy (daily ~06:00 UTC):
@@ -111,6 +211,16 @@ export async function GET(req: NextRequest) {
};
}
// 5) Pipeline Meta publish (safety net; prefer dedicated */10 cron)
try {
out.pipelinePublish = await runDuePipelinePublish(5);
} catch (e) {
out.pipelinePublish = {
ok: false,
error: e instanceof Error ? e.message : 'pipeline-publish failed',
};
}
const failed = ['organic', 'ads', 'superhuman', 'crm'].some(
(k) => (out[k] as { ok?: boolean } | undefined)?.ok === false
);

View File

@@ -397,6 +397,83 @@ export default function CreativePipelineBoard() {
}
}
/** Edit title/copy on an existing card; optionally sync RRSS calendar piece. */
async function saveContent(
id: string,
payload: {
title: string;
caption: string;
notes?: string | null;
syncCalendar: boolean;
calendarDate?: string | null;
calendarTime?: string | null;
}
) {
if (!isAgency) return;
setBusyId(id);
setErr(null);
try {
const target = items.find((x) => x.id === id) || previewItem;
if (
payload.syncCalendar &&
target?.calendar_piece_id &&
payload.calendarDate
) {
const calFmt = mapPipelineFormatToCalendar(target.format || 'post');
const calRes = await fetch('/api/calendar/pieces', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
pieceId: target.calendar_piece_id,
title: payload.title.trim(),
date: payload.calendarDate,
time: payload.calendarTime || '10:00',
format: calFmt.format,
kind: calFmt.kind,
body: payload.caption || undefined,
platform: 'instagram',
}),
});
const calData = await calRes.json();
if (!calRes.ok) {
setErr(calData.error || 'No se pudo actualizar el calendario RRSS');
return;
}
}
const sched =
payload.calendarDate
? scheduledAtFromPiece({
date: payload.calendarDate,
time: payload.calendarTime || '10:00',
})
: undefined;
const res = await fetch('/api/creative-pipeline', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
id,
title: payload.title.trim(),
caption: payload.caption || null,
notes: payload.notes ?? undefined,
...(sched !== undefined ? { scheduled_at: sched } : {}),
}),
});
const data = await res.json();
if (!res.ok) {
setErr(data.error || 'No se pudo guardar');
return;
}
if (previewItem && previewItem.id === id && data.item) {
setPreviewItem({ ...previewItem, ...data.item });
}
await load();
} finally {
setBusyId(null);
}
}
async function removeItem(id: string, alsoMeta = false) {
setBusyId(id);
setErr(null);
@@ -895,6 +972,7 @@ export default function CreativePipelineBoard() {
onClose={() => setPreviewItem(null)}
onStatus={(s) => setStatus(previewItem.id, s)}
onSaveSchedule={(payload) => saveSchedule(previewItem.id, payload)}
onSaveContent={(payload) => saveContent(previewItem.id, payload)}
onPublishNow={() => publishNow(previewItem.id)}
onDeleteMeta={() => deleteOnMeta(previewItem.id)}
/>
@@ -1198,6 +1276,7 @@ function DetailModal({
onClose,
onStatus,
onSaveSchedule,
onSaveContent,
onPublishNow,
onDeleteMeta,
}: {
@@ -1210,6 +1289,14 @@ function DetailModal({
scheduled_at: string | null;
channels: PublishChannel[];
}) => void;
onSaveContent: (payload: {
title: string;
caption: string;
notes?: string | null;
syncCalendar: boolean;
calendarDate?: string | null;
calendarTime?: string | null;
}) => void;
onPublishNow: () => void;
onDeleteMeta: () => void;
}) {
@@ -1225,13 +1312,37 @@ function DetailModal({
const [chFb, setChFb] = useState(
(item.channels || ['instagram', 'facebook']).includes('facebook')
);
const [editTitle, setEditTitle] = useState(item.title);
const [editCaption, setEditCaption] = useState(item.caption || '');
const [syncCal, setSyncCal] = useState(Boolean(item.calendar_piece_id));
const [editDate, setEditDate] = useState(
(item.scheduled_at || item.created_at || '').slice(0, 10)
);
const [editTime, setEditTime] = useState(() => {
if (!item.scheduled_at) return '10:00';
const d = new Date(item.scheduled_at);
if (Number.isNaN(d.getTime())) return '10:00';
return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
});
useEffect(() => {
setSchedLocal(toDatetimeLocalValue(item.scheduled_at));
const ch = item.channels || ['instagram', 'facebook'];
setChIg(ch.includes('instagram'));
setChFb(ch.includes('facebook'));
}, [item.id, item.scheduled_at, item.channels]);
setEditTitle(item.title);
setEditCaption(item.caption || '');
setSyncCal(Boolean(item.calendar_piece_id));
setEditDate((item.scheduled_at || item.created_at || '').slice(0, 10));
if (item.scheduled_at) {
const d = new Date(item.scheduled_at);
if (!Number.isNaN(d.getTime())) {
setEditTime(
`${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
);
}
}
}, [item.id, item.scheduled_at, item.channels, item.title, item.caption, item.calendar_piece_id, item.created_at]);
const activePath = allImages[activeIdx] || item.cover_path;
const currentUrl = mediaUrl(activePath);
@@ -1253,6 +1364,17 @@ function DetailModal({
});
}
function submitContent() {
if (!editTitle.trim()) return;
onSaveContent({
title: editTitle.trim(),
caption: editCaption,
syncCalendar: syncCal && Boolean(item.calendar_piece_id),
calendarDate: editDate || null,
calendarTime: editTime || '10:00',
});
}
return (
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-black/75 p-4 backdrop-blur-sm"
@@ -1356,10 +1478,32 @@ function DetailModal({
</div>
<div>
<h3 className="text-base font-bold text-gray-900 leading-snug">{item.title}</h3>
<p className="mt-1 text-xs text-gray-500">
{monthLabel(item.month)} {item.external_ref ? `· Ref: ${item.external_ref}` : ''}
</p>
{isAgency ? (
<div className="space-y-2">
<label className="block text-xs font-semibold text-gray-600">
Título
<input
value={editTitle}
onChange={(e) => setEditTitle(e.target.value)}
className="mt-1 w-full rounded-lg border border-gray-200 px-2 py-1.5 text-sm font-semibold text-gray-900"
/>
</label>
<p className="text-xs text-gray-500">
{monthLabel(item.month)}{' '}
{item.external_ref ? `· Ref: ${item.external_ref}` : ''}
</p>
</div>
) : (
<>
<h3 className="text-base font-bold text-gray-900 leading-snug">
{item.title}
</h3>
<p className="mt-1 text-xs text-gray-500">
{monthLabel(item.month)}{' '}
{item.external_ref ? `· Ref: ${item.external_ref}` : ''}
</p>
</>
)}
</div>
{igUrl && (
@@ -1375,14 +1519,74 @@ function DetailModal({
</a>
)}
{item.caption && (
{isAgency ? (
<div className="space-y-2">
<p className="text-xs font-semibold text-gray-700 uppercase tracking-wider">
Texto / Copy
</p>
<textarea
value={editCaption}
onChange={(e) => setEditCaption(e.target.value)}
rows={5}
className="w-full rounded-xl border border-gray-200 bg-white p-3 text-xs text-gray-800 leading-relaxed"
placeholder="Copy del anuncio"
/>
<div className="grid grid-cols-2 gap-2">
<label className="block text-[11px] text-gray-600">
Fecha plan
<input
type="date"
value={editDate}
onChange={(e) => setEditDate(e.target.value)}
className="mt-0.5 w-full rounded-lg border border-gray-200 px-2 py-1 text-xs"
/>
</label>
<label className="block text-[11px] text-gray-600">
Hora plan
<input
type="time"
value={editTime}
onChange={(e) => setEditTime(e.target.value)}
className="mt-0.5 w-full rounded-lg border border-gray-200 px-2 py-1 text-xs"
/>
</label>
</div>
{item.calendar_piece_id ? (
<label className="flex items-start gap-2 text-[11px] text-gray-700">
<input
type="checkbox"
className="mt-0.5"
checked={syncCal}
onChange={(e) => setSyncCal(e.target.checked)}
/>
<span>
Actualizar también la pieza enlazada en el calendario RRSS
</span>
</label>
) : (
<p className="text-[11px] text-gray-400">
Sin enlace a calendario — solo se guarda en el pipeline.
</p>
)}
<button
type="button"
disabled={busy || !editTitle.trim()}
onClick={submitContent}
className="w-full rounded-lg bg-gray-900 px-3 py-2 text-xs font-semibold text-white hover:bg-gray-800 disabled:opacity-60"
>
Guardar cambios
</button>
</div>
) : item.caption ? (
<div className="space-y-1">
<p className="text-xs font-semibold text-gray-700 uppercase tracking-wider">Texto / Copy</p>
<p className="text-xs font-semibold text-gray-700 uppercase tracking-wider">
Texto / Copy
</p>
<div className="rounded-xl border border-gray-200 bg-gray-50 p-3 text-xs text-gray-800 whitespace-pre-wrap leading-relaxed max-h-48 overflow-y-auto">
{item.caption}
</div>
</div>
)}
) : null}
{isAgency ? (
<div className="rounded-xl border border-sky-200 bg-sky-50/60 p-3 space-y-3">