Publish milestones per channel and add Instagram

Consent is bound to the channel it was given for: approving a post on X says
nothing about Instagram. Publishing state moves from the SocialMilestone row
into SocialMilestonePost, one row per channel, where a missing row means no
consent. The dialog asks per channel, shows the text each one will publish and
keeps a separate handle for each; Instagram captions end in hashtags because a
link there is not clickable.

Also fixes three problems in the existing X path:

- A QR code already past several thresholds produced one prompt per threshold,
  and since the post quotes the current scan count, every one of them would
  have published the same number. Only the highest threshold is announced now.
- Detection ran after every unique scan and re-read the QR code's full scan
  history just to hit skipDuplicates. Known milestones are filtered first.
- A failed post stayed failed forever because the consent dialog only opens
  once. The queue now retries three times on its own, spaces first attempts by
  SOCIAL_MILESTONE_MIN_GAP_HOURS, and Settings lists every milestone per
  channel with restart and revoke.

The worker no longer renders the card itself; it downloads the image the app
renders at /s/m/<token>/og, which also serves the new square and portrait
formats. Instagram publishing stays off until SOCIAL_MILESTONE_CHANNELS and
SOCIAL_WORKER_CHANNELS both name it.

Schema changes are manual SQL, see sql/2026-08-16_*.sql. Run both before
deploying this version.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-16 13:46:13 +02:00
parent 55c04761ce
commit eb932ebdaa
22 changed files with 1159 additions and 298 deletions

View File

@@ -10,6 +10,41 @@ import ChangePasswordModal from '@/components/settings/ChangePasswordModal';
type TabType = 'profile' | 'subscription';
type MilestonePost = {
channel: string;
status: string;
postUrl: string | null;
error: string | null;
postedAt: string | null;
};
type MilestoneHistoryItem = {
id: string;
qrTitle: string;
uniqueScans: number;
detectedAt: string;
promptStatus: string;
selfSharedAt: string | null;
shareUrl: string | null;
posts: MilestonePost[];
};
const CHANNEL_LABELS: Record<string, string> = { x: 'X', instagram: 'Instagram' };
function milestoneStateLabel(milestone: MilestoneHistoryItem) {
if (milestone.posts.some(post => post.status !== 'revoked')) return 'Approved for publishing';
if (milestone.selfSharedAt) return 'Shared by you';
if (milestone.promptStatus === 'declined') return 'Declined';
return 'Waiting for your decision';
}
function postStateLabel(post: MilestonePost) {
if (post.status === 'posted') return 'published';
if (post.status === 'failed') return 'publishing failed';
if (post.status === 'revoked') return 'revoked before publishing';
return 'queued';
}
export default function SettingsPage() {
const { fetchWithCsrf } = useCsrf();
const [activeTab, setActiveTab] = useState<TabType>('profile');
@@ -18,6 +53,8 @@ export default function SettingsPage() {
const [socialPromptsEnabled, setSocialPromptsEnabled] = useState(true);
const [socialTestResetAvailable, setSocialTestResetAvailable] = useState(false);
const [socialSaving, setSocialSaving] = useState(false);
const [milestones, setMilestones] = useState<MilestoneHistoryItem[]>([]);
const [milestoneBusy, setMilestoneBusy] = useState<string | null>(null);
// Profile states
const [name, setName] = useState('');
@@ -62,6 +99,12 @@ export default function SettingsPage() {
const data = await socialResponse.json();
setSocialPromptsEnabled(data.promptsEnabled !== false);
setSocialTestResetAvailable(data.testResetAvailable === true);
}
const historyResponse = await fetch('/api/social-milestones/history');
if (historyResponse.ok) {
const data = await historyResponse.json();
setMilestones(Array.isArray(data.milestones) ? data.milestones : []);
}
} catch (e) {
console.error('Failed to load user data:', e);
@@ -119,6 +162,30 @@ export default function SettingsPage() {
showToast(error instanceof Error ? error.message : 'Could not update milestone prompts', 'error');
} finally {
setSocialSaving(false);
}
};
const updateMilestone = async (id: string, action: 'retry' | 'revoke', channel: string) => {
setMilestoneBusy(`${id}:${channel}`);
try {
const response = await fetchWithCsrf(`/api/social-milestones/${id}`, {
method: 'PATCH',
body: JSON.stringify({ action, channel }),
});
const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Could not update this milestone');
setMilestones(current => current.map(milestone => milestone.id === id ? {
...milestone,
posts: milestone.posts.map(post => {
const next = (data.milestone?.posts || []).find((entry: MilestonePost) => entry.channel === post.channel);
return next ? { ...post, status: next.status, postUrl: next.postUrl, error: next.error } : post;
}),
} : milestone));
showToast(action === 'retry' ? 'Post queued again.' : 'Post revoked. Nothing will be published.', 'success');
} catch (error) {
showToast(error instanceof Error ? error.message : 'Could not update this milestone', 'error');
} finally {
setMilestoneBusy(null);
}
};
@@ -289,6 +356,52 @@ export default function SettingsPage() {
{socialPromptsEnabled ? 'Turn off' : 'Turn on'}
</Button>
</div>
{milestones.length > 0 && <div className="border-t border-gray-100 pt-4">
<h3 className="text-sm font-medium text-gray-900">Your milestones</h3>
<p className="mt-1 text-sm text-gray-500">Every scan milestone we detected and what happened to it.</p>
<ul className="mt-3 divide-y divide-gray-100">
{milestones.map(milestone => (
<li key={milestone.id} className="py-3">
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<div className="min-w-0">
<p className="truncate text-sm font-medium text-gray-900">{milestone.qrTitle}</p>
<p className="mt-0.5 text-xs text-gray-500">
{milestone.uniqueScans.toLocaleString('en-US')} unique scans · {new Date(milestone.detectedAt).toLocaleDateString('en-US')} · {milestoneStateLabel(milestone)}
</p>
</div>
{milestone.shareUrl && (
<a href={milestone.shareUrl} target="_blank" rel="noreferrer" className="shrink-0 text-sm font-medium text-blue-600 hover:underline">Open card</a>
)}
</div>
{/* One line per channel: consent, and everything that can be
withdrawn or restarted, is per channel. */}
{milestone.posts.map(post => (
<div key={post.channel} className="mt-2 flex flex-col gap-2 rounded-md bg-gray-50 px-3 py-2 sm:flex-row sm:items-center sm:justify-between">
<div className="min-w-0">
<p className="text-xs text-gray-600">
<span className="font-medium text-gray-900">{CHANNEL_LABELS[post.channel] || post.channel}</span> {postStateLabel(post)}
</p>
{post.status === 'failed' && post.error && (
<p className="mt-0.5 text-xs text-rose-600">{post.error}</p>
)}
</div>
<div className="flex shrink-0 flex-wrap items-center gap-2">
{post.postUrl && (
<a href={post.postUrl} target="_blank" rel="noreferrer" className="text-sm font-medium text-blue-600 hover:underline">View post</a>
)}
{post.status === 'failed' && (
<Button variant="outline" disabled={milestoneBusy === `${milestone.id}:${post.channel}`} onClick={() => updateMilestone(milestone.id, 'retry', post.channel)}>Try again</Button>
)}
{['approved', 'failed'].includes(post.status) && (
<Button variant="outline" disabled={milestoneBusy === `${milestone.id}:${post.channel}`} onClick={() => updateMilestone(milestone.id, 'revoke', post.channel)}>Cancel</Button>
)}
</div>
</div>
))}
</li>
))}
</ul>
</div>}
{socialTestResetAvailable && <div className="border-t border-gray-100 pt-4">
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<p className="text-sm text-gray-500">Test environment: reopen the latest milestone and clear its publishing state.</p>