diff --git a/docs/My-Egeria-Doc.md b/docs/My-Egeria-Doc.md index 1913fc7f..e4bb3ba1 100644 --- a/docs/My-Egeria-Doc.md +++ b/docs/My-Egeria-Doc.md @@ -33,6 +33,8 @@ All source files named here are in `my_egeria/my_egeria/`. | `network_handler.py`, `MyNetworkScreen.py` | `NetworkMixin` (peers linked by `Peer` relationships), `MyNetworkScreen` and `ConfirmRemovePeerScreen` | | `community_handler.py`, `CommunitiesScreen.py` | `CommunitiesMixin` (community membership through `AssignmentScope` relationships, resources, feedback on posts and resources), `CommunitiesScreen`, `CreateCommunityScreen` and `ConfirmLeaveCommunityScreen` | | `CommunityScreen.py` | `CommunityScreen` (one community's members, blog, resources and comments, and joining it), `NewBlogPostScreen`, `AddCommunityCommentScreen`, `ElementFeedbackScreen` (likes, ratings and comments on a blog post or resource) and `RateElementScreen` | +| `project_handler.py`, `ProjectsScreen.py` | `ProjectsMixin` (project membership through `AssignmentScope` relationships, team members, resources & dependencies, blog notes, comments), `ProjectsScreen`, `CreateProjectScreen` and `ConfirmLeaveProjectScreen` | +| `ProjectScreen.py` | `ProjectScreen` (one project's members, blog, resources & dependencies, and comments, and joining it), `NewProjectBlogPostScreen` and `AddProjectCommentScreen` | | `paging_support.py` | Egeria's paging contract as the handlers use it: `read_all`/`PagedRows`, the "at least" and "none" words, and the found / absent / unknown guards that writes check first (see [Paging and write guards](#paging-and-write-guards)) | | `UserIdentitiesScreen.py` | Read-only user identity table | | `StatusScreen.py` | Result message with copy-GUID | @@ -94,6 +96,18 @@ classDiagram get_element_feedback() / add_element_comment() like_element() / unlike_element() / rate_element() } + class ProjectsMixin { + show_projects(find) + open_project_row() + list_my_projects() + search_projects() + get_project_members() + get_project_resources() + create_project() + join_project() / leave_project() + get_project_blog_posts() / add_project_blog_post() + get_project_comments() / add_project_comment() + } App <|-- MyProfileApp TechTypesMixin <|-- MyProfileApp ShopForDataMixin <|-- MyProfileApp @@ -103,6 +117,7 @@ classDiagram BookmarksMixin <|-- MyProfileApp NetworkMixin <|-- MyProfileApp CommunitiesMixin <|-- MyProfileApp + ProjectsMixin <|-- MyProfileApp ``` - **App bindings:** @@ -196,12 +211,11 @@ It returns `200` on success and `401` on failure. | `blogs_table`, `journal_table` | Note Logs from `My-User-MD` | | | `todos_table` | `MyProfile.get_my_to_dos(report_spec="My-User-ToDos")` | | | `user_identity_table` | `MyProfile.get_my_profile(report_spec="User-Identities")` | | - -| `projects_table` | Projects from `My-User-MD` | | +| `projects_table` | Projects from `My-User-MD` | `Enter` on a row opens that project: `_on_projects_row_selected` → `open_project_row` → `ProjectScreen` | `communities_table` is not on the main screen (communities show in User Associations); `_populate_tables_sync` skips any table that isn't composed. -`MainScreen` tracks the selected table and row through focus, highlight, select and cell events. It uses them for `ctrl+t` (edit table), `ctrl+n` (add comment), `ctrl+o` (show comments), `ctrl+k` (bookmark the row) and `ctrl+b` (bookmarks), and `Enter` on a User Associations row opens that community. +`MainScreen` tracks the selected table and row through focus, highlight, select and cell events. It uses them for `ctrl+t` (edit table), `ctrl+n` (add comment), `ctrl+o` (show comments), `ctrl+k` (bookmark the row) and `ctrl+b` (bookmarks), and `Enter` on a User Associations or Projects row opens that community or project. ### Other Functions menu dispatch (`handle_option_selected`) @@ -216,6 +230,8 @@ It returns `200` on success and `401` on failure. | My Network | `show_my_network()` | | Work with Communities | `show_communities()` | | Find Community | `show_communities(find=True)`: the same screen, with focus on the search input | +| Work with Projects | `show_projects()` | +| Find Project | `show_projects(find=True)`: the same screen, with focus on the search input | | Change User | `ChangeUserScreen()`, callback `change_user_callback` | | Leave Feedback | `action_feedback()` | | Feedback Log | `action_view_feedback_log()` (owner only) | @@ -743,6 +759,124 @@ sequenceDiagram --- +## Work with Projects + +A user belongs to a project when an actor is linked to it by an `AssignmentScope` relationship, whose `assignmentType` says how they take part. The actor is either the user's own profile or a role they are appointed to. A project's blog is a `NoteLog` attached to it holding `BlogEntry` notes, and comments are attached to the project directly. Its resources are the elements it lists with `ResourceList` relationships, elements `ScopedBy` it, `ProjectDependency` links, and `SupportedProject` relationships. `ProjectsMixin` (`project_handler.py`) makes the Egeria calls; `ProjectsScreen` and `ProjectScreen` drive it through `self.app`. Each call builds a fresh `Egeria` client with a bearer token (`_project_client()`) and closes its session afterwards. + +There are three ways in: +- **Work with Projects** on the Other Functions menu: `show_projects()`. +- **Find Project** on the same menu: `show_projects(find=True)`, which opens the same screen with focus on the search input (`ProjectsScreen(..., focus_search=True)`). +- **`Enter` on a Projects row** on the main screen: `_on_projects_row_selected` → `open_project_row(table, row_key)`, which reads the row's name and GUID columns and pushes `ProjectScreen` directly, with `project_callback`. + +```mermaid +sequenceDiagram + autonumber + actor User + participant App as ProjectsMixin + participant PS as ProjectsScreen + participant Create as CreateProjectScreen + participant Confirm as ConfirmLeaveProjectScreen + participant EG as Egeria + + User->>App: Other Functions → Work with Projects / Find Project + App->>EG: get_my_profile(JSON) + App->>PS: push(my project rows, focus_search) + PS->>App: search_projects("*") + App->>EG: find_projects(JSON, graph_query_depth=0), paged + opt open a project (Enter / ctrl+o) — see the next diagram + PS->>PS: push ProjectScreen(GUID, name) + Note over PS: on return, re-read both lists if the user joined from inside it + end + opt join (ctrl+n) + PS->>App: join_project(GUID, assignment type) + App->>EG: link_assignment_scope(GUID, user_GUID, AssignmentScopeProperties) + PS->>App: list_my_projects() and search again + end + opt create (ctrl+t) + PS->>Create: push + Create-->>PS: {name, description, mission, project_type, assignment type} / None + PS->>App: create_project(name, description, mission, project_type, assignment type) + App->>EG: unique-name read of the qualified name + App->>EG: create_project(NewElementRequestBody, ProjectProperties) only on not-found + App->>EG: link_assignment_scope(new GUID, user_GUID, AssignmentScopeProperties) unless "Don't join" + PS->>App: list_my_projects() and search again, then highlight the new project + end + opt leave (ctrl+d) + PS->>Confirm: push(project name) + Confirm-->>PS: True / False + PS->>App: leave_project(GUID) + App->>EG: detach_assignment_scope(GUID, user_GUID) + PS->>App: list_my_projects() and search again + end +``` + +| Function | What it does | +| :--- | :--- | +| `show_projects(find=False)` | Refuses (with a notice) if `user_GUID` isn't set yet; otherwise pushes `ProjectsScreen(list_my_projects(), focus_search=find)` | +| `open_project_row(table, row_key)` | Opens the project in a main-screen Projects row `(type, name, description, GUID)`; warns and does nothing if the row has no GUID | +| `list_my_projects()` | `get_my_profile(JSON)`, then reads the profile's own `assignmentScope` links and each `performsRoles` appointment's `nestedElements`, keeping only `Project` and subtype elements. Returns one `(name, assignment types, linked through, description, GUID)` row per project; "linked through" is `Your profile` and/or `Role: `. `None` if Egeria can't be reached | +| `search_projects(search_string)` | Pages `find_projects(..., ignore_case=True, graph_query_depth=0)` with `read_all` → `(name, description, qualified name, GUID)` rows as `PagedRows`. The screen drops projects the user already belongs to, and shows the "at least" note, or "none found in what Egeria returned", when the end wasn't confirmed | +| `join_project(guid, assignment_type)` | `link_assignment_scope(guid, user_GUID, NewRelationshipRequestBody)` with `AssignmentScopeProperties`. Offers `Leader`, `Contributor` and `Observer` (`JOIN_ASSIGNMENT_TYPES`) | +| `create_project(name, description, mission, project_type, assignment_type)` | Builds the qualified name with `__create_qualified_name__(project_type, name)` and asks Egeria's unique-name read (`by_unique_name`) whether it exists. Found is a "find it below to join it" warning; an unclear answer is refused with the "Couldn't confirm ..." words. Both return `None` and create nothing. On not-found it calls `create_project(NewElementRequestBody)` with `ProjectProperties` (`mission` only when given), then, unless `assignment_type` is empty, links the user's profile. Returns the new GUID. The form offers `Project`, `Campaign`, `Task`, `StudyProject`, `PersonalProject` types and `Leader` (the default), `Contributor`, `Observer` and "Don't join" | +| `leave_project(guid)` | `detach_assignment_scope(guid, user_GUID, DeleteRelationshipRequestBody)`, using the same GUID order as `link_assignment_scope` (scope first, actor second) | + +- **Leaving only unlinks the profile.** The screen refuses to leave a project reached only through a role, because the role may be shared and belongs to whoever manages it. +- **Refresh.** After a successful create, join or leave the screen re-reads the user's projects and repeats the last search. After a create it also moves the cursor to the new project, in whichever list it appears. +- **The main screen.** A successful join, leave, or create-and-join sets `projects_changed`. When the user returns to the main screen, `projects_callback` or `project_callback` sees the flag, clears it and calls `call_later(action_refresh)`, so Projects is current. Nothing is refreshed if no membership changed. +- **Return code.** `ProjectsScreen` dismisses with `200` on `q`. + +### A project: team members, blog, resources & dependencies, and comments + +`ProjectScreen(guid, name)` loads its four lists when it mounts and reloads a list after a successful add. `ctrl+n` opens `AddProjectCommentScreen` when the comments table has focus, otherwise `NewProjectBlogPostScreen`; each form dismisses with a dict, or `None` on cancel. `Enter` on a blog post or resource, or `ctrl+o` (the resources table when it has focus, otherwise the highlighted post), opens [`ElementFeedbackScreen`](#feedback-on-a-blog-post-or-resource) for it. + +```mermaid +sequenceDiagram + autonumber + actor User + participant PrS as ProjectScreen + participant App as ProjectsMixin + participant EG as Egeria + + PrS->>App: get_project_members(GUID) + App->>EG: get_project_by_guid(JSON, graph_query_depth=1) + App->>EG: get_actor_role_by_guid(role, include_only_relationships=[PersonRoleAppointment]) for each role + PrS->>App: get_project_blog_posts(GUID) + App->>EG: get_attached_note_logs(GUID), paged + App->>EG: get_notes_for_note_log(log, "BlogEntry") for each log, paged + PrS->>App: get_project_resources(GUID) + App->>EG: get_project_by_guid(JSON, graph_query_depth=1, include_only_relationships=[ResourceList, ScopedBy, ProjectDependency, SupportedProject]) + PrS->>App: get_project_comments(GUID) + App->>EG: get_attached_comments(GUID), paged + opt join (ctrl+w), shown only when the user isn't a member + PrS->>App: join_project(GUID, assignment type) + PrS->>App: get_project_members(GUID) + end + opt new blog post (NewProjectBlogPostScreen) + PrS->>App: add_project_blog_post(GUID, name, title, text) + App->>EG: unique-name read of NoteLog::::ProjectBlog + App->>EG: create_note_log(GUID, NewAttachmentRequestBody) only on not-found + App->>EG: create_note(log, BlogEntryProperties) + end + opt add comment (AddProjectCommentScreen) + PrS->>App: add_project_comment(GUID, text, type) + App->>EG: add_comment_to_element(GUID, text, type) + end +``` + +| Function | What it does | +| :--- | :--- | +| `get_project_members(guid)` | People only. Reads `assignedActors`, `projectTeam`, and `resourceListUsers` from `get_project_by_guid(guid, JSON, graph_query_depth=1)`. A `Person` actor is a direct member. For an actor whose type is or inherits `ActorRole`, it calls `get_actor_role_by_guid(..., graph_query_depth=1, include_only_relationships=["PersonRoleAppointment"])` and takes the `Person` elements in `rolePerformers`. Other actors are skipped. Returns one `(name, assignment types, member through, qualified name, GUID)` row per person, sorted by name; "member through" is `Direct` and/or `Role: `. A role that can't be read is skipped and reported with one warning; `None` if the project itself can't be read | +| `get_project_blog_posts(guid)` | Pages the `BlogEntry` notes from every note log attached to the project, so posts written by other tools are included. Returns the `LATEST_POSTS` (20) newest as `(title, author, posted, text, GUID)` rows; author and time come from the element header's `versions`. When any read wasn't confirmed complete it warns that newer posts may be missing | +| `add_project_blog_post(guid, name, title, text)` | Finds the blog note log, qualified name `NoteLog::::ProjectBlog`, with Egeria's unique-name read. It creates the log (attached, display name "_name_ Blog") only when that read says not-found, then `create_note(log, BlogEntryProperties)`. On any other answer nothing is created or posted (`LookupUnconfirmed`, a warning) | +| `get_project_resources(guid)` | `get_project_by_guid(guid, JSON, graph_query_depth=1, include_only_relationships=["ResourceList", "ScopedBy", "ProjectDependency", "SupportedProject"])`. Takes `resourceList` (linked as `Resource`, or `Resource: `), `relevantToScopes` (`In scope`), `projectDependencies` (`Dependency`), and `supportedProjects` (`Supported Project`). Returns one `(name, type, linked as, description, GUID)` row per element, sorted by name; `None` if the read fails | +| `get_project_comments(guid)` | Pages `get_attached_comments(guid, graph_query_depth=0)` → `(comment, type, author, posted, GUID)` rows, newest first, as `PagedRows` (via the shared `_comment_rows`); warns with the "at least" note when the end wasn't confirmed | +| `add_project_comment(guid, text, type)` | `add_element_comment(guid, text, type)`; the form offers pyegeria's `COMMENT_TYPES` | + +- **Joining from here.** `_load_members` sets `is_member` when the app's `user_GUID` is among the members (directly or through a role) and shows the join controls (`project_join_controls`: `Leader`/`Contributor`/`Observer` and **Join Project**, `ctrl+w`) only when it is `False`. +- **Return codes.** `ProjectScreen` dismisses with `200` on `Escape` (back to the projects list, or the main screen if opened from there) and `210` on `q`; on `210` `ProjectsScreen` dismisses itself too, so `q` reaches the main screen. + +--- + ## Status Screen `StatusScreen(message)` shows a read-only message: @@ -826,6 +960,16 @@ The suite in `tests/micro-tests/my_profile/` has one module per handler and scre `test_my_egeria.py` checks the menu routing, including **Find Community**. The blog and comment functions were run against a live server on 2026-10-28. Listing and finding communities, `create_community` (with and without joining, and the duplicate check) and `get_community_members` were run there on 2026-10-30. Joining and leaving, `get_community_resources`, and liking, unliking, rating and commenting on a blog post and a resource were run there on 2026-11-17, and the community and feedback screens were rendered against live data. The screens haven't yet been driven by hand end to end on a live server. +**Work with Projects.** `test_project_handler.py` covers `ProjectsMixin`, `ProjectsScreen`, `ProjectScreen`, and dialogs. That includes: +- memberships direct and through roles, the leave confirmation, and refusing to leave a role membership; +- creating a project: subtypes (`Project`, `Campaign`, `Task`, `StudyProject`, `PersonalProject`), creator assignment types (`Leader`, `Contributor`, `Observer`, "Don't join"), duplicate name checks via unique-name reads, failed create, and failed link handling; +- the Create Project form: validation, cancellation, and highlighting the newly created project; +- members as people only, direct and through roles, merged per person; +- creating the project blog note log on the first post and reusing it on subsequent posts, and the blog post and comment forms; +- resources: `ResourceList`, `ScopedBy`, `ProjectDependency`, and `SupportedProject` relationships merged per element; +- joining from the project screen, and moving the project from the found list to the user's project list; +- opening a project from a main-screen `projects_table` row, Find Project starting with search focus, and main-screen auto-refresh on return after membership changes. + **Paging.** `test_paging_contract.py` checks the handlers against Egeria's paging contract: no total or "none" without a confirmed end, and no write when a guard's answer is unknown. **Screen headings.** `test_profile_utils.py::TestSetScreenHeading` covers `set_screen_heading`. `test_my_egeria.py` checks that the main screen's heading shows the Karma Points once the profile has loaded, and resets them to 0 on `change_user`. diff --git a/docs/developer_guide_pyegeria_textual.md b/docs/developer_guide_pyegeria_textual.md index 3e7cf889..e83e6b1f 100644 --- a/docs/developer_guide_pyegeria_textual.md +++ b/docs/developer_guide_pyegeria_textual.md @@ -562,8 +562,8 @@ All files are in |---|---| | `my_profile.py` | The `App` subclass, `MyProfileApp`: startup, loading the profile, filling the main tables, and shared actions such as comments. | | `MainScreen.py` | The main dashboard screen: its layout, and keeping track of which table and row are selected. | -| `*Screen.py`, `*Screens.py` | One class per screen or dialog: `SplashScreen`, `ShopForDataScreen`, `MyBookMarksScreen`, `AddCommentScreen`, the `Edit*`/`Add*` screens, and so on. | -| `*_handler.py` | **Mixins**, each holding one feature area's logic: `shop_for_data_handler.py`, `tech_types_handler.py`, `team_roles_handler.py`, `elements_crud_handler.py`, `feedback_handler.py`, `bookmarks_handler.py`. | +| `*Screen.py`, `*Screens.py` | One class per screen or dialog: `SplashScreen`, `ShopForDataScreen`, `MyBookMarksScreen`, `AddCommentScreen`, `CommunitiesScreen`, `CommunityScreen`, `ProjectsScreen`, `ProjectScreen`, the `Edit*`/`Add*` screens, and so on. | +| `*_handler.py` | **Mixins**, each holding one feature area's logic: `shop_for_data_handler.py`, `tech_types_handler.py`, `team_roles_handler.py`, `elements_crud_handler.py`, `feedback_handler.py`, `bookmarks_handler.py`, `network_handler.py`, `community_handler.py`, `project_handler.py`. | | `profile_utils.py` | Plain functions with no UI code: data clean-up, flattening Egeria elements (`element_summary`), reading a row's GUID and qualified name (`row_identity`), and the environment check. | | `my_profile.tcss` | All the Textual CSS for the app. | | `RETURN_CODES.md` | The catalogue of numeric codes that screens pass back through `dismiss()`. | @@ -574,7 +574,7 @@ Two design choices keep `my_profile.py` manageable. ```python class MyProfileApp(App, TechTypesMixin, ShopForDataMixin, TeamRolesMixin, ElementsCrudMixin, FeedbackMixin, - BookmarksMixin): + BookmarksMixin, NetworkMixin, CommunitiesMixin, ProjectsMixin): ``` Each mixin adds the methods for one feature. For example, `ShopForDataMixin` adds diff --git a/docs/my_egeria_manual.md b/docs/my_egeria_manual.md index b4182b5d..4b6c3b80 100644 --- a/docs/my_egeria_manual.md +++ b/docs/my_egeria_manual.md @@ -160,7 +160,7 @@ The header reads **Egeria — User: _your user ID_, Karma Points: _n_**. Karma P | **Journal** | Journal Entry, Date, Text, GUID | Your journal entries | | **To-Dos** | To-Do Name, Activity Status, Description, GUID | Your to-dos | | **User Identity** | Display Name, User ID, Distinguished Name, GUID | User identities linked to your profile | -| **Projects** | Status or Type, Name, Description, GUID | Projects you are involved in | +| **Projects** | Status or Type, Name, Description, GUID | Projects you are involved in. Press `Enter` on one (or click it a second time) to [open it](#a-project) | Click or move into a table to select it; the highlighted row is the "selected row" used by the shortcuts below. Press `ctrl+r` to reload everything from Egeria. The app also reloads automatically when you close an Add screen. @@ -328,6 +328,36 @@ The feedback screen shows how many people like the item (and whether you do), it ### Find Community Opens [Work with Communities](#work-with-communities) with the cursor in the search field: type a search term (`*` for all) and press `Enter`, then join or open a community from the found list. +### Work with Projects +The screen lists the projects you belong to (name, assignment type, what links you to it, description and GUID), lets you find others to join, and opens a project to show its members, blog, resources and comments. **Find Project** opens the same screen with the cursor in the search field. If your profile has not finished loading, the app tells you to wait and does not open the screen. When you return to the main screen after joining, leaving or creating-and-joining a project, the main screen reloads so Projects is up to date. + +- **Linked Through** is **Your profile** if you joined the project directly, or **Role: _name_** if you belong through a role you hold. A project you reach both ways is listed once. +- **Open a project:** highlight a project in either list and press `Enter`, `ctrl+o` or **Open Project**. See [A project](#a-project) below. +- **Create a project:** press `ctrl+t` (or **Create Project**). Choose a **Project Type** (`Project`, `Campaign`, `Task`, `StudyProject`, `PersonalProject`), enter a **Name\*** and **Description\***, and optionally a **Mission**, then choose **Your part in it**: **Leader** (the default), **Contributor**, **Observer** or **Don't join**. Press `ctrl+s` (or **Create**); **Cancel** or `Escape` discards it. The lists reload and the new project is highlighted: in your projects if you joined it, otherwise in the found list. If a project with that name already exists, you are told to find it and join it instead. If Egeria can't say either way, nothing is created and you are asked to try again later. +- **Find and join:** type a search term in the search field (`*` for all) and press `Enter`. Projects you already belong to are left out. If Egeria doesn't confirm it sent every match, a warning says the list may be incomplete (see [Troubleshooting](#troubleshooting)). Choose **Leader**, **Contributor** or **Observer**, highlight a project and press `ctrl+n` (or **Join Project**). +- **Leave:** highlight one of your projects and press `ctrl+d` (or **Leave Project**), then confirm with **Leave**. **Cancel** or `Escape` keeps you in it. Only the link between you and the project is removed. You can't leave a project you belong to through a role; ask whoever manages that role. +- `Escape` or `q` returns to the main screen. + +Membership is an `AssignmentScope` relationship from your profile (or a role) to the project, and the assignment type is stored on that relationship. + +#### A project +Open a project from either list on the Projects screen, or with `Enter` on a row of the main screen's Projects table. It shows four lists: its **latest blog posts** (the 20 newest, with title, author and date; the highlighted post's text is shown underneath), its **team members**, its **resources & dependencies** and the **comments** on it, newest first. You don't have to be a member to read or add to them. + +The team members list shows **people only**, in name order, not roles. It includes everyone linked to the project directly and everyone appointed to a role that is. **Member Through** says how each person belongs: **Direct**, or **Role: _name_** for each role they hold there. A person who belongs in several ways is listed once. Other kinds of member, such as teams, are not shown. If the people in one of the project's roles can't be read, the rest are still listed and a warning says some members may be missing. + +The resources list shows the elements the project lists as its resources (**Linked As** is **Resource**, or **Resource: _use_** when the link says what the resource is for), elements scoped to it (**In scope**), **Dependency** links, and **Supported Project** relationships. An element linked multiple ways is listed once. + +- **Join:** if you are not a member, the members panel offers **Leader**, **Contributor** or **Observer** and a **Join Project** button (`ctrl+w`). Once you have joined, the members list reloads and the button disappears; back on the Projects screen, the project moves from the found list to yours. If the members can't be read, joining isn't offered. +- **New blog post:** press `ctrl+n` (or **New Blog Post**), enter a title and the text, then press `ctrl+s` (or **Post**). **Cancel** or `Escape` discards it. +- **Add a comment:** select the comments list and press `ctrl+n` (or press **Add Comment**), choose a comment type (Standard Comment, Question, Answer, Suggestion, Usage Experience, Requirement or Other), enter the comment and press `ctrl+s` (or **Add Comment**). +- **Feedback on a post or resource:** press `Enter` on a blog post or resource, or highlight one and press `ctrl+o` (or **Feedback on Post** / **Feedback on Resource**). +- `Escape` returns to the projects list (or the main screen, if you opened the project from there); `q` returns to the main screen. + +The project's blog is a note log attached to the project, created when the first post is made (if Egeria can't say whether the blog already exists, nothing is posted and you are asked to try again); each post is a `BlogEntry` in it. Comments are attached to the project itself. Resources are `ResourceList`, `ScopedBy`, `ProjectDependency`, and `SupportedProject` relationships from or to the project. + +### Find Project +Opens [Work with Projects](#work-with-projects) with the cursor in the search field: type a search term (`*` for all) and press `Enter`, then join or open a project from the found list. + ### Change User Log in as a different Egeria user and reload the app for them. See [The Change User screen](#the-change-user-screen). @@ -348,12 +378,12 @@ Every screen follows the same rules: | `r` / `u` / `q` | Retry now / Change User / Quit | Connection error screen | | `q` | Main menu / quit the app | Every list screen / Main screen | | `Enter` | Select the highlighted row; continue | Tables and trees; Status screen | -| `ctrl+s` | Save / submit the form | Add screens, Add Comment, Create Subscription, Create/Edit Profile, Feedback, New Blog Post, Create Community | -| `ctrl+n` | Add a new item | Edit screens (row), Bookmarks, Comments, Main screen (comment), Communities (join), a community (blog post or comment), feedback on a post or resource (comment) | -| `ctrl+d` | Delete / remove the highlighted item | Edit screens, Bookmarks, My Network, Communities (leave) | -| `ctrl+o` | Open the highlighted item | Main screen (comments), Comments (responses), My Network (person details), Communities (open a community), a community (feedback on the highlighted post or resource) | -| `ctrl+w` | Join the community | A community you are not a member of | -| `ctrl+t` | Edit the selected table / create a community | Main screen / Communities | +| `ctrl+s` | Save / submit the form | Add screens, Add Comment, Create Subscription, Create/Edit Profile, Feedback, New Blog Post, Create Community, Create Project | +| `ctrl+n` | Add a new item | Edit screens (row), Bookmarks, Comments, Main screen (comment), Communities/Projects (join), a community/project (blog post or comment), feedback on a post or resource (comment) | +| `ctrl+d` | Delete / remove the highlighted item | Edit screens, Bookmarks, My Network, Communities/Projects (leave) | +| `ctrl+o` | Open the highlighted item | Main screen (comments), Comments (responses), My Network (person details), Communities/Projects (open), a community/project (feedback on the highlighted post or resource) | +| `ctrl+w` | Join the community / project | A community or project you are not a member of | +| `ctrl+t` | Edit the selected table / create a community or project | Main screen / Communities / Projects | | `ctrl+k` | Bookmark the highlighted row | Main screen, Shop for Data | | `ctrl+b` | Bookmarks, with the highlighted row's GUID ready to add | Main screen, Shop for Data | | `ctrl+u` | Subscribe | Shop for Data, Overview, sample-data view | diff --git a/my_egeria/my_egeria/MainScreen.py b/my_egeria/my_egeria/MainScreen.py index 9f7f7283..dc53dd1c 100644 --- a/my_egeria/my_egeria/MainScreen.py +++ b/my_egeria/my_egeria/MainScreen.py @@ -70,6 +70,8 @@ def compose(self) -> ComposeResult: Option("[] My Network"), Option("[] Work with Communities"), Option("[] Find Community"), + Option("[] Work with Projects"), + Option("[] Find Project"), Option("[] User Bookmarks"), Option("[] Leave Feedback"), Option("[] Feedback Log"), @@ -108,7 +110,7 @@ def compose(self) -> ComposeResult: id="main_identities_container" ) yield ScrollableContainer( - Static("Projects"), + Static("Projects [dim](Enter on a project: open it)[/dim]"), DataTable(id="projects_table"), id="main_projects_container" ) diff --git a/my_egeria/my_egeria/ProjectScreen.py b/my_egeria/my_egeria/ProjectScreen.py new file mode 100644 index 00000000..bdca40f2 --- /dev/null +++ b/my_egeria/my_egeria/ProjectScreen.py @@ -0,0 +1,398 @@ +""" + PDX-License-Identifier: Apache-2.0 + Copyright Contributors to the ODPi Egeria project. + + This file provides the Project view screen (team members, blog posts/notes, + resources and comments) for My Profile. + +""" +from textual import on +from textual.app import ComposeResult +from textual.containers import ScrollableContainer, Horizontal +from textual.screen import ModalScreen +from textual.widgets import DataTable, Header, Static, Footer, Input, Button, Select, TextArea + +from CommunityScreen import (ElementFeedbackScreen, RateElementScreen, comment_type_label, + star_label, STAR_VALUES, COMMENT_TYPES) +from paging_support import is_complete, none_words +from profile_utils import set_screen_heading + +# Assignment types offered when a user joins an existing project +JOIN_ASSIGNMENT_TYPES = ["Contributor", "Observer", "ProjectManagement"] + + +class NewProjectBlogPostScreen(ModalScreen): + """Collect the title and text of a new blog post / note on a project. + + Dismisses with {"title", "text"}, or None if cancelled. + """ + + BINDINGS = [ + ("escape", "cancel", "Back"), + ("ctrl+s", "submit", "Post"), + ] + + CSS_PATH = "my_profile.tcss" + + def __init__(self, project_name: str, *args, **kwargs): + super().__init__(*args, **kwargs, id="new_project_blog_post_screen") + self.project_name = project_name + + def compose(self) -> ComposeResult: + yield Header(show_clock=True) + yield Static("New Blog Post", classes="span-3", id="new_project_blog_post_title") + yield ScrollableContainer( + Static(f"[b]Post to {self.project_name} Blog[/b]"), + Static("Title *"), + Input(placeholder="Title of the post", id="project_blog_post_title_input"), + Static("Post *"), + TextArea(id="project_blog_post_text"), + Horizontal( + Button("Post", id="submit_project_blog_post_btn", variant="primary"), + Button("Cancel", id="cancel_project_blog_post_btn", variant="warning"), + ), + id="new_project_blog_post_container", + ) + yield Footer() + + def on_mount(self) -> None: + set_screen_heading(self, "Projects - New Blog Post") + self.query_one("#project_blog_post_title_input", Input).focus() + + def action_submit(self) -> None: + title = self.query_one("#project_blog_post_title_input", Input).value.strip() + text = self.query_one("#project_blog_post_text", TextArea).text.strip() + if not title or not text: + self.notify("Please enter both a title and text for the blog post", timeout=5, + severity="warning") + return + self.dismiss({"title": title, "text": text}) + + def action_cancel(self) -> None: + self.dismiss(None) + + @on(Button.Pressed, "#submit_project_blog_post_btn") + def handle_submit_button(self, event: Button.Pressed) -> None: + self.action_submit() + + @on(Button.Pressed, "#cancel_project_blog_post_btn") + def handle_cancel_button(self, event: Button.Pressed) -> None: + self.action_cancel() + + +class AddProjectCommentScreen(ModalScreen): + """Collect the text and type of a comment on a project. + + Dismisses with {"text", "comment_type"}, or None if cancelled. + """ + + BINDINGS = [ + ("escape", "cancel", "Back"), + ("ctrl+s", "submit", "Add Comment"), + ] + + CSS_PATH = "my_profile.tcss" + + def __init__(self, project_name: str, *args, **kwargs): + super().__init__(*args, **kwargs, id="add_project_comment_screen") + self.project_name = project_name + + def compose(self) -> ComposeResult: + yield Header(show_clock=True) + yield Static("Add Comment", classes="span-3", id="add_project_comment_title") + yield ScrollableContainer( + Static(f"[b]Comment on {self.project_name}[/b]"), + Static("Comment type"), + Select([(comment_type_label(t), t) for t in COMMENT_TYPES], value=COMMENT_TYPES[0], + allow_blank=False, id="project_comment_type"), + Static("Comment"), + TextArea(id="project_comment_text"), + Horizontal( + Button("Add Comment", id="submit_project_comment_btn", variant="primary"), + Button("Cancel", id="cancel_project_comment_btn", variant="warning"), + ), + id="add_project_comment_container", + ) + yield Footer() + + def on_mount(self) -> None: + set_screen_heading(self, "Projects - Add Comment") + self.query_one("#project_comment_text", TextArea).focus() + + def action_submit(self) -> None: + text = self.query_one("#project_comment_text", TextArea).text.strip() + if not text: + self.notify("Please enter a comment", timeout=5, severity="warning") + return + self.dismiss({"text": text, "comment_type": self.query_one("#project_comment_type", Select).value}) + + def action_cancel(self) -> None: + self.dismiss(None) + + @on(Button.Pressed, "#submit_project_comment_btn") + def handle_submit_button(self, event: Button.Pressed) -> None: + self.action_submit() + + @on(Button.Pressed, "#cancel_project_comment_btn") + def handle_cancel_button(self, event: Button.Pressed) -> None: + self.action_cancel() + + +class ProjectScreen(ModalScreen): + """One project: its team members, the latest posts on its blog/notes, its resources and its comments. + + The Egeria work is done by the app's ProjectsMixin (get_project_members, + get_project_blog_posts, add_project_blog_post, get_project_resources, + get_project_comments, add_project_comment, join_project); this screen only drives it. + Feedback on a blog post or resource opens an ElementFeedbackScreen. + + Dismisses with 200 to go back to the projects list, or 210 to go on to the main screen. + joined is True once the user has joined the project from this screen. + """ + + BINDINGS = [ + ("escape", "back", "Back"), + ("q", "quit", "Main Menu"), + ("ctrl+n", "add_item", "New Post / Comment"), + ("ctrl+o", "feedback", "Feedback on Post / Resource"), + ("ctrl+w", "join", "Join Project"), + ] + + CSS_PATH = "my_profile.tcss" + + def __init__(self, project_guid: str, project_name: str, *args, **kwargs): + super().__init__(id="project_screen", *args, **kwargs) + self.project_guid = project_guid + self.project_name = project_name + # Full text of each blog post, by GUID, shown below the posts table + self.post_text: dict[str, str] = {} + # Whether the user is a member (directly or through a role); None until the members are read + self.is_member: bool | None = None + self.joined = False + + def compose(self) -> ComposeResult: + yield Header(show_clock=True) + yield Static(self.project_name, classes="span-3", id="project_title") + yield ScrollableContainer( + Static("[b]Latest blog posts / notes[/b] [dim]ctrl+n adds a post; Enter or ctrl+o gives feedback on one[/dim]"), + DataTable(id="project_posts_table", zebra_stripes=True, cursor_type="row"), + Static("", id="project_post_text"), + Horizontal( + Button("New Blog Post", id="new_project_blog_post_btn", variant="primary"), + Button("Feedback on Post", id="project_post_feedback_btn", variant="primary"), + id="project_blog_buttons", + ), + id="project_blog_container", + ) + yield ScrollableContainer( + Static("[b]Members / Team[/b] [dim](people linked to the project, directly or through a role they hold)[/dim]"), + DataTable(id="project_members_table", zebra_stripes=True, cursor_type="row"), + Static("", id="project_membership_text"), + Horizontal( + Select([(t, t) for t in JOIN_ASSIGNMENT_TYPES], value=JOIN_ASSIGNMENT_TYPES[0], + allow_blank=False, id="project_join_assignment_type"), + Button("Join Project", id="project_join_btn", variant="primary"), + id="project_join_controls", + ), + id="project_members_container", + ) + yield ScrollableContainer( + Static("[b]Resources[/b] [dim](elements the project lists or looks after; " + "Enter or ctrl+o gives feedback on one)[/dim]"), + DataTable(id="project_resources_table", zebra_stripes=True, cursor_type="row"), + Button("Feedback on Resource", id="project_resource_feedback_btn", variant="primary"), + id="project_resources_container", + ) + yield ScrollableContainer( + Static("[b]Comments[/b] [dim]with this list selected, ctrl+n adds a comment[/dim]"), + DataTable(id="project_comments_table", zebra_stripes=True, cursor_type="row"), + Button("Add Comment", id="add_project_comment_btn", variant="primary"), + id="project_comments_container", + ) + yield Footer() + + def on_mount(self) -> None: + set_screen_heading(self, f"Project - {self.project_name}") + self.query_one("#project_posts_table", DataTable).add_columns("Title", "Author", "Posted", "GUID") + self.query_one("#project_members_table", DataTable).add_columns( + "Name", "Assignment Type", "Member Through", "Qualified Name", "GUID") + self.query_one("#project_resources_table", DataTable).add_columns( + "Name", "Type", "Linked As", "Description", "GUID") + self.query_one("#project_comments_table", DataTable).add_columns( + "Comment", "Type", "Author", "Posted", "GUID") + self._load_members() + self._load_posts() + self._load_resources() + self._load_comments() + + def _load_members(self) -> None: + members = self.app.get_project_members(self.project_guid) + if members is None: + self.query_one("#project_join_controls", Horizontal).display = False + return + table = self.query_one("#project_members_table", DataTable) + table.clear() + self.is_member = False + for row in members: + table.add_row(*row, key=row[4]) + if row[4] == self.app.user_GUID: + self.is_member = True + through = f" (through {row[2]})" if row[2] != "Direct" else "" + self.query_one("#project_membership_text", Static).update( + f"You are a member{through} with assignment type: {row[1]}") + self.query_one("#project_join_controls", Horizontal).display = not self.is_member + if not self.is_member: + self.query_one("#project_membership_text", Static).update("You are not a member of this project") + + def _load_posts(self) -> None: + posts = self.app.get_project_blog_posts(self.project_guid) + if posts is None: + return + table = self.query_one("#project_posts_table", DataTable) + table.clear() + self.post_text.clear() + for row in posts: + table.add_row(row[0], row[1], row[2], row[4], key=row[4]) + self.post_text[row[4]] = row[3] + if posts: + # Show the newest post's text straight away + self.query_one("#project_post_text", Static).update(self.post_text.get(posts[0][4], "")) + else: + self.query_one("#project_post_text", Static).update( + "No posts on the blog yet" if is_complete(posts) else none_words("blog posts", complete=False)) + + def _load_resources(self) -> None: + resources = self.app.get_project_resources(self.project_guid) + if resources is None: + return + table = self.query_one("#project_resources_table", DataTable) + table.clear() + for row in resources: + table.add_row(*row, key=row[4]) + if not resources: + self.notify("This project has no resources listed or scoped to it", timeout=5) + + def _load_comments(self) -> None: + comments = self.app.get_project_comments(self.project_guid) + if comments is None: + return + table = self.query_one("#project_comments_table", DataTable) + table.clear() + for row in comments: + table.add_row(*row, key=row[4]) + + # --- selection and display ------------------------------------------------ + + @on(DataTable.RowHighlighted, "#project_posts_table") + def handle_posts_table_highlighted(self, event: DataTable.RowHighlighted) -> None: + """Display the highlighted blog post's text.""" + self.query_one("#project_post_text", Static).update(self.post_text.get(str(event.row_key.value), "")) + + @on(DataTable.RowSelected, "#project_posts_table") + def handle_posts_table_selected(self, event: DataTable.RowSelected) -> None: + self.action_post_feedback() + + @on(DataTable.RowSelected, "#project_resources_table") + def handle_resources_table_selected(self, event: DataTable.RowSelected) -> None: + self.action_resource_feedback() + + @on(DataTable.RowSelected, "#project_comments_table") + def handle_comments_table_selected(self, event: DataTable.RowSelected) -> None: + self.action_add_comment() + + # --- blog ----------------------------------------------------------------- + + def action_new_blog_post(self) -> None: + def on_post(post_data: dict | None) -> None: + if not post_data: + return + if self.app.add_project_blog_post(self.project_guid, self.project_name, + post_data["title"], post_data["text"]): + self._load_posts() + + self.app.push_screen(NewProjectBlogPostScreen(self.project_name), callback=on_post) + + @on(Button.Pressed, "#new_project_blog_post_btn") + def handle_new_post_button(self, event: Button.Pressed) -> None: + self.action_new_blog_post() + + def action_post_feedback(self) -> None: + table = self.query_one("#project_posts_table", DataTable) + if table.row_count == 0: + self.notify("There are no blog posts on this project yet", timeout=5, severity="warning") + return + row = table.get_row_at(table.cursor_row) + self.app.push_screen(ElementFeedbackScreen(row[3], f"Blog post: {row[0]}", "BlogEntry")) + + @on(Button.Pressed, "#project_post_feedback_btn") + def handle_post_feedback_button(self, event: Button.Pressed) -> None: + self.action_post_feedback() + + # --- joining -------------------------------------------------------------- + + def action_join(self) -> None: + if self.is_member: + self.notify("You are already a member of this project", timeout=5, severity="warning") + return + assignment_type = self.query_one("#project_join_assignment_type", Select).value + if self.app.join_project(self.project_guid, assignment_type): + self.joined = True + self._load_members() + + @on(Button.Pressed, "#project_join_btn") + def handle_join_button(self, event: Button.Pressed) -> None: + self.action_join() + + # --- resources ------------------------------------------------------------ + + def action_resource_feedback(self) -> None: + table = self.query_one("#project_resources_table", DataTable) + if table.row_count == 0: + self.notify("This project has no resources listed or scoped to it", timeout=5, severity="warning") + return + row = table.get_row_at(table.cursor_row) + self.app.push_screen(ElementFeedbackScreen(row[4], f"{row[1]}: {row[0]}", row[1])) + + @on(Button.Pressed, "#project_resource_feedback_btn") + def handle_resource_feedback_button(self, event: Button.Pressed) -> None: + self.action_resource_feedback() + + # --- comments ------------------------------------------------------------- + + def action_add_comment(self) -> None: + def on_comment(comment: dict | None) -> None: + if not comment: + return + if self.app.add_project_comment(self.project_guid, comment["text"], comment["comment_type"]): + self._load_comments() + + self.app.push_screen(AddProjectCommentScreen(self.project_name), callback=on_comment) + + @on(Button.Pressed, "#add_project_comment_btn") + def handle_add_comment_button(self, event: Button.Pressed) -> None: + self.action_add_comment() + + # --- general actions (bindings) ------------------------------------------- + + def action_feedback(self) -> None: + """ctrl+o gives feedback on whichever of a post or a resource currently has focus.""" + resources_table = self.query_one("#project_resources_table", DataTable) + if self.focused is resources_table: + self.action_resource_feedback() + else: + self.action_post_feedback() + + def action_add_item(self) -> None: + """ctrl+n adds a comment when the comments list has focus, a blog post otherwise.""" + comments_table = self.query_one("#project_comments_table", DataTable) + if self.focused is comments_table: + self.action_add_comment() + else: + self.action_new_blog_post() + + def action_back(self) -> None: + self.dismiss(200) + + def action_quit(self) -> None: + """q goes straight back to the main screen, dismissing the projects list too.""" + self.dismiss(210) diff --git a/my_egeria/my_egeria/ProjectsScreen.py b/my_egeria/my_egeria/ProjectsScreen.py new file mode 100644 index 00000000..28c93624 --- /dev/null +++ b/my_egeria/my_egeria/ProjectsScreen.py @@ -0,0 +1,377 @@ +""" + PDX-License-Identifier: Apache-2.0 + Copyright Contributors to the ODPi Egeria project. + + This file provides the Work with Projects screen for My Profile. + +""" +from textual import on +from textual.app import ComposeResult +from textual.containers import ScrollableContainer, Horizontal +from textual.screen import ModalScreen +from textual.widgets import DataTable, Header, Static, Footer, Input, Button, Select, TextArea + +from ProjectScreen import ProjectScreen, JOIN_ASSIGNMENT_TYPES +from paging_support import is_complete, none_words +from profile_utils import set_screen_heading + +# The "Linked Through" value of a membership held by the user's own profile, which they can leave +DIRECT_LINK = "Your profile" +# Whoever creates a project manages it, so they may also lead it +CREATOR_ASSIGNMENT_TYPES = ["Leader", "ProjectManager"] + JOIN_ASSIGNMENT_TYPES +PROJECT_TYPES = ["Project", "Campaign", "Task", "PersonalProject", "StudyProject", "Experiment", "Investigation"] +# The "Your part in it" choice for a creator who doesn't join their new project +NOT_JOINING = "" + + +def is_direct_membership(row) -> bool: + """True if a my-projects row includes a link from the user's own profile.""" + return DIRECT_LINK in row[2].split("; ") + + +class CreateProjectScreen(ModalScreen): + """Collect the details of a new project, and the part the user will take in it. + + Dismisses with {"name", "description", "mission", "assignment_type", "project_type"}, where an empty + assignment_type means the user doesn't join, or None if cancelled. + """ + + BINDINGS = [ + ("escape", "cancel", "Back"), + ("ctrl+s", "submit", "Create"), + ] + + CSS_PATH = "my_profile.tcss" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs, id="create_project_screen") + + def compose(self) -> ComposeResult: + yield Header(show_clock=True) + yield Static("Create Project", classes="span-3", id="create_project_title") + yield ScrollableContainer( + Static("Name *"), + Input(placeholder="Name of the project", id="project_name_input"), + Static("Description *"), + Input(placeholder="What the project is about", id="project_description_input"), + Static("Project Type"), + Select([(t, t) for t in PROJECT_TYPES], value=PROJECT_TYPES[0], allow_blank=False, + id="project_type_select"), + Static("Mission / Planned Results"), + TextArea(id="project_mission_text"), + Static("Your part in it"), + Select([(t, t) for t in CREATOR_ASSIGNMENT_TYPES] + [("Don't join", NOT_JOINING)], + value=CREATOR_ASSIGNMENT_TYPES[0], allow_blank=False, id="project_creator_assignment_type"), + Horizontal( + Button("Create", id="submit_create_project_btn", variant="primary"), + Button("Cancel", id="cancel_create_project_btn", variant="warning"), + ), + id="create_project_container", + ) + yield Footer() + + def on_mount(self) -> None: + set_screen_heading(self, "Projects - Create Project") + self.query_one("#project_name_input", Input).focus() + + def action_submit(self) -> None: + name = self.query_one("#project_name_input", Input).value.strip() + description = self.query_one("#project_description_input", Input).value.strip() + if not name or not description: + self.notify("Please enter both a name and a description for the project", timeout=5, + severity="warning") + return + self.dismiss({"name": name, "description": description, + "mission": self.query_one("#project_mission_text", TextArea).text.strip(), + "project_type": self.query_one("#project_type_select", Select).value, + "assignment_type": self.query_one("#project_creator_assignment_type", Select).value}) + + def action_cancel(self) -> None: + self.dismiss(None) + + @on(Button.Pressed, "#submit_create_project_btn") + def handle_submit_button(self, event: Button.Pressed) -> None: + self.action_submit() + + @on(Button.Pressed, "#cancel_create_project_btn") + def handle_cancel_button(self, event: Button.Pressed) -> None: + self.action_cancel() + + +class ConfirmLeaveProjectScreen(ModalScreen[bool]): + """Confirmation prompt shown before the user leaves a project. + + Dismisses with True to proceed with leaving, False to cancel. + """ + + BINDINGS = [("escape", "cancel", "Cancel")] + + CSS_PATH = "my_profile.tcss" + + def __init__(self, project_name: str, *args, **kwargs): + super().__init__(*args, **kwargs, id="confirm_leave_project_screen") + self.project_name = project_name + + def compose(self) -> ComposeResult: + yield Header(show_clock=True) + yield Static("Leave Project", classes="span-3", id="confirm_leave_project_title") + yield ScrollableContainer( + Static(f"[b]Leave {self.project_name}?[/b]"), + Static("The project is not changed, only the link between you and it."), + Horizontal( + Button("Leave", id="submit_leave_project_btn", variant="error"), + Button("Cancel", id="cancel_leave_project_btn", variant="primary"), + ), + id="confirm_leave_project_container", + ) + yield Footer() + + def on_mount(self) -> None: + set_screen_heading(self, f"Projects - Leave {self.project_name}") + self.query_one("#cancel_leave_project_btn", Button).focus() + + def action_cancel(self) -> None: + self.dismiss(False) + + @on(Button.Pressed, "#submit_leave_project_btn") + def handle_submit_button(self, event: Button.Pressed) -> None: + self.dismiss(True) + + @on(Button.Pressed, "#cancel_leave_project_btn") + def handle_cancel_button(self, event: Button.Pressed) -> None: + self.dismiss(False) + + +class ProjectsScreen(ModalScreen): + """The user's projects and the means to find, join, create and leave projects. + + The Egeria work is done by the app's ProjectsMixin (list_my_projects, search_projects, + create_project, join_project, leave_project); this screen only drives it. Open Project + opens a ProjectScreen for the highlighted row. + """ + + BINDINGS = [ + ("escape", "quit", "Back"), + ("q", "quit", "Main Menu"), + ("ctrl+o", "open_project", "Open Project"), + ("ctrl+n", "join_project", "Join Project"), + ("ctrl+t", "create_project", "Create Project"), + ("ctrl+d", "leave_project", "Leave Project"), + ] + + CSS_PATH = "my_profile.tcss" + + def __init__(self, my_projects: list[tuple[str, str, str, str, str]], focus_search: bool = False, + *args, **kwargs): + super().__init__(id="projects_screen", *args, **kwargs) + self.my_projects_data = my_projects or [] + self.focus_search = focus_search + self.search_string = "*" + + def compose(self) -> ComposeResult: + yield Header(show_clock=True) + yield Static("Projects", classes="span-3", id="projects_title") + yield ScrollableContainer( + Static("[b]The projects you belong to[/b] [dim]Enter or ctrl+o opens one " + "(team, blog/notes, resources and comments); ctrl+d leaves; ctrl+t creates a new project[/dim]"), + DataTable(id="my_projects_table", zebra_stripes=True, cursor_type="row"), + Horizontal( + Button("Open Project", id="open_my_project_btn", variant="primary"), + Button("Create Project", id="create_project_btn", variant="primary"), + Button("Leave Project", id="leave_project_btn", variant="error"), + id="my_projects_buttons", + ), + id="my_projects_container", + ) + yield ScrollableContainer( + Static("[b]Find other projects[/b] [dim]enter a search term ('*' for all) and press return; " + "ctrl+n joins the highlighted project; Enter or ctrl+o opens it[/dim]"), + Input(placeholder="Search term or *", id="project_search_input"), + DataTable(id="projects_found_table", zebra_stripes=True, cursor_type="row"), + Horizontal( + Select([(t, t) for t in JOIN_ASSIGNMENT_TYPES], value=JOIN_ASSIGNMENT_TYPES[0], + allow_blank=False, id="project_join_assignment_type"), + Button("Join Project", id="join_project_btn", variant="primary"), + Button("Open Project", id="open_found_project_btn", variant="primary"), + id="found_projects_buttons", + ), + id="find_projects_container", + ) + yield Footer() + + def on_mount(self) -> None: + set_screen_heading(self, "Projects") + self.query_one("#my_projects_table", DataTable).add_columns( + "Name", "Assignment Type", "Linked Through", "Description", "GUID") + self.query_one("#projects_found_table", DataTable).add_columns( + "Name", "Description", "Qualified Name", "GUID") + self._fill_my_table() + self._search() + if self.focus_search: + self.query_one("#project_search_input", Input).focus() + + def _fill_my_table(self) -> None: + table = self.query_one("#my_projects_table", DataTable) + table.clear() + for row in self.my_projects_data: + table.add_row(*row, key=row[4]) + if not self.my_projects_data: + self.notify("You don't belong to any projects yet - find one to join", timeout=5) + + def _search(self) -> None: + """Run the current search, listing only projects the user doesn't already belong to.""" + found = self.app.search_projects(self.search_string) + if found is None: + return + table = self.query_one("#projects_found_table", DataTable) + table.clear() + mine = {row[4] for row in self.my_projects_data} + for row in found: + if row[3] not in mine: + table.add_row(*row, key=row[3]) + if table.row_count == 0: + if is_complete(found): + self.notify(f"No other projects found matching {self.search_string}", timeout=5, + severity="warning") + else: + self.notify(none_words("other projects", complete=False, matching=self.search_string), + timeout=10, severity="warning") + elif getattr(found, "note", None): + self.notify(found.note, timeout=10, severity="warning") + + def _reload(self) -> None: + rows = self.app.list_my_projects() + if rows is not None: + self.my_projects_data = rows + self._fill_my_table() + self._search() + + @staticmethod + def _highlighted(table: DataTable) -> list | None: + if table.row_count == 0: + return None + return table.get_row_at(table.cursor_row) + + def action_quit(self) -> None: + """The user elects to quit the projects function.""" + self.dismiss(200) + + # --- opening a project ------------------------------------------------ + + def _open(self, project_guid: str, project_name: str) -> None: + project_screen = ProjectScreen(project_guid, project_name) + + def on_close(result) -> None: + # q on the project screen goes on to the main screen + if result == 210: + self.dismiss(200) + elif project_screen.joined: + # Joined from inside the project: it moves from the found list to the user's own + self._reload() + + self.app.push_screen(project_screen, callback=on_close) + + def action_open_project(self) -> None: + """Open the highlighted project in whichever list has focus.""" + found_table = self.query_one("#projects_found_table", DataTable) + if self.focused is found_table: + self._open_found() + else: + self._open_mine() + + def _open_mine(self) -> None: + row = self._highlighted(self.query_one("#my_projects_table", DataTable)) + if row is None: + self.notify("You don't belong to any projects to select", timeout=5, severity="warning") + return + self._open(row[4], row[0]) + + def _open_found(self) -> None: + row = self._highlighted(self.query_one("#projects_found_table", DataTable)) + if row is None: + self.notify("There are no projects found to select", timeout=5, severity="warning") + return + self._open(row[3], row[0]) + + @on(Button.Pressed, "#open_my_project_btn") + def handle_open_mine_button(self, event: Button.Pressed) -> None: + self._open_mine() + + @on(Button.Pressed, "#open_found_project_btn") + def handle_open_found_button(self, event: Button.Pressed) -> None: + self._open_found() + + @on(DataTable.RowSelected, "#my_projects_table") + def handle_my_project_selected(self, event: DataTable.RowSelected) -> None: + self._open_mine() + + @on(DataTable.RowSelected, "#projects_found_table") + def handle_found_project_selected(self, event: DataTable.RowSelected) -> None: + self._open_found() + + # --- finding and joining ------------------------------------------------- + + @on(Input.Changed, "#project_search_input") + def handle_search_changed(self, event: Input.Changed) -> None: + self.search_string = event.value.strip() or "*" + + @on(Input.Submitted, "#project_search_input") + def handle_search_submitted(self, event: Input.Submitted) -> None: + self.search_string = event.value.strip() or "*" + self._search() + + def action_join_project(self) -> None: + """Join the project highlighted in the found list.""" + self._join_found() + + def _join_found(self) -> None: + row = self._highlighted(self.query_one("#projects_found_table", DataTable)) + if row is None: + self.notify("Please select a project to join from the list below", timeout=5, severity="warning") + return + assignment_type = self.query_one("#project_join_assignment_type", Select).value + if self.app.join_project(row[3], assignment_type): + self._reload() + + @on(Button.Pressed, "#join_project_btn") + def handle_join_button(self, event: Button.Pressed) -> None: + self._join_found() + + # --- creating ------------------------------------------------------------ + + def action_create_project(self) -> None: + def on_create(project_data: dict | None) -> None: + if not project_data: + return + if self.app.create_project(project_data["name"], project_data["description"], + project_data["mission"], project_data["assignment_type"], + project_data.get("project_type", PROJECT_TYPES[0])): + self._reload() + + self.app.push_screen(CreateProjectScreen(), callback=on_create) + + @on(Button.Pressed, "#create_project_btn") + def handle_create_button(self, event: Button.Pressed) -> None: + self.action_create_project() + + # --- leaving ------------------------------------------------------------- + + def action_leave_project(self) -> None: + row = self._highlighted(self.query_one("#my_projects_table", DataTable)) + if row is None: + self.notify("Please select a project to leave", timeout=5, severity="warning") + return + if not is_direct_membership(row): + self.notify(f"You belong to {row[0]} through a role ({row[2]}), not directly: " + f"leaving is not possible from here", timeout=10, severity="warning") + return + + def on_confirm(proceed: bool) -> None: + if proceed and self.app.leave_project(row[4]): + self._reload() + + self.app.push_screen(ConfirmLeaveProjectScreen(row[0]), callback=on_confirm) + + @on(Button.Pressed, "#leave_project_btn") + def handle_leave_button(self, event: Button.Pressed) -> None: + self.action_leave_project() diff --git a/my_egeria/my_egeria/README.md b/my_egeria/my_egeria/README.md index ea55749a..fd6f15be 100644 --- a/my_egeria/my_egeria/README.md +++ b/my_egeria/my_egeria/README.md @@ -11,8 +11,8 @@ The `my-egeria` Textual TUI application's package root — see the parent | `my_profile.py` | Production My Profile & Catalog TUI Application (`MyProfileApp` / `MyEgeriaApp`, entry point `uv run my_profile` / `python -m my_egeria.my_profile`). | | `main.py` | Entry point for MyEgeria app (`uv run my-egeria` / `python -m my_egeria.main`). | | `my_egeria_app.py` | The MyEgeria browser/navigation Textual `App` class. | -| `*Screen.py` / `*Screens.py` | Production Textual screens (Main, Splash, Profile Creation/Edit, Data Shopping, Bookmarks, Network, Teams, Communities and a single community with feedback on its posts and resources, Feedback, Tech Types, Subscriptions). | -| `*_handler.py` | Domain mixins for bookmarks, communities, CRUD operations, feedback, networks, shopping, team roles, and tech types. | +| `*Screen.py` / `*Screens.py` | Production Textual screens (Main, Splash, Profile Creation/Edit, Data Shopping, Bookmarks, Network, Teams, Communities, Projects, Feedback, Tech Types, Subscriptions). | +| `*_handler.py` | Domain mixins for bookmarks, communities, projects, CRUD operations, feedback, networks, shopping, team roles, and tech types. | | `paging_support.py` | Egeria's paging contract for the handlers: paged reads (`read_all`/`PagedRows`), "at least" / "none" wording, and the found / absent / unknown checks made before a write. | | `profile_utils.py` | Profile formatting, Mermaid graph sanitization, data structures, and connection utilities. | | `screens/` | Feature screens (`GovernanceOfficer`, `ProductManager`, `ProjectManager`, `collections`, `glossary`, `platform`). | diff --git a/my_egeria/my_egeria/my_profile.py b/my_egeria/my_egeria/my_profile.py index 0e03ac18..d17fc2fb 100644 --- a/my_egeria/my_egeria/my_profile.py +++ b/my_egeria/my_egeria/my_profile.py @@ -97,10 +97,11 @@ from MyBookMarksScreen import MyBookMarksScreen from network_handler import NetworkMixin from community_handler import CommunitiesMixin +from project_handler import ProjectsMixin class MyProfileApp(App, TechTypesMixin, ShopForDataMixin, TeamRolesMixin, ElementsCrudMixin, FeedbackMixin, - BookmarksMixin, NetworkMixin, CommunitiesMixin): + BookmarksMixin, NetworkMixin, CommunitiesMixin, ProjectsMixin): """My Profile / My Egeria App. Retrieves a user's profile from Egeria and displays current work items. @@ -741,6 +742,10 @@ async def handle_option_selected(self, event: OptionList.OptionSelected) -> None self.show_communities() elif selected_option == "Find Community": self.show_communities(find=True) + elif selected_option == "Work with Projects": + self.show_projects() + elif selected_option == "Find Project": + self.show_projects(find=True) elif selected_option == "Change User": await self.push_screen(ChangeUserScreen(), callback=self.change_user_callback) elif selected_option == "Subscriptions": @@ -772,6 +777,14 @@ def _on_associations_row_selected(self, event: DataTable.RowSelected) -> None: """ self.open_community_row(event.data_table, event.row_key) + @on(DataTable.RowSelected, "#projects_table") + def _on_projects_row_selected(self, event: DataTable.RowSelected) -> None: + """Open the project in a Projects row: its team, blog/notes, resources and comments. + + Registered here rather than on ProjectsMixin, for the same reason as the roles and associations handlers. + """ + self.open_project_row(event.data_table, event.row_key) + def show_main_screen(self) -> None: """Show or switch back to the main screen by unwinding the screen stack.""" # self.log("Returning to main screen") diff --git a/my_egeria/my_egeria/my_profile.tcss b/my_egeria/my_egeria/my_profile.tcss index 683c690b..7c92ae91 100644 --- a/my_egeria/my_egeria/my_profile.tcss +++ b/my_egeria/my_egeria/my_profile.tcss @@ -125,32 +125,58 @@ CommunitiesScreen { background: $background; } +/* Title row, then my projects + find side by side */ +ProjectsScreen { + grid-rows: auto 1fr; + background: $background; +} + #my_communities_container { column-span: 2; width: 100%; height: 100%; } +#my_projects_container { + column-span: 2; + width: 100%; + height: 100%; +} + #find_communities_container { width: 100%; height: 100%; } +#find_projects_container { + width: 100%; + height: 100%; +} + #my_communities_table { width: 100%; height: 1fr; } +#my_projects_table { + width: 100%; + height: 1fr; +} + #my_communities_buttons, -#found_communities_buttons { +#found_communities_buttons, +#my_projects_buttons, +#found_projects_buttons { height: auto; } -#join_assignment_type, #creator_assignment_type { +#join_assignment_type, #creator_assignment_type, +#project_join_assignment_type, #project_creator_assignment_type, #project_type_select { width: 20; } -#communities_found_table { +#communities_found_table, +#projects_found_table { height: auto; max-height: 12; } @@ -161,24 +187,33 @@ CommunityScreen { background: $background; } -#community_blog_container { +ProjectScreen { + grid-rows: auto 1fr 1fr; + background: $background; +} + +#community_blog_container, +#project_blog_container { column-span: 2; width: 100%; height: 100%; } -#community_members_container { +#community_members_container, +#project_members_container { width: 100%; height: 100%; } -#community_resources_container { +#community_resources_container, +#project_resources_container { column-span: 2; width: 100%; height: 100%; } -#community_comments_container { +#community_comments_container, +#project_comments_container { width: 100%; height: 100%; } @@ -186,13 +221,19 @@ CommunityScreen { #community_posts_table, #community_members_table, #community_resources_table, -#community_comments_table { +#community_comments_table, +#project_posts_table, +#project_members_table, +#project_resources_table, +#project_comments_table { height: auto; max-height: 12; } #community_blog_buttons, -#community_join_controls { +#community_join_controls, +#project_blog_buttons, +#project_join_controls { height: auto; } @@ -232,20 +273,23 @@ ElementFeedbackScreen { max-height: 16; } -#community_post_text { +#community_post_text, #project_post_text { padding: 1 0; } -NewBlogPostScreen, AddCommunityCommentScreen, RateElementScreen { +NewBlogPostScreen, AddCommunityCommentScreen, RateElementScreen, +NewProjectBlogPostScreen, AddProjectCommentScreen, CreateProjectScreen, ConfirmLeaveProjectScreen { grid-rows: auto 1fr; background: $background; } -#new_blog_post_container, #add_community_comment_container, #create_community_container, #rate_element_container { +#new_blog_post_container, #add_community_comment_container, #create_community_container, #rate_element_container, +#new_project_blog_post_container, #add_project_comment_container, #create_project_container, #confirm_leave_project_container { column-span: 3; } -#new_blog_post_container Horizontal, #add_community_comment_container Horizontal, #create_community_container Horizontal, #rate_element_container Horizontal { +#new_blog_post_container Horizontal, #add_community_comment_container Horizontal, #create_community_container Horizontal, #rate_element_container Horizontal, +#new_project_blog_post_container Horizontal, #add_project_comment_container Horizontal, #create_project_container Horizontal, #confirm_leave_project_container Horizontal { height: auto; } @@ -253,7 +297,8 @@ NewBlogPostScreen, AddCommunityCommentScreen, RateElementScreen { width: 30; } -#blog_post_text, #community_comment_text, #community_mission_text, #rating_review_text { +#blog_post_text, #community_comment_text, #community_mission_text, #rating_review_text, +#project_blog_post_text, #project_comment_text, #project_mission_text { height: 10; } @@ -261,7 +306,7 @@ ModalScreen > Header, ModalScreen > Footer { column-span: 3; } -#communities_title, #community_title, #element_feedback_title, #rate_element_title, #new_blog_post_title, #add_community_comment_title, #create_community_title, #confirm_leave_community_title, #my_network_title, #confirm_remove_peer_title, #edit_profile_title, #create_profile_title, #edit_teams_title, #edit_roles_title, #edit_communities_title, #edit_identities_title, #status_title, #generic_data_view_title, #feedback_title, #feedback_log_title, .span-3 { +#communities_title, #community_title, #projects_title, #project_title, #element_feedback_title, #rate_element_title, #new_blog_post_title, #new_project_blog_post_title, #add_community_comment_title, #add_project_comment_title, #create_community_title, #create_project_title, #confirm_leave_community_title, #confirm_leave_project_title, #my_network_title, #confirm_remove_peer_title, #edit_profile_title, #create_profile_title, #edit_teams_title, #edit_roles_title, #edit_communities_title, #edit_identities_title, #status_title, #generic_data_view_title, #feedback_title, #feedback_log_title, .span-3 { column-span: 3; text-align: center; background: #89b4fa; diff --git a/my_egeria/my_egeria/project_handler.py b/my_egeria/my_egeria/project_handler.py new file mode 100644 index 00000000..04979e4a --- /dev/null +++ b/my_egeria/my_egeria/project_handler.py @@ -0,0 +1,604 @@ +""" + PDX-License-Identifier: Apache-2.0 + Copyright Contributors to the ODPi Egeria project. + + Work with Projects handler mixin for My Profile Textual App. + + A person belongs to a project when an actor is linked to it by an + AssignmentScope relationship, whose assignmentType says how they take part + (https://egeria-project.org/types/1/0120-Assignment-Scopes/). The actor is + either the person's own profile, or a role they are appointed to. + + Creating a project makes it with create_project and, unless the user + chooses not to join, links their profile to it (as its Leader by default). + Joining links the user's profile to the project with link_assignment_scope, + and leaving removes that link with detach_assignment_scope. Memberships held + through a role are listed but not removed here: the role may be shared, and + changing it is a job for whoever manages the role. + + A project's blog is a NoteLog attached to the project, holding BlogEntry + notes. The app creates the log (qualified name BLOG_LOG_QN) on the first post; + posts are read from every note log attached to the project, so entries + written by other tools are shown too. Comments are attached to the project + directly. + + A project's resources are the elements it lists with ResourceList + relationships (https://egeria-project.org/types/0/0019-More-Information/) and + those scoped to it with ScopedBy relationships (such as datasets or deliverables + the project looks after), as well as project dependencies. The other end of a + ResourceList - where the project is itself someone else's resource - is not shown. + + Feedback on a blog post or a resource is its comments, likes and star ratings. + Egeria keeps one like and one rating per user on an element: liking or rating + again replaces the user's earlier one. +""" + +import sys +from pathlib import Path +from typing import Any + +# Ensure project root is on sys.path +root_path = Path(__file__).resolve().parents[2] +if str(root_path) not in sys.path: + sys.path.append(str(root_path)) + +current_dir = Path(__file__).resolve().parent +if str(current_dir) not in sys.path: + sys.path.append(str(current_dir)) + +from pyegeria import Egeria, PyegeriaException +from paging_support import (LookupUnconfirmed, PagedRows, by_unique_name, combine, paged_rows, read_all, + unique_refusal) +from ProjectsScreen import ProjectsScreen, DIRECT_LINK, JOIN_ASSIGNMENT_TYPES, CREATOR_ASSIGNMENT_TYPES, PROJECT_TYPES +from ProjectScreen import ProjectScreen, comment_type_label, star_label, STAR_VALUES + +PROJECT_TYPE = "Project" +PERSON_TYPE = "Person" +ROLE_TYPE = "ActorRole" +# The relationship between a role and the people appointed to it +APPOINTMENT_TYPE = "PersonRoleAppointment" +# The "Member Through" value of a person linked to a project directly, rather than through a role +MEMBER_DIRECT = "Direct" +BLOG_LOG_QN = "NoteLog::{project_guid}::ProjectBlog" +# How many of a project's most recent blog posts are listed +LATEST_POSTS = 20 +# The relationships that link a project to its resources, and the "Linked As" text of a scoped element +RESOURCE_RELATIONSHIPS = ["ResourceList", "ScopedBy", "ProjectDependency", "SupportedProject"] +IN_SCOPE = "In scope" +LIKE_EMOJI = "👍" + + +def _type_name(element: dict) -> str: + return ((element.get("elementHeader") or {}).get("type") or {}).get("typeName") or "" + + +def _is_role(element: dict) -> bool: + """True for an ActorRole, or any of its subtypes (PersonRole, GovernanceRole, ...).""" + element_type = (element.get("elementHeader") or {}).get("type") or {} + return ROLE_TYPE == element_type.get("typeName") or ROLE_TYPE in (element_type.get("superTypeNames") or []) + + +def _is_project(element: dict) -> bool: + """True for a Project, or any of its subtypes (Campaign, Task, StudyProject, PersonalProject, ...).""" + element_type = (element.get("elementHeader") or {}).get("type") or {} + type_name = element_type.get("typeName") or "" + super_types = element_type.get("superTypeNames") or [] + return type_name in PROJECT_TYPES or PROJECT_TYPE in super_types or "Project" in type_name + + +def _guid(element: dict) -> str: + return (element.get("elementHeader") or {}).get("guid") or "" + + +def _name(properties: dict) -> str: + return (properties.get("displayName") or properties.get("fullName") or properties.get("identifier") + or properties.get("name") or properties.get("qualifiedName") or "") + + +def _created(element: dict) -> tuple[str, str]: + """(created by, create time) from an element's header; the time is ISO 8601 text.""" + versions = (element.get("elementHeader") or {}).get("versions") or {} + return versions.get("createdBy") or "", str(versions.get("createTime") or "") + + +def _posted(create_time: str) -> str: + """'2026-10-23T13:27:27.750+00:00' -> '2026-10-23 13:27'""" + return create_time[:16].replace("T", " ") + + +class ProjectsMixin: + """Mixin class providing the Work with Projects feature for MyProfileApp.""" + + def _project_client(self) -> Egeria: + client = Egeria(view_server=self.view_server, platform_url=self.platform_url, + user_id=self.user_name, user_pwd=self.user_password) + client.create_egeria_bearer_token(self.user_name, self.user_password) + return client + + # --- listing and navigating ------------------------------------------------ + + def list_my_projects(self) -> list[tuple[str, str, str, str, str]] | None: + """The projects the user belongs to, as (name, assignment type, linked through, description, + GUID) rows, or None if they could not be retrieved.""" + client = None + try: + client = self._project_client() + profile = client.get_my_profile(output_format="JSON") + except PyegeriaException as e: + # self.log(f"Retrieving user profile for projects failed: {e}") + self.notify(f"Could not retrieve your projects: {e}", timeout=10, severity="error") + return None + finally: + if client: + client.close_session() + if not isinstance(profile, dict): + return [] + + memberships = [] + for scope in profile.get("assignmentScope") or []: + element = scope.get("relatedElement") or {} + if _is_project(element): + memberships.append((element, (scope.get("relationshipProperties") or {}).get("assignmentType") or "", + DIRECT_LINK)) + + for role_link in profile.get("performsRoles") or []: + role = role_link.get("relatedElement") or {} + role_name = _name(role.get("properties") or {}) + for scope in role_link.get("nestedElements") or []: + element = scope.get("relatedElement") or {} + if _is_project(element): + memberships.append((element, + (scope.get("relationshipProperties") or {}).get("assignmentType") or "", + f"Role: {role_name}")) + + projects: dict[str, dict] = {} + for element, assignment_type, linked_through in memberships: + guid = _guid(element) + if not guid: + continue + properties = element.get("properties") or {} + entry = projects.setdefault(guid, {"name": _name(properties), + "description": properties.get("description") or "", + "assignment_types": [], "linked_through": []}) + if assignment_type and assignment_type not in entry["assignment_types"]: + entry["assignment_types"].append(assignment_type) + if linked_through not in entry["linked_through"]: + entry["linked_through"].append(linked_through) + + return sorted(((p["name"], ", ".join(p["assignment_types"]), "; ".join(p["linked_through"]), + p["description"], guid) + for guid, p in projects.items()), key=lambda row: row[0].lower()) + + def show_projects(self, find: bool = False) -> None: + """Open the Work with Projects screen.""" + if not self.user_GUID: + self.notify("Please wait for your profile to load before working with projects", + timeout=5, severity="warning") + return + my_projects = self.list_my_projects() + if my_projects is None: + return + self.push_screen(ProjectsScreen(my_projects, focus_search=find), callback=self.projects_callback) + + def projects_callback(self, result: Any) -> None: + self._refresh_if_projects_changed() + + def open_project_row(self, table, row_key) -> None: + """Open the project in a main-screen Projects row: (status_or_type, name, description, GUID).""" + try: + row = table.get_row(row_key) + if len(row) == 4: + _, name, _, guid = row + elif len(row) >= 5: + name, _, _, _, guid = row[:5] + else: + return + if not guid: + return + except Exception: + return + self.push_screen(ProjectScreen(guid, name), callback=self.project_callback) + + def project_callback(self, result: Any) -> None: + self._refresh_if_projects_changed() + + def _projects_changed(self) -> None: + """Record that the user joined, left or created a project so the main screen reloads on return.""" + self.projects_changed = True + + def _refresh_if_projects_changed(self) -> None: + if getattr(self, "projects_changed", False): + self.projects_changed = False + self.call_later(self.action_refresh) + + # --- finding, members, resources, blog, comments -------------------------- + + def search_projects(self, search_string: str) -> list[tuple[str, str, str, str]] | None: + """Find projects matching search_string, as (name, description, qualified name, GUID) rows, + or None if the search could not be run.""" + client = None + try: + client = self._project_client() + search = search_string or "*" + + def fetch(start: int, size: int): + return client.find_projects(search_string=search, ignore_case=True, output_format="JSON", + graph_query_depth=0, start_from=start, page_size=size) + + read = read_all(fetch, method="find_projects", client=client) + except PyegeriaException as e: + # self.log(f"Finding projects matching {search_string} failed: {e}") + self.notify(f"Searching for projects failed: {e}", timeout=10, severity="error") + return None + finally: + if client: + client.close_session() + + rows = [] + for project in read.items: + if not isinstance(project, dict): + continue + properties = project.get("properties") or {} + rows.append((_name(properties), properties.get("description") or "", + properties.get("qualifiedName") or "", _guid(project))) + return paged_rows(sorted(rows, key=lambda row: row[0].lower()), read, "projects") + + def get_project_members(self, project_guid: str) -> list[tuple[str, str, str, str, str]] | None: + """The people linked to the project, as (name, assignment type, member through, qualified name, + GUID) rows, or None if they could not be retrieved. A person linked both directly and through a + role is one row.""" + client = None + try: + client = self._project_client() + project = client.get_project_by_guid(project_guid, output_format="JSON", graph_query_depth=1) + except PyegeriaException as e: + # self.log(f"Retrieving the members of project {project_guid} failed: {e}") + self.notify(f"Could not retrieve the project's members: {e}", timeout=10, severity="error") + return None + finally: + if client: + client.close_session() + if not isinstance(project, dict): + return [] + + members = [] + role_links: list[tuple[dict, str]] = [] + for link in (project.get("assignedActors") or []) + (project.get("projectTeam") or []) + (project.get("resourceListUsers") or []): + actor = link.get("relatedElement") or {} + assignment_type = (link.get("relationshipProperties") or {}).get("assignmentType") or "" + if _type_name(actor) == PERSON_TYPE: + members.append((actor, assignment_type, MEMBER_DIRECT)) + elif _is_role(actor): + role_links.append((actor, assignment_type)) + + if role_links: + client = None + try: + client = self._project_client() + for role, assignment_type in role_links: + role_guid = _guid(role) + if not role_guid: + continue + actor_role = client.get_actor_role_by_guid(role_guid, output_format="JSON", graph_query_depth=1) + if not isinstance(actor_role, dict): + continue + role_name = _name(role.get("properties") or {}) + for link in actor_role.get("rolePerformers") or []: + person = link.get("relatedElement") or {} + if _type_name(person) == PERSON_TYPE: + members.append((person, assignment_type, f"Role: {role_name}")) + except PyegeriaException as e: + # self.log(f"Retrieving members through roles for project {project_guid} failed: {e}") + self.notify(f"Could not retrieve some members through their roles: {e}", timeout=10, severity="warning") + finally: + if client: + client.close_session() + + people: dict[str, dict] = {} + for person, assignment_type, member_through in members: + guid = _guid(person) + if not guid: + continue + properties = person.get("properties") or {} + entry = people.setdefault(guid, {"name": _name(properties), + "qualified_name": properties.get("qualifiedName") or "", + "assignment_types": [], "member_through": []}) + if assignment_type and assignment_type not in entry["assignment_types"]: + entry["assignment_types"].append(assignment_type) + if member_through not in entry["member_through"]: + entry["member_through"].append(member_through) + return sorted(((p["name"], ", ".join(p["assignment_types"]), "; ".join(p["member_through"]), + p["qualified_name"], guid) + for guid, p in people.items()), key=lambda row: row[0].lower()) + + def get_project_resources(self, project_guid: str) -> list[tuple[str, str, str, str, str]] | None: + """The resources linked to the project, as (name, type, linked as, description, GUID) rows, + or None if they could not be retrieved. An element linked both ways is one row.""" + client = None + try: + client = self._project_client() + project = client.get_project_by_guid(project_guid, output_format="JSON", graph_query_depth=1, + include_only_relationships=RESOURCE_RELATIONSHIPS) + except PyegeriaException as e: + # self.log(f"Retrieving the resources of project {project_guid} failed: {e}") + self.notify(f"Could not retrieve the project's resources: {e}", timeout=10, severity="error") + return None + finally: + if client: + client.close_session() + if not isinstance(project, dict): + return [] + + links = [] + # resourceList is the project's own list; resourceListUsers, the other end, is left out + for link in project.get("resourceList") or []: + link_properties = link.get("relationshipProperties") or {} + use = link_properties.get("resourceUse") or link_properties.get("label") or "" + links.append((link, f"Resource: {use}" if use else "Resource")) + links += [(link, IN_SCOPE) for link in project.get("relevantToScopes") or []] + links += [(link, "Dependency") for link in project.get("projectDependencies") or []] + links += [(link, "Supported Project") for link in project.get("supportedProjects") or []] + + resources: dict[str, dict] = {} + for link, linked_as in links: + element = link.get("relatedElement") or {} + guid = _guid(element) + if not guid: + continue + properties = element.get("properties") or {} + entry = resources.setdefault(guid, {"name": _name(properties), "type": _type_name(element), + "description": properties.get("description") or "", + "linked_as": []}) + if linked_as not in entry["linked_as"]: + entry["linked_as"].append(linked_as) + return sorted(((r["name"], r["type"], "; ".join(r["linked_as"]), r["description"], guid) + for guid, r in resources.items()), key=lambda row: row[0].lower()) + + def get_project_blog_posts(self, project_guid: str) -> list[tuple[str, str, str, str, str]] | None: + """The project's latest blog posts/notes, newest first, as (title, author, posted, text, GUID) rows, + or None if they could not be retrieved.""" + client = None + posts = [] + try: + client = self._project_client() + logs = self._read_note_logs(client, project_guid) + reads = [logs] + for log in logs.items: + log_guid = _guid(log) if isinstance(log, dict) else "" + if not log_guid: + continue + + def fetch(start: int, size: int, log_guid=log_guid): + return client.get_notes_for_note_log(log_guid, metadata_element_type_name="BlogEntry", + graph_query_depth=0, start_from=start, page_size=size) + + entries = read_all(fetch, method="get_notes_for_note_log", client=client) + reads.append(entries) + posts += [entry for entry in entries.items if isinstance(entry, dict)] + except PyegeriaException as e: + # self.log(f"Retrieving the blog of project {project_guid} failed: {e}") + self.notify(f"Could not retrieve the project's blog: {e}", timeout=10, severity="error") + return None + finally: + if client: + client.close_session() + rows = [] + for post in posts: + properties = post.get("properties") or {} + author, create_time = _created(post) + rows.append((create_time, (_name(properties), author, _posted(create_time), + properties.get("description") or "", _guid(post)))) + rows.sort(key=lambda r: r[0], reverse=True) + latest = [row for _, row in rows[:LATEST_POSTS]] + if combine(*reads): # every read reached a confirmed end + return PagedRows(latest, complete=True) + note = (f"Showing the newest of at least {len(rows)} posts read; Egeria didn't confirm there are no more, " + f"so newer posts may be missing") + self.notify(note, timeout=10, severity="warning") + return PagedRows(latest, complete=False, note=note) + + def _read_note_logs(self, client: Egeria, project_guid: str): + """Every note log attached to the project, paged to Egeria's end (a PageResult).""" + def fetch(start: int, size: int): + return client.get_attached_note_logs(project_guid, graph_query_depth=0, start_from=start, + page_size=size) + + return read_all(fetch, method="get_attached_note_logs", client=client) + + def _project_blog_log(self, client: Egeria, project_guid: str, project_name: str) -> str: + """The GUID of the project's blog note log, which is created on first use.""" + qualified_name = BLOG_LOG_QN.format(project_guid=project_guid) + found = by_unique_name(client, qualified_name, "NoteLog") + if found.found: + return found.guid + if found.answer != "absent": + raise LookupUnconfirmed(unique_refusal(f"a blog for {project_name}", found, + "No blog was created and nothing was posted")) + body = { + "class": "NewAttachmentRequestBody", + "properties": { + "class": "NoteLogProperties", + "typeName": "NoteLog", + "qualifiedName": qualified_name, + "displayName": f"{project_name} Blog", + "description": f"Blog for the team members of {project_name}.", + } + } + log_guid = client.create_note_log(element_guid=project_guid, body=body) + # self.log(f"Created blog for project {project_guid}: {log_guid}") + return log_guid + + def add_project_blog_post(self, project_guid: str, project_name: str, title: str, text: str) -> bool: + """Post to the project's blog, creating the blog if it doesn't exist yet. Returns True on success.""" + client = None + try: + client = self._project_client() + log_guid = self._project_blog_log(client, project_guid, project_name) + properties = { + "class": "BlogEntryProperties", + "typeName": "BlogEntry", + "qualifiedName": client.make_feedback_qn("BlogEntry", project_guid, title), + "displayName": title, + "description": text, + } + post_guid = client.create_note(log_guid, body=properties) + # self.log(f"Posted to the blog of project {project_guid}: {post_guid}") + self.notify(f"Your post '{title}' has been added to the {project_name} blog", timeout=10, + severity="information") + return True + except LookupUnconfirmed as e: + self.notify(str(e), timeout=10, severity="warning") + return False + except PyegeriaException as e: + # self.log(f"Posting to the blog of project {project_guid} failed: {e}") + self.notify(f"Posting to the project's blog failed: {e}", timeout=10, severity="error") + return False + finally: + if client: + client.close_session() + + @staticmethod + def _comment_rows(read) -> PagedRows: + """(comment, type, author, posted, GUID) rows, newest first, from a paged read of comments""" + rows = [] + for comment in read.items: + if not isinstance(comment, dict): + continue + properties = comment.get("properties") or {} + author, create_time = _created(comment) + comment_type = comment_type_label(properties.get("commentType") or "") + rows.append((create_time, (properties.get("description") or "", comment_type, author, + _posted(create_time), _guid(comment)))) + rows.sort(key=lambda r: r[0], reverse=True) + return paged_rows([row for _, row in rows], read, "comments") + + @staticmethod + def _read_attached(client: Egeria, method: str, element_guid: str): + """Every comment, like or rating on an element, paged to Egeria's end (a PageResult).""" + def fetch(start: int, size: int): + return getattr(client, method)(element_guid, graph_query_depth=0, start_from=start, page_size=size) + + return read_all(fetch, method=method, client=client) + + def get_project_comments(self, project_guid: str) -> list[tuple[str, str, str, str, str]] | None: + """The comments attached to the project, newest first, as (comment, type, author, posted, GUID) rows, + or None if they could not be retrieved.""" + client = None + try: + client = self._project_client() + read = self._read_attached(client, "get_attached_comments", project_guid) + except PyegeriaException as e: + # self.log(f"Retrieving the comments on project {project_guid} failed: {e}") + self.notify(f"Could not retrieve the project's comments: {e}", timeout=10, severity="error") + return None + finally: + if client: + client.close_session() + result = self._comment_rows(read) + if result.note: + self.notify(result.note, timeout=10, severity="warning") + return result + + def add_project_comment(self, project_guid: str, text: str, comment_type: str) -> bool: + """Attach a comment to the project. Returns True on success.""" + return self.add_element_comment(project_guid, text, comment_type) + + # --- creating, joining, leaving -------------------------------------------- + + def create_project(self, name: str, description: str, mission: str = "", + assignment_type: str = CREATOR_ASSIGNMENT_TYPES[0], + project_type: str = PROJECT_TYPES[0]) -> str | None: + """Create a project, then link the user's profile to it with assignment_type (none if empty). + Returns the new project's GUID, or None if it could not be created; a failed link still + returns the GUID, because the project exists.""" + if project_type not in PROJECT_TYPES: + project_type = PROJECT_TYPES[0] + properties = { + "class": "ProjectProperties", + "typeName": project_type, + "displayName": name, + "description": description, + } + if mission: + properties["plannedResults"] = mission + client = None + try: + client = self._project_client() + qualified_name = client.__create_qualified_name__(project_type, name) + + existing = by_unique_name(client, qualified_name) + if existing.found: + self.notify(f"A project called {name} already exists - find it below to join it", + timeout=10, severity="warning") + return None + if existing.answer != "absent": + self.notify(unique_refusal(f"a project called {name}", existing), timeout=10, severity="warning") + return None + properties["qualifiedName"] = qualified_name + project_guid = client.create_project(body={"class": "NewElementRequestBody", "isOwnAnchor": True, + "properties": properties}) + if not assignment_type: + self.notify(f"Project {name} created", timeout=10, severity="information") + return project_guid + try: + client.link_assignment_scope(project_guid, self.user_GUID, { + "class": "NewRelationshipRequestBody", + "properties": {"class": "AssignmentScopeProperties", "assignmentType": assignment_type}, + }) + except PyegeriaException as e: + # self.log(f"Joining new project {project_guid} failed: {e}") + self.notify(f"Project {name} created, but joining it failed: {e}", timeout=10, severity="warning") + return project_guid + self._projects_changed() + self.notify(f"Project {name} created, and you have joined it as its {assignment_type}", + timeout=10, severity="information") + return project_guid + except PyegeriaException as e: + # self.log(f"Creating project {name} failed: {e}") + self.notify(f"Creating the project failed: {e}", timeout=10, severity="error") + return None + finally: + if client: + client.close_session() + + def join_project(self, project_guid: str, assignment_type: str = JOIN_ASSIGNMENT_TYPES[0]) -> bool: + """Link the user's profile to the project. Returns True on success.""" + body = { + "class": "NewRelationshipRequestBody", + "properties": { + "class": "AssignmentScopeProperties", + "assignmentType": assignment_type, + } + } + client = None + try: + client = self._project_client() + client.link_assignment_scope(project_guid, self.user_GUID, body) + self._projects_changed() + self.notify(f"You have joined the project as a {assignment_type}", timeout=10, + severity="information") + return True + except PyegeriaException as e: + # self.log(f"Joining project {project_guid} failed: {e}") + self.notify(f"Joining the project failed: {e}", timeout=10, severity="error") + return False + finally: + if client: + client.close_session() + + def leave_project(self, project_guid: str) -> bool: + """Remove the link between the user's profile and the project. Returns True on success.""" + client = None + try: + client = self._project_client() + client.detach_assignment_scope(project_guid, self.user_GUID, {"class": "DeleteRelationshipRequestBody"}) + self._projects_changed() + self.notify("You have left the project", timeout=10, severity="information") + return True + except PyegeriaException as e: + # self.log(f"Leaving project {project_guid} failed: {e}") + self.notify(f"Leaving the project failed: {e}", timeout=10, severity="error") + return False + finally: + if client: + client.close_session() diff --git a/tests/micro-tests/my_profile/test_project_handler.py b/tests/micro-tests/my_profile/test_project_handler.py new file mode 100644 index 00000000..03e94076 --- /dev/null +++ b/tests/micro-tests/my_profile/test_project_handler.py @@ -0,0 +1,449 @@ +""" + PDX-License-Identifier: Apache-2.0 + Copyright Contributors to the ODPi Egeria project. + + Unit tests for the Work with Projects mixin and screens (a user belongs to a + project when their profile, or a role they hold, is linked to it by an + AssignmentScope relationship; a project has a blog/note log and comments). +""" + +from unittest.mock import MagicMock, patch + +import pytest +from textual.app import App +from textual.widgets import DataTable, Input, Button, Select, Static, TextArea + +import project_handler +from project_handler import ProjectsMixin +from ProjectsScreen import (ProjectsScreen, ConfirmLeaveProjectScreen, CreateProjectScreen, DIRECT_LINK, + NOT_JOINING, PROJECT_TYPES, CREATOR_ASSIGNMENT_TYPES) +from ProjectScreen import (ProjectScreen, NewProjectBlogPostScreen, AddProjectCommentScreen) +from project_handler import IN_SCOPE, LIKE_EMOJI +from pyegeria import PyegeriaException + + +def _element(guid, type_name, display_name, description=""): + return {"elementHeader": {"guid": guid, "type": {"typeName": type_name}}, + "properties": {"displayName": display_name, "qualifiedName": f"{type_name}::{guid}", + "description": description}} + + +def _created(element, by, at): + element["elementHeader"]["versions"] = {"createdBy": by, "createTime": at} + return element + + +def _scope(element, assignment_type): + return {"relationshipHeader": {"guid": f"rel-{element['elementHeader']['guid']}"}, + "relationshipProperties": {"class": "AssignmentScopeProperties", "assignmentType": assignment_type}, + "relatedElement": element} + + +ROLE_PERFORMERS: dict[str, dict] = {} + + +def _role(guid, type_name, display_name, people): + """A role actor (whose type header lists its supertypes) appointed to the given people.""" + role = _element(guid, type_name, display_name) + supertypes = ["ActorRole", "Actor", "Referenceable", "OpenMetadataRoot"] + if type_name == "GovernanceRole": + supertypes.insert(0, "PersonRole") + role["elementHeader"]["type"]["superTypeNames"] = supertypes + ROLE_PERFORMERS[guid] = {**role, "rolePerformers": [{"relatedElement": person} for person in people]} + return role + + +CLINICAL_TRIAL = _element("ct-guid", "Project", "Cancer Clinical Trial", "Phase 3 clinical trial") +AI_PILOT = _element("ai-guid", "Campaign", "AI Pilot Campaign", "Healthcare AI research") + +PROFILE = { + "elementHeader": {"guid": "profile-guid"}, + "assignmentScope": [ + _scope(CLINICAL_TRIAL, "Contributor"), + _scope(_element("comm-guid", "Community", "Data Science SIG"), "Member"), # not a project + ], + "performsRoles": [ + {"relatedElement": _element("lead-role", "GovernanceRole", "Research Lead"), + "nestedElements": [_scope(AI_PILOT, "Leader")]}, + {"relatedElement": _element("champ-role", "GovernanceRole", "Trial Champion"), + "nestedElements": [_scope(AI_PILOT, "Contributor"), + _scope(_element("loc-guid", "Location", "London"), None)]}, + {"relatedElement": _element("tester-role", "PersonRole", "Tester")}, + ], +} + + +class DummyApp(ProjectsMixin): + def __init__(self): + self.view_server = "qs-view-server" + self.platform_url = "https://127.0.0.1:9443" + self.user_name = "garygeeke" + self.user_password = "secret" + self.user_GUID = "profile-guid" + self.notices = [] + self.pushed = [] + + def log(self, *args, **kwargs): + pass + + def notify(self, message, **kwargs): + self.notices.append((message, kwargs.get("severity"))) + + def push_screen(self, screen, callback=None): + self.pushed.append((screen, callback)) + + def add_element_comment(self, element_guid: str, text: str, comment_type: str) -> bool: + return True + + +@pytest.fixture +def client(): + with patch("project_handler.Egeria") as mock_egeria: + mock_egeria.return_value.__create_qualified_name__ = MagicMock( + side_effect=lambda type_name, name: f"{type_name}::{name.replace(' ', '-')}") + mock_egeria.return_value.get_element_by_unique_name.return_value = "No elements found" + yield mock_egeria.return_value + + +class TestProjectsMixin: + def test_list_merges_direct_and_role_memberships(self, client): + client.get_my_profile.return_value = PROFILE + app = DummyApp() + projects = app.list_my_projects() + + assert len(projects) == 2 + # AI Pilot campaign (alphabetical first) + assert projects[0][0] == "AI Pilot Campaign" + assert projects[0][1] == "Leader, Contributor" + assert projects[0][2] == "Role: Research Lead; Role: Trial Champion" + assert projects[0][3] == "Healthcare AI research" + assert projects[0][4] == "ai-guid" + + # Cancer Clinical Trial (direct) + assert projects[1][0] == "Cancer Clinical Trial" + assert projects[1][1] == "Contributor" + assert projects[1][2] == DIRECT_LINK + assert projects[1][3] == "Phase 3 clinical trial" + assert projects[1][4] == "ct-guid" + + def test_list_handles_empty_or_failed_profile(self, client): + app = DummyApp() + client.get_my_profile.return_value = {} + assert app.list_my_projects() == [] + + client.get_my_profile.side_effect = PyegeriaException("Server error") + assert app.list_my_projects() is None + assert any("Could not retrieve your projects" in n[0] for n in app.notices) + + def test_search_projects(self, client): + app = DummyApp() + client.find_projects.return_value = [ + _element("proj-1", "Project", "Alpha Project", "Alpha description"), + _element("proj-2", "Project", "Beta Project", "Beta description"), + ] + results = app.search_projects("Project") + assert len(results) == 2 + assert results[0][0] == "Alpha Project" + assert results[0][1] == "Alpha description" + assert results[0][3] == "proj-1" + + def test_search_projects_failure(self, client): + app = DummyApp() + client.find_projects.side_effect = PyegeriaException("Network Error") + assert app.search_projects("Project") is None + assert any("Searching for projects failed" in n[0] for n in app.notices) + + def test_get_project_members(self, client): + app = DummyApp() + client.get_project_by_guid.return_value = { + "elementHeader": {"guid": "proj-1"}, + "assignedActors": [ + {"relatedElement": _element("user-1", "Person", "Gary Geeke"), + "relationshipProperties": {"assignmentType": "Leader"}}, + ], + "projectTeam": [ + {"relatedElement": _element("user-2", "Person", "Callie Quartile"), + "relationshipProperties": {"assignmentType": "Contributor"}}, + ], + } + members = app.get_project_members("proj-1") + assert len(members) == 2 + assert members[0][0] == "Callie Quartile" + assert members[0][1] == "Contributor" + assert members[0][2] == "Direct" + assert members[1][0] == "Gary Geeke" + assert members[1][1] == "Leader" + + def test_get_project_resources(self, client): + app = DummyApp() + client.get_project_by_guid.return_value = { + "elementHeader": {"guid": "proj-1"}, + "resourceList": [ + {"relatedElement": _element("res-1", "DataSet", "Patient Cohort Data"), + "relationshipProperties": {"resourceUse": "Primary Assay"}}, + ], + "relevantToScopes": [ + {"relatedElement": _element("res-2", "DigitalProduct", "Clinical Trial Product"), + "relationshipProperties": {}}, + ], + } + resources = app.get_project_resources("proj-1") + assert len(resources) == 2 + assert resources[0][0] == "Clinical Trial Product" + assert resources[0][1] == "DigitalProduct" + assert resources[0][2] == IN_SCOPE + assert resources[1][0] == "Patient Cohort Data" + assert resources[1][2] == "Resource: Primary Assay" + + def test_get_project_blog_posts(self, client): + app = DummyApp() + client.get_attached_note_logs.return_value = [ + _element("log-1", "NoteLog", "Project Blog") + ] + post_elem = _created(_element("post-1", "BlogEntry", "Milestone 1 Reached", "Completed initial assay"), + "garygeeke", "2026-11-18T08:00:00.000+00:00") + client.get_notes_for_note_log.return_value = [post_elem] + + posts = app.get_project_blog_posts("proj-1") + assert len(posts) == 1 + assert posts[0][0] == "Milestone 1 Reached" + assert posts[0][1] == "garygeeke" + assert posts[0][2] == "2026-11-18 08:00" + assert posts[0][3] == "Completed initial assay" + assert posts[0][4] == "post-1" + + def test_add_project_blog_post(self, client): + app = DummyApp() + client.get_attached_note_logs.return_value = [ + _element("log-1", "NoteLog", "Project Blog") + ] + client.get_element_by_unique_name.return_value = { + "elementHeader": {"guid": "log-1", "type": {"typeName": "NoteLog"}} + } + client.create_note.return_value = "post-new-guid" + + success = app.add_project_blog_post("proj-1", "Cancer Trial", "Assay Complete", "Full report attached") + assert success is True + assert any("Your post 'Assay Complete' has been added" in n[0] for n in app.notices) + + def test_get_and_add_project_comments(self, client): + app = DummyApp() + comment_elem = _created(_element("comm-1", "Comment", "Review", "Looks good"), + "tessatube", "2026-11-18T08:15:00.000+00:00") + comment_elem["properties"]["commentType"] = "STANDARD_COMMENT" + client.get_attached_comments.return_value = [comment_elem] + + comments = app.get_project_comments("proj-1") + assert len(comments) == 1 + assert comments[0][0] == "Looks good" + assert comments[0][2] == "tessatube" + + client.add_comment_to_element.return_value = "comm-2-guid" + assert app.add_project_comment("proj-1", "Great progress", "QUESTION") is True + + def test_create_project(self, client): + app = DummyApp() + client.get_element_by_unique_name.return_value = "No elements found" + client.create_project.return_value = "new-proj-guid" + client.link_assignment_scope.return_value = "rel-guid" + + guid = app.create_project("New Trial", "Trial Description", "Goal 1", "Leader", "Project") + assert guid == "new-proj-guid" + assert getattr(app, "projects_changed", False) is True + + def test_join_and_leave_project(self, client): + app = DummyApp() + client.link_assignment_scope.return_value = "rel-guid" + assert app.join_project("proj-1", "Contributor") is True + assert getattr(app, "projects_changed", False) is True + + client.detach_assignment_scope.return_value = None + assert app.leave_project("proj-1") is True + assert any("You have left the project" in n[0] for n in app.notices) + + +ALL_PROJECTS = [ + ("Alpha Project", "Alpha description", "Project::alpha", "proj-1"), + ("Beta Project", "Beta description", "Project::beta", "proj-2"), + ("Privacy Review", "Privacy project", "Project::privacy", "proj-3"), +] +MY_PROJECT_ROWS = [ + ("Alpha Project", "Leader", DIRECT_LINK, "Alpha description", "proj-1"), + ("Beta Project", "Contributor", "Role: Lead", "Beta description", "proj-2"), +] + + +class ProjectsHostApp(App): + def __init__(self, rows=(), focus_search=False): + super().__init__() + self.rows = list(rows) + self.focus_search = focus_search + self.join_project = MagicMock(side_effect=self._join) + self.leave_project = MagicMock(side_effect=self._leave) + self.search_projects = MagicMock(return_value=list(ALL_PROJECTS)) + self.get_project_members = MagicMock(return_value=[("Gary", "Contributor", "Direct", "Person::g", "g")]) + self.posts = [("Second", "erin", "2026-10-20 13:27", "Again", "p2"), + ("First", "gary", "2026-10-01 09:00", "Hello", "p1")] + self.comments = [("Why?", "Question", "gary", "2026-10-01 09:00", "c1")] + self.get_project_blog_posts = MagicMock(side_effect=lambda guid: list(self.posts)) + self.get_project_comments = MagicMock(side_effect=lambda guid: list(self.comments)) + self.add_project_blog_post = MagicMock(side_effect=self._post) + self.add_project_comment = MagicMock(side_effect=self._comment) + self.create_project = MagicMock(side_effect=self._create) + self.user_GUID = "g" + self.resources = [("Software Servers", "DigitalProduct", IN_SCOPE, "Servers", "r1"), + ("Runbook", "ExternalReference", "Resource: Guidance", "How to", "r2")] + self.get_project_resources = MagicMock(side_effect=lambda guid: list(self.resources)) + self.dismissed = None + + def _create(self, name, description, mission, assignment_type, project_type="Project"): + self.search_projects.return_value.append((name, description, f"Project::{name}", "new-guid")) + if assignment_type: + self.rows.append((name, assignment_type, DIRECT_LINK, description, "new-guid")) + return "new-guid" + + def _post(self, guid, name, title, text): + self.posts.insert(0, (title, "garygeeke", "2026-10-28 12:00", text, "p-new")) + return True + + def _comment(self, guid, text, comment_type): + self.comments.insert(0, (text, comment_type, "garygeeke", "2026-10-28 12:00", "c-new")) + return True + + def _join(self, guid, assignment_type="Contributor"): + name = next(r[0] for r in ALL_PROJECTS if r[3] == guid) + self.rows.append((name, assignment_type, DIRECT_LINK, "", guid)) + return True + + def _leave(self, guid): + self.rows = [r for r in self.rows if r[4] != guid] + return True + + def list_my_projects(self): + return list(self.rows) + + async def on_mount(self): + self.screen_under_test = ProjectsScreen(list(self.rows), focus_search=self.focus_search) + await self.push_screen(self.screen_under_test, callback=lambda r: setattr(self, "dismissed", r)) + + +class TestProjectsScreens: + @pytest.mark.asyncio + async def test_projects_screen_composition_and_tables(self): + app = ProjectsHostApp(MY_PROJECT_ROWS) + async with app.run_test(): + screen = app.screen_under_test + my_table = screen.query_one("#my_projects_table", DataTable) + assert my_table.row_count == 2 + + found_table = screen.query_one("#projects_found_table", DataTable) + assert found_table.row_count == 1 + assert found_table.get_row_at(0)[3] == "proj-3" + + @pytest.mark.asyncio + async def test_search_term(self): + app = ProjectsHostApp(MY_PROJECT_ROWS) + async with app.run_test() as pilot: + search = app.screen_under_test.query_one("#project_search_input", Input) + search.value = "privacy" + await search.action_submit() + await pilot.pause() + app.search_projects.assert_called_with("privacy") + + @pytest.mark.asyncio + async def test_create_project_screen(self): + screen = CreateProjectScreen() + dismiss_val = None + + def on_dismiss(val): + nonlocal dismiss_val + dismiss_val = val + + app = App() + async with app.run_test() as pilot: + await app.push_screen(screen, callback=on_dismiss) + await pilot.pause() + + screen.query_one("#project_name_input", Input).value = "Target Project" + screen.query_one("#project_description_input", Input).value = "Project Description" + screen.action_submit() + await pilot.pause() + + assert dismiss_val is not None + assert dismiss_val["name"] == "Target Project" + assert dismiss_val["description"] == "Project Description" + + @pytest.mark.asyncio + async def test_confirm_leave_project_screen(self): + screen = ConfirmLeaveProjectScreen("Cancer Trial") + dismiss_val = None + + def on_dismiss(val): + nonlocal dismiss_val + dismiss_val = val + + app = App() + async with app.run_test() as pilot: + await app.push_screen(screen, callback=on_dismiss) + await pilot.pause() + + screen.query_one("#submit_leave_project_btn", Button).press() + await pilot.pause() + + assert dismiss_val is True + + @pytest.mark.asyncio + async def test_project_screen_composition(self): + screen = ProjectScreen("proj-1", "Test Project") + app = ProjectsHostApp(MY_PROJECT_ROWS) + + async with app.run_test() as pilot: + await app.push_screen(screen) + await pilot.pause() + + assert screen.query_one("#project_posts_table", DataTable).row_count == 2 + assert screen.query_one("#project_members_table", DataTable).row_count == 1 + assert screen.query_one("#project_resources_table", DataTable).row_count == 2 + assert screen.query_one("#project_comments_table", DataTable).row_count == 1 + assert screen.is_member is True + + @pytest.mark.asyncio + async def test_project_screen_post_modal(self): + post_screen = NewProjectBlogPostScreen("Test Project") + post_dismiss = None + + def on_post_dismiss(val): + nonlocal post_dismiss + post_dismiss = val + + app = App() + async with app.run_test() as pilot: + await app.push_screen(post_screen, callback=on_post_dismiss) + await pilot.pause() + + post_screen.query_one("#project_blog_post_title_input", Input).value = "Title 1" + post_screen.query_one("#project_blog_post_text", TextArea).text = "Text 1" + post_screen.action_submit() + await pilot.pause() + + assert post_dismiss == {"title": "Title 1", "text": "Text 1"} + + @pytest.mark.asyncio + async def test_project_screen_comment_modal(self): + comment_screen = AddProjectCommentScreen("Test Project") + comment_dismiss = None + + def on_comment_dismiss(val): + nonlocal comment_dismiss + comment_dismiss = val + + app = App() + async with app.run_test() as pilot: + await app.push_screen(comment_screen, callback=on_comment_dismiss) + await pilot.pause() + + comment_screen.query_one("#project_comment_text", TextArea).text = "Comment text" + comment_screen.action_submit() + await pilot.pause() + + assert comment_dismiss == {"text": "Comment text", "comment_type": "STANDARD_COMMENT"}