ReviewOS

also looking at this

stacks/postline

UI polish, real queue + scheduling, Bluesky threads, live analytics, blog target

#8
Merged glennmichael123 wants to merge feat/ui-polish into main
54 files +2036 -589
app/Services/Social/QueueService.tsadded+235-0
Changes to app/Services/Social/QueueService.ts
@@ -0,0 +1,235 @@
1import type { CrosspostTargetResult, SocialProvider } from '../../Support/Social/types'
2import { db } from '@stacksjs/database'
3import { env } from '@stacksjs/env'
4import { crosspost, crosspostProviders } from './CrosspostService'
5import { ensureAccount, now, uuid } from './support'
6
7const database = db as any
8
9/** Post statuses a user may still act on (publish now, delete). */
10const ACTIONABLE = new Set(['draft', 'scheduled', 'failed'])
11
12export interface QueueTargetView {
13 provider: SocialProvider
14 status: string
15 remoteUri: string | null
16 failureReason: string | null
17}
18
19export interface QueueItemView {
20 id: number
21 title: string | null
22 body: string
23 status: string
24 scheduledAt: string | null
25 publishedAt: string | null
26 createdAt: string
27 providers: QueueTargetView[]
28}
29
30export interface SaveQueueInput {
31 text: string
32 providers: SocialProvider[]
33 /** UTC `YYYY-MM-DD HH:MM:SS`; omitted → saved as a draft. */
34 scheduledAt?: string | null
35}
36
37export class QueueService {
38 /**
39 * Persist a post without publishing it. With `scheduledAt` the post is
40 * queued (`scheduled`) and picked up by the PublishScheduledPosts job when
41 * due; without it the post is stored as a `draft`. One placeholder
42 * `post_targets` row per provider records where the post should go — the
43 * real result rows replace them at publish time.
44 */
45 async save(input: SaveQueueInput): Promise<{ postId: number, status: 'draft' | 'scheduled', scheduledAt: string | null }> {
46 const body = input.text.trim()
47 if (!body)
48 throw new Error('Post text is required.')
49
50 const available = new Set<string>(crosspostProviders())
51 const providers = input.providers.filter(provider => available.has(provider))
52 if (providers.length === 0)
53 throw new Error('Select at least one connected provider.')
54
55 const scheduledAt = input.scheduledAt?.trim() || null
56 if (scheduledAt) {
57 if (!/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(scheduledAt))
58 throw new Error('Scheduled time must be a UTC YYYY-MM-DD HH:MM:SS timestamp.')
59 if (scheduledAt <= now())
60 throw new Error('Scheduled time must be in the future.')
61 }
62
63 const status = scheduledAt ? 'scheduled' as const : 'draft' as const
64 const accountId = await ensureAccount()
65 const postUuid = uuid()
66 const createdAt = now()
67
68 await database.insertInto('posts').values({
69 uuid: postUuid,
70 title: body.slice(0, 80),
71 body,
72 status,
73 scheduled_at: scheduledAt,
74 timezone: env.TZ || 'America/Los_Angeles',
75 source: 'composer',
76 account_id: accountId,
77 created_at: createdAt,
78 updated_at: createdAt,
79 }).execute()
80
81 const post = await database
82 .selectFrom('posts')
83 .select(['id'])
84 .where('uuid', '=', postUuid)
85 .executeTakeFirstOrThrow()
86
87 for (const provider of providers) {
88 await database.insertInto('post_targets').values({
89 uuid: uuid(),
90 provider,
91 status,
92 scheduled_at: scheduledAt,
93 post_id: post.id,
94 created_at: createdAt,
95 updated_at: createdAt,
96 }).execute()
97 }
98
99 return { postId: Number(post.id), status, scheduledAt }
100 }
101
102 /** Recent posts with their per-provider targets, newest first. */
103 async list(limit = 50): Promise<QueueItemView[]> {
104 const posts = await database
105 .selectFrom('posts')
106 .selectAll()
107 .where('status', '!=', 'archived')
108 .orderBy('created_at', 'desc')
109 .limit(limit)
110 .execute()
111
112 if (posts.length === 0)
113 return []
114
115 const targets = await database
116 .selectFrom('post_targets')
117 .selectAll()
118 .where('post_id', 'in', posts.map((post: any) => post.id))
119 .execute()
120
121 return posts.map((post: any): QueueItemView => ({
122 id: Number(post.id),
123 title: post.title || null,
124 body: String(post.body || ''),
125 status: String(post.status),
126 scheduledAt: post.scheduled_at || null,
127 publishedAt: post.published_at || null,
128 createdAt: String(post.created_at),
129 providers: targets
130 .filter((target: any) => Number(target.post_id) === Number(post.id))
131 .map((target: any): QueueTargetView => ({
132 provider: target.provider,
133 status: String(target.status),
134 remoteUri: target.remote_uri || null,
135 failureReason: target.failure_reason || null,
136 })),
137 }))
138 }
139
140 /** Delete a draft, scheduled, or failed post along with its targets. */
141 async remove(id: number): Promise<void> {
142 const post = await this.findActionable(id)
143 await database.deleteFrom('post_targets').where('post_id', '=', post.id).execute()
144 await database.deleteFrom('posts').where('id', '=', post.id).execute()
145 }
146
147 /** Publish a draft/scheduled/failed post immediately. */
148 async publishNow(id: number): Promise<{ postId: number, results: CrosspostTargetResult[] }> {
149 const post = await this.findActionable(id)
150
151 const placeholders = await database
152 .selectFrom('post_targets')
153 .selectAll()
154 .where('post_id', '=', post.id)
155 .where('status', 'in', ['draft', 'scheduled', 'failed'])
156 .execute()
157
158 const providers = [...new Set(placeholders.map((target: any) => target.provider))] as SocialProvider[]
159 if (providers.length === 0)
160 throw new Error('This post has no pending targets to publish.')
161
162 await database.updateTable('posts').set({
163 status: 'publishing',
164 updated_at: now(),
165 }).where('id', '=', post.id).execute()
166
167 // The provider services insert fresh result rows; drop the placeholders
168 // so the queue doesn't show both. (Deleted one-by-one — the query
169 // builder mis-compiles `where in` on DELETE statements.)
170 for (const target of placeholders) {
171 await database.deleteFrom('post_targets').where('id', '=', target.id).execute()
172 }
173
174 const results = await crosspost.publishExisting(
175 { id: Number(post.id), body: String(post.body) },
176 providers,
177 )
178
179 const anyOk = results.some(result => result.ok)
180 const finishedAt = now()
181 await database.updateTable('posts').set({
182 status: anyOk ? 'published' : 'failed',
183 ...(anyOk ? { published_at: finishedAt } : {}),
184 updated_at: finishedAt,
185 }).where('id', '=', post.id).execute()
186
187 return { postId: Number(post.id), results }
188 }
189
190 /**
191 * Publish every scheduled post whose time has come. Called by the
192 * PublishScheduledPosts job every minute; failures on one post never block
193 * the rest.
194 */
195 async publishDue(): Promise<{ published: number, failed: number }> {
196 const due = await database
197 .selectFrom('posts')
198 .select(['id'])
199 .where('status', '=', 'scheduled')
200 .where('scheduled_at', '<=', now())
201 .execute()
202
203 let published = 0
204 let failed = 0
205 for (const post of due) {
206 try {
207 const { results } = await this.publishNow(Number(post.id))
208 if (results.some(result => result.ok)) published += 1
209 else failed += 1
210 }
211 catch {
212 failed += 1
213 }
214 }
215
216 return { published, failed }
217 }
218
219 private async findActionable(id: number): Promise<any> {
220 const post = await database
221 .selectFrom('posts')
222 .selectAll()
223 .where('id', '=', id)
224 .executeTakeFirst()
225
226 if (!post)
227 throw new Error('Post not found.')
228 if (!ACTIONABLE.has(String(post.status)))
229 throw new Error('Only draft, scheduled, or failed posts can be changed.')
230
231 return post
232 }
233}
234
235export const postQueue = new QueueService()