gateway/docs/frontend-documentation/prompt-page-requirements.md

549 lines
22 KiB
Markdown

# Prompt Page Requirements
This document contains the complete frontend requirements for all prompt management pages and components. All UI components are dynamically generated from backend metadata—no hardcoding required.
## Table of Contents
1. [Overview](#overview)
2. [Page Structure and Layout](#page-structure-and-layout)
3. [User Interactions and Functionality](#user-interactions-and-functionality)
4. [Backend Routes and API Integration](#backend-routes-and-api-integration)
5. [Field and Attribute Reference](#field-and-attribute-reference)
6. [Dynamic Rendering Guidelines](#dynamic-rendering-guidelines)
---
## Overview
The prompt management page enables users to manage prompts within their mandate. The frontend consists of a single page (`/prompts`) with different views/states:
- **List View** - Browse, search, filter, and sort prompts
- **Edit View** - Edit prompt properties
- **Create View** - Create new prompts
All views use backend-driven UI generation, meaning field definitions, labels, validation rules, and UI structure come entirely from backend metadata through the `/api/attributes/Prompt` endpoint. Views are managed through component state and routing within the same page, not as separate routes.
---
## Page Structure and Layout
### Prompt Management Page (`/prompts`)
The prompt management page uses different views/states to handle different user interactions. Views are managed through component state and routing within the same page component.
### List View
**State:** `view === 'list'` or `selectedPromptId === null`
**What the user sees:**
- **Main Content Area:**
- Table or card grid displaying all prompts in the mandate
- Each prompt row/card shows: name, content preview, mandate ID
- **Action buttons column** in table (rendered on first load):
- "Start Prompt" button - navigates to `/chat-playground` and starts workflow with prompt content
- "Edit" button - switches to Edit View
- "Delete" button - shows confirmation dialog and deletes prompt
- Clickable rows/cards that switch to Detail View (set selectedPromptId and view state)
- **Search and Filter Controls:**
- General search input box (searches across all text fields)
- Field-specific filter controls (one filter per visible field)
- Active filter indicators (chips/badges showing applied filters)
- "Clear all filters" button when filters are active
- **Sorting Controls:**
- Clickable column headers with sort indicators (up/down arrows)
- Visual indication of current sort field and direction
- Support for multi-level sorting
- **Pagination Controls:**
- Page information display ("Page X of Y", "Showing 1-20 of 45 prompts")
- Previous/Next page buttons
- Page number buttons
- Page size selector (10, 20, 50, 100 items per page)
- **Action Buttons:**
- "Create Prompt" button - switches to Create View
### Detail View
**State:** `view === 'detail'` and `selectedPromptId !== null`
**What the user sees:**
- **Prompt Header Section:**
- Prompt name (editable indicator if user has permission)
- Mandate ID (read-only)
- **Prompt Information Section:**
- All prompt properties displayed as formatted fields
- Read-only fields shown as formatted text
- Editable fields shown with edit indicators (if user has permission)
- Special formatting:
- Content → Display as formatted textarea or code block (if applicable)
- Name → Display as heading
- **Action Buttons:**
- Start Prompt button - navigates to `/chat-playground` and starts workflow with prompt content
- Edit button (if user has permission and editable fields exist) - switches to Edit View
- Delete button (if user has permission)
### Edit View
**State:** `view === 'edit'` and `selectedPromptId !== null`
**What the user sees:**
- **Form Section:**
- Dynamic form with editable prompt fields only
- Field labels with required indicators (asterisk for required fields)
- Help text/tooltips from field descriptions
- Input validation errors displayed inline
- **Action Buttons:**
- Save button (submits form)
- Cancel button (switches back to Detail View)
### Create View
**State:** `view === 'create'`
**What the user sees:**
- **Form Section:**
- Dynamic form with all editable prompt fields
- Field labels with required indicators
- Help text/tooltips from field descriptions
- Input validation errors displayed inline
- **Action Buttons:**
- Create button (submits form)
- Cancel button (switches back to List View)
- **Confirmation Dialogs:**
- Delete confirmation dialog (on prompt detail page)
---
## User Interactions and Functionality
### Browsing and Discovery
**Search Functionality:**
- User types in general search box
- Frontend debounces input (300-500ms delay)
- Search applies across all text fields in prompt objects
- Results update automatically
- Page resets to page 1 when search changes
**Field Filtering:**
- User selects field to filter by
- Frontend shows appropriate filter UI based on field type:
- Text fields → Text input with operator selection (contains, equals, startsWith, endsWith)
- Textarea fields → Text input filter
- Select fields → Dropdown with options from backend metadata
- Email fields → Email input filter
- Checkbox fields → Boolean toggle (true/false/any)
- User applies filter → Filter appears as active chip/badge
- User can remove individual filters
- Multiple filters work together (AND logic)
- Page resets to page 1 when filters change
**Sorting:**
- User clicks column header
- Sort direction toggles (asc → desc → remove)
- Multiple columns can be sorted (multi-level sorting)
- Sort indicators show on column headers
- All filters and search preserved when sorting
**Pagination:**
- User clicks page number or navigation button
- Page updates and data refetches
- All filters, search, and sort preserved
- User changes page size → Page resets to 1, data refetches
**View Switching:**
- User clicks prompt row/card → Switches to Detail View (set selectedPromptId and view state)
- User clicks prompt name → Switches to Detail View (set selectedPromptId and view state)
### Viewing Prompt Details
**Information Display:**
- All prompt fields displayed using dynamic rendering
- Read-only fields shown as formatted text
- Editable fields shown with edit indicators
- Special fields formatted appropriately (content as formatted text)
**Action Availability:**
- Edit button shown if editable fields exist and user has permission
- Delete button shown if user has permission
### Creating Prompts
**Form Interaction:**
- User clicks "Create Prompt" button → Switches to Create View (set `view: 'create'`)
- Form shows all editable fields
- User fills in fields
- Client-side validation shows errors immediately
- User clicks Create → Form validates and submits
- User clicks Cancel → Switches back to List View (set `view: 'list'`, `selectedPromptId: null`)
**Form Validation:**
- Required field validation (shows error if empty)
- Type validation (e.g., textarea fields must be valid text)
- Validation errors displayed inline below fields
**Form Submission:**
- Prompt data sent as Prompt object
- Success → Switch to Detail View for created prompt (set `selectedPromptId` to new prompt ID, `view: 'detail'`)
- Error handling:
- 403 (permission denied) → Show permission error
- 400 (validation errors) → Display backend validation errors
- Other errors → Show generic error message
### Editing Prompts
**Form Interaction:**
- User clicks "Edit" button → Switches to Edit View (set `view: 'edit'`)
- Form pre-populated with current prompt values
- User modifies fields
- Client-side validation shows errors immediately
- User clicks Save → Form validates and submits
- User clicks Cancel → Switches back to Detail View (set `view: 'detail'`)
**Form Validation:**
- Required field validation (shows error if empty)
- Type validation (e.g., textarea fields must be valid text)
- Validation errors displayed inline below fields
**Form Submission:**
- Only changed fields sent (or all form data)
- Success → Switch back to Detail View (set `view: 'detail'`) and show success message
- Error handling:
- 403 (permission denied) → Show permission error
- 400 (validation errors) → Display backend validation errors
- Other errors → Show generic error message
### Starting Prompts
**Start Prompt Action:**
- User clicks "Start Prompt" button in table row or detail page
- Frontend fetches prompt data to get prompt content
- Frontend navigates to `/chat-playground` page
- Frontend pre-fills the chat input with the prompt's content
- Frontend displays prompt name as context (optional)
- User can optionally modify the prompt or add files before starting
- User clicks "Start" or "Send" button in chat playground
- Frontend calls `POST /api/chat/playground/start` with:
- `workflowMode` query parameter: "Dynamic" (default) or user-selected mode
- `userInput` body: `{prompt: promptContent, listFileId: [...], userLanguage: "en"}`
**Start Prompt Submission:**
- Success → Workflow starts, chat playground updates with workflow data, messages/logs appear
- Error handling:
- 403 (permission denied) → Show permission error
- 400 (validation errors) → Display backend validation errors
- Other errors → Show generic error message
**Implementation Notes:**
- Action buttons (Start Prompt, Edit, Delete) are rendered in the table on first load
- Buttons should be visible in each table row
- Start Prompt button should be clearly distinguished (e.g., primary button style)
- Navigation to chat playground should preserve prompt context
### Deleting Prompts
**Delete Action:**
- User clicks delete button (on detail page or list)
- Confirmation dialog appears with prompt name
- Warning about permanent deletion
- User confirms → Prompt deleted
- User cancels → Dialog closes, no action
**Delete Success Handling:**
- Success message displayed
- If in Detail View → Switch back to List View (set `view: 'list'`, `selectedPromptId: null`)
- If in List View → Remove prompt from list or refresh
---
## Backend Routes and API Integration
### Complete Route Reference
All backend routes used by prompt pages:
| Route | Method | Purpose | When Used | Access Control |
|-------|--------|---------|-----------|----------------|
| `/api/prompts/` | GET | Get all prompts (with pagination) | Initial page load, pagination changes, sort changes, filter changes, search changes | All authenticated users (filtered by mandate) |
| `/api/prompts/{promptId}` | GET | Get prompt details | Detail page load, edit page load | All authenticated users |
| `/api/prompts/{promptId}` | PUT | Update prompt | Edit form submission | All authenticated users |
| `/api/prompts/{promptId}` | DELETE | Delete prompt | User confirms deletion | All authenticated users |
| `/api/prompts` | POST | Create prompt | Create form submission | All authenticated users |
| `/api/attributes/Prompt` | GET | Get field definitions | Page load (once per page) - used to generate all UI components | All authenticated users |
| `/api/chat/playground/start` | POST | Start workflow with prompt | User clicks "Start Prompt" button | All authenticated users |
### API Request Patterns
**Pagination Request:**
```
GET /api/prompts/?pagination={"page":1,"pageSize":20,"sort":[],"filters":null}
```
- `pagination` parameter is JSON-encoded string
- If user wants all prompts: omit `pagination` parameter entirely
- Filters structure: `{"search":"query","fieldName":"value",...}`
- Optional `mandateId` query parameter to filter by mandate
**Create Request:**
```
POST /api/prompts
Content-Type: application/json
Body: {
"name": "Invoice Processing",
"content": "Process the following invoice..."
}
```
- All Prompt model fields sent as Prompt object
- Handle 403 (permission denied) and 400 (validation errors)
**Update Request:**
```
PUT /api/prompts/{promptId}
Content-Type: application/json
Body: {fieldName: value, ...}
```
- Send only changed fields or all form data
- Handle 403 (permission denied) and 400 (validation errors)
**Start Prompt Request:**
```
POST /api/chat/playground/start?workflowMode=Dynamic
Content-Type: application/json
Body: {
"prompt": "Prompt content here...",
"listFileId": ["file1", "file2"],
"userLanguage": "en"
}
```
- `workflowMode` query parameter is required: "Actionplan", "Dynamic", or "Template" (default: "Dynamic")
- `prompt` field contains the prompt's content
- `listFileId` is optional array of file IDs to attach
- `userLanguage` should match user's preferred language
- Handle 403 (permission denied) and 400 (validation errors)
**Delete Requests:**
```
DELETE /api/prompts/{promptId}
```
- Delete operation requires user confirmation
- Handle 403 (permission denied) and 404 (not found) gracefully
### Response Handling
**Paginated Response:**
```json
{
"items": [...],
"pagination": {
"currentPage": 1,
"pageSize": 20,
"totalItems": 45,
"totalPages": 3,
"sort": [...],
"filters": {...}
}
}
```
**Error Responses:**
- 403 Forbidden → Show permission error message
- 404 Not Found → Show "not found" error message
- 400 Bad Request → Display validation errors from response
- 500 Internal Server Error → Show generic error message
---
## Field and Attribute Reference
### Complete Field List
The following is a comprehensive list of all parameters, attributes, and fields that will be displayed for prompts. All of these are provided by the backend through the `/api/attributes/Prompt` endpoint and should never be hardcoded in the frontend.
#### Core Prompt Fields
**Identification Fields:**
- `id` - Unique prompt identifier (text, readonly, not required, visible)
- `mandateId` - ID of the mandate this prompt belongs to (text, readonly, not required, visible)
**Content Fields:**
- `name` - Name of the prompt (text, editable, required, visible)
- `content` - Content of the prompt (textarea, editable, required, visible)
### Pagination Parameters
**Request Parameters (`PaginationParams`):**
- `page` - Current page number (1-based, minimum 1)
- `pageSize` - Number of items per page (minimum 1, maximum 1000)
- `sort` - Array of sort field configurations
- Each sort field contains:
- `field` - Field name to sort by (must match a prompt field name)
- `direction` - Sort direction: "asc" or "desc"
- `filters` - Filter criteria dictionary
- `search` - General search term (searches across all text fields, case-insensitive)
- Field-specific filters: `{fieldName: value}` or `{fieldName: {operator: "operator", value: value}}`
- Supported operators: "equals", "contains", "startsWith", "endsWith", "in", "notIn"
**Response Metadata (`PaginationMetadata`):**
- `currentPage` - Current page number (1-based)
- `pageSize` - Number of items per page
- `totalItems` - Total number of items across all pages (after filters applied)
- `totalPages` - Total number of pages (calculated from totalItems / pageSize)
- `sort` - Current sort configuration applied (array of SortField objects)
- `filters` - Current filters applied (mirrors request filters)
### Attribute Definition Structure
Each field returned from `/api/attributes/Prompt` contains:
- `name` - Field name (e.g., "name", "content", "id")
- `type` - Field data type (e.g., "text", "textarea", "select", "checkbox")
- `label` - Localized field label (object with language keys: {"en": "English Label", "fr": "French Label"})
- `description` - Field description text
- `required` - Boolean indicating if field is required
- `readonly` - Boolean indicating if field is read-only
- `editable` - Boolean indicating if field can be edited (inverse of readonly)
- `visible` - Boolean indicating if field should be displayed in UI
- `options` - Array of options for select fields (each option has `value` and localized `label`)
---
## Dynamic Rendering Guidelines
The frontend must render all UI components dynamically based on backend metadata. No field definitions, labels, validation rules, or UI structure should be hardcoded.
### Table Column Generation
When rendering the prompt list table:
1. Fetch attribute definitions from `/api/attributes/Prompt`
2. Filter attributes where `visible: true` to determine which columns to display
3. Use `label` property for column headers (select appropriate language based on user preference)
4. Use `type` property to determine how to format cell values:
- `text` fields → Display as plain text
- `textarea` fields → Display as truncated text with "..." or expandable preview
- `select` fields → Display value using label from options array (match value to option.value, then display option.label)
- `checkbox` fields → Display as checkmark icon or "Yes"/"No" text
5. Use `readonly` property to determine if column should be sortable (readonly fields may still be sortable, but editable fields definitely are)
6. Generate click handlers for column headers to update sort parameters and refetch data
7. **Add Actions Column:**
- Render action buttons in each table row on first load
- Include "Start Prompt" button (primary style) - navigates to `/chat-playground` with prompt content
- Include "Edit" button - switches to Edit View
- Include "Delete" button - shows confirmation dialog
- Buttons should be visible and accessible in each row
### Filter Control Generation
When rendering filter controls:
1. Fetch attribute definitions from `/api/attributes/Prompt`
2. Filter attributes where `visible: true` to determine which filters to show
3. For each visible field, generate appropriate filter UI based on `type`:
- `text` fields → Text input filter (supports "contains", "equals", "startsWith", "endsWith" operators)
- `textarea` fields → Text input filter (supports "contains", "equals", "startsWith", "endsWith" operators)
- `email` fields → Email input filter
- `select` fields → Dropdown filter with options from `options` array (use localized labels)
- `checkbox` fields → Boolean toggle filter (true/false/any)
4. Use `label` property for filter labels (localized)
5. When user applies filter, update `filters` object in pagination parameters and refetch data
6. Display active filters as chips/badges showing field label and value
7. Allow removing individual filters by removing them from `filters` object
### Search Implementation
For general search functionality:
1. Display a single search input box (not field-specific)
2. When user types, update `filters.search` in pagination parameters
3. Debounce search input (wait 300-500ms after user stops typing before sending request)
4. Search applies across all text fields in the prompt object
5. Reset to page 1 when search query changes
6. Combine search with field-specific filters (both are in the `filters` object)
### Form Field Generation
When rendering edit forms:
1. Fetch attribute definitions from `/api/attributes/Prompt`
2. Filter attributes where `visible: true` AND `editable: true` to determine which fields to show
3. For each editable field, generate appropriate form input based on `type`:
- `text` fields → Text input
- `textarea` fields → Textarea input (with appropriate rows/height)
- `email` fields → Email input
- `select` fields → Dropdown/select input with options from `options` array (use localized labels)
- `checkbox` fields → Checkbox input
4. Use `label` property for field labels (localized)
5. Use `required` property to show required indicators (asterisk, etc.)
6. Use `description` property to show help text or tooltips
7. Validate form before submission:
- Check all `required: true` fields have values
- Validate types (e.g., textarea fields must be valid text)
- Validate select fields (value must be in options array)
8. On submit, send only changed fields or all form data to update endpoint
### Create Form Field Generation
When rendering create forms:
1. Follow same pattern as edit forms for Prompt model fields
2. On submit, send Prompt object fields in request body
### Display Formatting
When displaying field values:
1. Use `type` property to determine formatting:
- `text` → Display as-is (may need HTML escaping)
- `textarea` → Display as formatted text (preserve line breaks, may truncate with "Read more" link)
- `select` → Look up value in `options` array and display localized label
- `checkbox` → Display as checkmark icon or "Yes"/"No" text
2. Handle `null` or `undefined` values gracefully (show "-" or "Not set")
3. Use `readonly` property to determine if field should show edit indicators
4. For content field (textarea), consider:
- Truncating long content in list view with "Show more" link
- Showing full content in detail view
- Preserving formatting (line breaks, whitespace)
### Localization
All labels and options support multiple languages:
1. Use user's preferred language (from user settings or browser locale)
2. Access localized labels from `label` object: `label[userLanguage]` or `label.en` as fallback
3. For select options, use `option.label[userLanguage]` or `option.label.en` as fallback
4. If label for current language is missing, fall back to English
### Key Principles
- Never hardcode field names, labels, types, or validation rules
- Always fetch attribute definitions from backend before rendering UI
- Use attribute metadata to determine what to display and how to display it
- Support all field types dynamically - if backend adds new types, frontend should handle them
- Respect `visible`, `editable`, `readonly`, and `required` flags from backend
- Use localized labels from backend metadata
- Generate filters, forms, and tables entirely from attribute definitions
- When backend adds new fields, frontend should automatically display them without code changes
- Handle all error cases gracefully (403, 404, 400, 500)
- Provide user feedback for all actions (loading states, success messages, error messages)
---
## Summary
This document provides complete frontend requirements for all prompt management pages and components. All requirements follow the principle of **backend-driven UI generation**—no hardcoding of field definitions, labels, or validation rules. The frontend should dynamically generate all UI components from backend metadata provided through the `/api/attributes/Prompt` endpoint.
**Key Architecture Pattern:** The prompt management interface is a single page (`/prompts`) with different views managed through component state. All interactions happen within the same page component without separate routes.
For generic patterns that apply across all entity types (not just prompts), see the [Dynamic Forms and Pagination documentation](./dynamic-forms-and-pagination.md).