# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## 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/`)
Visual BPMN workflow designer with three 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

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

### 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 with JSON schema, versioning, and templates
- `form`: Dynamic form configurations with custom scripts and validation
- `caseInstance`: Process execution instances with status tracking
- `task`: User tasks within process cases
- `user/role/userrole`: Authentication and RBAC system

**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

### Component Architecture

**Process Flow Components (`/components/process-flow/`):**
- `ProcessFlowCanvas.vue`: Main BPMN editor using Vue Flow
- `ProcessBuilderComponents.vue`: Draggable component palette
- Node Configuration Modals: Specialized modals for each BPMN node type
- `VariableManager.vue`: Process variable management interface

**Form Components (`/components/formkit/`):**
- Custom FormKit inputs with enhanced functionality
- Conditional logic engine for dynamic field visibility
- JavaScript API integration for real-time calculations

**Rose UI Components (`/components/rs-*/`):**
- Custom design system components (buttons, modals, cards, etc.)
- Consistent styling and behavior across the application

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

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

**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`

### 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.

### 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
- Node configuration through specialized modal components
- Auto-save with debouncing to prevent data loss
- History tracking for undo/redo functionality

### 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
- Task assignment and routing based on process definition
- Variable management throughout process lifecycle
- Integration points for external APIs and services

**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
- Create test cases in `/execution/` interface
- Monitor variables through the Variable Manager

**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.