feat(clips): auto-fill publish schedule from a global start date
All checks were successful
CI / unit (push) Successful in 48s
CI / backend-e2e (push) Successful in 1m24s
CI / dashboard-e2e (push) Successful in 2m30s

Add a SCHEDULE START date picker to the results panel. When set, each
clip's post modal auto-fills its date/time from the clip's virality rank
(rank 1 = most viral): odd ranks on the picked date, even ranks the next
day, sharing the 6pm / 9pm / 1pm slots and repeating three slots per day
forward. Scheduling is switched on so the suggestion is visible up front.

Mapping lives in dashboard/src/lib/schedule.js; covered by a Playwright
spec (schedule-autofill).
This commit is contained in:
pedro-bento 2026-10-16 21:14:27 +01:00
parent c7f922de32
commit 26b05ab56c
4 changed files with 167 additions and 8 deletions

View file

@ -0,0 +1,53 @@
// Global schedule start date (results header) auto-fills each clip's post modal
// date/time from that clip's VIRALITY RANK (rank 1 = most viral = top card).
//
// The mocked session clips are:
// clip index 0 "First viral clip" score 91 -> rank 1
// clip index 1 "Second viral clip" score 77 -> rank 2
// Per the agreed cadence (odd rank on the picked date, even rank the next day,
// shared time cycles 18:00 -> 21:00 -> 13:00):
// rank 1 -> start date @ 18:00
// rank 2 -> start date + 1 day @ 18:00
import { test, expect } from '@playwright/test';
import { openApp, completedSession } from '../fixtures/app.js';
const START = '2030-01-02';
const seed = {
session: completedSession(),
postizUrl: 'http://postiz.e2e.local',
postizKey: 'postiz-e2e-key',
};
test.describe('global schedule auto-fill', () => {
test('prefills each clip post time from its virality rank', async ({ page }) => {
await openApp(page, { seed });
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
// Pick the global start date in the results header.
await page.getByTestId('schedule-start-date').fill(START);
// Rank 1 (top card): start date @ 18:00, scheduling auto-enabled so the
// prefilled time is visible.
await page.getByRole('button', { name: 'post', exact: true }).nth(0).click();
let dialog = page.getByRole('dialog');
await expect(dialog.getByLabel('date', { exact: true })).toHaveValue(START);
await expect(dialog.getByLabel('time (HH:MM)', { exact: true })).toHaveValue('18:00');
await expect(dialog.getByRole('checkbox', { name: /schedule post/i })).toBeChecked();
await dialog.getByRole('button', { name: 'close' }).click();
// Rank 2: next day, same first time slot.
await page.getByRole('button', { name: 'post', exact: true }).nth(1).click();
dialog = page.getByRole('dialog');
await expect(dialog.getByLabel('date', { exact: true })).toHaveValue('2030-01-03');
await expect(dialog.getByLabel('time (HH:MM)', { exact: true })).toHaveValue('18:00');
});
test('with no start date the schedule stays off', async ({ page }) => {
await openApp(page, { seed });
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
await page.getByRole('button', { name: 'post', exact: true }).nth(0).click();
const dialog = page.getByRole('dialog');
await expect(dialog.getByRole('checkbox', { name: /schedule post/i })).not.toBeChecked();
});
});

View file

@ -14,6 +14,7 @@ import Modal from './components/ui/Modal';
import { useAuth } from './contexts/AuthContext';
import { apiFetch } from './lib/api';
import { track } from './lib/analytics';
import { scheduleForRank } from './lib/schedule';
// Enhanced "Encryption" using XOR + Base64 with a Salt
// This is better than plain Base64 but still client-side.
@ -199,6 +200,14 @@ const readableError = (raw) => {
// already purged server-side fails gracefully and clears the saved session.
const SESSION_MAX_AGE = 86400000; // 24 hours
// Today as YYYY-MM-DD in the user's own timezone, for the schedule-start date
// input's `min`. Built from local parts (not toISOString, which would shift the
// day across the UTC boundary for users west of Greenwich).
const todayInputValue = () => {
const n = new Date();
return `${n.getFullYear()}-${String(n.getMonth() + 1).padStart(2, '0')}-${String(n.getDate()).padStart(2, '0')}`;
};
// Mock polling function
const pollJob = async (jobId) => {
const res = await apiFetch(`/api/status/${jobId}`);
@ -238,6 +247,12 @@ function App() {
const [jobId, setJobId] = useState(null);
const [status, setStatus] = useState('idle'); // idle, processing, complete, error
const [results, setResults] = useState(null);
// Global publish start date for the whole results panel. When set, each clip's
// modal auto-fills its post date/time from this date and the clip's virality
// rank (rank 1 = most viral = first card). Empty means the feature is off.
const [scheduleStartDate, setScheduleStartDate] = useState(() => {
try { return localStorage.getItem('cw_schedule_start') || ''; } catch (_) { return ''; }
});
// Best clips first. The backend hands them back in transcript order, which
// buries the strongest one wherever it happens to fall in the video — and
// the first card is the one people actually watch and publish.
@ -259,6 +274,14 @@ function App() {
return sb - sa || a.index - b.index;
});
}, [results]);
// One suggested publish slot per virality rank, taken from the shared start
// date. Memoized so a card's `suggestedSchedule` keeps a stable identity
// across unrelated re-renders — otherwise the modal-open reset (which the
// card keys off this prop) would clobber a date/time the user just picked.
const suggestedSchedules = useMemo(
() => rankedClips.map((_, rank) => scheduleForRank(scheduleStartDate, rank + 1)),
[rankedClips, scheduleStartDate]
);
// Bulk subtitles: apply one style to every clip of the job (triggered from
// within a clip's subtitle modal via "apply to all").
const [bulkSub, setBulkSub] = useState({ running: false, current: 0, total: 0, errors: 0 });
@ -464,6 +487,13 @@ function App() {
} catch (_) { /* ignore */ }
}, [postizUrl]);
useEffect(() => {
try {
if (scheduleStartDate) localStorage.setItem('cw_schedule_start', scheduleStartDate);
else localStorage.removeItem('cw_schedule_start');
} catch (_) { /* ignore */ }
}, [scheduleStartDate]);
useEffect(() => {
if (postizKey && postizUrl && postizChannels.length === 0) {
fetchPostizChannels({ silent: true });
@ -1360,7 +1390,23 @@ function App() {
)}
</h2>
{results?.clips?.length > 0 && status === 'complete' && (
<div className="flex flex-col sm:flex-row sm:justify-end items-stretch sm:items-center gap-2">
<div className="flex flex-col sm:flex-row sm:items-end sm:justify-between gap-2">
<div className="flex flex-col gap-1">
<div className="flex items-center gap-2">
<label htmlFor="schedule-start-date" className="eyebrow whitespace-nowrap">SCHEDULE START</label>
<input
id="schedule-start-date"
type="date"
value={scheduleStartDate}
onChange={(e) => setScheduleStartDate(e.target.value)}
min={todayInputValue()}
aria-label="schedule start date"
data-testid="schedule-start-date"
className="input-field w-auto py-1.5 text-xs [color-scheme:dark]"
/>
</div>
<p className="text-xs text-muted">clips fill in by virality rank — 6pm, 9pm, 1pm</p>
</div>
<button
onClick={handleDownloadAll}
disabled={downloadingAll}
@ -1433,12 +1479,13 @@ function App() {
<div className="flex-1 overflow-y-auto custom-scrollbar p-1">
{results && results.clips && results.clips.length > 0 ? (
<div className={`grid gap-4 pb-10 ${status === 'complete' ? 'grid-cols-[repeat(auto-fill,minmax(min(100%,600px),1fr))]' : 'grid-cols-1'}`}>
{rankedClips.map(({ clip, index: i }) => (
{rankedClips.map(({ clip, index: i }, rank) => (
<ResultCard
key={`${jobId}-${i}-${clip.video_url || ''}`}
clip={clip}
index={i}
jobId={jobId}
suggestedSchedule={suggestedSchedules[rank] ?? null}
onEditClip={(index) => setEditingClip(index)}
onReframeClip={(index) => setReframingClip(index)}
postizKey={postizKey}

View file

@ -77,7 +77,7 @@ function formatDuration(clip) {
return `${String(Math.floor(secs / 60)).padStart(2, '0')}:${String(secs % 60).padStart(2, '0')}`;
}
export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, geminiApiKey, onPlay, onPause, onBulkSubtitle, clipCount = 1, bulkProgress, onConnectSocials, onEditClip = null, onReframeClip = null }) {
export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, geminiApiKey, onPlay, onPause, onBulkSubtitle, clipCount = 1, bulkProgress, onConnectSocials, onEditClip = null, onReframeClip = null, suggestedSchedule = null }) {
const [showModal, setShowModal] = useState(false);
// The "why" line is clamped to two lines so cards in a row stay level;
// when it overflows, a hover (desktop) or tap (touch) shows the whole
@ -319,17 +319,20 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g
}, [showModal, postizKey, postizUrl]);
// Reset the form each time the modal opens; the effect above also reloads
// the channel list and reselects every enabled channel.
// the channel list and reselects every enabled channel. When the results
// panel has a global schedule start date, the post is prefilled with this
// clip's slot for its virality rank and scheduling is switched on, so the
// suggested time is visible up front (the user can uncheck to post now).
useEffect(() => {
if (showModal) {
setPostTitle(clip.video_title_for_youtube_short || "Viral Short");
setPostDescription(clip.video_description_for_instagram || clip.video_description_for_tiktok || "");
setIsScheduling(false);
setScheduleDate("");
setScheduleTime("");
setIsScheduling(!!suggestedSchedule);
setScheduleDate(suggestedSchedule?.date ?? "");
setScheduleTime(suggestedSchedule?.time ?? "");
setPostResult(null);
}
}, [showModal, clip]);
}, [showModal, clip, suggestedSchedule]);
const handleAutoEdit = async () => {
setIsEditing(true);
@ -1092,6 +1095,9 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g
/>
</div>
<p className="text-xs text-muted mt-1.5">pick a day and a time, in your local timezone</p>
{suggestedSchedule && (
<p className="text-xs text-muted mt-1">auto-filled from the schedule start date — change it freely</p>
)}
</div>
)}
</div>

View file

@ -0,0 +1,53 @@
// Global publish-date scheduling.
//
// Given one start date chosen by the user and a clip's virality RANK (1-based,
// rank 1 = most viral — the order the results are presented in), produce the
// concrete local date/time that clip should be posted at.
//
// The cadence posts three clips a day at 18:00 (6pm), 21:00 (9pm) and 13:00
// (1pm). Ranks are taken in pairs: the odd rank of each pair lands on one day
// and the even rank of the same pair the next day, at the pair's shared time.
//
// rank 1 -> day 0 @ 18:00 rank 2 -> day 1 @ 18:00
// rank 3 -> day 0 @ 21:00 rank 4 -> day 1 @ 21:00
// rank 5 -> day 0 @ 13:00 rank 6 -> day 1 @ 13:00
// rank 7 -> day 2 @ 18:00 rank 8 -> day 3 @ 18:00
// rank 9 -> day 2 @ 21:00 rank 10 -> day 3 @ 21:00
// ...
//
// i.e. every three pairs (six clips) the pair of day-blocks advances by two
// days and the time cycles back to 18:00.
// The three posting times, in the order they are handed to pairs.
const SLOT_TIMES = ['18:00', '21:00', '13:00'];
const pad2 = (n) => String(n).padStart(2, '0');
// Shift a 'YYYY-MM-DD' string by `days`, built from LOCAL date parts so it never
// crosses the UTC day boundary the way `new Date(...).toISOString()` would for
// users west of Greenwich. Returns null when the input is not a plain date.
export function addDays(dateStr, days) {
const m = String(dateStr || '').match(/^(\d{4})-(\d{2})-(\d{2})$/);
if (!m) return null;
const d = new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
d.setDate(d.getDate() + Number(days));
return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
}
// rank: 1-based position in the virality-ordered results.
// Returns { date: 'YYYY-MM-DD', time: 'HH:MM' } in the user's local timezone,
// or null when there is no start date / no valid rank.
export function scheduleForRank(startDate, rank) {
if (!startDate) return null;
const r = Number(rank);
if (!Number.isInteger(r) || r < 1) return null;
const pairIndex = Math.floor((r - 1) / 2); // 0 for ranks 1-2, 1 for 3-4, …
const time = SLOT_TIMES[pairIndex % 3];
// Every three pairs (6 clips) move the two day-blocks forward by two days.
const dayOffset = Math.floor(pairIndex / 3) * 2 + ((r - 1) % 2);
const date = addDays(startDate, dayOffset);
if (!date) return null;
return { date, time };
}