summaryrefslogtreecommitdiff
path: root/makima/src/db/repository.rs
diff options
context:
space:
mode:
Diffstat (limited to 'makima/src/db/repository.rs')
-rw-r--r--makima/src/db/repository.rs53
1 files changed, 51 insertions, 2 deletions
diff --git a/makima/src/db/repository.rs b/makima/src/db/repository.rs
index d274548..aa1203a 100644
--- a/makima/src/db/repository.rs
+++ b/makima/src/db/repository.rs
@@ -5387,7 +5387,8 @@ pub async fn create_directive_step(
req: CreateDirectiveStepRequest,
) -> Result<DirectiveStep, sqlx::Error> {
let generation = req.generation.unwrap_or(1);
- sqlx::query_as::<_, DirectiveStep>(
+ let order_id = req.order_id;
+ let step = sqlx::query_as::<_, DirectiveStep>(
r#"
INSERT INTO directive_steps (directive_id, name, description, task_plan, depends_on, order_index, generation)
VALUES ($1, $2, $3, $4, $5, $6, $7)
@@ -5402,7 +5403,20 @@ pub async fn create_directive_step(
.bind(req.order_index)
.bind(generation)
.fetch_one(pool)
- .await
+ .await?;
+
+ // If an order_id was provided, auto-link the order to this step
+ if let Some(oid) = order_id {
+ sqlx::query(
+ r#"UPDATE orders SET directive_step_id = $1, updated_at = NOW() WHERE id = $2"#,
+ )
+ .bind(step.id)
+ .bind(oid)
+ .execute(pool)
+ .await?;
+ }
+
+ Ok(step)
}
/// Batch create multiple directive steps.
@@ -6392,3 +6406,38 @@ pub async fn get_orders_by_step_id(
.await
}
+/// Reconcile directive orders by checking linked step statuses.
+/// - Orders linked to completed steps are marked "done"
+/// - Orders linked to running/ready steps are marked "under_review"
+/// Returns the count of orders updated.
+pub async fn reconcile_directive_orders(
+ pool: &PgPool,
+ owner_id: Uuid,
+ directive_id: Uuid,
+) -> Result<i64, sqlx::Error> {
+ let rows: Vec<(Uuid,)> = sqlx::query_as(
+ r#"
+ UPDATE orders o
+ SET status = CASE
+ WHEN ds.status = 'completed' THEN 'done'
+ WHEN ds.status IN ('running', 'ready') THEN 'under_review'
+ ELSE o.status
+ END,
+ updated_at = NOW()
+ FROM directive_steps ds
+ WHERE o.directive_step_id = ds.id
+ AND o.directive_id = $1
+ AND o.owner_id = $2
+ AND o.status NOT IN ('done', 'archived')
+ AND ds.status IN ('completed', 'running', 'ready')
+ RETURNING o.id
+ "#,
+ )
+ .bind(directive_id)
+ .bind(owner_id)
+ .fetch_all(pool)
+ .await?;
+
+ Ok(rows.len() as i64)
+}
+