summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--makima/migrations/20260213000000_create_orders.sql22
-rw-r--r--makima/src/db/models.rs59
-rw-r--r--makima/src/db/repository.rs268
-rw-r--r--makima/src/server/handlers/mod.rs1
-rw-r--r--makima/src/server/handlers/orders.rs414
-rw-r--r--makima/src/server/mod.rs16
6 files changed, 779 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..06ed40d
--- /dev/null
+++ b/makima/migrations/20260213000000_create_orders.sql
@@ -0,0 +1,22 @@
+-- Orders: lightweight work items similar to issues/cards
+CREATE TABLE IF NOT EXISTS 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,
+ order_type VARCHAR(32) NOT NULL DEFAULT 'feature',
+ priority VARCHAR(32) NOT NULL DEFAULT 'medium',
+ status VARCHAR(32) NOT NULL DEFAULT 'backlog',
+ directive_id UUID REFERENCES directives(id) ON DELETE SET NULL,
+ contract_id UUID REFERENCES contracts(id) ON DELETE SET NULL,
+ labels JSONB DEFAULT '[]',
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+);
+
+CREATE INDEX idx_orders_owner_id ON orders(owner_id);
+CREATE INDEX idx_orders_status ON orders(status);
+CREATE INDEX idx_orders_directive_id ON orders(directive_id);
+CREATE INDEX idx_orders_contract_id ON orders(contract_id);
+CREATE INDEX idx_orders_priority ON orders(priority);
+CREATE INDEX idx_orders_order_type ON orders(order_type);
diff --git a/makima/src/db/models.rs b/makima/src/db/models.rs
index 66c0a30..11e0ac1 100644
--- a/makima/src/db/models.rs
+++ b/makima/src/db/models.rs
@@ -2893,3 +2893,62 @@ pub struct DirectiveMemoryListResponse {
pub memories: Vec<DirectiveMemory>,
pub total: i64,
}
+
+// =============================================================================
+// Order Types (lightweight work items / issues)
+// =============================================================================
+
+/// An order — a lightweight work item similar to a GitHub Issue or Linear card.
+/// Orders can be created independently and optionally attached 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>,
+ /// Type: feature, bugfix, spike, chore
+ pub order_type: String,
+ /// Priority: low, medium, high, critical
+ pub priority: String,
+ /// Status: backlog, ready, in_progress, done, archived
+ pub status: String,
+ pub directive_id: Option<Uuid>,
+ pub contract_id: Option<Uuid>,
+ pub labels: serde_json::Value,
+ 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 order_type: Option<String>,
+ pub priority: Option<String>,
+ pub labels: Option<Vec<String>>,
+}
+
+/// Request to update an order.
+#[derive(Debug, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct UpdateOrderRequest {
+ pub title: Option<String>,
+ pub description: Option<String>,
+ pub order_type: Option<String>,
+ pub priority: Option<String>,
+ pub status: Option<String>,
+ pub directive_id: Option<Option<Uuid>>,
+ pub contract_id: Option<Option<Uuid>>,
+ pub labels: Option<Vec<String>>,
+}
+
+/// Response for order list endpoint.
+#[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..d17e9be 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,
};
/// Repository error types.
@@ -6020,3 +6021,270 @@ 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_for_owner(
+ pool: &PgPool,
+ owner_id: Uuid,
+ req: CreateOrderRequest,
+) -> Result<Order, sqlx::Error> {
+ let order_type = req.order_type.as_deref().unwrap_or("feature");
+ let priority = req.priority.as_deref().unwrap_or("medium");
+ let labels = match req.labels {
+ Some(ref l) => serde_json::to_value(l).unwrap_or_else(|_| serde_json::json!([])),
+ None => serde_json::json!([]),
+ };
+
+ sqlx::query_as::<_, Order>(
+ r#"
+ INSERT INTO orders (owner_id, title, description, order_type, priority, labels)
+ VALUES ($1, $2, $3, $4, $5, $6)
+ RETURNING *
+ "#,
+ )
+ .bind(owner_id)
+ .bind(&req.title)
+ .bind(&req.description)
+ .bind(order_type)
+ .bind(priority)
+ .bind(&labels)
+ .fetch_one(pool)
+ .await
+}
+
+/// Get a single order by ID (no ownership check).
+pub async fn get_order(
+ pool: &PgPool,
+ id: Uuid,
+) -> Result<Option<Order>, sqlx::Error> {
+ sqlx::query_as::<_, Order>(
+ r#"SELECT * FROM orders WHERE id = $1"#,
+ )
+ .bind(id)
+ .fetch_optional(pool)
+ .await
+}
+
+/// Get a single order for an owner.
+pub async fn get_order_for_owner(
+ pool: &PgPool,
+ owner_id: Uuid,
+ 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 all orders for an owner.
+pub async fn list_orders_for_owner(
+ pool: &PgPool,
+ owner_id: Uuid,
+) -> Result<Vec<Order>, sqlx::Error> {
+ sqlx::query_as::<_, Order>(
+ r#"
+ SELECT * FROM orders
+ WHERE owner_id = $1
+ ORDER BY
+ CASE priority
+ WHEN 'critical' THEN 0
+ WHEN 'high' THEN 1
+ WHEN 'medium' THEN 2
+ WHEN 'low' THEN 3
+ ELSE 4
+ END,
+ created_at DESC
+ "#,
+ )
+ .bind(owner_id)
+ .fetch_all(pool)
+ .await
+}
+
+/// Update an order for an owner.
+pub async fn update_order_for_owner(
+ pool: &PgPool,
+ owner_id: Uuid,
+ 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(&current.title);
+ let description = match &req.description {
+ Some(d) => Some(d.as_str()),
+ None => current.description.as_deref(),
+ };
+ let order_type = req.order_type.as_deref().unwrap_or(&current.order_type);
+ let priority = req.priority.as_deref().unwrap_or(&current.priority);
+ let status = req.status.as_deref().unwrap_or(&current.status);
+ let directive_id = match req.directive_id {
+ Some(d) => d,
+ None => current.directive_id,
+ };
+ let contract_id = match req.contract_id {
+ Some(c) => c,
+ None => current.contract_id,
+ };
+ let labels = match req.labels {
+ Some(ref l) => serde_json::to_value(l).unwrap_or_else(|_| serde_json::json!([])),
+ None => current.labels.clone(),
+ };
+
+ sqlx::query_as::<_, Order>(
+ r#"
+ UPDATE orders
+ SET title = $3, description = $4, order_type = $5, priority = $6,
+ status = $7, directive_id = $8, contract_id = $9, labels = $10,
+ updated_at = NOW()
+ WHERE id = $1 AND owner_id = $2
+ RETURNING *
+ "#,
+ )
+ .bind(id)
+ .bind(owner_id)
+ .bind(title)
+ .bind(description)
+ .bind(order_type)
+ .bind(priority)
+ .bind(status)
+ .bind(directive_id)
+ .bind(contract_id)
+ .bind(&labels)
+ .fetch_optional(pool)
+ .await
+}
+
+/// Delete an order for an owner.
+pub async fn delete_order_for_owner(
+ pool: &PgPool,
+ owner_id: Uuid,
+ 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)
+}
+
+/// List orders attached to a directive.
+pub async fn list_orders_for_directive(
+ pool: &PgPool,
+ directive_id: Uuid,
+) -> Result<Vec<Order>, sqlx::Error> {
+ sqlx::query_as::<_, Order>(
+ r#"
+ SELECT * FROM orders
+ WHERE directive_id = $1
+ ORDER BY created_at DESC
+ "#,
+ )
+ .bind(directive_id)
+ .fetch_all(pool)
+ .await
+}
+
+/// List orders attached to a contract.
+pub async fn list_orders_for_contract(
+ pool: &PgPool,
+ contract_id: Uuid,
+) -> Result<Vec<Order>, sqlx::Error> {
+ sqlx::query_as::<_, Order>(
+ r#"
+ SELECT * FROM orders
+ WHERE contract_id = $1
+ ORDER BY created_at DESC
+ "#,
+ )
+ .bind(contract_id)
+ .fetch_all(pool)
+ .await
+}
+
+/// Attach an order to a directive.
+pub async fn attach_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
+}
+
+/// Attach an order to a contract.
+pub async fn attach_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
+}
+
+/// Detach an order from both directive and contract.
+pub async fn detach_order(
+ pool: &PgPool,
+ owner_id: Uuid,
+ order_id: Uuid,
+) -> Result<Option<Order>, sqlx::Error> {
+ sqlx::query_as::<_, Order>(
+ r#"
+ UPDATE orders
+ SET directive_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..94c409c 100644
--- a/makima/src/server/handlers/mod.rs
+++ b/makima/src/server/handlers/mod.rs
@@ -14,6 +14,7 @@ pub mod listen;
pub mod mesh;
pub mod mesh_chat;
pub mod mesh_daemon;
+pub mod orders;
pub mod mesh_merge;
pub mod mesh_supervisor;
pub mod mesh_ws;
diff --git a/makima/src/server/handlers/orders.rs b/makima/src/server/handlers/orders.rs
new file mode 100644
index 0000000..0850645
--- /dev/null
+++ b/makima/src/server/handlers/orders.rs
@@ -0,0 +1,414 @@
+//! HTTP handlers for order CRUD operations.
+
+use axum::{
+ extract::{Path, State},
+ http::StatusCode,
+ response::IntoResponse,
+ Json,
+};
+use uuid::Uuid;
+
+use crate::db::models::{
+ CreateOrderRequest, Order, 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",
+ 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,
+) -> 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_for_owner(pool, auth.owner_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_for_owner(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 a single order.
+#[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_for_owner(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(
+ 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_for_owner(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 = 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_for_owner(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 Attach/Detach
+// =============================================================================
+
+/// Attach an order to a directive.
+#[utoipa::path(
+ post,
+ path = "/api/v1/orders/{id}/attach/directive/{directive_id}",
+ params(
+ ("id" = Uuid, Path, description = "Order ID"),
+ ("directive_id" = Uuid, Path, description = "Directive ID"),
+ ),
+ responses(
+ (status = 200, description = "Order attached to directive", 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 attach_directive(
+ State(state): State<SharedState>,
+ Authenticated(auth): Authenticated,
+ Path((id, directive_id)): Path<(Uuid, 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();
+ };
+
+ // Verify directive exists and belongs to the owner
+ match repository::get_directive_for_owner(pool, auth.owner_id, 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::attach_order_to_directive(pool, auth.owner_id, id, 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 attach order to directive: {}", e);
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ApiError::new("ATTACH_FAILED", &e.to_string())),
+ )
+ .into_response()
+ }
+ }
+}
+
+/// Attach an order to a contract.
+#[utoipa::path(
+ post,
+ path = "/api/v1/orders/{id}/attach/contract/{contract_id}",
+ params(
+ ("id" = Uuid, Path, description = "Order ID"),
+ ("contract_id" = Uuid, Path, description = "Contract ID"),
+ ),
+ responses(
+ (status = 200, description = "Order attached to contract", 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 attach_contract(
+ State(state): State<SharedState>,
+ Authenticated(auth): Authenticated,
+ Path((id, contract_id)): Path<(Uuid, 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();
+ };
+
+ // Verify contract exists and belongs to the owner
+ match repository::get_contract_for_owner(pool, auth.owner_id, 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::attach_order_to_contract(pool, auth.owner_id, id, 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 attach order to contract: {}", e);
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ApiError::new("ATTACH_FAILED", &e.to_string())),
+ )
+ .into_response()
+ }
+ }
+}
+
+/// Detach an order from both directive and contract.
+#[utoipa::path(
+ post,
+ path = "/api/v1/orders/{id}/detach",
+ params(("id" = Uuid, Path, description = "Order ID")),
+ responses(
+ (status = 200, description = "Order detached", 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 detach_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::detach_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 detach order: {}", e);
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ApiError::new("DETACH_FAILED", &e.to_string())),
+ )
+ .into_response()
+ }
+ }
+}
diff --git a/makima/src/server/mod.rs b/makima/src/server/mod.rs
index 7110ef8..f5ba49a 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,20 @@ 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}/attach/directive/{directive_id}", post(orders::attach_directive))
+ .route("/orders/{id}/attach/contract/{contract_id}", post(orders::attach_contract))
+ .route("/orders/{id}/detach", post(orders::detach_order))
// Timeline endpoint (unified history for user)
.route("/timeline", get(history::get_timeline))
// Contract type templates (built-in only)