Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

13.2 KB
Raw Blame
//! Read-use-case policy, pagination and visibility.

use std::{cmp::Ordering, collections::HashMap};

use chrono::{DateTime, Utc};
use entity_access::domain::models::{
    Entity, EntityAccessAuth, EntityAccessReceipt, EntityType, ViewAccessLevel,
};
use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use serde::{Deserialize, Serialize};

use super::{InitiativeServiceImpl, receipt_access_level};
use crate::domain::{
    models::{InitiativeError, InitiativeId},
    ports::{InitiativeDescriptionSurfaces, InitiativeRepo, InitiativeService},
    reads::{
        InitiativePage, InitiativePageRequest, InitiativePageRow, InitiativeRead, InitiativeSort,
        InitiativeTasksPage, InitiativeTasksRequest, MAX_CURSOR_LENGTH, page_size as limit,
    },
};

struct Position {
    id: InitiativeId,
    name: String,
    updated_at: DateTime<Utc>,
    due_date: Option<DateTime<Utc>>,
}

impl From<&InitiativePageRow> for Position {
    fn from(row: &InitiativePageRow) -> Self {
        Self {
            id: row.initiative.id,
            name: row.initiative.name.to_lowercase(),
            updated_at: row.initiative.updated_at,
            due_date: row.properties.due_date,
        }
    }
}

#[derive(Serialize, Deserialize)]
struct Cursor {
    sort: InitiativeSort,
    descending: bool,
    position: CursorPosition,
}

/// Keep continuation tokens bounded independently of Unicode name byte length.
#[derive(Serialize, Deserialize)]
#[serde(tag = "key", rename_all = "camelCase")]
enum CursorPosition {
    Updated {
        id: InitiativeId,
        updated_at: DateTime<Utc>,
    },
    Name {
        id: InitiativeId,
        updated_at: DateTime<Utc>,
    },
    Due {
        id: InitiativeId,
        due_date: Option<DateTime<Utc>>,
    },
}

impl CursorPosition {
    fn from_row(row: &InitiativePageRow, sort: InitiativeSort) -> Self {
        let id = row.initiative.id;
        match sort {
            InitiativeSort::Updated => Self::Updated {
                id,
                updated_at: row.initiative.updated_at,
            },
            InitiativeSort::Name => Self::Name {
                id,
                updated_at: row.initiative.updated_at,
            },
            InitiativeSort::Due => Self::Due {
                id,
                due_date: row.properties.due_date,
            },
        }
    }

    fn resolve(
        self,
        sort: InitiativeSort,
        rows: &[InitiativePageRow],
    ) -> Result<Position, InitiativeError> {
        match (self, sort) {
            (Self::Updated { id, updated_at }, InitiativeSort::Updated) => Ok(Position {
                id,
                name: String::new(),
                updated_at,
                due_date: None,
            }),
            (Self::Due { id, due_date }, InitiativeSort::Due) => Ok(Position {
                id,
                name: String::new(),
                updated_at: DateTime::UNIX_EPOCH,
                due_date,
            }),
            (Self::Name { id, updated_at }, InitiativeSort::Name) => rows
                .iter()
                // A renamed anchor must not silently move the continuation point.
                // Names have no byte bound, so keep a bounded row version instead
                // of embedding their potentially unbounded sort key in the cursor.
                .find(|row| row.initiative.id == id && row.initiative.updated_at == updated_at)
                .map(Into::into)
                .ok_or_else(|| {
                    InitiativeError::BadRequest(
                        "cursor anchor changed or is unavailable; restart pagination".into(),
                    )
                }),
            _ => Err(InitiativeError::BadRequest(
                "cursor ordering differs from request".into(),
            )),
        }
    }
}

fn order(left: &Position, right: &Position, sort: InitiativeSort, descending: bool) -> Ordering {
    if sort == InitiativeSort::Due {
        match (left.due_date, right.due_date) {
            (None, Some(_)) => return Ordering::Greater,
            (Some(_), None) => return Ordering::Less,
            _ => (),
        }
    }
    let order = match sort {
        InitiativeSort::Updated => left.updated_at.cmp(&right.updated_at),
        InitiativeSort::Name => left.name.cmp(&right.name),
        InitiativeSort::Due => left.due_date.cmp(&right.due_date),
    }
    .then_with(|| left.id.as_uuid().cmp(&right.id.as_uuid()));
    if descending { order.reverse() } else { order }
}

impl<R: InitiativeRepo, S: InitiativeDescriptionSurfaces> InitiativeServiceImpl<R, S> {
    pub(super) async fn read_summary(
        &self,
        read: &InitiativeRead,
    ) -> Result<InitiativePageRow, InitiativeError> {
        let detail = read.detail();
        let tasks = read.task_receipts();
        let mut properties = self
            .resources
            .properties(
                std::iter::once(read.receipt())
                    .chain(tasks)
                    .cloned()
                    .collect(),
            )
            .await?;
        let completed_task_count = tasks
            .iter()
            .filter(|task| {
                properties
                    .get(&task.entity().entity_id)
                    .is_some_and(|value| value.completed)
            })
            .count();
        Ok(InitiativePageRow {
            initiative: crate::domain::models::InitiativeSummary {
                id: detail.id,
                name: detail.name.clone(),
                updated_at: detail.updated_at,
            },
            user_access_level: detail.user_access_level,
            properties: properties
                .remove(&detail.id.to_string())
                .unwrap_or_default(),
            task_count: u32::try_from(tasks.len()).unwrap_or(u32::MAX),
            completed_task_count: u32::try_from(completed_task_count).unwrap_or(u32::MAX),
        })
    }

    pub(super) async fn visible_tasks(
        &self,
        auth: &EntityAccessAuth,
        ids: Vec<String>,
    ) -> Result<Vec<EntityAccessReceipt<ViewAccessLevel>>, InitiativeError> {
        let mut visible = Vec::new();
        for id in ids {
            if let Some(receipt) = self
                .resources
                .view(
                    auth.clone(),
                    Entity {
                        entity_id: id,
                        entity_type: EntityType::Document,
                    },
                )
                .await?
            {
                visible.push(receipt);
            }
        }
        Ok(visible)
    }

    pub(super) async fn read_page(
        &self,
        user_id: &MacroUserIdStr<'_>,
        request: InitiativePageRequest,
    ) -> Result<InitiativePage, InitiativeError> {
        let size = limit(request.limit)?;
        if request
            .query
            .as_ref()
            .is_some_and(|query| query.len() > 400)
        {
            return Err(InitiativeError::BadRequest("search query too long".into()));
        }
        if matches!((request.due_after, request.due_before), (Some(after), Some(before)) if after > before)
        {
            return Err(InitiativeError::BadRequest(
                "dueAfter must precede dueBefore".into(),
            ));
        }
        let descending = request
            .descending
            .unwrap_or(request.sort == InitiativeSort::Updated);
        let cursor: Option<Cursor> = request
            .cursor
            .as_ref()
            .map(|cursor| {
                if cursor.len() > MAX_CURSOR_LENGTH {
                    return Err(InitiativeError::BadRequest("invalid cursor".into()));
                }
                serde_json::from_str(cursor)
                    .map_err(|_| InitiativeError::BadRequest("invalid cursor".into()))
            })
            .transpose()?;
        if cursor
            .as_ref()
            .is_some_and(|cursor| cursor.sort != request.sort || cursor.descending != descending)
        {
            return Err(InitiativeError::BadRequest(
                "cursor ordering differs from request".into(),
            ));
        }
        let auth = EntityAccessAuth::Authenticated(user_id.clone().into_owned());
        let query = request.query.as_deref().unwrap_or("").trim().to_lowercase();
        let candidates = self
            .repo
            .list_accessible(&user_id.clone().into_owned())
            .await
            .map_err(Into::into)?;
        let mut authorized = Vec::new();
        for project in candidates.initiatives {
            if !project.name.to_lowercase().contains(&query) {
                continue;
            }
            if let Some(receipt) = self
                .resources
                .view(
                    auth.clone(),
                    Entity {
                        entity_id: project.id.to_string(),
                        entity_type: EntityType::Initiative,
                    },
                )
                .await?
            {
                authorized.push((project, receipt));
            }
        }
        let mut properties = self
            .resources
            .properties(
                authorized
                    .iter()
                    .map(|(_, receipt)| receipt.clone())
                    .collect(),
            )
            .await?;
        let mut rows = Vec::new();
        for (initiative, receipt) in authorized {
            let values = properties
                .remove(&initiative.id.to_string())
                .unwrap_or_default();
            if request
                .status
                .is_some_and(|status| values.status != Some(status))
                || request
                    .priority
                    .is_some_and(|priority| values.priority != Some(priority))
                || request
                    .assignee
                    .as_ref()
                    .is_some_and(|id| !values.assignees.contains(id))
                || request
                    .due_after
                    .is_some_and(|date| values.due_date.is_none_or(|due| due < date))
                || request
                    .due_before
                    .is_some_and(|date| values.due_date.is_none_or(|due| due > date))
            {
                continue;
            }
            rows.push(InitiativePageRow {
                initiative,
                user_access_level: receipt_access_level(&receipt)?,
                properties: values,
                task_count: 0,
                completed_task_count: 0,
            });
        }
        rows.sort_by(|left, right| order(&left.into(), &right.into(), request.sort, descending));
        if let Some(cursor) = cursor {
            let position = cursor.position.resolve(request.sort, &rows)?;
            rows.retain(|row| {
                order(&row.into(), &position, request.sort, descending) == Ordering::Greater
            });
        }
        let has_more = rows.len() > size;
        rows.truncate(size);
        let next_cursor = if has_more {
            rows.last()
                .map(|last| {
                    serde_json::to_string(&Cursor {
                        sort: request.sort,
                        descending,
                        position: CursorPosition::from_row(last, request.sort),
                    })
                    .map_err(|error| InitiativeError::Internal(rootcause::report!(error).into()))
                })
                .transpose()?
        } else {
            None
        };
        // Hydrate progress only for the selected page, using current task access.
        let mut tasks_by_project = HashMap::new();
        let mut task_receipts = Vec::new();
        for row in &rows {
            let mut ids = Vec::new();
            for id in self.resources.project_tasks(row.initiative.id).await? {
                if let Some(receipt) = self
                    .resources
                    .view(
                        auth.clone(),
                        Entity {
                            entity_id: id.clone(),
                            entity_type: EntityType::Document,
                        },
                    )
                    .await?
                {
                    ids.push(id);
                    task_receipts.push(receipt);
                }
            }
            tasks_by_project.insert(row.initiative.id, ids);
        }
        let task_properties = self.resources.properties(task_receipts).await?;
        for row in &mut rows {
            if let Some(ids) = tasks_by_project.get(&row.initiative.id) {
                row.task_count = u32::try_from(ids.len()).unwrap_or(u32::MAX);
                row.completed_task_count = u32::try_from(
                    ids.iter()
                        .filter(|id| {
                            task_properties
                                .get(*id)
                                .is_some_and(|properties| properties.completed)
                        })
                        .count(),
                )
                .unwrap_or(u32::MAX);
            }
        }
        Ok(InitiativePage {
            initiatives: rows,
            next_cursor,
        })
    }

    pub(super) async fn read_tasks_page(
        &self,
        receipt: EntityAccessReceipt<ViewAccessLevel>,
        request: InitiativeTasksRequest,
    ) -> Result<InitiativeTasksPage, InitiativeError> {
        request.validate()?;
        self.get(receipt).await?.task_page(request)
    }
}