# CLAUDE.md

## AI Guidance
- This documentation is for AI memory/context. Use it to answer questions, generate code, and reason about the system.
- Always follow the schema and field descriptions exactly as written.
- When in doubt, refer to the code locations provided in this file.
- Do not invent new fields, types, or patterns unless explicitly documented here.
- If a field or pattern is ambiguous, prefer the most common usage as shown in the codebase.
- For process definitions, ensure there is exactly one start and one end node.
- For form components, only use 'options' for select/radio/checkbox types.
- If you encounter a new node/component type, check `/components/` for its implementation.
- Avoid anti-patterns: do not use fields in the wrong context (e.g., 'options' in a text field), do not omit required fields, and do not mix node types inappropriately.
- If unsure, ask for clarification or check the referenced code files.

## Getting Started
- Clone the repo and run `yarn install` to install dependencies.
- Start the dev server with `yarn dev`.
- For database setup, see the Database Operations section below.
- Explore `/pages/` for main app entry points.
- See `/docs/json/` for sample process and form definitions.
- For custom components, see `/components/`.
- For API endpoints, see `/server/api/`.
- For contributing, follow project conventions and see comments in code.

## Common Development Commands

### Development Server
```bash
yarn dev              # Start development server
yarn build            # Build for production
yarn build:new        # Build with pre/post-build scripts
yarn preview          # Preview production build
yarn generate         # Generate static site
```

### Database Operations
```bash
yarn prisma           # Pull DB schema, generate client, and start dev server
npx prisma generate   # Generate Prisma client only
npx prisma db pull    # Pull database schema
npx prisma studio     # Open Prisma Studio for database management
```

### Code Quality
```bash
npx eslint .          # Run ESLint
npx prettier --write . # Format code with Prettier
```

## Architecture Overview

### Technology Stack
- **Framework**: Nuxt 3 with Vue 3 Composition API
- **Database**: MySQL with Prisma ORM
- **State Management**: Pinia stores
- **UI Framework**: Tailwind CSS + Custom Rose UI components
- **Forms**: FormKit with custom extensions
- **Process Visualization**: Vue Flow for BPMN diagrams
- **Authentication**: JWT-based with custom middleware

### Core System Components

This is a **Business Process Management (BPM) platform** with two primary modules:

#### 1. Process Builder (`/process-builder/`)
Professional BPMN-compliant workflow designer with comprehensive node types and sophisticated integration capabilities:

**Main Pages:**
- **index.vue**: Main process designer (drag-and-drop BPMN editor, ~40k tokens)
- **manage.vue**: Process management dashboard with metrics and CRUD operations
- **analytics/[id].vue**: Process analytics and journey visualization

**Available Node Types:**
- **Start/End Points**: Define process boundaries; start or finish a process.
- **Form Tasks**: User input forms; integrate with form builder.
- **API Calls**: Call external/internal APIs; supports authentication and error handling.
- **Script Tasks**: Run JavaScript code; map input/output variables.
- **Business Rules**: Evaluate conditions and set variables; supports AND/OR logic.
- **Gateways**: Decision points; branch process flow based on conditions.
- **Notifications**: Send messages (email, SMS, in-app) to users/roles.
- **HTML Content**: Display custom HTML/CSS/JS content in the process.
- **Sub Processes**: Run nested processes; supports variable mapping.
- **Design Elements**: Visual aids (swimlanes, shapes, text annotations).

> Node type implementations: `/components/process-flow/ProcessFlowNodes.js` and related Vue components.

#### 2. Form Builder (`/form-builder/`)
Dynamic form creator with conditional logic, validation, and JavaScript API integration.

**Form Component Types:**
- **Text**: Single-line input.
- **Select**: Dropdown selection.
- **Radio**: Single-choice radio buttons.
- **Checkbox**: Multi-choice checkboxes.
- **Date**: Date picker.
- **Repeating Group**: Dynamic list of grouped fields.
- **Heading**: Section titles.
- **Static/Display**: Read-only or info fields.

> See `/components/FormBuilderComponents.vue` and `/components/formkit/` for implementations.

### State Management Architecture

**Primary Stores:**
- `processBuilder.js`: Process design, node management, auto-save, history tracking
- `formBuilder.js`: Form components, validation, custom scripts, preview data
- `variableStore.js`: Global process variables and data flow management
- `user.js`: Authentication and user session management

**Store Patterns:**
- All stores use Pinia with persistence
- Reactive state updates trigger UI changes automatically
- Centralized error handling and loading states
- Auto-save functionality prevents data loss

### Database Schema (Prisma)

**Core Entities:**
- **process**: BPMN process definitions (JSON schema, versioning, templates).
- **form**: Dynamic form configurations (fields, scripts, validation).
- **caseInstance**: Tracks process execution instances and status.
- **task**: User tasks within process cases.
- **user/role/userrole**: Authentication and RBAC system.

> See `/prisma/schema.prisma` for schema details.

**Key Relationships:**
- Forms can be embedded in process tasks.
- Process variables flow between forms and process nodes.
- Complete audit trail through `processHistory` and `formHistory`.
- Case timeline tracking for process execution monitoring.

### RBAC & Permissions System
- **Roles**: Define user access levels (e.g., admin, manager, user).
- **Permissions**: Assigned to roles; control access to features and data.
- **UserRole**: Maps users to roles.
- **Where to find**: `/prisma/schema.prisma` (models), `/server/api/role/` (API), `/stores/user.js` (frontend usage).

### API Architecture (`/server/api/`)

**RESTful Structure:**
- `/api/forms/`: CRUD for forms, with history.
- `/api/process/`: Process management, publishing, execution.
- `/api/tasks/`: Task assignment and completion.
- `/api/devtool/`: Dev utilities (ORM, code editor, etc).

**API Request/Response:**
- Most endpoints accept/return JSON.
- Auth via JWT in headers.
- For request/response shapes, see handler files in `/server/api/` or use browser dev tools.
- For OpenAPI/Swagger docs, see project root if available.

**Special Endpoints:**
- Form field extraction: `/api/forms/[formId]/fields.get.js`
- Process analytics: `/api/process/dashboard/summary.get.js`
- Version management: `/api/forms/[id]/history.get.js`

### Process Execution Flow
1. User starts a process (via UI or API).
2. System creates a case instance and assigns initial tasks.
3. User(s) complete form tasks, triggering API/script/business rule nodes as defined.
4. Variables are updated and routed through gateways/conditions.
5. Notifications and HTML content nodes are processed as needed.
6. Process continues until end node is reached; case is closed.

> For execution logic, see `/server/api/process/` and `/components/process-flow/`.

### Configuration Files (`/docs/json/`)

**Critical System Configurations:**
- `formComponents.json`: Complete form structure for Malaysian Asnaf registration system
- `processDefinition.json`: BPMN process flow definitions with nodes and edges
- `processVariables.json`: 100+ process variables for data management
- `customScript.js`: Form conditional logic and field visibility rules

These JSON files define a production Malaysian welfare application system with complex business rules.

### JSON Data Structure Schemas

#### Process Definition Schema
- **nodes**: Array<Node> (required) — List of all process steps.
  - Node:
    - id: String (required) — Unique node identifier.
    - type: String (required) — Node type (e.g., 'form', 'api', 'start', etc.).
    - label: String (optional) — Display label for the node.
    - position: { x: Number, y: Number } (required) — Canvas position.
    - data: Object — Type-specific config (see below).
      - For 'form': formId, formName, assignedRoles, etc.
      - For 'api': apiUrl, apiMethod, headers, etc.
      - For 'gateway': conditions, defaultPath, etc.
- **edges**: Array<Edge> (required) — Connections between nodes.
  - Edge:
    - id: String (required) — Unique edge identifier.
    - type: String (required) — Edge type (usually 'custom').
    - source: String (required) — Source node id.
    - target: String (required) — Target node id.
    - sourceHandle: String (optional) — Source connection handle.
    - targetHandle: String (optional) — Target connection handle.
    - animated: Boolean (optional) — Animate edge.
    - label: String (optional) — Edge label.
    - data: Object (optional) — Extra edge metadata.
- **viewport**: { x: Number, y: Number, zoom: Number } (required) — Canvas viewport settings.

> For real-world examples, see `/docs/json/process-builder/` and `/components/process-flow/`.

#### Process Variable Schema
- **variableName**: Object (key is variable name)
  - type: String (required, e.g. string, number, boolean, object, array) — Data type.
  - value: Any (optional) — Initial value.
  - description: String (optional) — Human-readable description.
  - scope: String (optional, e.g. 'global') — Variable scope.
  - name: String (optional, usually matches the key).

#### Form Builder Custom Component Schema
- **type**: String (required) — Component type (e.g., 'text', 'select', 'repeating-group').
- **props**: Object (required) — Component properties.
  - name: String (required) — Field name (unique).
  - label: String (required) — Field label.
  - type: String (required) — Should match component type.
  - placeholder: String (optional) — Placeholder text.
  - validation: String (optional) — Validation rules (e.g., 'required').
  - help: String (optional) — Helper text.
  - width: String (optional) — Field width (e.g., '100%').
  - gridColumn: String (optional) — Grid layout column span.
  - options: Array<{ label: String, value: Any }> (optional, for select/radio/checkbox) — Choices for selection fields.
  - conditionalLogic: { action: String, enabled: Boolean, operator: String, conditions: Array } (optional) — Show/hide logic.
  - fields: Array<Component> (optional, for repeating-group) — Nested fields.
  - maxItems: Number (optional, for repeating-group) — Max items allowed.
  - minItems: Number (optional, for repeating-group) — Min items required.
  - buttonText: String (optional, for repeating-group) — Add button label.
  - removeText: String (optional, for repeating-group) — Remove button label.
  - level: Number (optional, for heading components) — Heading level.
  - value: Any (optional, for static fields) — Static value.

> Some fields are required only for certain types (e.g., 'options' for select/radio, 'fields' for repeating-group).
> For more, see `/docs/json/form/` and `/components/FormBuilder*`.

#### Custom Script Schema
- JavaScript using these helpers (in form script context):
  - this.hideField(fieldName) — Hide a field.
  - this.showField(fieldName) — Show a field.
  - this.onFieldChange(fieldName, callback) — Run callback on field change.
  - getField(fieldName) — Get field value.
  - hideField(fieldName) — (Global) Hide a field.
  - showField(fieldName) — (Global) Show a field.
  - onFieldChange(fieldName, callback) — (Global) Field change handler.
- Scripts run in the form context; `this` refers to the script engine. Global helpers are also available.
- Use for field visibility, conditional logic, and dynamic form behavior.

> For script examples, see `/docs/json/form/customScript.js` and `/components/FormScriptEngine.vue`.

### Development Patterns

**Vue 3 Composition API Usage:**
- Use `ref()` for primitive reactive data
- Use `shallowRef()` for large objects (like Vue Flow nodes) to avoid deep reactivity
- Implement proper cleanup in `onUnmounted()` for timers and event listeners
- Use `watch()` for complex reactive logic, `computed()` for derived state

**State Management Patterns:**
- Store actions handle all business logic and API calls
- Components focus on presentation and user interaction
- Use store getters for computed values across components
- Implement optimistic updates with error rollback

**Form Builder Patterns:**
- FormKit schema generation from component configurations
- Conditional logic engine evaluates field visibility in real-time
- JavaScript API provides hooks for custom calculations and validations
- Custom script execution sandbox for security

**Process Builder Patterns:**
- Vue Flow integration for professional BPMN rendering with Vue 3 Composition API
- Node configuration through specialized modal components for each node type
- Smart connection system with 4-directional handles and type validation
- Auto-save with debouncing to prevent data loss (2-second intervals)
- History tracking for undo/redo functionality with change descriptions
- Real-time variable usage tracking and dependency analysis
- Drag-and-drop component palette with visual feedback
- Mobile-responsive design with collapsible panels and touch support

**Process-Form Integration Patterns:**
- Bidirectional data flow: Process variables ↔ Form fields
- Dynamic form behavior based on process state and variables
- Shared variable system with type validation and scope management
- Real-time synchronization between process nodes and form configurations
- Form field mapping in process tasks with input/output variable assignment

### Security Considerations

**Authentication:**
- JWT tokens with refresh mechanism
- Role-based access control (RBAC) through `user/role/userrole` models
- Route-level middleware protection

**Data Security:**
- XSS protection disabled for specific API routes (devtool, forms)
- Rate limiting: 200 requests per minute
- Input validation through FormKit and Prisma
- SQL injection protection through Prisma ORM

**Script Execution:**
- Form custom scripts run in 'safe' mode by default
- Script execution sandbox prevents direct DOM access
- Advanced mode available for power users with additional permissions

### Key Implementation Details

**Auto-save System:**
- Debounced saves every 2 seconds after changes
- Unsaved changes protection with navigation guards
- Visual indicators for save status

**Process Execution:**
- BPMN-compliant process engine with standards-based execution
- Task assignment and routing based on process definition and business rules
- Variable management throughout process lifecycle with type safety
- Integration points for external APIs and services with authentication
- Case instance tracking with complete audit trail
- Dynamic user/role assignment with conditional logic
- Decision logic with complex branching (AND/OR condition combinations)
- Sub-process execution with variable inheritance and mapping

**Form System:**
- Dynamic component rendering from JSON schema
- Real-time validation and conditional logic
- Preview mode for form testing
- Import/export functionality for form templates

**Performance Optimizations:**
- Lazy loading for heavy components (modals, editors)
- Virtual scrolling for large lists
- Optimized API calls with loading states
- Bundle splitting for reduced initial load times

### Development Tips

**Working with Large Files:**
- `pages/process-builder/index.vue` is ~40k tokens - consider code splitting
- Use component lazy loading for modal components
- Implement proper loading states for better UX

**Database Changes:**
- Always run `npx prisma generate` after schema changes
- Use migrations for production database updates
- Test with realistic data volumes

**Testing Process Flows:**
- Use the process management dashboard for testing and monitoring
- Create test cases in `/execution/` interface with realistic data
- Monitor variables through the Variable Manager with real-time updates
- Test node configurations through specialized modal interfaces
- Validate API integrations with authentication and error handling
- Test conditional logic and gateway decision paths
- Verify form-process integration with variable mapping
- Use process analytics for performance monitoring and optimization

**Custom Scripts:**
- Test in 'safe' mode first before enabling 'advanced' mode
- Use the JavaScript API documentation for available functions
- Implement proper error handling for custom scripts

This codebase represents a sophisticated, production-ready BPM platform with comprehensive process design, form building, and execution capabilities.

### Process Builder Node Architecture Details

**Node Connection System:**
- **Handle Types**: 4-directional connection points (top, bottom, left, right)
- **Connection Validation**: Type-safe connections with business rule enforcement
- **Edge Management**: Interactive edges with labels, conditions, and repositioning
- **Smart Routing**: Automatic handle assignment based on node type and flow direction

**Variable System Integration:**
- **Variable Types**: String, Integer, Decimal, Boolean, Date, DateTime, Object
- **Scoping**: Global process-level variables with inheritance to sub-processes
- **Usage Tracking**: Real-time analysis of where variables are used across nodes
- **Type Validation**: Constraint enforcement and automatic type conversion
- **Dependency Analysis**: Visual indication of variable dependencies between nodes

**Advanced Process Features:**
- **Template System**: Reusable process templates with variable mapping
- **Version Control**: Process versioning with rollback capability and change tracking
- **Export/Import**: Process definition portability with JSON schema validation
- **Process Analytics**: Execution metrics, performance tracking, and bottleneck analysis
- **Integration Capabilities**: RESTful API calls, database operations, webhook support
- **Notification System**: Multi-channel messaging with template support and user preferences

**Mobile and Responsive Design:**
- **Collapsible Panels**: Left (components) and right (properties) panels with toggle controls
- **Touch Support**: Mobile-optimized drag-and-drop with gesture recognition
- **Keyboard Shortcuts**: Ctrl+1/2/3 for panel management, standard undo/redo support
- **Responsive Canvas**: Adaptive grid layout with zoom and pan capabilities
- **Device Preview**: Mobile, tablet, and desktop preview modes for form integration testing