diff options
| author | soryu <soryu@soryu.co> | 2026-02-13 21:40:13 +0000 |
|---|---|---|
| committer | soryu <soryu@soryu.co> | 2026-02-13 21:40:13 +0000 |
| commit | 04cc7f3b19e28f67725864bcf7fe4ba1e93367df (patch) | |
| tree | 5df52bb228c0eb1f8fee295b2d828c6d60cd452b | |
| parent | 5edaf1228b4e48a441b98c49f58de312b7924ed6 (diff) | |
| download | soryu-makima/makima-system--create-orders-database-schema-and-b-36dfdf9f.tar.gz soryu-makima/makima-system--create-orders-database-schema-and-b-36dfdf9f.zip | |
WIP: heartbeat checkpointmakima/makima-system--create-orders-database-schema-and-b-36dfdf9f
| -rw-r--r-- | makima/migrations/20260213000000_create_orders.sql | 22 | ||||
| -rw-r--r-- | makima/src/db/models.rs | 71 | ||||
| -rw-r--r-- | makima/src/db/repository.rs | 184 | ||||
| -rw-r--r-- | makima/src/server/handlers/mod.rs | 1 | ||||
| -rw-r--r-- | makima/src/server/handlers/orders.rs | 348 | ||||
| -rw-r--r-- | makima/src/server/mod.rs | 15 |
6 files changed, 640 insertions, 1 deletions
diff --git a/makima/migrations/20260213000000_create_orders.sql b/makima/migrations/20260213000000_create_orders.sql new file mode 100644 index 0000000..eee36c4 --- /dev/null +++ b/makima/migrations/20260213000000_create_orders.sql @@ -0,0 +1,22 @@ +-- Orders table: work items like GitHub Issues / Linear cards +-- Orders represent planned work that can be attached to directives or contracts. + +CREATE TABLE orders ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + owner_id UUID NOT NULL REFERENCES owners(id) ON DELETE CASCADE, + title VARCHAR(500) NOT NULL, + description TEXT, + status VARCHAR(50) NOT NULL DEFAULT 'backlog', + priority VARCHAR(20) NOT NULL DEFAULT 'medium', + labels JSONB DEFAULT '[]', + directive_id UUID REFERENCES directives(id) ON DELETE SET NULL, + directive_step_id UUID, + contract_id UUID REFERENCES contracts(id) ON DELETE SET NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE INDEX idx_orders_owner ON orders(owner_id); +CREATE INDEX idx_orders_status ON orders(owner_id, status); +CREATE INDEX idx_orders_directive ON orders(directive_id) WHERE directive_id IS NOT NULL; +CREATE INDEX idx_orders_contract ON orders(contract_id) WHERE contract_id IS NOT NULL; diff --git a/makima/src/db/models.rs b/makima/src/db/models.rs index 66c0a30..14d039b 100644 --- a/makima/src/db/models.rs +++ b/makima/src/db/models.rs @@ -2893,3 +2893,74 @@ pub struct DirectiveMemoryListResponse { pub memories: Vec<DirectiveMemory>, pub total: i64, } + +// ============================================================================= +// Order Types (work items like GitHub Issues / Linear cards) +// ============================================================================= + +/// An order — a planned work item that can be linked to directives or contracts. +#[derive(Debug, Clone, FromRow, Serialize, Deserialize, ToSchema)] +#[serde(rename_all = "camelCase")] +pub struct Order { + pub id: Uuid, + pub owner_id: Uuid, + pub title: String, + pub description: Option<String>, + /// Status: backlog, todo, in_progress, done, cancelled + pub status: String, + /// Priority: low, medium, high, urgent + pub priority: String, + /// Labels as a JSON array of strings + pub labels: serde_json::Value, + /// Linked directive (optional) + pub directive_id: Option<Uuid>, + /// Linked directive step (optional) + pub directive_step_id: Option<Uuid>, + /// Linked contract (optional) + pub contract_id: Option<Uuid>, + pub created_at: DateTime<Utc>, + pub updated_at: DateTime<Utc>, +} + +/// Request to create a new order. +#[derive(Debug, Deserialize, ToSchema)] +#[serde(rename_all = "camelCase")] +pub struct CreateOrderRequest { + pub title: String, + pub description: Option<String>, + pub priority: Option<String>, + #[serde(default = "default_order_labels")] + pub labels: serde_json::Value, +} + +fn default_order_labels() -> serde_json::Value { + serde_json::Value::Array(vec![]) +} + +/// Request to update an order. +#[derive(Debug, Default, Deserialize, ToSchema)] +#[serde(rename_all = "camelCase")] +pub struct UpdateOrderRequest { + pub title: Option<String>, + pub description: Option<String>, + pub status: Option<String>, + pub priority: Option<String>, + pub labels: Option<serde_json::Value>, +} + +/// Request to link an order to a directive and/or contract. +#[derive(Debug, Deserialize, ToSchema)] +#[serde(rename_all = "camelCase")] +pub struct LinkOrderRequest { + pub directive_id: Option<Uuid>, + pub directive_step_id: Option<Uuid>, + pub contract_id: Option<Uuid>, +} + +/// List response for orders. +#[derive(Debug, Serialize, ToSchema)] +#[serde(rename_all = "camelCase")] +pub struct OrderListResponse { + pub orders: Vec<Order>, + pub total: i64, +} diff --git a/makima/src/db/repository.rs b/makima/src/db/repository.rs index 51f49cd..3b00c1c 100644 --- a/makima/src/db/repository.rs +++ b/makima/src/db/repository.rs @@ -20,6 +20,7 @@ use super::models::{ PhaseDefinition, SupervisorHeartbeatRecord, SupervisorState, Task, TaskCheckpoint, TaskEvent, TaskSummary, UpdateContractRequest, UpdateFileRequest, UpdateTaskRequest, UpdateTemplateRequest, + Order, CreateOrderRequest, UpdateOrderRequest, LinkOrderRequest, }; /// Repository error types. @@ -6020,3 +6021,186 @@ pub async fn clear_directive_memories( .await?; Ok(result.rows_affected()) } + +// ============================================================================= +// Order CRUD +// ============================================================================= + +/// Create a new order for an owner. +pub async fn create_order( + pool: &PgPool, + owner_id: Uuid, + req: CreateOrderRequest, +) -> Result<Order, sqlx::Error> { + let priority = req.priority.as_deref().unwrap_or("medium"); + sqlx::query_as::<_, Order>( + r#" + INSERT INTO orders (owner_id, title, description, priority, labels) + VALUES ($1, $2, $3, $4, $5) + RETURNING * + "#, + ) + .bind(owner_id) + .bind(&req.title) + .bind(&req.description) + .bind(priority) + .bind(&req.labels) + .fetch_one(pool) + .await +} + +/// Get a single order for an owner. +pub async fn get_order( + pool: &PgPool, + id: Uuid, + owner_id: Uuid, +) -> Result<Option<Order>, sqlx::Error> { + sqlx::query_as::<_, Order>( + r#"SELECT * FROM orders WHERE id = $1 AND owner_id = $2"#, + ) + .bind(id) + .bind(owner_id) + .fetch_optional(pool) + .await +} + +/// List orders for an owner with optional status and priority filters. +pub async fn list_orders( + pool: &PgPool, + owner_id: Uuid, + status_filter: Option<&str>, + priority_filter: Option<&str>, +) -> Result<Vec<Order>, sqlx::Error> { + // Build query dynamically based on filters + let mut query = String::from("SELECT * FROM orders WHERE owner_id = $1"); + let mut param_idx = 2; + + if status_filter.is_some() { + query.push_str(&format!(" AND status = ${}", param_idx)); + param_idx += 1; + } + if priority_filter.is_some() { + query.push_str(&format!(" AND priority = ${}", param_idx)); + } + query.push_str(" ORDER BY created_at DESC"); + + // Use query_as with dynamic binding + let mut q = sqlx::query_as::<_, Order>(&query).bind(owner_id); + + if let Some(status) = status_filter { + q = q.bind(status.to_string()); + } + if let Some(priority) = priority_filter { + q = q.bind(priority.to_string()); + } + + q.fetch_all(pool).await +} + +/// Update an order for an owner. +pub async fn update_order( + pool: &PgPool, + id: Uuid, + owner_id: Uuid, + req: UpdateOrderRequest, +) -> Result<Option<Order>, sqlx::Error> { + let current = sqlx::query_as::<_, Order>( + r#"SELECT * FROM orders WHERE id = $1 AND owner_id = $2"#, + ) + .bind(id) + .bind(owner_id) + .fetch_optional(pool) + .await?; + + let current = match current { + Some(c) => c, + None => return Ok(None), + }; + + let title = req.title.as_deref().unwrap_or(¤t.title); + let description = req.description.as_deref().or(current.description.as_deref()); + let status = req.status.as_deref().unwrap_or(¤t.status); + let priority = req.priority.as_deref().unwrap_or(¤t.priority); + let labels = req.labels.as_ref().unwrap_or(¤t.labels); + + sqlx::query_as::<_, Order>( + r#" + UPDATE orders + SET title = $3, description = $4, status = $5, priority = $6, labels = $7, updated_at = NOW() + WHERE id = $1 AND owner_id = $2 + RETURNING * + "#, + ) + .bind(id) + .bind(owner_id) + .bind(title) + .bind(description) + .bind(status) + .bind(priority) + .bind(labels) + .fetch_optional(pool) + .await +} + +/// Delete an order for an owner. +pub async fn delete_order( + pool: &PgPool, + id: Uuid, + owner_id: Uuid, +) -> Result<bool, sqlx::Error> { + let result = sqlx::query( + r#"DELETE FROM orders WHERE id = $1 AND owner_id = $2"#, + ) + .bind(id) + .bind(owner_id) + .execute(pool) + .await?; + Ok(result.rows_affected() > 0) +} + +/// Link an order to a directive and/or contract. +pub async fn link_order_to_directive( + pool: &PgPool, + order_id: Uuid, + owner_id: Uuid, + req: LinkOrderRequest, +) -> Result<Option<Order>, sqlx::Error> { + sqlx::query_as::<_, Order>( + r#" + UPDATE orders + SET directive_id = COALESCE($3, directive_id), + directive_step_id = COALESCE($4, directive_step_id), + contract_id = COALESCE($5, contract_id), + updated_at = NOW() + WHERE id = $1 AND owner_id = $2 + RETURNING * + "#, + ) + .bind(order_id) + .bind(owner_id) + .bind(req.directive_id) + .bind(req.directive_step_id) + .bind(req.contract_id) + .fetch_optional(pool) + .await +} + +/// Unlink an order from its directive and contract. +pub async fn unlink_order_from_directive( + pool: &PgPool, + order_id: Uuid, + owner_id: Uuid, +) -> Result<Option<Order>, sqlx::Error> { + sqlx::query_as::<_, Order>( + r#" + UPDATE orders + SET directive_id = NULL, directive_step_id = NULL, contract_id = NULL, updated_at = NOW() + WHERE id = $1 AND owner_id = $2 + RETURNING * + "#, + ) + .bind(order_id) + .bind(owner_id) + .fetch_optional(pool) + .await +} diff --git a/makima/src/server/handlers/mod.rs b/makima/src/server/handlers/mod.rs index 29cd09f..0b7961e 100644 --- a/makima/src/server/handlers/mod.rs +++ b/makima/src/server/handlers/mod.rs @@ -8,6 +8,7 @@ pub mod contract_discuss; pub mod contracts; pub mod directives; pub mod file_ws; +pub mod orders; pub mod files; pub mod history; pub mod listen; diff --git a/makima/src/server/handlers/orders.rs b/makima/src/server/handlers/orders.rs new file mode 100644 index 0000000..70cafe3 --- /dev/null +++ b/makima/src/server/handlers/orders.rs @@ -0,0 +1,348 @@ +//! HTTP handlers for order CRUD operations. + +use axum::{ + extract::{Path, Query, State}, + http::StatusCode, + response::IntoResponse, + Json, +}; +use serde::Deserialize; +use uuid::Uuid; + +use crate::db::models::{ + CreateOrderRequest, LinkOrderRequest, Order, OrderListResponse, UpdateOrderRequest, +}; +use crate::db::repository; +use crate::server::auth::Authenticated; +use crate::server::messages::ApiError; +use crate::server::state::SharedState; + +/// Query parameters for the order list endpoint. +#[derive(Debug, Deserialize)] +pub struct OrderListQuery { + pub status: Option<String>, + pub priority: Option<String>, +} + +// ============================================================================= +// Order CRUD +// ============================================================================= + +/// List all orders for the authenticated user. +#[utoipa::path( + get, + path = "/api/v1/orders", + params( + ("status" = Option<String>, Query, description = "Filter by status"), + ("priority" = Option<String>, Query, description = "Filter by priority"), + ), + responses( + (status = 200, description = "List of orders", body = OrderListResponse), + (status = 401, description = "Unauthorized", body = ApiError), + (status = 503, description = "Database not configured", body = ApiError), + ), + security(("bearer_auth" = []), ("api_key" = [])), + tag = "Orders" +)] +pub async fn list_orders( + State(state): State<SharedState>, + Authenticated(auth): Authenticated, + Query(query): Query<OrderListQuery>, +) -> impl IntoResponse { + let Some(ref pool) = state.db_pool else { + return ( + StatusCode::SERVICE_UNAVAILABLE, + Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")), + ) + .into_response(); + }; + + match repository::list_orders( + pool, + auth.owner_id, + query.status.as_deref(), + query.priority.as_deref(), + ) + .await + { + Ok(orders) => { + let total = orders.len() as i64; + Json(OrderListResponse { orders, total }).into_response() + } + Err(e) => { + tracing::error!("Failed to list orders: {}", e); + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(ApiError::new("LIST_FAILED", &e.to_string())), + ) + .into_response() + } + } +} + +/// Create a new order. +#[utoipa::path( + post, + path = "/api/v1/orders", + request_body = CreateOrderRequest, + responses( + (status = 201, description = "Order created", body = Order), + (status = 401, description = "Unauthorized", body = ApiError), + (status = 503, description = "Database not configured", body = ApiError), + ), + security(("bearer_auth" = []), ("api_key" = [])), + tag = "Orders" +)] +pub async fn create_order( + State(state): State<SharedState>, + Authenticated(auth): Authenticated, + Json(req): Json<CreateOrderRequest>, +) -> impl IntoResponse { + let Some(ref pool) = state.db_pool else { + return ( + StatusCode::SERVICE_UNAVAILABLE, + Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")), + ) + .into_response(); + }; + + match repository::create_order(pool, auth.owner_id, req).await { + Ok(order) => (StatusCode::CREATED, Json(order)).into_response(), + Err(e) => { + tracing::error!("Failed to create order: {}", e); + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(ApiError::new("CREATE_FAILED", &e.to_string())), + ) + .into_response() + } + } +} + +/// Get an order by ID. +#[utoipa::path( + get, + path = "/api/v1/orders/{id}", + params(("id" = Uuid, Path, description = "Order ID")), + responses( + (status = 200, description = "Order details", body = Order), + (status = 404, description = "Not found", body = ApiError), + (status = 503, description = "Database not configured", body = ApiError), + ), + security(("bearer_auth" = []), ("api_key" = [])), + tag = "Orders" +)] +pub async fn get_order( + State(state): State<SharedState>, + Authenticated(auth): Authenticated, + Path(id): Path<Uuid>, +) -> impl IntoResponse { + let Some(ref pool) = state.db_pool else { + return ( + StatusCode::SERVICE_UNAVAILABLE, + Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")), + ) + .into_response(); + }; + + match repository::get_order(pool, id, auth.owner_id).await { + Ok(Some(order)) => Json(order).into_response(), + Ok(None) => ( + StatusCode::NOT_FOUND, + Json(ApiError::new("NOT_FOUND", "Order not found")), + ) + .into_response(), + Err(e) => { + tracing::error!("Failed to get order: {}", e); + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(ApiError::new("GET_FAILED", &e.to_string())), + ) + .into_response() + } + } +} + +/// Update an order. +#[utoipa::path( + put, + path = "/api/v1/orders/{id}", + params(("id" = Uuid, Path, description = "Order ID")), + request_body = UpdateOrderRequest, + responses( + (status = 200, description = "Order updated", body = Order), + (status = 404, description = "Not found", body = ApiError), + (status = 503, description = "Database not configured", body = ApiError), + ), + security(("bearer_auth" = []), ("api_key" = [])), + tag = "Orders" +)] +pub async fn update_order( + State(state): State<SharedState>, + Authenticated(auth): Authenticated, + Path(id): Path<Uuid>, + Json(req): Json<UpdateOrderRequest>, +) -> impl IntoResponse { + let Some(ref pool) = state.db_pool else { + return ( + StatusCode::SERVICE_UNAVAILABLE, + Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")), + ) + .into_response(); + }; + + match repository::update_order(pool, id, auth.owner_id, req).await { + Ok(Some(order)) => Json(order).into_response(), + Ok(None) => ( + StatusCode::NOT_FOUND, + Json(ApiError::new("NOT_FOUND", "Order not found")), + ) + .into_response(), + Err(e) => { + tracing::error!("Failed to update order: {}", e); + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(ApiError::new("UPDATE_FAILED", &e.to_string())), + ) + .into_response() + } + } +} + +/// Delete an order. +#[utoipa::path( + delete, + path = "/api/v1/orders/{id}", + params(("id" = Uuid, Path, description = "Order ID")), + responses( + (status = 204, description = "Deleted"), + (status = 404, description = "Not found", body = ApiError), + (status = 503, description = "Database not configured", body = ApiError), + ), + security(("bearer_auth" = []), ("api_key" = [])), + tag = "Orders" +)] +pub async fn delete_order( + State(state): State<SharedState>, + Authenticated(auth): Authenticated, + Path(id): Path<Uuid>, +) -> impl IntoResponse { + let Some(ref pool) = state.db_pool else { + return ( + StatusCode::SERVICE_UNAVAILABLE, + Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")), + ) + .into_response(); + }; + + match repository::delete_order(pool, id, auth.owner_id).await { + Ok(true) => StatusCode::NO_CONTENT.into_response(), + Ok(false) => ( + StatusCode::NOT_FOUND, + Json(ApiError::new("NOT_FOUND", "Order not found")), + ) + .into_response(), + Err(e) => { + tracing::error!("Failed to delete order: {}", e); + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(ApiError::new("DELETE_FAILED", &e.to_string())), + ) + .into_response() + } + } +} + +// ============================================================================= +// Order Linking +// ============================================================================= + +/// Link an order to a directive and/or contract. +#[utoipa::path( + post, + path = "/api/v1/orders/{id}/link", + params(("id" = Uuid, Path, description = "Order ID")), + request_body = LinkOrderRequest, + responses( + (status = 200, description = "Order linked", body = Order), + (status = 404, description = "Not found", body = ApiError), + (status = 503, description = "Database not configured", body = ApiError), + ), + security(("bearer_auth" = []), ("api_key" = [])), + tag = "Orders" +)] +pub async fn link_order( + State(state): State<SharedState>, + Authenticated(auth): Authenticated, + Path(id): Path<Uuid>, + Json(req): Json<LinkOrderRequest>, +) -> impl IntoResponse { + let Some(ref pool) = state.db_pool else { + return ( + StatusCode::SERVICE_UNAVAILABLE, + Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")), + ) + .into_response(); + }; + + match repository::link_order_to_directive(pool, id, auth.owner_id, req).await { + Ok(Some(order)) => Json(order).into_response(), + Ok(None) => ( + StatusCode::NOT_FOUND, + Json(ApiError::new("NOT_FOUND", "Order not found")), + ) + .into_response(), + Err(e) => { + tracing::error!("Failed to link order: {}", e); + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(ApiError::new("LINK_FAILED", &e.to_string())), + ) + .into_response() + } + } +} + +/// Unlink an order from its directive and contract. +#[utoipa::path( + post, + path = "/api/v1/orders/{id}/unlink", + params(("id" = Uuid, Path, description = "Order ID")), + responses( + (status = 200, description = "Order unlinked", body = Order), + (status = 404, description = "Not found", body = ApiError), + (status = 503, description = "Database not configured", body = ApiError), + ), + security(("bearer_auth" = []), ("api_key" = [])), + tag = "Orders" +)] +pub async fn unlink_order( + State(state): State<SharedState>, + Authenticated(auth): Authenticated, + Path(id): Path<Uuid>, +) -> impl IntoResponse { + let Some(ref pool) = state.db_pool else { + return ( + StatusCode::SERVICE_UNAVAILABLE, + Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")), + ) + .into_response(); + }; + + match repository::unlink_order_from_directive(pool, id, auth.owner_id).await { + Ok(Some(order)) => Json(order).into_response(), + Ok(None) => ( + StatusCode::NOT_FOUND, + Json(ApiError::new("NOT_FOUND", "Order not found")), + ) + .into_response(), + Err(e) => { + tracing::error!("Failed to unlink order: {}", e); + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(ApiError::new("UNLINK_FAILED", &e.to_string())), + ) + .into_response() + } + } +} diff --git a/makima/src/server/mod.rs b/makima/src/server/mod.rs index 7110ef8..19b8477 100644 --- a/makima/src/server/mod.rs +++ b/makima/src/server/mod.rs @@ -18,7 +18,7 @@ use tower_http::trace::TraceLayer; use utoipa::OpenApi; use utoipa_swagger_ui::SwaggerUi; -use crate::server::handlers::{api_keys, chat, contract_chat, contract_daemon, contract_discuss, contracts, directives, file_ws, files, history, listen, mesh, mesh_chat, mesh_daemon, mesh_merge, mesh_supervisor, mesh_ws, repository_history, speak, templates, transcript_analysis, users, versions}; +use crate::server::handlers::{api_keys, chat, contract_chat, contract_daemon, contract_discuss, contracts, directives, file_ws, files, history, listen, mesh, mesh_chat, mesh_daemon, mesh_merge, mesh_supervisor, mesh_ws, orders, repository_history, speak, templates, transcript_analysis, users, versions}; use crate::server::openapi::ApiDoc; use crate::server::state::SharedState; @@ -242,6 +242,19 @@ pub fn make_router(state: SharedState) -> Router { .route("/directives/{id}/memories", get(directives::list_memories).post(directives::set_memory).delete(directives::clear_memories)) .route("/directives/{id}/memories/batch", post(directives::batch_set_memories)) .route("/directives/{id}/memories/{key}", get(directives::get_memory).delete(directives::delete_memory)) + // Order endpoints + .route( + "/orders", + get(orders::list_orders).post(orders::create_order), + ) + .route( + "/orders/{id}", + get(orders::get_order) + .put(orders::update_order) + .delete(orders::delete_order), + ) + .route("/orders/{id}/link", post(orders::link_order)) + .route("/orders/{id}/unlink", post(orders::unlink_order)) // Timeline endpoint (unified history for user) .route("/timeline", get(history::get_timeline)) // Contract type templates (built-in only) |
