tuitbot-server 0.1.49

HTTP API server for Tuitbot autonomous X growth assistant
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
//! Approval queue write handlers: edit, approve, reject, batch approve/reject.

use std::sync::Arc;

use axum::extract::{Path, State};
use axum::Json;
use serde::Deserialize;
use serde_json::{json, Value};
use tuitbot_core::config::Config;
use tuitbot_core::storage::{action_log, approval_queue, provenance, scheduled_content};

use crate::account::{require_approve, AccountContext};
use crate::error::ApiError;
use crate::state::AppState;
use crate::ws::{AccountWsEvent, WsEvent};

/// Request body for editing approval item content.
#[derive(Deserialize)]
pub struct EditContentRequest {
    pub content: String,
    /// Optional updated media paths.
    #[serde(default)]
    pub media_paths: Option<Vec<String>>,
    /// Who made the edit (default: "dashboard").
    #[serde(default = "default_editor")]
    pub editor: String,
}

fn default_editor() -> String {
    "dashboard".to_string()
}

/// `PATCH /api/approval/:id` — edit content before approving.
pub async fn edit_item(
    State(state): State<Arc<AppState>>,
    ctx: AccountContext,
    Path(id): Path<i64>,
    Json(body): Json<EditContentRequest>,
) -> Result<Json<Value>, ApiError> {
    require_approve(&ctx)?;

    let item = approval_queue::get_by_id_for(&state.db, &ctx.account_id, id).await?;
    let item = item.ok_or_else(|| ApiError::NotFound(format!("approval item {id} not found")))?;

    let content = body.content.trim();
    if content.is_empty() {
        return Err(ApiError::BadRequest("content cannot be empty".to_string()));
    }

    // Record edit history before updating (queries by PK, implicitly scoped).
    if content != item.generated_content {
        let _ = approval_queue::record_edit(
            &state.db,
            id,
            &body.editor,
            "generated_content",
            &item.generated_content,
            content,
        )
        .await;
    }

    approval_queue::update_content_for(&state.db, &ctx.account_id, id, content).await?;

    if let Some(media_paths) = &body.media_paths {
        let media_json = serde_json::to_string(media_paths).unwrap_or_else(|_| "[]".to_string());

        // Record media_paths edit if changed.
        if media_json != item.media_paths {
            let _ = approval_queue::record_edit(
                &state.db,
                id,
                &body.editor,
                "media_paths",
                &item.media_paths,
                &media_json,
            )
            .await;
        }

        approval_queue::update_media_paths_for(&state.db, &ctx.account_id, id, &media_json).await?;
    }

    // Log to action log.
    let metadata = json!({
        "approval_id": id,
        "editor": body.editor,
        "field": "generated_content",
    });
    let _ = action_log::log_action_for(
        &state.db,
        &ctx.account_id,
        "approval_edited",
        "success",
        Some(&format!("Edited approval item {id}")),
        Some(&metadata.to_string()),
    )
    .await;

    let updated = approval_queue::get_by_id_for(&state.db, &ctx.account_id, id)
        .await?
        .expect("item was just verified to exist");
    Ok(Json(json!(updated)))
}

/// `POST /api/approval/:id/approve` — approve a queued item.
pub async fn approve_item(
    State(state): State<Arc<AppState>>,
    ctx: AccountContext,
    Path(id): Path<i64>,
    body: Option<Json<approval_queue::ReviewAction>>,
) -> Result<Json<Value>, ApiError> {
    require_approve(&ctx)?;

    let item = approval_queue::get_by_id_for(&state.db, &ctx.account_id, id).await?;
    let item = item.ok_or_else(|| ApiError::NotFound(format!("approval item {id} not found")))?;

    // Safety guard: only allow approval if status is "pending"
    if item.status != "pending" {
        return Err(ApiError::Conflict(format!(
            "cannot approve item {id}: status is '{}', expected 'pending'",
            item.status
        )));
    }

    // Verify X auth tokens exist before allowing approval.
    let token_path =
        tuitbot_core::storage::accounts::account_token_path(&state.data_dir, &ctx.account_id);
    if !token_path.exists() {
        return Err(ApiError::BadRequest(
            "Cannot approve: X API not authenticated. Complete X auth setup first.".to_string(),
        ));
    }

    let review = body.map(|b| b.0).unwrap_or_default();

    // Check if this item has a future scheduling intent.
    let schedule_bridge = item.scheduled_for.as_deref().and_then(|sched| {
        chrono::NaiveDateTime::parse_from_str(sched, "%Y-%m-%dT%H:%M:%SZ")
            .ok()
            .filter(|dt| *dt > chrono::Utc::now().naive_utc())
            .map(|_| sched.to_string())
    });

    if let Some(ref sched) = schedule_bridge {
        // Approve and mark as "scheduled" — the posting engine only picks up "approved" items,
        // so "scheduled" prevents double-posting.
        approval_queue::update_status_with_review_for(
            &state.db,
            &ctx.account_id,
            id,
            "scheduled",
            &review,
        )
        .await?;

        // Bridge to scheduled_content so the scheduler posts at the intended time.
        let sc_id = scheduled_content::insert_for(
            &state.db,
            &ctx.account_id,
            &item.action_type,
            &item.generated_content,
            Some(sched),
        )
        .await?;

        // Copy provenance links from approval_queue to scheduled_content.
        let _ = provenance::copy_links_for(
            &state.db,
            &ctx.account_id,
            "approval_queue",
            id,
            "scheduled_content",
            sc_id,
        )
        .await;

        let metadata = json!({
            "approval_id": id,
            "scheduled_content_id": sc_id,
            "scheduled_for": sched,
            "actor": review.actor,
            "notes": review.notes,
            "action_type": item.action_type,
        });
        let _ = action_log::log_action_for(
            &state.db,
            &ctx.account_id,
            "approval_approved_scheduled",
            "success",
            Some(&format!("Approved item {id} → scheduled for {sched}")),
            Some(&metadata.to_string()),
        )
        .await;

        let _ = state.event_tx.send(AccountWsEvent {
            account_id: ctx.account_id.clone(),
            event: WsEvent::ApprovalUpdated {
                id,
                status: "scheduled".to_string(),
                action_type: item.action_type,
                actor: review.actor,
            },
        });

        return Ok(Json(json!({
            "status": "scheduled",
            "id": id,
            "scheduled_content_id": sc_id,
            "scheduled_for": sched,
        })));
    }

    // No scheduling intent (or scheduled_for is in the past) — approve for immediate posting.
    approval_queue::update_status_with_review_for(
        &state.db,
        &ctx.account_id,
        id,
        "approved",
        &review,
    )
    .await?;

    // Log to action log.
    let metadata = json!({
        "approval_id": id,
        "actor": review.actor,
        "notes": review.notes,
        "action_type": item.action_type,
    });
    let _ = action_log::log_action_for(
        &state.db,
        &ctx.account_id,
        "approval_approved",
        "success",
        Some(&format!("Approved item {id}")),
        Some(&metadata.to_string()),
    )
    .await;

    let _ = state.event_tx.send(AccountWsEvent {
        account_id: ctx.account_id.clone(),
        event: WsEvent::ApprovalUpdated {
            id,
            status: "approved".to_string(),
            action_type: item.action_type,
            actor: review.actor,
        },
    });

    Ok(Json(json!({"status": "approved", "id": id})))
}

/// `POST /api/approval/:id/reject` — reject a queued item.
pub async fn reject_item(
    State(state): State<Arc<AppState>>,
    ctx: AccountContext,
    Path(id): Path<i64>,
    body: Option<Json<approval_queue::ReviewAction>>,
) -> Result<Json<Value>, ApiError> {
    require_approve(&ctx)?;

    let item = approval_queue::get_by_id_for(&state.db, &ctx.account_id, id).await?;
    let item = item.ok_or_else(|| ApiError::NotFound(format!("approval item {id} not found")))?;

    // Safety guard: only allow rejection if status is "pending"
    if item.status != "pending" {
        return Err(ApiError::Conflict(format!(
            "cannot reject item {id}: status is '{}', expected 'pending'",
            item.status
        )));
    }

    let review = body.map(|b| b.0).unwrap_or_default();
    approval_queue::update_status_with_review_for(
        &state.db,
        &ctx.account_id,
        id,
        "rejected",
        &review,
    )
    .await?;

    // Log to action log.
    let metadata = json!({
        "approval_id": id,
        "actor": review.actor,
        "notes": review.notes,
        "action_type": item.action_type,
    });
    let _ = action_log::log_action_for(
        &state.db,
        &ctx.account_id,
        "approval_rejected",
        "success",
        Some(&format!("Rejected item {id}")),
        Some(&metadata.to_string()),
    )
    .await;

    let _ = state.event_tx.send(AccountWsEvent {
        account_id: ctx.account_id.clone(),
        event: WsEvent::ApprovalUpdated {
            id,
            status: "rejected".to_string(),
            action_type: item.action_type,
            actor: review.actor,
        },
    });

    Ok(Json(json!({"status": "rejected", "id": id})))
}

/// Request body for batch approve.
#[derive(Deserialize)]
pub struct BatchApproveRequest {
    /// Maximum number of items to approve (clamped to server config).
    #[serde(default)]
    pub max: Option<usize>,
    /// Specific IDs to approve (if provided, `max` is ignored).
    #[serde(default)]
    pub ids: Option<Vec<i64>>,
    /// Review metadata.
    #[serde(default)]
    pub review: approval_queue::ReviewAction,
}

/// `POST /api/approval/approve-all` — batch-approve pending items.
pub async fn approve_all(
    State(state): State<Arc<AppState>>,
    ctx: AccountContext,
    body: Option<Json<BatchApproveRequest>>,
) -> Result<Json<Value>, ApiError> {
    require_approve(&ctx)?;

    // Verify X auth tokens exist before allowing approval.
    let token_path =
        tuitbot_core::storage::accounts::account_token_path(&state.data_dir, &ctx.account_id);
    if !token_path.exists() {
        return Err(ApiError::BadRequest(
            "Cannot approve: X API not authenticated. Complete X auth setup first.".to_string(),
        ));
    }

    let config = read_config(&state);
    let max_batch = config.max_batch_approve;

    let body = body.map(|b| b.0);
    let review = body.as_ref().map(|b| b.review.clone()).unwrap_or_default();

    let approved_ids = if let Some(ids) = body.as_ref().and_then(|b| b.ids.as_ref()) {
        // Approve specific IDs (still clamped to max_batch).
        let clamped: Vec<&i64> = ids.iter().take(max_batch).collect();
        let mut approved = Vec::with_capacity(clamped.len());
        for &id in &clamped {
            if let Ok(Some(item)) =
                approval_queue::get_by_id_for(&state.db, &ctx.account_id, *id).await
            {
                let result = approve_single_item(&state, &ctx.account_id, &item, &review).await;
                if result.is_ok() {
                    approved.push(*id);
                }
            }
        }
        approved
    } else {
        // Approve oldest N pending items, handling scheduling intent per-item.
        let effective_max = body
            .as_ref()
            .and_then(|b| b.max)
            .map(|m| m.min(max_batch))
            .unwrap_or(max_batch);

        let pending = approval_queue::get_pending_for(&state.db, &ctx.account_id).await?;
        let mut approved = Vec::with_capacity(effective_max);
        for item in pending.iter().take(effective_max) {
            if approve_single_item(&state, &ctx.account_id, item, &review)
                .await
                .is_ok()
            {
                approved.push(item.id);
            }
        }
        approved
    };

    let count = approved_ids.len();

    // Log to action log.
    let metadata = json!({
        "count": count,
        "ids": approved_ids,
        "actor": review.actor,
        "max_configured": max_batch,
    });
    let _ = action_log::log_action_for(
        &state.db,
        &ctx.account_id,
        "approval_batch_approved",
        "success",
        Some(&format!("Batch approved {count} items")),
        Some(&metadata.to_string()),
    )
    .await;

    let _ = state.event_tx.send(AccountWsEvent {
        account_id: ctx.account_id.clone(),
        event: WsEvent::ApprovalUpdated {
            id: 0,
            status: "approved_all".to_string(),
            action_type: String::new(),
            actor: review.actor,
        },
    });

    Ok(Json(
        json!({"status": "approved", "count": count, "ids": approved_ids, "max_batch": max_batch}),
    ))
}

/// Approve a single item, bridging to scheduled_content if it has a future `scheduled_for`.
pub(super) async fn approve_single_item(
    state: &AppState,
    account_id: &str,
    item: &approval_queue::ApprovalItem,
    review: &approval_queue::ReviewAction,
) -> Result<(), ApiError> {
    let schedule_bridge = item.scheduled_for.as_deref().and_then(|sched| {
        chrono::NaiveDateTime::parse_from_str(sched, "%Y-%m-%dT%H:%M:%SZ")
            .ok()
            .filter(|dt| *dt > chrono::Utc::now().naive_utc())
            .map(|_| sched.to_string())
    });

    if let Some(ref sched) = schedule_bridge {
        approval_queue::update_status_with_review_for(
            &state.db,
            account_id,
            item.id,
            "scheduled",
            review,
        )
        .await?;

        let sc_id = scheduled_content::insert_for(
            &state.db,
            account_id,
            &item.action_type,
            &item.generated_content,
            Some(sched),
        )
        .await?;

        // Copy provenance links from approval_queue to scheduled_content.
        let _ = provenance::copy_links_for(
            &state.db,
            account_id,
            "approval_queue",
            item.id,
            "scheduled_content",
            sc_id,
        )
        .await;
    } else {
        approval_queue::update_status_with_review_for(
            &state.db, account_id, item.id, "approved", review,
        )
        .await?;
    }

    Ok(())
}

/// Read the config from disk (best-effort, returns defaults on failure).
pub(super) fn read_config(state: &AppState) -> Config {
    std::fs::read_to_string(&state.config_path)
        .ok()
        .and_then(|s| toml::from_str(&s).ok())
        .unwrap_or_default()
}