diff options
| author | soryu <soryu@soryu.co> | 2026-02-14 21:27:42 +0000 |
|---|---|---|
| committer | soryu <soryu@soryu.co> | 2026-02-14 21:27:42 +0000 |
| commit | 1e60728de44dd0bf25ff61c2dceb962bff70874d (patch) | |
| tree | 645327c2353153ce81d97bab98e72a866b242edd | |
| parent | 74946d4146516cb6f270c22e665c0eae72410b6c (diff) | |
| parent | cf35db7de9ba945d87cf83c6713d735585dd3636 (diff) | |
| download | soryu-1e60728de44dd0bf25ff61c2dceb962bff70874d.tar.gz soryu-1e60728de44dd0bf25ff61c2dceb962bff70874d.zip | |
Merge remote-tracking branch 'origin/makima/soryu-co-soryu---makima--create-orders-database-sc-f5c58fc2' into makima/directive-soryu-co-soryu-makima-c29f9112
| -rw-r--r-- | makima/migrations/20260214000000_create_orders.sql | 38 | ||||
| -rw-r--r-- | makima/src/db/models.rs | 117 | ||||
| -rw-r--r-- | makima/src/db/repository.rs | 304 | ||||
| -rw-r--r-- | makima/src/server/handlers/mod.rs | 1 | ||||
| -rw-r--r-- | makima/src/server/handlers/orders.rs | 443 | ||||
| -rw-r--r-- | makima/src/server/mod.rs | 16 | ||||
| -rw-r--r-- | makima/src/server/openapi.rs | 33 |
7 files changed, 946 insertions, 6 deletions
diff --git a/makima/migrations/20260214000000_create_orders.sql b/makima/migrations/20260214000000_create_orders.sql new file mode 100644 index 0000000..cb2fbae --- /dev/null +++ b/makima/migrations/20260214000000_create_orders.sql @@ -0,0 +1,38 @@ +-- Orders system: card-based issue tracker (similar to Linear/Jira/GitHub Issues). +-- Orders represent planned work items (features, bugs, spikes) that can later be +-- attached to directives (as steps) or contracts for execution. + +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, + -- Priority: critical > high > medium > low > none + priority VARCHAR(32) NOT NULL DEFAULT 'medium' + CHECK (priority IN ('critical', 'high', 'medium', 'low', 'none')), + -- Status lifecycle: open -> in_progress -> done | archived + status VARCHAR(32) NOT NULL DEFAULT 'open' + CHECK (status IN ('open', 'in_progress', 'done', 'archived')), + -- Type of work item + order_type VARCHAR(32) NOT NULL DEFAULT 'feature' + CHECK (order_type IN ('feature', 'bug', 'spike', 'chore', 'improvement')), + -- Flexible labels stored as JSON array of strings + labels JSONB NOT NULL DEFAULT '[]', + -- Optional links to directives, directive steps, and contracts + directive_id UUID REFERENCES directives(id) ON DELETE SET NULL, + directive_step_id UUID REFERENCES directive_steps(id) ON DELETE SET NULL, + contract_id UUID REFERENCES contracts(id) ON DELETE SET NULL, + -- Repository context + repository_url VARCHAR(512), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +-- Index for listing orders by owner +CREATE INDEX idx_orders_owner_id ON orders(owner_id); +-- Composite index for filtering by owner + status (common query pattern) +CREATE INDEX idx_orders_owner_status ON orders(owner_id, status); +-- Index for looking up orders linked to a directive +CREATE INDEX idx_orders_directive_id ON orders(directive_id); +-- Index for looking up orders linked to a contract +CREATE INDEX idx_orders_contract_id ON orders(contract_id); diff --git a/makima/src/db/models.rs b/makima/src/db/models.rs index 131dffc..e36da0d 100644 --- a/makima/src/db/models.rs +++ b/makima/src/db/models.rs @@ -2848,3 +2848,120 @@ pub struct UpdateDirectiveStepRequest { pub order_index: Option<i32>, } +// ============================================================================= +// Order Types +// ============================================================================= + +/// An order — a card-based work item (feature, bug, spike, chore, improvement) +/// similar to GitHub Issues or Linear cards. Orders can be linked to directives +/// or contracts for execution. +#[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>, + /// Priority: critical, high, medium, low, none + pub priority: String, + /// Status: open, in_progress, done, archived + pub status: String, + /// Type of work: feature, bug, spike, chore, improvement + pub order_type: String, + /// Flexible labels as 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>, + /// Repository context + pub repository_url: Option<String>, + 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>, + pub status: Option<String>, + pub order_type: Option<String>, + #[serde(default = "default_empty_labels")] + pub labels: serde_json::Value, + pub directive_id: Option<Uuid>, + pub contract_id: Option<Uuid>, + pub repository_url: Option<String>, +} + +/// Default empty JSON array for labels. +fn default_empty_labels() -> serde_json::Value { + serde_json::json!([]) +} + +/// Request to update an existing order. +#[derive(Debug, Default, Deserialize, ToSchema)] +#[serde(rename_all = "camelCase")] +pub struct UpdateOrderRequest { + pub title: Option<String>, + pub description: Option<String>, + pub priority: Option<String>, + pub status: Option<String>, + pub order_type: Option<String>, + pub labels: Option<serde_json::Value>, + pub directive_id: Option<Uuid>, + pub directive_step_id: Option<Uuid>, + pub contract_id: Option<Uuid>, + pub repository_url: Option<String>, +} + +/// Response for order list endpoint. +#[derive(Debug, Serialize, ToSchema)] +#[serde(rename_all = "camelCase")] +pub struct OrderListResponse { + pub orders: Vec<Order>, + pub total: i64, +} + +/// Query parameters for listing orders. +#[derive(Debug, Deserialize, ToSchema)] +#[serde(rename_all = "camelCase")] +pub struct OrderListQuery { + /// Filter by status (e.g., "open", "in_progress", "done", "archived") + pub status: Option<String>, + /// Filter by order type (e.g., "feature", "bug", "spike", "chore", "improvement") + #[serde(rename = "type")] + pub order_type: Option<String>, + /// Filter by priority (e.g., "critical", "high", "medium", "low", "none") + pub priority: Option<String>, + /// Filter by linked directive ID + pub directive_id: Option<Uuid>, + /// Filter by linked contract ID + pub contract_id: Option<Uuid>, +} + +/// Request body for linking an order to a directive. +#[derive(Debug, Deserialize, ToSchema)] +#[serde(rename_all = "camelCase")] +pub struct LinkDirectiveRequest { + pub directive_id: Uuid, +} + +/// Request body for linking an order to a contract. +#[derive(Debug, Deserialize, ToSchema)] +#[serde(rename_all = "camelCase")] +pub struct LinkContractRequest { + pub contract_id: Uuid, +} + +/// Request body for converting an order to a directive step. +#[derive(Debug, Deserialize, ToSchema)] +#[serde(rename_all = "camelCase")] +pub struct ConvertToStepRequest { + pub directive_id: Uuid, +} + diff --git a/makima/src/db/repository.rs b/makima/src/db/repository.rs index d8168f6..bfc485b 100644 --- a/makima/src/db/repository.rs +++ b/makima/src/db/repository.rs @@ -14,6 +14,7 @@ use super::models::{ DeliverableDefinition, Directive, DirectiveStep, DirectiveSummary, CreateDirectiveRequest, CreateDirectiveStepRequest, UpdateDirectiveRequest, UpdateDirectiveStepRequest, + CreateOrderRequest, Order, UpdateOrderRequest, File, FileSummary, FileVersion, HistoryEvent, HistoryQueryFilters, MeshChatConversation, MeshChatMessageRecord, PhaseChangeResult, PhaseConfig, PhaseDefinition, SupervisorHeartbeatRecord, SupervisorState, @@ -5917,3 +5918,306 @@ pub async fn get_directive_max_generation( Ok(row.0.unwrap_or(0)) } +// ============================================================================= +// Order CRUD +// ============================================================================= + +/// Create a new order for the given 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"); + let status = req.status.as_deref().unwrap_or("open"); + let order_type = req.order_type.as_deref().unwrap_or("feature"); + + sqlx::query_as::<_, Order>( + r#" + INSERT INTO orders (owner_id, title, description, priority, status, order_type, labels, directive_id, contract_id, repository_url) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) + RETURNING * + "#, + ) + .bind(owner_id) + .bind(&req.title) + .bind(&req.description) + .bind(priority) + .bind(status) + .bind(order_type) + .bind(&req.labels) + .bind(req.directive_id) + .bind(req.contract_id) + .bind(&req.repository_url) + .fetch_one(pool) + .await +} + +/// List orders for the given owner with optional filters. +pub async fn list_orders( + pool: &PgPool, + owner_id: Uuid, + status_filter: Option<&str>, + type_filter: Option<&str>, + priority_filter: Option<&str>, + directive_id_filter: Option<Uuid>, + contract_id_filter: Option<Uuid>, +) -> Result<Vec<Order>, sqlx::Error> { + // Build dynamic query with optional filters + let mut query = String::from("SELECT * FROM orders WHERE owner_id = $1"); + let mut param_idx = 2u32; + + if status_filter.is_some() { + query.push_str(&format!(" AND status = ${}", param_idx)); + param_idx += 1; + } + if type_filter.is_some() { + query.push_str(&format!(" AND order_type = ${}", param_idx)); + param_idx += 1; + } + if priority_filter.is_some() { + query.push_str(&format!(" AND priority = ${}", param_idx)); + param_idx += 1; + } + if directive_id_filter.is_some() { + query.push_str(&format!(" AND directive_id = ${}", param_idx)); + param_idx += 1; + } + if contract_id_filter.is_some() { + query.push_str(&format!(" AND contract_id = ${}", param_idx)); + let _ = param_idx; // suppress unused warning + } + query.push_str(" ORDER BY created_at DESC"); + + let mut q = sqlx::query_as::<_, Order>(&query).bind(owner_id); + + if let Some(s) = status_filter { + q = q.bind(s); + } + if let Some(t) = type_filter { + q = q.bind(t); + } + if let Some(p) = priority_filter { + q = q.bind(p); + } + if let Some(d) = directive_id_filter { + q = q.bind(d); + } + if let Some(c) = contract_id_filter { + q = q.bind(c); + } + + q.fetch_all(pool).await +} + +/// Get a single order by ID (owner-scoped). +pub async fn get_order( + pool: &PgPool, + owner_id: Uuid, + order_id: Uuid, +) -> Result<Option<Order>, sqlx::Error> { + sqlx::query_as::<_, Order>( + r#"SELECT * FROM orders WHERE id = $1 AND owner_id = $2"#, + ) + .bind(order_id) + .bind(owner_id) + .fetch_optional(pool) + .await +} + +/// Update an order (owner-scoped). Uses COALESCE pattern to only update provided fields. +pub async fn update_order( + pool: &PgPool, + owner_id: Uuid, + order_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(order_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 priority = req.priority.as_deref().unwrap_or(¤t.priority); + let status = req.status.as_deref().unwrap_or(¤t.status); + let order_type = req.order_type.as_deref().unwrap_or(¤t.order_type); + let labels = req.labels.as_ref().unwrap_or(¤t.labels); + let directive_id = req.directive_id.or(current.directive_id); + let directive_step_id = req.directive_step_id.or(current.directive_step_id); + let contract_id = req.contract_id.or(current.contract_id); + let repository_url = req.repository_url.as_deref().or(current.repository_url.as_deref()); + + sqlx::query_as::<_, Order>( + r#" + UPDATE orders + SET title = $3, description = $4, priority = $5, status = $6, + order_type = $7, labels = $8, directive_id = $9, directive_step_id = $10, + contract_id = $11, repository_url = $12, updated_at = NOW() + WHERE id = $1 AND owner_id = $2 + RETURNING * + "#, + ) + .bind(order_id) + .bind(owner_id) + .bind(title) + .bind(description) + .bind(priority) + .bind(status) + .bind(order_type) + .bind(labels) + .bind(directive_id) + .bind(directive_step_id) + .bind(contract_id) + .bind(repository_url) + .fetch_optional(pool) + .await +} + +/// Delete an order (owner-scoped). Returns true if a row was deleted. +pub async fn delete_order( + pool: &PgPool, + owner_id: Uuid, + order_id: Uuid, +) -> Result<bool, sqlx::Error> { + let result = sqlx::query( + r#"DELETE FROM orders WHERE id = $1 AND owner_id = $2"#, + ) + .bind(order_id) + .bind(owner_id) + .execute(pool) + .await?; + + Ok(result.rows_affected() > 0) +} + +/// Link an order to a directive. +pub async fn link_order_to_directive( + pool: &PgPool, + owner_id: Uuid, + order_id: Uuid, + directive_id: Uuid, +) -> Result<Option<Order>, sqlx::Error> { + sqlx::query_as::<_, Order>( + r#" + UPDATE orders + SET directive_id = $3, updated_at = NOW() + WHERE id = $1 AND owner_id = $2 + RETURNING * + "#, + ) + .bind(order_id) + .bind(owner_id) + .bind(directive_id) + .fetch_optional(pool) + .await +} + +/// Link an order to a contract. +pub async fn link_order_to_contract( + pool: &PgPool, + owner_id: Uuid, + order_id: Uuid, + contract_id: Uuid, +) -> Result<Option<Order>, sqlx::Error> { + sqlx::query_as::<_, Order>( + r#" + UPDATE orders + SET contract_id = $3, updated_at = NOW() + WHERE id = $1 AND owner_id = $2 + RETURNING * + "#, + ) + .bind(order_id) + .bind(owner_id) + .bind(contract_id) + .fetch_optional(pool) + .await +} + +/// Convert an order to a directive step. Creates a new DirectiveStep from the order's +/// title and description, links the order to both the directive and the new step, +/// and returns the created step. +pub async fn convert_order_to_step( + pool: &PgPool, + owner_id: Uuid, + order_id: Uuid, + directive_id: Uuid, +) -> Result<Option<DirectiveStep>, sqlx::Error> { + // Verify the order exists and belongs to this owner + let order = sqlx::query_as::<_, Order>( + r#"SELECT * FROM orders WHERE id = $1 AND owner_id = $2"#, + ) + .bind(order_id) + .bind(owner_id) + .fetch_optional(pool) + .await?; + + let order = match order { + Some(o) => o, + None => return Ok(None), + }; + + // Verify the directive exists and belongs to this owner + let directive = sqlx::query_as::<_, Directive>( + r#"SELECT * FROM directives WHERE id = $1 AND owner_id = $2"#, + ) + .bind(directive_id) + .bind(owner_id) + .fetch_optional(pool) + .await?; + + if directive.is_none() { + return Ok(None); + } + + // Get the next order_index for this directive + let max_index: (Option<i32>,) = sqlx::query_as( + r#"SELECT MAX(order_index) FROM directive_steps WHERE directive_id = $1"#, + ) + .bind(directive_id) + .fetch_one(pool) + .await?; + let next_index = max_index.0.unwrap_or(-1) + 1; + + // Create the directive step from order data + let step = sqlx::query_as::<_, DirectiveStep>( + r#" + INSERT INTO directive_steps (directive_id, name, description, order_index) + VALUES ($1, $2, $3, $4) + RETURNING * + "#, + ) + .bind(directive_id) + .bind(&order.title) + .bind(&order.description) + .bind(next_index) + .fetch_one(pool) + .await?; + + // Link the order to the directive and the new step + sqlx::query( + r#" + UPDATE orders + SET directive_id = $3, directive_step_id = $4, updated_at = NOW() + WHERE id = $1 AND owner_id = $2 + "#, + ) + .bind(order_id) + .bind(owner_id) + .bind(directive_id) + .bind(step.id) + .execute(pool) + .await?; + + Ok(Some(step)) +} + diff --git a/makima/src/server/handlers/mod.rs b/makima/src/server/handlers/mod.rs index 29cd09f..8b06a28 100644 --- a/makima/src/server/handlers/mod.rs +++ b/makima/src/server/handlers/mod.rs @@ -13,6 +13,7 @@ pub mod history; pub mod listen; pub mod mesh; pub mod mesh_chat; +pub mod orders; pub mod mesh_daemon; pub mod mesh_merge; pub mod mesh_supervisor; diff --git a/makima/src/server/handlers/orders.rs b/makima/src/server/handlers/orders.rs new file mode 100644 index 0000000..c43c406 --- /dev/null +++ b/makima/src/server/handlers/orders.rs @@ -0,0 +1,443 @@ +//! HTTP handlers for order CRUD operations. +//! Orders are card-based work items (features, bugs, spikes) similar to +//! GitHub Issues or Linear cards. + +use axum::{ + extract::{Path, Query, State}, + http::StatusCode, + response::IntoResponse, + Json, +}; +use uuid::Uuid; + +use crate::db::models::{ + ConvertToStepRequest, CreateOrderRequest, DirectiveStep, LinkContractRequest, + LinkDirectiveRequest, Order, OrderListQuery, OrderListResponse, UpdateOrderRequest, +}; +use crate::db::repository; +use crate::server::auth::Authenticated; +use crate::server::messages::ApiError; +use crate::server::state::SharedState; + +// ============================================================================= +// 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"), + ("type" = Option<String>, Query, description = "Filter by order type"), + ("priority" = Option<String>, Query, description = "Filter by priority"), + ("directive_id" = Option<Uuid>, Query, description = "Filter by directive ID"), + ("contract_id" = Option<Uuid>, Query, description = "Filter by contract ID"), + ), + 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.order_type.as_deref(), + query.priority.as_deref(), + query.directive_id, + query.contract_id, + ) + .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 = 401, description = "Unauthorized", 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, auth.owner_id, 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( + patch, + 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 = 401, description = "Unauthorized", 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, auth.owner_id, 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 = 401, description = "Unauthorized", 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, auth.owner_id, 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 & Conversion +// ============================================================================= + +/// Link an order to a directive. +#[utoipa::path( + post, + path = "/api/v1/orders/{id}/link-directive", + params(("id" = Uuid, Path, description = "Order ID")), + request_body = LinkDirectiveRequest, + responses( + (status = 200, description = "Order linked to directive", body = Order), + (status = 404, description = "Not found", body = ApiError), + (status = 401, description = "Unauthorized", body = ApiError), + (status = 503, description = "Database not configured", body = ApiError), + ), + security(("bearer_auth" = []), ("api_key" = [])), + tag = "Orders" +)] +pub async fn link_to_directive( + State(state): State<SharedState>, + Authenticated(auth): Authenticated, + Path(id): Path<Uuid>, + Json(req): Json<LinkDirectiveRequest>, +) -> impl IntoResponse { + let Some(ref pool) = state.db_pool else { + return ( + StatusCode::SERVICE_UNAVAILABLE, + Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")), + ) + .into_response(); + }; + + // Verify the directive exists and belongs to this owner + match repository::get_directive_for_owner(pool, auth.owner_id, req.directive_id).await { + Ok(Some(_)) => {} + Ok(None) => { + return ( + StatusCode::NOT_FOUND, + Json(ApiError::new("NOT_FOUND", "Directive not found")), + ) + .into_response(); + } + Err(e) => { + return ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(ApiError::new("GET_FAILED", &e.to_string())), + ) + .into_response(); + } + } + + match repository::link_order_to_directive(pool, auth.owner_id, id, req.directive_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 link order to directive: {}", e); + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(ApiError::new("LINK_FAILED", &e.to_string())), + ) + .into_response() + } + } +} + +/// Link an order to a contract. +#[utoipa::path( + post, + path = "/api/v1/orders/{id}/link-contract", + params(("id" = Uuid, Path, description = "Order ID")), + request_body = LinkContractRequest, + responses( + (status = 200, description = "Order linked to contract", body = Order), + (status = 404, description = "Not found", body = ApiError), + (status = 401, description = "Unauthorized", body = ApiError), + (status = 503, description = "Database not configured", body = ApiError), + ), + security(("bearer_auth" = []), ("api_key" = [])), + tag = "Orders" +)] +pub async fn link_to_contract( + State(state): State<SharedState>, + Authenticated(auth): Authenticated, + Path(id): Path<Uuid>, + Json(req): Json<LinkContractRequest>, +) -> impl IntoResponse { + let Some(ref pool) = state.db_pool else { + return ( + StatusCode::SERVICE_UNAVAILABLE, + Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")), + ) + .into_response(); + }; + + // Verify the contract exists and belongs to this owner + match repository::get_contract_for_owner(pool, auth.owner_id, req.contract_id).await { + Ok(Some(_)) => {} + Ok(None) => { + return ( + StatusCode::NOT_FOUND, + Json(ApiError::new("NOT_FOUND", "Contract not found")), + ) + .into_response(); + } + Err(e) => { + return ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(ApiError::new("GET_FAILED", &e.to_string())), + ) + .into_response(); + } + } + + match repository::link_order_to_contract(pool, auth.owner_id, id, req.contract_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 link order to contract: {}", e); + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(ApiError::new("LINK_FAILED", &e.to_string())), + ) + .into_response() + } + } +} + +/// Convert an order to a directive step. +/// Creates a new step in the specified directive using the order's title/description, +/// and links the order to both the directive and the new step. +#[utoipa::path( + post, + path = "/api/v1/orders/{id}/convert-to-step", + params(("id" = Uuid, Path, description = "Order ID")), + request_body = ConvertToStepRequest, + responses( + (status = 201, description = "Directive step created from order", body = DirectiveStep), + (status = 404, description = "Order or directive not found", body = ApiError), + (status = 401, description = "Unauthorized", body = ApiError), + (status = 503, description = "Database not configured", body = ApiError), + ), + security(("bearer_auth" = []), ("api_key" = [])), + tag = "Orders" +)] +pub async fn convert_to_step( + State(state): State<SharedState>, + Authenticated(auth): Authenticated, + Path(id): Path<Uuid>, + Json(req): Json<ConvertToStepRequest>, +) -> 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::convert_order_to_step(pool, auth.owner_id, id, req.directive_id).await { + Ok(Some(step)) => (StatusCode::CREATED, Json(step)).into_response(), + Ok(None) => ( + StatusCode::NOT_FOUND, + Json(ApiError::new("NOT_FOUND", "Order or directive not found")), + ) + .into_response(), + Err(e) => { + tracing::error!("Failed to convert order to step: {}", e); + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(ApiError::new("CONVERT_FAILED", &e.to_string())), + ) + .into_response() + } + } +} diff --git a/makima/src/server/mod.rs b/makima/src/server/mod.rs index c1e1309..29c55c4 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; @@ -238,6 +238,20 @@ pub fn make_router(state: SharedState) -> Router { .route("/directives/{id}/steps/{step_id}/skip", post(directives::skip_step)) .route("/directives/{id}/goal", put(directives::update_goal)) .route("/directives/{id}/cleanup-tasks", post(directives::cleanup_tasks)) + // Order endpoints + .route( + "/orders", + get(orders::list_orders).post(orders::create_order), + ) + .route( + "/orders/{id}", + get(orders::get_order) + .patch(orders::update_order) + .delete(orders::delete_order), + ) + .route("/orders/{id}/link-directive", post(orders::link_to_directive)) + .route("/orders/{id}/link-contract", post(orders::link_to_contract)) + .route("/orders/{id}/convert-to-step", post(orders::convert_to_step)) // Timeline endpoint (unified history for user) .route("/timeline", get(history::get_timeline)) // Contract type templates (built-in only) diff --git a/makima/src/server/openapi.rs b/makima/src/server/openapi.rs index e68286e..b21dab9 100644 --- a/makima/src/server/openapi.rs +++ b/makima/src/server/openapi.rs @@ -8,26 +8,30 @@ use crate::db::models::{ ChangePhaseRequest, Contract, ContractChatHistoryResponse, ContractChatMessageRecord, ContractEvent, ContractListResponse, ContractRepository, ContractSummary, ContractWithRelations, - CleanupTasksResponse, + CleanupTasksResponse, ConvertToStepRequest, CreateContractRequest, CreateDirectiveRequest, CreateDirectiveStepRequest, CreateFileRequest, - CreateManagedRepositoryRequest, CreateTaskRequest, Daemon, DaemonDirectoriesResponse, + CreateManagedRepositoryRequest, CreateOrderRequest, CreateTaskRequest, + Daemon, DaemonDirectoriesResponse, DaemonDirectory, DaemonListResponse, Directive, DirectiveListResponse, DirectiveStep, DirectiveSummary, DirectiveWithSteps, File, FileListResponse, FileSummary, + LinkContractRequest, LinkDirectiveRequest, MergeCommitRequest, MergeCompleteCheckResponse, MergeResolveRequest, MergeResultResponse, MergeSkipRequest, MergeStartRequest, MergeStatusResponse, MeshChatConversation, - MeshChatHistoryResponse, MeshChatMessageRecord, RepositoryHistoryEntry, + MeshChatHistoryResponse, MeshChatMessageRecord, + Order, OrderListResponse, OrderListQuery, + RepositoryHistoryEntry, RepositoryHistoryListResponse, RepositorySuggestionsQuery, SendMessageRequest, Task, TaskEventListResponse, TaskListResponse, TaskSummary, TaskWithSubtasks, TranscriptEntry, UpdateContractRequest, UpdateDirectiveRequest, UpdateDirectiveStepRequest, - UpdateFileRequest, UpdateGoalRequest, UpdateTaskRequest, + UpdateFileRequest, UpdateGoalRequest, UpdateOrderRequest, UpdateTaskRequest, }; use crate::server::auth::{ ApiKey, ApiKeyInfoResponse, CreateApiKeyRequest, CreateApiKeyResponse, RefreshApiKeyRequest, RefreshApiKeyResponse, RevokeApiKeyResponse, }; -use crate::server::handlers::{api_keys, contract_chat, contract_discuss, contracts, directives, files, listen, mesh, mesh_chat, mesh_merge, repository_history, users}; +use crate::server::handlers::{api_keys, contract_chat, contract_discuss, contracts, directives, files, listen, mesh, mesh_chat, mesh_merge, orders, repository_history, users}; use crate::server::messages::{ApiError, AudioEncoding, StartMessage, StopMessage, TranscriptMessage}; #[derive(OpenApi)] @@ -125,6 +129,15 @@ use crate::server::messages::{ApiError, AudioEncoding, StartMessage, StopMessage directives::skip_step, directives::update_goal, directives::cleanup_tasks, + // Order endpoints + orders::list_orders, + orders::create_order, + orders::get_order, + orders::update_order, + orders::delete_order, + orders::link_to_directive, + orders::link_to_contract, + orders::convert_to_step, // Repository history/settings endpoints repository_history::list_repository_history, repository_history::get_repository_suggestions, @@ -222,6 +235,15 @@ use crate::server::messages::{ApiError, AudioEncoding, StartMessage, StopMessage CreateDirectiveStepRequest, UpdateDirectiveStepRequest, CleanupTasksResponse, + // Order schemas + Order, + OrderListResponse, + OrderListQuery, + CreateOrderRequest, + UpdateOrderRequest, + LinkDirectiveRequest, + LinkContractRequest, + ConvertToStepRequest, // Repository history schemas RepositoryHistoryEntry, RepositoryHistoryListResponse, @@ -236,6 +258,7 @@ use crate::server::messages::{ApiError, AudioEncoding, StartMessage, StopMessage (name = "API Keys", description = "API key management for programmatic access"), (name = "Users", description = "User account management"), (name = "Directives", description = "Directive management with DAG-based step progression"), + (name = "Orders", description = "Order management — card-based issue tracking for planned work items"), (name = "Settings", description = "User settings including repository history"), ) )] |
